Gateway Function and Farm Automation MVP Design
Date: 2026-05-03
Status: Approved (conversation-level), pending file review gate
1. Goal
Thiết kế một mô hình domain và runtime flow để:
- quản lý
gateway functiontheo cách có thể mở rộng thành automation platform - tách rõ
hardware capabilityvớioperational enablement - chuẩn hóa mọi sensor, gateway, actuator thành các
endpointcó danh tính rõ ràng - cho phép tạo automation rule ở scope
farm - để backend trung tâm đánh giá rule và gửi lệnh điều khiển thiết bị
Use case mục tiêu:
- khi
DO < ngưỡng, backend tự động bậtmáy bơmđang được map vàooutputcụ thể của gateway - source và target có thể là các device khác nhau
- rule được phép cross-device, cross-pond nhưng không vượt ra ngoài cùng
farm
2. Current State
device.typehiện chỉ có các loại tổng quát nhưsensor,gateway,inverter,feeder- năng lực thiết bị đang được nhét chủ yếu vào
devices.capabilitieskiểu JSON - luồng control hiện tại của gateway đang hard-code theo
4 IO - UI control gateway và backend control API đang giả định command theo
io1..io4 - chưa có domain model riêng cho:
- hardware profile
- endpoint catalog
- endpoint enablement theo từng device instance
- automation rule và execution audit
- chưa có rule engine backend để map telemetry event sang control action
Điều này đủ cho monitoring/control đơn giản, nhưng chưa đủ vững cho mục tiêu Automation - Tự động hoá.
3. Decisions Already Locked In
Các quyết định đã được chốt trong buổi brainstorming:
Gateway functionđược quản lý theo mô hình hai lớp:device profile/modellà trần phần cứngdevice instancebật hoặc tắt phần được dùng thực tế
- Hệ thống cần cả:
functiontổng quát cho UI và phân quyềnendpointchi tiết cho automation runtime
- Automation được phép:
- cross-device
- cross-pond
- nhưng chỉ trong cùng
farm
- Endpoint phải hỗ trợ cả:
- tên kỹ thuật gốc như
gpio1 - alias nghiệp vụ như
pump_1
- tên kỹ thuật gốc như
- Alias nên có hai lớp:
- alias mặc định ở cấp device
- alias override theo context lắp đặt/vận hành
- Mô hình endpoint phải dùng chung cho mọi device có thể tham gia automation, không chỉ riêng gateway
- Rule engine phase đầu chạy ở
backend trung tâm, không chạy local trong gateway - Phase đầu là
Catalog + rule engine MVP, không làm full automation platform
4. Options Considered
Option A: JSON-first on devices.capabilities
Tiếp tục dùng devices.capabilities làm nơi lưu:
- function tổng quát
- endpoint chi tiết
- alias
- enable/disable
- binding cho automation
Pros
- nhanh triển khai
- ít migration
- tận dụng cấu trúc hiện có
Cons
- khó query và validate
- khó enforce tính nhất quán giữa profile, device instance, và rule
- rule engine phải đọc JSON blob động
- audit, UI builder, và safety check sẽ nhanh chóng rối
Option B (selected): Profile + Endpoint Catalog + Instance Overrides
Tách domain thành:
device typedevice profileprofile endpointdevice instance endpoint configautomation rule
Pros
- phản ánh đúng bài toán
hardware ceilingvàoperational enablement - endpoint model dùng chung cho sensor, gateway, actuator
- backend rule engine có contract rõ ràng để evaluate và phát lệnh
- UI, permission, audit, và testing đều có ranh giới rõ
Cons
- cần thêm thực thể và migration mới
- cần thiết kế cẩn thận để không over-engineer MVP
Option C: Full automation platform from day one
Làm luôn:
- rule graph phức tạp
- conflict engine
- scheduler
- simulation/replay
- distributed execution
Pros
- tầm nhìn dài hạn đầy đủ
Cons
- vượt quá scope phase đầu
- chậm ra giá trị thực
- rủi ro platform work lớn hơn lợi ích trước mắt
5. Selected Design
Chọn Option B: tách profile, endpoint catalog, instance endpoint config, và farm-scoped automation rule.
Nguyên tắc cốt lõi:
device typechỉ là lớp phân loại tổng quátdevice profilelà nguồn sự thật cho khả năng phần cứng tối đadevice instancequyết định endpoint nào đang được bật thậtautomation rulechỉ làm việc vớiendpoint identityổn địnhaliaschỉ phục vụ con người, không được dùng làm khóa kỹ thuật cho execution engine
6. Domain Architecture
6.1. Device Type
Lớp phân loại cấp product như:
gatewaysensorfeederpump_controller
Mục đích:
- filter
- search
- navigation
- nhóm quyền/UI tổng quát
Không dùng device type để chứa logic endpoint chi tiết.
6.2. Device Profile
Device profile đại diện cho model hoặc family phần cứng.
Ví dụ:
gateway-4do-2di-v1sensor-do-rs485-v1pump-relay-2ch-v1
Profile mô tả:
- loại thiết bị tổng quát
- function tổng quát được hỗ trợ như
monitoring,control - endpoint kỹ thuật tối đa mà phần cứng có thể expose
- protocol/binding cần để map sang telemetry hoặc command thực
Đây là lớp trả lời câu hỏi: thiết bị này tối đa làm được gì.
6.3. Profile Endpoint
Mỗi profile endpoint là một điểm tham gia automation chuẩn hóa.
Ví dụ:
telemetry.dotelemetry.phtelemetry.temperatureoutput.gpio1output.gpio2input.di1command.start
Mỗi endpoint có metadata chuẩn:
direction:read,write,read_writedataType:number,boolean,enumfunctionKey: ví dụmonitoring,controldefaultLabel: ví dụDO,GPIO 1unit: ví dụmg/L,pHtransportType: ví dụmqtt_telemetry,mqtt_attribute,rpctransportBinding: field hoặc command key thật ở tầng protocolconstraints: min/max/allowed values hoặc metadata tương tự
Endpoint ID là danh tính kỹ thuật ổn định. Binding là lớp map xuống firmware hoặc MQTT payload thật.
6.4. Device Instance Endpoint Config
Khi tạo một device từ profile, hệ thống phải materialize ra cấu hình endpoint ở cấp instance.
Lớp này quyết định:
- endpoint nào đang
enabled - endpoint nào đang được phép
write - alias kỹ thuật mặc định và alias nghiệp vụ
- metadata vận hành hoặc override theo ngữ cảnh lắp đặt
Đây là lớp hiện thực hóa quyết định:
- profile là
hardware ceiling - instance là
operational enablement
6.5. Automation Rule
Rule không tham chiếu trực tiếp device.type = gateway hay text thô như gpio1.
Rule luôn tham chiếu:
source endpointtarget endpointfarmIdconditionaction
Ví dụ:
- source:
sensor-1.telemetry.do - condition:
< 4.5 - target:
gateway-7.output.gpio1 - target alias hiển thị:
pump_1
Rule engine chỉ chạy bằng endpoint identity. Alias chỉ dùng cho UI, authoring, và audit.
7. Data Model
7.1. device_types
Catalog nhẹ cho loại thiết bị tổng quát.
Field chính:
idcodenameisActive
Ví dụ dữ liệu:
gatewaysensorfeederpump_controller
7.2. device_profiles
Đại diện cho model hoặc family phần cứng.
Field chính:
idcodenamedeviceTypeIdmanufacturermodelfirmwareFamilysupportedFunctionsisActive
7.3. device_profile_endpoints
Catalog endpoint chuẩn của một profile.
Field chính:
iddeviceProfileIdkeydirectiondataTypefunctionKeydefaultLabelunittransportTypetransportBindingconstraintsdisplayOrderisActive
Ví dụ:
telemetry.dooutput.gpio1output.gpio2
7.4. device_instance_endpoints
Bản cấu hình endpoint ở cấp device cụ thể.
Field chính:
iddeviceIdprofileEndpointIdisEnabledtechnicalLabelbusinessAliasfarmContextAliasisWritablemetadata
Ràng buộc đề xuất cho MVP:
businessAliasunique trong phạm videviceIdfarmContextAliaskhông bắt buộc unique toàn farm ở phase 1- không cho bind endpoint từ profile khác sang device hiện tại
7.5. devices
Giữ devices là asset gốc nhưng thêm deviceProfileId.
Quan hệ:
devices.deviceTypetiếp tục phục vụ filter nhanh hoặc reportingdevices.deviceProfileIdlà nguồn sự thật cho endpoint catalog- khi tạo device từ profile, hệ thống sinh
device_instance_endpoints
7.6. automation_rules
Rule ở scope farm.
Field chính:
idorganizationIdfarmIdnamedescriptionstatus:draft,active,paused,archivedtriggerModecooldownSecondscreatedByupdatedBycreatedAtupdatedAt
MVP chỉ cần triggerMode = event_driven.
7.7. automation_rule_conditions
Điều kiện của rule.
Field chính:
idruleIdsourceDeviceEndpointIdoperatorthresholdValuesequenceOrder
MVP chỉ cần:
- một condition chính cho mỗi rule
- operator đơn giản như
<,<=,>,>=,=,!=
7.8. automation_rule_actions
Action mà rule sẽ thực hiện.
Field chính:
idruleIdtargetDeviceEndpointIdactionTypetargetValuesequenceOrder
MVP chỉ cần actionType = set_value.
7.9. automation_rule_executions
Audit runtime của rule engine.
Field chính:
idruleIdtriggeredAtsourceTelemetryPayloadevaluatedConditionSnapshotactionRequestactionResultstatus:triggered,skipped,sent,succeeded,failedfailureReason
8. Runtime Flow
8.1. Telemetry Ingestion
Device gửi telemetry, attribute, hoặc status lên backend qua MQTT hoặc cơ chế tương tự.
Backend sẽ:
- resolve
devicetừ serial number hoặc topic - resolve
device profile - resolve
device_instance_endpoints - dùng
transportBindingđể map payload field thật sang endpoint value chuẩn hóa
Ví dụ:
- firmware gửi
{ "do": 3.8 } - backend map thành event cho endpoint
telemetry.do = 3.8
8.2. Endpoint Event Normalization
Rule engine không nên đọc payload thô trực tiếp.
Hệ thống tạo một endpoint event logic-level gồm:
deviceIddeviceInstanceEndpointIdfarmIdtimestampvaluerawPayloadRefhoặc snapshot
Đây là đầu vào chuẩn cho evaluation engine.
8.3. Rule Selection
Engine chỉ lấy:
- rule có
status = active - rule có
farmId = sourceEvent.farmId
Kết quả:
- source và target được phép khác device hoặc khác pond
- nhưng không bao giờ vượt ra ngoài cùng
farm
8.4. Condition Evaluation
Engine chỉ match những condition có:
sourceDeviceEndpointId = endpoint event.deviceInstanceEndpointId
Sau đó evaluate operator đơn giản:
<<=>>==!=
MVP chạy theo kiểu event-driven, nghĩa là event tới đâu evaluate rule liên quan tới endpoint đó tới đó.
8.5. Safety Gates Before Command Dispatch
Ngay cả khi condition đúng, backend vẫn phải kiểm tra:
- rule vẫn
active - target endpoint còn
isEnabled = true - target endpoint cho phép
write - target device vẫn thuộc cùng
farm - target device không ở
maintenance - target device không ở
retired - rule đang ngoài
cooldownSeconds
Nếu fail ở bước này:
- không gửi lệnh
- vẫn ghi execution audit với trạng thái
skippedhoặcfailed
8.6. Command Dispatch
Nếu pass safety gate, backend build command từ transportBinding.
Ví dụ:
- target endpoint là
output.gpio1 - binding transform action thành payload RPC
{ "io1": true }
Execution engine không phụ thuộc vào alias pump_1 hay tên UI khác. Nó chỉ biết endpoint nào cần set value nào.
8.7. Execution Audit
Mỗi lần evaluate và phát lệnh phải ghi log vào automation_rule_executions, kể cả khi skip hoặc fail.
Audit tối thiểu phải trả lời được:
- rule nào chạy
- telemetry nào kích hoạt
- condition snapshot lúc evaluate là gì
- command nào đã build
- kết quả gửi lệnh ra sao
9. Validation Rules
9.1. Catalog Validation
Khi tạo hoặc sửa device profile và profile endpoint, hệ thống phải chặn:
- trùng
endpoint keytrong cùng profile - endpoint
writenhưng thiếu binding để gửi command dataTypekhông khớp với ràng buộc hoặc binding- profile khai báo
controlnhưng không có endpoint writable nào - binding kỹ thuật mơ hồ, không xác định được field thật
9.2. Device Instance Validation
Khi materialize hoặc cập nhật device_instance_endpoints, hệ thống phải chặn:
- enable endpoint không tồn tại trong profile
- alias trùng nhau trong cùng device
- endpoint read-only nhưng bị mở writable trái phép
- device thuộc profile A nhưng cố bind endpoint từ profile B
9.3. Rule Authoring Validation
Khi tạo rule, backend phải kiểm tra:
- rule có
farmId - source endpoint thuộc device trong đúng farm đó
- target endpoint cũng thuộc đúng farm đó
- source endpoint phải
readđược - target endpoint phải
writeđược - source và target đều đang
isEnabled = true - target device không
retired - operator phải hợp lệ với
dataType targetValuephải hợp lệ vớidataType
Ví dụ:
- endpoint boolean không được dùng operator kiểu
< 4.5 - GPIO boolean chỉ nhận
truehoặcfalse
10. Error Handling and Safety Constraints
10.1. Runtime Error Classes
Tôi đề xuất chia lỗi thành ba nhóm:
Configuration errors- sai profile
- sai endpoint config
- sai rule config
- xử lý bằng cách chặn ngay ở create/update API
Runtime skip- rule đúng nhưng không nên bắn lệnh
- ví dụ target đang maintenance
- xử lý bằng log
skipped
Execution failure- đã quyết định gửi lệnh nhưng command timeout hoặc publish thất bại
- xử lý bằng log
failed
10.2. Idempotency and Anti-Flapping
MVP chưa cần conflict engine phức tạp, nhưng cần ít nhất:
cooldownSecondstheo rule- không gửi lại cùng một command nếu target state đã bằng target value và còn trong cooldown
Debounce hoặc hysteresis phức tạp có thể để phase sau, trừ khi test thực tế cho thấy telemetry nhiễu là vấn đề lớn ngay từ đầu.
10.3. Permission Boundary
Khuyến nghị permission cho MVP:
- Super Admin quản lý:
device typedevice profileprofile endpointsystem device endpoint configuration
- Admin hoặc operator có scope phù hợp quản lý:
automation rulescủa farm
- user không có quyền catalog thì không được sửa
transportBindinghoặc metadata kỹ thuật
11. API Shape
11.1. Catalog APIs
Dành cho platform hoặc Super Admin:
GET /device-typesGET /device-profilesPOST /device-profilesGET /device-profiles/:id/endpointsPOST /device-profiles/:id/endpoints
11.2. Device Endpoint Configuration APIs
Dành cho Super Admin:
GET /system/devices/:id/endpointsPUT /system/devices/:id/endpoints/:endpointId
Use case:
- bật hoặc tắt endpoint
- sửa alias
- override metadata
11.3. Automation APIs
Dành cho farm automation:
GET /automation/rules?farmId=...POST /automation/rulesPUT /automation/rules/:idPOST /automation/rules/:id/activatePOST /automation/rules/:id/pauseGET /automation/rules/:id/executions
Contract MVP nên giữ explicit:
- một source endpoint
- một operator
- một threshold
- một target endpoint
- một target value
12. UI Shape
12.1. Device Profile Management
Dành cho Super Admin.
Cho phép:
- tạo profile
- khai báo supported functions
- định nghĩa endpoint catalog
- xem binding kỹ thuật của từng endpoint
12.2. System Device Endpoint Configuration
Dành cho Super Admin khi xem một device cụ thể.
Cho phép:
- xem các endpoint materialize từ profile
- bật hoặc tắt endpoint
- gán alias mặc định như
pump_1 - override label theo ngữ cảnh triển khai nếu cần
12.3. Farm Automation Rules
Dành cho operator ở farm.
Flow tạo rule nên có hướng dẫn rõ:
- chọn source device
- chọn source endpoint readable
- chọn operator và threshold
- chọn target device trong cùng farm
- chọn target endpoint writable
- chọn target value
- chọn cooldown
- review summary trước khi activate
UI nên ưu tiên alias nghiệp vụ, nhưng vẫn phải cho phép truy ngược về endpoint kỹ thuật khi debug.
13. Testing Strategy
13.1. Domain and Unit Tests
- validate endpoint catalog
- validate operator theo
dataType - transform action thành payload MQTT hoặc RPC từ
transportBinding - cooldown và skip logic
13.2. Service Tests
- materialize
device_instance_endpointskhi tạo device từ profile - evaluate rule từ source event
- reject target khác farm
- skip target đang maintenance hoặc endpoint bị disable
13.3. Integration Tests
- telemetry vào backend
- map thành endpoint event
- evaluate đúng rule
- tạo execution log
- gửi command đúng binding
13.4. Permission Tests
- chỉ Super Admin sửa catalog
- chỉ actor đúng scope mới tạo hoặc activate rule
- user không đúng quyền không sửa binding kỹ thuật
14. Acceptance Criteria
- Hệ thống có thể mô hình hóa
device profiletách biệt khỏidevice instance. - Một
device profilecó thể định nghĩa nhiều endpoint chuẩn hóa cho monitoring và control. - Một
device instancecó thể bật hoặc tắt từng endpoint mà không vượt quá trần phần cứng của profile. - Endpoint hỗ trợ cả danh tính kỹ thuật ổn định và alias nghiệp vụ cho UI.
- Automation rule ở scope
farmcó thể dùng source và target thuộc các device khác nhau trong cùng farm. - Backend có thể map telemetry thực sang endpoint event chuẩn hóa.
- Backend có thể evaluate một rule đơn giản kiểu
source endpoint < threshold. - Backend có thể build command từ target endpoint binding và gửi lệnh control tương ứng.
- Mỗi lần rule evaluate hoặc dispatch đều có execution audit đủ để debug.
- Super Admin quản lý catalog, còn operator ở farm quản lý rule, theo boundary permission rõ ràng.
15. Out of Scope
- AND/OR condition tree phức tạp
- multi-step workflow hoặc chaining rule
- scheduler hoặc cron automation
- local execution ở gateway
- conflict resolution engine nâng cao
- simulation hoặc replay UI đầy đủ
- cross-farm hoặc organization-wide automation
- dùng alias như định danh kỹ thuật cho runtime
16. Risks and Mitigations
Risk 1: Over-modeling too early
Nếu domain quá rộng, MVP sẽ chậm ra giá trị.
Mitigation
- giữ rule engine MVP ở mức single-condition, single-action
- chỉ thêm các thực thể thật sự cần cho catalog và execution audit
Risk 2: Binding mismatch between profile and firmware
Profile endpoint có thể khai báo binding sai so với payload firmware thật.
Mitigation
- tách
transportBindingthành contract rõ - cover bằng integration tests từ telemetry/control flow
Risk 3: Unsafe automation execution
Rule cấu hình sai có thể bật nhầm thiết bị thật.
Mitigation
- validate rule theo
dataType, direction, scope - runtime safety gates trước khi dispatch
- execution audit đầy đủ
Risk 4: Alias confusion
Nếu runtime dựa vào alias, rename alias có thể làm gãy automation.
Mitigation
- runtime chỉ tham chiếu endpoint identity
- alias chỉ phục vụ UI, authoring, và audit
17. Recommended Implementation Sequence
- Thêm catalog cho
device type,device profile,profile endpoint. - Mở rộng
devicesđể gắndeviceProfileId. - Materialize
device_instance_endpointskhi tạo device. - Thêm API và UI để quản lý endpoint config ở cấp device.
- Thêm domain
automation rule,condition,action,execution. - Thêm backend engine để map telemetry thành endpoint event.
- Evaluate rule active trong cùng farm và dispatch command.
- Ghi execution audit và hiển thị rule history cơ bản.