Skip to content

Script System ​

Overview ​

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

Release environments compile FASTBEE_ENABLE_COMMAND_SCRIPT and FASTBEE_ENABLE_RULE_SCRIPT. The pages and actions are available only when both runtime features pass the user switch and memory budget.

The Rule Scripts page maintains transformation rules; command scripts are normally edited from Peripheral Exec actions.

NameStatusTriggerProtocol TypeStatsOperations
MQTT Receive: Object to ArrayDisabledData ReceiveMQTTTriggered: 0Edit / Enable / Delete
MQTT Report: Array to ObjectDisabledData ReportMQTTTriggered: 0Edit / 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 transform data on protocol paths integrated with the firmware. The current release connects this pipeline to MQTT and Modbus RTU. Values for Modbus TCP, HTTP, CoAP, and raw TCP remain in the configuration enum for compatibility but do not provide protocol clients.

Core Uses:

  • Convert between platform standard array format and third-party system custom JSON formats
  • Unify data formats across enabled protocol paths so external devices can 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 Result

Rule 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 TypeNumberDescriptionData Flow
Data Receive (DATA_RECEIVE)0Triggered when protocol data arrivesExternal --> ESP32
Data Report (DATA_REPORT)1Triggered before protocol data is sentESP32 --> 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 TypeNumberRelease Status
MQTT0Integrated message send/receive path
Modbus RTU1Integrated serial data path
Modbus TCP2Compatibility enum only; no release client
HTTP3Compatibility enum only; no outbound release client
CoAP4Compatibility enum only; no release client
TCP5Compatibility enum only; no raw TCP release client

Selecting a compatibility-only value does not create a network connection or transmit data.

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:

  1. The system parses the input JSON data and extracts all key-value pairs
  2. Scans the template for ${key} placeholders
  3. Replaces each placeholder with the corresponding value
  4. 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: id field as key, value field as value
  • 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 ​

  1. Open the Web management page and go to the Rule Scripts page
  2. Click the New Rule button
  3. 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)
  4. 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 id values, 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:

json
[
  {"id": "temperature", "value": "27.43", "remark": ""},
  {"id": "humidity", "value": "32.18", "remark": ""}
]

System-extracted key-value pairs:

keyvalue
temperature27.43
humidity32.18

4.3 Object Format Input Parsing ​

When input data is a flat JSON object:

json
{"temperature": 26.5, "humidity": 65.8}

System-extracted key-value pairs:

keyvalue
temperature26.5
humidity65.8

4.4 Limit Parameters ​

ItemLimitDescription
Max script length2048 bytesMaximum bytes for scriptContent field
Max key-value pairs32Excess is ignored
Input formatJSON array or objectNon-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):

json
[
  {"id": "temperature", "value": "27.43", "remark": ""},
  {"id": "humidity", "value": "32.18", "remark": ""}
]

Script Content:

{"temperature": ${temperature}, "humidity": ${humidity}}

Output Result:

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

json
{"temperature": 26.5, "humidity": 65.8}

Script Content:

[{"id":"temperature","value":"${temperature}","remark":""},{"id":"humidity","value":"${humidity}","remark":""}]

Output Result:

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

json
{"temperature": 25.3, "humidity": 60.1}

Script Content:

[{"id":"temperature","value":"${temperature}","remark":""},{"id":"humidity","value":"${humidity}","remark":""}]

Output Result:

json
[{"id":"temperature","value":"25.3","remark":""},{"id":"humidity","value":"60.1","remark":""}]

Case 4: HTTP-shaped Output (Template Only) ​

This example demonstrates output formatting only. The release firmware does not include an outbound HTTP client, so the template alone cannot send an HTTP request.

Scenario: Custom firmware with an HTTP client needs a specific JSON structure.

Trigger Type: Data Report (DATA_REPORT) Protocol Type: HTTP

Input Data:

json
[{"id":"temperature","value":"27.43"},{"id":"humidity","value":"32.18"}]

Script Content:

{"device":"esp32","temp":${temperature},"humi":${humidity}}

Output Result:

json
{"device":"esp32","temp":27.43,"humi":32.18}

Case 5: TCP-shaped Output (Template Only) ​

This example demonstrates output formatting only. The release firmware does not include a raw TCP client, so the template alone cannot open a TCP connection.

Scenario: Custom firmware with a TCP client needs compact text to reduce bandwidth.

Trigger Type: Data Report (DATA_REPORT) Protocol Type: TCP

Input Data:

json
[{"id":"temperature","value":"27.43"},{"id":"humidity","value":"32.18"}]

Script Content:

T:${temperature},H:${humidity}

Output Result:

T:27.43,H:32.18

Case 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

6.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 creates two disabled MQTT transformation examples. Modify and test a copy before enabling it. RuleScript protocol types currently cover MQTT and Modbus RTU; TCP, HTTP, CoAP and Modbus TCP clients are not part of the release firmware.

Example NameTrigger TypeProtocolDescription
MQTT Report: Array to ObjectData ReportMQTTStandard array --> Flat object
MQTT Receive: Object to ArrayData ReceiveMQTTFlat object --> Standard array

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-script

Response Fields:

FieldTypeDescription
idstringRule unique identifier
namestringRule name
enabledbooleanWhether enabled
triggerTypenumberTrigger type (0=Data Receive, 1=Data Report)
protocolTypenumberProtocol enum (0-5); release data paths use 0=MQTT and 1=Modbus RTU
scriptContentstringTemplate script content
lastTriggerTimenumberLast trigger time (ms timestamp)
triggerCountnumberTotal 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=true

7.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_a2o

7.5 Delete Rule ​

DELETE /api/rule-script/?id=script_mqtt_a2o

Part 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.

CategoryContentUsage Recommendation
Common CommandsGPIO pin HIGH/LOW, DELAY ms, PWM pin duty freq, PERIPH id action value, MQTT key value, LOG textOne command per line, keep actions short, sequential, and auditable.
Safety BoundariesOne command per line, comments on their own line, limit script length, limit delay and nesting depthDo not write infinite loops or long-blocking actions.
Troubleshooting PathSyntax validation on save -> Manually execute single action -> Check peripheral state and logs -> Confirm target peripheral enabled -> Connect to triggerUse 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 LOW

3. Supported Commands Overview ​

CommandFormatDescription
GPIOGPIO <pin> HIGH|LOWSet pin HIGH/LOW
DELAYDELAY <ms>Delay wait (max 10 seconds per command)
PWMPWM <pin> <duty>Set PWM duty cycle (0-255)
DACDAC <pin> <value>Set DAC analog output (0-255)
LOGLOG <message>Output debug log (supports random number expressions)
PERIPHPERIPH <id> <action> [param]Control configured peripheral by ID
MQTTMQTT <topicIndex> <message>Publish MQTT message (supports random number expressions)

Random Number Expressions (usable in MQTT and LOG commands):

ExpressionDescriptionExampleOutput
RANDOM(min,max)Random integerRANDOM(-10,100)27
RANDOMF(min,max,decimals)Random floatRANDOMF(-10,100,1)23.5

4. Basic Syntax Rules ​

  • One command per line
  • Command names are case-insensitive (GPIO, gpio, Gpio are 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 HIGH

5. Command Reference ​

GPIO -- Digital Pin Control ​

Set the specified GPIO pin HIGH or LOW.

GPIO <pin> HIGH|LOW
ParameterDescription
PinGPIO number, e.g., 2, 4, 5, 12-33, etc.
HIGH/LOWOutput 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 HIGH

Note: 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>
ParameterDescription
msWait time in ms, range 1-10000

Examples:

DELAY 500         # Wait 500 milliseconds
DELAY 1000        # Wait 1 second
DELAY 5000        # Wait 5 seconds

Limits:

  • 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>
ParameterDescription
PinGPIO number
Duty0-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 output

Note: 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>
ParameterDescription
PinDAC pin, ESP32 only supports GPIO 25 and GPIO 26
Value0-255, corresponding to 0V-3.3V

Examples:

DAC 25 128        # Output ~1.65V
DAC 26 255        # Output ~3.3V
DAC 25 0          # Output 0V

LOG -- Output Log ​

Output a message in the system log for debugging and tracking script execution. Supports RANDOM/RANDOMF random number expressions.

LOG <message>
ParameterDescription
MessageAny 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) degrees

Logs 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]
ParameterDescription
Peripheral IDIdentifier from peripheral configuration, e.g., led_1, fan, relay_main
Sub-actionControl action, see table below
ParameterSome sub-actions require additional parameters

Supported Sub-Actions:

Sub-ActionParameterDescription
HIGHNoneSet peripheral HIGH
LOWNoneSet peripheral LOW
PWM <duty>Duty cycle 0-255Set PWM duty cycle
BLINK [ms]Optional, interval ms, default 500Start blink effect (async timer)
BREATHE [ms]Optional, period ms, default 2000Start breathe effect (async timer)
STOPNoneStop current timer action (blink/breathe)
DISPLAY <content>Number string, supports templates7-segment display number (max 4 digits, supports decimal and colon)
TEXT <content>Max 4 chars, supports templates7-segment display alphanumeric text
CLEARNone7-segment clear display (all segments off)
BRIGHTNESS <level>0-77-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 display

Notes:

  • Peripheral ID must match a configured peripheral in the peripheral configuration page
  • BLINK and BREATHE start 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/BRIGHTNESS only 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>
FormatExampleDisplay Effect
IntegerDISPLAY 12341234
DecimalDISPLAY 25.325.3 (decimal point at corresponding position)
ClockDISPLAY 12:3412:34 (center colon lit)
NegativeDISPLAY -12-12 (minus sign at first position)
TemplateDISPLAY ${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 character

CLEAR -- Clear Display ​

Turn off all segments, clear the display.

PERIPH <displayID> CLEAR

BRIGHTNESS -- Brightness Adjustment ​

Set the display brightness level, 8 levels total.

PERIPH <displayID> BRIGHTNESS <level>
LevelDescription
0Dimmest (nearly invisible)
1-2Night low brightness
3Default brightness (indoor)
4-5Normal brightness
6-7Brightest (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 daytime

Values 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>]}
AttributeDescriptionExample
Omitted (default value)Read field current value${dht_01.temperature} -> 25.3
.unitRead field unit${dht_01.temperature.unit} -> ℃
.labelRead field display label${dht_01.temperature.label} -> Temp

How It Works ​

  1. Sensor peripherals (e.g., DHT11/DHT22/DS18B20/Modbus collection) write each field to global cache with key <peripheralID>_<fieldName> after collection completes
  2. Before DISPLAY/TEXT execution, ${...} placeholders are scanned and corresponding values are looked up from cache for text substitution
  3. When cache misses occur, original placeholder text is preserved for debugging uncaptured or misspelled IDs/field names

Common Field Names ​

Peripheral TypeCommon Fields
DHT11/DHT22temperature, humidity
DS18B20temperature
Modbus CollectionDetermined 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>
ParameterDescription
Topic IndexConfigured MQTT publish topic index (starting from 0)
MessageMessage 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/RANDOMF expressions 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)
ParameterDescription
minMinimum value (integer, can be negative)
maxMaximum 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)
ParameterDescription
minMinimum value (can be negative or decimal)
maxMaximum value
decimalsDecimal places (0-6)

6. Command Script Limit Parameters ​

ItemLimitDescription
Max script length1024 bytesTotal bytes of script text
Max commands50Excluding comments and empty lines
Single DELAY limit10,000 ms10 seconds
Accumulated DELAY limit30,000 ms30 seconds
Script execution timeout35,000 ms35 seconds, auto-abort on timeout
Disabled pinsGPIO 6-11Reserved 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 ​

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 complete

Example 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 complete

Example 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 activated

Example 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 complete

Example 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 reported

Example 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 2800

Configuration Notes:

  • Both tm1637_01 (7-segment) and dht_01 (DHT11) must have enabled=true in peripheral configuration
  • Use execMode=0 (asynchronous execution) to avoid blocking the main scheduling loop
  • intervalSec should be 1-2 seconds longer than the accumulated DELAY time 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:

  1. Is the rule enabled (enabled=true)?
  2. Is the trigger type correct (0=Data Receive, 1=Data Report)?
  3. Does the protocol type match (ensure it matches the actual communication protocol used)?
  4. 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:

  1. Hardware enabled: Confirm platformio.ini has -DFASTBEE_ENABLE_SEVEN_SEGMENT=1 enabled, recompile and flash firmware
  2. Peripheral enabled: Confirm 7-segment entry has enabled=true in peripheral configuration page
  3. Rule enabled: Confirm peripheral execution rule has enabled=true and has been triggered (check trigger count)
  4. Wiring: CLK/DIO pins match peripheral configuration pins, AC VCC/GND power is normal
  5. Brightness: If BRIGHTNESS is 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:

  1. Sensor peripheral (e.g., DHT11) has enabled=false and has never collected
  2. Sensor first collection not yet completed (device just started or timer interval too long)
  3. Peripheral ID or field name typo (case-sensitive)
  4. Sensor collection failed, cache not updated; check logs for [PeriphExec] Update sensor cache to 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:

  1. Increase intervalSec (recommend at least 2 seconds more than total DELAY sum)
  2. Disable other high-frequency async rules (e.g., flowing light, BLINK/BREATHE)
  3. Simplify script, reduce command count

Debugging Methods ​

  1. Add LOG commands: Add LOG markers before and after key steps to track execution progress
  2. Check device logs: Go to Device Log in the Web management page, look for [Script] and [PeriphExec] prefixed logs
  3. Segment testing: Split complex scripts into small segments, verify each segment before merging
  4. 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):

PinDescriptionScript Usable
GPIO 0BOOT button, pull-upUse with caution
GPIO 1TX0 serial outputNot recommended
GPIO 2Onboard LED (some dev boards)Usable
GPIO 3RX0 serial inputNot recommended
GPIO 4General purposeUsable
GPIO 5General purposeUsable
GPIO 6-11SPI FlashDo not use
GPIO 12-33General purposeUsable
GPIO 34-39Input 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 by RuleScriptManager. triggerType field meanings:
    • 0: Data Receive (DATA_RECEIVE)
    • 1: Data Report (DATA_REPORT)
  • /config/periph_exec.json -- Stores peripheral execution rules (including command script actions), managed by PeriphExecManager. triggerType field meanings:
    • 0: Platform Trigger
    • 1: Timer Trigger
    • 2: 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.

FastBee | fastbee.cn