Skip to content

Core Framework ​

This document describes the core framework components, key class structures and important methods of FastBee-Arduino in detail, providing developers with an in-depth implementation reference.

The main framework modules map to status, peripherals, rules, and configuration capabilities in the Web console. When debugging the framework lifecycle, inspect dashboard resources, the peripheral list, and peripheral execution rules, and back up relevant configuration from Device Configuration > Advanced Configuration.

Device Dashboard Overview

IDNameTypePinsStatusActions
adcADC Analog ConversionADC36DisabledEdit / Enable / Delete
canCAN BusCAN4, 5DisabledEdit / Enable / Delete
i2cI2C BusI2C17, 18DisabledEdit / Enable / Delete
jtagJTAG Debug InterfaceJTAG12, 13, 14, 15DisabledEdit / Enable / Delete
modbus_rtuModbus RTU - Industrial DeviceUART16, 17DisabledEdit / Enable / Delete
oled_ssd1306_c3OLED Display - SSD1306LCD5, 6DisabledEdit / Enable / Delete
gpio_pwmPWM OutputPWM Output21DisabledEdit / Enable / Delete
sdioSD Card SDIO InterfaceSDIO14, 15, 2, 4, 12, 13DisabledEdit / Enable / Delete
swdSWD Debug InterfaceSWD13, 14DisabledEdit / Enable / Delete
uartUART SerialUART16, 17DisabledEdit / Enable / Delete
NameStatusTriggerTarget PeripheralActionStatsActions
ADC Voltage Collection ReportDisabledTimer TriggerADC Analog ConversionSensor Data Read -> ADC Analog ConversionTrigger Count: 1Execute Once / Edit / Enable / Delete
ADC Voltage Below 2.30V Close RelayDisabledEvent Trigger-Set Low LevelTrigger Count: 1Execute Once / Edit / Enable / Delete
ADC Voltage Above 2.50V Open RelayDisabledEvent Trigger-Set High LevelTrigger Count: 1Execute Once / Edit / Enable / Delete
ADC Voltage Display on 7-SegmentDisabledTimer Trigger-Display NumberTrigger Count: 1Execute Once / Edit / Enable / Delete
NTP Time SyncDisabledPlatform Trigger (MQTT)-NTP SyncTrigger Count: 1Execute Once / Edit / Enable / Delete
OLED Temp/Humidity DisplayDisabledTimer Trigger-OLED Custom DisplayTrigger Count: 1Execute Once / Edit / Enable / Delete
OLED Custom Display - Button Trigger Device InfoDisabledEvent Trigger-OLED Custom DisplayTrigger Count: 1Execute Once / Edit / Enable / Delete
OLED Custom Display - Timer MixedDisabledTimer Trigger-OLED Custom DisplayTrigger Count: 1Execute Once / Edit / Enable / Delete
OLED Custom Display - MQTT MessageDisabledPlatform Trigger (MQTT)-OLED Custom DisplayTrigger Count: 1Execute Once / Edit / Enable / Delete
OTA UpgradeDisabledPlatform Trigger (MQTT)-OTA UpgradeTrigger Count: 1Execute Once / Edit / Enable / Delete

The core service boundary diagram helps determine which module a feature should belong to: peripherals go to Peripheral, rules go to PeriphExec, networking goes to Network, platform and bus go to Protocols, files, logs and config go to system services.

FastBeeFramework Main Framework ​

FastBeeFramework is the core controller of the system, responsible for initializing all sub-modules and coordinating their work.

Initialization Flow ​

cpp
FastBeeFramework::getInstance()
  ├── loadConfig()              // Load all JSON configs from LittleFS
  ├── initPeripherals()         // Initialize all enabled peripherals
  ├── initNetwork()             // Start WiFi/network services and web server
  ├── initProtocols()           // Initialize MQTT/Modbus and other protocols
  ├── initPeriphExec()          // Start rule engine and async execution
  └── startHealthMonitor()      // Start health monitoring and memory gating

Key Methods ​

MethodDescription
setup()System boot entry point, calls all initialization methods in sequence
loop()Main loop, handles scheduled tasks and event dispatch
getPeripheralManager()Get peripheral manager instance
getPeriphExecManager()Get rule engine instance
getProtocolManager()Get protocol manager instance
getNetworkManager()Get network manager instance

Lifecycle Management ​

Boot → setup() → Load Config → Init Modules → Enter loop()
                                    ↓
                              Handle Scheduled Tasks
                              Handle Network Events
                              Handle Protocol Messages
                              Health Monitor Check
                                    ↓
                              Continuous Operation (24/7)

PeriphExecManager Rule Engine ​

PeriphExecManager is the core module that implements "execute actions when conditions are met".

Rule Data Model ​

json
{
  "id": "exec_rule_01",
  "name": "Rule Name",
  "enabled": true,
  "execMode": 0,
  "triggers": [
    {
      "triggerType": 1,
      "triggerPeriphId": "dht_01",
      "timerMode": 0,
      "intervalSec": 10,
      "timePoint": "",
      "eventId": "",
      "operatorType": 0,
      "compareValue": "",
      "pollResponseTimeout": 1000,
      "pollMaxRetries": 2,
      "pollInterPollDelay": 100
    }
  ],
  "actions": [
    {
      "targetPeriphId": "relay_01",
      "actionType": 0,
      "actionValue": "",
      "useReceivedValue": false,
      "syncDelayMs": 0,
      "execMode": 0
    }
  ],
  "protocolType": 0,
  "scriptContent": "",
  "reportAfterExec": true
}

Trigger Types ​

TypeValueNameDescriptionKey Fields
Platform Trigger0PLATFORM_TRIGGERTriggered by MQTT downstream dataoperatorType, compareValue
Timer Trigger1TIMER_TRIGGERPeriodic/fixed-time triggertimerMode, intervalSec, timePoint
Event Trigger4EVENT_TRIGGERSystem event/data source thresholdeventId, operatorType, compareValue
Poll Trigger5POLL_TRIGGERModbus/local data conditiontriggerPeriphId, poll config

Trigger Relationship: Multiple triggers in the same rule have an OR relationship; any match triggers the rule.

Action Types ​

ValueEnum NameCategoryactionValue Meaning
0ACTION_HIGHGPIOIgnored, set target pin HIGH
1ACTION_LOWGPIOIgnored, set target pin LOW
2ACTION_BLINKGPIOBlink interval in ms (default 500)
3ACTION_BREATHEGPIOBreathe cycle in ms (default 2000)
4ACTION_SET_PWMGPIOPWM duty cycle 0-255
5ACTION_SET_DACGPIODAC output value 0-255
6ACTION_SYS_RESTARTSystemIgnored, restart device after 500ms delay
7ACTION_SYS_FACTORY_RESETSystemIgnored, format LittleFS then restart
8ACTION_SYS_NTP_SYNCSystemIgnored, trigger NTP time sync
10ACTION_CALL_PERIPHERALPeripheralCall peripheral-specific method (JSON)
13ACTION_HIGH_INVERTEDGPIOIgnored, inverted HIGH (active LOW)
15ACTION_SCRIPTScriptCommand script content
19ACTION_SENSOR_READSensorRead parameters (JSON)
21ACTION_TRIGGER_EVENTEventTrigger logical event
24ACTION_DISPLAY_TM1637DisplayTM1637 display parameters
25ACTION_DISPLAY_OLEDDisplayOLED display parameters
26ACTION_DISPLAY_LCDDisplayLCD display parameters
27ACTION_DISPLAY_ROTATEDisplayRotate display parameters

Action Relationship: Multiple actions in the same rule are executed sequentially in array order.

Sensor Read actionValue Format ​

actionType: 19 uses a JSON string to describe the read parameters:

json
{
  "periphId": "sht31_i2c",
  "sensorCategory": "SHT31",
  "dataField": "temperature",
  "sensorLabel": "Temperature",
  "unit": "C",
  "decimalPlaces": 1,
  "driverParams": {
    "addr": "0x44",
    "sda": 21,
    "scl": 22
  }
}

Common sensorCategory Values:

sensorCategoryOutput FieldsResource Recommendation
analogvoltage, valueAvailable on ESP32
digitalvalueAvailable on ESP32
dht11 / dht22temperature, humidityAvailable on ESP32
ds18b20temperatureAvailable on ESP32
ultrasonicdistanceAvailable on ESP32
currentcurrentAvailable on ESP32
voltagevoltageAvailable on ESP32
SHT31temperature, humidityAvailable on ESP32, lightweight I2C
AHT20temperature, humidityAvailable on ESP32, lightweight I2C
BH1750illuminanceAvailable on ESP32, lightweight I2C
BMP280temperature, pressure, altitudeRecommended esp32s3-F16R8
MPU6050accelX/Y/Z, temperature, gyroX/Y/ZRecommended esp32s3-F16R8

Async Execution Engine ​

Worker Pool Architecture:

  • Pre-created 3 async tasks (avoid runtime allocation)
  • Minimum heap memory gate: 30KB
  • Task stack size: 4KB (normal) / 8KB (script)
  • Task priority: 0 (lowest)

Execution Flow:

Rule Triggered → Check Heap Memory (>30KB?)
       → Yes: Dispatch async task to Worker Pool
       → No: Log WARN, skip execution
       → Worker executes action sequence
       → Report execution result

Key Methods:

  • evaluateCondition(): Evaluate trigger conditions
  • dispatchAction(): Dispatch actions to executor
  • executeRuleAsync(): Execute rule asynchronously
  • onSensorData(): Handle sensor data events

PeripheralManager Peripheral Management ​

PeripheralManager manages the lifecycle of all peripherals.

Peripheral Configuration Model ​

json
{
  "id": "sensor_01",
  "name": "Sensor Name",
  "type": 38,
  "enabled": true,
  "pinCount": 1,
  "pins": [13, 255, 255, 255, 255, 255, 255, 255],
  "params": {}
}

Field Description:

  • id: Unique identifier for rule references
  • name: Display name
  • type: Peripheral type enum value
  • enabled: Whether enabled
  • pinCount: Number of pins used
  • pins: Pin array (255 means unused)
  • params: Type-specific parameters

Common Peripheral Types ​

typeNameDescriptionPin Count
1UARTSerial / Modbus RTU2 (TX/RX)
2I2CI2C Bus2 (SDA/SCL)
11GPIO_DIGITAL_INPUTDigital Input1
12GPIO_DIGITAL_OUTPUTDigital Output1
13GPIO_DIGITAL_INPUT_PULLUPPull-up Input (Button)1
14GPIO_DIGITAL_INPUT_PULLDOWNPull-down Input1
15GPIO_ANALOG_INPUTADC Analog Input1
17GPIO_PWM_OUTPUTPWM Output1
18-20GPIO_INTERRUPTInterrupt Input (rising/falling/both edges)1
21GPIO_TOUCHTouch Input1
26ADC_INPUTADC Input (alias)1
36LCDDisplay (SSD1306/SH1106)2 (I2C)
37SDIOSD Card Interface (placeholder)4-6
38SENSORSensor (DHT/DS18B20/Ultrasonic etc.)1-2
41PWM_SERVOServo1
42STEPPER_MOTORStepper Motor4-6
43ENCODERRotary Encoder2-3
44ONE_WIREOne-Wire (DS18B20)1
45NEO_PIXELWS2812B RGB LED Strip1
47SEVEN_SEGMENT_TM1637TM1637 7-Segment Display2 (CLK/DIO)
51MODBUS_DEVICEModbus Slave Device0 (UART)
60DEVICE_EVENTLogical Event Source0

Hardware Initialization Flow ​

1. Validate Pin Legality
   - Avoid GPIO6-11 (Flash pins)
   - GPIO34-39 are input-only
   - ADC2 unavailable when WiFi is active

2. Check Pin Conflicts
   - Same pin cannot be allocated twice
   - I2C devices can share SDA/SCL

3. Configure Pin Mode
   - pinMode(pin, INPUT/OUTPUT/INPUT_PULLUP)
   - ledcSetup() for PWM
   - adcAttachPin() for ADC

4. Initialize Peripheral Driver
   - Create corresponding Driver based on type
   - Call driver->begin(pins, params)

5. Register to Peripheral List
   - Add to m_peripherals map
   - Record pin occupation table

Key Methods:

  • addPeripheral(): Add a peripheral
  • initHardware(): Initialize hardware
  • setupHardware(): Configure pins
  • removePeripheral(): Remove a peripheral
  • getPeripheral(): Get peripheral instance
  • performMaintenance(): Periodic maintenance (handle ISR interrupt queue)
  • processInterruptQueue(): Take interrupt events from FreeRTOS queue and dispatch

Interrupt Handling Mechanism:

GPIO interrupts are safely passed from ISR context to the main loop via a FreeRTOS queue:

ISR Interrupt → xQueueSendFromISR(pin) → Main Loop performMaintenance() → processInterruptQueue() → handleInterrupt(pin)

Sensor Data Cache ​

Sensor read actions write the most recent reading to a local cache:

cpp
// Cache key format
"sensor_cache:<periphId>:<dataField>"

// Examples
"sensor_cache:dht_01:temperature" → 28.5
"sensor_cache:dht_01:humidity" → 65.2

Cached data is used for:

  • Event trigger condition evaluation
  • Web interface real-time display
  • MQTT data reporting

ConfigStorage Configuration Storage ​

ConfigStorage manages persistence of all configurations.

Configuration File Structure ​

/config/
  ├── device.json       # Device config (name/model/serial number)
  ├── network.json      # Network config (WiFi/Ethernet/4G)
  ├── peripherals.json  # Peripheral config (all peripheral list)
  ├── periph_exec.json  # Execution rules (triggers + actions)
  ├── protocol.json     # Protocol config (MQTT/Modbus)
  ├── rule_scripts.json # Rule scripts when the feature is active
  └── users.json        # User configuration

Storage Strategy ​

LittleFS File System:

  • Embedded Flash file system
  • Supports wear leveling
  • Power-loss safe (atomic writes)

JSON Serialization:

  • Uses ArduinoJson library
  • Compact mode (reduces space usage)
  • Stream read/write (avoids full loading)

Write Protection:

  • Write to temporary file .tmp first
  • Validate JSON format
  • Atomically replace original file
  • Preserve original config on failure

Config Import/Export ​

Export API:

GET /api/system/export-config?type=peripherals
GET /api/system/export-config?type=periph_exec
GET /api/system/export-config?type=all

Import API:

POST /api/system/import-config
Body: multipart/form-data (JSON file)

Key Methods:

  • loadConfig(): Load configuration
  • saveConfig(): Save configuration
  • exportConfig(): Export configuration
  • importConfig(): Import configuration

HealthMonitor Health Monitoring ​

HealthMonitor continuously monitors system health status.

Monitoring Metrics ​

MetricCheck IntervalDescription
Free Heap Memory5sESP.getFreeHeap()
Max Allocatable Block5sESP.getMaxAllocHeap()
WiFi Connection Status1sWiFi.status()
MQTT Connection Status1sMQTTClient.connected()
System UptimeContinuousmillis()

Alert Mechanism ​

Memory Thresholds:

Heap MemoryActionReason
< 20KBWARN logAlert low memory
< 10KBDisable SSESSE connections use ~8KB
< 5KBReduce log levelReduce string allocations

Recovery Strategy:

  • No auto-recovery (avoid frequent oscillation)
  • Requires external intervention (restart/disable features)
  • Logs alert messages for troubleshooting

WDT Watchdog ​

Configuration:

cpp
esp_task_wdt_init(10, true);  // 10-second timeout

Reasons:

  • async_tcp file I/O may block
  • Large JSON serialization is time-consuming
  • Prevent system deadlock

Feeding:

  • loop() main loop auto-feeds
  • Async tasks need manual feeding

Boot Diagnostics ​

Output:

[BOOT] Chip: ESP32-WROOM-32U Rev3
[BOOT] Flash: 4096KB, PSRAM: 0KB
[BOOT] Cores: 2, Features: WiFi/BT/BLE
[BOOT] Free heap: 285432 bytes
[BOOT] Max alloc: 114688 bytes
[BOOT] PSRAM: disabled (no-PSRAM build)

Purpose:

  • Quickly determine if PSRAM is available
  • Confirm available memory capacity
  • Troubleshoot boot failures

Key Class Relationships ​

FastBeeFramework
  ├── PeripheralManager* m_peripheralManager
  ├── PeriphExecManager* m_periphExecManager
  ├── NetworkManager* m_networkManager
  ├── ProtocolManager* m_protocolManager
  ├── ConfigStorage* m_configStorage
  └── HealthMonitor* m_healthMonitor

PeripheralManager
  ├── map<string, Peripheral*> m_peripherals
  ├── map<int, bool> m_pinOccupancy
  └── vector<Driver*> m_drivers

PeriphExecManager
  ├── map<string, ExecRule*> m_rules
  ├── WorkerPool* m_workerPool
  ├── map<string, string> m_sensorCache
  └── ButtonEventSubsystem* m_buttonEvents

NetworkManager
  ├── WiFiManager* m_wifiManager
  ├── WebConfigManager* m_webManager
  └── NetworkAdapter* m_activeAdapter

ProtocolManager
  ├── MQTTClient* m_mqttClient
  ├── ModbusHandler* m_modbusHandler
  └── map<string, ProtocolHandler*> m_protocols

FastBee | fastbee.cn