Skip to content

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:

TypeTypical channelsSignal characteristicsDirectionTypical loads
DI4~16Optocoupler-isolated, 12/24V dry/wet contactsInputDoor contacts, smoke detectors, buttons, limit switches
DO4~8Relay or MOSFET, normally open/normally closedOutputAlarms, indicator lights, solenoid valves
AI2~44-20mA / 0-10V standard signalsInputTemperature/pressure/level transmitters
AO1~24-20mA / 0-10V standard signalsOutputVFDs, control valves
LED4Lit by low/high levelOutputPower/running/network/fault indication
BUZZER1Active/passive buzzerOutputLocal audible/visual alarm
WATCHDOG1Requires periodic feed pulsesOutputHardware 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 ​

ParameterDefaultDescription
pullUptrueInternal pull-up
activeLowfalseActive-low (set true when the optocoupler output is inverted)
debounceMs30Software debounce time (a change is confirmed only after two consecutive identical samples)
reportOnChangetrueReport on state change
triggerEdgebothTrigger edge: rising / falling / both

3.2 DO Digital Output ​

ParameterDefaultDescription
initialState0Initial level (0=open / 1=closed)
activeLowfalseActive-low drive (relay modules commonly trigger on low level)
outputTyperelayOutput type: relay / mosfet
pulseMs0Pulse output duration (0=continuous, >0=auto-revert, for momentary solenoid valve jog)

3.3 AI Analog Input ​

ParameterDefaultDescription
signalType4-20mASignal type: 4-20mA / 0-10V / 0-20mA / 0-5V
rawMin / rawMax0 / 4095ADC raw value range
engMin / engMax0 / 100Engineering value range (linear mapping)
unit""Engineering unit (°C / MPa / m …)
sampleIntervalMs1000Sampling interval
deadband0.0Deadband (report only when the change exceeds the deadband, suppressing jitter)
wireFaultDetectfalseWire-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 ​

ParameterDefaultDescription
signalType4-20mASignal type
engMin / engMax0 / 100Engineering value range
defaultValueengMinDefault output value at power-on
slewRateMs0Output ramp time (prevents valve shock)

3.5 LED / BUZZER / WATCHDOG ​

  • LED: role (power stays on at power-on / running heartbeat 1Hz blink / network reflects network connectivity / fault driven by system faults).
  • BUZZER: activeLevel active level, buzzerType (active / passive), defaultPattern (off / on / beep three short beeps / alarm rapid continuous tone).
  • WATCHDOG: feedIntervalMs (feed interval; must be shorter than the hardware watchdog timeout), feedPulseMs, mode (toggle / pulse fixed 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 ​

json
{
  "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 ​

TypeInput sourceIndustrial scenario
Platform trigger (0)MQTT / cloud commandsRemotely 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 eventsDoor 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 ​

TypeNameDescription
0/1/2/3Set DO high/low/toggle/blinkBlink parameter "count,intervalMs"
4Set AO valueEngineering-value output
5LED control"on" / "off" / "blink"
6Buzzer"off" / "on" / "beep" / "alarm"
10Send commandMQTT report; $value is the placeholder for the trigger value
15Command scriptMulti-line sequential execution of PERIPH / DELAY / LOG / MQTT
21/22/23Trigger event / enable rule / disable ruleRule linkage
30System rebootHigh-impact action; recommended only for platform triggers

4.3 Rule Example ​

json
{
  "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: false and 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:

  1. Configure peripherals and rules on the first gateway, then enable and verify them one by one.
  2. Export all configuration (GET /api/system/config and each module's export endpoints).
  3. Import into each gateway of the same model; peripherals/rules load after restart (disabled by default).
  4. 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.

FastBee | fastbee.cn