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 function theo cách có thể mở rộng thành automation platform
  • tách rõ hardware capability với operational enablement
  • chuẩn hóa mọi sensor, gateway, actuator thành các endpoint có 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ật máy bơm đang được map vào output cụ 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.type hiệ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.capabilities kiể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:

  1. Gateway function được quản lý theo mô hình hai lớp:
    • device profile/model là trần phần cứng
    • device instance bật hoặc tắt phần được dùng thực tế
  2. Hệ thống cần cả:
    • function tổng quát cho UI và phân quyền
    • endpoint chi tiết cho automation runtime
  3. Automation được phép:
    • cross-device
    • cross-pond
    • nhưng chỉ trong cùng farm
  4. Endpoint phải hỗ trợ cả:
    • tên kỹ thuật gốc như gpio1
    • alias nghiệp vụ như pump_1
  5. 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
  6. Mô hình endpoint phải dùng chung cho mọi device có thể tham gia automation, không chỉ riêng gateway
  7. Rule engine phase đầu chạy ở backend trung tâm, không chạy local trong gateway
  8. 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 type
  • device profile
  • profile endpoint
  • device instance endpoint config
  • automation rule

Pros

  • phản ánh đúng bài toán hardware ceilingoperational 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 type chỉ là lớp phân loại tổng quát
  • device profile là nguồn sự thật cho khả năng phần cứng tối đa
  • device instance quyết định endpoint nào đang được bật thật
  • automation rule chỉ làm việc với endpoint identity ổn định
  • alias chỉ 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ư:

  • gateway
  • sensor
  • feeder
  • pump_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-v1
  • sensor-do-rs485-v1
  • pump-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.do
  • telemetry.ph
  • telemetry.temperature
  • output.gpio1
  • output.gpio2
  • input.di1
  • command.start

Mỗi endpoint có metadata chuẩn:

  • direction: read, write, read_write
  • dataType: number, boolean, enum
  • functionKey: ví dụ monitoring, control
  • defaultLabel: ví dụ DO, GPIO 1
  • unit: ví dụ mg/L, pH
  • transportType: ví dụ mqtt_telemetry, mqtt_attribute, rpc
  • transportBinding: field hoặc command key thật ở tầng protocol
  • constraints: 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 endpoint
  • target endpoint
  • farmId
  • condition
  • action

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:

  • id
  • code
  • name
  • isActive

Ví dụ dữ liệu:

  • gateway
  • sensor
  • feeder
  • pump_controller

7.2. device_profiles

Đại diện cho model hoặc family phần cứng.

Field chính:

  • id
  • code
  • name
  • deviceTypeId
  • manufacturer
  • model
  • firmwareFamily
  • supportedFunctions
  • isActive

7.3. device_profile_endpoints

Catalog endpoint chuẩn của một profile.

Field chính:

  • id
  • deviceProfileId
  • key
  • direction
  • dataType
  • functionKey
  • defaultLabel
  • unit
  • transportType
  • transportBinding
  • constraints
  • displayOrder
  • isActive

Ví dụ:

  • telemetry.do
  • output.gpio1
  • output.gpio2

7.4. device_instance_endpoints

Bản cấu hình endpoint ở cấp device cụ thể.

Field chính:

  • id
  • deviceId
  • profileEndpointId
  • isEnabled
  • technicalLabel
  • businessAlias
  • farmContextAlias
  • isWritable
  • metadata

Ràng buộc đề xuất cho MVP:

  • businessAlias unique trong phạm vi deviceId
  • farmContextAlias khô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.deviceType tiếp tục phục vụ filter nhanh hoặc reporting
  • devices.deviceProfileId là 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:

  • id
  • organizationId
  • farmId
  • name
  • description
  • status: draft, active, paused, archived
  • triggerMode
  • cooldownSeconds
  • createdBy
  • updatedBy
  • createdAt
  • updatedAt

MVP chỉ cần triggerMode = event_driven.

7.7. automation_rule_conditions

Điều kiện của rule.

Field chính:

  • id
  • ruleId
  • sourceDeviceEndpointId
  • operator
  • thresholdValue
  • sequenceOrder

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:

  • id
  • ruleId
  • targetDeviceEndpointId
  • actionType
  • targetValue
  • sequenceOrder

MVP chỉ cần actionType = set_value.

7.9. automation_rule_executions

Audit runtime của rule engine.

Field chính:

  • id
  • ruleId
  • triggeredAt
  • sourceTelemetryPayload
  • evaluatedConditionSnapshot
  • actionRequest
  • actionResult
  • status: triggered, skipped, sent, succeeded, failed
  • failureReason

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ẽ:

  1. resolve device từ serial number hoặc topic
  2. resolve device profile
  3. resolve device_instance_endpoints
  4. 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:

  • deviceId
  • deviceInstanceEndpointId
  • farmId
  • timestamp
  • value
  • rawPayloadRef hoặ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 skipped hoặc failed

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 profileprofile endpoint, hệ thống phải chặn:

  • trùng endpoint key trong cùng profile
  • endpoint write nhưng thiếu binding để gửi command
  • dataType không khớp với ràng buộc hoặc binding
  • profile khai báo control như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
  • targetValue phải hợp lệ với dataType

Ví dụ:

  • endpoint boolean không được dùng operator kiểu < 4.5
  • GPIO boolean chỉ nhận true hoặc false

10. Error Handling and Safety Constraints

10.1. Runtime Error Classes

Tôi đề xuất chia lỗi thành ba nhóm:

  1. Configuration errors
    • sai profile
    • sai endpoint config
    • sai rule config
    • xử lý bằng cách chặn ngay ở create/update API
  2. 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
  3. 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:

  • cooldownSeconds theo 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 type
    • device profile
    • profile endpoint
    • system device endpoint configuration
  • Admin hoặc operator có scope phù hợp quản lý:
    • automation rules của farm
  • user không có quyền catalog thì không được sửa transportBinding hoặc metadata kỹ thuật

11. API Shape

11.1. Catalog APIs

Dành cho platform hoặc Super Admin:

  • GET /device-types
  • GET /device-profiles
  • POST /device-profiles
  • GET /device-profiles/:id/endpoints
  • POST /device-profiles/:id/endpoints

11.2. Device Endpoint Configuration APIs

Dành cho Super Admin:

  • GET /system/devices/:id/endpoints
  • PUT /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/rules
  • PUT /automation/rules/:id
  • POST /automation/rules/:id/activate
  • POST /automation/rules/:id/pause
  • GET /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õ:

  1. chọn source device
  2. chọn source endpoint readable
  3. chọn operator và threshold
  4. chọn target device trong cùng farm
  5. chọn target endpoint writable
  6. chọn target value
  7. chọn cooldown
  8. 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_endpoints khi 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

  1. Hệ thống có thể mô hình hóa device profile tách biệt khỏi device instance.
  2. Một device profile có thể định nghĩa nhiều endpoint chuẩn hóa cho monitoring và control.
  3. Một device instance có 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.
  4. Endpoint hỗ trợ cả danh tính kỹ thuật ổn định và alias nghiệp vụ cho UI.
  5. Automation rule ở scope farm có thể dùng source và target thuộc các device khác nhau trong cùng farm.
  6. Backend có thể map telemetry thực sang endpoint event chuẩn hóa.
  7. Backend có thể evaluate một rule đơn giản kiểu source endpoint < threshold.
  8. Backend có thể build command từ target endpoint binding và gửi lệnh control tương ứng.
  9. Mỗi lần rule evaluate hoặc dispatch đều có execution audit đủ để debug.
  10. 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 transportBinding thà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
  1. Thêm catalog cho device type, device profile, profile endpoint.
  2. Mở rộng devices để gắn deviceProfileId.
  3. Materialize device_instance_endpoints khi tạo device.
  4. Thêm API và UI để quản lý endpoint config ở cấp device.
  5. Thêm domain automation rule, condition, action, execution.
  6. Thêm backend engine để map telemetry thành endpoint event.
  7. Evaluate rule active trong cùng farm và dispatch command.
  8. Ghi execution audit và hiển thị rule history cơ bản.