Features #2313
closedFeatures #2280: Server-Software
Features #2281: ThingsBoard
Tìm hiểu phương pháp nhóm thiết bị
100%
Description
Mục tiêu: tạo dashboard quản lý nhóm thiết bị, xấy dựng cấu trúc quản lý thiết bị theo tầng nhằm đáp ứng quản lý dashboard
Company
├─ Factory
│ ├─ Building
│ │ ├─ Floor
│ │ │ ├─ Zone
│ │ │ │ ├─ Sensor Node
Files
Updated by T. Nguyen Van Thanh 8 months ago
- Due date set to 2026-04-03
- ThingsBoard CE 4.2.1 -- Thiết kế cơ chế nhóm thiết bị (Grouping Architecture)
- 1. Mục tiêu
Thiết kế cơ chế nhóm thiết bị trong ThingsBoard CE để: - Quản lý thiết
bị theo cấu trúc tổ chức - Dễ dàng filter dashboard - Scale hệ thống khi
số lượng device tăng - Hỗ trợ alarm và monitoring theo khu vực - Thay
thế Entity Groups (chỉ có trong PE)
- 2. Cơ sở thiết kế (Design foundation)
ThingsBoard CE không có: - Entity Groups UI - Dynamic Groups
Nhưng có các feature thay thế: - Assets - Entity Relations -
Attributes - Device Profiles - Dashboard state filtering
=\> Có thể kết hợp để tạo hệ thống grouping mạnh tương đương.
- 3. Kiến trúc đề xuất (Recommended Architecture)
Hierarchy công nghiệp:
Company → Area → Workshop → Room → Cabinet → Device
Mapping vào ThingsBoard:
| Level \ | ThingsBoard Type \ |
\|-------\|------------------\| Company \| Asset \| \| Area \| Asset \|
\| Workshop \| Asset \| \| Room \| Asset \| \| Cabinet \| Asset \| \|
Device \| Device \|
Relation:
Parent → Contains → Child
Ví dụ:
Company\
└── Area A\
└── Workshop A\
└── Room 101\
└── Cabinet 1\
└── Sensor Node
- 4. Vai trò từng thành phần
- Asset dùng cho:
- Hierarchy
- Location
- Organization
- Physical structure
- Attribute dùng cho:
- Tags
- Metadata
- Config
- Thresholds
- Device classification
- Telemetry:
- Sensor data
- Measurements
- Runtime state
- 5. Attribute schema đề xuất
- Device attributes:
{ "nodeType":"environment", "sensorCount":4, "zone":"A",
"installDate":"2026-03-01" }
- Threshold attributes:
{ "temp1_warn":30, "temp1_crit":40 }
- 6. Naming convention (rất quan trọng)
Asset:
AREA-A WORKSHOP-A ROOM-101 CABINET-01
Device:
ENV-NODE-ROOM101-01
Tránh:
device1 sensorABC tempNode
- 7. Cách query group trong Dashboard
Sử dụng:
Datasource → Entity relations query
Config:
Root entity: Room 101
Relation: Contains
Direction: From
Entity type: Device
=\> Lấy tất cả device trong room.
- 8. Pattern dashboard chuẩn
Layout đề xuất:
LEFT: Entity hierarchy
RIGHT: Device info Charts Alarms Map
Flow:
Click hierarchy → change state → update widgets
- 9. Tính khả thi
Feature CE support
--------------------- ------------
Assets YES
Relations YES
Attributes YES
Dashboard filtering YES
Hierarchy queries YES
=\> Hoàn toàn khả thi trong CE.
- 10. Ưu điểm kiến trúc này
- Scalable
- Dễ maintain
- Query nhanh
- Dashboard dynamic
- Alarm routing theo location
- Map filtering
- Rule engine grouping
Có thể scale: 10 → 100 → 1000 → 10000 devices
Không cần redesign.
- 11. Best practice khuyến nghị
Nên:
- Dùng Asset cho hierarchy
- Dùng Contains relation
- Dùng Attribute cho metadata
- Chuẩn hóa naming
- Chuẩn hóa telemetry key
- Chuẩn hóa threshold structure
Không nên:
- Hardcode group trong widget
- Dùng random relation type
- Lưu location trong device name
- Trộn hierarchy và metadata
- 12. Kiến trúc mở rộng tương lai
Có thể thêm:
Company Factory Area Production Line Room Cabinet Device
Có thể thêm device:
Power meter Gateway PLC Camera Fire sensor
Không cần đổi structure.
- 13. Recommendation cuối cùng
Kiến trúc tốt nhất cho ThingsBoard CE:
Asset → Structure Relation → Hierarchy Attribute → Metadata Telemetry →
Data
Đây là kiến trúc chuẩn cho Industrial IoT platform.
- 14. Kết luận
Kết hợp:
Assets + Relations + Attributes
=\> Tạo grouping mạnh tương đương ThingsBoard PE.
Đây là cách recommended cho production system.
Updated by T. Nguyen Van Thanh 8 months ago
- % Done changed from 20 to 50
Tài liệu xây dựng kiến trúc quản lý thiết bị
https://docs.google.com/document/d/1db75W2DTTW7VeS_QWLRqFnnsB_vvDqBqkR8QvogttsA/edit?usp=sharing
Updated by D. Vu Minh Duc 8 months ago
- Target version set to PROTOTYPE
Updated by D. Vu Minh Duc 8 months ago
- Due date changed from 2026-04-03 to 2026-04-10
Gia hạn thêm thời gian hoàn thành
Updated by T. Nguyen Van Thanh 8 months ago
- % Done changed from 50 to 90
Phase 1 — Setup nền tảng
Cài đặt ThingsBoard CE v4.2.1 với PostgreSQL 14+ + TimescaleDB extension
Bật ts_key_value_partitioning = MONTHS trong thingsboard.yml
Tạo Service Account và API key cho provisioning script
Phase 2 — Topology & Provisioning
Tạo Company Asset và cấu hình server attributes
Tạo Factory Assets, assign cho Customer tương ứng, gắn Contains với Company
Tạo Floor Assets với mapFloorId đồng bộ với floor plan dashboard
Tạo Line Assets, cấu hình targetOEE, managerId
Tạo Device Profiles, cấu hình Provisioning key/secret
Chạy provisioning script từ https://github.com/MKAC-R-D-S/tb_tool_created_device.git — set đầy đủ attributes bao gồm xPos/yPos/zone
Phase 3 — Rule Engine
Tạo Root Rule Chain với enrichment + routing theo group
Tạo Alarm Processing sub-chain với hysteresis logic (clear threshold)
Tạo Data Enrichment sub-chain (inject factory, floor, line, zone, shiftId)
Tạo Aggregation sub-chain (1-min, 15-min averages)
Tạo Maintenance Reminder sub-chain (scheduler daily)
Cấu hình Notification targets: email, Telegram webhook theo priority
Phase 4 — Dashboard
Tạo Main Dashboard với Entity Tree widget (phân tầng Contains)
Cấu hình Dashboard States theo phân tầng với drill-down navigation
Tạo Floor Plan widget dùng xPos/yPos cho từng mapFloorId
Cấu hình Entity Alias với managerId filterCấu hình User roles: Tenant Admin, Factory Manager (Customer Admin), Operator
Updated by T. Nguyen Van Thanh 8 months ago
- Kiến trúc Hierarchy Statistics tối ưu cho ThingsBoard CE v4.2.1
Phiên bản 2.0 — Bổ sung Statistics Microservice, sửa race condition, fan-out mechanism, và hierarchy traversal
- Mục tiêu thiết kế
Thiết kế kiến trúc quản lý hierarchy cho hệ IoT/EMS có khả năng:
- Hỗ trợ hierarchy động không giới hạn level
- Scale 10k → 100k devices
- Rule chain nhẹ, không block Rule Engine
- Dashboard load nhanh
- Không query relation runtime
- Realtime statistics với số liệu chính xác dưới tải cao
- Dễ mở rộng trong tương lai
- Nguyên tắc thiết kế cốt lõi
- NÊN làm
- Cache parent hierarchy vào device attribute
- Incremental aggregation qua atomic counter
- Event driven update qua webhook
- Attribute based dashboard
- Periodic reconcile job
- External microservice xử lý fan-out và traverse
- KHÔNG NÊN
- Query hierarchy mỗi event
- Scan devices để đếm
- Recalculate toàn bộ thường xuyên
- Dùng telemetry để đếm stats
- Read-modify-write attribute trực tiếp trong rule chain (race condition)
- Traverse relation graph bên trong transformation script
- Kiến trúc tổng thể
Thay đổi so với v1: Bổ sung Statistics Microservice làm lớp trung gian xử lý fan-out, atomic counter, và hierarchy traversal. Rule chain chỉ còn nhiệm vụ detect event và gọi webhook — không còn tự aggregate.
```
┌─────────────────────────────────────────────────────────────────┐
│ ThingsBoard CE │
│ │
│ Device Event ──► Rule Chain ──► REST API Call node │
│ │ │
│ Dashboard ◄── Server Attributes ◄─────┼────────────────┐ │
└────────────────────────────────────────┼────────────────┼───────┘
│ │
▼ │
┌───────────────────────────┐ │
│ Statistics Microservice │ │
│ (FastAPI + Redis) │ │
│ │ │
│ • Fan-out to N parents │ │
│ • Atomic counter │ │
│ • Hierarchy traversal │ │
│ • Reconcile job │ │
└────────────┬──────────────┘ │
│ │
│ TB REST API │
└───────────────────┘
```
```mermaid
flowchart TD
DeviceEvent[Device Event] --> RuleChain[Rule Chain\nDetect + Forward]
RuleChain --> Webhook[REST API Call\nPOST /stats/event]
Webhook --> MicroService[Statistics Microservice]
MicroService --> Redis[Redis\nAtomic Counter]
MicroService --> TBAPI[TB REST API\nSave Attributes]
TBAPI --> AssetAttr[Asset Server Attributes]
AssetAttr --> Dashboard[Dashboard]
```
- Cấu trúc Hierarchy
Relation type: `Contains`
```mermaid
graph TD
Company --> Factory
Factory --> Building
Building --> Floor
Floor --> Room
Room --> Line
Line --> Device
```
Không fix số level. Microservice traverse động theo relation graph.
- Data Model chuẩn
- Device — Server Attributes
```json
{
"parentIds": "[\"line_uuid\",\"room_uuid\",\"floor_uuid\",\"factory_uuid\",\"company_uuid\"]",
"parentEntityTypes": "{\"line_uuid\":\"ASSET\",\"room_uuid\":\"ASSET\",\"factory_uuid\":\"ASSET\",\"company_uuid\":\"ASSET\"}",
"isOnline": false,
"hasAlarm": false,
"deviceType": "power",
"system": "ems"
}
```
Lưu ý quan trọng: `parentIds` lưu dưới dạng JSON string (không phải array native).
Mọi script đọc attribute này phải gọi `JSON.parse()` trước khi xử lý.
`parentEntityTypes` bổ sung để microservice biết entity type khi gọi TB REST API.
- Asset — Server Attributes
```json
{
"totalDevices": 0,
"onlineDevices": 0,
"offlineDevices": 0,
"alarmDevices": 0,
"criticalAlarms": 0,
"majorAlarms": 0,
"minorAlarms": 0,
"warningAlarms": 0
}
```
Generic cho mọi level hierarchy.
- Flow Provision Device (Đã sửa)
Thay đổi so với v1: Bước traverse hierarchy chuyển sang Statistics Microservice thay vì rule chain. Rule chain không thể đệ quy query relation graph.
```mermaid
sequenceDiagram
participant Device
participant TB
participant Rule as Rule Chain
participant MS as Statistics Microservice
participant TBAPI as TB REST API
Device->>TB: Provision / Tạo relation
TB->>Rule: ENTITY_CREATED hoặc RELATION_CREATED
Rule->>MS: POST /provision/traverse\n{deviceId, deviceType}
MS->>TBAPI: GET /api/relations?fromId=&relationType=Contains (lặp đến root)
TBAPI-->>MS: Danh sách parent từng level
MS->>TBAPI: POST /api/plugins/telemetry/DEVICE/{id}/SERVER_SCOPE\n{parentIds: "...", parentEntityTypes: "..."}
MS->>TBAPI: Tăng totalDevices, offlineDevices cho mỗi parent
```- API endpoint provision
```
POST /provision/traverse
{
"deviceId": "uuid",
"entityType": "DEVICE"
}
```
Microservice tự traverse ngược lên root, lưu `parentIds` về device, cập nhật `totalDevices` và `offlineDevices` cho mỗi ancestor.
- Rule Chain Architecture (Đã sửa hoàn chỉnh)
Thay đổi quan trọng so với v1:
1. Thêm Originator Attributes node (enrichment) trước mọi script cần đọc attribute device
2. Thêm REST API Call node để forward event tới microservice thay vì tự aggregate
3. Script aggregation chuyển sang microservice
```mermaid
flowchart TD
Input[Message In] --> Switch[Message Type Switch]
Switch -->|CONNECT_EVENT| EnrichConnect[Originator Attributes\nLoad: isOnline, parentIds, parentEntityTypes]
Switch -->|DISCONNECT_EVENT| EnrichDisconnect[Originator Attributes\nLoad: isOnline, parentIds, parentEntityTypes]
Switch -->|ALARM_CREATED| EnrichAlarm[Originator Attributes\nLoad: parentIds, parentEntityTypes, hasAlarm]
Switch -->|ALARM_CLEARED| EnrichAlarmEnrichConnect --> StateFilterConnect[State Change Filter\nSkip nếu isOnline true]
EnrichDisconnect --> StateFilterDisconnect[State Change Filter\nSkip nếu isOnline false]StateFilterConnect --> UpdateDevice[Save Attributes node\nCập nhật isOnline=true]
StateFilterDisconnect --> UpdateDevice2[Save Attributes node\nCập nhật isOnline=false]UpdateDevice --> CallMS[REST API Call\nPOST /stats/event]
UpdateDevice2 --> CallMS
EnrichAlarm --> CallMS
```- Thứ tự node bắt buộc trong rule chain
```
1. Message Type Switch
2. Originator Attributes (enrichment) ← BẮT BUỘC trước mọi script
3. State Change Filter (script)
4. Save Attributes (cập nhật isOnline / hasAlarm trên device)
5. REST API Call → Statistics Microservice
```
- Node 1: Message Type Switch
Filter các message type:
```
CONNECT_EVENT
DISCONNECT_EVENT
ALARM_CREATED
ALARM_CLEARED
```
- Node 2: Originator Attributes (Enrichment — Phần mới, bắt buộc)
Đây là node bị thiếu trong v1. Nếu không có node này, metadata không có `isOnline` hay `parentIds` — script sẽ luôn nhận `undefined`.
Cấu hình node "Originator Attributes" trong TB:
```
Scope: SERVER
Keys to fetch:
- isOnline
- hasAlarm
- parentIds
- parentEntityTypes
```
Sau node này, các giá trị trên sẽ có trong `metadata` dưới dạng:
```
metadata.isOnline = "true" hoặc "false" (string, không phải boolean)
metadata.parentIds = "[\"uuid1\",\"uuid2\"]" (JSON string)
metadata.parentEntityTypes = "{\"uuid1\":\"ASSET\"}" (JSON string)
metadata.hasAlarm = "true" hoặc "false"
```
- Node 3: State Change Filter (Đã sửa)
Thay đổi so với v1: Script phải ép kiểu string→boolean vì TB trả attribute dạng string.
```javascript
// Script cho CONNECT_EVENT
// metadata.isOnline là string "true"/"false", không phải boolean
var currentOnline = (metadata.isOnline === 'true');
if (currentOnline === true) {
// Device đã online rồi, bỏ qua tránh double-count
return null;
}
return { msg: msg, metadata: metadata, msgType: msgType };
```
```javascript
// Script cho DISCONNECT_EVENT
var currentOnline = (metadata.isOnline === 'true');
if (currentOnline === false) {
// Device đã offline rồi, bỏ qua
return null;
}
return { msg: msg, metadata: metadata, msgType: msgType };
```
- Node 4: Save Attributes (Cập nhật state trên device)
Sau khi xác nhận state thực sự thay đổi, cập nhật attribute trên device ngay trong rule chain:
```javascript
// Script build message cập nhật isOnline
// Chạy trong Transformation node trước Save Attributes node
var newState = (msgType === 'CONNECT_EVENT');
msg.isOnline = newState;
return { msg: msg, metadata: metadata, msgType: 'POST_ATTRIBUTES_REQUEST' };
```
Sau đó nối vào node "Save Attributes" scope `SERVER`.
- Node 5: REST API Call → Statistics Microservice
Thay vì tự aggregate (gây race condition), rule chain chỉ gọi webhook:
Cấu hình REST API Call node:
```
Method: POST
URL: http://stats-service:8080/stats/event
Headers:
X-API-Key: <internal_api_key>
Content-Type: application/json
Body (script):
var body = {
deviceId: metadata.originatorId,
eventType: msgType,
parentIds: metadata.parentIds,
parentEntityTypes: metadata.parentEntityTypes,
alarmSeverity: msg.severity || null
};
return JSON.stringify(body);
```
- Statistics Microservice (Phần mới hoàn toàn)
- Mục đích
Xử lý tất cả những gì Rule Chain không làm được:
- Fan-out: ghi attribute lên N parent entities cùng lúc
- Atomic counter: dùng Redis `INCR`/`DECR` để tránh race condition
- Hierarchy traversal: gọi TB REST API đệ quy khi provision
- Write-back: đẩy giá trị từ Redis về TB server attributes định kỳ
- Reconcile job: tính lại toàn bộ stats theo lịch
- Cấu trúc dự án
```
stats_service/
├── app/
│ ├── main.py
│ ├── config.py
│ ├── api/
│ │ ├── stats_api.py # POST /stats/event
│ │ └── provision_api.py # POST /provision/traverse
│ ├── core/
│ │ ├── tb_client.py # TB REST API client
│ │ ├── redis_counter.py # Atomic counter operations
│ │ └── hierarchy.py # Traverse relation graph
│ ├── jobs/
│ │ ├── write_back.py # Flush Redis → TB attributes
│ │ └── reconcile.py # Full recalculate job
│ └── models/
│ └── events.py
├── requirements.txt
└── .env
```
- API endpoints
```
POST /stats/event ← Nhận event từ TB rule chain
POST /provision/traverse ← Traverse hierarchy khi provision device
GET /health
```
- Xử lý event (fan-out + atomic)
- app/api/stats_api.py
from fastapi import APIRouter, HTTPException
from app.core.redis_counter import RedisCounter
from app.core.tb_client import TBClient
import json
router = APIRouter()
@router.post("/stats/event")
async def handle_event(payload: dict):
device_id = payload["deviceId"]
event_type = payload["eventType"]
parent_ids_str = payload.get("parentIds", "[]")
parent_types_str = payload.get("parentEntityTypes", "{}")
alarm_severity = payload.get("alarmSeverity")
try:
parent_ids = json.loads(parent_ids_str)
parent_types = json.loads(parent_types_str)
except Exception:
raise HTTPException(status_code=400, detail="parentIds/parentEntityTypes parse error")- Tính delta theo event type
deltas = _compute_deltas(event_type, alarm_severity)
- Fan-out: cập nhật atomic counter cho tất cả parent
for parent_id in parent_ids:
entity_type = parent_types.get(parent_id, "ASSET")
for field, delta in deltas.items():
await counter.increment(
entity_type=entity_type,
entity_id=parent_id,
field=field,
delta=delta
)
def _compute_deltas(event_type: str, alarm_severity: str | None) -> dict:
if event_type "CONNECT_EVENT":
return {"onlineDevices": 1, "offlineDevices": -1}
if event_type == "ALARM_CREATED":
deltas = {"alarmDevices": 1}
if alarm_severity == "CRITICAL": deltas["criticalAlarms"] = 1
elif alarm_severity == "MAJOR": deltas["majorAlarms"] = 1
elif alarm_severity == "MINOR": deltas["minorAlarms"] = 1
elif alarm_severity == "WARNING":deltas["warningAlarms"] = 1
return deltasif event_type == "ALARM_CLEARED":
deltas = {"alarmDevices": -1}
if alarm_severity == "CRITICAL": deltas["criticalAlarms"] = -1
elif alarm_severity == "MAJOR": deltas["majorAlarms"] = -1
elif alarm_severity == "MINOR": deltas["minorAlarms"] = -1
elif alarm_severity == "WARNING":deltas["warningAlarms"] = -1
return deltas- Redis Atomic Counter (Giải pháp race condition)
```pythonĐây là giải pháp cho vấn đề race condition của v1.
Redis `INCR`/`DECR` là atomic — không có lost update dù 100k device event đồng thời.
- app/core/redis_counter.py
import redis.asyncio as aioredis
class RedisCounter:
"""
Mỗi field của mỗi entity lưu thành một Redis key:
key format: stats:{entity_type}:{entity_id}:{field}
Ví dụ: stats:ASSET:factory-uuid:onlineDevices
"""
def _key(self, entity_type: str, entity_id: str, field: str) -> str:
return f"stats:{entity_type}:{entity_id}:{field}"async def increment(self, entity_type: str, entity_id: str,
field: str, delta: int) -> int:
key = self._key(entity_type, entity_id, field)
if delta >= 0:
result = await self.redis.incrby(key, delta)
else:
result = await self.redis.decrby(key, abs(delta))- Không để xuống dưới 0
if result < 0:
await self.redis.set(key, 0)
result = 0
- Đánh dấu entity này cần write-back
await self.redis.sadd("dirty_entities", f"{entity_type}:{entity_id}")
return result
async def get_all_fields(self, entity_type: str, entity_id: str) -> dict:
fields = [
"totalDevices", "onlineDevices", "offlineDevices",
"alarmDevices", "criticalAlarms", "majorAlarms",
"minorAlarms", "warningAlarms"
]
result = {}
for field in fields:
key = self._key(entity_type, entity_id, field)
val = await self.redis.get(key)
result[field] = int(val) if val else 0
return resultasync def get_dirty_entities(self) -> list[str]:
members = await self.redis.smembers("dirty_entities")
return [m.decode() for m in members]async def clear_dirty(self, entity_key: str):
await self.redis.srem("dirty_entities", entity_key)
```- Write-back job: Redis → TB Attributes
- app/jobs/write_back.py
- Chạy mỗi 5 giây — flush dirty entities từ Redis về TB attributes
import asyncio
from app.core.redis_counter import RedisCounter
from app.core.tb_client import TBClient
async def write_back_loop():
counter = RedisCounter()
tb = TBClient()
for entity_key in dirty:
entity_type, entity_id = entity_key.split(":", 1)
stats = await counter.get_all_fields(entity_type, entity_id)success = await tb.save_server_attributes(
entity_type=entity_type,
entity_id=entity_id,
attributes=stats
)
if success:
await counter.clear_dirty(entity_key)
```Tại sao không ghi thẳng vào TB mỗi event?
Với 100k device, mỗi event gây N lần REST call đến TB (N = số levels hierarchy).
Write-back 5 giây batch nhiều event lại, chỉ ghi 1 lần per entity per 5 giây — giảm tải TB đáng kể.
- TB REST API Client
- app/core/tb_client.py
import httpx
import asyncio
from app.config import settings
class TBClient:
def init(self):
self.base_url = settings.TB_BASE_URL
self._token: str | None = None
self._client = httpx.AsyncClient(timeout=10.0)
async def _get_token(self) -> str:
if self._token:
return self._token
resp = await self._client.post(
f"{self.base_url}/api/auth/login",
json={"username": settings.TB_USERNAME, "password": settings.TB_PASSWORD}
)
self._token = resp.json()["token"]
return self._tokenasync def save_server_attributes(self, entity_type: str,
entity_id: str, attributes: dict) -> bool:
token = await self._get_token()
url = f"{self.base_url}/api/plugins/telemetry/{entity_type}/{entity_id}/SERVER_SCOPE"
resp = await self._client.post(
url,
json=attributes,
headers={"X-Authorization": f"Bearer {token}"}
)
if resp.status_code == 401:
self._token = None # Token hết hạn, retry
return await self.save_server_attributes(entity_type, entity_id, attributes)
return resp.status_code == 200async def get_relations(self, from_id: str, from_type: str,
relation_type: str = "Contains") -> list[dict]:
token = await self._get_token()
url = f"{self.base_url}/api/relations"
resp = await self._client.get(
url,
params={"fromId": from_id, "fromType": from_type,
"relationType": relation_type},
headers={"X-Authorization": f"Bearer {token}"}
)
return resp.json() if resp.status_code == 200 else []
```- Hierarchy Traversal Service (Phần mới — giải quyết vấn đề provision)
```pythonVấn đề của v1: Rule chain không thể đệ quy query relation graph.
Giải pháp: Microservice traverse toàn bộ ancestor chain bằng cách gọi TB REST API lặp.
- app/core/hierarchy.py
from app.core.tb_client import TBClient
class HierarchyTraverser:
async def get_all_ancestors(self, entity_id: str,
entity_type: str) -> list[dict]:
"""
Traverse ngược từ device/asset lên đến root.
Trả về list [{id, type, level}] từ gần nhất đến xa nhất.
"""
ancestors = []
visited = set()
queue = [(entity_id, entity_type)]- Tìm tất cả parent của entity hiện tại
- TB API: GET /api/relations/info?toId=...&toType=...&relationType=Contains
parents = await self.tb.get_parent_relations(
to_id=current_id,
to_type=current_type
)
for parent in parents:
parent_id = parent["from"]["id"]
parent_type = parent["from"]["entityType"]
if parent_id not in visited:
ancestors.append({
"id": parent_id,
"type": parent_type
})
queue.append((parent_id, parent_type))async def build_and_save_parent_ids(self, device_id: str) -> dict:
"""
Tính parentIds và lưu vào device attributes.
Gọi khi provision hoặc khi hierarchy thay đổi.
"""
ancestors = await self.get_all_ancestors(device_id, "DEVICE")import json
await self.tb.save_server_attributes(
entity_type="DEVICE",
entity_id=device_id,
attributes={
"parentIds": json.dumps(parent_ids),
"parentEntityTypes": json.dumps(parent_types)
}
)
return {"parentIds": parent_ids, "parentEntityTypes": parent_types}
```- Bổ sung vào TBClient: query parent relations
async def get_parent_relations(self, to_id: str, to_type: str,
relation_type: str = "Contains") -> list[dict]:
token = await self._get_token()
url = f"{self.base_url}/api/relations/info"
resp = await self._client.get(
url,
params={"toId": to_id, "toType": to_type,
"relationType": relation_type, "direction": "FROM"},
headers={"X-Authorization": f"Bearer {token}"}
)
return resp.json() if resp.status_code == 200 else []
```
- Provision API endpoint
- app/api/provision_api.py
from fastapi import APIRouter
from app.core.hierarchy import HierarchyTraverser
from app.core.tb_client import TBClient
from app.core.redis_counter import RedisCounter
router = APIRouter()
@router.post("/provision/traverse")
async def provision_device(payload: dict):
device_id = payload["deviceId"]
- 1. Traverse và lưu parentIds về device
result = await traverser.build_and_save_parent_ids(device_id)
- 2. Tăng totalDevices và offlineDevices cho mỗi ancestor
parent_ids = result["parentIds"]
parent_types = result["parentEntityTypes"]
for parent_id in parent_ids:
entity_type = parent_types.get(parent_id, "ASSET")
await counter.increment(entity_type, parent_id, "totalDevices", 1)
await counter.increment(entity_type, parent_id, "offlineDevices", 1)- Reconcile Job (Đã sửa — dùng external scheduler)
```pythonThay đổi so với v1: TB CE không có built-in job scheduler chạy external logic.
Reconcile job chạy bên trong microservice, trigger bằng cron hoặc APScheduler.
- app/jobs/reconcile.py
import asyncio
from app.core.tb_client import TBClient
from app.core.redis_counter import RedisCounter
class ReconcileJob:
"""
Tính lại toàn bộ stats từ TB relations và device attributes.
Chạy mỗi 30 phút để sửa bất kỳ sai lệch nào.
"""
- 1. Lấy danh sách tất cả asset
assets = await self.tb.get_all_assets()
- 2. Đếm lại từ relation graph
devices = await self._get_all_devices_under(asset_id)
total = len(devices)
online = sum(1 for d in devices if d.get("isOnline") "true")
alarmed = sum(1 for d in devices if d.get("hasAlarm") "true")- 3. Ghi thẳng về TB (bỏ qua Redis để đảm bảo accuracy)
await self.tb.save_server_attributes(
entity_type=asset_type,
entity_id=asset_id,
attributes={
"totalDevices": total,
"onlineDevices": online,
"offlineDevices": total - online,
"alarmDevices": alarmed
}
)
- 4. Sync Redis để khớp với TB
for field, val in [("totalDevices", total), ("onlineDevices", online),
("offlineDevices", total - online), ("alarmDevices", alarmed)]:
key = f"stats:{asset_type}:{asset_id}:{field}"
await self.counter.redis.set(key, val)
async def _get_all_devices_under(self, asset_id: str) -> list[dict]:
# Lấy toàn bộ device thuộc asset này bằng cách scan parentIds
# Hoặc dùng TB's findByQuery API nếu có index
# Đây là operation nặng — chỉ chạy trong reconcile, không chạy runtime
pass
```- Cấu hình scheduler
- app/main.py
from fastapi import FastAPI
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from app.api import stats_api, provision_api
from app.jobs.reconcile import ReconcileJob
from app.jobs.write_back import write_back_loop
import asyncio
app = FastAPI()
app.include_router(stats_api.router, prefix="/stats")
app.include_router(provision_api.router, prefix="/provision")
scheduler = AsyncIOScheduler()
@app.on_event("startup")
async def startup():
# Write-back Redis → TB mỗi 5 giây
asyncio.create_task(write_back_loop())
- Reconcile toàn bộ mỗi 30 phút
job = ReconcileJob()
scheduler.add_job(job.run, "interval", minutes=30)
scheduler.start()
```
- Rule Chain — Script aggregation (Đã xóa, không còn dùng)
Xóa khỏi rule chain: Toàn bộ logic aggregation đã chuyển vào Statistics Microservice.
Rule chain chỉ còn:
1. Enrichment node (load attributes)
2. State change filter (skip nếu không có gì thay đổi)
3. Save Attributes (cập nhật isOnline/hasAlarm trên device)
4. REST API Call (gọi microservice)
- Dashboard Design (Không thay đổi — đã đúng)
Dashboard chỉ đọc server attributes. Không query relation runtime.
```mermaid
flowchart TD
Dashboard --> EntityAlias
EntityAlias --> Attributes
Attributes --> Table
```
- Hierarchy table widget — columns
| Tên cột | Attribute key |
| --------------- | ----------------- |
| Name | name (entity) |
| Total Devices | totalDevices |
| Online | onlineDevices |
| Offline | offlineDevices |
| Alarm | alarmDevices |
| Critical | criticalAlarms |
- Entity alias config
```
Filter: Relations query
Direction: FROM
Relation: Contains
Max level: 10
```
Chỉ dùng cho hiển thị trên dashboard. Không dùng cho runtime processing.
- Naming Convention
- Device attributes
| Key | Type | Mô tả |
| ---------------------- | --------------- | ------------------------------- |
| `parentIds` | JSON string | Array UUID các ancestor |
| `parentEntityTypes` | JSON string | Map UUID → entity type |
| `isOnline` | boolean | Trạng thái kết nối |
| `hasAlarm` | boolean | Có alarm active không |
| `system` | string | Tên hệ thống (vd: "ems") |
| `deviceType` | string | Loại thiết bị (vd: "power") |
- Asset attributes
| Key | Type | Mô tả |
| ------------------ | --------- | ------------------------------ |
| `totalDevices` | integer | Tổng số thiết bị con |
| `onlineDevices` | integer | Số thiết bị đang online |
| `offlineDevices` | integer | Số thiết bị đang offline |
| `alarmDevices` | integer | Số thiết bị có alarm active |
| `criticalAlarms` | integer | Số alarm Critical |
| `majorAlarms` | integer | Số alarm Major |
| `minorAlarms` | integer | Số alarm Minor |
| `warningAlarms` | integer | Số alarm Warning |
- Anti-patterns (Tránh tuyệt đối)
| Không làm | Lý do |
| ------------------------------------------------------- | ---------------------------------------------------- |
| Query relations trong rule chain mỗi event | Không scale, tạo tải lớn lên DB |
| Read-modify-write attribute trực tiếp trong rule chain | Race condition dưới tải cao |
| forEach parents trong script để save attributes | Script chỉ tạo metadata, không trigger N saves |
| Traverse hierarchy trong transformation script | Không thể đệ quy — rule chain không có loop node |
| Dùng telemetry để lưu stats | Không query được dưới dạng attribute trên dashboard |
| Dashboard query relations | Chậm, tạo tải mỗi lần load |
| Aggregate toàn bộ thường xuyên | Tốn tài nguyên, không real-time |
- Deployment Architecture
```
┌─────────────────────────────────────────────────────┐
│ Docker Compose │
│ │
│ ┌──────────────────┐ ┌──────────────────────┐ │
│ │ ThingsBoard CE │ │ Statistics Service │ │
│ │ :8080, :1883 │ │ FastAPI :8081 │ │
│ └──────────────────┘ └──────────┬─────────── ┘ │
│ │ │
│ ┌──────────────────┐ │ │
│ │ Redis │◄─────────────┘ │
│ │ :6379 │ │
│ └──────────────────┘ │
└─────────────────────────────────────────────────────┘
```
- docker-compose.yml (phần stats service)
stats-service:
build: ./stats_service
ports:
- "8081:8081"
environment:
TB_BASE_URL: http://thingsboard:8080
TB_USERNAME: tenant@example.com
TB_PASSWORD: ${TB_PASSWORD}
REDIS_URL: redis://redis:6379
API_KEY: ${STATS_API_KEY}
depends_on:
- thingsboard
- redis- Performance Analysis
- So sánh v1 vs v2
| Metrics | v1 (rule chain only) | v2 (với microservice) |
| -------------------------------- | --------------------- | ---------------------- |
| Relation query per event | 0 | 0 |
| Race condition risk | Cao (100k events) | Không có (Redis atomic) |
| Fan-out correctness | Không đảm bảo | Đảm bảo |
| Provision hierarchy support | Không có | Đầy đủ |
| Write latency to TB | Ngay lập tức | ≤5 giây (write-back) |
| Throughput (events/sec) | ~500-1k | ~5k-20k |
- Độ phức tạp
```
Mỗi event:
Rule chain: O(1)
Microservice: O(level_depth) — Redis INCR per parent
Write-back: O(dirty_entities) — batch 5 giây một lần
```
- Scale Estimation
| Số thiết bị | Đánh giá | Ghi chú |
| ------------- | ---------------- | ------------------------------------------- |
| 5k | Excellent | Rule chain + microservice single instance |
| 10k | Excellent | Không cần điều chỉnh |
| 50k | Good | Có thể cần scale Redis |
| 100k | Acceptable | Scale out write-back workers |
| 500k+ | Cần review | Cân nhắc Kafka thay REST webhook |
- Migration Strategy
Nếu device đã tồn tại và chưa có `parentIds`:
```
1. Gọi POST /provision/traverse cho từng device hiện có
2. Microservice tự tính parentIds và lưu về TB
3. Không cần thay đổi rule chain
4. Chạy reconcile job một lần để đồng bộ stats ban đầu
```
Nếu hierarchy thay đổi (di chuyển device sang line khác):
```
1. Gọi POST /provision/traverse với deviceId
2. Microservice tính lại parentIds mới
3. Cập nhật counters: trừ từ parents cũ, cộng vào parents mới
4. Reconcile job chạy định kỳ sẽ tự phát hiện sai lệch nếu có
```
- Future Improvements
Khi scale > 500k devices:
- Thay REST webhook bằng Kafka topic — Rule chain publish event, microservice consume
- Sharding Redis theo tenant để tránh hot key
- Read replica TB PostgreSQL cho reconcile job — không tạo tải DB chính
- Timeseries aggregation — lưu lịch sử stats theo giờ/ngày để vẽ trend chart
- Kiến trúc tổng kết
```mermaid
flowchart TD
Device --> ConnectEvent[CONNECT / DISCONNECT / ALARM]
ConnectEvent --> RuleChain[Rule Chain\nEnrich + Filter + Forward]
RuleChain --> MicroService[Statistics Microservice\nFan-out + Atomic]
MicroService --> Redis[Redis\nAtomic Counters]
Redis --> WriteBack[Write-back job\nmỗi 5 giây]
WriteBack --> AssetAttrs[Asset Server Attributes]
AssetAttrs --> Dashboard[Dashboard]
Provision[Provision Device] --> ProvisionAPI[/provision/traverse]
ProvisionAPI --> Traverse[Traverse Hierarchy]
Traverse --> SaveParentIds[Lưu parentIds về device]
SaveParentIds --> InitCounter[Init counters cho parents]CronJob[Cron mỗi 30 phút] --> Reconcile[Reconcile Job\nFull recalculate]
Reconcile --> AssetAttrs
```- Kết luận
Đây là kiến trúc hierarchy statistics hoàn chỉnh cho ThingsBoard CE v4.2.1, giải quyết tất cả các vấn đề của v1:
| Vấn đề v1 | Giải pháp v2 |
| ------------------------------ | ----------------------------------------- |
| Race condition aggregation | Redis atomic INCR/DECR |
| Fan-out không thực thi được | Microservice xử lý fan-out |
| Traverse hierarchy không có | HierarchyTraverser gọi TB REST API |
| Thiếu enrichment node | Bổ sung Originator Attributes node |
| Reconcile không rõ mechanism | APScheduler trong microservice |
| metadata.parentIds undefined | JSON.parse() + enrichment node đúng thứ tự |
Cho phép:
- Hierarchy động không giới hạn level
- Realtime stats (≤5 giây latency)
- Rule chain nhẹ — không aggregate
- Dashboard nhanh — chỉ đọc attributes
- Scale lớn với số liệu chính xác
Updated by T. Nguyen Van Thanh 7 months ago
- Attachments clipboard-202604241606-ihfjo.png clipboard-202604241606-ihfjo.png added
- Status changed from In Progress to Review
- % Done changed from 90 to 100
hoàn thành giai đoạn ghép các trường dữ liệu lên các device chứa các thông tin liên kết của device trong tree
Updated by D. Vu Minh Duc 4 months ago
- Status changed from Review to Closed