Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions .github/workflows/platformio.yml
Original file line number Diff line number Diff line change
@@ -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
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -303,4 +303,7 @@ __pycache__/
*.xsd.cs

# OpenCover UI analysis results
OpenCover/
OpenCover/

# PlatformIO
.pio/
30 changes: 22 additions & 8 deletions Fault.cpp
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
#include "Fault.h"
#include "DataTypes.h"

#if WIN32
#include <assert.h>
#include <stdlib.h>

// 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();
}
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down
56 changes: 56 additions & 0 deletions examples/platformio/statemachine-demo/platformio.ini
Original file line number Diff line number Diff line change
@@ -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
68 changes: 68 additions & 0 deletions examples/platformio/statemachine-demo/src/Motor.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include "Motor.h"
#include <stdio.h>

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;
}
60 changes: 60 additions & 0 deletions examples/platformio/statemachine-demo/src/Motor.h
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading