Agrego unicamente README y ARCHITECTURE al repositorio

main
EMOTIONS-HUNTER 1 week ago
parent e158168c36
commit 5ed3b7b879

@ -0,0 +1,336 @@
# System Architecture — EZO RTD Temperature Monitor
> **Purpose of this document:** Provide a complete architectural snapshot of the project so that any contributor (or AI assistant) can understand the full system — hardware, firmware, data pipeline, and frontend — without reading every source file individually.
---
## 1. System Overview
The system is a **single-node embedded IoT monitoring platform** composed of four layers:
```
┌─────────────────────────────────────────────────────────────┐
│ Layer 4 — Presentation index.html / index-css.html │
│ Browser polls JSON via HTTP every 1 s │
├─────────────────────────────────────────────────────────────┤
│ Layer 3 — Web Server Nginx (static file server) │
│ Serves HTML, SVG assets, and JSON data files │
├─────────────────────────────────────────────────────────────┤
│ Layer 2 — Backend Daemon ezortd_daemon (C binary) │
│ Reads I²C → writes JSON + appends CSV │
├─────────────────────────────────────────────────────────────┤
│ Layer 1 — Hardware / HAL EZO-RTD via I²C on RPi │
│ Atlas Scientific ISCCB-2 @ 0x66, I²C bus 1 │
└─────────────────────────────────────────────────────────────┘
```
**Host board:** Raspberry Pi (any model with 40-pin GPIO; developed on Raspberry Pi Zero or similar)
**OS:** Raspberry Pi OS (Debian-based, Linux kernel)
**Language:** C (backend), HTML/CSS/JavaScript (frontend)
**IPC mechanism:** File system — JSON files in `data/` act as the shared state between daemon and web server
---
## 2. Hardware Layer
### 2.1 Sensor — Atlas Scientific EZO-RTD™ (ISCCB-2)
The EZO-RTD is a signal-conditioning circuit for Pt-100 or Pt-1000 RTD probes. It digitizes the analog RTD signal internally and exposes a clean digital interface via I²C or UART.
| Property | Value |
|---|---|
| Module | Atlas Scientific ISCCB-2 |
| Protocol in use | I²C |
| I²C Address | `0x66` (fixed, factory default) |
| I²C Bus | Bus 1 (`/dev/i2c-1`) |
| Supply voltage | 3.3 V |
| Read command | ASCII string `"R"` (1 byte) |
| Response time | ~1000 ms after issuing `"R"` |
| Response format | Byte 0: status code (`0x01` = success); Bytes 1N: null-terminated ASCII float |
| Resolution | 0.001 °C |
### 2.2 Physical Wiring
```
EZO-RTD (ISCCB-2) Raspberry Pi 40-pin Header
───────────────── ──────────────────────────
VCC ────────────────────── Pin 1 (3.3 V)
GND ────────────────────── Pin 6 (GND)
SDA ────────────────────── Pin 3 (GPIO2, I²C1 SDA)
SCL ────────────────────── Pin 5 (GPIO3, I²C1 SCL)
OFF ──── not connected
```
> The `OFF` pin (active-low sleep input) is left floating/unconnected; the circuit is permanently powered. Future implementations may drive this pin from a GPIO to enable power management.
### 2.3 I²C Bus Configuration
- **Bus:** `/dev/i2c-1`
- **Speed:** 100 kHz (standard mode; the EZO-RTD supports up to 400 kHz Fast Mode)
- **Pull-ups:** Provided internally by the Raspberry Pi (1.8 kΩ on SDA/SCL lines)
- **Enable:** `sudo raspi-config` → Interface Options → I2C → Enable
---
## 3. Firmware / HAL Layer (C)
### 3.1 Source Files
| File | Role |
|---|---|
| `sensors/EZORTD/ezortd.h` | Public API: I²C address constant, `getTemperature()` declaration |
| `sensors/EZORTD/ezortd.c` | `getTemperature()` implementation |
| `sensors/EZORTD/main.c` | One-shot binary: single read → JSON to stdout |
| `sensors/EZORTD/ezortd_daemon.c` | Daemon: infinite loop, writes JSON + CSV every second |
| `sensors/EZORTD/Makefile` | Builds `EZORTD` binary (one-shot target) |
### 3.2 `getTemperature()` — Protocol Detail
```c
// Signature
int getTemperature(int fd, double *temperature);
// Returns 0 on success, -1 on error
```
**Communication sequence:**
```
1. ioctl(fd, I2C_SLAVE, 0x66) — select slave address
2. write(fd, "R", 1) — issue read command (ASCII 'R')
3. usleep(1000000) — wait 1000 ms for conversion
4. read(fd, response, 32) — read up to 32 bytes
5. Check response[0] == 0x01 — status byte: 0x01 = success
6. atof(&response[1]) — parse ASCII float from bytes 1..N
```
**Error codes in `response[0]`:**
| Code | Meaning |
|---|---|
| `0x01` | Success |
| `0x02` | Syntax error in command |
| `0xFF` | No data (not ready) |
| `0xFE` | Pending (not ready yet) |
### 3.3 One-Shot Executable (`EZORTD`)
Compiled from `main.c + ezortd.c`. Opens `/dev/i2c-1`, calls `getTemperature()` once, prints result as JSON to stdout, exits.
```sh
./EZORTD
{ "temperature": 24.414 }
```
Used for testing and for cron-based updates.
### 3.4 Daemon (`ezortd_daemon`)
Compiled from `ezortd_daemon.c + ezortd.c`. Runs an infinite loop with 1-second sleep between iterations. On each iteration:
1. Reads temperature via `getTemperature()`
2. Overwrites `data/EZORTD.json` with current value
3. Appends a Unix-timestamp + temperature row to `logs/temp.csv`
**Output paths** (hardcoded in source — update before compiling):
```c
// JSON
"/home/cristian/airquality/basic-ui-dashboard/data/EZORTD.json"
// CSV log
"/home/cristian/airquality/basic-ui-dashboard/logs/temp.csv"
```
**JSON output format:**
```json
{ "temperature": 24.414 }
```
**CSV output format:**
```
timestamp,temperature ← header row (from EZORTD.csv template)
1717027200,24.414 ← Unix epoch (seconds), float to 3 decimal places
```
---
## 4. Data Pipeline
```
[EZO-RTD sensor]
│ I²C (0x66, /dev/i2c-1)
[ezortd_daemon — C process]
├──► data/EZORTD.json (overwrite, every 1 s)
│ { "temperature": 24.414 }
└──► logs/temp.csv (append, every 1 s)
1717027200,24.414
[Future: historical chart]
[Nginx — static file server]
│ HTTP GET ./data/EZORTD.json
[Browser — index.html]
│ setInterval(fetchData, 1000)
[DOM update — temp-value element]
```
---
## 5. Web Server Layer
**Server:** Nginx (static file serving only — no application logic)
**Document root:** Set to the repository root directory in `/etc/nginx/sites-available/default`:
```nginx
root /home/pi/<repo-path>;
```
**Served assets:**
| Path | Description |
|---|---|
| `/` or `/index.html` | Minimal temperature dashboard |
| `/index-css.html` | Extended multi-sensor dashboard |
| `/data/EZORTD.json` | Live temperature JSON (written by daemon) |
| `/images/*.svg` | Ionicons SVG assets (thermometer, water, cloud, sun) |
No server-side scripting is used. The daemon writes files to disk; Nginx serves them as-is.
---
## 6. Frontend Layer
### 6.1 `index.html` — Minimal Dashboard
Single-sensor display. Pure HTML + inline CSS + vanilla JS.
**Data source:** `GET ./data/EZORTD.json`
**Polling interval:** 1000 ms (`setInterval`)
**DOM targets:**
| Element ID | Content |
|---|---|
| `temp-value` | `data.temperature.toFixed(3) + " ℃"` |
| `last-update` | `"Updated: " + new Date().toLocaleTimeString()` |
### 6.2 `index-css.html` — Extended Dashboard
Multi-sensor card layout using Roboto (Google Fonts), flexbox, and CSS animations.
**Data sources (partially commented out):**
```javascript
const res = await Promise.all([
// fetch("./data/BH1750.json"), // light — pending
// fetch("./data/BMP180.json"), // pressure — pending
fetch("./data/HTU21D.json"), // temp + humidity (legacy sensor, active)
// fetch("./data/MH_Z19.json") // CO₂ — pending
]);
```
**Polling interval:** 6000 ms
**DOM targets:** `temp-value`, `humidity-value`, `co2-value`, `pressure-value`
---
## 7. Key Constants and Configuration
| Constant | Value | Location |
|---|---|---|
| EZO-RTD I²C address | `0x66` | `sensors/EZORTD/ezortd.h` |
| HTU21D I²C address | `0x40` | `sensors/HTU21D/htu21d.h` |
| I²C bus device | `/dev/i2c-1` | `sensors/EZORTD/main.c`, `ezortd_daemon.c` |
| Sensor read delay | 1,000,000 µs (1 s) | `sensors/EZORTD/ezortd.c` |
| Daemon loop interval | `sleep(1)` — 1 s | `sensors/EZORTD/ezortd_daemon.c` |
| JSON output path | `/home/cristian/…/data/EZORTD.json` | `ezortd_daemon.c` (**update per deployment**) |
| CSV log path | `/home/cristian/…/logs/temp.csv` | `ezortd_daemon.c` (**update per deployment**) |
| Frontend poll interval (primary) | 1000 ms | `index.html` |
| Frontend poll interval (extended) | 6000 ms | `index-css.html` |
| Nginx document root | `/home/pi/<repo-path>` | `/etc/nginx/sites-available/default` |
---
## 8. Build System
### EZO RTD
```makefile
CC=gcc
CFLAGS=-I.
OBJ=main.o ezortd.o
%.o: %.c
$(CC) -c -o $@ $< $(CFLAGS)
EZORTD: $(OBJ)
$(CC) -o $@ $^ $(CFLAGS)
```
No external libraries required. Uses only standard Linux I²C headers: `<linux/i2c-dev.h>`, `<sys/ioctl.h>`.
### HTU21D (legacy)
```makefile
EXTRA_LIBS=-li2c
```
Requires `libi2c` (`sudo apt install libi2c-dev`). Uses SMBus wrappers from `<i2c/smbus.h>`.
---
## 9. Legacy Sensor — HTU21D
Retained in `sensors/HTU21D/` for reference and backward compatibility with `index-css.html`.
| Property | Value |
|---|---|
| I²C Address | `0x40` |
| Measurements | Temperature + Relative Humidity |
| Temperature formula | `T = -46.85 + 175.72 × raw / 65536.0` |
| Humidity formula | `RH = -6 + 125 × raw / 65536.0` |
| Library dependency | `libi2c` |
| Command | SMBus block read (`0xE3` temp, `0xE5` humidity) |
---
## 10. Planned Sensors (Not Yet Integrated)
| Sensor | Measurement | Interface | Data file |
|---|---|---|---|
| BH1750 | Ambient light (lux) | I²C | `data/BH1750.json` |
| BMP581 | Atmospheric pressure (hPa) | I²C | `data/BMP581.json` |
| ZMOD4410 | TVOC / IAQ index | I²C | `data/ZMOD4410.json` |
---
## 11. File I/O Summary
| File | Writer | Reader | Format | Update Rate |
|---|---|---|---|---|
| `data/EZORTD.json` | `ezortd_daemon` | Nginx → browser | JSON object | 1 s |
| `logs/temp.csv` | `ezortd_daemon` | (manual / future viz) | CSV (epoch, float) | 1 s (append) |
| `data/HTU21D.json` | `HTU21D` binary (manual / cron) | Nginx → browser | JSON object | On demand |
| `data/EZORTD.csv` | (template only — unused) | — | CSV | — |
---
## 12. Security and Deployment Notes
- The Nginx instance serves on port 80 with no authentication. Suitable for a local LAN network only.
- The daemon runs as root (required for I²C access unless the user is added to the `i2c` group). Use `sudo usermod -aG i2c $USER` to avoid running as root.
- File paths in `ezortd_daemon.c` are hardcoded and must be updated per deployment before compilation.
- No input validation is performed on the JSON data in the browser; malformed JSON causes a silent catch/error in the console.

@ -0,0 +1,280 @@
# EZO RTD Temperature Monitor — Basic UI Dashboard
## Overview
This project implements a real-time temperature monitoring system based on the **Atlas Scientific EZO-RTD™** sensor module, interfaced via I²C to a Raspberry Pi. It extends a previous air quality monitoring platform (originally built around the HTU21D sensor) by replacing the temperature/humidity measurement stage with a high-precision RTD (Resistance Temperature Detector) circuit that provides temperature-only readings with significantly improved accuracy.
The system follows a layered architecture: a C daemon reads sensor data over I²C, writes it to a JSON file, and a lightweight HTML/CSS/JS dashboard served by Nginx polls that file every second to display live temperature readings in a browser.
---
## Hardware
### Sensor: Atlas Scientific EZO-RTD™ (ISCCB-2 Module)
The EZO-RTD is a complete circuit board that conditions RTD signals and communicates digitally. It supports both UART and I²C protocols. In this project it operates in **I²C mode**.
Key specifications:
| Parameter | Value |
|---|---|
| I²C Address | `0x66` |
| Supply Voltage | 3.3 V 5.0 V |
| Temperature Range | 126.000 °C to 1254.000 °C |
| Resolution | 0.001 °C |
| Accuracy | ±(0.1 °C + 0.0017 × |T|) |
| Communication | I²C / UART |
| Response Time | ≈ 1 s per reading |
### Wiring — ISCCB-2 → Raspberry Pi
| ISCCB-2 Pin | Raspberry Pi Pin | Signal |
|---|---|---|
| VCC | Pin 1 | 3.3 V |
| GND | Pin 6 | Ground |
| SDA | Pin 3 (GPIO2) | I²C Data |
| SCL | Pin 5 (GPIO3) | I²C Clock |
| OFF | — | Not connected |
> **Note:** The `OFF` pin is used to put the EZO circuit into low-power sleep mode. It is left unconnected in this implementation, meaning the circuit remains always active.
---
## Repository Structure
```
basic-ui-dashboard/
├── data/
│ ├── EZORTD.json # Live temperature output (written by daemon)
│ ├── EZORTD.csv # CSV log with timestamps (written by daemon)
│ └── HTU21D.json # Legacy HTU21D data (retained from previous project)
├── images/
│ ├── thermometer-outline.svg
│ ├── water-outline.svg
│ ├── cloud-outline.svg
│ └── sunny-outline.svg
├── sensors/
│ ├── EZORTD/
│ │ ├── ezortd.h # EZO RTD library header
│ │ ├── ezortd.c # I²C communication implementation
│ │ ├── main.c # One-shot executable (single reading → stdout)
│ │ ├── ezortd_daemon.c # Continuous daemon (writes JSON + CSV log)
│ │ └── Makefile
│ └── HTU21D/ # Legacy sensor (retained for reference)
│ ├── htu21d.h
│ ├── htu21d.c
│ ├── main.c
│ └── Makefile
├── index.html # Minimal dashboard (temperature only)
├── index-css.html # Extended dashboard (temperature, humidity, CO₂, pressure)
└── README.md
```
---
## Prerequisites
### Enable I²C on the Raspberry Pi
```sh
sudo raspi-config
# Navigate to: Interface Options → I2C → Enable
sudo reboot
```
### Install Required Packages
```sh
sudo apt update
sudo apt install i2c-tools build-essential
```
### Verify Sensor Detection
After wiring, confirm the EZO-RTD responds at address `0x66`:
```sh
sudo i2cdetect -y 1
```
Expected output (address `0x66` should be visible):
```
0 1 2 3 4 5 6 7 8 9 a b c d e f
00:
...
60: -- -- -- -- -- -- 66 -- -- -- -- -- -- -- -- --
```
> The EZO-RTD uses I²C bus 1 on the Raspberry Pi (pins 3 and 5). Confirm with `ls /dev/i2c-*`.
---
## Building the Sensor Programs
### EZO RTD (primary sensor)
```sh
cd sensors/EZORTD
make
```
This produces two targets:
- **`EZORTD`** — single-shot binary. Reads one temperature sample and prints it as JSON to stdout:
```sh
./EZORTD
{ "temperature": 24.414 }
```
- **`ezortd_daemon`** (compiled separately) — continuous loop that writes `data/EZORTD.json` and appends to a CSV log every second:
```sh
gcc -o ezortd_daemon ezortd_daemon.c ezortd.c -I.
./ezortd_daemon &
```
> Adjust the output file paths inside `ezortd_daemon.c` to match your local repository path before compiling.
---
## Serving the Dashboard
### Install and Configure Nginx
```sh
sudo apt install nginx
```
Edit the default site configuration:
```sh
sudo nano /etc/nginx/sites-available/default
```
Replace the `root` directive:
```nginx
root /home/pi/path/to/basic-ui-dashboard;
```
Restart Nginx:
```sh
sudo systemctl restart nginx
```
Open a browser and navigate to the device's hostname or IP address:
```
http://<raspberry-pi-ip>/
```
or, if mDNS is configured:
```
http://<hostname>.local/
```
The dashboard (`index.html`) polls `data/EZORTD.json` every **1 second** and displays the current temperature value.
---
## Automating Data Updates
To keep the JSON file continuously updated, run the daemon as a background service or configure it to start on boot using `systemd`.
### Minimal systemd unit (recommended)
Create `/etc/systemd/system/ezortd.service`:
```ini
[Unit]
Description=EZO RTD Temperature Daemon
After=network.target
[Service]
ExecStart=/home/pi/path/to/sensors/EZORTD/ezortd_daemon
Restart=always
[Install]
WantedBy=multi-user.target
```
Enable and start:
```sh
sudo systemctl enable ezortd
sudo systemctl start ezortd
```
### Alternative: crontab (lower resolution, simpler)
```sh
sudo crontab -e
```
Add (updates every minute):
```sh
* * * * * /home/pi/path/to/sensors/EZORTD/EZORTD > /home/pi/path/to/data/EZORTD.json
```
---
## Dashboard Files
### `index.html` — Temperature-only Display
Minimal single-sensor dashboard. Fetches `data/EZORTD.json` and refreshes every 1 second. Suitable for monitoring a single RTD probe.
### `index-css.html` — Multi-sensor Dashboard
Extended dashboard supporting temperature, humidity, CO₂, and atmospheric pressure from multiple JSON sources. Sensor cards are currently wired to `HTU21D.json`; the other fetch calls are commented out pending integration of additional sensors.
---
## Migration Notes from HTU21D
The previous version of this project used the HTU21D sensor for combined temperature and humidity measurements. The EZO-RTD replaces only the temperature measurement stage. Key differences:
| Aspect | HTU21D | EZO-RTD |
|---|---|---|
| I²C Address | `0x40` | `0x66` |
| I²C Bus | Bus 1 | Bus 1 |
| Measurements | Temperature + Humidity | Temperature only |
| Resolution | 0.01 °C | 0.001 °C |
| Communication library | `libi2c` (SMBus) | Raw I²C (`linux/i2c-dev.h`) |
| Read command | SMBus block read (`0xE3`) | ASCII `"R"` command, 1 s delay |
The HTU21D source files are retained in `sensors/HTU21D/` for reference.
---
## Troubleshooting
**Sensor not detected at `0x66`:**
Check that I²C mode is selected on the EZO-RTD. The default factory mode is UART. To switch to I²C, consult the [Atlas Scientific EZO-RTD datasheet](https://atlas-scientific.com/circuits/ezo-rtd-circuit/) and follow the UART-to-I²C mode switching procedure.
**`ioctl: Operation not permitted`:**
Run the executable with `sudo` or add the user to the `i2c` group:
```sh
sudo usermod -aG i2c $USER
```
**JSON file not updating:**
Verify the daemon is running (`ps aux | grep ezortd_daemon`) and that the output path in `ezortd_daemon.c` is correct and writable.
**Browser shows `--` (no data):**
Confirm Nginx is serving files from the correct directory and that `data/EZORTD.json` exists and is valid JSON.
---
## Future Work
- Integrate remaining sensors: BH1750 (light), BMP581 (pressure), ZMOD4410 (TVOC/IAQ)
- Add historical data visualization using the CSV log
- Implement WebSocket-based push updates to replace polling
- Package the daemon as a proper `systemd` service with logging
- Add temperature alarm thresholds with visual/audible notification

@ -1,248 +0,0 @@
# Readme basic-aqm
# Air Quality Monitor
The Air Quality Monitor (AQM) project is a large development that requieres hardware, back-end programmming for the sensor, and front-end programming/configuration to display the measuring data. **To read about each step please visit the specific repositories.**
This repository is about the setup and configuration of the sensors, back-end (APIs), and front-end (dashboard).
# Sensors setup
The project uses a PCB custom designed that includes the following sensors:
- HTU21D: Board Mount Humidity Sensors I.C 20D RH/T with I2C
- BH1750: Ambient Light Sensors Ambient Light Sensor Digital 16bit Serial I2C
- ZMOD4410: Air Quality Sensors TVOC IAQ Sensor with I2C output
- BMP581: Board Mount Pressure Sensors The BMP581 is a very small, low-power and low-noise 24-bit absolute barometric pressure sensor.
**Todo: add here the pcb image**
**However, you can connect the sensor-module version that is already prepared to communicate by I2C, like the one shown in the figure; htu21d module.**
![HTU21D-Module-Pinout](TZCBIN8qL-HTU21D-Module-Pinout.png)
## The HTU21D sensor
In case you want to test the application without the complete AQM-Hat, the sensor must be connected to the second I2C peripherical by:
P9.03 -> +3.3V (2nd pin - left position)
P9.01 -> DGND (1st pin - left position)
P9.19 -> I2C2_SCL (10th pin - left position)
P9.20 -> I2C2_SDA (10th pin - right position)
![beaglebone_black_pinmap](2MbNe2guV-beaglebone_black_pinmap.png)
## Reading Data from HTU21D
The HTU21D sensor uses specific commands to read temperature and humidity data. Heres how you can properly read and interpret this data. But first let us check if the device is connected and detected by the B3.
Before starting, install the bash tools to work with I2C:
```sh
sudo apt update
sudo apt install i2c-tools
```
Also install the build essential libraries to compile in C:
```sh
sudo apt update
sudo apt install build-essential
```
Next, to check if the sensor is connected and detected by the B3 into the I2C port 2, try the next command:
```sh
sudo i2cdetect -y 2
Warning: Can't use SMBus Quick Write command, will skip some addresses
0 1 2 3 4 5 6 7 8 9 a b c d e f
00:
10:
20:
30: -- -- -- -- -- -- -- --
40:
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60:
70:
```
This output **looks like there is no sensor connected at any address**. Nevertheless, for some reason the detection command is not checking the `0x40` line-address for the I2C. Thus we can try to directly read the specific addresses. To read the temperature, send the temperature measurement command (0xE3 for no hold mode or 0xF3 for hold mode) and then read two bytes of data.
```sh
sudo i2cget -y 2 0x40 0xE3 w
0x3871
```
if you get a similar output in the terminal the sensor is properly connected and ready.
## Converting temperature measurements
**Pending Todo**
# Back-end Apps
## Compiling and testing the sensor C-Programs
In the repository folder, go to the `sensors` sub-folder and make each main.c file to read and store the measurements:
```sh
$ cd sensors/HTU21D
$ make
gcc -c -o main.o main.c -I.
gcc -o HTU21D main.o htu21d.o -I. -li2c
$ ./HTU21D
{ "temperature": 24.60, "humidity": 52.50 }
```
The previous output indicates that the `HTU21D` executable is now working. **Do the same for all sensors.**
```sh
cd sensors/BMP180
make
cd ..
cd sensors/XXXX
make
cd ..
```
Finally, let us prepare the `JSON` files to test the Dashboard:
```sh
./sensors/HTU21D/HTU21D > ./data/HTU21D.json
...
```
# Front-end Dashboard
This project provides a basic web dashboard to test the functionality of the AQM-hat. The way it works and a improved version are presented later, after understanding how to prepare data and the web server to visualize the dashboard.
## Configuring Nginx
First install the Nginx package in the B3 board:
```sh
sudo apt update
sudo apt install nginx
```
Next, let's redirect the configuration file to our repository folder:
```sh
sudo vi /etc/nginx/sites-available/default
```
Replace the line:
```
root /var/www/html;
```
with:
```
root /home/debian/path/to/your/repository;
```
in my particular case:
```sh
root /home/debian/lwc/7-air-quality-ui/basic-ui;
```
```sh
sudo systemctl restart nginx
```
Open the web interface and type the IP addess of your device or visit the hostname + .local (`http://bbgmarx.local`); you should see a UI similar to the next one:
![basic-ui](C8ZLtB-py-basic-ui.jpg)
# Simple Sensor Dashboard
A simple sensor dashboard has been developed to fetch the data from the `JSON` files and then show them in a HTML fashion. The dashboard UI es updated every 60 seconds and considers a minimal HTML with CSS and JavaScript.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Sensor Dashboard</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; }
.sensor { margin: 10px; padding: 10px; border: 1px solid #ccc; }
.sensor-title { font-weight: bold; }
.sensor-value { font-size: 2em; color: #333; }
</style>
</head>
<body>
<h1>Sensor Data</h1>
<div id="temperature" class="sensor">
<div class="sensor-title">Temperature</div>
<div class="sensor-value" id="temp-value">--</div>
</div>
<div id="humidity" class="sensor">
<div class="sensor-title">Humidity</div>
<div class="sensor-value" id="humidity-value">--</div>
</div>
<script>
async function fetchData() {
try {
const tempResponse = await fetch('./data/HTU21D.json');
const tempData = await tempResponse.json();
document.getElementById('temp-value').textContent = tempData.temperature.toFixed(1) + ' ℃';
document.getElementById('humidity-value').textContent = tempData.humidity.toFixed(1) + ' %';
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Update data every 60 seconds
setInterval(fetchData, 60000);
fetchData(); // Initial fetch
</script>
</body>
</html>
```
## Code Explanation
### HTML Structure
1. **Header**:
- Sets the character encoding and viewport for responsiveness.
- Styles the page with a basic CSS structure for sensor data presentation.
2. **Sensor Display Elements**:
- The dashboard includes two sensors: **Temperature** and **Humidity**.
- Each sensor reading is displayed in a `.sensor` box with a title and value.
### CSS Styling
- **General Styles**: Applies a basic font style (Arial) and centers the text.
- **Sensor Box Styling**: `.sensor` boxes have a border, padding, and margin to create separation between sensor readings.
### JavaScript Logic
1. **Data Fetching (`fetchData`)**:
- Uses `fetch()` to retrieve JSON data for temperature and humidity.
- Updates the corresponding HTML elements with the latest data.
2. **Automatic Refresh**:
- `setInterval(fetchData, 60000);` updates the sensor data every 60 seconds, ensuring it stays current.
Ensure that the JSON file is regularly updated by a background service or script to keep the data current.
# Data updating
Configure roots crontab to update data every 5 minutes
```sh
sudo crontab -e
```
Edit it like so:
```sh
*/5 * * * * /usr/bin/python -m mh_z19 > /home/pi/anavi-phat-sensors-ui/data/MH_Z19.json
*/5 * * * * /home/pi/anavi-phat-sensors-ui/sensors/HTU21D/HTU21D > /home/pi/anavi-phat-sensors-ui/data/HTU21D.json
*/5 * * * * /home/pi/anavi-phat-sensors-ui/sensors/BMP180/BMP180 > /home/pi/anavi-phat-sensors-ui/data/BMP180.json
*/5 * * * * /home/pi/anavi-phat-sensors-ui/sensors/BH1750/BH1750 > /home/pi/anavi-phat-sensors-ui/data/BH1750.json
```

@ -1 +1 @@
{ "temperature": 24.900 } { "temperature": 25.270 }

Loading…
Cancel
Save