Gateway Peripherals and Linkage
Development Preview
This page is based on the source code at commit b1a16cbc and the project peripheral system design document. The PeripheralManager and PeriphExecEngine code already exists and the API routes are registered; real hardware access depends on build options and backend implementations (libgpiod / Linux IIO / simulated backend), and the x86 development environment uses the simulated backend by default.
1. Overview
Industrial gateway models differ greatly in hardware configuration (DI 4~16 channels, DO 4~8 channels, AI 2~4 channels, and so on), so pin functions cannot be hard-coded. The peripheral system maps physical pins to virtual peripheral objects, defines them dynamically through configuration files and the Web/API, and the execution rule engine implements "trigger → action" automation linkage (for example, door contact opens → light on, temperature over limit → start fan).
Two core modules:
- PeripheralManager (peripheral configuration center): the unified entry for peripheral CRUD, hardware initialization/release, pin conflict detection, runtime state, and reads/writes.
- PeriphExecEngine (peripheral execution rule engine): trigger detection, rule matching, action orchestration and execution, result recording, and MQTT reporting.
Key constraint: the rule engine never touches hardware backends directly; all reads and writes go through PeripheralManager, ensuring that pin conflict detection, state synchronization, and log auditing follow a single path.
2. Peripheral Type System
String type codes are used (more readable for field engineers), focusing on 7 classes of industrial I/O:
| Type | Typical channels | Signal characteristics | Direction | Typical loads |
|---|---|---|---|---|
DI | 4~16 | Optocoupler-isolated, 12/24V dry/wet contacts | Input | Door contacts, smoke detectors, buttons, limit switches |
DO | 4~8 | Relay or MOSFET, normally open/normally closed | Output | Alarms, indicator lights, solenoid valves |
AI | 2~4 | 4-20mA / 0-10V standard signals | Input | Temperature/pressure/level transmitters |
AO | 1~2 | 4-20mA / 0-10V standard signals | Output | VFDs, control valves |
LED | 4 | Lit by low/high level | Output | Power/running/network/fault indication |
BUZZER | 1 | Active/passive buzzer | Output | Local audible/visual alarm |
WATCHDOG | 1 | Requires periodic feed pulses | Output | Hardware watchdog chip |
Peripheral runtime state machine: DISABLED(0) → ENABLED(1) → INITIALIZED(2) → RUNNING(3), with ERROR(4) for fault conditions.
3. Peripheral Configuration Parameters
Each peripheral consists of id, name, type, enabled, channel, pins (the physical pin array), and params (type-specific parameters). Key params for each type:
3.1 DI Digital Input
| Parameter | Default | Description |
|---|---|---|
pullUp | true | Internal pull-up |
activeLow | false | Active-low (set true when the optocoupler output is inverted) |
debounceMs | 30 | Software debounce time (a change is confirmed only after two consecutive identical samples) |
reportOnChange | true | Report on state change |
triggerEdge | both | Trigger edge: rising / falling / both |
3.2 DO Digital Output
| Parameter | Default | Description |
|---|---|---|
initialState | 0 | Initial level (0=open / 1=closed) |
activeLow | false | Active-low drive (relay modules commonly trigger on low level) |
outputType | relay | Output type: relay / mosfet |
pulseMs | 0 | Pulse output duration (0=continuous, >0=auto-revert, for momentary solenoid valve jog) |
3.3 AI Analog Input
| Parameter | Default | Description |
|---|---|---|
signalType | 4-20mA | Signal type: 4-20mA / 0-10V / 0-20mA / 0-5V |
rawMin / rawMax | 0 / 4095 | ADC raw value range |
engMin / engMax | 0 / 100 | Engineering value range (linear mapping) |
unit | "" | Engineering unit (°C / MPa / m …) |
sampleIntervalMs | 1000 | Sampling interval |
deadband | 0.0 | Deadband (report only when the change exceeds the deadband, suppressing jitter) |
wireFaultDetect | false | Wire-break detection (4-20mA below 3.6mA is treated as a broken wire) |
Engineering-value linear mapping: eng = engMin + (raw - rawMin) / (rawMax - rawMin) × (engMax - engMin).
3.4 AO Analog Output
| Parameter | Default | Description |
|---|---|---|
signalType | 4-20mA | Signal type |
engMin / engMax | 0 / 100 | Engineering value range |
defaultValue | engMin | Default output value at power-on |
slewRateMs | 0 | Output ramp time (prevents valve shock) |
3.5 LED / BUZZER / WATCHDOG
- LED:
role(powerstays on at power-on /runningheartbeat 1Hz blink /networkreflects network connectivity /faultdriven by system faults). - BUZZER:
activeLevelactive level,buzzerType(active/passive),defaultPattern(off/on/beepthree short beeps /alarmrapid continuous tone). - WATCHDOG:
feedIntervalMs(feed interval; must be shorter than the hardware watchdog timeout),feedPulseMs,mode(toggle/pulsefixed pulse). When the main thread hangs, the hardware watchdog times out and automatically resets the gateway — a key means of "self-recovery from crashes" in industrial sites.
3.6 Configuration Example
{
"id": "ai_temp", "name": "Boiler temperature transmitter", "type": "AI",
"enabled": true, "channel": 0, "pins": [0],
"params": { "signalType": "4-20mA", "rawMin": 0, "rawMax": 4095,
"engMin": 0, "engMax": 200, "unit": "°C",
"sampleIntervalMs": 1000, "deadband": 0.5, "wireFaultDetect": true }
}Peripheral configuration is stored in config/peripherals.json; writes are atomic ("write to .tmp first, then rename"). The file contains version (format version) and _templates (peripheral templates for quickly filling parameters during batch deployment).
4. Peripheral Execution Rule Engine
A rule consists of triggers (OR logic) and actions (executed in order); configuration is stored in config/periph_exec.json.
4.1 Trigger Types
| Type | Input source | Industrial scenario |
|---|---|---|
| Platform trigger (0) | MQTT / cloud commands | Remotely switching DO, parameter delivery |
| Timer trigger (1) | Local clock (interval / fixed time of day) | Periodic reporting, scheduled pump on/off |
| Event trigger (4) | DI changes, system events | Door contact opens → light on, smoke detector → alarm |
| Polling trigger (5) | Actively reads AI/Modbus (checked per pollIntervalMs) | Temperature over limit → start fan |
Comparison operators 0~9: EQ / NE / GT / LT / GE / LE / IN_RANGE / OUT_RANGE / CONTAINS / NOT_CONTAINS. DI changes automatically publish a ds:<periphId> event; when rule execution completes, a mc:<ruleId>:success/failed event is published, supporting chained rule linkage.
4.2 Action Types
| Type | Name | Description |
|---|---|---|
| 0/1/2/3 | Set DO high/low/toggle/blink | Blink parameter "count,intervalMs" |
| 4 | Set AO value | Engineering-value output |
| 5 | LED control | "on" / "off" / "blink" |
| 6 | Buzzer | "off" / "on" / "beep" / "alarm" |
| 10 | Send command | MQTT report; $value is the placeholder for the trigger value |
| 15 | Command script | Multi-line sequential execution of PERIPH / DELAY / LOG / MQTT |
| 21/22/23 | Trigger event / enable rule / disable rule | Rule linkage |
| 30 | System reboot | High-impact action; recommended only for platform triggers |
4.3 Rule Example
{
"id": "exec_1717392000",
"name": "Smoke alarm linkage",
"enabled": true,
"execMode": 0,
"triggers": [
{ "triggerType": 4, "triggerPeriphId": "di_smoke",
"operatorType": 0, "compareValue": "1", "eventId": "ds:di_smoke" }
],
"actions": [
{ "actionType": 0, "targetPeriphId": "do_alarm" },
{ "actionType": 6, "targetPeriphId": "buzzer_alarm", "actionValue": "alarm" },
{ "actionType": 10, "actionValue": "{\"alarm\":\"smoke\"}" }
],
"reportAfterExec": true
}execMode: 0=async (default; the submitting thread does not block scheduling), 1=sync (delay between actions per syncDelayMs; rules containing a system reboot are forced to sync). Repeated triggers are skipped while the same rule is running (reentrancy prevention).
5. Safety Conventions and Reliability Design
- Factory-safe defaults: peripherals and rules default to
enabled: falseand will not act automatically in an unknown wiring environment. - Disabled by default after import: batch-imported peripherals and rules are forcibly disabled and must be enabled one by one after manual confirmation.
- Pin conflict detection: the same pin cannot be occupied by two enabled peripherals; disabled peripherals may keep their pin definitions and are re-validated when re-enabled.
- Deletion protection: deleting a peripheral referenced by rules is rejected, with a prompt to remove the references first.
- Automatic backup before restore: the current state is snapshotted before restoring a backup, ensuring rollback is possible.
- Execution auditing: rule execution results are kept in a ring buffer (latest 100 entries) and logged.
- High-impact action restriction: actions involving relays/solenoid valves/reboot must first be manually verified with a "run once" before being enabled.
6. Configuration Management and Batch Deployment
Peripherals and rules support full export/import. A typical batch deployment flow:
- Configure peripherals and rules on the first gateway, then enable and verify them one by one.
- Export all configuration (
GET /api/system/configand each module's export endpoints). - Import into each gateway of the same model; peripherals/rules load after restart (disabled by default).
- Enable and verify I/O one by one on site; restore the backup to roll back if anything goes wrong.
7. API Entry Points
The full endpoint tables for peripheral management (9 endpoints) and peripheral execution rules (9 endpoints) are in Sections 12 and 13 of API.
8. Implementation Status
- The PeripheralManager / PeriphExecEngine code exists and its routes are registered; the data model and trigger/action semantics of peripherals and rules stay consistent with FastBee-Arduino (the ESP32 firmware) to keep the ecosystem unified.
- Hardware backends:
LibgpiodBackend(digital I/O, real gateways),IioBackend(analog I/O, Linux IIO subsystem),SimulatedHwBackend(development/CI/unit tests; can inject DI/AI states and assert DO/AO outputs). - Platform triggers depend on the MQTT reverse-control link, which is not yet connected (see Section 8 of the Overview); timer/event/polling triggers are local logic.
- The earlier channel-style
GpioManager(/api/gpio/*) remains available; peripheral management will gradually become the single authoritative configuration source.

