### Build Examples Configuration Source: https://github.com/andrew-gresyk/hfsm2/blob/master/CMakeLists.txt Configures the build process for the HFSM2 examples. It checks for the existence of an examples directory and adds subdirectories containing CMakeLists.txt files. ```cmake # Examples section option(HFSM2_BUILD_EXAMPLES "Build the examples" OFF) if(HFSM2_BUILD_EXAMPLES) # Check if examples directory exists if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/examples") # Get all subdirectories in examples folder file(GLOB EXAMPLE_DIRS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/examples" "${CMAKE_CURRENT_SOURCE_DIR}/examples/*") foreach(EXAMPLE_DIR ${EXAMPLE_DIRS}) # Check if the subdirectory contains a CMakeLists.txt if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/examples/${EXAMPLE_DIR}/CMakeLists.txt") message(STATUS "Adding example: ${EXAMPLE_DIR}") add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/examples/${EXAMPLE_DIR}") endif() endforeach() else() message(STATUS "Examples directory not found, skipping examples") endif() endif() ``` -------------------------------- ### Library and Header Installation Source: https://github.com/andrew-gresyk/hfsm2/blob/master/CMakeLists.txt Configures the installation of the HFSM2 library targets and header files. This ensures that the library can be found and used by other projects. ```cmake # Install the library install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}Targets INCLUDES DESTINATION include ) # Install the headers install(DIRECTORY include/ DESTINATION include) ``` -------------------------------- ### Project Setup and Library Creation Source: https://github.com/andrew-gresyk/hfsm2/blob/master/CMakeLists.txt Initializes the CMake project and creates an interface library for HFSM2. It sets include directories and C++ standard requirements for users of the library. ```cmake cmake_minimum_required(VERSION 3.10) project(hfsm2 VERSION 2.8.0 LANGUAGES CXX) # Create an interface library (header-only) add_library(${PROJECT_NAME} INTERFACE) add_library(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME}) # Set include directories for users of this library target_include_directories(${PROJECT_NAME} INTERFACE $ $ ) # Set C++11 requirement for users of this library target_compile_features(${PROJECT_NAME} INTERFACE cxx_std_11) ``` -------------------------------- ### Minimal State Machine Example Source: https://github.com/andrew-gresyk/hfsm2/wiki/Minimal-Example This C++ code demonstrates a minimal state machine with two states, 'Off' and 'On'. It shows how to define a context, configure the machine, create an instance, transition to a state, update the machine, and assert the context's state. ```cpp #include #include struct Context { bool on = false; }; using Config = hfsm2::Config ::ContextT; using M = hfsm2::MachineT; using FSM = M::PeerRoot< struct Off, struct On >; struct Off : FSM::State { void enter(PlanControl& control) { control.context().on = false; } }; struct On : FSM::State { void enter(PlanControl& control) { control.context().on = true; } }; int main() { Context context; FSM::Instance machine{context}; machine.changeTo(); machine.update(); assert(context.on == true); return 0; } ``` -------------------------------- ### CMakeLists.txt Configuration Source: https://github.com/andrew-gresyk/hfsm2/blob/master/examples/debug_logger_interface/CMakeLists.txt Configures the CMake project, finds source files, sets include directories, and specifies C++ standard and compiler options for the debug logger example. ```cmake cmake_minimum_required(VERSION 3.10) get_filename_component(EXAMPLE_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) project(${EXAMPLE_NAME}_example) file(GLOB SOURCE_FILES "*.cpp") add_executable(${PROJECT_NAME} ${SOURCE_FILES}) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../include) target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_11) if(MSVC) target_compile_options(${PROJECT_NAME} PRIVATE /W4 /WX) else() target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Werror -pedantic) endif() ``` -------------------------------- ### Iterate Over Plan Tasks Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Use first() to get an iterator for range-based for loop iteration over plan tasks. ```cpp CIterator CPlan::first() const; Iterator Plan::first(); ``` -------------------------------- ### Exporting Targets and Configuration Files Source: https://github.com/andrew-gresyk/hfsm2/blob/master/CMakeLists.txt Exports the library targets and generates package configuration files. This allows CMake to find and use the installed HFSM2 library in other projects. ```cmake # Export the targets export(EXPORT ${PROJECT_NAME}Targets FILE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Targets.cmake" NAMESPACE ${PROJECT_NAME}:: ) # Create and install package configuration files include(CMakePackageConfigHelpers) write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion ) # Simple config file approach (no template required) file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" "include(CMakeFindDependencyMacro) include(\" ${CMAKE_CURRENT_LIST_DIR}/${PROJECT_NAME}Targets.cmake\") ") # Install the configuration files install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" DESTINATION lib/cmake/${PROJECT_NAME} ) install(EXPORT ${PROJECT_NAME}Targets FILE ${PROJECT_NAME}Targets.cmake NAMESPACE ${PROJECT_NAME}:: DESTINATION lib/cmake/${PROJECT_NAME} ) ``` -------------------------------- ### Logging and Initialization Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Initialize the Root instance with a context and logger, or attach a logger. ```APIDOC ## Constructor and attachLogger ### Description Construct a Root instance with a context and logger, or attach a logger to an existing instance. ### Method `Root::Root(Context&, Logger* const);` `void Root::attachLogger(Logger* const);` ``` -------------------------------- ### Configure Calculator Project with CMake Source: https://github.com/andrew-gresyk/hfsm2/blob/master/examples/calculator/CMakeLists.txt Sets up the minimum CMake version, project name, and finds source files. This is the standard entry point for CMake projects. ```cmake cmake_minimum_required(VERSION 3.10) get_filename_component(EXAMPLE_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) project(${EXAMPLE_NAME}_example) ``` ```cmake file(GLOB SOURCE_FILES "*.cpp") add_executable(${PROJECT_NAME} ${SOURCE_FILES}) ``` ```cmake target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../include) ``` ```cmake target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_17) ``` ```cmake if(MSVC) target_compile_options(${PROJECT_NAME} PRIVATE /W4 /WX) else() target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Werror -pedantic) endif() ``` -------------------------------- ### Enable Transition History Support Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Transition-History Include this macro before including the machine header to enable transition history support. ```cpp #define HFSM2_ENABLE_TRANSITION_HISTORY #include ``` -------------------------------- ### Configure C++ Project with CMake Source: https://github.com/andrew-gresyk/hfsm2/blob/master/examples/temp/CMakeLists.txt Sets up a C++ executable project, including source files, include directories, C++ standard, and compiler options for MSVC and other compilers. ```cmake cmake_minimum_required(VERSION 3.10) get_filename_component(EXAMPLE_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) project(${EXAMPLE_NAME}_example) file(GLOB SOURCE_FILES "*.cpp") add_executable(${PROJECT_NAME} ${SOURCE_FILES}) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../include) target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_17) if(MSVC) target_compile_options(${PROJECT_NAME} PRIVATE /W4 /WX) else() target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Werror -pedantic) endif() ``` -------------------------------- ### Root FSM Instance Transition Methods Source: https://github.com/andrew-gresyk/hfsm2/wiki/Transitions Use these methods on FSM instances like `Root` to change the current state. Transitions can target a specific state type or a `StateID`. ```cpp void Root::changeTo(); ``` ```cpp void Root::changeTo(StateID); ``` -------------------------------- ### Enable Manual Activation Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Enable manual activation for your FSM instance using Config::ManualActivation. ```cpp Config::ManualActivation ``` -------------------------------- ### Client Code for State Machine Usage Source: https://github.com/andrew-gresyk/hfsm2/wiki/Extended-Tutorial Write client code to instantiate and interact with the defined state machine. This includes setting up context and asserting state. ```cpp TEST_CASE("Wiki.Tutorial") { ``` ```cpp Context context; context.powerOn = true; FSM::Instance fsm{context}; assert(fsm.isActive()); // activated by Off::entryGuard() assert(fsm.isActive()); // On's initial sub-state ``` ```cpp fsm.update(); assert(fsm.isActive()); // 1st setp of On's plan fsm.update(); assert(fsm.isActive()); // 2nd setp of On's plan ``` ```cpp fsm.react(Event{}); assert(fsm.isActive()); // 3rd setp of On's plan ``` ```cpp } ``` -------------------------------- ### Serialization Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Save and load the state of the Root instance. ```APIDOC ## save/load ### Description Handle serialization and deserialization of the Root instance. ### Method `void Root::save(SerialBuffer& buffer) const;` `void Root::load(const SerialBuffer& buffer);` ``` -------------------------------- ### State Transition Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Enqueue a state transition to be executed. ```APIDOC ## changeTo ### Description Enqueue a transition to be executed during the next `update()` or `react()`. ### Method `void Root::changeTo()` `void Root::changeTo(const StateID);` ``` ```APIDOC ## changeWith (Payload) ### Description Enqueue a transition with a `const` payload. ### Method `void Root::changeWith(const TPayload&);` `void Root::changeWith(StateID, const TPayload&);` ``` ```APIDOC ## changeWith (Moved Payload) ### Description Enqueue a transition with a moved payload. ### Method `void Root::changeWith(TPayload&&);` `void Root::changeWith(StateID, TPayload&&);` ``` -------------------------------- ### Manual Activation and Deactivation Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Manually trigger the enter and exit actions for the Root instance. ```APIDOC ## enter/exit ### Description Optional manual activation and deactivation of the Root instance. ### Method `void Root::enter();` `void Root::exit();` ``` -------------------------------- ### FullControl Methods Source: https://github.com/andrew-gresyk/hfsm2/wiki/Controls Methods available on the FullControl object, including all PlanControl functionality plus transition initiation. ```APIDOC ## FullControl ### Description Includes everything from `PlanControl`. ### Methods - `void FullControl::changeTo(const StateID)` - Initiate a transition to a specified state ID. - `void FullControl::changeTo()` - Initiate a transition to a specified state type. - `void FullControl::changeWith(const StateID, const Payload&)` - Initiate a transition with a payload. - `void FullControl::changeWith(const StateID, Payload&&)` - Initiate a transition with a moved payload. - `void FullControl::changeWith(const Payload&)` - Initiate a transition with a payload to a specified state type. - `void FullControl::changeWith(Payload&&)` - Initiate a transition with a moved payload to a specified state type. - `void FullControl::succeed()` - Mark the current task as succeeded. - `void FullControl::fail()` - Mark the current task as failed. ``` -------------------------------- ### Enable Plan Support in HFSM2 Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Define HFSM2_ENABLE_PLANS and include the machine header to enable plan support. ```cpp #define HFSM2_ENABLE_PLANS #include ``` -------------------------------- ### Enable Transition Payloads Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Enable transition payloads using Config::PayloadT, specifying the type for the payload. ```cpp Config::PayloadT ``` -------------------------------- ### FullControl/GuardControl Transition Methods Source: https://github.com/andrew-gresyk/hfsm2/wiki/Transitions These methods are available on controls like `FullControl` and `GuardControl` for triggering state changes. They support transitions to a state type or a `StateID`. ```cpp void FullControl::changeTo(); ``` ```cpp void FullControl::changeTo(StateID); ``` -------------------------------- ### Replication Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Access previous transitions and replay states. ```APIDOC ## previousTransition ### Description Get the previous transition. ### Method `const Transition& Root::previousTransition() const;` ``` ```APIDOC ## replayEnter ### Description Replay the enter action for a given state ID. ### Method `void Root::replayEnter(const StateID);` ``` ```APIDOC ## replayTransition ### Description Replay a transition for a given state ID. ### Method `bool Root::replayTransition(const StateID);` ``` -------------------------------- ### Enable Serialization Support Source: https://github.com/andrew-gresyk/hfsm2/wiki/Feature-Macros Enables support for serializing and deserializing HFSM2 state machines. Use this macro when persistence or state transfer is needed. ```cpp #define HFSM2_ENABLE_SERIALIZATION ``` -------------------------------- ### Access Constant and Mutable Plan Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Use plan() to access a constant plan or plan() to access a mutable plan. ```cpp CPlan PlanControl::plan() const; Plan PlanControl::plan(); ``` -------------------------------- ### Define Basic Config Type Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Use this to define the base Config type for your FSM instance. ```cpp using Config = hfsm2::Config; using M = hfsm2::MachineT; ``` -------------------------------- ### Plan Methods Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Methods for manipulating and querying plan objects. ```APIDOC ## Plan Methods ### Check if Plan is Empty - **`operator CPlan::bool() const;`**: Returns `true` if the plan is not empty, `false` otherwise. ### Iterate Over Plan Tasks - **`CIterator CPlan::first() const;`**: Returns an iterator to the first task in the plan (constant access). - **`Iterator Plan::first();`**: Returns an iterator to the first task in the plan (mutable access). ### Clear Plan - **`void Plan::clear();`**: Removes all tasks from the plan. ### Append Transitions to Plan - **`bool Plan::change(const StateID, const StateID);`**: Appends a default transition from origin to destination state. - **`bool Plan::change(const StateID);`**: Appends a default transition from `TOrigin` state to a specified destination state. - **`bool Plan::change();`**: Appends a default transition between `TOrigin` and `TDestination` states. ### Append Transitions with Payload - **`bool Plan::changeWith(const StateID, const StateID, const Payload&);`**: Appends a default transition with a `const` payload. - **`bool Plan::changeWith(const StateID, const Payload&);`**: Appends a default transition from `TOrigin` state with a `const` payload. - **`bool Plan::changeWith(const Payload&);`**: Appends a default transition between `TOrigin` and `TDestination` states with a `const` payload. - **`bool Plan::changeWith(const StateID, const StateID, Payload&&);`**: Appends a default transition with a moved payload. - **`bool Plan::changeWith(const StateID, Payload&&);`**: Appends a default transition from `TOrigin` state with a moved payload. - **`bool Plan::changeWith(Payload&&);`**: Appends a default transition between `TOrigin` and `TDestination` states with a moved payload. ``` -------------------------------- ### Feature Macros for Logging Source: https://github.com/andrew-gresyk/hfsm2/wiki/Basic-Logging Macros to enable and configure logging support. ```APIDOC ## Feature Macros 1. Enable logging support: ```cpp #define HFSM2_ENABLE_LOG_INTERFACE ``` 1. Log **all** state methods, not just the user-overridden ones: ```cpp #define HFSM2_ENABLE_VERBOSE_DEBUG_LOG ``` ``` -------------------------------- ### State Activation, Reactivation, and Deactivation Source: https://github.com/andrew-gresyk/hfsm2/wiki/State-Methods These methods are executed upon successful transition and handle the activation, reactivation, and deactivation of states. ```APIDOC ## State::enter ### Description Called when a state is entered. ### Method `void State::enter(PlanControl&);` ## State::reenter ### Description Called when a state is re-entered. ### Method `void State::reenter(PlanControl&);` ## State::exit ### Description Called when a state is exited. ### Method `void State::exit(PlanControl&);` ``` -------------------------------- ### Define Context and Machine Types Source: https://github.com/andrew-gresyk/hfsm2/wiki/Context Defines a basic 'Context' struct and configures the HFSM2 machine to use it. ```cpp struct Context {}; using Config = hfsm2::Config::ContextT; using M = hfsm2::MachineT; ``` -------------------------------- ### Instance Methods for Logger Attachment Source: https://github.com/andrew-gresyk/hfsm2/wiki/Basic-Logging Methods for constructing an instance with a logger or attaching one after construction. ```APIDOC ## Instance Methods | Method | Description | | -------------------------------------------- | ------------------------------- | | `Root::Root(const Context&, LoggerInterface* const);` | Construct an instance with logger attached | | `void Root::attachLogger(LoggerInterface* const);` | Attach logger after construction | ``` -------------------------------- ### Actor FSM Implementation Source: https://github.com/andrew-gresyk/hfsm2/wiki/Usage-Class-Members Implements the `Actor` class's FSM logic. It defines the FSM configuration, states, and manages the FSM instance within the `FsmHost` buffer. Static assertions ensure the `FsmHost` is sufficiently aligned and sized. ```cpp #include "actor.hpp" #include namespace actor_fsm { using Config = hfsm2::Config ::ContextT; using M = hfsm2::MachineT; #define S(s) struct s using FSM = M::PeerRoot< S(Off), S(On) >; #undef S struct Off : FSM::State {}; struct On : FSM::State {}; FSM::Instance& fsm( Actor::FsmHost& fsmHost) { return *reinterpret_cast< FSM::Instance*>(&fsmHost); } const FSM::Instance& fsm(const Actor::FsmHost& fsmHost) { return *reinterpret_cast(&fsmHost); } } Actor::Actor() { //hfsm2::StaticPrintConstT alignment; static_assert(alignof(actor_fsm::FSM::Instance) <= alignof(FsmHost), "Uncomment the line above to find out the alignment of the `FsmHost` needed"); //hfsm2::StaticPrintConstT size; static_assert(sizeof(actor_fsm::FSM::Instance) <= sizeof(FsmHost), "Uncomment the line above to find out the size of the `FsmHost` needed"); new (&_fsmHost) actor_fsm::FSM::Instance{*this}; } Actor::~Actor() { hfsm2::destroy(actor_fsm::fsm(_fsmHost)); } void Actor::turnOn() { actor_fsm::fsm(_fsmHost).immediateChangeTo(); } bool Actor::isOn() const { return actor_fsm::fsm(_fsmHost).isActive(); } ``` -------------------------------- ### Define State Methods Source: https://github.com/andrew-gresyk/hfsm2/wiki/Extended-Tutorial Define states and override required state methods like entryGuard, enter, update, exit, react, planSucceeded, and planFailed. ```cpp struct Off : FSM::State { void entryGuard(FullControl& control) { // called before state activation if (control.context().powerOn) // access shared data control.changeTo(); // initiate a transition into 'On' region } void exit(PlanControl& /*control*/) {} }; struct On : FSM::State { void enter(PlanControl& control) { // called on state activation auto plan = control.plan(); // access the plan for the region plan.change(); // sequence plan steps, executed plan.change(); // when the previous state succeeds plan.change(); plan.change(); } void exit(PlanControl& /*control*/) {} void planSucceeded(FullControl& control) { // called on the successful completion control.changeTo(); // of all plan steps } void planFailed(FullControl& /*control*/) {} }; struct Red : FSM::State { void update(FullControl& control) { // called on periodic state machine updates control.succeed(); // notify successful completion of the plan step } // plan will advance to the 'Yellow' state }; struct Yellow : FSM::State { void update(FullControl& control) { control.succeed(); // plan will advance to the 'Green' state // on the first entry and 'Red' state // on the second one } }; struct Green : FSM::State { void react(const Event&, FullControl& control) { // called on external events control.succeed(); // advance to the next plan step } }; struct Done : FSM::State {}; ``` -------------------------------- ### Create Machine Alias Source: https://github.com/andrew-gresyk/hfsm2/wiki/Extended-Tutorial Create a convenient alias for the HFSM2 MachineT template with the defined configuration. ```cpp using M = hfsm2::MachineT; ``` -------------------------------- ### Enable Logging Support Source: https://github.com/andrew-gresyk/hfsm2/wiki/Feature-Macros Enables logging support for HFSM2. Define HFSM2_ENABLE_LOG_INTERFACE for basic logging and HFSM2_ENABLE_VERBOSE_DEBUG_LOG for more detailed debug logs. ```cpp #define HFSM2_ENABLE_LOG_INTERFACE #define HFSM2_ENABLE_VERBOSE_DEBUG_LOG ``` -------------------------------- ### Build Tests Configuration Source: https://github.com/andrew-gresyk/hfsm2/blob/master/CMakeLists.txt Configures the build process for the HFSM2 tests. This includes enabling testing, finding test source files, and setting compiler options based on the compiler. ```cmake # Testing section option(HFSM2_BUILD_TESTS "Build the HFSM2 tests" OFF) if(HFSM2_BUILD_TESTS) enable_testing() file(GLOB TEST_SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/test/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/test/*/*.cpp") add_executable(${PROJECT_NAME}_test ${TEST_SOURCE_FILES}) target_include_directories(${PROJECT_NAME}_test PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/external" "${CMAKE_CURRENT_SOURCE_DIR}/include") target_compile_features(${PROJECT_NAME}_test PRIVATE cxx_std_11) if(MSVC) target_compile_options(${PROJECT_NAME}_test PRIVATE /W4 /WX) else() target_compile_options(${PROJECT_NAME}_test PRIVATE -Werror -Wall -Wextra -Wpedantic -Wshadow -Wold-style-cast) endif() add_test(NAME ${PROJECT_NAME}_test COMMAND ${PROJECT_NAME}_test) add_custom_command(TARGET ${PROJECT_NAME}_test POST_BUILD COMMAND ${PROJECT_NAME}_test) endif() ``` -------------------------------- ### Enable Logging Interface Source: https://github.com/andrew-gresyk/hfsm2/wiki/Basic-Logging Define this macro to enable the logging interface for custom logger implementations. ```cpp #define HFSM2_ENABLE_LOG_INTERFACE ``` -------------------------------- ### Set Context Type Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Configure the context type for your FSM instance using Config::ContextT. ```cpp Config::ContextT<> ``` -------------------------------- ### Set Transition Substitution Limit Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Set the limit for transition destination substitution using Config::SubstitutionLimitN. ```cpp Config::SubstitutionLimitN<> ``` -------------------------------- ### Enable Verbose Debug Logging Source: https://github.com/andrew-gresyk/hfsm2/wiki/Basic-Logging Define this macro to log all state methods, not just user-overridden ones, for detailed debugging. ```cpp #define HFSM2_ENABLE_VERBOSE_DEBUG_LOG ``` -------------------------------- ### Enable Transition History Reporting Source: https://github.com/andrew-gresyk/hfsm2/wiki/Feature-Macros Enables reporting of transition history within the state machine. Useful for debugging and understanding the sequence of state changes. ```cpp #define HFSM2_ENABLE_TRANSITION_HISTORY ``` -------------------------------- ### Enable Serialization Support in C++ Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Serialization To enable serialization, define HFSM2_ENABLE_SERIALIZATION before including the machine header. This macro activates the necessary components for saving and loading FSM states. ```cpp #define HFSM2_ENABLE_SERIALIZATION #include ``` -------------------------------- ### PlanControl Methods Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Methods for accessing and controlling plans within the HFSM2 state machine. ```APIDOC ## PlanControl Methods ### Access Plan - **`CPlan PlanControl::plan() const;`**: Access a constant reference to the plan. - **`Plan PlanControl::plan();`**: Access a mutable reference to the plan. ### Plan Completion - **`void PlanControl::succeed();`**: Called when all tasks within a plan have succeeded. - **`void PlanControl::fail();`**: Called when any task within a plan has failed. ``` -------------------------------- ### Transition with Moved Payload Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Transition-Payloads Use the changeWith method with an rvalue reference (&&) to a payload for default transitions. This allows the payload to be moved into the transition, potentially improving efficiency. ```cpp void Plan::changeWith(const StateID, Payload&&); ``` ```cpp void Plan::changeWith(Payload&&); ``` -------------------------------- ### Configure Task Capacity for Plans Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Set the maximum number of tasks across all plans for an FSM instance using Config::TaskCapacityN. ```cpp using Config = hfsm2::Config ::TaskCapacityN; using M = hfsm2::MachineT; ``` -------------------------------- ### Include HFSM2 Machine Header Source: https://github.com/andrew-gresyk/hfsm2/wiki/Extended-Tutorial Include the main HFSM2 machine header file to use the state machine functionalities. ```cpp #include ``` -------------------------------- ### Append Default Transition to Plan Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Use change() to append a default transition to the plan. Overloads exist for specifying origin and destination states, with template overloads for TOrigin. ```cpp bool Plan::change(const StateID, const StateID); bool Plan::change(const StateID); bool Plan::change(); ``` -------------------------------- ### Enable Plans Support Source: https://github.com/andrew-gresyk/hfsm2/wiki/Feature-Macros Enables support for HFSM2's advanced plans feature. Define this macro if you intend to use plans for complex state transitions or logic. ```cpp #define HFSM2_ENABLE_PLANS ``` -------------------------------- ### LoggerInterface Methods Source: https://github.com/andrew-gresyk/hfsm2/wiki/Basic-Logging Methods available in the LoggerInterface for recording state machine events. ```APIDOC ## LoggerInterface | Method | Description | | ---------------------------------------------------------- | ----------------------------------------------- | | `virtual void recordMethod(Context&, const StateID, const Method);` | Record [state method](../wiki/Basic-State-Methods) call | | `virtual void recordTransition(Context&, const StateID, const StateID);` | Record successful [transitions](../wiki/Basic-Transitions) | | `virtual void recordTaskStatus(Context&, const StateID, const StatusEvent);`
`virtual void recordPlanStatus(Context&, const StatusEvent);` | Record [task or plan](../wiki/Advanced-Plans) status | | `virtual void recordCancelledPending(Context&, const StateID);` | Record a cancelled pending [transition](../wiki/Basic-Transitions) | ``` -------------------------------- ### Region Head Methods Source: https://github.com/andrew-gresyk/hfsm2/wiki/State-Methods These methods handle success or failure reactions for plans within a region. ```APIDOC ## State::planSucceeded ### Description Handles success reactions for plans within a region. ### Method `void State::planSucceeded(FullControl&);` ## State::planFailed ### Description Handles failure reactions for plans within a region. ### Method `void State::planFailed(FullControl&);` ``` -------------------------------- ### Enable All HFSM2 Features Source: https://github.com/andrew-gresyk/hfsm2/wiki/Feature-Macros Define this macro to enable all available features in HFSM2. Use when all functionalities are required. ```cpp #define HFSM2_ENABLE_ALL ``` -------------------------------- ### Transition with Constant Payload Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Transition-Payloads Use the changeWith method with a const reference to a payload for default transitions. This is suitable when the payload does not need to be modified or moved. ```cpp void Plan::changeWith(const StateID, const Payload&); ``` ```cpp void Plan::changeWith(const Payload&); ``` -------------------------------- ### Enable Manual Activation in HFSM2 Configuration Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Manual-Activation Use `hfsm2::Config::ManualActivation` to disable automatic FSM instance activation. This requires explicit calls to `enter()` and `exit()` methods. ```cpp using Config = hfsm2::Config ::ManualActivation; using M = hfsm2::MachineT; ``` -------------------------------- ### GuardControl Methods Source: https://github.com/andrew-gresyk/hfsm2/wiki/Controls Methods available on the GuardControl object, including all FullControl functionality plus transition inspection. ```APIDOC ## GuardControl ### Description Includes everything from `FullControl`. ### Methods - `const Transition& FullControl::currentTransitions() const` - Query the current transition. - `const Transition& FullControl::pendingTransition() const` - Query the pending transition. - `void FullControl::cancelPendingTransition()` - Cancel the pending transition. ``` -------------------------------- ### Define Type Configuration Source: https://github.com/andrew-gresyk/hfsm2/wiki/Extended-Tutorial Define the type configuration for the state machine, specifying the context type to be used. ```cpp using Config = hfsm2::Config::ContextT; ``` -------------------------------- ### Enable Structure Report Source: https://github.com/andrew-gresyk/hfsm2/wiki/Feature-Macros Enables the generation of a structure report for the state machine. This can be helpful for analyzing and visualizing the machine's structure. ```cpp #define HFSM2_ENABLE_STRUCTURE_REPORT ``` -------------------------------- ### Instance::access Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-State-Access Provides access to state data within an FSM instance. Overloads are available for both mutable and const access. ```APIDOC ## Instance::access ### Description Accesses the state data of type `TState` within the FSM instance. This method is available in both mutable and const contexts. ### Method `TState& Instance::access();` (mutable) `const TState& Instance::access() const;` (const) ### Parameters * **TState** (template parameter) - The type of the state to access. ### Response * **TState&** - A reference to the mutable state data. * **const TState&** - A const reference to the state data. ``` -------------------------------- ### Combine Multiple Config Sub-types Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Combine multiple hfsm2::Config sub-types to create a comprehensive configuration for your FSM. ```cpp using Config = hfsm2::Config ::ContextT ::ManualActivation ::PayloadT; ``` -------------------------------- ### Configure Instance Payload Type Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Transition-Payloads Set the payload type for the entire FSM instance using the Config::PayloadT template parameter. This must be done before creating the machine instance. ```cpp using Config = hfsm2::Config ::PayloadT; using M = hfsm2::MachineT; ``` -------------------------------- ### PlanControl Methods Source: https://github.com/andrew-gresyk/hfsm2/wiki/Controls Methods available on the PlanControl object for accessing state information and context. ```APIDOC ## PlanControl ### Methods - `static StateID PlanControl::stateId()` - Query ID for a state type. - `Context& PlanControl::context()` - Access mutable [context](../wiki/Context). - `const Context& PlanControl::context() const` - Access `const` [context](../wiki/Context). - `CPlan PlanControl::plan()` - Access mutable [plan](../wiki/Advanced-Plans). - `const Plan PlanControl::plan() const` - Access `const` [plan](../wiki/Advanced-Plans). - `const Transition& PlanControl::request() const` - Query current transition request. - `const Transition& PlanControl::previousTransitions() const` - Access the [last processed transition](../wiki/Advanced-Transition-History). ``` -------------------------------- ### Enable Utility Theory Transitions Source: https://github.com/andrew-gresyk/hfsm2/wiki/Feature-Macros Enables transitions based on utility theory. This macro is for advanced use cases involving decision-making based on calculated utilities. ```cpp #define HFSM2_ENABLE_UTILITY_THEORY ``` -------------------------------- ### Check if Plan is Empty Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Use the boolean conversion operator to check if a plan is not empty. ```cpp operator CPlan::bool() const; ``` -------------------------------- ### Provide Custom RNG for Utility Theory Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Supply a custom Random Number Generator (RNG) for utility theory transitions using Config::RandomT. ```cpp Config::RandomT<> ``` -------------------------------- ### Context Access and Modification Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Access and modify the context associated with the Root instance. ```APIDOC ## context ### Description Access the context associated with the Root instance. ### Method `Context& Root::context();` `const Context& Root::context() const;` ``` ```APIDOC ## setContext ### Description Set the context associated with the Root instance. ### Method `void Root::setContext(const Context&);` `void Root::setContext(Context&& context);` ``` -------------------------------- ### Enable Debug State Type for Visual Studio Source: https://github.com/andrew-gresyk/hfsm2/wiki/Feature-Macros Enables per-state debug information, specifically for Visual Studio's .natvis debugger integration. Useful for inspecting state types during debugging. ```cpp #define HFSM2_ENABLE_DEBUG_STATE_TYPE ``` -------------------------------- ### Clear a Plan Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Use clear() to remove all tasks from a plan. ```cpp void Plan::clear(); ``` -------------------------------- ### Set Event Processing Order Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Configure the event processing order to BottomUpReactions using Config::BottomUpReactions. ```cpp Config::BottomUpReactions ``` -------------------------------- ### Set Utility Type for Utility Theory Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Define the Utility type for utility theory transitions using Config::UtilityT. ```cpp Config::UtilityT<> ``` -------------------------------- ### Update FSM until completion Source: https://github.com/andrew-gresyk/hfsm2/wiki/Extended-Tutorial Continuously updates the finite state machine (FSM) until it reaches a completed state. Asserts the active state after each update to verify the FSM's progression. ```cpp fsm.update(); assert(fsm.isActive()); // 4th setp of On's plan fsm.update(); assert(fsm.isActive()); // activated by On::planSucceeded() return 0; } ``` -------------------------------- ### State Activation Check Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Query whether a state is currently active. ```APIDOC ## isActive ### Description Query if a state is active. ### Method `bool Root::isActive() const;` `bool Root::isActive(const StateID) const;` ``` -------------------------------- ### State Update and Event Reaction Source: https://github.com/andrew-gresyk/hfsm2/wiki/State-Methods These methods handle the regular update cycle of active states and allow states to react to specific events. ```APIDOC ## State::update ### Description Called periodically to update the state. ### Method `void State::update(FullControl&);` ## State::react ### Description Allows an active state to react to a specific event. ### Method `void State::react(const TEvent&, FullControl&);` ``` -------------------------------- ### Append Transition with Moved Payload Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Use changeWith() to append a default transition with a moved payload. Overloads exist for specifying origin and destination states, with template overloads for TOrigin. ```cpp bool Plan::changeWith(const StateID, const StateID, Payload&&); bool Plan::changeWith(const StateID, Payload&&); bool Plan::changeWith(Payload&&); ``` -------------------------------- ### Event Reaction Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Trigger a recursive event reaction cycle on active states. ```APIDOC ## react ### Description Trigger a recursive event reaction cycle on active states and execute any queued transitions. ### Method `void Root::react(const TEvent&);` ``` -------------------------------- ### Signal Plan Success or Failure Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Call succeed() when all plan tasks have succeeded, or fail() when they have failed. ```cpp void PlanControl::succeed(); void PlanControl::fail(); ``` -------------------------------- ### Set Task Capacity Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Set the maximum number of tasks across all plans for the FSM instance using Config::TaskCapacityN. ```cpp Config::TaskCapacityN ``` -------------------------------- ### Declare State Machine Structure Source: https://github.com/andrew-gresyk/hfsm2/wiki/Extended-Tutorial Declare the state machine structure, including root, composite, and sub-states. States need to be forward declared. ```cpp #define S(s) struct s using FSM = M::PeerRoot< S(Off), // initial state M::Composite; #undef S ``` -------------------------------- ### Actor Class Definition Source: https://github.com/andrew-gresyk/hfsm2/wiki/Usage-Class-Members Defines the `Actor` class with a `FsmHost` member to contain the FSM instance. This header avoids including the FSM library directly. ```cpp #pragma once #include // max_align_t class Actor { public: struct alignas(std::max_align_t) FsmHost { char buffer[104]; // the size is hand-adjusted }; public: Actor(); ~Actor(); void turnOn(); bool isOn() const; private: FsmHost _fsmHost; }; ``` -------------------------------- ### Append Transition with Constant Payload Source: https://github.com/andrew-gresyk/hfsm2/wiki/Advanced-Plans Use changeWith() to append a default transition with a const payload. Overloads exist for specifying origin and destination states, with template overloads for TOrigin. ```cpp bool Plan::changeWith(const StateID, const StateID, const Payload&); bool Plan::changeWith(const StateID, const Payload&); bool Plan::changeWith(const Payload&); ``` -------------------------------- ### Configure Context Type for HFSM2 Source: https://github.com/andrew-gresyk/hfsm2/wiki/Context Configures the HFSM2 machine to use a generic context type 'TContext'. This can be a value, reference, or pointer. ```cpp using Config = hfsm2::Config ::ContextT; using M = hfsm2::MachineT; ``` -------------------------------- ### Set Rank Type for Utility Theory Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Configuration Define the Rank type for utility theory transitions using Config::RankT. ```cpp Config::RankT<> ``` -------------------------------- ### State Entry and Exit Guards Source: https://github.com/andrew-gresyk/hfsm2/wiki/State-Methods Guards are invoked before a transition is actualized, controlling whether the transition can proceed. ```APIDOC ## State::entryGuard ### Description Guard invoked before a state is entered. ### Method `void State::entryGuard(GuardControl&);` ## State::exitGuard ### Description Guard invoked before a state is exited. ### Method `void State::exitGuard(GuardControl&);` ``` -------------------------------- ### Define State Machine Context Source: https://github.com/andrew-gresyk/hfsm2/wiki/Extended-Tutorial Define the interface class for the context shared between the state machine and its host. This context can hold shared data. ```cpp struct Context { bool powerOn; }; ``` -------------------------------- ### Update Cycle Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Trigger a recursive update cycle on active states. ```APIDOC ## update ### Description Trigger a recursive update cycle on active states and execute any queued transitions. ### Method `void Root::update();` ``` -------------------------------- ### Define Event Structure Source: https://github.com/andrew-gresyk/hfsm2/wiki/Extended-Tutorial Define a simple event structure that the state machine can react to. This allows for external stimuli processing. ```cpp struct Event {}; ``` -------------------------------- ### StateID Query Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Query the StateID for a given state type. ```APIDOC ## stateId ### Description Query the `StateID` for a state type. ### Method `static StateID Root::stateId();` ``` -------------------------------- ### State Data Access Source: https://github.com/andrew-gresyk/hfsm2/wiki/Instance-Methods Access the data associated with a specific state type. ```APIDOC ## access ### Description Access the data of a specific state type. ### Method `TState& Root::access();` `const TState& Root::access() const;` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.