[
  {
    "path": ".github/workflows/cmake_clang.yml",
    "content": "name: Clang\n\non:\n  push:\n    branches:\n      - master  # Trigger on push to 'master' branch\n  pull_request:\n    branches:\n      - master  # Trigger on pull request targeting 'master' branch\n\njobs:\n  build:\n    runs-on: ubuntu-latest  # Use Ubuntu environment for the build\n\n    steps:\n    - name: Checkout code\n      uses: actions/checkout@v2  # Checkout the repository code\n\n    - name: Configure CMake with Clang\n      run: cmake -S . -B Build -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++  # Configure CMake with Clang as the compiler\n\n    - name: Build\n      run: cmake --build Build  # Build the project using CMake\n\n    - name: Run C_StateMachineApp\n      run: ./Build/C_StateMachineApp  # Run the built executable\n"
  },
  {
    "path": ".github/workflows/cmake_ubuntu.yml",
    "content": "name: Ubuntu\n\non:\n  push:\n    branches:\n      - master  # Trigger on push to 'master' branch\n  pull_request:\n    branches:\n      - master  # Trigger on pull request targeting 'master' branch\n\njobs:\n  build:\n    runs-on: ubuntu-latest  # Use Ubuntu environment for the build\n\n    steps:\n    - name: Checkout code\n      uses: actions/checkout@v2  # Checkout the repository code\n\n    - name: Configure CMake\n      run: cmake -S . -B Build  # Configure CMake to generate build files in 'Build' directory\n\n    - name: Build\n      run: cmake --build Build  # Build the project using CMake\n\n    - name: Run C_StateMachineApp\n      run: ./Build/C_StateMachineApp  # Run the built executable\n"
  },
  {
    "path": ".github/workflows/cmake_windows.yml",
    "content": "name: Windows\n\non:\n  push:\n    branches:\n      - master  # Trigger on push to 'main' branch\n  pull_request:\n    branches:\n      - master  # Trigger on pull request targeting 'main' branch\n\njobs:\n  build:\n    runs-on: windows-latest  # Use Windows environment for the build\n\n    steps:\n    - name: Checkout code\n      uses: actions/checkout@v2  # Checkout the repository code\n\n    - name: Set up Visual Studio\n      uses: microsoft/setup-msbuild@v1.1  # Set up Visual Studio environment (MSBuild)\n\n    - name: Configure CMake\n      run: cmake -S . -B Build -G \"Visual Studio 17 2022\" -A Win32 # Configure CMake for Visual Studio\n\n    - name: Build\n      run: cmake --build Build --config Release  # Build the project using CMake with Release configuration\n\n    - name: Run C_StateMachineApp\n      run: .\\Build\\Release\\C_StateMachineApp.exe  # Run the built executable (adjust path for MSBuild)\n"
  },
  {
    "path": ".gitignore",
    "content": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n##\n## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore\n\n# User-specific files\n*.suo\n*.user\n*.userosscache\n*.sln.docstates\n\n# User-specific files (MonoDevelop/Xamarin Studio)\n*.userprefs\n\n# Build results\nBuild\n[Dd]ebug/\n[Dd]ebugPublic/\n[Rr]elease/\n[Rr]eleases/\nx64/\nx86/\nbld/\n[Bb]in/\n[Oo]bj/\n[Ll]og/\n\n# Visual Studio 2015 cache/options directory\n.vs/\n# Uncomment if you have tasks that create the project's static files in wwwroot\n#wwwroot/\n\n# MSTest test Results\n[Tt]est[Rr]esult*/\n[Bb]uild[Ll]og.*\n\n# NUNIT\n*.VisualState.xml\nTestResult.xml\n\n# Build Results of an ATL Project\n[Dd]ebugPS/\n[Rr]eleasePS/\ndlldata.c\n\n# Benchmark Results\nBenchmarkDotNet.Artifacts/\n\n# .NET Core\nproject.lock.json\nproject.fragment.lock.json\nartifacts/\n**/Properties/launchSettings.json\n\n*_i.c\n*_p.c\n*_i.h\n*.ilk\n*.meta\n*.obj\n*.pch\n*.pdb\n*.pgc\n*.pgd\n*.rsp\n*.sbr\n*.tlb\n*.tli\n*.tlh\n*.tmp\n*.tmp_proj\n*.log\n*.vspscc\n*.vssscc\n.builds\n*.pidb\n*.svclog\n*.scc\n\n# Chutzpah Test files\n_Chutzpah*\n\n# Visual C++ cache files\nipch/\n*.aps\n*.ncb\n*.opendb\n*.opensdf\n*.sdf\n*.cachefile\n*.VC.db\n*.VC.VC.opendb\n\n# Visual Studio profiler\n*.psess\n*.vsp\n*.vspx\n*.sap\n\n# Visual Studio Trace Files\n*.e2e\n\n# TFS 2012 Local Workspace\n$tf/\n\n# Guidance Automation Toolkit\n*.gpState\n\n# ReSharper is a .NET coding add-in\n_ReSharper*/\n*.[Rr]e[Ss]harper\n*.DotSettings.user\n\n# JustCode is a .NET coding add-in\n.JustCode\n\n# TeamCity is a build add-in\n_TeamCity*\n\n# DotCover is a Code Coverage Tool\n*.dotCover\n\n# AxoCover is a Code Coverage Tool\n.axoCover/*\n!.axoCover/settings.json\n\n# Visual Studio code coverage results\n*.coverage\n*.coveragexml\n\n# NCrunch\n_NCrunch_*\n.*crunch*.local.xml\nnCrunchTemp_*\n\n# MightyMoose\n*.mm.*\nAutoTest.Net/\n\n# Web workbench (sass)\n.sass-cache/\n\n# Installshield output folder\n[Ee]xpress/\n\n# DocProject is a documentation generator add-in\nDocProject/buildhelp/\nDocProject/Help/*.HxT\nDocProject/Help/*.HxC\nDocProject/Help/*.hhc\nDocProject/Help/*.hhk\nDocProject/Help/*.hhp\nDocProject/Help/Html2\nDocProject/Help/html\n\n# Click-Once directory\npublish/\n\n# Publish Web Output\n*.[Pp]ublish.xml\n*.azurePubxml\n# Note: Comment the next line if you want to checkin your web deploy settings,\n# but database connection strings (with potential passwords) will be unencrypted\n*.pubxml\n*.publishproj\n\n# Microsoft Azure Web App publish settings. Comment the next line if you want to\n# checkin your Azure Web App publish settings, but sensitive information contained\n# in these scripts will be unencrypted\nPublishScripts/\n\n# NuGet Packages\n*.nupkg\n# The packages folder can be ignored because of Package Restore\n**/[Pp]ackages/*\n# except build/, which is used as an MSBuild target.\n!**/[Pp]ackages/build/\n# Uncomment if necessary however generally it will be regenerated when needed\n#!**/[Pp]ackages/repositories.config\n# NuGet v3's project.json files produces more ignorable files\n*.nuget.props\n*.nuget.targets\n\n# Microsoft Azure Build Output\ncsx/\n*.build.csdef\n\n# Microsoft Azure Emulator\necf/\nrcf/\n\n# Windows Store app package directories and files\nAppPackages/\nBundleArtifacts/\nPackage.StoreAssociation.xml\n_pkginfo.txt\n*.appx\n\n# Visual Studio cache files\n# files ending in .cache can be ignored\n*.[Cc]ache\n# but keep track of directories ending in .cache\n!*.[Cc]ache/\n\n# Others\nClientBin/\n~$*\n*~\n*.dbmdl\n*.dbproj.schemaview\n*.jfm\n*.pfx\n*.publishsettings\norleans.codegen.cs\n\n# Since there are multiple workflows, uncomment next line to ignore bower_components\n# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)\n#bower_components/\n\n# RIA/Silverlight projects\nGenerated_Code/\n\n# Backup & report files from converting an old project file\n# to a newer Visual Studio version. Backup files are not needed,\n# because we have git ;-)\n_UpgradeReport_Files/\nBackup*/\nUpgradeLog*.XML\nUpgradeLog*.htm\n\n# SQL Server files\n*.mdf\n*.ldf\n*.ndf\n\n# Business Intelligence projects\n*.rdl.data\n*.bim.layout\n*.bim_*.settings\n\n# Microsoft Fakes\nFakesAssemblies/\n\n# GhostDoc plugin setting file\n*.GhostDoc.xml\n\n# Node.js Tools for Visual Studio\n.ntvs_analysis.dat\nnode_modules/\n\n# Typescript v1 declaration files\ntypings/\n\n# Visual Studio 6 build log\n*.plg\n\n# Visual Studio 6 workspace options file\n*.opt\n\n# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)\n*.vbw\n\n# Visual Studio LightSwitch build output\n**/*.HTMLClient/GeneratedArtifacts\n**/*.DesktopClient/GeneratedArtifacts\n**/*.DesktopClient/ModelManifest.xml\n**/*.Server/GeneratedArtifacts\n**/*.Server/ModelManifest.xml\n_Pvt_Extensions\n\n# Paket dependency manager\n.paket/paket.exe\npaket-files/\n\n# FAKE - F# Make\n.fake/\n\n# JetBrains Rider\n.idea/\n*.sln.iml\n\n# CodeRush\n.cr/\n\n# Python Tools for Visual Studio (PTVS)\n__pycache__/\n*.pyc\n\n# Cake - Uncomment if you are using it\n# tools/**\n# !tools/packages.config\n\n# Tabs Studio\n*.tss\n\n# Telerik's JustMock configuration file\n*.jmconfig\n\n# BizTalk build output\n*.btp.cs\n*.btm.cs\n*.odx.cs\n*.xsd.cs\n\n# OpenCover UI analysis results\nOpenCover/"
  },
  {
    "path": "CMakeLists.txt",
    "content": "# Example CMake command line to create project build files:\n#\n# *** Windows ***\n# cmake -G \"Visual Studio 17 2022\" -A Win32 -B Build -S .\n#\n# *** Linux ***\n# cmake -G \"Unix Makefiles\" -B Build -S .\n\n# Specify the minimum CMake version required\ncmake_minimum_required(VERSION 3.10)\n\n# Project name and language (C or C++)\nproject(C_StateMachine VERSION 1.0 LANGUAGES C CXX)\n\n# Collect all source files in the current directory\nfile(GLOB SOURCES\n    \"${CMAKE_SOURCE_DIR}/*.cpp\"\n    \"${CMAKE_SOURCE_DIR}/*.c\"\n    \"${CMAKE_SOURCE_DIR}/*.h\"\n)\n\n# Add an executable target\nadd_executable(C_StateMachineApp ${SOURCES})\n\n\n\n"
  },
  {
    "path": "CentrifugeTest.c",
    "content": "#include \"CentrifugeTest.h\"\n#include \"StateMachine.h\"\n#include <stdio.h>\n\n// CentrifugeTest object structure\ntypedef struct\n{\n    INT speed;\n    BOOL pollActive;\n} CentrifugeTest;\n\n// Define private instance of motor state machine\nCentrifugeTest centrifugeTestObj;\nSM_DEFINE(CentrifugeTestSM, &centrifugeTestObj)\n\n// State enumeration order must match the order of state\n// method entries in the state map\nenum States\n{\n    ST_IDLE,\n    ST_COMPLETED,\n    ST_FAILED,\n    ST_START_TEST,\n    ST_ACCELERATION,\n    ST_WAIT_FOR_ACCELERATION,\n    ST_DECELERATION,\n    ST_WAIT_FOR_DECELERATION,\n    ST_MAX_STATES\n};\n\n// State machine state functions\nSTATE_DECLARE(Idle, NoEventData)\nENTRY_DECLARE(Idle, NoEventData)\nSTATE_DECLARE(Completed, NoEventData)\nSTATE_DECLARE(Failed, NoEventData)\nSTATE_DECLARE(StartTest, NoEventData)\nGUARD_DECLARE(StartTest, NoEventData)\nSTATE_DECLARE(Acceleration, NoEventData)\nSTATE_DECLARE(WaitForAcceleration, NoEventData)\nEXIT_DECLARE(WaitForAcceleration)\nSTATE_DECLARE(Deceleration, NoEventData)\nSTATE_DECLARE(WaitForDeceleration, NoEventData)\nEXIT_DECLARE(WaitForDeceleration)\n\n// State map to define state function order\nBEGIN_STATE_MAP_EX(CentrifugeTest)\n    STATE_MAP_ENTRY_ALL_EX(ST_Idle, 0, EN_Idle, 0)\n    STATE_MAP_ENTRY_EX(ST_Completed)\n    STATE_MAP_ENTRY_EX(ST_Failed)\n    STATE_MAP_ENTRY_ALL_EX(ST_StartTest, GD_StartTest, 0, 0)\n    STATE_MAP_ENTRY_EX(ST_Acceleration)\n    STATE_MAP_ENTRY_ALL_EX(ST_WaitForAcceleration, 0, 0, EX_WaitForAcceleration)\n    STATE_MAP_ENTRY_EX(ST_Deceleration)\n    STATE_MAP_ENTRY_ALL_EX(ST_WaitForDeceleration, 0, 0, EX_WaitForDeceleration)\nEND_STATE_MAP_EX(CentrifugeTest)\n\nEVENT_DEFINE(CFG_Start, NoEventData)\n{\n    BEGIN_TRANSITION_MAP                                // - Current State -\n        TRANSITION_MAP_ENTRY(ST_START_TEST)             // ST_IDLE\n        TRANSITION_MAP_ENTRY(CANNOT_HAPPEN)             // ST_COMPLETED\n        TRANSITION_MAP_ENTRY(CANNOT_HAPPEN)             // ST_FAILED\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)             // ST_START_TEST\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)             // ST_ACCELERATION\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)             // ST_WAIT_FOR_ACCELERATION\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)             // ST_DECELERATION\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)             // ST_WAIT_FOR_DECELERATION\n    END_TRANSITION_MAP(CentrifugeTest, pEventData)\n}\n\nEVENT_DEFINE(CFG_Cancel, NoEventData)\n{\n    BEGIN_TRANSITION_MAP                                // - Current State -\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)             // ST_IDLE\n        TRANSITION_MAP_ENTRY(CANNOT_HAPPEN)             // ST_COMPLETED\n        TRANSITION_MAP_ENTRY(CANNOT_HAPPEN)             // ST_FAILED\n        TRANSITION_MAP_ENTRY(ST_FAILED)                 // ST_START_TEST\n        TRANSITION_MAP_ENTRY(ST_FAILED)                 // ST_ACCELERATION\n        TRANSITION_MAP_ENTRY(ST_FAILED)                 // ST_WAIT_FOR_ACCELERATION\n        TRANSITION_MAP_ENTRY(ST_FAILED)                 // ST_DECELERATION\n        TRANSITION_MAP_ENTRY(ST_FAILED)                 // ST_WAIT_FOR_DECELERATION\n    END_TRANSITION_MAP(CentrifugeTest, pEventData)\n}\n\nEVENT_DEFINE(CFG_Poll, NoEventData)\n{\n    BEGIN_TRANSITION_MAP                                    // - Current State -\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)                 // ST_IDLE\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)                 // ST_COMPLETED\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)                 // ST_FAILED\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)                 // ST_START_TEST\n        TRANSITION_MAP_ENTRY(ST_WAIT_FOR_ACCELERATION)      // ST_ACCELERATION\n        TRANSITION_MAP_ENTRY(ST_WAIT_FOR_ACCELERATION)      // ST_WAIT_FOR_ACCELERATION\n        TRANSITION_MAP_ENTRY(ST_WAIT_FOR_DECELERATION)      // ST_DECELERATION\n        TRANSITION_MAP_ENTRY(ST_WAIT_FOR_DECELERATION)      // ST_WAIT_FOR_DECELERATION\n    END_TRANSITION_MAP(CentrifugeTest, pEventData)\n}\n\nstatic void StartPoll(void)\n{\n    centrifugeTestObj.pollActive = TRUE;\n}\n\nstatic void StopPoll(void)\n{\n    centrifugeTestObj.pollActive = FALSE;\n}\n\nBOOL CFG_IsPollActive(void) \n{ \n    return centrifugeTestObj.pollActive;\n}\n\nSTATE_DEFINE(Idle, NoEventData)\n{\n    printf(\"%s ST_Idle\\n\", self->name);\n}\n\nENTRY_DEFINE(Idle, NoEventData)\n{\n    printf(\"%s EN_Idle\\n\", self->name);\n    centrifugeTestObj.speed = 0;\n    StopPoll();\n}\n\nSTATE_DEFINE(Completed, NoEventData)\n{\n    printf(\"%s ST_Completed\\n\", self->name);\n    SM_InternalEvent(ST_IDLE, NULL);\n}\n\nSTATE_DEFINE(Failed, NoEventData)\n{\n    printf(\"%s ST_Failed\\n\", self->name);\n    SM_InternalEvent(ST_IDLE, NULL);\n}\n\n// Start the centrifuge test state.\nSTATE_DEFINE(StartTest, NoEventData)\n{\n    printf(\"%s ST_StartTest\\n\", self->name);\n    SM_InternalEvent(ST_ACCELERATION, NULL);\n}\n\n// Guard condition to determine whether StartTest state is executed.\nGUARD_DEFINE(StartTest, NoEventData)\n{\n    printf(\"%s GD_StartTest\\n\", self->name);\n    if (centrifugeTestObj.speed == 0)\n        return TRUE;    // Centrifuge stopped. OK to start test.\n    else\n        return FALSE;   // Centrifuge spinning. Can't start test.\n}\n\n// Start accelerating the centrifuge.\nSTATE_DEFINE(Acceleration, NoEventData)\n{\n    printf(\"%s ST_Acceleration\\n\", self->name);\n\n    // Start polling while waiting for centrifuge to ramp up to speed\n    StartPoll();\n}\n\n// Wait in this state until target centrifuge speed is reached.\nSTATE_DEFINE(WaitForAcceleration, NoEventData)\n{\n    printf(\"%s ST_WaitForAcceleration : Speed is %d\\n\", self->name, centrifugeTestObj.speed);\n    if (++centrifugeTestObj.speed >= 5)\n        SM_InternalEvent(ST_DECELERATION, NULL);\n}\n\n// Exit action when WaitForAcceleration state exits.\nEXIT_DEFINE(WaitForAcceleration)\n{\n    printf(\"%s EX_WaitForAcceleration\\n\", self->name);\n\n    // Acceleration over, stop polling\n    StopPoll();\n}\n\n// Start decelerating the centrifuge.\nSTATE_DEFINE(Deceleration, NoEventData)\n{\n    printf(\"%s ST_Deceleration\\n\", self->name);\n\n    // Start polling while waiting for centrifuge to ramp down to 0\n    StartPoll();\n}\n\n// Wait in this state until centrifuge speed is 0.\nSTATE_DEFINE(WaitForDeceleration, NoEventData)\n{\n    printf(\"%s ST_WaitForDeceleration : Speed is %d\\n\", self->name, centrifugeTestObj.speed);\n    if (centrifugeTestObj.speed-- == 0)\n        SM_InternalEvent(ST_COMPLETED, NULL);\n}\n\n// Exit action when WaitForDeceleration state exits.\nEXIT_DEFINE(WaitForDeceleration)\n{\n    printf(\"%s EX_WaitForDeceleration\\n\", self->name);\n\n    // Deceleration over, stop polling\n    StopPoll();\n}\n\n\n"
  },
  {
    "path": "CentrifugeTest.h",
    "content": "#ifndef _CENTRIFUGE_TEST_H\n#define _CENTRIFUGE_TEST_H\n\n#include \"DataTypes.h\"\n#include \"StateMachine.h\"\n\n// Declare the private instance of CentrifugeTest state machine\nSM_DECLARE(CentrifugeTestSM)\n\n// State machine event functions\nEVENT_DECLARE(CFG_Start, NoEventData)\nEVENT_DECLARE(CFG_Cancel, NoEventData)\nEVENT_DECLARE(CFG_Poll, NoEventData)\n\nBOOL CFG_IsPollActive();\n\n#endif // _CENTRIFUGE_TEST_H\n"
  },
  {
    "path": "DataTypes.h",
    "content": "#ifndef _DATA_TYPES_H\n#define _DATA_TYPES_H\n\n#if WIN32\n\t#include \"windows.h\"\n#else\n\ttypedef signed char INT8;\n\ttypedef unsigned char UINT8;\n\ttypedef signed short INT16;\n\ttypedef unsigned short UINT16;\n\ttypedef unsigned int UINT32;\n\ttypedef int INT32;\n\ttypedef char CHAR;\n\ttypedef short SHORT;\n\ttypedef long LONG;\n\ttypedef int INT;\n\ttypedef unsigned int UINT;\n\ttypedef unsigned long DWORD;\n\ttypedef unsigned char BYTE;\n\ttypedef unsigned short WORD;\n\ttypedef float FLOAT;\n\ttypedef double DOUBLE;\n\ttypedef int BOOL;\n\n\t#ifndef NULL\n\t#ifdef __cplusplus\n\t#define NULL    0\n\t#else\n\t#define NULL    ((void *)0)\n\t#endif\n\t#endif\n\n\t#ifndef FALSE\n\t#define FALSE               0\n\t#endif\n\n\t#ifndef TRUE\n\t#define TRUE                1\n\t#endif\n#endif\n\n#endif\n"
  },
  {
    "path": "Fault.cpp",
    "content": "#include \"Fault.h\"\n#include <assert.h>\n#if WIN32\n\t#include \"windows.h\"\n#endif\n\n//----------------------------------------------------------------------------\n// FaultHandler\n//----------------------------------------------------------------------------\nvoid FaultHandler(const char* file, unsigned short line)\n{\n#if WIN32\n\t// If you hit this line, it means one of the ASSERT macros failed.\n    DebugBreak();\n#endif\n\n\tassert(0);\n}"
  },
  {
    "path": "Fault.h",
    "content": "#ifndef _FAULT_H\n#define _FAULT_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#pragma warning(disable : 4005)  // Disable warning C4005\n\n// Used for compile-time checking for array sizes. On Windows VC++, you get \n// an \"error C2118: negative subscript\" error. On GCC: size of \"unnamed array is negative\"\n#ifndef C_ASSERT\n//#define C_ASSERT(expr)  {char uname[(expr)?1:-1];uname[0]=0;}\t\t// Original macro\n#define C_ASSERT(expr)  ((void)sizeof(char[(expr) ? 1 : -1]))\t\t// New macro to fix GCC warning\n#endif\n\n#define ASSERT() \\\n\tFaultHandler(__FILE__, (unsigned short) __LINE__)\n\n#define ASSERT_TRUE(condition) \\\n\tdo {if (!(condition)) FaultHandler(__FILE__, (unsigned short) __LINE__);} while (0)\n\n\t/// Handles all software assertions in the system.\n\t/// @param[in] file - the file name that the software assertion occurred on\n\t/// @param[in] line - the line number that the software assertion occurred on\n\tvoid FaultHandler(const char* file, unsigned short line);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif \n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2022 David Lafreniere\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "LockGuard.cpp",
    "content": "#include \"LockGuard.h\"\n#include \"Fault.h\"\n#include <mutex>\n\n// A lock is a mutex\n#define LOCK std::mutex\n\n//------------------------------------------------------------------------------\n// LK_Create\n//------------------------------------------------------------------------------\nLOCK_HANDLE LK_Create(void)\n{\n    LOCK* lock = new LOCK;\n    return lock;\n}\n\n//------------------------------------------------------------------------------\n// LK_Destroy\n//------------------------------------------------------------------------------\nvoid LK_Destroy(LOCK_HANDLE hLock)\n{\n    ASSERT_TRUE(hLock);\n    LOCK* lock = (LOCK*)(hLock);\n    delete lock;\n}\n\n//------------------------------------------------------------------------------\n// LK_Lock\n//------------------------------------------------------------------------------\nvoid LK_Lock(LOCK_HANDLE hLock)\n{\n    ASSERT_TRUE(hLock);\n    LOCK* lock = (LOCK*)(hLock);\n\tlock->lock();\n}\n\n//------------------------------------------------------------------------------\n// LK_Unlock\n//------------------------------------------------------------------------------\nvoid LK_Unlock(LOCK_HANDLE hLock)\n{\n    ASSERT_TRUE(hLock);\n    LOCK* lock = (LOCK*)(hLock);\n    lock->unlock();\n}\n\n"
  },
  {
    "path": "LockGuard.h",
    "content": "#ifndef _LOCK_GUARD_H\n#define _LOCK_GUARD_H\n\n#include \"DataTypes.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef void* LOCK_HANDLE;\n\n#define LK_CREATE()     LK_Create()\n#define LK_DESTROY(h)   LK_Destroy(h)\n#define LK_LOCK(h)      LK_Lock(h)\n#define LK_UNLOCK(h)    LK_Unlock(h)\n\nLOCK_HANDLE LK_Create(void);\nvoid LK_Destroy(LOCK_HANDLE hLock);\nvoid LK_Lock(LOCK_HANDLE hLock);\nvoid LK_Unlock(LOCK_HANDLE hLock);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif \n"
  },
  {
    "path": "Motor.c",
    "content": "#include \"Motor.h\"\n#include \"StateMachine.h\"\n#include <stdio.h>\n\n// State enumeration order must match the order of state\n// method entries in the state map\nenum States\n{\n    ST_IDLE,\n    ST_STOP,\n    ST_START,\n    ST_CHANGE_SPEED,\n    ST_MAX_STATES\n};\n\n// State machine state functions\nSTATE_DECLARE(Idle, NoEventData)\nSTATE_DECLARE(Stop, NoEventData)\nSTATE_DECLARE(Start, MotorData)\nSTATE_DECLARE(ChangeSpeed, MotorData)\n\n// State map to define state function order\nBEGIN_STATE_MAP(Motor)\n    STATE_MAP_ENTRY(ST_Idle)\n    STATE_MAP_ENTRY(ST_Stop)\n    STATE_MAP_ENTRY(ST_Start)\n    STATE_MAP_ENTRY(ST_ChangeSpeed)\nEND_STATE_MAP(Motor)\n\n// Set motor speed external event\nEVENT_DEFINE(MTR_SetSpeed, MotorData)\n{\n    // Given the SetSpeed event, transition to a new state based upon \n    // the current state of the state machine\n    BEGIN_TRANSITION_MAP                        // - Current State -\n        TRANSITION_MAP_ENTRY(ST_START)          // ST_Idle       \n        TRANSITION_MAP_ENTRY(CANNOT_HAPPEN)     // ST_Stop       \n        TRANSITION_MAP_ENTRY(ST_CHANGE_SPEED)   // ST_Start      \n        TRANSITION_MAP_ENTRY(ST_CHANGE_SPEED)   // ST_ChangeSpeed\n    END_TRANSITION_MAP(Motor, pEventData)\n}\n\n// Halt motor external event\nEVENT_DEFINE(MTR_Halt, NoEventData)\n{\n    // Given the Halt event, transition to a new state based upon \n    // the current state of the state machine\n    BEGIN_TRANSITION_MAP                        // - Current State -\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)     // ST_Idle\n        TRANSITION_MAP_ENTRY(CANNOT_HAPPEN)     // ST_Stop\n        TRANSITION_MAP_ENTRY(ST_STOP)           // ST_Start\n        TRANSITION_MAP_ENTRY(ST_STOP)           // ST_ChangeSpeed\n    END_TRANSITION_MAP(Motor, pEventData)\n}\n\n// State machine sits here when motor is not running\nSTATE_DEFINE(Idle, NoEventData)\n{\n    printf(\"%s ST_Idle\\n\", self->name);\n}\n\n// Stop the motor \nSTATE_DEFINE(Stop, NoEventData)\n{\n    // Get pointer to the instance data and update currentSpeed\n    Motor* pInstance = SM_GetInstance(Motor);\n    pInstance->currentSpeed = 0;\n\n    // Perform the stop motor processing here\n    printf(\"%s ST_Stop: %d\\n\", self->name, pInstance->currentSpeed);\n\n    // Transition to ST_Idle via an internal event\n    SM_InternalEvent(ST_IDLE, NULL);\n}\n\n// Start the motor going\nSTATE_DEFINE(Start, MotorData)\n{\n    ASSERT_TRUE(pEventData);\n\n    // Get pointer to the instance data and update currentSpeed\n    Motor* pInstance = SM_GetInstance(Motor);\n    pInstance->currentSpeed = pEventData->speed;\n\n    // Set initial motor speed processing here\n    printf(\"%s ST_Start: %d\\n\", self->name, pInstance->currentSpeed);\n}\n\n// Changes the motor speed once the motor is moving\nSTATE_DEFINE(ChangeSpeed, MotorData)\n{\n    ASSERT_TRUE(pEventData);\n\n    // Get pointer to the instance data and update currentSpeed\n    Motor* pInstance = SM_GetInstance(Motor);\n    pInstance->currentSpeed = pEventData->speed;\n\n    // Perform the change motor speed here\n    printf(\"%s ST_ChangeSpeed: %d\\n\", self->name, pInstance->currentSpeed);\n}\n\n// Get current speed\nGET_DEFINE(MTR_GetSpeed, INT)\n{\n    Motor* pInstance = SM_GetInstance(Motor);\n    return pInstance->currentSpeed;\n}\n\n"
  },
  {
    "path": "Motor.h",
    "content": "#ifndef _MOTOR_H\n#define _MOTOR_H\n\n#include \"DataTypes.h\"\n#include \"StateMachine.h\"\n\n// Motor object structure\ntypedef struct\n{\n    INT currentSpeed;\n} Motor;\n\n// Event data structure\ntypedef struct\n{\n    INT speed;\n} MotorData;\n\n// State machine event functions\nEVENT_DECLARE(MTR_SetSpeed, MotorData)\nEVENT_DECLARE(MTR_Halt, NoEventData)\n\n// Public accessor\nGET_DECLARE(MTR_GetSpeed, INT);\n\n#endif // _MOTOR_H\n"
  },
  {
    "path": "README.md",
    "content": "![License MIT](https://img.shields.io/github/license/BehaviorTree/BehaviorTree.CPP?color=blue)\n[![conan Ubuntu](https://github.com/endurodave/C_StateMachine/actions/workflows/cmake_ubuntu.yml/badge.svg)](https://github.com/endurodave/C_StateMachine/actions/workflows/cmake_ubuntu.yml)\n[![conan Ubuntu](https://github.com/endurodave/C_StateMachine/actions/workflows/cmake_clang.yml/badge.svg)](https://github.com/endurodave/C_StateMachine/actions/workflows/cmake_clang.yml)\n[![conan Windows](https://github.com/endurodave/C_StateMachine/actions/workflows/cmake_windows.yml/badge.svg)](https://github.com/endurodave/C_StateMachine/actions/workflows/cmake_windows.yml)\n\n# State Machine Design in C\n\nA compact C finite state machine (FSM) implementation that's easy to use on embedded and PC-based systems.\n\n# Table of Contents\n\n- [State Machine Design in C](#state-machine-design-in-c)\n- [Table of Contents](#table-of-contents)\n- [Preface](#preface)\n  - [Related repositories](#related-repositories)\n- [Getting Started](#getting-started)\n- [Introduction](#introduction)\n  - [Background](#background)\n- [Why use a state machine?](#why-use-a-state-machine)\n- [State machine design](#state-machine-design)\n  - [Internal and external events](#internal-and-external-events)\n  - [Event data](#event-data)\n  - [State transitions](#state-transitions)\n- [StateMachine module](#statemachine-module)\n- [Motor example](#motor-example)\n  - [External events](#external-events)\n  - [State enumerations](#state-enumerations)\n  - [State functions](#state-functions)\n  - [State map](#state-map)\n  - [State machine objects](#state-machine-objects)\n  - [Transition map](#transition-map)\n  - [New state machine steps](#new-state-machine-steps)\n- [State engine](#state-engine)\n- [Generating events](#generating-events)\n- [No heap usage](#no-heap-usage)\n- [CentrifugeTest example](#centrifugetest-example)\n- [Multithread safety](#multithread-safety)\n- [Conclusion](#conclusion)\n- [References](#references)\n\n# Preface\n\nOriginally published on CodeProject at: <a href=\"https://www.codeproject.com/Articles/1275479/State-Machine-Design-in-C\"><strong>State Machine Design in C</strong></a>\n\nBased on original design published in C\\C++ Users Journal (Dr. Dobb's) at: <a href=\"http://www.drdobbs.com/cpp/state-machine-design-in-c/184401236\"><strong>State Machine Design in C++</strong></a>\n\n## Related repositories\n\nRelated repositories containing alternative state machine implementations.\n\n| Project | Description |\n  | :--- | :--- |\n| [**Active-Object State Machine in C++**](https://github.com/endurodave/active-fsm) | A compact active-object C++ finite state machine providing RAII-safe asynchronous dispatch and pub/sub signals. |\n  | [**C Language State Machine with Threads**](https://github.com/endurodave/C_StateMachineWithThreads) | A C language state machine with OS threads. |\n  | [**State Machine Design in C++**](https://github.com/endurodave/StateMachine) | A C++ finite state machine (FSM) implementation. |\n\n# Getting Started\n\n[CMake](https://cmake.org/) is used to create the project build files on any Windows or Linux machine. The state machine source code works on any C language compiler on any platform.\n\n1. Clone the repository.\n2. From the repository root, run the following CMake command:   \n   `cmake -B Build .`\n3. Build and run the project within the `Build` directory. \n\n# Introduction\n\n<p>In 2000, I wrote an article entitled &quot;<em>State Machine Design in C++</em>&quot; for C/C++ Users Journal (R.I.P.). Interestingly, that old article is still available and (at the time of writing this article) the #1 hit on Google when searching for C++ state machine. The article was written over 15 years ago, but I continue to use the basic idea on numerous projects. It&#39;s compact, easy to understand and, in most cases, has just enough features to accomplish what I need.</p>\n\n<p>Sometimes C is the right tool for the job. This article provides an alternate C language state machine implementation based on the ideas presented within the article &ldquo;<em>State Machine Design in C++</em>&rdquo;. The design is suitable for any platform, embedded or PC, with any C compiler. This state machine has the following features:</p>\n\n<ul>\n\t<li><strong>C language</strong> &ndash; state machine written in C</li>\n\t<li><strong>Compact </strong>&ndash; consumes a minimum amount of resources.</li>\n\t<li><strong>Objects</strong>&nbsp;&ndash; support&nbsp;multiple instantiations of a&nbsp;single state machine type.</li>\n\t<li><strong>Transition tables</strong> &ndash; transition tables precisely control state transition behavior.</li>\n\t<li><strong>Events </strong>&ndash; every event is a simple function with any argument types.</li>\n\t<li><strong>State action</strong> &ndash; every state action is a separate function with a single, unique event data argument if desired.</li>\n\t<li><strong>Guards/entry/exit actions</strong>&nbsp;&ndash; optionally a state machine can use guard conditions and separate entry/exit action functions for each state.</li>\n\t<li><strong>Macros </strong>&ndash; optional multiline macro support simplifies usage by automating the code &quot;machinery&quot;.</li>\n\t<li><strong>Error checking</strong> &ndash; compile time and runtime checks catch mistakes early.</li>\n\t<li><strong>Thread-safe</strong> &ndash; adding software locks to make the code thread-safe is easy.</li>\n</ul>\n\n<p>The article is not a tutorial on the best design decomposition practices for software state machines. I&#39;ll be focusing on state machine code and simple examples with just enough complexity to facilitate understanding the features and usage.</p>\n\n## Background\n\n<p>A common design technique in the repertoire of most programmers is the venerable finite state machine (FSM). Designers use this programming construct to break complex problems into manageable states and state transitions. There are innumerable ways to implement a state machine.</p>\n\n<p>A switch statement provides one of the easiest to implement and most common version of a state machine. Here, each case within the switch statement becomes a state, implemented something like:</p>\n\n<pre lang=\"c++\">\nswitch (currentState) {\n   case ST_IDLE:\n       // do something in the idle state\n       break;\n\n    case ST_STOP:\n       // do something in the stop state\n       break;\n\n    // etc...\n}</pre>\n\n<p>This method is certainly appropriate for solving many different design problems. When employed on an event driven, multithreaded project, however, state machines of this form can be quite limiting.</p>\n\n<p>The first problem revolves around controlling what state transitions are valid and which ones are invalid. There is no way to enforce the state transition rules. Any transition is allowed at any time, which is not particularly desirable. For most designs, only a few transition patterns are valid. Ideally, the software design should enforce these predefined state sequences and prevent the unwanted transitions. Another problem arises when trying to send data to a specific state. Since the entire state machine is located within a single function, sending additional data to any given state proves difficult. And lastly these designs are rarely suitable for use in a multithreaded system. The designer must ensure the state machine is called from a single thread of control.</p>\n\n# Why use a state machine?\n\n<p>Implementing code using a state machine is an extremely handy design technique for solving complex engineering problems. State machines break down the design into a series of steps, or what are called states in state-machine lingo. Each state performs some narrowly defined task. Events, on the other hand, are the stimuli, which cause the state machine to move, or transition, between states.</p>\n\n<p>To take a simple example, which I will use throughout this article, let&#39;s say we are designing motor-control software. We want to start and stop the motor, as well as change the motor&#39;s speed. Simple enough. The motor control events to be exposed to the client software will be as follows:</p>\n\n<ol>\n\t<li><strong>Set Speed</strong> &ndash; sets the motor going at a specific speed.</li>\n\t<li><strong>Halt</strong> &ndash; stops the motor.</li>\n</ol>\n\n<p>These events provide the ability to start the motor at whatever speed desired, which also implies changing the speed of an already moving motor. Or we can stop the motor altogether. To the motor-control module, these two events, or functions, are considered external events. To a client using our code, however, these are just plain functions.</p>\n\n<p>These events are not state machine states. The steps required to handle these two events are different. In this case the states are:</p>\n\n<ol>\n\t<li><strong>Idle </strong>&mdash; the motor is not spinning but is at rest.</li>\n</ol>\n\n<ul>\n\t<li>Do nothing.</li>\n</ul>\n\n<ol start=\"2\">\n\t<li><strong>Start </strong>&mdash; starts the motor from a dead stop.</li>\n</ol>\n\n<ul>\n\t<li>Turn on motor power.</li>\n\t<li>Set motor speed.</li>\n</ul>\n\n<ol start=\"3\">\n\t<li><strong>Change Speed </strong>&mdash; adjust the speed of an already moving motor.</li>\n</ol>\n\n<ul>\n\t<li>Change motor speed.</li>\n</ul>\n\n<ol start=\"4\">\n\t<li><strong>Stop </strong>&mdash; stop a moving motor.</li>\n</ol>\n\n<ul>\n\t<li>Turn off motor power.</li>\n\t<li>Go to the Idle state.</li>\n</ul>\n\n<p>As can be seen, breaking the motor control into discreet states, as opposed to having one monolithic function, we can more easily manage the rules of how to operate the motor.</p>\n\n<p>Every state machine has the concept of a &quot;current state.&quot; This is the state the state machine currently occupies. At any given moment in time, the state machine can be in only a single state. Every instance of a particular state machine instance can set the initial state when defined. That initial state, however, does not execute during object creation. Only an event sent to the state machine causes a state function to execute.</p>\n\n<p>To graphically illustrate the states and events, we use a state diagram. Figure 1 below shows the state transitions for the motor control module. A box denotes a state and a connecting arrow indicates the event transitions. Arrows with the event name listed are external events, whereas unadorned lines are considered internal events. (I cover the differences between internal and external events later in the article.)</p>\n\n<p><img alt=\"\" src=\"Motor.png\" /></p>\n\n<div class=\"Caption\">Figure 1: Motor state diagram</div>\n\n<p>As you can see, when an event comes in the state transition that occurs depends on state machine&#39;s current state. When a SetSpeed event comes in, for instance, and the motor is in the Idle state, it transitions to the Start state. However, that same SetSpeed event generated while the current state is Start transitions the motor to the ChangeSpeed state. You can also see that not all state transitions are valid. For instance, the motor can&#39;t transition from ChangeSpeed to Idle without first going through the Stop state.</p>\n\n<p>In short, using a state machine captures and enforces complex interactions, which might otherwise be difficult to convey and implement.</p>\n\n# State machine design\n\n## Internal and external events\n\n<p>As I mentioned earlier, an event is the stimulus that causes a state machine to transition between states. For instance, a button press could be an event. Events can be broken out into two categories: external and internal. The external event, at its most basic level, is a function call into a state-machine module. These functions are public and are called from the outside or from code external to the state-machine object. Any thread or task within a system can generate an external event. If the external event function call causes a state transition to occur, the state will execute synchronously within the caller&#39;s thread of control. An internal event, on the other hand, is self-generated by the state machine itself during state execution.</p>\n\n<p>A typical scenario consists of an external event being generated, which, again, boils down to a function call into the module&#39;s public interface. Based upon the event being generated and the state machine&#39;s current state, a lookup is performed to determine if a transition is required. If so, the state machine transitions to the new state and the code for that state executes. At the end of the state function, a check is performed to determine whether an internal event was generated. If so, another transition is performed and the new state gets a chance to execute. This process continues until the state machine is no longer generating internal events, at which time the original external event function call returns. The external event and all internal events, if any, execute within the caller&#39;s thread of control.</p>\n\n<p>Once the external event starts the state machine executing, it cannot be interrupted by another external event until the external event and all internal events have completed execution if locks are used. This run to completion model provides a multithread-safe environment for the state transitions. Semaphores or mutexes can be used in the state machine engine to block other threads that might be trying to be simultaneously access the same state machine instance. See source code function <code>_SM_ExternalEvent()</code> comments for where the locks go.</p>\n\n## Event data\n\n<p>When an event is generated, it can optionally attach event data to be used by the state function during execution. Event data is a single <code>const</code> or non-<code>const </code>pointer to any built-in or user-defined data type.</p>\n\n<p>Once the state has completed execution, the event data is considered used up and must be deleted. Therefore, any event data sent to a state machine must be dynamically created via <code>SM_XAlloc()</code>. &nbsp;The state machine engine automatically frees allocated event data using <code>SM_XFree()</code>.</p>\n\n## State transitions\n\n<p>When an external event is generated, a lookup is performed to determine the state transition course of action. There are three possible outcomes to an event: new state, event ignored, or cannot happen. A new state causes a transition to a new state where it is allowed to execute. Transitions to the existing state are also possible, which means the current state is re-executed. For an ignored event, no state executes. However, the event data, if any, is deleted. The last possibility, cannot happen, is reserved for situations where the event is not valid given the current state of the state machine. If this occurs, the software faults.</p>\n\n<p>In this implementation, internal events are not required to perform a validating transition lookup. The state transition is assumed to be valid. You could check for both valid internal and external event transitions, but in practice, this just takes more storage space and generates busywork for very little benefit. The real need for validating transitions lies in the asynchronous, external events where a client can cause an event to occur at an inappropriate time. Once the state machine is executing, it cannot be interrupted. It is under the control of the private implementation, thereby making transition checks unnecessary. This gives the designer the freedom to change states, via internal events, without the burden of updating transition tables.</p>\n\n# StateMachine module\n\n<p>The state machine source code is contained within the <strong>StateMachine.c</strong> and <strong>StateMachine.h</strong> files. The code below shows the partial header. The <strong><code>StateMachine</code> </strong>header contains various preprocessor multiline macros to ease implementation of a state machine.</p>\n\n<pre lang=\"c++\">\nenum { EVENT_IGNORED = 0xFE, CANNOT_HAPPEN = 0xFF };\n\ntypedef void NoEventData;\n\n// State machine constant data\ntypedef struct\n{\n    const CHAR* name;\n    const BYTE maxStates;\n    const struct SM_StateStruct* stateMap;\n    const struct SM_StateStructEx* stateMapEx;\n} SM_StateMachineConst;\n\n// State machine instance data\ntypedef struct \n{\n    const CHAR* name;\n    void* pInstance;\n    BYTE newState;\n    BYTE currentState;\n    BOOL eventGenerated;\n    void* pEventData;\n} SM_StateMachine;\n\n// Generic state function signatures\ntypedef void (*SM_StateFunc)(SM_StateMachine* self, void* pEventData);\ntypedef BOOL (*SM_GuardFunc)(SM_StateMachine* self, void* pEventData);\ntypedef void (*SM_EntryFunc)(SM_StateMachine* self, void* pEventData);\ntypedef void (*SM_ExitFunc)(SM_StateMachine* self);\n\ntypedef struct SM_StateStruct\n{\n    SM_StateFunc pStateFunc;\n} SM_StateStruct;\n\ntypedef struct SM_StateStructEx\n{\n    SM_StateFunc pStateFunc;\n    SM_GuardFunc pGuardFunc;\n    SM_EntryFunc pEntryFunc;\n    SM_ExitFunc pExitFunc;\n} SM_StateStructEx;\n\n// Public functions\n#define SM_Event(_smName_, _eventFunc_, _eventData_) \\\n    _eventFunc_(&amp;_smName_##Obj, _eventData_)\n\n// Protected functions\n#define SM_InternalEvent(_newState_, _eventData_) \\\n    _SM_InternalEvent(self, _newState_, _eventData_)\n#define SM_GetInstance(_instance_) \\\n    (_instance_*)(self-&gt;pInstance);\n\n// Private functions\nvoid _SM_ExternalEvent(SM_StateMachine* self, const SM_StateMachineConst* selfConst, BYTE newState, void* pEventData);\nvoid _SM_InternalEvent(SM_StateMachine* self, BYTE newState, void* pEventData);\nvoid _SM_StateEngine(SM_StateMachine* self, const SM_StateMachineConst* selfConst);\nvoid _SM_StateEngineEx(SM_StateMachine* self, const SM_StateMachineConst* selfConst);\n\n#define SM_DECLARE(_smName_) \\\n    extern SM_StateMachine _smName_##Obj; \n\n#define SM_DEFINE(_smName_, _instance_) \\\n    SM_StateMachine _smName_##Obj = { #_smName_, _instance_, \\\n        0, 0, 0, 0 }; \n\n#define EVENT_DECLARE(_eventFunc_, _eventData_) \\\n    void _eventFunc_(SM_StateMachine* self, _eventData_* pEventData);\n\n#define EVENT_DEFINE(_eventFunc_, _eventData_) \\\n    void _eventFunc_(SM_StateMachine* self, _eventData_* pEventData)\n\n#define STATE_DECLARE(_stateFunc_, _eventData_) \\\n    static void ST_##_stateFunc_(SM_StateMachine* self, _eventData_* pEventData);\n\n#define STATE_DEFINE(_stateFunc_, _eventData_) \\\n    static void ST_##_stateFunc_(SM_StateMachine* self, _eventData_* pEventData)\n</pre>\n\n<p>The <code>SM_Event()</code> macro is used to generate external events whereas <code>SM_InternalEvent()</code> generates an internal event during state function execution. <code>SM_GetInstance()</code> obtains a pointer to the current state machine object.</p>\n\n<p><code>SM_DECLARE </code>and <code>SM_DEFINE</code> are used to create a state machine instance. <code>EVENT_DECLARE</code> and <code>EVENT_DEFINE</code> create external event functions. And finally, <code>STATE_DECLARE</code> and <code>STATE_DEFINE</code> create state functions.</p>\n\n# Motor example\n\n<p><code>Motor </code>implements our hypothetical motor-control state machine, where clients can start the motor, at a specific speed, and stop the motor. The <code>Motor</code> header interface is shown below:</p>\n\n<pre lang=\"c++\">\n#include &quot;StateMachine.h&quot;\n\n// Motor object structure\ntypedef struct\n{\n    INT currentSpeed;\n} Motor;\n\n// Event data structure\ntypedef struct\n{\n    INT speed;\n} MotorData;\n\n// State machine event functions\nEVENT_DECLARE(MTR_SetSpeed, MotorData)\nEVENT_DECLARE(MTR_Halt, NoEventData)</pre>\n\n<p>The <code>Motor</code> source file uses macros to simplify usage by hiding the required state machine machinery.</p>\n\n<pre lang=\"c++\">\n// State enumeration order must match the order of state\n// method entries in the state map\nenum States\n{\n    ST_IDLE,\n    ST_STOP,\n    ST_START,\n    ST_CHANGE_SPEED,\n    ST_MAX_STATES\n};\n\n// State machine state functions\nSTATE_DECLARE(Idle, NoEventData)\nSTATE_DECLARE(Stop, NoEventData)\nSTATE_DECLARE(Start, MotorData)\nSTATE_DECLARE(ChangeSpeed, MotorData)\n\n// State map to define state function order\nBEGIN_STATE_MAP(Motor)\n    STATE_MAP_ENTRY(ST_Idle)\n    STATE_MAP_ENTRY(ST_Stop)\n    STATE_MAP_ENTRY(ST_Start)\n    STATE_MAP_ENTRY(ST_ChangeSpeed)\nEND_STATE_MAP(Motor)\n\n// Set motor speed external event\nEVENT_DEFINE(MTR_SetSpeed, MotorData)\n{\n    // Given the SetSpeed event, transition to a new state based upon \n    // the current state of the state machine\n    BEGIN_TRANSITION_MAP                        // - Current State -\n        TRANSITION_MAP_ENTRY(ST_START)          // ST_Idle       \n        TRANSITION_MAP_ENTRY(CANNOT_HAPPEN)     // ST_Stop       \n        TRANSITION_MAP_ENTRY(ST_CHANGE_SPEED)   // ST_Start      \n        TRANSITION_MAP_ENTRY(ST_CHANGE_SPEED)   // ST_ChangeSpeed\n    END_TRANSITION_MAP(Motor, pEventData)\n}\n\n// Halt motor external event\nEVENT_DEFINE(MTR_Halt, NoEventData)\n{\n    // Given the Halt event, transition to a new state based upon \n    // the current state of the state machine\n    BEGIN_TRANSITION_MAP                        // - Current State -\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)     // ST_Idle\n        TRANSITION_MAP_ENTRY(CANNOT_HAPPEN)     // ST_Stop\n        TRANSITION_MAP_ENTRY(ST_STOP)           // ST_Start\n        TRANSITION_MAP_ENTRY(ST_STOP)           // ST_ChangeSpeed\n    END_TRANSITION_MAP(Motor, pEventData)\n}</pre>\n\n## External events\n\n<p><code>MTR_SetSpeed </code>and <code>MTR_Halt</code> are considered external events into the <code>Motor</code> state machine. <code>MTR_SetSpeed </code>takes a pointer to <code>MotorData</code> event data, containing the motor speed. This data structure will be freed using <code>SM_XFree()</code> upon completion of the state processing, so it is imperative that it be created using <code>SM_XAlloc()</code> before the function call is made.</p>\n\n## State enumerations\n\n<p>Each state function must have an enumeration associated with it. These enumerations are used to store the current state of the state machine. In <code>Motor</code>, <code>States</code> provides these enumerations, which are used later for indexing into the transition map and state map lookup tables.</p>\n\n## State functions\n\n<p>State functions implement each state &mdash; one state function per state-machine state. <code>STATE_DECLARE </code>is used to declare the state function interface and <code>STATE_DEFINE </code>defines the implementation.</p>\n\n<pre lang=\"c++\">\n// State machine sits here when motor is not running\nSTATE_DEFINE(Idle, NoEventData)\n{\n    printf(&quot;%s ST_Idle\\n&quot;, self-&gt;name);\n}\n\n// Stop the motor \nSTATE_DEFINE(Stop, NoEventData)\n{\n    // Get pointer to the instance data and update currentSpeed\n    Motor* pInstance = SM_GetInstance(Motor);\n    pInstance-&gt;currentSpeed = 0;\n\n    // Perform the stop motor processing here\n    printf(&quot;%s ST_Stop: %d\\n&quot;, self-&gt;name, pInstance-&gt;currentSpeed);\n\n    // Transition to ST_Idle via an internal event\n    SM_InternalEvent(ST_IDLE, NULL);\n}\n\n// Start the motor going\nSTATE_DEFINE(Start, MotorData)\n{\n    ASSERT_TRUE(pEventData);\n\n    // Get pointer to the instance data and update currentSpeed\n    Motor* pInstance = SM_GetInstance(Motor);\n    pInstance-&gt;currentSpeed = pEventData-&gt;speed;\n\n    // Set initial motor speed processing here\n    printf(&quot;%s ST_Start: %d\\n&quot;, self-&gt;name, pInstance-&gt;currentSpeed);\n}\n\n// Changes the motor speed once the motor is moving\nSTATE_DEFINE(ChangeSpeed, MotorData)\n{\n    ASSERT_TRUE(pEventData);\n\n    // Get pointer to the instance data and update currentSpeed\n    Motor* pInstance = SM_GetInstance(Motor);\n    pInstance-&gt;currentSpeed = pEventData-&gt;speed;\n\n    // Perform the change motor speed here\n    printf(&quot;%s ST_ChangeSpeed: %d\\n&quot;, self-&gt;name, pInstance-&gt;currentSpeed);\n}\n</pre>\n\n<p><code>STATE_DECLARE</code> and <code>STATE_DEFINE</code> use two arguments. The first argument is the state function name. The second argument is the event data type. If no event data is required, use <code>NoEventData</code>. Macros are also available for creating guard, exit and entry actions which are explained later in the article.</p>\n\n<p>The <code>SM_GetInstance()</code> macro obtains an instance to the state machine object. The argument to the macro is the state machine name.</p>\n\n<p>In this implementation, all state machine functions must adhere to these signatures, which are as follows:</p>\n\n<pre lang=\"c++\">\n// Generic state function signatures\ntypedef void (*SM_StateFunc)(SM_StateMachine* self, void* pEventData);\ntypedef BOOL (*SM_GuardFunc)(SM_StateMachine* self, void* pEventData);\ntypedef void (*SM_EntryFunc)(SM_StateMachine* self, void* pEventData);\ntypedef void (*SM_ExitFunc)(SM_StateMachine* self);\n</pre>\n\n<p>Each <code>SM_StateFunc </code>accepts a pointer to a <code>SM_StateMachine</code> object and event data. If <code>NoEventData </code>is used, the <code>pEventData </code>argument will be <code>NULL</code>. Otherwise, the <code>pEventData</code> argument is of the type specified in <code>STATE_DEFINE</code>.</p>\n\n<p>In <code>Motor</code>&rsquo;s <code>Start</code> state function, the <code>STATE_DEFINE(Start, MotorData)&nbsp;</code>macro expands to:</p>\n\n<pre lang=\"c++\">\nvoid ST_Start(SM_StateMachine* self, MotorData* pEventData)</pre>\n\n<p>Notice that every state function has <code>self </code>and&nbsp;<code>pEventData </code>arguments. <code>self </code>is a pointer to the state machine object and <code>pEventData </code>is the event data. Also note that the macro prepends &ldquo;ST_&rdquo; to the state name to create the function <code>ST_Start()</code>.</p>\n\n<p>Similarly, the <code>Stop </code>state function <code>STATE_DEFINE(Stop, NoEventData)</code> is expands to:</p>\n\n<pre lang=\"c++\">\nvoid ST_Stop(SM_StateMachine* self, void* pEventData)</pre>\n\n<p><code>Stop </code>doesn&#39;t accept event data so the <code>pEventData </code>argument is <code>void*</code>.&nbsp;</p>\n\n<p>Three characters are added to each state/guard/entry/exit function automatically within the macros. For instance, if declaring a function using <code>STATE_DEFINE(Idle, NoEventData)</code> the actual state function name is called <code>ST_Idle()</code>.</p>\n\n<ol>\n\t<li>ST_ - state function prepend characters</li>\n\t<li>GD_ - guard function prepend characters</li>\n\t<li>EN_ - entry function prepend characters</li>\n\t<li>EX_ - exit function prepend characters</li>\n</ol>\n\n<p><code>SM_GuardFunc </code>and <code>SM_Entry </code>function <code>typedef</code>&rsquo;s also accept event data. <code>SM_ExitFunc </code>is unique in that no event data is allowed.</p>\n\n## State map\n\n<p>The state-machine engine knows which state function to call by using the state map. The state map maps the <code>currentState</code> variable to a specific state function. For instance, if <code>currentState </code>is 2, then the third state-map function pointer entry will be called (counting from zero). The state map table is created using these three macros:</p>\n\n<div>\n<pre>\nBEGIN_STATE_MAP\nSTATE_MAP_ENTRY\nEND_STATE_MAP</pre>\n</div>\n\n<p><code>BEGIN_STATE_MAP </code>starts the state map sequence. Each <code>STATE_MAP_ENTRY </code>has a state function name argument. <code>END_STATE_MAP </code>terminates the map. The state map for <code>Motor </code>is shown below.</p>\n\n<pre lang=\"c++\">\nBEGIN_STATE_MAP(Motor)\n    STATE_MAP_ENTRY(ST_Idle)\n    STATE_MAP_ENTRY(ST_Stop)\n    STATE_MAP_ENTRY(ST_Start)\n    STATE_MAP_ENTRY(ST_ChangeSpeed)\nEND_STATE_MAP\n</pre>\n\n<p>Alternatively, guard/entry/exit features require utilizing the <code>_EX</code> (extended) version of the macros.</p>\n\n<pre lang=\"c++\">\nBEGIN_STATE_MAP_EX\nSTATE_MAP_ENTRY_EX or STATE_MAP_ENTRY_ALL_EX \nEND_STATE_MAP_EX</pre>\n\n<p>The <code>STATE_MAP_ENTRY_ALL_EX </code>macro has four arguments for the state action, guard condition, entry action and exit action in that order. The state action is mandatory but the other actions are optional. If a state doesn&#39;t have an action, then use 0 for the argument. If a state doesn&#39;t have any guard/entry/exit options, the <code>STATE_MAP_ENTRY_EX </code>macro defaults all unused options to 0. The macro snippet below is for an advanced example presented later in the article.</p>\n\n<pre lang=\"c++\">\n// State map to define state function order\nBEGIN_STATE_MAP_EX(CentrifugeTest)\n    STATE_MAP_ENTRY_ALL_EX(ST_Idle, 0, EN_Idle, 0)\n    STATE_MAP_ENTRY_EX(ST_Completed)\n    STATE_MAP_ENTRY_EX(ST_Failed)\n    STATE_MAP_ENTRY_ALL_EX(ST_StartTest, GD_StartTest, 0, 0)\n    STATE_MAP_ENTRY_EX(ST_Acceleration)\n    STATE_MAP_ENTRY_ALL_EX(ST_WaitForAcceleration, 0, 0, EX_WaitForAcceleration)\n    STATE_MAP_ENTRY_EX(ST_Deceleration)\n    STATE_MAP_ENTRY_ALL_EX(ST_WaitForDeceleration, 0, 0, EX_WaitForDeceleration)\nEND_STATE_MAP_EX(CentrifugeTest)</pre>\n\n<p>Don&rsquo;t forget to add the prepended characters (ST_, GD_, EN_ or EX_) for each function.</p>\n\n## State machine objects\n\n<p>In C++, objects are integral to the language. Using C, you have to work a bit harder to accomplish similar behavior. This C language state machine supports multiple state machine objects (or instances) instead of having&nbsp;a single, static state machine implementation.</p>\n\n<p>The <code>SM_StateMachine </code>data structure stores state machine instance data; one object per state machine instance. The&nbsp;<code>SM_StateMachineConst </code>data structure stores constant data; one constant object per state machine type.</p>\n\n<p>The state machine is defined using <code>SM_DEFINE </code>macro. The first argument is the state machine name. The second argument is a pointer to a user defined state machine structure, or <code>NULL </code>if no user object.</p>\n\n<pre lang=\"c++\">\n#define SM_DEFINE(_smName_, _instance_) \\\n    SM_StateMachine _smName_##Obj = { #_smName_, _instance_, \\\n        0, 0, 0, 0 };</pre>\n\n<p>In this example, the state machine name is <code>Motor</code> and two objects and two state machines are created.</p>\n\n<pre lang=\"c++\">\n// Define motor objects\nstatic Motor motorObj1;\nstatic Motor motorObj2;\n\n// Define two public Motor state machine instances\nSM_DEFINE(Motor1SM, &amp;motorObj1)\nSM_DEFINE(Motor2SM, &amp;motorObj2)</pre>\n\n<p>Each motor object handles state execution independent of the other. The <code>Motor </code>structure is used to store state machine instance-specific data. Within a state function, use <code>SM_GetInstance()</code>&nbsp;to obtain&nbsp;a pointer to the <code>Motor </code>object at runtime.</p>\n\n<pre lang=\"c++\">\n// Get pointer to the instance data and update currentSpeed\nMotor* pInstance = SM_GetInstance(Motor);\npInstance-&gt;currentSpeed = pEventData-&gt;speed;\n</pre>\n\n## Transition map\n\n<p>The last detail to attend to are the state transition rules. How does the state machine know what transitions should occur? The answer is the transition map. A transition map is lookup table that maps the <code>currentState </code>variable to a state enum constant. Every external event function has a transition map table created with three macros:</p>\n\n<pre lang=\"c++\">\nBEGIN_TRANSITION_MAP\nTRANSITION_MAP_ENTRY\nEND_TRANSITION_MAP\n</pre>\n\n<p>The <code>MTR_Halt </code>event function in <code>Motor </code>defines the transition map as:</p>\n\n<pre lang=\"c++\">\n// Halt motor external event\nEVENT_DEFINE(MTR_Halt, NoEventData)\n{\n    // Given the Halt event, transition to a new state based upon \n    // the current state of the state machine\n    BEGIN_TRANSITION_MAP                        // - Current State -\n        TRANSITION_MAP_ENTRY(EVENT_IGNORED)     // ST_Idle\n        TRANSITION_MAP_ENTRY(CANNOT_HAPPEN)     // ST_Stop\n        TRANSITION_MAP_ENTRY(ST_STOP)           // ST_Start\n        TRANSITION_MAP_ENTRY(ST_STOP)           // ST_ChangeSpeed\n    END_TRANSITION_MAP(Motor, pEventData)\n}\n</pre>\n\n<p><code>BEGIN_TRANSITION_MAP</code> starts the map. Each <code>TRANSITION_MAP_ENTRY</code> that follows indicates what the state machine should do based upon the current state. The number of entries in each transition map table must match the number of state functions exactly. In our example, we have four state functions, so we need four transition map entries. The location of each entry matches the order of state functions defined within the state map. Thus, the first entry within the <code>MTR_Halt</code> function indicates an <code>EVENT_IGNORED </code>as shown below.</p>\n\n<pre lang=\"c++\">\nTRANSITION_MAP_ENTRY (EVENT_IGNORED)&nbsp;&nbsp;&nbsp; <i>// ST_Idle</i></pre>\n\n<p>This is interpreted as &quot;If a Halt event occurs while the current state is state Idle, just ignore the event.&quot;</p>\n\n<p>Similarly, the third entry in the map is:</p>\n\n<div>\n<pre>\nTRANSITION_MAP_ENTRY (ST_STOP)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <em>// ST_Start</em></pre>\n</div>\n\n<p>This indicates &quot;If a Halt event occurs while current is state Start, then transition to state Stop.&quot;</p>\n\n<p><code>END_TRANSITION_MAP </code>terminates the map. The first argument to this macro is the state machine name. The second argument is the event data.</p>\n\n<p>The <code>C_ASSERT()</code> macro is used within <code>END_TRANSITION_MAP</code>. If there is a mismatch between the number of state machine states and the number of transition map entries, a compile time error is generated.</p>\n\n## New state machine steps\n\n<p>Creating a new state machine requires a few basic high-level steps:</p>\n\n<ol>\n\t<li>Create a <code>States </code>enumeration with one entry per state function.</li>\n\t<li>Define state functions.</li>\n\t<li>Define event functions.</li>\n\t<li>Create one state map lookup table using the <code>STATE_MAP</code> macros.</li>\n\t<li>Create one transition map lookup table for each external event function using the <code>TRANSITION_MAP </code>macros.</li>\n</ol>\n\n# State engine\n\n<p>The state engine executes the state functions based upon events generated. The transition map is an array of <code>SM_StateStruct</code> instances indexed by the <code>currentState </code>variable. When the <code>_SM_StateEngine()</code> function executes, it looks up the correct state function within the <code>SM_StateStruct </code>array. After the state function has a chance to execute, it frees the event data, if any, before checking to see if any internal events were generated via <code>SM_InternalEvent()</code>.</p>\n\n<pre lang=\"c++\">\n// The state engine executes the state machine states\nvoid _SM_StateEngine(SM_StateMachine* self, SM_StateMachineConst* selfConst)\n{\n&nbsp; &nbsp; void* pDataTemp = NULL;\n\n&nbsp; &nbsp; ASSERT_TRUE(self);\n&nbsp; &nbsp; ASSERT_TRUE(selfConst);\n\n&nbsp; &nbsp; // While events are being generated keep executing states\n&nbsp; &nbsp; while (self-&gt;eventGenerated)\n&nbsp; &nbsp; {\n&nbsp; &nbsp; &nbsp; &nbsp; // Error check that the new state is valid before proceeding\n&nbsp; &nbsp; &nbsp; &nbsp; ASSERT_TRUE(self-&gt;newState &lt; selfConst-&gt;maxStates);\n\n&nbsp; &nbsp; &nbsp; &nbsp; // Get the pointers from the state map\n&nbsp; &nbsp; &nbsp; &nbsp; SM_StateFunc state = selfConst-&gt;stateMap[self-&gt;newState].pStateFunc;\n\n&nbsp; &nbsp; &nbsp; &nbsp; // Copy of event data pointer\n&nbsp; &nbsp; &nbsp; &nbsp; pDataTemp = self-&gt;pEventData;\n\n&nbsp; &nbsp; &nbsp; &nbsp; // Event data used up, reset the pointer\n&nbsp; &nbsp; &nbsp; &nbsp; self-&gt;pEventData = NULL;\n\n&nbsp; &nbsp; &nbsp; &nbsp; // Event used up, reset the flag\n&nbsp; &nbsp; &nbsp; &nbsp; self-&gt;eventGenerated = FALSE;\n\n&nbsp; &nbsp; &nbsp; &nbsp; // Switch to the new current state\n&nbsp; &nbsp; &nbsp; &nbsp; self-&gt;currentState = self-&gt;newState;\n\n&nbsp; &nbsp; &nbsp; &nbsp; // Execute the state action passing in event data\n&nbsp; &nbsp; &nbsp; &nbsp; ASSERT_TRUE(state != NULL);\n&nbsp; &nbsp; &nbsp; &nbsp; state(self, pDataTemp);\n\n&nbsp; &nbsp; &nbsp; &nbsp; // If event data was used, then delete it\n&nbsp; &nbsp; &nbsp; &nbsp; if (pDataTemp)\n&nbsp; &nbsp; &nbsp; &nbsp; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SM_XFree(pDataTemp);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pDataTemp = NULL;\n&nbsp; &nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; }\n}\n</pre>\n\n<p>The state engine logic for guard, entry, state, and exit actions is expressed by the following sequence. The <code>_SM_StateEngine()</code> engine implements only #1 and #5 below. The extended <code>_SM_StateEngineEx()</code> engine uses the entire logic sequence.</p>\n\n<ol>\n\t<li>Evaluate the state transition table. If <code>EVENT_IGNORED</code>, the event is ignored and the transition is not performed. If <code>CANNOT_HAPPEN</code>, the software faults. Otherwise, continue with next step.</li>\n\t<li>If a guard condition is defined execute the guard condition function. If the guard condition returns <code>FALSE</code>, the state transition is ignored and the state function is not called. If the guard returns <code>TRUE</code>, or if no guard condition exists, the state function will be executed.</li>\n\t<li>If transitioning to a new state and an exit action is defined for the current state, call the current state exit action function.</li>\n\t<li>If transitioning to a new state and an entry action is defined for the new state, call the new state entry action function.</li>\n\t<li>Call the state action function for the new state. The new state is now the current state.</li>\n</ol>\n\n# Generating events\n\n<p>At this point, we have a working state machine. Let&#39;s see how to generate events to it. An external event is generated by dynamically creating the event data structure using <code>SM_XAlloc()</code>, assigning the structure member variables, and calling the external event function using the <code>SM_Event()</code> macro. The following code fragment shows how a synchronous call is made.</p>\n\n<pre lang=\"c++\">\nMotorData* data;\n \n// Create event data\ndata = SM_XAlloc(sizeof(MotorData));\ndata-&gt;speed = 100;\n\n// Call MTR_SetSpeed event function to start motor\nSM_Event(Motor1SM, MTR_SetSpeed, data);\n</pre>\n\n<p>The <code>SM_Event()</code> first argument is the state machine name. The second argument is the event function to invoke. The third argument is the event data, or <code>NULL </code>if no data.</p>\n\n<p>To generate an internal event from within a state function, call <code>SM_InternalEvent()</code>. If the destination doesn&#39;t accept event data, then the last argument is <code>NULL</code>. Otherwise, create the event data using <code>SM_XAlloc()</code>.</p>\n\n<pre lang=\"c++\">\nSM_InternalEvent(ST_IDLE, NULL);</pre>\n\n<p>In the example above, once the state function completes execution the state machine will transition to the <code>ST_Idle</code> state. If, on the other hand, event data needs to be sent to the destination state, then the data structure needs to be created on the heap and passed in as an argument.</p>\n\n<pre lang=\"c++\">\nMotorData* data;    \ndata = SM_XAlloc(sizeof(MotorData));\ndata-&gt;speed = 100;\nSM_InternalEvent(ST_CHANGE_SPEED, data);\n</pre>\n\n# No heap usage\n\n<p>All state machine event data must be dynamically created. However, on some systems using the heap is undesirable. The included <code>x_allocator</code> module is a fixed block memory allocator that eliminates heap usage. Define <code>USE_SM_ALLOCATOR </code>within <strong>StateMachine.c</strong> to use the fixed block allocator. See the <strong>References</strong> section below for&nbsp;<code>x_allocator</code> information.</p>\n\n# CentrifugeTest example\n\n<p>The <code>CentrifugeTest </code>example shows how an extended state machine is created using guard, entry and exit actions. The state diagram is shown below.</p>\n\n<p><img alt=\"\" src=\"CentrifugeTest.png\" style=\"height: 736px; width: 500px\" /></p>\n\n<div class=\"Caption\">Figure 2: CentrifugeTest state diagram</div>\n\n<p>A <code>CentrifgeTest </code>object and state machine is created. The only difference here is that the state machine is a singleton, meaning the object is private and only one instance of <code>CentrifugeTest </code>can be created. This is unlike the <code>Motor </code>state machine where multiple instances are allowed.</p>\n\n<pre lang=\"c++\">\n// CentrifugeTest object structure\ntypedef struct\n{\n    INT speed;\n    BOOL pollActive;\n} CentrifugeTest;\n\n// Define private instance of motor state machine\nCentrifugeTest centrifugeTestObj;\nSM_DEFINE(CentrifugeTestSM, &amp;centrifugeTestObj)\n</pre>\n\n<p>The extended state machine uses <code>ENTRY_DECLARE</code>, <code>GUARD_DECLARE</code> and <code>EXIT_DECLARE </code>macros.</p>\n\n<pre lang=\"c++\">\n// State enumeration order must match the order of state\n// method entries in the state map\nenum States\n{\n    ST_IDLE,\n    ST_COMPLETED,\n    ST_FAILED,\n    ST_START_TEST,\n    ST_ACCELERATION,\n    ST_WAIT_FOR_ACCELERATION,\n    ST_DECELERATION,\n    ST_WAIT_FOR_DECELERATION,\n    ST_MAX_STATES\n};\n\n// State machine state functions\nSTATE_DECLARE(Idle, NoEventData)\nENTRY_DECLARE(Idle, NoEventData)\nSTATE_DECLARE(Completed, NoEventData)\nSTATE_DECLARE(Failed, NoEventData)\nSTATE_DECLARE(StartTest, NoEventData)\nGUARD_DECLARE(StartTest, NoEventData)\nSTATE_DECLARE(Acceleration, NoEventData)\nSTATE_DECLARE(WaitForAcceleration, NoEventData)\nEXIT_DECLARE(WaitForAcceleration)\nSTATE_DECLARE(Deceleration, NoEventData)\nSTATE_DECLARE(WaitForDeceleration, NoEventData)\nEXIT_DECLARE(WaitForDeceleration)\n\n// State map to define state function order\nBEGIN_STATE_MAP_EX(CentrifugeTest)\n    STATE_MAP_ENTRY_ALL_EX(ST_Idle, 0, EN_Idle, 0)\n    STATE_MAP_ENTRY_EX(ST_Completed)\n    STATE_MAP_ENTRY_EX(ST_Failed)\n    STATE_MAP_ENTRY_ALL_EX(ST_StartTest, GD_StartTest, 0, 0)\n    STATE_MAP_ENTRY_EX(ST_Acceleration)\n    STATE_MAP_ENTRY_ALL_EX(ST_WaitForAcceleration, 0, 0, EX_WaitForAcceleration)\n    STATE_MAP_ENTRY_EX(ST_Deceleration)\n    STATE_MAP_ENTRY_ALL_EX(ST_WaitForDeceleration, 0, 0, EX_WaitForDeceleration)\nEND_STATE_MAP_EX(CentrifugeTest)\n</pre>\n\n<p>Notice the <code>_EX</code> extended state map macros so the guard/entry/exit features are supported. Each guard/entry/exit <code>DECLARE </code>macro must be matched with the <code>DEFINE</code>. For instance, a guard condition for the <code>StartTest </code>state function is declared as:</p>\n\n<pre lang=\"c++\">\nGUARD_DECLARE(StartTest, NoEventData)</pre>\n\n<p>The guard condition function returns <code>TRUE </code>if the state function is to be executed or <code>FALSE </code>otherwise.</p>\n\n<pre lang=\"c++\">\n// Guard condition to determine whether StartTest state is executed.\nGUARD_DEFINE(StartTest, NoEventData)\n{\n    printf(&quot;%s GD_StartTest\\n&quot;, self-&gt;name);\n    if (centrifugeTestObj.speed == 0)\n        return TRUE;    // Centrifuge stopped. OK to start test.\n    else\n        return FALSE;   // Centrifuge spinning. Can&#39;t start test.\n}\n</pre>\n\n# Multithread safety    \n\n<p>To prevent preemption by another thread when the state machine is in the process of execution, the <code>StateMachine </code>module can use locks within the <code>_SM_ExternalEvent()</code>&nbsp;function. Before the external event is allowed to execute, a semaphore can be locked. When the external event and all internal events have been processed, the software lock is released, allowing another external event to enter the state machine instance.</p>\n\n<p>Comments indicate where the lock and unlock should be placed if the application is multithreaded&nbsp;<em>and</em> mutiple threads are able to access a single state machine instance. Note that each <code>StateMachine </code>object should have its own instance of a software lock. This prevents a single instance from locking and preventing all other <code>StateMachine </code>objects from executing. Software locks are only required if a <code>StateMachine </code>instance is called by multiple threads of control. If not, then locks are not required.</p>\n\n<ul>\n</ul>\n\n# Conclusion\n\n<p>Implementing a state machine using this method as opposed to the old switch statement style may seem like extra effort. However, the payoff is in a more robust design that is capable of being employed uniformly over an entire multithreaded system. Having each state in its own function provides easier reading than a single huge <code>switch</code> statement, and allows unique event data to be sent to each state. In addition, validating state transitions prevents client misuse by eliminating the side effects caused by unwanted state transitions.</p>\n\n<p>This C language version is a close translation of the&nbsp;C++ implementation I&rsquo;ve used for many years on different projects. Consider the C++ implementation within the <strong>References </strong>section if using C++.</p>\n\n# References\n\n<ul>\n    <li><a href=\"https://github.com/endurodave/C_StateMachineWithThreads\">C Language State Machine with Threads</a> - by David Lafreniere</li>\n\t<li><a href=\"https://github.com/endurodave/C_Allocator\">A Fixed Block Allocator in C</a> - by David Lafreniere</li>\n    <li><a href=\"https://github.com/endurodave/StateMachine\">State Machine Design in C++</a> - by David Lafreniere</li>\n</ul>\n"
  },
  {
    "path": "StateMachine.c",
    "content": "#include \"Fault.h\"\n#include \"StateMachine.h\"\n\n// @see https://github.com/endurodave/C_StateMachine\n\n// Generates an external event. Called once per external event \n// to start the state machine executing\nvoid _SM_ExternalEvent(SM_StateMachine* self, const SM_StateMachineConst* selfConst, BYTE newState, void* pEventData)\n{\n    // If we are supposed to ignore this event\n    if (newState == EVENT_IGNORED) \n    {\n        // Just delete the event data, if any\n        if (pEventData)\n            SM_XFree(pEventData);\n    }\n    else \n    {\n        // TODO - capture software lock here for thread-safety if necessary\n\n        // Generate the event \n        _SM_InternalEvent(self, newState, pEventData);\n\n        // Execute state machine based on type of state map defined\n        if (selfConst->stateMap)\n            _SM_StateEngine(self, selfConst);\n        else\n            _SM_StateEngineEx(self, selfConst);\n\n        // TODO - release software lock here \n    }\n}\n\n// Generates an internal event. Called from within a state \n// function to transition to a new state\nvoid _SM_InternalEvent(SM_StateMachine* self, BYTE newState, void* pEventData)\n{\n    ASSERT_TRUE(self);\n\n    self->pEventData = pEventData;\n    self->eventGenerated = TRUE;\n    self->newState = newState;\n}\n\n// The state engine executes the state machine states\nvoid _SM_StateEngine(SM_StateMachine* self, const SM_StateMachineConst* selfConst)\n{\n    void* pDataTemp = NULL;\n\n    ASSERT_TRUE(self);\n    ASSERT_TRUE(selfConst);\n\n    // While events are being generated keep executing states\n    while (self->eventGenerated)\n    {\n        // Error check that the new state is valid before proceeding\n        ASSERT_TRUE(self->newState < selfConst->maxStates);\n\n        // Get the pointers from the state map\n        SM_StateFunc state = selfConst->stateMap[self->newState].pStateFunc;\n\n        // Copy of event data pointer\n        pDataTemp = self->pEventData;\n\n        // Event data used up, reset the pointer\n        self->pEventData = NULL;\n\n        // Event used up, reset the flag\n        self->eventGenerated = FALSE;\n\n        // Switch to the new current state\n        self->currentState = self->newState;\n\n        // Execute the state action passing in event data\n        ASSERT_TRUE(state != NULL);\n        state(self, pDataTemp);\n\n        // If event data was used, then delete it\n        if (pDataTemp)\n        {\n            SM_XFree(pDataTemp);\n            pDataTemp = NULL;\n        }\n    }\n}\n\n// The state engine executes the extended state machine states\nvoid _SM_StateEngineEx(SM_StateMachine* self, const SM_StateMachineConst* selfConst)\n{\n    BOOL guardResult = TRUE;\n    void* pDataTemp = NULL;\n\n    ASSERT_TRUE(self);\n    ASSERT_TRUE(selfConst);\n\n    // While events are being generated keep executing states\n    while (self->eventGenerated)\n    {\n        // Error check that the new state is valid before proceeding\n        ASSERT_TRUE(self->newState < selfConst->maxStates);\n\n        // Get the pointers from the extended state map\n        SM_StateFunc state = selfConst->stateMapEx[self->newState].pStateFunc;\n        SM_GuardFunc guard = selfConst->stateMapEx[self->newState].pGuardFunc;\n        SM_EntryFunc entry = selfConst->stateMapEx[self->newState].pEntryFunc;\n        SM_ExitFunc exit = selfConst->stateMapEx[self->currentState].pExitFunc;\n\n        // Copy of event data pointer\n        pDataTemp = self->pEventData;\n\n        // Event data used up, reset the pointer\n        self->pEventData = NULL;\n\n        // Event used up, reset the flag\n        self->eventGenerated = FALSE;\n\n        // Execute the guard condition\n        if (guard != NULL)\n            guardResult = guard(self, pDataTemp);\n\n        // If the guard condition succeeds\n        if (guardResult == TRUE)\n        {\n            // Transitioning to a new state?\n            if (self->newState != self->currentState)\n            {\n                // Execute the state exit action on current state before switching to new state\n                if (exit != NULL)\n                    exit(self);\n\n                // Execute the state entry action on the new state\n                if (entry != NULL)\n                    entry(self, pDataTemp);\n\n                // Ensure exit/entry actions didn't call SM_InternalEvent by accident \n                ASSERT_TRUE(self->eventGenerated == FALSE);\n            }\n\n            // Switch to the new current state\n            self->currentState = self->newState;\n\n            // Execute the state action passing in event data\n            ASSERT_TRUE(state != NULL);\n            state(self, pDataTemp);\n        }\n\n        // If event data was used, then delete it\n        if (pDataTemp)\n        {\n            SM_XFree(pDataTemp);\n            pDataTemp = NULL;\n        }\n    }\n}\n"
  },
  {
    "path": "StateMachine.h",
    "content": "// https://github.com/endurodave/C_StateMachine\n//\n// The StateMachine module is a C language implementation of a finite state \n// machine (FSM).\n//\n// All event data must be created dynamically using SM_XAlloc. Use a fixed \n// block allocator or the heap as desired. \n//\n// The standard version (non-EX) supports state and event functions. The \n// extended version (EX) supports the additional guard, entry and exit state\n// machine features. \n//\n// Macros are used to assist in creating the state machine machinery. \n\n#ifndef _STATE_MACHINE_H\n#define _STATE_MACHINE_H\n\n#include \"DataTypes.h\"\n#include \"Fault.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// Define USE_SM_ALLOCATOR to use the fixed block allocator instead of heap\n#define USE_SM_ALLOCATOR\n#ifdef USE_SM_ALLOCATOR\n    #include \"sm_allocator.h\"\n    #define SM_XAlloc(size)    SMALLOC_Alloc(size)\n    #define SM_XFree(ptr)      SMALLOC_Free(ptr)\n#else\n    #include <stdlib.h>\n    #define SM_XAlloc(size)    malloc(size)\n    #define SM_XFree(ptr)      free(ptr)\n#endif\n\nenum { EVENT_IGNORED = 0xFE, CANNOT_HAPPEN = 0xFF };\n\ntypedef void NoEventData;\n\n// State machine constant data\ntypedef struct\n{\n    const CHAR* name;\n    const BYTE maxStates;\n    const struct SM_StateStruct* stateMap;\n    const struct SM_StateStructEx* stateMapEx;\n} SM_StateMachineConst;\n\n// State machine instance data\ntypedef struct \n{\n    const CHAR* name;\n    void* pInstance;\n    BYTE newState;\n    BYTE currentState;\n    BOOL eventGenerated;\n    void* pEventData;\n} SM_StateMachine;\n\n// Generic state function signatures\ntypedef void (*SM_StateFunc)(SM_StateMachine* self, void* pEventData);\ntypedef BOOL (*SM_GuardFunc)(SM_StateMachine* self, void* pEventData);\ntypedef void (*SM_EntryFunc)(SM_StateMachine* self, void* pEventData);\ntypedef void (*SM_ExitFunc)(SM_StateMachine* self);\n\ntypedef struct SM_StateStruct\n{\n    SM_StateFunc pStateFunc;\n} SM_StateStruct;\n\ntypedef struct SM_StateStructEx\n{\n    SM_StateFunc pStateFunc;\n    SM_GuardFunc pGuardFunc;\n    SM_EntryFunc pEntryFunc;\n    SM_ExitFunc pExitFunc;\n} SM_StateStructEx;\n\n// Public functions\n#define SM_Event(_smName_, _eventFunc_, _eventData_) \\\n    _eventFunc_(&_smName_##Obj, _eventData_)\n#define SM_Get(_smName_, _getFunc_) \\\n    _getFunc_(&_smName_##Obj)\n\n// Protected functions\n#define SM_InternalEvent(_newState_, _eventData_) \\\n    _SM_InternalEvent(self, _newState_, _eventData_)\n#define SM_GetInstance(_instance_) \\\n    (_instance_*)(self->pInstance);\n\n// Private functions\nvoid _SM_ExternalEvent(SM_StateMachine* self, const SM_StateMachineConst* selfConst, BYTE newState, void* pEventData);\nvoid _SM_InternalEvent(SM_StateMachine* self, BYTE newState, void* pEventData);\nvoid _SM_StateEngine(SM_StateMachine* self, const SM_StateMachineConst* selfConst);\nvoid _SM_StateEngineEx(SM_StateMachine* self, const SM_StateMachineConst* selfConst);\n\n#define SM_DECLARE(_smName_) \\\n    extern SM_StateMachine _smName_##Obj; \n\n#define SM_DEFINE(_smName_, _instance_) \\\n    SM_StateMachine _smName_##Obj = { #_smName_, _instance_, \\\n        0, 0, 0, 0 }; \n\n#define EVENT_DECLARE(_eventFunc_, _eventData_) \\\n    void _eventFunc_(SM_StateMachine* self, _eventData_* pEventData);\n\n#define EVENT_DEFINE(_eventFunc_, _eventData_) \\\n    void _eventFunc_(SM_StateMachine* self, _eventData_* pEventData)\n\n#define GET_DECLARE(_getFunc_, _getData_) \\\n    _getData_ _getFunc_(SM_StateMachine* self);\n\n#define GET_DEFINE(_getFunc_, _getData_) \\\n    _getData_ _getFunc_(SM_StateMachine* self)\n\n#define STATE_DECLARE(_stateFunc_, _eventData_) \\\n    static void ST_##_stateFunc_(SM_StateMachine* self, _eventData_* pEventData);\n\n#define STATE_DEFINE(_stateFunc_, _eventData_) \\\n    static void ST_##_stateFunc_(SM_StateMachine* self, _eventData_* pEventData)\n\n#define GUARD_DECLARE(_guardFunc_, _eventData_) \\\n    static BOOL GD_##_guardFunc_(SM_StateMachine* self, _eventData_* pEventData);\n\n#define GUARD_DEFINE(_guardFunc_, _eventData_) \\\n    static BOOL GD_##_guardFunc_(SM_StateMachine* self, _eventData_* pEventData)\n\n#define ENTRY_DECLARE(_entryFunc_, _eventData_) \\\n    static void EN_##_entryFunc_(SM_StateMachine* self, _eventData_* pEventData);\n\n#define ENTRY_DEFINE(_entryFunc_, _eventData_) \\\n    static void EN_##_entryFunc_(SM_StateMachine* self, _eventData_* pEventData)\n\n#define EXIT_DECLARE(_exitFunc_) \\\n    static void EX_##_exitFunc_(SM_StateMachine* self);\n\n#define EXIT_DEFINE(_exitFunc_) \\\n    static void EX_##_exitFunc_(SM_StateMachine* self)\n\n#define BEGIN_STATE_MAP(_smName_) \\\n    static const SM_StateStruct _smName_##StateMap[] = { \n\n#define STATE_MAP_ENTRY(_stateFunc_) \\\n    { (SM_StateFunc)_stateFunc_ },\n\n#define END_STATE_MAP(_smName_) \\\n    }; \\\n    static const SM_StateMachineConst _smName_##Const = { #_smName_, \\\n        (sizeof(_smName_##StateMap)/sizeof(_smName_##StateMap[0])), \\\n        _smName_##StateMap, NULL };\n\n#define BEGIN_STATE_MAP_EX(_smName_) \\\n    static const SM_StateStructEx _smName_##StateMap[] = { \n\n#define STATE_MAP_ENTRY_EX(_stateFunc_) \\\n    { (SM_StateFunc)_stateFunc_, NULL, NULL, NULL },\n\n#define STATE_MAP_ENTRY_ALL_EX(_stateFunc_, _guardFunc_, _entryFunc_, _exitFunc_) \\\n    { (SM_StateFunc)_stateFunc_, (SM_GuardFunc)_guardFunc_, (SM_EntryFunc)_entryFunc_, (SM_ExitFunc)_exitFunc_ },\n\n#define END_STATE_MAP_EX(_smName_) \\\n    }; \\\n    static const SM_StateMachineConst _smName_##Const = { #_smName_, \\\n        (sizeof(_smName_##StateMap)/sizeof(_smName_##StateMap[0])), \\\n        NULL, _smName_##StateMap };\n\n#define BEGIN_TRANSITION_MAP \\\n    static const BYTE TRANSITIONS[] = { \\\n\n#define TRANSITION_MAP_ENTRY(_entry_) \\\n    _entry_,\n\n#define END_TRANSITION_MAP(_smName_, _eventData_) \\\n    }; \\\n    _SM_ExternalEvent(self, &_smName_##Const, TRANSITIONS[self->currentState], _eventData_); \\\n    C_ASSERT((sizeof(TRANSITIONS)/sizeof(BYTE)) == (sizeof(_smName_##StateMap)/sizeof(_smName_##StateMap[0])));\n\n#ifdef __cplusplus\n}\n#endif\n \n#endif // _STATE_MACHINE_H\n"
  },
  {
    "path": "fb_allocator.c",
    "content": "#include \"fb_allocator.h\"\n#include \"DataTypes.h\"\n#include \"Fault.h\"\n#include <string.h>\n\n// Define USE_LOCK to use the default lock implementation\n#define USE_LOCKS\n#ifdef USE_LOCKS\n    #include \"LockGuard.h\"\n    static LOCK_HANDLE _hLock;\n#else\n    #pragma message(\"WARNING: Define software lock.\")\n    typedef int LOCK_HANDLE;\n    static LOCK_HANDLE _hLock;\n\n    #define LK_CREATE()     (1)\n    #define LK_DESTROY(h)  \n    #define LK_LOCK(h)    \n    #define LK_UNLOCK(h)  \n#endif\n\n// Get a pointer to the client's area within a memory block\n#define GET_CLIENT_PTR(_block_ptr_) \\\n    (_block_ptr_ ? ((void*)((char*)_block_ptr_)) : NULL)\n\n// Get a pointer to the block using a client pointer\n#define GET_BLOCK_PTR(_client_ptr_) \\\n    (_client_ptr_ ? ((void*)((char*)_client_ptr_)) : NULL)\n\nstatic void* ALLOC_NewBlock(ALLOC_Allocator* alloc);\nstatic void ALLOC_Push(ALLOC_Allocator* alloc, void* pBlock);\nstatic void* ALLOC_Pop(ALLOC_Allocator* alloc);\n\n//----------------------------------------------------------------------------\n// ALLOC_NewBlock\n//----------------------------------------------------------------------------\nstatic void* ALLOC_NewBlock(ALLOC_Allocator* self)\n{\n    ALLOC_Block* pBlock = NULL;\n\n    LK_LOCK(_hLock);\n\n    // If we have not exceeded the pool maximum\n    if (self->poolIndex < self->maxBlocks)\n    {\n        // Get pointer to a new fixed memory block within the pool\n        pBlock = (void*)(self->pPool + (self->poolIndex++ * self->blockSize));\n    }\n\n    LK_UNLOCK(_hLock);\n\n    if (!pBlock)\n    {\n        // Out of fixed block memory\n        ASSERT();\n    }\n\n    return pBlock;\n} \n\n//----------------------------------------------------------------------------\n// ALLOC_Push\n//----------------------------------------------------------------------------\nstatic void ALLOC_Push(ALLOC_Allocator* self, void* pBlock)\n{\n    if (!pBlock)\n        return;\n\n    // Get a pointer to the client's location within the block\n    ALLOC_Block* pClient = (ALLOC_Block*)GET_CLIENT_PTR(pBlock);\n\n    LK_LOCK(_hLock);\n\n    // Point client block's next pointer to head\n    pClient->pNext = self->pHead;\n\n    // The client block is now the new head\n    self->pHead = pClient;\n\n    LK_UNLOCK(_hLock); \n}\n\n//----------------------------------------------------------------------------\n// ALLOC_Pop\n//----------------------------------------------------------------------------\nstatic void* ALLOC_Pop(ALLOC_Allocator* self)\n{\n    ALLOC_Block* pBlock = NULL;\n\n    LK_LOCK(_hLock);\n\n    // Is the free-list empty?\n    if (self->pHead)\n    {\n        // Remove the head block\n        pBlock = self->pHead;\n\n        // Set the head to the next block\n        self->pHead = self->pHead->pNext;\n    }\n\n    LK_UNLOCK(_hLock); \n    return GET_BLOCK_PTR(pBlock);\n} \n\n//----------------------------------------------------------------------------\n// ALLOC_Init\n//----------------------------------------------------------------------------\nvoid ALLOC_Init()\n{\n    _hLock = LK_CREATE();\n} \n\n//----------------------------------------------------------------------------\n// ALLOC_Term\n//----------------------------------------------------------------------------\nvoid ALLOC_Term()\n{\n    LK_DESTROY(_hLock);\n}\n\n//----------------------------------------------------------------------------\n// ALLOC_Alloc\n//----------------------------------------------------------------------------\nvoid* ALLOC_Alloc(ALLOC_HANDLE hAlloc, size_t size)\n{\n    ALLOC_Allocator* self = NULL;\n    void* pBlock = NULL;\n\n    ASSERT_TRUE(hAlloc);\n\n    // Convert handle to an ALLOC_Allocator instance\n    self = (ALLOC_Allocator*)hAlloc;\n\n    // Ensure requested size fits within memory block \n    ASSERT_TRUE(size <= self->blockSize);\n\n    // Get a block from the free-list\n    pBlock = ALLOC_Pop(self);\n\n    // If the free-list empty?\n    if (!pBlock)\n    {\n        // Get a new block from the pool\n        pBlock = ALLOC_NewBlock(self);\n    }\n\n    if (pBlock)\n    {\n        // Keep track of usage statistics\n        self->allocations++;\n        self->blocksInUse++;\n        if (self->blocksInUse > self->maxBlocksInUse)\n        {\n            self->maxBlocksInUse = self->blocksInUse;\n        }\n    }\n\n    return GET_CLIENT_PTR(pBlock);\n} \n\n//----------------------------------------------------------------------------\n// ALLOC_Calloc\n//----------------------------------------------------------------------------\nvoid* ALLOC_Calloc(ALLOC_HANDLE hAlloc, size_t num, size_t size)\n{\n    void* pMem = NULL;\n    size_t n = 0;\n\n    ASSERT_TRUE(hAlloc);\n\n    // Compute the total size of the block\n    n = num * size;\n\n    // Allocate the memory\n    pMem = ALLOC_Alloc(hAlloc, n);\n\n    if (pMem != NULL)\n    {\n        // Initialize memory to 0 per calloc behavior \n        memset(pMem, 0, n);\n    }\n\n    return pMem;\n}\n\n//----------------------------------------------------------------------------\n// ALLOC_Free\n//----------------------------------------------------------------------------\nvoid ALLOC_Free(ALLOC_HANDLE hAlloc, void* pBlock)\n{\n    ALLOC_Allocator* self = NULL;\n\n    if (!pBlock)\n        return;\n\n    ASSERT_TRUE(hAlloc);\n\n    // Cast handle to an allocator instance\n    self = (ALLOC_Allocator*)hAlloc;\n\n    // Get a pointer to the block\n    pBlock = GET_BLOCK_PTR(pBlock);\n\n    // Push the block onto a stack (i.e. the free-list)\n    ALLOC_Push(self, pBlock);\n\n    // Keep track of usage statistics\n    self->deallocations++;\n    self->blocksInUse--;\n} \n\n\n\n"
  },
  {
    "path": "fb_allocator.h",
    "content": "// https://github.com/endurodave/C_Allocator\n//\n// The fb_allocator is a fixed block memory allocator that handles a \n// single block size. \n//\n// Create an allocator instance using the ALLOC_DEFINE macro. Call \n// ALLOC_Init() one time at startup. ALLOC_Alloc() allocates a fixed \n// memory block. ALLOC_Free() frees the block. \n//\n// #include \"fb_allocator.h\"\n// ALLOC_DEFINE(myAllocator, 32, 5)\n//\n// void main() \n// {\n//      void* block;\n//      ALLOC_Init();\n//      block = ALLOC_Alloc(myAllocator, 32);\n//      ALLOC_Free(myAllocator, block);\n// }\n\n#ifndef _FB_ALLOCATOR_H\n#define _FB_ALLOCATOR_H\n\n#include <stdlib.h>\n#include \"DataTypes.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef void* ALLOC_HANDLE;\n\ntypedef struct \n{\n    void* pNext;\n} ALLOC_Block;\n\n// Use ALLOC_DEFINE to declare an ALLOC_Allocator object\ntypedef struct\n{\n    const char* name;\n    const char* pPool;\n    const size_t objectSize;\n    const size_t blockSize;\n    const UINT32 maxBlocks;\n    ALLOC_Block* pHead;\n    UINT16 poolIndex;\n    UINT16 blocksInUse;\n    UINT16 maxBlocksInUse;\n    UINT16 allocations;\n    UINT16 deallocations;\n} ALLOC_Allocator;\n\n// Align fixed blocks on X-byte boundary based on CPU architecture.\n// Set value to 1, 2, 4 or 8.\n#define ALLOC_MEM_ALIGN   (1)\n\n// Get the maximum between a or b\n#define ALLOC_MAX(a,b) (((a)>(b))?(a):(b))\n\n// Round _numToRound_ to the next higher _multiple_\n#define ALLOC_ROUND_UP(_numToRound_, _multiple_) \\\n    (((_numToRound_ + _multiple_ - 1) / _multiple_) * _multiple_)\n\n// Ensure the memory block size is: (a) is aligned on desired boundary and (b) at\n// least the size of a ALLOC_Allocator*. \n#define ALLOC_BLOCK_SIZE(_size_) \\\n    (ALLOC_MAX((ALLOC_ROUND_UP(_size_, ALLOC_MEM_ALIGN)), sizeof(ALLOC_Allocator*)))\n\n// Defines block memory, allocator instance and a handle. On the example below, \n// the ALLOC_Allocator instance is myAllocatorObj and the handle is myAllocator.\n// _name_ - the allocator name\n// _size_ - fixed memory block size in bytes\n// _objects_ - number of fixed memory blocks \n// e.g. ALLOC_DEFINE(myAllocator, 32, 10)\n#define ALLOC_DEFINE(_name_, _size_, _objects_) \\\n    static char _name_##Memory[ALLOC_BLOCK_SIZE(_size_) * (_objects_)] = { 0 }; \\\n    static ALLOC_Allocator _name_##Obj = { #_name_, _name_##Memory, _size_, \\\n        ALLOC_BLOCK_SIZE(_size_), _objects_, NULL, 0, 0, 0, 0, 0 }; \\\n    static ALLOC_HANDLE _name_ = &_name_##Obj;\n\nvoid ALLOC_Init(void);\nvoid ALLOC_Term(void);\nvoid* ALLOC_Alloc(ALLOC_HANDLE hAlloc, size_t size);\nvoid* ALLOC_Calloc(ALLOC_HANDLE hAlloc, size_t num, size_t size);\nvoid ALLOC_Free(ALLOC_HANDLE hAlloc, void* pBlock);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif  // _FB_ALLOCATOR_H\n\n\n\n\n"
  },
  {
    "path": "main.c",
    "content": "#include \"fb_allocator.h\"\r\n#include \"StateMachine.h\"\r\n#include \"Motor.h\"\r\n#include \"CentrifugeTest.h\"\r\n\r\n// @see https://github.com/endurodave/C_StateMachine\r\n// \r\n// Other related repos:\r\n// @see https://github.com/endurodave/C_StateMachineWithThreads\r\n// @see https://github.com/endurodave/C_Allocator\r\n\r\n// Define motor objects\r\nstatic Motor motorObj1;\r\nstatic Motor motorObj2;\r\n\r\n// Define two public Motor state machine instances\r\nSM_DEFINE(Motor1SM, &motorObj1)\r\nSM_DEFINE(Motor2SM, &motorObj2)\r\n\r\nint main(void)\r\n{\r\n    ALLOC_Init();\r\n\r\n    MotorData* data;\r\n\r\n    // Create event data\r\n    data = SM_XAlloc(sizeof(MotorData));\r\n    data->speed = 100;\r\n\r\n    // Call MTR_SetSpeed event function to start motor\r\n    SM_Event(Motor1SM, MTR_SetSpeed, data);\r\n\r\n    // Call MTR_SetSpeed event function to change motor speed\r\n    data = SM_XAlloc(sizeof(MotorData));\r\n    data->speed = 200;\r\n    SM_Event(Motor1SM, MTR_SetSpeed, data);\r\n\r\n    // Get current speed from Motor1SM\r\n    INT currentSpeed = SM_Get(Motor1SM, MTR_GetSpeed);\r\n\r\n    // Stop motor again will be ignored\r\n    SM_Event(Motor1SM, MTR_Halt, NULL);\r\n\r\n    // Motor2SM example\r\n    data = SM_XAlloc(sizeof(MotorData));\r\n    data->speed = 300;\r\n    SM_Event(Motor2SM, MTR_SetSpeed, data);\r\n    SM_Event(Motor2SM, MTR_Halt, NULL);\r\n\r\n    // CentrifugeTestSM example\r\n    SM_Event(CentrifugeTestSM, CFG_Cancel, NULL);\r\n    SM_Event(CentrifugeTestSM, CFG_Start, NULL);\r\n    while (CFG_IsPollActive())\r\n        SM_Event(CentrifugeTestSM, CFG_Poll, NULL);\r\n\r\n    ALLOC_Term();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "sm_allocator.c",
    "content": "// SMALLOC allocates either a 32 or 128 byte block depending \n// on the requested size. \n\n#include \"sm_allocator.h\"\n#include \"x_allocator.h\"\n\n// Maximum number of blocks for each size\n#define MAX_32_BLOCKS   10\n#define MAX_128_BLOCKS\t5\n\n// Define size of each block including meta data overhead\n#define BLOCK_32_SIZE     32 + XALLOC_BLOCK_META_DATA_SIZE\n#define BLOCK_128_SIZE    128 + XALLOC_BLOCK_META_DATA_SIZE\n\n// Define individual fb_allocators\nALLOC_DEFINE(smDataAllocator32, BLOCK_32_SIZE, MAX_32_BLOCKS)\nALLOC_DEFINE(smDataAllocator128, BLOCK_128_SIZE, MAX_128_BLOCKS)\n\n// An array of allocators sorted by smallest block first\nstatic ALLOC_Allocator* allocators[] = {\n    &smDataAllocator32Obj,\n    &smDataAllocator128Obj\n};\n\n#define MAX_ALLOCATORS   (sizeof(allocators) / sizeof(allocators[0]))\n\nstatic XAllocData self = { allocators, MAX_ALLOCATORS };\n\n//----------------------------------------------------------------------------\n// SMALLOC_Alloc\n//----------------------------------------------------------------------------\nvoid* SMALLOC_Alloc(size_t size)\n{\n    return XALLOC_Alloc(&self, size);\n}\n\n//----------------------------------------------------------------------------\n// SMALLOC_Free\n//----------------------------------------------------------------------------\nvoid SMALLOC_Free(void* ptr)\n{\n    XALLOC_Free(ptr);\n}\n\n//----------------------------------------------------------------------------\n// SMALLOC_Realloc\n//----------------------------------------------------------------------------\nvoid* SMALLOC_Realloc(void *ptr, size_t new_size)\n{\n    return XALLOC_Realloc(&self, ptr, new_size);\n}\n\n//----------------------------------------------------------------------------\n// SMALLOC_Calloc\n//----------------------------------------------------------------------------\nvoid* SMALLOC_Calloc(size_t num, size_t size)\n{\n    return XALLOC_Calloc(&self, num, size);\n}\n\n"
  },
  {
    "path": "sm_allocator.h",
    "content": "#ifndef _SM_ALLOCATOR_H\n#define _SM_ALLOCATOR_H\n\n#include <stddef.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nvoid* SMALLOC_Alloc(size_t size);\nvoid SMALLOC_Free(void* ptr);\nvoid* SMALLOC_Realloc(void *ptr, size_t new_size);\nvoid* SMALLOC_Calloc(size_t num, size_t size);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // _SM_ALLOCATOR_H\n"
  },
  {
    "path": "x_allocator.c",
    "content": "#include \"x_allocator.h\"\n#include \"fb_allocator.h\"\n#include \"DataTypes.h\"\n#include \"Fault.h\"\n#include <string.h>\n\nstatic void* XALLOC_PutAllocatorPtrInBlock(void* block, ALLOC_Allocator* allocator);\nstatic ALLOC_Allocator* XALLOC_GetAllocatorPtrFromBlock(void* block);\nstatic ALLOC_Allocator* XALLOC_GetAllocator(XAllocData* self, size_t size);\n\n//----------------------------------------------------------------------------\n// XALLOC_PutAllocatorPtrInBlock\n//----------------------------------------------------------------------------\nstatic void* XALLOC_PutAllocatorPtrInBlock(void* block, ALLOC_Allocator* allocator)\n{\n    ALLOC_Allocator** pAllocatorInBlock;\n\n    ASSERT_TRUE(block);\n    ASSERT_TRUE(allocator);\n\n    // Cast raw block memory to ALLOC_Allocator**\n    pAllocatorInBlock = (ALLOC_Allocator**)(block);\n\n    // Store the allocator pointer in the memory block \n    *pAllocatorInBlock = allocator;\n\n    // Advance the pointer past the ALLOC_Allocator* and return a\n    // pointer to the client's memory region\n    return ++pAllocatorInBlock;\n}\n\n//----------------------------------------------------------------------------\n// XALLOC_GetAllocatorPtrFromBlock\n//----------------------------------------------------------------------------\nstatic ALLOC_Allocator* XALLOC_GetAllocatorPtrFromBlock(void* block)\n{\n    ALLOC_Allocator** pAllocatorInBlock;\n\n    ASSERT_TRUE(block);\n\n    // Cast raw memory block to ALLOC_Allocator**\n    pAllocatorInBlock = (ALLOC_Allocator**)(block);\n\n    // Backup one ALLOC_Allocator* position to get the stored allocator instance\n    pAllocatorInBlock--;\n\n    // Return the allocator instance stored within the memory block\n    return *pAllocatorInBlock;\n}\n\n//----------------------------------------------------------------------------\n// XALLOC_GetBlockPtr\n//----------------------------------------------------------------------------\nstatic void* XALLOC_GetBlockPtr(void* block)\n{\n    ALLOC_Allocator** pAllocatorInBlock;\n\n    ASSERT_TRUE(block);\n\n    // Cast the client memory to ALLOC_Allocator* \n    pAllocatorInBlock = (ALLOC_Allocator**)(block);\n\n    // Back up one ALLOC_Allocator* position and return raw memory block pointer\n    return --pAllocatorInBlock;\n}\n\n//----------------------------------------------------------------------------\n// XALLOC_GetAllocator\n//----------------------------------------------------------------------------\nstatic ALLOC_Allocator* XALLOC_GetAllocator(XAllocData* self, size_t size)\n{\n    UINT16 i = 0;\n    ALLOC_Allocator* pAllocator = NULL;\n\n    ASSERT_TRUE(self);\n\n    // Each block stores additional meta data (i.e. an ALLOC_Allocator pointer). \n    // Add overhead for the additional memory required.\n    size += XALLOC_BLOCK_META_DATA_SIZE;\n\n    // Iterate over all allocators \n    for (i=0; i<self->maxAllocators; i++)\n    {\n        // Can the allocator instance handle the requested size?\n        if (self->allocators[i] && self->allocators[i]->blockSize >= size)\n        {\n            // Return allocator instance to handle memory request\n            pAllocator = self->allocators[i];\n            break;\n        }\n    }\n\n    return pAllocator;\n} \n\n//----------------------------------------------------------------------------\n// XALLOC_Alloc\n//----------------------------------------------------------------------------\nvoid* XALLOC_Alloc(XAllocData* self, size_t size)\n{\n    ALLOC_Allocator* pAllocator;\n    void* pBlockMemory = NULL;\n    void* pClientMemory = NULL;\n\n    ASSERT_TRUE(self);\n\n    // Get an allocator instance to handle the memory request\n    pAllocator = XALLOC_GetAllocator(self, size);\n\n    // An allocator found to handle memory request?\n    if (pAllocator)\n    {\n        // Get a fixed memory block from the allocator instance\n        pBlockMemory = ALLOC_Alloc(pAllocator, size + XALLOC_BLOCK_META_DATA_SIZE);\n        if (pBlockMemory)\n        {\n            // Set the block ALLOC_Allocator* ptr within the raw memory block region\n            pClientMemory = XALLOC_PutAllocatorPtrInBlock(pBlockMemory, pAllocator);\n        }\n    }\n    else\n    {\n        // Too large a memory block requested\n        ASSERT();\n    }\n\n    return pClientMemory;\n} \n\n//----------------------------------------------------------------------------\n// XALLOC_Free\n//----------------------------------------------------------------------------\nvoid XALLOC_Free(void* ptr)\n{\n    ALLOC_Allocator* pAllocator = NULL;\n    void* pBlock = NULL;\n\n    if (!ptr)\n        return;\n\n    // Extract the original allocator instance from the caller's block pointer\n    pAllocator = XALLOC_GetAllocatorPtrFromBlock(ptr);\n    if (pAllocator)\n    {\n        // Convert the client pointer into the original raw block pointer\n        pBlock = XALLOC_GetBlockPtr(ptr);\n\n        // Deallocate the fixed memory block\n        ALLOC_Free(pAllocator, pBlock);\n    }\n} \n\n//----------------------------------------------------------------------------\n// XALLOC_Realloc\n//----------------------------------------------------------------------------\nvoid* XALLOC_Realloc(XAllocData* self, void *ptr, size_t new_size)\n{\n    void* pNewMem = NULL;\n    ALLOC_Allocator* pOldAllocator = NULL;\n    size_t oldSize = 0;\n\n    ASSERT_TRUE(self);\n\n    if (!ptr)\n        pNewMem = XALLOC_Alloc(self, new_size);\n    else if (0 == new_size)\n        XALLOC_Free(ptr);\n    else\n    {\n        // Create a new memory block\n        pNewMem = XALLOC_Alloc(self, new_size);\n        if (pNewMem != 0)\n        {\n            // Get the original allocator instance from the old memory block\n            pOldAllocator = XALLOC_GetAllocatorPtrFromBlock(ptr);\n            oldSize = pOldAllocator->blockSize - XALLOC_BLOCK_META_DATA_SIZE;\n\n            // Copy the bytes from the old memory block into the new (as much as will fit)\n            memcpy(pNewMem, ptr, (oldSize < new_size) ? oldSize : new_size);\n\n            // Free the old memory block\n            XALLOC_Free(ptr);\n        }\n    }\n\n    // Return the client pointer to the new memory block\n    return pNewMem;\n} \n\n//----------------------------------------------------------------------------\n// XALLOC_Calloc\n//----------------------------------------------------------------------------\nvoid* XALLOC_Calloc(XAllocData* self, size_t num, size_t size)\n{\n    void* pMem = NULL;\n    size_t n;\n\n    ASSERT_TRUE(self);\n\n    // Compute the total block size\n    n = num * size;\n\n    // Allocate the memory\n    pMem = XALLOC_Alloc(self, n);\n\n    if (pMem)\n    {\n        // Initialize memory to 0\n        memset(pMem, 0, n);\n    }\n\n    return pMem;\n} \n\n\n\n"
  },
  {
    "path": "x_allocator.h",
    "content": "// @see https://github.com/endurodave/C_Allocator\n//\n// The x_allocator is a fixed block memory allocator that handles multiple \n// block sizes by using two or more fb_allocator objects. Typically users \n// create a thin wrapper module for each x_allocator managed memory blocks. \n//\n// For example, create a XAllocData instance and wrapper functions \n// in my_allocator.c:\n//\n// #define MAX_32_BLOCKS   10\n// #define MAX_128_BLOCKS   5\n// #define MAX_512_BLOCKS   2\n//\n// #define BLOCK_32_SIZE           32 + XALLOC_BLOCK_META_DATA_SIZE\n// #define BLOCK_128_SIZE          128 + XALLOC_BLOCK_META_DATA_SIZE\n// #define BLOCK_512_SIZE          512 + XALLOC_BLOCK_META_DATA_SIZE\n//\n// // Define each fb_allocator instance\n// ALLOC_DEFINE(myAllocator32, BLOCK_32_SIZE, MAX_32_BLOCKS)\n// ALLOC_DEFINE(myAllocator128, BLOCK_128_SIZE, MAX_128_BLOCKS)\n// ALLOC_DEFINE(myAllocator512, BLOCK_512_SIZE, MAX_512_BLOCKS)\n//\n// // An array of allocators sorted by smallest to largest block \n// static ALLOC_Allocator* allocators[] = {\n//    &myAllocator32Obj,\n//    &myAllocator128Obj,\n//    &myAllocator512Obj\n// };\n//\n// #define MAX_ALLOCATORS   (sizeof(allocators) / sizeof(allocators[0]))\n//\n// static XAllocData self = { allocators, MAX_ALLOCATORS };\n//\n// // Thin allocator wrapper function implementations call XALLOC\n// void* MYALLOC_Alloc(size_t size) { return XALLOC_Alloc(&self, size); }\n// void MYALLOC_Free(void* ptr) { XALLOC_Free(ptr); }\n// void* MYALLOC_Realloc(void *ptr, size_t new_size) { return XALLOC_Realloc(&self, ptr, new_size); }\n// void* MYALLOC_Calloc(size_t num, size_t size) { return XALLOC_Calloc(&self, num, size); }\n//\n// Expose the allocator functions in my_allocator.h:\n//\n// void* MYALLOC_Alloc(size_t size);\n// void MYALLOC_Free(void* ptr);\n// void* MYALLOC_Realloc(void *ptr, size_t new_size);\n// void* MYALLOC_Calloc(size_t num, size_t size);\n\n#ifndef _X_ALLOCATOR_H\n#define _X_ALLOCATOR_H\n\n#include \"fb_allocator.h\"\n#include <stddef.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// Overhead bytes added to each XALLOC memory block\n#define XALLOC_BLOCK_META_DATA_SIZE  sizeof(ALLOC_Allocator*)\n\ntypedef struct\n{\n    // Array of allocator instances sorted from smallest to largest block\n    ALLOC_Allocator* const *allocators;\n\n    // Number of allocator instances stored within the allocators array\n    const UINT16 maxAllocators;\n} XAllocData;\n\nvoid* XALLOC_Alloc(XAllocData* self, size_t size);\nvoid XALLOC_Free(void* ptr);\nvoid* XALLOC_Realloc(XAllocData* self, void *ptr, size_t new_size);\nvoid* XALLOC_Calloc(XAllocData* self, size_t num, size_t size);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // _X_ALLOCATOR_H\n"
  }
]