TEMPERATURE
-- °C

0% Since last hour

HUMIDITY
-- %

0% Since last hour

DEVICES
-- Online

All active System stable

POWER
-- kWh

0% Efficiency up

API Reference

Tài liệu hướng dẫn sử dụng REST API cho thiết bị IoT và tích hợp hệ thống bên ngoài. Giao tiếp an toàn và thời gian thực.

Quick Start

Bước 1: Đăng ký thiết bị

// POST /api/auth/register-device curl -X POST http://localhost:5175/api/auth/register-device \ -H "Content-Type: application/json" \ -d '{ "macAddress": "AA:BB:CC:DD:EE:FF", "name": "ESP32 Living Room", "secret": "my_secret_key", "areaId": 1 }' // Response: { "success": true, "data": { "deviceId": 1, "token": "eyJhbGciOiJIUzI1NiIs...", "macAddress": "AA:BB:CC:DD:EE:FF" } }

Bước 2: Gửi dữ liệu sensor

// POST /api/datastream/{deviceId}/update curl -X POST http://localhost:5175/api/datastream/1/update \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_TOKEN" \ -d '{ "pins": [ {"pin": 0, "value": "25.5"}, {"pin": 1, "value": "60.2"} ] }'

Bước 3: Đọc dữ liệu từ Dashboard

// GET /api/datastream/{deviceId} curl http://localhost:5175/api/datastream/1 \ -H "Authorization: Bearer YOUR_TOKEN" // Response: { "success": true, "pins": [ {"pin": 0, "name": "Temperature", "value": "25.5", "unit": "°C"}, {"pin": 1, "name": "Humidity", "value": "60.2", "unit": "%"} ] }

Xác thực (Authentication)

Lưu ý: Mọi API request đều cần JWT Token trong header Authorization: Bearer {token}, trừ các endpoint được đánh dấu Public.

POST /api/auth/register-device Public Đăng ký thiết bị mới

Đăng ký thiết bị IoT mới và nhận Device Token để giao tiếp với API.

Request Body:

ParameterTypeRequiredMô tả
macAddressstringMAC address của thiết bị (VD: AA:BB:CC:DD:EE:FF)
namestringTên thiết bị (mặc định: "Device {mac}")
secretstringBí mật thiết bị để xác thực
areaIdintID khu vực (mặc định: 1)
templateIdintID device template
firmwareVersionstringPhiên bản firmware

Response (200 OK):

{ "success": true, "message": "Đăng ký thiết bị thành công!", "data": { "deviceId": 1, "deviceName": "ESP32 Living Room", "token": "eyJhbGciOiJIUzI1NiIs...", "macAddress": "AA:BB:CC:DD:EE:FF" } }
POST /api/auth/login Public Đăng nhập người dùng

Đăng nhập bằng email + password để nhận JWT Token.

// Request: POST /api/auth/login { "email": "admin@supperqnn.com", "password": "Admin@123", "rememberMe": true } // Response: { "success": true, "data": { "token": "eyJhbGciOiJIUzI1NiIs...", "user": { "id": "...", "email": "admin@supperqnn.com", "fullName": "Admin", "roles": ["admin"] } } }
POST /api/auth/register Public Đăng ký tài khoản mới
{ "email": "user@example.com", "password": "Pass@123", "fullName": "Nguyen Van A" }
POST /api/auth/refresh Auth Làm mới token
{ "token": "eyJhbGciOiJIUzI1NiIs..." } // Response: { "success": true, "data": { "token": "NEW_TOKEN..." } }
GET /api/auth/profile Auth Xem thông tin profile
{ "success": true, "data": { "userId": "...", "email": "user@example.com", "roles": ["admin"], "tokenType": "Bearer" } }

Quản lý Thiết bị (Device)

GET /api/device Auth Danh sách thiết bị

Query Parameters:

ParameterTypeMô tả
areaIdintFilter theo khu vực
templateIdintFilter theo template
isOnlineboolFilter theo trạng thái online
pageintTrang (mặc định: 1)
pageSizeintSố item/trang (mặc định: 50)
// Response: { "success": true, "data": [ { "id": 1, "name": "ESP32 Kitchen", "macAddress": "AA:BB:CC:DD:EE:FF", "isOnline": true, "lastSeen": "2026-06-09T12:00:00Z", "area": { "id": 1, "name": "Living Room" }, "template": { "id": 1, "name": "Weather Station" } } ], "pagination": { "page": 1, "pageSize": 50, "total": 5, "totalPages": 1 } }
GET /api/device/{id} Auth Chi tiết thiết bị + Pin Values
// Response: { "success": true, "data": { "id": 1, "name": "ESP32 Kitchen", "isOnline": true, "template": { "datastreams": [ { "pin": 0, "name": "Temperature", "value": "25.5", "unit": "°C" }, { "pin": 1, "name": "Humidity", "value": "60.2", "unit": "%" }, { "pin": 2, "name": "LED Control", "value": "0", "accessMode": "rw" } ] } } }
POST /api/device/{id}/ping Auth Thiết bị báo cáo trạng thái

Thiết bị gọi định kỳ để giữ trạng thái "online". Trả về pin values hiện tại để sync.

// Request: POST /api/device/1/ping { "ip": "192.168.1.100" } // Response: { "success": true, "data": { "deviceId": 1, "isOnline": true, "lastSeen": "2026-06-09T12:00:00Z", "pinValues": [ { "datastreamId": 1, "value": "25.5" } ] } }
POST /api/device/{id}/command Auth Gửi lệnh đến thiết bị qua SignalR
{ "command": "set_pin", "params": { "pin": "2", "value": "1" } }
GET /api/device/online Auth Danh sách thiết bị đang online
{ "success": true, "data": [ { "id": 1, "name": "ESP32 Kitchen", "lastSeen": "..." } ], "count": 3 }

Device Templates

Định nghĩa cấu trúc thiết bị: tên, kiểu, và danh sách Virtual Pin (Datastream).

GET /api/template Auth Danh sách templates
ParameterTypeMô tả
deviceTypestringFilter: esp32, arduino, raspberry-pi
familyIdintFilter theo gia đình
POST /api/template Auth Tạo template mới
{ "name": "ESP32 Weather Station", "templateId": "tpl_weather_001", "deviceType": "esp32", "datastreams": [ { "pin": 0, "name": "Temperature", "dataType": "double", "unit": "°C", "minValue": -40, "maxValue": 80 }, { "pin": 1, "name": "Humidity", "dataType": "double", "unit": "%", "minValue": 0, "maxValue": 100 }, { "pin": 2, "name": "LED Control", "dataType": "boolean", "accessMode": "rw" } ] }
POST /api/template/{id}/clone Auth Nhân bản template
{ "newTemplateId": "tpl_weather_002", "newName": "Weather Station Copy" }

Virtual Pins (Datastream)

Đọc/Ghi giá trị Virtual Pin - tương tự Blynk Virtual Pin API.

GET /api/datastream/{deviceId} Auth Lấy tất cả pin values
// Response: { "success": true, "deviceId": 1, "pins": [ { "pin": 0, "name": "Temperature", "value": "25.5", "unit": "°C", "lastUpdated": "..." }, { "pin": 1, "name": "Humidity", "value": "60.2", "unit": "%" } ] }
GET /api/datastream/{deviceId}/{pin} Auth Đọc giá trị pin cụ thể
GET /api/datastream/1/0 { "success": true, "data": { "pin": 0, "name": "Temperature", "value": "25.5" } }
POST /api/datastream/{deviceId}/update Auth Batch update (ESP32 gửi dữ liệu)

API chính cho ESP32: Gửi nhiều pin values cùng lúc. Tự động cập nhật trạng thái thiết bị online.

// Request: POST /api/datastream/1/update Authorization: Bearer {device_token} { "pins": [ { "pin": 0, "value": "25.5" }, { "pin": 1, "value": "60.2" }, { "pin": 3, "value": "1.5" } ] } // Response: { "success": true, "message": "Đã cập nhật 3 Virtual Pins", "timestamp": "2026-06-09T12:00:00Z" }
PUT /api/datastream/{deviceId}/{pin} Auth Ghi giá trị pin (từ dashboard)
PUT /api/datastream/1/2 { "value": "1" } // → Bật LED (Virtual Pin V2 = 1)
GET /api/datastream/{deviceId}/{pin}/history Auth Lịch sử giá trị pin
ParameterTypeMô tả
fromdatetimeTừ thời điểm
todatetimeĐến thời điểm
pageintTrang (mặc định: 1)
pageSizeintSố item/trang (mặc định: 100)

Lịch sử & Thống kê

GET /api/history/stats Auth Thống kê tổng quan
{ "success": true, "data": { "totalDevices": 5, "onlineDevices": 3, "offlineDevices": 2, "totalReadings": 1250, "avgTemperature": 25.3, "avgHumidity": 62.1, "avgPower": 0.45, "lastUpdate": "2026-06-09T12:00:00Z" } }
GET /api/history/sensor Auth Lịch sử sensor readings
GET /api/history/sensor?deviceId=1&type=temp&from=2026-06-01&to=2026-06-09
GET /api/history/export Auth Export dữ liệu (CSV/JSON)
GET /api/history/export?deviceId=1&type=temp&format=csv

Webhooks

HTTP callback tự động khi có sự kiện IoT (pin change, device offline, v.v.).

POST /api/webhook Auth Tạo webhook mới
{ "name": "Notify khi nhiệt độ cao", "url": "https://my-server.com/api/notify", "method": "POST", "bodyTemplate": "{\"device_id\": \"{device_id}\", \"temp\": {value}}", "eventType": "pin_change", "targetPin": 0, "condition": "{\"min\": 30, \"max\": 100}", "deviceId": 1 }
POST /api/webhook/{id}/test Auth Test webhook thủ công
{ "success": true, "data": { "url": "https://my-server.com/api/notify", "statusCode": 200, "responseBody": "OK" } }

Tự động hóa (Automation)

Quy tắc IF-THEN tự động: "Nếu nhiệt độ > 30°C thì bật quạt".

POST /api/automation Auth Tạo automation mới
// Ví dụ: Bật LED khi nhiệt độ > 30°C { "name": "Bật LED khi nóng", "triggerType": "pin_change", "triggerConfig": "{\"device_id\": 1, \"pin\": 0, \"operator\": \">\", \"threshold\": 30}", "actions": [ {"type": "set_pin", "device_id": 1, "pin": 2, "value": "1"}, {"type": "notify", "message": "Nhiệt độ cao! Đã bật LED."} ], "familyId": 1 } // Ví dụ: Lịch trình mỗi ngày 7h sáng { "name": "Bật đèn mỗi sáng", "triggerType": "cron", "triggerConfig": "{\"cron\": \"0 7 * * *\"}", "actions": [ {"type": "set_pin", "device_id": 1, "pin": 2, "value": "1"} ] }
POST /api/automation/{id}/trigger Auth Kích hoạt thủ công

Thực thi tất cả actions trong automation ngay lập tức (dùng để test).

SignalR Real-time

Kết nối WebSocket real-time để nhận cập nhật tức thời.

Kết nối Hub

// JavaScript (Browser) const connection = new signalR.HubConnectionBuilder() .withUrl("/iotHub") .build(); await connection.start(); // Lắng nghe sự kiện connection.on("ReceivePinUpdate", (deviceId, pin, value) => { console.log(`Device ${deviceId} Pin V${pin} = ${value}`); }); connection.on("ReceiveDeviceStatus", (deviceId, isOnline) => { console.log(`Device ${deviceId} is ${isOnline ? 'ONLINE' : 'OFFLINE'}`); }); connection.on("ReceiveCommand", (data) => { console.log("Command:", data.command, data.params); }); connection.on("ReceiveNotification", (data) => { console.log("Notification:", data.message); });

ESP32 WebSocket (SignalR Protocol)

// ESP32 gửi lệnh JoinDeviceGroup { "type": 1, "target": "JoinDeviceGroup", "arguments": [1] } // ESP32 nhận lệnh từ server { "type": 1, "target": "ReceiveCommand", "arguments": [{ "command": "set_pin", "params": { "pin": 2, "value": "1" } }] }

Hướng dẫn ESP32

Thư viện cần thiết

  • WiFi (ESP32 core)
  • HTTPClient (ESP32 core)
  • ArduinoJson v7.x
  • DHT sensor library (Adafruit)
  • WebSocketsClient (Markus Sattler) - cho SignalR

Luồng hoạt động

1️⃣ Kết nối WiFi

2️⃣ Đọc token từ EEPROM (hoặc đăng ký mới)

3️⃣ Kết nối WebSocket SignalR Hub

4️⃣ Gửi sensor data qua HTTP POST mỗi 10s

5️⃣ Nhận lệnh real-time qua WebSocket

6️⃣ Ping server mỗi 30s giữ trạng thái online

Cấu hình EEPROM

AddressSizeNội dung
0200 bytesJWT Token
2004 bytesDevice ID (big-endian)

Virtual Pin Mapping (mẫu)

PinTênLoạiQuyềnMô tả
V0Temperaturedoubler (read)Nhiệt độ °C
V1Humiditydoubler (read)Độ ẩm %
V2LED Controlbooleanrw (read/write)Bật/tắt LED
V3Powerdoubler (read)Công suất kW
Web hosting by Somee.com