Rule Engine

Xây dựng luồng xử lý sự kiện tự động với Rule Chain và hơn 90 loại node.

Rule Engine

Rule Engine là hệ thống xử lý sự kiện theo luồng (flow-based processing). Mọi dữ liệu từ thiết bị đều đi qua Rule Engine trước khi được lưu trữ hoặc kích hoạt hành động.

Khái niệm

Message (Thông điệp)

Đơn vị xử lý trong Rule Engine. Mỗi message gồm:

  • Originator — Thực thể nguồn (device, asset...)
  • Type — Loại message (POST_TELEMETRY, POST_ATTRIBUTES, RPC...)
  • Payload — Nội dung JSON
  • Metadata — Thông tin bổ sung (deviceName, deviceType, ts...)

Rule Chain

Đồ thị xử lý, gồm nhiều Rule Node kết nối nhau. Mỗi tenant có một Root Rule Chain mặc định.

Rule Node

Một bước xử lý. Nhận message → xử lý → chuyển tiếp qua relation có tên (Success, Failure, True, False, Custom...).

Relation

Cạnh nối giữa các node, mang nhãn kết quả. Node tiếp theo chỉ nhận message nếu relation label khớp.

Luồng xử lý mặc định

Thiết bị gửi telemetry ↓ [Rule Chain Input] ↓ [Message Type Filter] → True → [Save Telemetry] → [Create Alarm?] ↓ False (discard)

Message Types

TypeKhi nào
POST_TELEMETRY_REQUESTThiết bị gửi telemetry
POST_ATTRIBUTES_REQUESTThiết bị gửi attributes
TO_SERVER_RPC_REQUESTThiết bị gửi RPC request
RPC_CALL_FROM_SERVER_TO_DEVICEServer gửi lệnh đến thiết bị
CONNECT_EVENTThiết bị kết nối
DISCONNECT_EVENTThiết bị ngắt kết nối
ACTIVITY_EVENTThiết bị active
INACTIVITY_EVENTThiết bị inactive

Các loại Node

Filter Nodes — Lọc message

NodeMô tả
Message Type FilterLọc theo type (POST_TELEMETRY...)
Script FilterLọc bằng JavaScript expression
Threshold FilterSo sánh giá trị số với ngưỡng
GPS Geofencing FilterLọc theo vị trí địa lý
Check RelationKiểm tra quan hệ giữa các thực thể
Originator Type FilterLọc theo loại originator

Transform Nodes — Biến đổi message

NodeMô tả
Transform Message (Script)Biến đổi payload bằng JavaScript
Rename KeysĐổi tên key trong JSON
Copy KeysSao chép key từ payload sang metadata
Delete KeysXóa key khỏi payload
Math NodeTính toán (cộng, nhân, sqrt...)
Change OriginatorĐổi entity nguồn của message
To EmailChuyển message thành email template

Enrichment Nodes — Làm giàu dữ liệu

NodeMô tả
Originator AttributesThêm attributes của originator vào metadata
Originator FieldsThêm fields (name, type) vào metadata
Customer AttributesThêm attributes của customer
Tenant AttributesThêm attributes của tenant
Related AttributesThêm attributes từ entity liên quan
Get TelemetryThêm telemetry vào metadata
Device ProfileThêm thông tin device profile

Action Nodes — Thực hiện hành động

NodeMô tả
Save TelemetryLưu telemetry vào database
Save AttributesLưu attributes
Create/Clear AlarmTạo hoặc xóa alarm
Send EmailGửi email qua SMTP
Send SMSGửi SMS
Send NotificationGửi thông báo hệ thống
REST API CallGọi API bên ngoài
MQTT PublishPublish đến MQTT broker ngoài
Kafka PublishGửi message đến Kafka
RabbitMQ PublishGửi đến RabbitMQ
AWS SQS/SNS/LambdaTích hợp AWS
GCP Pub/SubTích hợp Google Cloud
LogGhi log để debug
Send RPC ReplyPhản hồi RPC từ thiết bị
Assign to CustomerGiao thiết bị cho customer

Flow Nodes — Điều hướng luồng

NodeMô tả
Rule Chain InputĐiểm vào của rule chain
Rule Chain OutputChuyển sang rule chain khác
Message Type SwitchPhân nhánh theo message type
Device Type SwitchPhân nhánh theo device type
DelayTrì hoãn xử lý
CheckpointLưu trạng thái xử lý
SyncĐồng bộ nhiều luồng song song

Viết Script trong Node

Script dùng JavaScript (TBEL) — biến thể thiết kế cho IoT:

Script Filter

// Chỉ xử lý khi temperature > 35 return msg.temperature !== undefined && msg.temperature > 35;

Transform Message

// Thêm trường tính toán, đổi tên var newMsg = { temp_celsius: msg.temperature, temp_fahrenheit: msg.temperature * 9/5 + 32, humidity: msg.humidity, ts: metadata.ts }; return { msg: newMsg, metadata: metadata, msgType: msgType };

Enrichment Script

// Truy cập attributes từ metadata var threshold = parseFloat(metadata.maxTemperatureThreshold); if (msg.temperature > threshold) { metadata.alertLevel = 'HIGH'; } return { msg: msg, metadata: metadata, msgType: msgType };

Ví dụ Rule Chain hoàn chỉnh

Yêu cầu: Khi nhiệt độ > 35°C kéo dài 5 phút → tạo alarm + gửi email

[Message Type Filter] type == POST_TELEMETRY_REQUEST │ True ▼ [Script Filter] msg.temperature !== undefined │ True ▼ [Threshold Filter] temperature > 35 │ True ▼ [Create Alarm] type: "High Temperature" severity: CRITICAL duration: 5 phút │ Created ▼ [Originator Attributes] server scope: contactEmail │ Success ▼ [To Email] to: ${metadata.contactEmail} subject: Cảnh báo nhiệt độ cao! body: Thiết bị ${metadata.deviceName}: ${msg.temperature}°C │ Success ▼ [Send Email]

Quản lý Rule Chain qua API

# Lấy danh sách GET /api/ruleChains?pageSize=20&page=0 Authorization: Bearer {JWT} # Tạo rule chain POST /api/ruleChain Authorization: Bearer {JWT} Content-Type: application/json { "name": "My Custom Chain", "type": "CORE" } # Lưu metadata (nodes + connections) POST /api/ruleChain/{ruleChainId}/metadata Authorization: Bearer {JWT}