QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
QGCStateMachine Class Reference

QGroundControl specific state machine with enhanced error handling. More...

#include <QGCStateMachine.h>

+ Inheritance diagram for QGCStateMachine:
+ Collaboration diagram for QGCStateMachine:

Public Types

using EntryCallback = std::function< void()>
 Name of the currently active state (for QML binding)
 
using ExitCallback = std::function< void()>
 
using EventHandler = std::function< bool(QEvent *)>
 

Public Slots

void start ()
 Start the state machine with debug logging.
 

Signals

void error ()
 
void progressUpdate (float progress)
 
void machineEvent (const QString &eventName)
 
void currentStateNameChanged ()
 Emitted when the current state changes (for QML binding)
 
void runningChanged ()
 Emitted when the running state changes (for QML binding)
 
void stateHistoryChanged ()
 Emitted when the state history changes (for QML binding)
 

Public Member Functions

 QGCStateMachine (const QString &machineName, Vehicle *vehicle, QObject *parent=nullptr)
 
Vehiclevehicle () const
 
QString machineName () const
 
StateContextcontext ()
 
const StateContextcontext () const
 
bool active () const
 
QString currentStateName () const
 
QStringList stateHistory () const
 
void setStateHistoryLimit (int limit)
 Set the maximum number of state history entries to keep.
 
void setOnEntry (EntryCallback callback)
 Set a callback to be invoked when the machine starts.
 
void setOnExit (ExitCallback callback)
 Set a callback to be invoked when the machine stops.
 
void setCallbacks (EntryCallback onEntry, ExitCallback onExit=nullptr)
 Set both entry and exit callbacks.
 
void setEventHandler (EventHandler handler)
 
void enablePropertyRestore ()
 
bool isPropertyRestoreEnabled () const
 Check if property restoration is enabled.
 
void setGlobalErrorState (QAbstractState *errorState)
 
QAbstractState * globalErrorState () const
 Get the global error state.
 
void registerState (QGCState *state)
 
void registerState (QGCAbstractState *state)
 
FunctionStateaddFunctionState (const QString &stateName, std::function< void()> function)
 
AsyncFunctionStateaddAsyncFunctionState (const QString &stateName, AsyncFunctionState::SetupFunction setupFunction, int timeoutMsecs=0)
 
QGCStateaddErrorRecoveryState (const QString &stateName, ErrorRecoveryBuilder::Action action, int maxRetries=0, int retryDelayMsecs=1000, ErrorRecoveryBuilder::ExhaustedBehavior exhaustedBehavior=ErrorRecoveryBuilder::EmitError, ErrorRecoveryBuilder::Action fallback=nullptr, ErrorRecoveryBuilder::VoidAction rollback=nullptr, int timeoutMsecs=0)
 
DelayStateaddDelayState (int delayMsecs)
 
ParallelStateaddParallelState (const QString &stateName)
 
void postEvent (const QString &eventName, const QVariant &data=QVariant(), EventPriority priority=NormalPriority)
 
int postDelayedEvent (const QString &eventName, int delayMsecs, const QVariant &data=QVariant())
 
bool cancelDelayedEvent (int eventId)
 
void setInitialState (QAbstractState *state, bool autoStart=false)
 
QGCFinalStateaddFinalState (const QString &stateName=QString())
 
ConditionalStateaddConditionalState (const QString &stateName, ConditionalState::Predicate predicate, ConditionalState::Action action=nullptr)
 
template<typename Func >
WaitForSignalStateaddWaitForSignalState (const QString &stateName, const QObject *sender, Func signal, int timeoutMsecs=0)
 
SubMachineStateaddSubMachineState (const QString &stateName, SubMachineState::MachineFactory factory)
 
EventQueuedStateaddEventQueuedState (const QString &stateName, const QString &eventName, int timeoutMsecs=0)
 
QState * createTimedActionState (const QString &stateName, int durationMsecs, std::function< void()> onEntry=nullptr, std::function< void()> onExit=nullptr)
 
bool isStateActive (QAbstractState *state) const
 
QSet< QAbstractState * > activeStates () const
 
QAbstractState * findState (const QString &stateName) const
 
template<typename T >
QList< T * > findStates () const
 Find all states of a specific type.
 
bool isInErrorState () const
 Check if the machine is in an error state.
 
FunctionStateaddLogAndContinueErrorState (const QString &stateName, QAbstractState *nextState, const QString &message=QString())
 Create a logging error handler state that advances to nextState.
 
FunctionStateaddLogAndStopErrorState (const QString &stateName, const QString &message=QString())
 Create a logging error handler state that stops the machine.
 
QString lastError () const
 Get the last error message (from Qt's internal error handling)
 
void clearError (bool restart=false)
 
bool resetToState (QAbstractState *state)
 
bool recoverFromError ()
 
void setRecoveryState (QAbstractState *state)
 
QAbstractState * recoveryState () const
 Get the recovery state.
 
bool attemptRecovery ()
 
void ensureRunning ()
 Start the machine if not already running.
 
void stopMachine (bool deleteOnStop=true)
 
void restart ()
 Restart the machine (stop then start)
 
template<typename Func >
QSignalTransition * addTransition (QState *from, Func signal, QAbstractState *to, QAbstractAnimation *animation=nullptr)
 
template<typename Func >
GuardedTransitionaddGuardedTransition (QState *from, Func signal, QAbstractState *to, GuardedTransition::Guard guard, QAbstractAnimation *animation=nullptr)
 
MachineEventTransitionaddEventTransition (QState *from, const QString &eventName, QAbstractState *to, QAbstractAnimation *animation=nullptr)
 
TimeoutTransitionaddTimeoutTransition (QState *from, int timeoutMsecs, QAbstractState *to, QAbstractAnimation *animation=nullptr)
 
template<typename SenderType , typename Func >
RetryTransitionaddRetryTransition (SenderType *from, Func signal, QAbstractState *to, std::function< void()> retryAction, int maxRetries=1)
 
template<typename SenderType , typename Func >
GuardedTransitionaddConditionalTransition (SenderType *from, Func signal, QAbstractState *to, std::function< bool()> guard)
 
template<typename Sender , typename Signal >
QSignalTransition * addSelfLoopTransition (QState *state, Sender *sender, Signal signal, std::function< void()> action)
 
template<typename Sender , typename Signal >
InternalTransitionaddInternalTransition (QState *state, Sender *sender, Signal signal, std::function< void()> action)
 
QList< QAbstractTransition * > transitionsFrom (QAbstractState *state) const
 
QList< QAbstractTransition * > transitionsTo (QAbstractState *state) const
 
QList< QAbstractState * > reachableFrom (QAbstractState *state) const
 
QList< QAbstractState * > predecessorsOf (QAbstractState *state) const
 
QString dumpCurrentState () const
 
QString dumpConfiguration () const
 
void logCurrentState () const
 Log the current state to debug output.
 
void logConfiguration () const
 Log the full configuration to debug output.
 
void setHistoryRecordingEnabled (bool enabled, int maxEntries=1000)
 Enable/disable structured transition history recording.
 
bool historyRecordingEnabled () const
 
QString dumpRecordedHistory () const
 
QJsonArray recordedHistoryJson () const
 
void setProfilingEnabled (bool enabled)
 Enable/disable state timing profiler.
 
bool profilingEnabled () const
 
QString profilingSummary () const
 
void setStructuredLoggingEnabled (bool enabled)
 Enable/disable structured state-machine logger.
 
bool structuredLoggingEnabled () const
 
QString exportAsDot () const
 
QList< QAbstractState * > unreachableStates () const
 
int maxPathLength () const
 
QList< QAbstractState * > deadEndStates () const
 
void setProgressWeights (const QList< QPair< QAbstractState *, int > > &stateWeights)
 
void setSubProgress (float subProgress)
 
float progress () const
 Get the current overall progress (0.0 to 1.0)
 
void resetProgress ()
 Reset progress tracking (call when restarting the machine)
 
void setTimeoutOverride (const QString &stateName, int timeoutMsecs)
 
void removeTimeoutOverride (const QString &stateName)
 
int timeoutOverride (const QString &stateName) const
 Get the timeout override for a state, or -1 if not set.
 
QHash< QString, int > allTimeoutOverrides () const
 Get all timeout overrides.
 
void clearTimeoutOverrides ()
 Clear all timeout overrides.
 
QHash< QString, int > timeoutStats () const
 Get timeout statistics (how often each state timed out)
 
void recordTimeout (const QString &stateName)
 Record a timeout for statistics.
 
void clearTimeoutStats ()
 Clear timeout statistics.
 

Protected Member Functions

virtual void onEnter ()
 Override to perform actions when machine starts.
 
virtual void onLeave ()
 Override to perform actions when machine stops.
 
void onEntry (QEvent *event) override
 
void onExit (QEvent *event) override
 
bool event (QEvent *event) override
 

Detailed Description

QGroundControl specific state machine with enhanced error handling.

Definition at line 62 of file QGCStateMachine.h.

Member Typedef Documentation

◆ EntryCallback

using QGCStateMachine::EntryCallback = std::function<void()>

Name of the currently active state (for QML binding)

Current progress from 0.0 to 1.0 (for QML binding) Whether the machine is currently running (for QML binding) List of recent state names for history display (for QML binding)

Definition at line 80 of file QGCStateMachine.h.

◆ EventHandler

using QGCStateMachine::EventHandler = std::function<bool(QEvent*)>

Definition at line 82 of file QGCStateMachine.h.

◆ ExitCallback

using QGCStateMachine::ExitCallback = std::function<void()>

Definition at line 81 of file QGCStateMachine.h.

Constructor & Destructor Documentation

◆ QGCStateMachine()

QGCStateMachine::QGCStateMachine ( const QString &  machineName,
Vehicle vehicle,
QObject *  parent = nullptr 
)

Member Function Documentation

◆ active()

bool QGCStateMachine::active ( ) const
inline
Returns
true if the state machine is currently running Compatibility method matching old StateMachine::active()

Definition at line 96 of file QGCStateMachine.h.

Referenced by currentStateName(), dumpCurrentState(), and Vehicle::isInitialConnectComplete().

◆ activeStates()

QSet< QAbstractState * > QGCStateMachine::activeStates ( ) const
inline

Get all currently active states

Returns
Set of active states

Definition at line 308 of file QGCStateMachine.h.

Referenced by currentStateName().

◆ addAsyncFunctionState()

AsyncFunctionState * QGCStateMachine::addAsyncFunctionState ( const QString &  stateName,
AsyncFunctionState::SetupFunction  setupFunction,
int  timeoutMsecs = 0 
)

Create and register an AsyncFunctionState

Parameters
stateNameName for the state
setupFunctionFunction to execute on entry
timeoutMsecsOptional timeout
Returns
The created state

Definition at line 109 of file QGCStateMachine.cc.

References registerState().

◆ addConditionalState()

ConditionalState * QGCStateMachine::addConditionalState ( const QString &  stateName,
ConditionalState::Predicate  predicate,
ConditionalState::Action  action = nullptr 
)

Create and register a ConditionalState

Parameters
stateNameName for the state
predicateCondition to evaluate
actionAction to execute if predicate is true
Returns
The created state

Definition at line 197 of file QGCStateMachine.cc.

References registerState().

◆ addConditionalTransition()

template<typename SenderType , typename Func >
GuardedTransition * QGCStateMachine::addConditionalTransition ( SenderType *  from,
Func  signal,
QAbstractState *  to,
std::function< bool()>  guard 
)
inline

Create a conditional guarded transition Transition only taken if guard returns true

Parameters
fromSource state (must match signal's object type)
signalSignal that triggers evaluation
toTarget state
guardPredicate that must return true

Definition at line 462 of file QGCStateMachine.h.

◆ addDelayState()

DelayState * QGCStateMachine::addDelayState ( int  delayMsecs)

Create and register a DelayState

Parameters
delayMsecsDelay duration
Returns
The created state

Definition at line 145 of file QGCStateMachine.cc.

References registerState().

◆ addErrorRecoveryState()

QGCState * QGCStateMachine::addErrorRecoveryState ( const QString &  stateName,
ErrorRecoveryBuilder::Action  action,
int  maxRetries = 0,
int  retryDelayMsecs = 1000,
ErrorRecoveryBuilder::ExhaustedBehavior  exhaustedBehavior = ErrorRecoveryBuilder::EmitError,
ErrorRecoveryBuilder::Action  fallback = nullptr,
ErrorRecoveryBuilder::VoidAction  rollback = nullptr,
int  timeoutMsecs = 0 
)

Create and register an ErrorRecoveryState via fluent builder semantics.

Parameters
stateNameName for the state
actionPrimary action to execute (returns true on success)
maxRetriesNumber of retries after initial attempt
retryDelayMsecsDelay between retries
exhaustedBehaviorBehavior when all options are exhausted
fallbackOptional fallback action
rollbackOptional rollback action
timeoutMsecsOptional overall timeout
Returns
The created state

Definition at line 118 of file QGCStateMachine.cc.

References ErrorRecoveryBuilder::build(), ErrorRecoveryBuilder::onExhausted(), ErrorRecoveryBuilder::retry(), ErrorRecoveryBuilder::withAction(), ErrorRecoveryBuilder::withFallback(), ErrorRecoveryBuilder::withRollback(), and ErrorRecoveryBuilder::withTimeout().

◆ addEventQueuedState()

EventQueuedState * QGCStateMachine::addEventQueuedState ( const QString &  stateName,
const QString &  eventName,
int  timeoutMsecs = 0 
)

Create and register an EventQueuedState

Parameters
stateNameName for the state
eventNameEvent name to wait for
timeoutMsecsOptional timeout (0 = no timeout)
Returns
The created state

Definition at line 213 of file QGCStateMachine.cc.

References registerState().

◆ addEventTransition()

MachineEventTransition * QGCStateMachine::addEventTransition ( QState *  from,
const QString &  eventName,
QAbstractState *  to,
QAbstractAnimation *  animation = nullptr 
)

Create a machine event transition

Parameters
fromSource state
eventNameEvent name to match
toTarget state
animationOptional animation to run during transition

Definition at line 410 of file QGCStateMachine.cc.

◆ addFinalState()

QGCFinalState * QGCStateMachine::addFinalState ( const QString &  stateName = QString())

Add a final state that will stop the machine when entered

Parameters
stateNameName for the state
Returns
The created final state

Definition at line 191 of file QGCStateMachine.cc.

◆ addFunctionState()

FunctionState * QGCStateMachine::addFunctionState ( const QString &  stateName,
std::function< void()>  function 
)

Create and register a FunctionState

Parameters
stateNameName for the state
functionFunction to execute
Returns
The created state

Definition at line 102 of file QGCStateMachine.cc.

References registerState().

◆ addGuardedTransition()

template<typename Func >
GuardedTransition * QGCStateMachine::addGuardedTransition ( QState *  from,
Func  signal,
QAbstractState *  to,
GuardedTransition::Guard  guard,
QAbstractAnimation *  animation = nullptr 
)
inline

Create a guarded transition between states

Parameters
fromSource state
signalSignal that triggers the transition
toTarget state
guardPredicate that must return true for transition
animationOptional animation to play during transition

Definition at line 410 of file QGCStateMachine.h.

◆ addInternalTransition()

template<typename Sender , typename Signal >
InternalTransition * QGCStateMachine::addInternalTransition ( QState *  state,
Sender *  sender,
Signal  signal,
std::function< void()>  action 
)
inline

Create a self-loop internal transition (no state exit/entry). Unlike addSelfLoopTransition, this does NOT trigger onExit/onEntry. Use when you want to handle signals without re-entering the state.

Parameters
stateThe state containing the transition
senderObject that emits the signal
signalSignal that triggers the action
actionAction to perform on each signal
Returns
The created internal transition

Definition at line 516 of file QGCStateMachine.h.

◆ addLogAndContinueErrorState()

FunctionState * QGCStateMachine::addLogAndContinueErrorState ( const QString &  stateName,
QAbstractState *  nextState,
const QString &  message = QString() 
)

Create a logging error handler state that advances to nextState.

Definition at line 292 of file QGCStateMachine.cc.

References ErrorHandlers::logAndContinue(), and registerState().

◆ addLogAndStopErrorState()

FunctionState * QGCStateMachine::addLogAndStopErrorState ( const QString &  stateName,
const QString &  message = QString() 
)

Create a logging error handler state that stops the machine.

Definition at line 301 of file QGCStateMachine.cc.

References ErrorHandlers::logAndStop(), and registerState().

◆ addParallelState()

ParallelState * QGCStateMachine::addParallelState ( const QString &  stateName)

Create and register a ParallelState

Parameters
stateNameName for the state
Returns
The created state

Definition at line 152 of file QGCStateMachine.cc.

References registerState().

◆ addRetryTransition()

template<typename SenderType , typename Func >
RetryTransition * QGCStateMachine::addRetryTransition ( SenderType *  from,
Func  signal,
QAbstractState *  to,
std::function< void()>  retryAction,
int  maxRetries = 1 
)
inline

Create a retry transition that retries an action before advancing

Parameters
fromSource state (must match signal's object type)
signalSignal that triggers retry evaluation
toTarget state (used after max retries)
retryActionAction to perform on retry
maxRetriesMaximum number of retries before advancing

Definition at line 445 of file QGCStateMachine.h.

◆ addSelfLoopTransition()

template<typename Sender , typename Signal >
QSignalTransition * QGCStateMachine::addSelfLoopTransition ( QState *  state,
Sender *  sender,
Signal  signal,
std::function< void()>  action 
)
inline

Create a self-loop transition that performs an action but stays in the same state. Useful for handling events/signals without changing state.

Inspired by Qt's rogue example where input events are processed but the state machine stays in the input state.

Example usage:

// Process button clicks without leaving the state
machine.addSelfLoopTransition(inputState, button, &QPushButton::clicked,
[this]() { handleClick(); });
// Handle incoming messages while waiting
machine.addSelfLoopTransition(waitState, receiver, &Receiver::messageReceived,
[this](const Message& msg) { processMessage(msg); });
Parameters
stateThe state to loop back to
senderObject that emits the signal
signalSignal that triggers the action
actionAction to perform on each signal
Returns
The created transition

Definition at line 494 of file QGCStateMachine.h.

◆ addSubMachineState()

SubMachineState * QGCStateMachine::addSubMachineState ( const QString &  stateName,
SubMachineState::MachineFactory  factory 
)

Create and register a SubMachineState

Parameters
stateNameName for the state
factoryFunction that creates the child state machine
Returns
The created state

Definition at line 206 of file QGCStateMachine.cc.

References registerState().

◆ addTimeoutTransition()

TimeoutTransition * QGCStateMachine::addTimeoutTransition ( QState *  from,
int  timeoutMsecs,
QAbstractState *  to,
QAbstractAnimation *  animation = nullptr 
)

Create a timeout transition

Parameters
fromSource state
timeoutMsecsTimeout in milliseconds
toTarget state
animationOptional animation to run during transition

Definition at line 421 of file QGCStateMachine.cc.

◆ addTransition()

template<typename Func >
QSignalTransition * QGCStateMachine::addTransition ( QState *  from,
Func  signal,
QAbstractState *  to,
QAbstractAnimation *  animation = nullptr 
)
inline

Create a simple signal transition between states

Parameters
fromSource state
signalSignal that triggers the transition
toTarget state
animationOptional animation to play during transition

Definition at line 393 of file QGCStateMachine.h.

◆ addWaitForSignalState()

template<typename Func >
WaitForSignalState * QGCStateMachine::addWaitForSignalState ( const QString &  stateName,
const QObject *  sender,
Func  signal,
int  timeoutMsecs = 0 
)
inline

Create and register a WaitForSignalState

Parameters
stateNameName for the state
senderObject that emits the signal
signalSignal to wait for
timeoutMsecsOptional timeout (0 = no timeout)
Returns
The created state

Definition at line 247 of file QGCStateMachine.h.

References registerState().

◆ allTimeoutOverrides()

QHash< QString, int > QGCStateMachine::allTimeoutOverrides ( ) const
inline

Get all timeout overrides.

Definition at line 655 of file QGCStateMachine.h.

◆ attemptRecovery()

bool QGCStateMachine::attemptRecovery ( )

Attempt recovery to the recovery state (if set).

Returns
true if recovery was initiated

Definition at line 363 of file QGCStateMachine.cc.

References resetToState().

◆ cancelDelayedEvent()

bool QGCStateMachine::cancelDelayedEvent ( int  eventId)

Cancel a previously posted delayed event

Parameters
eventIdThe ID returned by postDelayedEvent
Returns
true if the event was cancelled, false if already delivered or not found

Definition at line 173 of file QGCStateMachine.cc.

◆ clearError()

void QGCStateMachine::clearError ( bool  restart = false)

Clear the error state and optionally restart

Parameters
restartIf true, restarts the machine after clearing

Definition at line 309 of file QGCStateMachine.cc.

References restart(), and start().

Referenced by recoverFromError().

◆ clearTimeoutOverrides()

void QGCStateMachine::clearTimeoutOverrides ( )
inline

Clear all timeout overrides.

Definition at line 658 of file QGCStateMachine.h.

◆ clearTimeoutStats()

void QGCStateMachine::clearTimeoutStats ( )
inline

Clear timeout statistics.

Definition at line 667 of file QGCStateMachine.h.

◆ context() [1/2]

StateContext & QGCStateMachine::context ( )
inline

Get the state machine's context for inter-state data passing

Returns
Reference to the context object

Definition at line 91 of file QGCStateMachine.h.

Referenced by QGCAbstractState::context().

◆ context() [2/2]

const StateContext & QGCStateMachine::context ( ) const
inline

Definition at line 92 of file QGCStateMachine.h.

◆ createTimedActionState()

QState * QGCStateMachine::createTimedActionState ( const QString &  stateName,
int  durationMsecs,
std::function< void()>  onEntry = nullptr,
std::function< void()>  onExit = nullptr 
)

Create a composite state that performs an action, waits for a duration, then finishes. The state has internal structure: entry -> timing -> done (final). When done, emits QState::finished() which can be used for transitions.

Inspired by Qt's trafficlight example pattern.

Example usage:

auto* showMessage = machine.createTimedActionState("ShowMessage", 3000,
[]() { qDebug() << "Message shown"; },
[]() { qDebug() << "Message hidden"; }
);
showMessage->addTransition(showMessage, &QState::finished, nextState);
Parameters
stateNameName for the state
durationMsecsHow long to stay in the state
onEntryOptional action to perform when state is entered
onExitOptional action to perform when state is exited
Returns
The created composite state (use QState::finished for transitions)

Definition at line 222 of file QGCStateMachine.cc.

References onEntry(), and onExit().

◆ currentStateName()

QString QGCStateMachine::currentStateName ( ) const

Get the name of the currently active state

Returns
State name or empty string if not running

Definition at line 51 of file QGCStateMachine.cc.

References active(), and activeStates().

◆ currentStateNameChanged

void QGCStateMachine::currentStateNameChanged ( )
signal

Emitted when the current state changes (for QML binding)

◆ deadEndStates()

QList< QAbstractState * > QGCStateMachine::deadEndStates ( ) const

Find states that have no outgoing transitions and are not final states. These are potential dead-ends.

Returns
List of dead-end states

Definition at line 775 of file QGCStateMachine.cc.

References transitionsFrom().

◆ dumpConfiguration()

QString QGCStateMachine::dumpConfiguration ( ) const

Get a human-readable string showing all states and transitions. Useful for debugging and documentation.

Returns
Multi-line string describing the machine structure

Definition at line 515 of file QGCStateMachine.cc.

References transitionsFrom().

Referenced by logConfiguration().

◆ dumpCurrentState()

QString QGCStateMachine::dumpCurrentState ( ) const

Get a human-readable string showing the current state. Useful for debugging.

Returns
String like "MachineName: CurrentState (running)" or "MachineName: (not running)"

Definition at line 489 of file QGCStateMachine.cc.

References active().

Referenced by logCurrentState().

◆ dumpRecordedHistory()

QString QGCStateMachine::dumpRecordedHistory ( ) const

Definition at line 592 of file QGCStateMachine.cc.

References StateHistoryRecorder::dumpHistory().

◆ enablePropertyRestore()

void QGCStateMachine::enablePropertyRestore ( )

Enable automatic property restoration when states exit When enabled, properties set via QGCState::setProperty/setEnabled/setVisible are automatically restored to their previous values when the state exits.

Definition at line 75 of file QGCStateMachine.cc.

◆ ensureRunning()

void QGCStateMachine::ensureRunning ( )

Start the machine if not already running.

Definition at line 378 of file QGCStateMachine.cc.

References start().

◆ error

void QGCStateMachine::error ( )
signal

◆ event()

bool QGCStateMachine::event ( QEvent *  event)
overrideprotected

Definition at line 958 of file QGCStateMachine.cc.

References event().

Referenced by event(), onEntry(), and onExit().

◆ exportAsDot()

QString QGCStateMachine::exportAsDot ( ) const

Export state machine structure as Graphviz DOT format. The output can be rendered using Graphviz tools like dot -Tpng output.dot -o output.png.

Returns
DOT format string representation of the state machine

Definition at line 633 of file QGCStateMachine.cc.

References transitionsFrom().

◆ findState()

QAbstractState * QGCStateMachine::findState ( const QString &  stateName) const

Find a state by name

Parameters
stateNameThe object name of the state
Returns
The state, or nullptr if not found

Definition at line 274 of file QGCStateMachine.cc.

◆ findStates()

template<typename T >
QList< T * > QGCStateMachine::findStates ( ) const
inline

Find all states of a specific type.

Definition at line 317 of file QGCStateMachine.h.

◆ globalErrorState()

QAbstractState * QGCStateMachine::globalErrorState ( ) const
inline

Get the global error state.

Definition at line 143 of file QGCStateMachine.h.

◆ historyRecordingEnabled()

bool QGCStateMachine::historyRecordingEnabled ( ) const

Definition at line 587 of file QGCStateMachine.cc.

References StateHistoryRecorder::isEnabled().

◆ isInErrorState()

bool QGCStateMachine::isInErrorState ( ) const

Check if the machine is in an error state.

Definition at line 284 of file QGCStateMachine.cc.

Referenced by recoverFromError().

◆ isPropertyRestoreEnabled()

bool QGCStateMachine::isPropertyRestoreEnabled ( ) const

Check if property restoration is enabled.

Definition at line 81 of file QGCStateMachine.cc.

◆ isStateActive()

bool QGCStateMachine::isStateActive ( QAbstractState *  state) const

Check if a specific state is currently active

Parameters
stateThe state to check
Returns
true if the state is in the current configuration

Definition at line 269 of file QGCStateMachine.cc.

◆ lastError()

QString QGCStateMachine::lastError ( ) const
inline

Get the last error message (from Qt's internal error handling)

Definition at line 339 of file QGCStateMachine.h.

References errorString.

◆ logConfiguration()

void QGCStateMachine::logConfiguration ( ) const

Log the full configuration to debug output.

Definition at line 568 of file QGCStateMachine.cc.

References dumpConfiguration().

◆ logCurrentState()

void QGCStateMachine::logCurrentState ( ) const

Log the current state to debug output.

Definition at line 563 of file QGCStateMachine.cc.

References dumpCurrentState().

◆ machineEvent

void QGCStateMachine::machineEvent ( const QString &  eventName)
signal

Emitted when a named event is posted to the machine Used by EventQueuedState to detect events

Parameters
eventNameName of the posted event

Referenced by EventQueuedState::connectWaitSignal(), and postEvent().

◆ machineName()

QString QGCStateMachine::machineName ( ) const
inline

Definition at line 87 of file QGCStateMachine.h.

Referenced by SubMachineState::onEntry(), and QGCStateMachine().

◆ maxPathLength()

int QGCStateMachine::maxPathLength ( ) const

Calculate the maximum path length from initial state to any final state. Useful for understanding worst-case execution depth.

Returns
Maximum number of transitions in any path, or -1 if no initial state

Definition at line 735 of file QGCStateMachine.cc.

References reachableFrom().

◆ onEnter()

virtual void QGCStateMachine::onEnter ( )
inlineprotectedvirtual

Override to perform actions when machine starts.

Definition at line 696 of file QGCStateMachine.h.

Referenced by onEntry().

◆ onEntry()

void QGCStateMachine::onEntry ( QEvent *  event)
overrideprotected

Definition at line 936 of file QGCStateMachine.cc.

References event(), and onEnter().

Referenced by createTimedActionState(), and setCallbacks().

◆ onExit()

void QGCStateMachine::onExit ( QEvent *  event)
overrideprotected

Definition at line 947 of file QGCStateMachine.cc.

References event(), and onLeave().

Referenced by createTimedActionState(), and setCallbacks().

◆ onLeave()

virtual void QGCStateMachine::onLeave ( )
inlineprotectedvirtual

Override to perform actions when machine stops.

Definition at line 699 of file QGCStateMachine.h.

Referenced by onExit().

◆ postDelayedEvent()

int QGCStateMachine::postDelayedEvent ( const QString &  eventName,
int  delayMsecs,
const QVariant &  data = QVariant() 
)

Post a named event with a delay

Parameters
eventNameName of the event
delayMsecsDelay in milliseconds
dataOptional payload data
Returns
Event ID that can be used to cancel the event

Definition at line 167 of file QGCStateMachine.cc.

◆ postEvent()

void QGCStateMachine::postEvent ( const QString &  eventName,
const QVariant &  data = QVariant(),
EventPriority  priority = NormalPriority 
)

Post a named event to be processed immediately

Parameters
eventNameName of the event
dataOptional payload data
priorityEvent priority (HighPriority events are processed before NormalPriority)

Definition at line 159 of file QGCStateMachine.cc.

References machineEvent().

◆ predecessorsOf()

QList< QAbstractState * > QGCStateMachine::predecessorsOf ( QAbstractState *  state) const

Get states that can reach this state

Parameters
stateThe target state
Returns
List of states that have transitions to this state

Definition at line 472 of file QGCStateMachine.cc.

References transitionsTo().

◆ profilingEnabled()

bool QGCStateMachine::profilingEnabled ( ) const

Definition at line 610 of file QGCStateMachine.cc.

References StateMachineProfiler::isEnabled().

◆ profilingSummary()

QString QGCStateMachine::profilingSummary ( ) const

Definition at line 615 of file QGCStateMachine.cc.

References StateMachineProfiler::summary().

◆ progress()

float QGCStateMachine::progress ( ) const

Get the current overall progress (0.0 to 1.0)

Definition at line 865 of file QGCStateMachine.cc.

◆ progressUpdate

void QGCStateMachine::progressUpdate ( float  progress)
signal

Emitted when progress changes (if progress tracking is enabled)

Parameters
progressOverall progress from 0.0 to 1.0

Referenced by QGCStateMachine(), and setSubProgress().

◆ reachableFrom()

QList< QAbstractState * > QGCStateMachine::reachableFrom ( QAbstractState *  state) const

Get the target states reachable from a state

Parameters
stateThe source state
Returns
List of states that can be reached from this state

Definition at line 459 of file QGCStateMachine.cc.

References transitionsFrom().

Referenced by maxPathLength(), and unreachableStates().

◆ recordedHistoryJson()

QJsonArray QGCStateMachine::recordedHistoryJson ( ) const

Definition at line 597 of file QGCStateMachine.cc.

References StateHistoryRecorder::toJson().

◆ recordTimeout()

void QGCStateMachine::recordTimeout ( const QString &  stateName)

Record a timeout for statistics.

Definition at line 915 of file QGCStateMachine.cc.

◆ recoverFromError()

bool QGCStateMachine::recoverFromError ( )

Recover from error state by restarting the machine. If not in error state, this has no effect.

Returns
true if recovery was initiated

Definition at line 351 of file QGCStateMachine.cc.

References clearError(), and isInErrorState().

◆ recoveryState()

QAbstractState * QGCStateMachine::recoveryState ( ) const
inline

Get the recovery state.

Definition at line 363 of file QGCStateMachine.h.

◆ registerState() [1/2]

void QGCStateMachine::registerState ( QGCAbstractState state)

Register a QGCAbstractState with the machine and automatically wire up error transitions

Parameters
stateThe state to register

Definition at line 94 of file QGCStateMachine.cc.

References QGCAbstractState::error().

◆ registerState() [2/2]

void QGCStateMachine::registerState ( QGCState state)

Register a QGCState with the machine and automatically wire up error transitions If a global error state is set, the state's error() signal will transition to it

Parameters
stateThe state to register

Definition at line 86 of file QGCStateMachine.cc.

References QGCAbstractState::error(), and QGCState::localErrorState().

Referenced by addAsyncFunctionState(), addConditionalState(), addDelayState(), addEventQueuedState(), addFunctionState(), addLogAndContinueErrorState(), addLogAndStopErrorState(), addParallelState(), addSubMachineState(), addWaitForSignalState(), and ErrorRecoveryBuilder::build().

◆ removeTimeoutOverride()

void QGCStateMachine::removeTimeoutOverride ( const QString &  stateName)

Remove a timeout override

Parameters
stateNameThe state name to remove override for

Definition at line 905 of file QGCStateMachine.cc.

◆ resetProgress()

void QGCStateMachine::resetProgress ( )

Reset progress tracking (call when restarting the machine)

Definition at line 870 of file QGCStateMachine.cc.

Referenced by resetToState(), and InitialConnectStateMachine::start().

◆ resetToState()

bool QGCStateMachine::resetToState ( QAbstractState *  state)

Reset the machine and restart from a specific state. Useful for retrying from a failed state without restarting the entire sequence.

Parameters
stateThe state to start from
Returns
true if successful, false if state is invalid

Definition at line 317 of file QGCStateMachine.cc.

References resetProgress(), setInitialState(), and start().

Referenced by attemptRecovery().

◆ restart()

void QGCStateMachine::restart ( )

Restart the machine (stop then start)

Definition at line 391 of file QGCStateMachine.cc.

References start().

Referenced by clearError().

◆ runningChanged

void QGCStateMachine::runningChanged ( )
signal

Emitted when the running state changes (for QML binding)

Referenced by QGCStateMachine().

◆ setCallbacks()

void QGCStateMachine::setCallbacks ( EntryCallback  onEntry,
ExitCallback  onExit = nullptr 
)

Set both entry and exit callbacks.

Definition at line 926 of file QGCStateMachine.cc.

References onEntry(), and onExit().

◆ setEventHandler()

void QGCStateMachine::setEventHandler ( EventHandler  handler)
inline

Set a global event handler for the machine Handler is called before events are processed by states

Definition at line 128 of file QGCStateMachine.h.

◆ setGlobalErrorState()

void QGCStateMachine::setGlobalErrorState ( QAbstractState *  errorState)

Set a global error state that all QGCState errors will transition to

Parameters
errorStateThe state to transition to on error

Definition at line 70 of file QGCStateMachine.cc.

◆ setHistoryRecordingEnabled()

void QGCStateMachine::setHistoryRecordingEnabled ( bool  enabled,
int  maxEntries = 1000 
)

Enable/disable structured transition history recording.

Definition at line 578 of file QGCStateMachine.cc.

References StateHistoryRecorder::setEnabled(), and StateHistoryRecorder::setMaxEntries().

Referenced by QGCStateMachine().

◆ setInitialState()

void QGCStateMachine::setInitialState ( QAbstractState *  state,
bool  autoStart = false 
)

Set the initial state and optionally start the machine

Parameters
stateThe initial state
autoStartIf true, starts the machine immediately

Definition at line 183 of file QGCStateMachine.cc.

References start().

Referenced by resetToState().

◆ setOnEntry()

void QGCStateMachine::setOnEntry ( EntryCallback  callback)
inline

Set a callback to be invoked when the machine starts.

Definition at line 114 of file QGCStateMachine.h.

◆ setOnExit()

void QGCStateMachine::setOnExit ( ExitCallback  callback)
inline

Set a callback to be invoked when the machine stops.

Definition at line 117 of file QGCStateMachine.h.

◆ setProfilingEnabled()

void QGCStateMachine::setProfilingEnabled ( bool  enabled)

Enable/disable state timing profiler.

Definition at line 602 of file QGCStateMachine.cc.

References StateMachineProfiler::setEnabled().

Referenced by QGCStateMachine().

◆ setProgressWeights()

void QGCStateMachine::setProgressWeights ( const QList< QPair< QAbstractState *, int > > &  stateWeights)

Set up weighted progress tracking for a sequence of states. Each state is assigned a weight representing its relative contribution to overall progress. States with higher weights contribute more to the progress bar.

Example:

machine.setProgressWeights({
{state1, 1}, // 1/10 of progress
{state2, 5}, // 5/10 of progress (e.g., slow parameter load)
{state3, 2}, // 2/10 of progress
{state4, 2} // 2/10 of progress
});
Parameters
stateWeightsList of state/weight pairs in order of execution

Definition at line 800 of file QGCStateMachine.cc.

◆ setRecoveryState()

void QGCStateMachine::setRecoveryState ( QAbstractState *  state)
inline

Set a recovery state to transition to after error handling. When an error occurs and this is set, the machine can recover to this state instead of stopping.

Parameters
stateThe state to recover to (nullptr to disable)

Definition at line 360 of file QGCStateMachine.h.

◆ setStateHistoryLimit()

void QGCStateMachine::setStateHistoryLimit ( int  limit)
inline

Set the maximum number of state history entries to keep.

Definition at line 107 of file QGCStateMachine.h.

◆ setStructuredLoggingEnabled()

void QGCStateMachine::setStructuredLoggingEnabled ( bool  enabled)

Enable/disable structured state-machine logger.

Definition at line 620 of file QGCStateMachine.cc.

References StateMachineLogger::setEnabled().

Referenced by QGCStateMachine().

◆ setSubProgress()

void QGCStateMachine::setSubProgress ( float  subProgress)

Update sub-progress within the current state (0.0 to 1.0). Call this from state callbacks to show progress within a long-running state.

Parameters
subProgressProgress within current state (0.0 = just started, 1.0 = complete)

Definition at line 854 of file QGCStateMachine.cc.

References progressUpdate().

◆ setTimeoutOverride()

void QGCStateMachine::setTimeoutOverride ( const QString &  stateName,
int  timeoutMsecs 
)

Set a timeout override for a specific state. Use this to adjust timeouts at runtime without recompiling.

Parameters
stateNameThe object name of the state
timeoutMsecsNew timeout in milliseconds

Definition at line 899 of file QGCStateMachine.cc.

◆ start

◆ stateHistory()

QStringList QGCStateMachine::stateHistory ( ) const
inline

Get a list of recent state names (limited history for QML display)

Returns
List of state names, most recent last

Definition at line 104 of file QGCStateMachine.h.

◆ stateHistoryChanged

void QGCStateMachine::stateHistoryChanged ( )
signal

Emitted when the state history changes (for QML binding)

◆ stopMachine()

void QGCStateMachine::stopMachine ( bool  deleteOnStop = true)

Stop the machine and optionally delete it

Parameters
deleteOnStopIf true, the machine will be deleted when stopped

Definition at line 385 of file QGCStateMachine.cc.

◆ structuredLoggingEnabled()

bool QGCStateMachine::structuredLoggingEnabled ( ) const

Definition at line 628 of file QGCStateMachine.cc.

References StateMachineLogger::isEnabled().

◆ timeoutOverride()

int QGCStateMachine::timeoutOverride ( const QString &  stateName) const

Get the timeout override for a state, or -1 if not set.

Definition at line 910 of file QGCStateMachine.cc.

Referenced by WaitStateBase::restartWait().

◆ timeoutStats()

QHash< QString, int > QGCStateMachine::timeoutStats ( ) const
inline

Get timeout statistics (how often each state timed out)

Definition at line 661 of file QGCStateMachine.h.

◆ transitionsFrom()

QList< QAbstractTransition * > QGCStateMachine::transitionsFrom ( QAbstractState *  state) const

Get all transitions originating from a state

Parameters
stateThe source state
Returns
List of transitions from this state

Definition at line 437 of file QGCStateMachine.cc.

Referenced by deadEndStates(), dumpConfiguration(), exportAsDot(), and reachableFrom().

◆ transitionsTo()

QList< QAbstractTransition * > QGCStateMachine::transitionsTo ( QAbstractState *  state) const

Get all transitions targeting a state

Parameters
stateThe target state
Returns
List of transitions to this state

Definition at line 446 of file QGCStateMachine.cc.

Referenced by predecessorsOf().

◆ unreachableStates()

QList< QAbstractState * > QGCStateMachine::unreachableStates ( ) const

Find states that are not reachable from the initial state. These are typically configuration errors or dead code.

Returns
List of unreachable states

Definition at line 699 of file QGCStateMachine.cc.

References reachableFrom().

◆ vehicle()

Vehicle * QGCStateMachine::vehicle ( ) const
inline

The documentation for this class was generated from the following files: