📄 Case cơ bản: Hệ thống IoT giám sát nhiệt độ và pH nước
🎯 Mục tiêu
Đọc dữ liệu từ cảm biến nhiệt độ và pH bằng ESP32.
Gửi dữ liệu qua TCP socket đến server .
Lưu dữ liệu vào PostgreSQL.
Hiển thị dữ liệu trên dashboard ReactJS + .
🧱 Thành phần hệ thống
Thành phần | Công nghệ sử dụng |
---|---|
Vi điều khiển | ESP32 + Arduino C |
Giao thức | TCP Socket |
Backend | + Express |
Cơ sở dữ liệu | PostgreSQL |
Dashboard | ReactJS + |
🔌 ESP32 (Arduino C)
#include <WiFi.h>
const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";
const char* host = "your_server_ip";
const uint16_t port = 3000;
WiFiClient client;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(500);
if (!client.connect(host, port)) {
Serial.println("Connection failed");
}
}
void loop() {
float temperature = random(250, 300) / 10.0;
float ph = random(60, 80) / 10.0;
String payload = "{\"device_id\":\"pond_01\",\"temperature\":" + String(temperature) + ",\"ph\":" + String(ph) + "}";
client.println(payload);
delay(10000);
}
🖥️ + Express
js
const net = require('net');
const { Pool } = require('pg');
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'aquafarm',
password: 'your_password',
port: 5432,
});
const server = net.createServer(socket => {
socket.on('data', async data => {
try {
const json = JSON.parse(data.toString());
await pool.query(
'INSERT INTO sensor_data (device_id, temperature, ph) VALUES ($1, $2, $3)',
[json.device_id, json.temperature, json.ph]
);
} catch (err) {
console.error('Error:', err.message);
}
});
});
server.listen(3000, () => console.log('TCP server listening on port 3000'));
🗄️ PostgreSQL
sql
CREATE TABLE sensor_data (
id SERIAL PRIMARY KEY,
device_id VARCHAR(50),
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
temperature FLOAT,
ph FLOAT
);
📊 Dashboard ReactJS +
jsx
import { Line } from 'react-chartjs-2';
import axios from 'axios';
import { useEffect, useState } from 'react';
function Dashboard() {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('/api/sensor_data').then(res => setData(res.data));
}, []);
const chartData = {
labels: data.map(d => d.timestamp),
datasets: [
{
label: 'Temperature (°C)',
data: data.map(d => d.temperature),
borderColor: 'red',
},
{
label: 'pH',
data: data.map(d => d.ph),
borderColor: 'blue',
},
],
};
return <Line data={chartData} />;
}
Comments
Post a Comment