Skip to content

Code Change Guidelines ​

This document is for maintainers of FastBee-Arduino firmware, Web console and test scripts. The goal is to reduce cross-module regressions and keep all nine release environments stable.

Pre-Change Impact Analysis ​

Call Chain Check ​

Before modifying any function, configuration structure or API, search all call sites:

text
1. Search for function name, config field, API path or macro name.
2. Check if callers depend on return values, side effects, state changes or error codes.
3. Determine whether tests, default config, Web UI, docs and runtime capability interfaces need synchronized updates.

For example, when modifying NetworkManager::startAPMode(), also check initialize(), attemptReconnect(), handle(), ProtocolManager, WiFiManager and the Web network status page to avoid WiFi mode switching affecting MQTT state machine or provisioning page.

State Machine Assessment ​

When changes involve network, MQTT, OTA, peripheral execution, authentication or config saving, you must list key state flows before and after the change. Do not only check the "happy path" for state machine changes - also cover connecting, failed, timeout, recovery, low-memory and post-reboot states.

text
Before: STA -> AP+STA -> STA -> AP+STA (may oscillate)
After: STA -> AP (terminate retry, keep provisioning entry)
Sync Impact: auto-reconnect, MQTT disconnect, dashboard status, log alerts

Cross-Module Dependencies ​

Module RelationshipFocus
NetworkManager ↔ WiFiManagerWiFi mode, STA/AP state, reconnect strategy
NetworkManager → ProtocolManagerMQTT/Modbus init and recovery after network ready
ProtocolManager → Web/APIMQTT/Modbus status, config save, error codes
HealthMonitor → Network/Web/SSELow-memory degradation, connection cleanup, log throttling
WebConfigManager → All ModulesREST API routes, authentication, config read/write

Multi-Chip Compatibility ​

ChipConstraints
ESP324MB tight space, serial defaults to UART0
ESP32-S3PSRAM can relieve large object allocation, but RMT/IR drivers need separate verification
ESP32-C3Tightest runtime budget; keep concurrency and optional features conservative
ESP32-C6Library support differs; preserve and test the OneWire/DallasTemperature compatibility path

Any changes involving memory allocation, task stacks, library dependencies, serial, RMT, USB-CDC, PSRAM or lib_ignore must be compiled for the corresponding chip environment.

In-Change Coding Constraints ​

Defensive Coding ​

  • State checks must cover intermediate states: connecting, disconnecting, failed, low-memory.
  • External inputs, JSON fields, config arrays and pin lists must all be boundary-validated.
  • High-frequency paths should avoid temporary String concatenation, large object JSON and frequent new/delete.
cpp
if (currentStatus != WL_DISCONNECTED) {
    WiFi.disconnect(false);
    delay(100);
}

Resource Cleanup ​

  • Confirm whether WiFi.disconnect() and reconnect task stop are needed before/after WiFi mode switches.
  • new, malloc, file handles, tasks, timers and callback registrations must have release or deregistration paths.
  • Prefer RAII, static pools, pre-allocated buffers and clear failure returns.

Log Levels ​

cpp
static unsigned long lastLog = 0;
if (millis() - lastLog > 30000) {
    lastLog = millis();
    Serial.printf("[MODULE] Status info\n");
}

LOG_ERROR("NetworkManager: Failed to start AP mode");
  • Use throttled logs for high-frequency paths.
  • Use INFO for one-time events.
  • Use ERROR/WARN for errors and exceptions, with sufficient context.
  • Production builds default to FASTBEE_STRIP_INFO_LOGS=1, FASTBEE_DEBUG_LOG=0.

Type & Interface Safety ​

  • When calling across abstraction layers, verify if the interface belongs to the base class; use explicit casts and null checks when necessary.
  • When API response fields are added, removed or change semantics, sync Web UI, test matrix and documentation.
  • When config structures gain new fields, sync default config, migration logic, import/export and factory reset.

Frontend Styles ​

  • Prefer reusing .fb-* component classes and design tokens from web-src/css/main.css.
  • In-page styles should only be used for local overrides genuinely needed by the current page.
  • After frontend changes, verify gzip artifact size and static asset integrity.

Post-Change Verification Matrix ​

The unified entry point is scripts/test-all.ps1. Select checks based on change risk; do not run only a single environment when shared modules, config, network, protocol or Web/API are affected.

CheckCommandCoverage
Static Checksscripts/test-all.ps1 -Checks staticUTF-8, test registration, API matrix, default config, Web static assets, etc.
Native Unit Testsscripts/test-all.ps1 -Checks nativeHost-side C++ unit tests
Multi-Chip Buildscripts/test-all.ps1 -Checks buildESP32, C3, C6, S3 release environments
Release Artifactsscripts/test-all.ps1 -Checks artifactsMerged firmware, LittleFS, manifest
Device Smokescripts/test-all.ps1 -Checks device-smoke -BaseUrl http://<device-ip> -DeviceProfile unifiedLogin, system, network, protocol, peripherals, execution and runtime capabilities
Device Soakscripts/test-all.ps1 -Checks device-soak -BaseUrl http://<device-ip> -DeviceProfile unified -SoakRounds 100API loops, memory trends, auth stability and response time

Common local commands:

powershell
# Quick pre-commit check
powershell -ExecutionPolicy Bypass -Command ".\scripts\test-all.ps1 -Checks static,build"

# Full local matrix, no real device access
powershell -ExecutionPolicy Bypass -Command ".\scripts\test-all.ps1 -Checks static,native,build,artifacts"

# Single native test
pio test -e native -f test_web_api

High-Risk Change Checklist ​

TypeRiskMust Check
WiFi Mode SwitchStack overflow, state oscillation, provisioning entry lossProhibit unconstrained AP+STA oscillation; clean state before mode switch
MQTT Connection ManagementPointless retries on disconnect, memory consumption, main loop blockingisNetworkConnected() gating, backoff reconnect, low-memory pause
Memory AllocationHeap fragmentation, max contiguous block insufficient, task stack overflowPrefer PSRAM for large objects, low-memory degradation, avoid high-frequency allocation
platformio.ini DependenciesUnused libraries compiled, Flash bloat, chip incompatibilityCheck lib_deps, lib_ignore, macros and multi-chip build
Web/API FieldsFrontend display anomalies, test matrix mismatch, old config incompatibilitySync UI, default config, import/export, API tests
OTA/File SystemPower loss corruption, partition mismatch, recovery failurePower-loss recovery, checksum failure path, old firmware rollback

Regression Test Standards ​

Every bug fix should include a corresponding test. Test files are organized by module and registered in test/run_tests.cpp or the current test entry.

Bug TypeTest Recommendation
Logic ErrorBehavioral unit test or source regression test
State Machine ErrorState transition simulation test
Memory IssuesHeap threshold, low-memory protection or long-term stability test
Config ErrorsDefault config, import/export, invalid field tests
Multi-Module CollaborationE2E scenario tests
Performance DegradationPerformance benchmark or soak metrics

When adding a device API, update scripts/device-api-test-matrix.json and run at least one smoke test on the lowest-resource applicable environment plus any affected chip-specific environment.

Git Commit Requirements ​

  • One commit per issue, fix and corresponding test in the same commit.
  • Use Conventional Commits for commit messages, e.g., fix(network): fall back to pure AP mode after STA failure.
  • Commit body should describe root cause, changes, verification commands and impact scope.
  • Do not mix unrelated formatting, doc syncs and feature fixes in one commit.

AI-Assisted Development Notes ​

  • When making requests, prefer providing symptoms, logs, expected behavior and reproduction steps.
  • When reviewing changes, check if call sites, state machines, log formats, tests and documentation are in sync.
  • AI cannot replace hardware verification; WiFi, MQTT, memory trends, multi-device concurrency and specific sensor compatibility still require real device confirmation.

FastBee | fastbee.cn