From 36cc54f015f5c6089e53be280bef0f7d95468834 Mon Sep 17 00:00:00 2001 From: David Lafreniere Date: Sun, 15 Nov 2026 08:14:27 -0800 Subject: [PATCH] PlatformIO example and CI; FaultHandler weak and halting (v1.2.0) - examples/platformio/statemachine-demo: Motor state machine through its states plus 1000 events (event data deleted by the state machine), for ESP32, ESP32-C3, Nucleo-F401RE, STM32F4 Discovery, Pico and native. - PlatformIO CI workflow builds every board and runs native. - Fault.cpp: FaultHandler is weak on GCC/Clang (an application or another library can provide its own) and calls abort() after assert. It used to end in while(1), which hung desktop builds, and returned nothing useful under NDEBUG. DebugBreak() only with a debugger attached. - README: owner-qualified lib_deps (endurodave/StateMachine), example, FaultHandler, PlatformIO badge. .gitignore: .pio/. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/platformio.yml | 59 ++++++++++ .gitignore | 5 +- Fault.cpp | 30 ++++-- README.md | 19 +++- .../statemachine-demo/platformio.ini | 56 ++++++++++ .../statemachine-demo/src/Motor.cpp | 68 ++++++++++++ .../platformio/statemachine-demo/src/Motor.h | 60 +++++++++++ .../platformio/statemachine-demo/src/main.cpp | 101 ++++++++++++++++++ library.json | 59 ++++++++-- 9 files changed, 440 insertions(+), 17 deletions(-) create mode 100644 .github/workflows/platformio.yml create mode 100644 examples/platformio/statemachine-demo/platformio.ini create mode 100644 examples/platformio/statemachine-demo/src/Motor.cpp create mode 100644 examples/platformio/statemachine-demo/src/Motor.h create mode 100644 examples/platformio/statemachine-demo/src/main.cpp diff --git a/.github/workflows/platformio.yml b/.github/workflows/platformio.yml new file mode 100644 index 0000000..e50f567 --- /dev/null +++ b/.github/workflows/platformio.yml @@ -0,0 +1,59 @@ +name: PlatformIO + +# Builds examples/platformio/statemachine-demo for every board in its +# platformio.ini, and runs the native build on the desktop. The example's +# lib_deps points at this checkout, so each push tests the library as +# PlatformIO users consume it (library.json, srcFilter). + +on: + push: + branches: + - master + pull_request: + branches: + - master + +# Least privilege for GITHUB_TOKEN: these jobs only check out code. +permissions: + contents: read + +jobs: + build: + name: ${{ matrix.env }} + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + env: [esp32dev, esp32-c3, nucleo_f401re, disco_f407vg, pico, native] + + defaults: + run: + working-directory: examples/platformio/statemachine-demo + + steps: + - name: Checkout code + uses: actions/checkout@v7 + + - name: Cache PlatformIO + uses: actions/cache@v4 + with: + path: | + ~/.cache/pip + ~/.platformio + key: pio-${{ matrix.env }}-${{ hashFiles('examples/platformio/statemachine-demo/platformio.ini') }} + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install PlatformIO + run: pip install --upgrade platformio + + - name: Build + run: pio run -e ${{ matrix.env }} + + - name: Run (native) + if: matrix.env == 'native' + run: pio run -e native -t exec diff --git a/.gitignore b/.gitignore index 4485e1f..1423ce2 100644 --- a/.gitignore +++ b/.gitignore @@ -303,4 +303,7 @@ __pycache__/ *.xsd.cs # OpenCover UI analysis results -OpenCover/ \ No newline at end of file +OpenCover/ + +# PlatformIO +.pio/ diff --git a/Fault.cpp b/Fault.cpp index c022024..56affe0 100644 --- a/Fault.cpp +++ b/Fault.cpp @@ -1,22 +1,36 @@ #include "Fault.h" #include "DataTypes.h" - -#if WIN32 #include +#include + +// The default FaultHandler. On GCC and Clang it is a weak symbol: define your +// own FaultHandler() (e.g. to log and reset) and it replaces this one. That +// also lets StateMachine link with other libraries that provide a +// FaultHandler (C_Allocator, SimpleSocketProtocol). +#if defined(__GNUC__) || defined(__clang__) + #define FAULT_WEAK __attribute__((weak)) +#else + #define FAULT_WEAK #endif //---------------------------------------------------------------------------- // FaultHandler //---------------------------------------------------------------------------- -void FaultHandler(const char* file, unsigned short line) +FAULT_WEAK void FaultHandler(const char* file, unsigned short line) { + (void)file; + (void)line; + // If you hit this line, it means one of the ASSERT macros failed. #if WIN32 - DebugBreak(); + // Without a debugger attached, DebugBreak() would just crash the program + if (IsDebuggerPresent()) + DebugBreak(); +#endif assert(0); -#endif - - // Trap fault here - while(1); + + // assert() does nothing with NDEBUG (e.g. the STM32 Arduino core defines + // it): a fault must not return to the code that detected it + abort(); } diff --git a/README.md b/README.md index 609a03b..aba9c6f 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ [![Ubuntu](https://github.com/endurodave/StateMachine/actions/workflows/cmake_ubuntu.yml/badge.svg)](https://github.com/endurodave/StateMachine/actions/workflows/cmake_ubuntu.yml) [![Clang](https://github.com/endurodave/StateMachine/actions/workflows/cmake_clang.yml/badge.svg)](https://github.com/endurodave/StateMachine/actions/workflows/cmake_clang.yml) [![Windows](https://github.com/endurodave/StateMachine/actions/workflows/cmake_windows.yml/badge.svg)](https://github.com/endurodave/StateMachine/actions/workflows/cmake_windows.yml) +[![PlatformIO](https://github.com/endurodave/StateMachine/actions/workflows/platformio.yml/badge.svg)](https://github.com/endurodave/StateMachine/actions/workflows/platformio.yml) # State Machine Design in C++ A compact C++ finite state machine (FSM) implementation that's easy to use on embedded and PC-based systems. @@ -65,7 +66,23 @@ Related repositories containing alternative state machine implementations. `cmake -B Build .` 3. Build and run the project within the `Build` directory. -**PlatformIO:** add `lib_deps = StateMachine` to `platformio.ini`. The library builds `StateMachine.cpp` and `Fault.cpp`; the Motor, Player and Centrifuge demos aren't included. RTTI is optional: with RTTI, sending a state function the wrong event data type faults at run time; without it (`-fno-rtti`, the Arduino and ESP32 default) that check is skipped. A C++ standard library is required, so 8-bit AVR boards such as the Uno aren't supported. +**PlatformIO:** StateMachine is in the [PlatformIO registry](https://registry.platformio.org/libraries/endurodave/StateMachine). Add it to `platformio.ini`: + +```ini +lib_deps = endurodave/StateMachine@^1.2.0 +``` + +The library builds `StateMachine.cpp` and `Fault.cpp`; the Motor, Player and Centrifuge demos in the repository root aren't included. RTTI is optional: with RTTI, sending a state function the wrong event data type faults at run time; without it (`-fno-rtti`, the Arduino and ESP32 default) that check is skipped. A C++ standard library is required, so 8-bit AVR boards such as the Uno aren't supported. + +The [statemachine-demo](https://github.com/endurodave/StateMachine/tree/master/examples/platformio/statemachine-demo) example drives the Motor state machine through its states, then sends 1000 events to check that every event's data is deleted. It runs on ESP32, ESP32-C3, STM32 Nucleo-F401RE, STM32F4 Discovery, Raspberry Pi Pico and the desktop: + +```shell +cd examples/platformio/statemachine-demo +pio run -e esp32dev -t upload -t monitor +pio run -e native -t exec +``` + +A failed check (`ASSERT`, e.g. an event that `CANNOT_HAPPEN`) calls `FaultHandler(file, line)`, which halts (`abort()`), also in builds with `NDEBUG`. It is a weak symbol on GCC and Clang: define your own `extern "C" void FaultHandler(const char* file, unsigned short line)` to log or reset instead. # Introduction diff --git a/examples/platformio/statemachine-demo/platformio.ini b/examples/platformio/statemachine-demo/platformio.ini new file mode 100644 index 0000000..08127c5 --- /dev/null +++ b/examples/platformio/statemachine-demo/platformio.ini @@ -0,0 +1,56 @@ +; StateMachine PlatformIO example, also the board build matrix. +; +; pio run build every board below +; pio run -e esp32dev build one board +; pio run -e esp32dev -t upload -t monitor +; pio run -e native -t exec build and run on the desktop +; +; Copying this example into your own project? Change lib_deps to +; lib_deps = endurodave/StateMachine@^1.2.0 +; (here it points at this repository so every commit is tested). +; +; Needs a C++ compiler with the C++ standard library, so 8-bit AVR is not +; supported. + +[env] +lib_deps = symlink://../../.. +monitor_speed = 115200 + +; ESP32 (Xtensa) +[env:esp32dev] +platform = espressif32 +board = esp32dev +framework = arduino + +; ESP32-C3 (RISC-V) +[env:esp32-c3] +platform = espressif32 +board = esp32-c3-devkitm-1 +framework = arduino + +; STM32 Nucleo-F401RE (Cortex-M4) +[env:nucleo_f401re] +platform = ststm32 +board = nucleo_f401re +framework = arduino + +; STM32F4 Discovery (STM32F407VG Cortex-M4). +; Flashed over its ST-LINK/V2, which has no USB serial port: Serial goes to +; USART6 (TX PC6, RX PC7), 115200 8N1, through a 3.3 V USB-UART adapter. +[env:disco_f407vg] +platform = ststm32 +board = disco_f407vg +framework = arduino +upload_protocol = stlink +build_flags = -DSERIAL_UART_INSTANCE=6 -DPIN_SERIAL_TX=PC6 -DPIN_SERIAL_RX=PC7 + +; Raspberry Pi Pico (RP2040 Cortex-M0+) +[env:pico] +platform = https://github.com/maxgerhardt/platform-raspberrypi.git +board = pico +board_build.core = earlephilhower +framework = arduino + +; Desktop (Linux, or Windows with MinGW) +[env:native] +platform = native diff --git a/examples/platformio/statemachine-demo/src/Motor.cpp b/examples/platformio/statemachine-demo/src/Motor.cpp new file mode 100644 index 0000000..5e53e9e --- /dev/null +++ b/examples/platformio/statemachine-demo/src/Motor.cpp @@ -0,0 +1,68 @@ +#include "Motor.h" +#include + +static void NoLog(const char*) {} +void (*Motor::Log)(const char* msg) = NoLog; + +Motor::Motor() : + StateMachine(ST_MAX_STATES), + m_currentSpeed(0) +{ +} + +// Set motor speed external event +void Motor::SetSpeed(MotorData* data) +{ + BEGIN_TRANSITION_MAP // - Current State - + TRANSITION_MAP_ENTRY (ST_START) // ST_IDLE + TRANSITION_MAP_ENTRY (CANNOT_HAPPEN) // ST_STOP + TRANSITION_MAP_ENTRY (ST_CHANGE_SPEED) // ST_START + TRANSITION_MAP_ENTRY (ST_CHANGE_SPEED) // ST_CHANGE_SPEED + END_TRANSITION_MAP(data) +} + +// Halt motor external event +void Motor::Halt() +{ + BEGIN_TRANSITION_MAP // - Current State - + TRANSITION_MAP_ENTRY (EVENT_IGNORED) // ST_IDLE + TRANSITION_MAP_ENTRY (CANNOT_HAPPEN) // ST_STOP + TRANSITION_MAP_ENTRY (ST_STOP) // ST_START + TRANSITION_MAP_ENTRY (ST_STOP) // ST_CHANGE_SPEED + END_TRANSITION_MAP(NULL) +} + +// State machine sits here when motor is not running +STATE_DEFINE(Motor, Idle, NoEventData) +{ + Log("Motor::ST_Idle"); +} + +// Stop the motor +STATE_DEFINE(Motor, Stop, NoEventData) +{ + Log("Motor::ST_Stop"); + m_currentSpeed = 0; + + // Perform the stop motor processing here + // Transition to ST_Idle via an internal event + InternalEvent(ST_IDLE); +} + +// Start the motor going +STATE_DEFINE(Motor, Start, MotorData) +{ + char buf[48]; + snprintf(buf, sizeof(buf), "Motor::ST_Start : Speed is %d", (int)data->speed); + Log(buf); + m_currentSpeed = data->speed; +} + +// Changes the motor speed once the motor is moving +STATE_DEFINE(Motor, ChangeSpeed, MotorData) +{ + char buf[48]; + snprintf(buf, sizeof(buf), "Motor::ST_ChangeSpeed : Speed is %d", (int)data->speed); + Log(buf); + m_currentSpeed = data->speed; +} diff --git a/examples/platformio/statemachine-demo/src/Motor.h b/examples/platformio/statemachine-demo/src/Motor.h new file mode 100644 index 0000000..233de53 --- /dev/null +++ b/examples/platformio/statemachine-demo/src/Motor.h @@ -0,0 +1,60 @@ +// Motor state machine: Idle -> Start -> ChangeSpeed -> Stop -> Idle. +// The same state machine as Motor.h in the repository root, logging through +// a callback instead of std::cout so it shows on an Arduino serial port. + +#ifndef _MOTOR_H +#define _MOTOR_H + +#include "StateMachine.h" + +class MotorData : public EventData +{ +public: + INT speed; +}; + +class Motor : public StateMachine +{ +public: + Motor(); + + // External events taken by this state machine + void SetSpeed(MotorData* data); + void Halt(); + + INT GetSpeed() const { return m_currentSpeed; } + + // Called with a line of text on every state change + static void (*Log)(const char* msg); + + // State enumeration order must match the order of state method entries + // in the state map. + enum States + { + ST_IDLE, + ST_STOP, + ST_START, + ST_CHANGE_SPEED, + ST_MAX_STATES + }; + +private: + INT m_currentSpeed; + + // Define the state machine state functions with event data type + STATE_DECLARE(Motor, Idle, NoEventData) + STATE_DECLARE(Motor, Stop, NoEventData) + STATE_DECLARE(Motor, Start, MotorData) + STATE_DECLARE(Motor, ChangeSpeed, MotorData) + + // State map to define state object order. Each state map entry defines a + // state object. + BEGIN_STATE_MAP + STATE_MAP_ENTRY(&Idle) + STATE_MAP_ENTRY(&Stop) + STATE_MAP_ENTRY(&Start) + STATE_MAP_ENTRY(&ChangeSpeed) + END_STATE_MAP +}; + +#endif diff --git a/examples/platformio/statemachine-demo/src/main.cpp b/examples/platformio/statemachine-demo/src/main.cpp new file mode 100644 index 0000000..e7f7386 --- /dev/null +++ b/examples/platformio/statemachine-demo/src/main.cpp @@ -0,0 +1,101 @@ +// StateMachine PlatformIO example: a motor state machine driven by external +// events, with typed event data. Runs on Arduino boards and the desktop +// (native). +// +// Event data is created with new and deleted by the state machine after the +// state function runs. +// +// @see https://github.com/endurodave/StateMachine + +#include "Motor.h" +#include + +#ifdef ARDUINO +#include +#endif + +// Set while Stress() runs, so its 1000 state changes are not logged +static bool quiet = false; + +static void Log(const char* msg) +{ + if (quiet) + return; +#ifdef ARDUINO + Serial.println(msg); +#else + printf("%s\n", msg); +#endif +} + +static void SetSpeed(Motor& motor, INT speed) +{ + MotorData* data = new MotorData(); // deleted by the state machine + data->speed = speed; + motor.SetSpeed(data); +} + +static bool Demo() +{ + Motor motor; + bool ok = true; + + SetSpeed(motor, 100); // Idle -> Start + ok = ok && motor.GetCurrentState() == Motor::ST_START && motor.GetSpeed() == 100; + SetSpeed(motor, 200); // Start -> ChangeSpeed + ok = ok && motor.GetCurrentState() == Motor::ST_CHANGE_SPEED && motor.GetSpeed() == 200; + motor.Halt(); // ChangeSpeed -> Stop -> Idle + ok = ok && motor.GetCurrentState() == Motor::ST_IDLE && motor.GetSpeed() == 0; + motor.Halt(); // ignored in Idle + ok = ok && motor.GetCurrentState() == Motor::ST_IDLE; + return ok; +} + +// Many events: each event's data must be deleted again, or the heap runs out +static bool Stress() +{ + Motor motor; + quiet = true; + bool ok = true; + for (INT i = 1; i <= 1000 && ok; i++) + { + SetSpeed(motor, i); + ok = motor.GetSpeed() == i; + if (i % 100 == 0) + { + motor.Halt(); + ok = ok && motor.GetCurrentState() == Motor::ST_IDLE; + } + } + quiet = false; + Log(ok ? "1000 events processed" : "stress test failed"); + return ok; +} + +static bool Run() +{ + Motor::Log = Log; + bool ok = Demo() && Stress(); + Log(ok ? "StateMachine demo PASSED" : "StateMachine demo FAILED"); + return ok; +} + +#ifdef ARDUINO +void setup() +{ + Serial.begin(115200); + delay(1000); + Log("StateMachine demo"); + Run(); +} + +void loop() +{ +} +#else +int main() +{ + Log("StateMachine demo"); + return Run() ? 0 : 1; +} +#endif diff --git a/library.json b/library.json index 96e7a58..e019bec 100644 --- a/library.json +++ b/library.json @@ -1,21 +1,66 @@ { "name": "StateMachine", - "version": "1.1.0", + "version": "1.2.0", "description": "Compact C++ finite state machine for embedded systems. Table-driven, guard/entry/exit actions, typed event data, no dependencies.", - "keywords": ["state machine", "fsm", "hsm", "embedded", "cpp", "event driven"], - "repository": { "type": "git", "url": "https://github.com/endurodave/StateMachine.git" }, - "authors": [{ "name": "David Lafreniere", "url": "https://github.com/endurodave", "maintainer": true }], + "keywords": [ + "state machine", + "fsm", + "hsm", + "embedded", + "cpp", + "event driven" + ], + "repository": { + "type": "git", + "url": "https://github.com/endurodave/StateMachine.git" + }, + "authors": [ + { + "name": "David Lafreniere", + "url": "https://github.com/endurodave", + "maintainer": true + } + ], "license": "MIT", "homepage": "https://github.com/endurodave/StateMachine", "frameworks": "*", "platforms": "*", "headers": "StateMachine.h", "export": { - "include": ["StateMachine.cpp", "StateMachine.h", "Fault.cpp", "Fault.h", "DataTypes.h", "LICENSE", "README.md", "library.json"] + "include": [ + "StateMachine.cpp", + "StateMachine.h", + "Fault.cpp", + "Fault.h", + "DataTypes.h", + "LICENSE", + "README.md", + "library.json", + "examples/platformio/statemachine-demo/platformio.ini", + "examples/platformio/statemachine-demo/src/main.cpp", + "examples/platformio/statemachine-demo/src/Motor.cpp", + "examples/platformio/statemachine-demo/src/Motor.h" + ] }, "build": { "srcDir": ".", "includeDir": ".", - "srcFilter": ["-<*>", "+", "+"] - } + "srcFilter": [ + "-<*>", + "+", + "+" + ] + }, + "examples": [ + { + "name": "statemachine-demo", + "base": "examples/platformio/statemachine-demo", + "files": [ + "platformio.ini", + "src/main.cpp", + "src/Motor.cpp", + "src/Motor.h" + ] + } + ] }