Script System
Script System
This document covers the two major scripting features of the FastBee peripheral execution system:
- Rule Scripts (Data Conversion Template Engine) -- for multi-protocol data format conversion
- Command Scripts (Hardware Control Script Engine) -- for GPIO/PWM/DAC hardware automation control
Lite firmware disables
FASTBEE_ENABLE_COMMAND_SCRIPTandFASTBEE_ENABLE_RULE_SCRIPTby default, and the Web pages do not expose script management entries. This document primarily applies to Standard, Full, or custom builds with script switches enabled; for Lite local interlocking, prefer using timer, event, and sensor actions in peripheral execution.
The Rule Scripts page in Standard / Full is used to maintain the script list; command scripts are typically accessed from peripheral execution actions.
| Name | Status | Trigger | Protocol Type | Stats | Operations |
|---|---|---|---|---|---|
| CoAP Receive Convert | Disabled | Data Receive | CoAP | Triggered: 0 | Edit / Enable / Delete |
| HTTP Report: Custom Format | Disabled | Data Report | HTTP | Triggered: 0 | Edit / Enable / Delete |
| MQTT Receive: Object to Array | Disabled | Data Receive | MQTT | Triggered: 0 | Edit / Enable / Delete |
| MQTT Report: Array to Object | Disabled | Data Report | MQTT | Triggered: 0 | Edit / Enable / Delete |
| ModbusRTU Receive Convert | Disabled | Data Receive | Modbus RTU | Triggered: 0 | Edit / Enable / Delete |
| TCP Report: Compact Format | Disabled | Data Report | TCP | Triggered: 0 | Edit / Enable / Delete |
| ModbusTCP Receive Convert | Disabled | Data Receive | Modbus TCP | Triggered: 0 | Edit / Enable / Delete |
When debugging scripts, start with fixed-field templates first. After confirming input data, rule matching, and output payload are all correct, gradually add conditions, expressions, and peripheral actions.
Command scripts are best suited for short action sequences such as flowing lights, PWM gradients, or simple display refreshes. Complex logic is still recommended to be placed in peripheral execution triggers or RuleScript.
Part 1: Rule Scripts (Data Conversion Templates)
1. Feature Overview
Rule scripts are FastBee's multi-protocol data format conversion pipeline. When devices send/receive data through different protocols (MQTT, Modbus RTU/TCP, HTTP, CoAP, TCP), rule scripts can automatically perform format conversion as data flows through the system.
Core Uses:
- Convert between platform standard array format and third-party system custom JSON formats
- Unify data formats across different protocols so external devices seamlessly integrate with the FastBee platform
- Adapt to new data format requirements without modifying firmware code
Execution Model:
Input Data (JSON) --> Extract key-value --> Replace template placeholders --> Output ResultRule scripts are pure data conversion pipelines with no side effects (no GPIO control, no message sending); they only transform the format of passing data.
2. Basic Concepts
2.1 Trigger Types
Rule scripts have two trigger types:
| Trigger Type | Number | Description | Data Flow |
|---|---|---|---|
| Data Receive (DATA_RECEIVE) | 0 | Triggered when protocol data arrives | External --> ESP32 |
| Data Report (DATA_REPORT) | 1 | Triggered before protocol data is sent | ESP32 --> External |
Data Receive (triggerType=0): After the device receives data from external sources, it passes through the rule script for conversion before system processing. A typical use case is converting custom JSON formats from third-party devices to FastBee standard array format.
Data Report (triggerType=1): Before the device sends data externally, it passes through the rule script for conversion. A typical use case is converting FastBee's internal standard array format to the JSON format required by the target platform.
2.2 Protocol Types
Each rule is bound to one protocol type and only takes effect on that protocol's data flow:
| Protocol Type | Number | Description |
|---|---|---|
| MQTT | 0 | MQTT message send/receive |
| Modbus RTU | 1 | Modbus serial communication |
| Modbus TCP | 2 | Modbus TCP/IP communication |
| HTTP | 3 | HTTP request/response |
| CoAP | 4 | CoAP IoT protocol |
| TCP | 5 | Raw TCP socket |
2.3 Template Syntax (${key} Placeholder)
Rule scripts use plain text templates with ${key} placeholders to reference field values from input data.
How It Works:
- The system parses the input JSON data and extracts all key-value pairs
- Scans the template for
${key}placeholders - Replaces each placeholder with the corresponding value
- Returns the replaced string as output
When debugging rule scripts, line up the input JSON, placeholders, and output template for cross-checking. If ${key} remains as literal text, it usually means the input data has no matching key, or array format was not extracted by id/value.
Supported Input Formats:
- Array format (FastBee standard):
[{"id":"temperature","value":"27.43"}, ...]- Extraction rule:
idfield as key,valuefield as value
- Extraction rule:
- Object format (flat JSON):
{"temperature": 27.43, ...}- Extraction rule: Each object key name as key, key value as value
3. Creating and Managing Rule Scripts
3.1 Create Rule
- Open the Web management page and go to the Rule Scripts page
- Click the New Rule button
- Fill in rule information:
- Name: Descriptive name, e.g., "MQTT Report: Array to Object"
- Trigger Type: Select "Data Receive" or "Data Report"
- Protocol Type: Select the communication protocol this rule applies to
- Script Content: Write
${key}placeholder template (see below)
- Click Save
3.2 Edit Rule
In the rule script table, click the Edit button of the corresponding rule, modify and save.
3.3 Enable/Disable Rule
- Click the Enable/Disable button on the rule row to toggle state
- Disabled rules do not participate in data conversion matching
- Newly created preset examples are disabled by default and need to be manually enabled
3.4 Delete Rule
Click the Delete button on the rule row to remove the rule. Deletion is irreversible.
3.5 Rule Matching Priority
- For the same protocol type and trigger direction, only the first matching enabled rule takes effect
- If no rules match, data passes through unchanged without any conversion
4. Script Syntax Details
4.1 Placeholder Format
${variableName}- Variable names correspond to keys in the input JSON (array format
idvalues, or object format key names) - Variable names are case-sensitive:
${temperature}and${Temperature}are different - Unmatched placeholders remain as-is without substitution
4.2 Array Format Input Parsing
When input data is in FastBee standard array format:
[
{"id": "temperature", "value": "27.43", "remark": ""},
{"id": "humidity", "value": "32.18", "remark": ""}
]System-extracted key-value pairs:
| key | value |
|---|---|
| temperature | 27.43 |
| humidity | 32.18 |
4.3 Object Format Input Parsing
When input data is a flat JSON object:
{"temperature": 26.5, "humidity": 65.8}System-extracted key-value pairs:
| key | value |
|---|---|
| temperature | 26.5 |
| humidity | 65.8 |
4.4 Limit Parameters
| Item | Limit | Description |
|---|---|---|
| Max script length | 2048 bytes | Maximum bytes for scriptContent field |
| Max key-value pairs | 32 | Excess is ignored |
| Input format | JSON array or object | Non-JSON input returns original data |
5. Practical Application Cases
Case 1: MQTT Report -- Array to Object
Scenario: FastBee internally uses array format for sensor data, but the cloud platform requires flat JSON object format.
Trigger Type: Data Report (DATA_REPORT) Protocol Type: MQTT
Input Data (FastBee standard format):
[
{"id": "temperature", "value": "27.43", "remark": ""},
{"id": "humidity", "value": "32.18", "remark": ""}
]Script Content:
{"temperature": ${temperature}, "humidity": ${humidity}}Output Result:
{"temperature": 27.43, "humidity": 32.18}Case 2: MQTT Receive -- Object to Array
Scenario: External device sends flat JSON that needs to be converted to FastBee standard array format for correct system parsing.
Trigger Type: Data Receive (DATA_RECEIVE) Protocol Type: MQTT
Input Data (external device format):
{"temperature": 26.5, "humidity": 65.8}Script Content:
[{"id":"temperature","value":"${temperature}","remark":""},{"id":"humidity","value":"${humidity}","remark":""}]Output Result:
[{"id":"temperature","value":"26.5","remark":""},{"id":"humidity","value":"65.8","remark":""}]Case 3: Modbus RTU Data Receive Conversion
Scenario: Modbus RTU slave register data parsed by the driver layer as a JSON object needs to be converted to FastBee standard array format for platform reporting.
Trigger Type: Data Receive (DATA_RECEIVE) Protocol Type: Modbus RTU
Input Data:
{"temperature": 25.3, "humidity": 60.1}Script Content:
[{"id":"temperature","value":"${temperature}","remark":""},{"id":"humidity","value":"${humidity}","remark":""}]Output Result:
[{"id":"temperature","value":"25.3","remark":""},{"id":"humidity","value":"60.1","remark":""}]Case 4: HTTP Report Custom Format
Scenario: Pushing data to a third-party HTTP API that requires a specific JSON structure.
Trigger Type: Data Report (DATA_REPORT) Protocol Type: HTTP
Input Data:
[{"id":"temperature","value":"27.43"},{"id":"humidity","value":"32.18"}]Script Content:
{"device":"esp32","temp":${temperature},"humi":${humidity}}Output Result:
{"device":"esp32","temp":27.43,"humi":32.18}Case 5: TCP Report Compact Text
Scenario: Sending compact text format data to a server via TCP connection to save bandwidth.
Trigger Type: Data Report (DATA_REPORT) Protocol Type: TCP
Input Data:
[{"id":"temperature","value":"27.43"},{"id":"humidity","value":"32.18"}]Script Content:
T:${temperature},H:${humidity}Output Result:
T:27.43,H:32.18Case 6: Multi-Sensor Combination Conversion
Scenario: Device simultaneously collects temperature, humidity, pressure, and light sensor values; needs conversion to nested JSON format.
Script Content:
{"sensors":{"temp":${temperature},"humi":${humidity},"press":${pressure},"light":${light}},"unit":"metric"}6. Best Practices
6.1 Naming Convention
Use clear naming format: Protocol Name + Direction + Brief Description
MQTT Report: Array to Object
MQTT Receive: Object to Array
ModbusRTU Receive Convert
HTTP Report: Custom Format6.2 Disable Before Editing
When editing complex conversion templates, disable the rule first, then enable after editing is complete. This prevents incomplete templates from affecting data flow during editing.
6.3 One Rule Per Protocol Direction
Only the first matching rule takes effect for the same protocol type + same trigger direction. Avoid creating duplicate rules.
6.4 Pay Attention to Value Types
- Numeric types use placeholders directly:
"temp": ${temperature}-- outputs"temp": 27.43 - String types need quotes:
"name": "${deviceName}"-- outputs"name": "esp32"
6.5 Preset Example Data
On first startup, the system auto-creates 7 preset example rules covering all 6 protocol types. These examples are disabled by default and can be directly modified and enabled, or used as reference templates.
| Example Name | Trigger Type | Protocol | Description |
|---|---|---|---|
| MQTT Report: Array to Object | Data Report | MQTT | Standard array --> Flat object |
| MQTT Receive: Object to Array | Data Receive | MQTT | Flat object --> Standard array |
| ModbusRTU Receive Convert | Data Receive | Modbus RTU | Object --> Standard array |
| ModbusTCP Receive Convert | Data Receive | Modbus TCP | Object --> Standard array |
| HTTP Report: Custom Format | Data Report | HTTP | Standard array --> Custom JSON |
| CoAP Receive Convert | Data Receive | CoAP | Object --> Standard array |
| TCP Report: Compact Format | Data Report | TCP | Standard array --> Plain text |
7. API Reference
Rule scripts are managed by the independent RuleScriptManager via dedicated REST API (/api/rule-script*) for CRUD operations. Rule scripts are stored in a separate config file /config/rule_scripts.json, completely separated from peripheral execution rules (/config/periph_exec.json).
7.1 Get All Rules
GET /api/rule-scriptResponse Fields:
| Field | Type | Description |
|---|---|---|
| id | string | Rule unique identifier |
| name | string | Rule name |
| enabled | boolean | Whether enabled |
| triggerType | number | Trigger type (0=Data Receive, 1=Data Report) |
| protocolType | number | Protocol type (0-5) |
| scriptContent | string | Template script content |
| lastTriggerTime | number | Last trigger time (ms timestamp) |
| triggerCount | number | Total trigger count |
7.2 Create Rule
POST /api/rule-script
Content-Type: application/x-www-form-urlencoded
name=MQTT Report: Array to Object
&triggerType=1
&protocolType=0
&scriptContent={"temperature": ${temperature}, "humidity": ${humidity}}
&enabled=true7.3 Update Rule
POST /api/rule-script/update
Content-Type: application/x-www-form-urlencoded
id=script_mqtt_a2o
&name=MQTT Report: Array to Object
&triggerType=1
&protocolType=0
&scriptContent={"temperature": ${temperature}, "humidity": ${humidity}}7.4 Enable/Disable Rule
POST /api/rule-script/enable id=script_mqtt_a2o
POST /api/rule-script/disable id=script_mqtt_a2o7.5 Delete Rule
DELETE /api/rule-script/?id=script_mqtt_a2oPart 2: Command Scripts (Hardware Control)
1. Feature Overview
Command scripts are an advanced feature of the FastBee peripheral execution system, allowing users to implement complex automation control logic through simple text command sequences. Scripts are parsed and executed locally on the ESP32 device, supporting GPIO/PWM/DAC hardware control, peripheral linkage, MQTT data reporting, and random number generation.
| Category | Content | Usage Recommendation |
|---|---|---|
| Common Commands | GPIO pin HIGH/LOW, DELAY ms, PWM pin duty freq, PERIPH id action value, MQTT key value, LOG text | One command per line, keep actions short, sequential, and auditable. |
| Safety Boundaries | One command per line, comments on their own line, limit script length, limit delay and nesting depth | Do not write infinite loops or long-blocking actions. |
| Troubleshooting Path | Syntax validation on save -> Manually execute single action -> Check peripheral state and logs -> Confirm target peripheral enabled -> Connect to trigger | Use LOG to mark steps first, then add hardware actions one by one. |
Command scripts are suited for short, sequential, auditable hardware actions. For complex conditions, loop logic, or long waits, prefer placing conditions in triggers and keeping scripts as clear execution steps.
2. Quick Start
On the Web management page, go to Peripheral Execution > New Rule, select Command Script as the action type, then enter commands in the script editor.
Simplest Example -- Blink GPIO 5 once:
GPIO 5 HIGH
DELAY 500
GPIO 5 LOW3. Supported Commands Overview
| Command | Format | Description |
|---|---|---|
GPIO | GPIO <pin> HIGH|LOW | Set pin HIGH/LOW |
DELAY | DELAY <ms> | Delay wait (max 10 seconds per command) |
PWM | PWM <pin> <duty> | Set PWM duty cycle (0-255) |
DAC | DAC <pin> <value> | Set DAC analog output (0-255) |
LOG | LOG <message> | Output debug log (supports random number expressions) |
PERIPH | PERIPH <id> <action> [param] | Control configured peripheral by ID |
MQTT | MQTT <topicIndex> <message> | Publish MQTT message (supports random number expressions) |
Random Number Expressions (usable in MQTT and LOG commands):
| Expression | Description | Example | Output |
|---|---|---|---|
RANDOM(min,max) | Random integer | RANDOM(-10,100) | 27 |
RANDOMF(min,max,decimals) | Random float | RANDOMF(-10,100,1) | 23.5 |
4. Basic Syntax Rules
- One command per line
- Command names are case-insensitive (
GPIO,gpio,Gpioare all valid) - Parameters separated by spaces or tabs
- Lines starting with
#are comments and are skipped - Empty lines are automatically ignored
# This is a comment, will not execute
GPIO 5 HIGH # Inline comments not supported, this line will fail to parse
# Correct: comments on their own line
GPIO 5 HIGH5. Command Reference
GPIO -- Digital Pin Control
Set the specified GPIO pin HIGH or LOW.
GPIO <pin> HIGH|LOW| Parameter | Description |
|---|---|
| Pin | GPIO number, e.g., 2, 4, 5, 12-33, etc. |
| HIGH/LOW | Output level, HIGH for high level, LOW for low level |
Examples:
GPIO 2 HIGH # Onboard LED on (most ESP32 dev boards)
GPIO 2 LOW # Onboard LED off
GPIO 15 HIGH # GPIO15 output HIGHNote: GPIO 6-11 are reserved for SPI Flash; do not use in scripts.
DELAY -- Delay Wait
Pause script execution for the specified milliseconds.
DELAY <ms>| Parameter | Description |
|---|---|
| ms | Wait time in ms, range 1-10000 |
Examples:
DELAY 500 # Wait 500 milliseconds
DELAY 1000 # Wait 1 second
DELAY 5000 # Wait 5 secondsLimits:
- Single DELAY max 10000ms (10 seconds)
- Total accumulated DELAY in a script must not exceed 30000ms (30 seconds)
PWM -- PWM Output
Set the PWM duty cycle for the specified pin.
PWM <pin> <duty>| Parameter | Description |
|---|---|
| Pin | GPIO number |
| Duty | 0-255, 0 = fully off, 255 = fully on |
Examples:
PWM 4 128 # 50% duty cycle
PWM 4 255 # 100% duty cycle (full brightness)
PWM 4 0 # Turn off PWM outputNote: PWM in scripts uses LEDC channel 15 (dedicated), 5000Hz frequency, 8-bit resolution, and does not conflict with the peripheral manager's channels.
DAC -- Analog Output
Set the DAC analog output value for the specified pin.
DAC <pin> <value>| Parameter | Description |
|---|---|
| Pin | DAC pin, ESP32 only supports GPIO 25 and GPIO 26 |
| Value | 0-255, corresponding to 0V-3.3V |
Examples:
DAC 25 128 # Output ~1.65V
DAC 26 255 # Output ~3.3V
DAC 25 0 # Output 0VLOG -- Output Log
Output a message in the system log for debugging and tracking script execution. Supports RANDOM/RANDOMF random number expressions.
LOG <message>| Parameter | Description |
|---|---|
| Message | Any text, supports spaces, multiple words are auto-concatenated. Supports RANDOM/RANDOMF expressions |
Examples:
LOG Script started
LOG Setting GPIO 5 to HIGH
LOG Temperature too high, starting fan
LOG Current simulated temp: RANDOMF(20,35,1) degreesLogs are output with [Script] prefix to the system log, viewable on the Device Log page.
PERIPH -- Peripheral Control
Control configured peripherals by peripheral ID, supporting multiple sub-actions.
PERIPH <peripheralID> <sub-action> [parameter]| Parameter | Description |
|---|---|
| Peripheral ID | Identifier from peripheral configuration, e.g., led_1, fan, relay_main |
| Sub-action | Control action, see table below |
| Parameter | Some sub-actions require additional parameters |
Supported Sub-Actions:
| Sub-Action | Parameter | Description |
|---|---|---|
HIGH | None | Set peripheral HIGH |
LOW | None | Set peripheral LOW |
PWM <duty> | Duty cycle 0-255 | Set PWM duty cycle |
BLINK [ms] | Optional, interval ms, default 500 | Start blink effect (async timer) |
BREATHE [ms] | Optional, period ms, default 2000 | Start breathe effect (async timer) |
STOP | None | Stop current timer action (blink/breathe) |
DISPLAY <content> | Number string, supports templates | 7-segment display number (max 4 digits, supports decimal and colon) |
TEXT <content> | Max 4 chars, supports templates | 7-segment display alphanumeric text |
CLEAR | None | 7-segment clear display (all segments off) |
BRIGHTNESS <level> | 0-7 | 7-segment adjust brightness (0=dimmest, 7=brightest) |
Examples:
# Basic on/off control
PERIPH relay_1 HIGH # Turn on relay
PERIPH relay_1 LOW # Turn off relay
# PWM dimming
PERIPH led_strip PWM 200 # LED strip brightness to 200
# Effect control
PERIPH status_led BLINK 300 # Status LED blink at 300ms interval
PERIPH mood_led BREATHE 1500 # Mood LED 1.5s breathe cycle
PERIPH mood_led STOP # Stop breathe effect
# 7-segment display (TM1637)
PERIPH tm1637_01 DISPLAY 25.3 # Display 25.3
PERIPH tm1637_01 DISPLAY 12:34 # Display clock 12:34
PERIPH tm1637_01 TEXT HELO # Display HELO (max 4 chars)
PERIPH tm1637_01 BRIGHTNESS 5 # Brightness to level 5
PERIPH tm1637_01 CLEAR # Clear displayNotes:
- Peripheral ID must match a configured peripheral in the peripheral configuration page
BLINKandBREATHEstart async timers and return immediately without blocking subsequent commands- If the peripheral ID does not exist, the command is skipped (warning logged) and the script continues
DISPLAY/TEXT/CLEAR/BRIGHTNESSonly work with 7-segment (TM1637) type peripherals; requires 7-segment enabled in peripheral configuration
7-Segment Display (TM1637) Specific Notes
When the PERIPH command targets a TM1637 4-digit 7-segment display, use DISPLAY, TEXT, CLEAR, BRIGHTNESS sub-actions for display control.
DISPLAY -- Display Numbers
Display numeric content on the 7-segment display, supporting integers, decimals, and colon-separated clock format.
PERIPH <displayID> DISPLAY <content>| Format | Example | Display Effect |
|---|---|---|
| Integer | DISPLAY 1234 | 1234 |
| Decimal | DISPLAY 25.3 | 25.3 (decimal point at corresponding position) |
| Clock | DISPLAY 12:34 | 12:34 (center colon lit) |
| Negative | DISPLAY -12 | -12 (minus sign at first position) |
| Template | DISPLAY ${dht_01.temperature} | Dynamically replaced with sensor reading |
Notes:
- 7-segment has only 4 digits; excess is truncated or flagged as overflow
- Floating point numbers automatically place the decimal point based on digit count
- When placeholders miss the cache, original text is preserved for debugging
TEXT -- Display Text
Display alphanumeric characters (max 4 chars) on the 7-segment display. Limited by the 7-segment charset, only certain letters are clearly displayable (e.g., A/b/C/d/E/F/H/L/o/P/U).
PERIPH <displayID> TEXT <content>Examples:
PERIPH tm1637_01 TEXT ON # Display ON
PERIPH tm1637_01 TEXT OFF # Display OFF
PERIPH tm1637_01 TEXT HELO # Display HELO
PERIPH tm1637_01 TEXT ${dht_01.temperature.unit} # Display unit characterCLEAR -- Clear Display
Turn off all segments, clear the display.
PERIPH <displayID> CLEARBRIGHTNESS -- Brightness Adjustment
Set the display brightness level, 8 levels total.
PERIPH <displayID> BRIGHTNESS <level>| Level | Description |
|---|---|
| 0 | Dimmest (nearly invisible) |
| 1-2 | Night low brightness |
| 3 | Default brightness (indoor) |
| 4-5 | Normal brightness |
| 6-7 | Brightest (bright light environments) |
Examples:
PERIPH tm1637_01 BRIGHTNESS 0 # Dimmest before night lights off
PERIPH tm1637_01 BRIGHTNESS 3 # Restore default brightness
PERIPH tm1637_01 BRIGHTNESS 7 # Brightest for outdoor daytimeValues outside 0-7 are automatically clamped to boundaries.
Sensor Data Template (${periphId.field})
The PERIPH ... DISPLAY and PERIPH ... TEXT sub-actions in command scripts, as well as the Display Number / Display Text action values in peripheral execution rules, support dynamically reading sensor data cache via ${periphId.field} placeholders, enabling "collection -> display" linkage.
Syntax Format
${<peripheralID>.<fieldName>[.<attribute>]}| Attribute | Description | Example |
|---|---|---|
| Omitted (default value) | Read field current value | ${dht_01.temperature} -> 25.3 |
.unit | Read field unit | ${dht_01.temperature.unit} -> ℃ |
.label | Read field display label | ${dht_01.temperature.label} -> Temp |
How It Works
- Sensor peripherals (e.g., DHT11/DHT22/DS18B20/Modbus collection) write each field to global cache with key
<peripheralID>_<fieldName>after collection completes - Before
DISPLAY/TEXTexecution,${...}placeholders are scanned and corresponding values are looked up from cache for text substitution - When cache misses occur, original placeholder text is preserved for debugging uncaptured or misspelled IDs/field names
Common Field Names
| Peripheral Type | Common Fields |
|---|---|
| DHT11/DHT22 | temperature, humidity |
| DS18B20 | temperature |
| Modbus Collection | Determined by object model identifiers, e.g., temp, humi, voltage, etc. |
Examples
# Display DHT11 temperature reading
PERIPH tm1637_01 DISPLAY ${dht_01.temperature}
# Display humidity reading
PERIPH tm1637_01 DISPLAY ${dht_01.humidity}
# Display DS18B20 temperature
PERIPH tm1637_01 DISPLAY ${ds18b20_01.temperature}Notes:
- Template substitution occurs at script runtime; latest cache values are re-read on each execution
- If the peripheral is not enabled or has not completed first collection, cache is empty and placeholder text is preserved
- Peripheral IDs and field names are case-sensitive and must match the peripheral configuration page exactly
MQTT -- MQTT Data Reporting
Publish messages to a configured publish topic via MQTT protocol, useful for simulated data reporting, status notifications, etc.
MQTT <topicIndex> <message>| Parameter | Description |
|---|---|
| Topic Index | Configured MQTT publish topic index (starting from 0) |
| Message | Message text to publish, supports RANDOM/RANDOMF random number expressions |
Examples:
# Report fixed data
MQTT 0 [{"id":"switch","value":"1"}]
# Report random temperature (integer, -10 to 100)
MQTT 0 [{"id":"temperature","value":"RANDOM(-10,100)"}]
# Report random temperature (float, 1 decimal place)
MQTT 0 [{"id":"temperature","value":"RANDOMF(-10,100,1)"}]
# Report multiple attributes simultaneously
MQTT 0 [{"id":"temperature","value":"RANDOMF(15,35,1)"},{"id":"humidity","value":"RANDOMF(30,90,1)"}]Notes:
- Topic index corresponds to the Publish Topics list order in MQTT configuration page (first = 0, second = 1, etc.)
- When MQTT is not connected, the command is skipped (warning logged) and the script continues
RANDOM/RANDOMFexpressions in message content generate new random values on each execution
Random Number Expressions
Random number expressions can be used in MQTT and LOG command message content to generate different random values on each script execution.
RANDOM(min,max) -- Random Integer
Generates a random integer in the range [min, max] (inclusive).
RANDOM(min,max)| Parameter | Description |
|---|---|
| min | Minimum value (integer, can be negative) |
| max | Maximum value (integer) |
RANDOMF(min,max,decimals) -- Random Float
Generates a random float in the range [min, max], formatted to the specified decimal places.
RANDOMF(min,max,decimals)| Parameter | Description |
|---|---|
| min | Minimum value (can be negative or decimal) |
| max | Maximum value |
| decimals | Decimal places (0-6) |
6. Command Script Limit Parameters
| Item | Limit | Description |
|---|---|---|
| Max script length | 1024 bytes | Total bytes of script text |
| Max commands | 50 | Excluding comments and empty lines |
| Single DELAY limit | 10,000 ms | 10 seconds |
| Accumulated DELAY limit | 30,000 ms | 30 seconds |
| Script execution timeout | 35,000 ms | 35 seconds, auto-abort on timeout |
| Disabled pins | GPIO 6-11 | Reserved for SPI Flash, cannot be used |
These limits ensure scripts do not long-block the device's main loop. For longer processes, split into multiple rules triggered in stages via events or platform commands, logging at each stage.
7. Command Script Practical Examples
Example 1: Alarm Blink
Triggered when temperature is too high; LED blinks rapidly 5 times as alarm indication.
# Temperature alarm - LED rapid blink 5 times
LOG Temperature alarm triggered
GPIO 2 HIGH
DELAY 200
GPIO 2 LOW
DELAY 200
GPIO 2 HIGH
DELAY 200
GPIO 2 LOW
DELAY 200
GPIO 2 HIGH
DELAY 200
GPIO 2 LOW
DELAY 200
GPIO 2 HIGH
DELAY 200
GPIO 2 LOW
DELAY 200
GPIO 2 HIGH
DELAY 200
GPIO 2 LOW
LOG Alarm blink completeExample 2: Fade-In Effect
LED gradual brightening from dim to bright via PWM.
# LED fade-in effect
LOG Starting fade-in
PWM 4 0
DELAY 100
PWM 4 50
DELAY 100
PWM 4 100
DELAY 100
PWM 4 150
DELAY 100
PWM 4 200
DELAY 100
PWM 4 255
LOG Fade-in completeExample 3: Multi-Peripheral Linkage
Coordinate control of multiple devices via peripheral IDs.
# Scenario: Night mode
LOG Entering night mode
PERIPH main_light LOW
DELAY 500
PERIPH night_light PWM 30
PERIPH mood_led BREATHE 3000
LOG Night mode activatedExample 4: Periodic Simulated Sensor Data Reporting
With timer trigger, periodically report random environment data to MQTT platform.
# Report simulated environment sensor data
LOG Starting environment data report
MQTT 0 [{"id":"temperature","value":"RANDOMF(-10,45,1)"},{"id":"humidity","value":"RANDOMF(20,95,1)"},{"id":"co2","value":"RANDOM(400,2000)"}]
LOG Environment data report completeExample 5: Alarm Linkage + Status Reporting
After detecting anomaly, control peripheral alarm and report status.
# Anomaly alarm linkage
LOG Anomaly detected, starting alarm
PERIPH alarm_led BLINK 200
PERIPH alarm_out HIGH
DELAY 3000
PERIPH alarm_out LOW
MQTT 0 [{"id":"alarm","value":"1"},{"id":"alarm_type","value":"temperature_high"}]
LOG Alarm status reportedExample 6: 7-Segment Temp/Humidity Alternating Display
With peripheral execution timer trigger (recommended intervalSec=8), 7-segment displays temperature for 3 seconds, then humidity for 3 seconds, cycling. Requires DHT11 peripheral enabled and first collection completed.
# TM1637 temp/humidity alternating display
PERIPH tm1637_01 DISPLAY ${dht_01.temperature}
DELAY 3000
PERIPH tm1637_01 DISPLAY ${dht_01.humidity}
DELAY 2800Configuration Notes:
- Both
tm1637_01(7-segment) anddht_01(DHT11) must haveenabled=truein peripheral configuration - Peripheral execution rule recommended
execMode=1(async execution) to avoid blocking the main scheduling loop intervalSecshould be 1-2 seconds longer than the accumulatedDELAYtime in the script, allowing buffer for task stack release
Example 7: 7-Segment Status & Brightness Linkage
Auto-dim 7-segment at night, restore default brightness at dawn.
# Enter night mode
LOG Entering night mode
PERIPH tm1637_01 BRIGHTNESS 1
PERIPH tm1637_01 TEXT NITE
DELAY 2000
PERIPH tm1637_01 DISPLAY ${dht_01.temperature}Part 3: FAQ & Troubleshooting
When troubleshooting scripts, categorize first: save failures check syntax and length, rule not triggered checks trigger and enable state, variable not substituted checks input JSON and placeholders, action no effect checks target peripheral and logs. Do not rewrite the script from scratch right away.
Rule Script FAQ
Q: Why isn't my conversion rule taking effect?
Check items:
- Is the rule enabled (enabled=true)?
- Is the trigger type correct (0=Data Receive, 1=Data Report)?
- Does the protocol type match (ensure it matches the actual communication protocol used)?
- Are
${key}variable names in the script content exactly matching the keys in the input data (case-sensitive)?
Q: Can I create multiple conversion rules for the same protocol?
You can create multiple, but only the first matching enabled rule takes effect for the same protocol type + same trigger direction. Recommend keeping only one rule per protocol per direction.
Q: What happens if JSON parsing fails?
If the input data is not valid JSON, the template engine skips conversion and returns the original data unmodified. No error is generated in system logs; data flow is unaffected.
Q: What happens if ${key} key is not found?
Unmatched placeholders remain as-is. For example, if the input has no pressure field, ${pressure} in the template remains as literal text ${pressure}.
Q: Does rule script execution affect device performance?
Minimal impact. The template engine uses simple string substitution without regex or script interpreters. Conversion completes in microseconds. The mutex lock is only held during rule matching; template substitution executes without locks.
Q: How to view rule script conversion logs?
On the device log page, look for log entries with [PeriphExec] Template applied: prefix. Each successful conversion logs the variable count and data size change.
Command Script FAQ
Q: Script save fails with "Script content cannot be empty"
The script editor is empty or contains only empty lines/comments. Enter at least one valid command.
Q: Script save fails with "Script exceeds maximum length"
Script exceeds 1024 bytes. Simplify the script content and reduce comments.
Q: Script does not execute
Check if the rule is enabled. Go to the rule list and confirm enable status is on.
Q: PERIPH command has no effect
Peripheral ID mismatch. Verify the ID in the peripheral configuration page matches what is used in the script.
Q: MQTT command has no effect
MQTT not connected or topic index incorrect. Check MQTT connection status and confirm the topic index corresponds to an existing publish topic.
Q: 7-segment display is not lit or not showing content
Troubleshoot in this order:
- Hardware enabled: Confirm
platformio.inihas-DFASTBEE_ENABLE_SEVEN_SEGMENT=1enabled, recompile and flash firmware - Peripheral enabled: Confirm 7-segment entry has
enabled=truein peripheral configuration page - Rule enabled: Confirm peripheral execution rule has
enabled=trueand has been triggered (check trigger count) - Wiring: CLK/DIO pins match peripheral configuration
pins, AC VCC/GND power is normal - Brightness: If
BRIGHTNESSis set to 0, it's nearly invisible; try setting to 3-5
Q: ${periphId.field} shows as original text instead of value
This means the sensor cache has no corresponding key. Common causes:
- Sensor peripheral (e.g., DHT11) has
enabled=falseand has never collected - Sensor first collection not yet completed (device just started or timer interval too long)
- Peripheral ID or field name typo (case-sensitive)
- Sensor collection failed, cache not updated; check logs for
[PeriphExec] Update sensor cacheto confirm
Q: 7-segment alternating display rule reports "insufficient memory"
intervalSec and script DELAY accumulated time are too close; async task stack has not been released in time. Solutions:
- Increase
intervalSec(recommend at least 2 seconds more than total DELAY sum) - Disable other high-frequency async rules (e.g., flowing light, BLINK/BREATHE)
- Simplify script, reduce command count
Debugging Methods
- Add LOG commands: Add
LOGmarkers before and after key steps to track execution progress - Check device logs: Go to Device Log in the Web management page, look for
[Script]and[PeriphExec]prefixed logs - Segment testing: Split complex scripts into small segments, verify each segment before merging
- Check trigger conditions: Confirm the rule's trigger type and condition configuration is correct
Appendix
GPIO Pin Quick Reference
Below are commonly available ESP32 pins (may vary by dev board model):
| Pin | Description | Script Usable |
|---|---|---|
| GPIO 0 | BOOT button, pull-up | Use with caution |
| GPIO 1 | TX0 serial output | Not recommended |
| GPIO 2 | Onboard LED (some dev boards) | Usable |
| GPIO 3 | RX0 serial input | Not recommended |
| GPIO 4 | General purpose | Usable |
| GPIO 5 | General purpose | Usable |
| GPIO 6-11 | SPI Flash | Do not use |
| GPIO 12-33 | General purpose | Usable |
| GPIO 34-39 | Input only (no internal pull-up) | Read only, no output support |
Configuration Files
The script system uses two separate configuration files:
/config/rule_scripts.json-- Stores rule scripts (data conversion templates), managed byRuleScriptManager.triggerTypefield meanings:0: Data Receive (DATA_RECEIVE)1: Data Report (DATA_REPORT)
/config/periph_exec.json-- Stores peripheral execution rules (including command script actions), managed byPeriphExecManager.triggerTypefield meanings:0: Platform Trigger1: Timer Trigger2: Device Trigger
The two rule types use different REST API namespaces (/api/rule-script* vs /api/periph-exec*) and do not interfere with each other.
