The state machine module (\a PIStateMachine) provides hierarchical states, event-driven and timeout-driven transitions, and aligns with the [SCXML](https://www.w3.org/TR/scxml/) idea of state charts.
# State Machine
# Concepts
## State Machine Description
* **State** — a named node with an optional entry handler. You add states with \a PIStateMachine::addState() (or equivalent on the template subclass), giving an enum or id, name, and optional handler.
State machine is a behavioral design pattern that allows an object to change its behavior when its internal state changes.
* **Transition (rule)** — from one state to another, triggered by an event (and optionally guarded). Use \a addRule() to register a transition; you can attach conditions and actions.
Implementation in PIP is based on the **SCXML** (State Chart XML) standard.
* **Event** — an integer id posted with \a postEvent(); the machine delivers it to active states and runs the first matching transition guard.
* **Conditions** — named flags that can be required for a transition (e.g. \a addCondition() on a \a Rule). Call \a performCondition() to set them; \a resetConditions() to clear.
* **Timeout** — a transition can fire after a delay; combine with \a PITimer or internal timeout support in transition classes.
The machine is a \a PIObject subclass; you can connect timers or other objects to post events. Call \a setInitialState() and \a start() to run. Use \a switchToState() for direct state changes, \a performCondition() to satisfy named conditions.
### SCXML Concepts
# Minimal example
- **State** — a node in the state tree, can be atomic or compound
- **Transition** — a connection between states that triggers on an event
- **Event** — a trigger that causes a transition
- **Guard** — a condition that must be true for a transition to execute
- **Action** — an operation executed during a transition
- **Parallel** — a state where all substates are activated simultaneously
Define an enum for states, subclass \a PIStateMachine<YourEnum>, add states and rules in the constructor, set the initial state, then start. Post events from keyboard, timer, or other handlers.
### PIP StateMachine Features
- **Cannot create state, event, transition on stack** — all objects are created via `new` and managed via pointers
- **State machine is the root state** — `PIStateMachine` inherits from `PIStateBase`
- **All transitions and states are automatically deleted** — when the parent object is destroyed
### State Types
- **Atomic state** — a state without nested substates
- **Compound state** — a state containing nested substates
- **Final state** — a terminating state indicating the end of machine execution
- **Parallel state** — a state where all substates are activated simultaneously
### Transition Types
- **Normal transition** — triggers on receiving a specific event
- **Timeout transition** — triggers automatically after a specified time interval
- **Guarded transition** — triggers only when a specific condition is met
## State Machine API
### Main Classes
#### PIStateMachine
Main state machine class.
**Key methods:**
-`bool start()` — starts state machine execution
-`bool isRunning()` — checks if state machine is running
// In key handler: machine.performCondition("init_ok"); or machine.switchToState(Manual);
\endcode
\endcode
Full example: doc/examples/pistatemachine.cpp. API details: \a PIStateMachine, \a PIStateBase, \a pistatemachine_state.h, \a pistatemachine_transition.h.
#### PIStateFinal
\~russian
Final state of state machine.
Модуль машины состояний (\a PIStateMachine) предоставляет иерархические состояния, переходы по событиям и по таймауту и ориентирован на идеи [SCXML](https://www.w3.org/TR/scxml/).
* **Состояние** — именованный узел с опциональным обработчиком входа. Состояния добавляются через \a PIStateMachine::addState() (или аналог в шаблонном подклассе): enum/id, имя, при необходимости обработчик.
Base class for transitions.
* **Переход (правило)** — из одного состояния в другое по событию (и при выполнении условий). \a addRule() регистрирует переход; можно задать условия и действия.
* **Событие** — целочисленный id, посылаемый через \a postEvent(); машина доставляет его активным состояниям и выполняет первый подходящий переход.
* **Условия** — именованные флаги, требуемые для перехода (например \a addCondition() на \a Rule). Установка через \a performCondition(), сброс — \a resetConditions().
* **Таймаут** — переход по истечении времени; используется вместе с \a PITimer или встроенной поддержкой таймаутов в классах переходов.
Машина — подкласс \a PIObject; к ней можно подключать таймеры и другие объекты для посылки событий. Перед запуском задают \a setInitialState() и вызывают \a start(). \a switchToState() — прямая смена состояния, \a performCondition() — выполнение именованного условия.
**Key methods:**
# Минимальный пример
-`PITransitionBase *addGuard(std::function<R(Args...)> f)` — adds guard function
Определяют enum состояний, подкласс \a PIStateMachine<YourEnum>, в конструкторе добавляют состояния и правила, задают начальное состояние и запускают. События посылают из обработчика клавиш, таймера и т.д. Код минимального примера приведён выше в англоязычной секции.
//! \~english This file provides includes for the HTTP server module
//! \~russian Этот файл предоставляет включения для модуля HTTP сервера
//!
//! \~\authors
//! \~english
//! Ivan Pelipenko peri4ko@yandex.ru;
//! \~russian
//! Иван Пелипенко peri4ko@yandex.ru;
//!
#ifndef pihttpservermodule_H
#ifndef pihttpservermodule_H
#define pihttpservermodule_H
#define pihttpservermodule_H
//! \~\addtogroup HTTPServer
//! \~\{
//! \~\file pihttpservermodule.h
//! \~\brief HTTP server module includes
//! \~english HTTP server module includes
//! \~russian Модуль включений HTTP сервера
//! \~\details
//! \~english This file provides includes for the HTTP server module
//! \~russian Этот файл предоставляет включения для модуля HTTP сервера
//! \~\}
#include"pihttpserver.h"
#include"pihttpserver.h"
#endif
#endif
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.