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 inProgressChanged ()
 Emitted when inProgress() 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)
Vehicle * vehicle () const
QString machineName () const
StateContext & context ()
const StateContext & context () const
bool inProgress () const
bool isRunning () const =delete
 Use inProgress() instead: isRunning() is false until Qt processes the queued start.
void setRunning (bool running)=delete
 Use start() and stop() instead: setRunning() calls QStateMachine::start() and bypasses start().
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 (EventHandlerEventHandler 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)
FunctionState * addFunctionState (const QString &stateName, std::function< void()> function)
AsyncFunctionState * addAsyncFunctionState (const QString &stateName, AsyncFunctionState::SetupFunction setupFunction, int timeoutMsecs=0)
QGCState * 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)
DelayState * addDelayState (int delayMsecs)
ParallelState * addParallelState (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)
QGCFinalState * addFinalState (const QString &stateName=QString())
ConditionalState * addConditionalState (const QString &stateName, ConditionalState::Predicate predicate, ConditionalState::Action action=nullptr)
template<typename Func>
WaitForSignalState * addWaitForSignalState (const QString &stateName, const QObject *sender, Func signal, int timeoutMsecs=0)
SubMachineState * addSubMachineState (const QString &stateName, SubMachineState::MachineFactory factory)
EventQueuedState * addEventQueuedState (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.
FunctionState * addLogAndContinueErrorState (const QString &stateName, QAbstractState *nextState, const QString &message=QString())
 Create a logging error handler state that advances to nextState.
FunctionState * addLogAndStopErrorState (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 in progress.
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>
GuardedTransition * addGuardedTransition (QState *from, Func signal, QAbstractState *to, GuardedTransition::Guard guard, QAbstractAnimation *animation=nullptr)
MachineEventTransition * addEventTransition (QState *from, const QString &eventName, QAbstractState *to, QAbstractAnimation *animation=nullptr)
TimeoutTransition * addTimeoutTransition (QState *from, int timeoutMsecs, QAbstractState *to, QAbstractAnimation *animation=nullptr)
template<typename SenderType, typename Func>
RetryTransition * addRetryTransition (SenderType *from, Func signal, QAbstractState *to, std::function< void()> retryAction, int maxRetries=1)
template<typename SenderType, typename Func>
GuardedTransition * addConditionalTransition (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>
InternalTransition * addInternalTransition (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 in progress (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()

Member Function Documentation

◆ activeStates()

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

Get all currently active states

Returns
Set of active states

Definition at line 314 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 134 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 222 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 468 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 170 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 143 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 238 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 435 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 216 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 127 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 416 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 522 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 317 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 326 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 177 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 451 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 500 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 231 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 446 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 399 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 253 of file QGCStateMachine.h.

References registerState().

◆ allTimeoutOverrides()

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

Get all timeout overrides.

Definition at line 661 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 388 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 198 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 334 of file QGCStateMachine.cc.

References restart(), and start().

Referenced by recoverFromError().

◆ clearTimeoutOverrides()

void QGCStateMachine::clearTimeoutOverrides ( )
inline

Clear all timeout overrides.

Definition at line 664 of file QGCStateMachine.h.

◆ clearTimeoutStats()

void QGCStateMachine::clearTimeoutStats ( )
inline

Clear timeout statistics.

Definition at line 673 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 247 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 59 of file QGCStateMachine.cc.

References 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 800 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 540 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 514 of file QGCStateMachine.cc.

References inProgress().

Referenced by logCurrentState().

◆ dumpRecordedHistory()

QString QGCStateMachine::dumpRecordedHistory ( ) const

Definition at line 617 of file QGCStateMachine.cc.

◆ 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 100 of file QGCStateMachine.cc.

◆ ensureRunning()

void QGCStateMachine::ensureRunning ( )

Start the machine if not already in progress.

Definition at line 403 of file QGCStateMachine.cc.

References inProgress(), and start().

◆ error

void QGCStateMachine::error ( )
signal

◆ event()

bool QGCStateMachine::event ( QEvent * event)
overrideprotected

Definition at line 983 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 658 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 299 of file QGCStateMachine.cc.

◆ findStates()

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

Find all states of a specific type.

Definition at line 323 of file QGCStateMachine.h.

◆ globalErrorState()

QAbstractState * QGCStateMachine::globalErrorState ( ) const
inline

Get the global error state.

Definition at line 149 of file QGCStateMachine.h.

◆ historyRecordingEnabled()

bool QGCStateMachine::historyRecordingEnabled ( ) const

Definition at line 612 of file QGCStateMachine.cc.

◆ inProgress()

bool QGCStateMachine::inProgress ( ) const
inline
Returns
true from start() until the machine emits stopped or finished Unlike QStateMachine::isRunning(), this is already true before Qt processes the queued start.

Definition at line 96 of file QGCStateMachine.h.

Referenced by dumpCurrentState(), ensureRunning(), ComponentInformationManager::progress(), ComponentInformationManager::requestAllComponentInformation(), resetToState(), and restart().

◆ inProgressChanged

void QGCStateMachine::inProgressChanged ( )
signal

Emitted when inProgress() changes (for QML binding).

Referenced by start().

◆ isInErrorState()

bool QGCStateMachine::isInErrorState ( ) const

Check if the machine is in an error state.

Definition at line 309 of file QGCStateMachine.cc.

Referenced by recoverFromError().

◆ isPropertyRestoreEnabled()

bool QGCStateMachine::isPropertyRestoreEnabled ( ) const

Check if property restoration is enabled.

Definition at line 106 of file QGCStateMachine.cc.

◆ isRunning()

bool QGCStateMachine::isRunning ( ) const
delete

Use inProgress() instead: isRunning() is false until Qt processes the queued start.

◆ 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 294 of file QGCStateMachine.cc.

◆ lastError()

QString QGCStateMachine::lastError ( ) const
inline

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

Definition at line 345 of file QGCStateMachine.h.

◆ logConfiguration()

void QGCStateMachine::logConfiguration ( ) const

Log the full configuration to debug output.

Definition at line 593 of file QGCStateMachine.cc.

References dumpConfiguration().

◆ logCurrentState()

void QGCStateMachine::logCurrentState ( ) const

Log the current state to debug output.

Definition at line 588 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 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 760 of file QGCStateMachine.cc.

References reachableFrom().

◆ onEnter()

virtual void QGCStateMachine::onEnter ( )
inlineprotectedvirtual

Override to perform actions when machine starts.

Definition at line 702 of file QGCStateMachine.h.

Referenced by onEntry().

◆ onEntry()

void QGCStateMachine::onEntry ( QEvent * event)
overrideprotected

Definition at line 961 of file QGCStateMachine.cc.

References event(), and onEnter().

Referenced by createTimedActionState(), and setCallbacks().

◆ onExit()

void QGCStateMachine::onExit ( QEvent * event)
overrideprotected

Definition at line 972 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 705 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 192 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 184 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 497 of file QGCStateMachine.cc.

References transitionsTo().

◆ profilingEnabled()

bool QGCStateMachine::profilingEnabled ( ) const

Definition at line 635 of file QGCStateMachine.cc.

◆ profilingSummary()

QString QGCStateMachine::profilingSummary ( ) const

Definition at line 640 of file QGCStateMachine.cc.

◆ progress()

float QGCStateMachine::progress ( ) const

Get the current overall progress (0.0 to 1.0).

Definition at line 890 of file QGCStateMachine.cc.

Referenced by progressUpdate().

◆ 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

References progress().

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 484 of file QGCStateMachine.cc.

References transitionsFrom().

Referenced by maxPathLength(), and unreachableStates().

◆ recordedHistoryJson()

QJsonArray QGCStateMachine::recordedHistoryJson ( ) const

Definition at line 622 of file QGCStateMachine.cc.

◆ recordTimeout()

void QGCStateMachine::recordTimeout ( const QString & stateName)

Record a timeout for statistics.

Definition at line 940 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 376 of file QGCStateMachine.cc.

References clearError(), and isInErrorState().

◆ recoveryState()

QAbstractState * QGCStateMachine::recoveryState ( ) const
inline

Get the recovery state.

Definition at line 369 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 119 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 111 of file QGCStateMachine.cc.

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

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

◆ removeTimeoutOverride()

void QGCStateMachine::removeTimeoutOverride ( const QString & stateName)

Remove a timeout override

Parameters
stateNameThe state name to remove override for

Definition at line 930 of file QGCStateMachine.cc.

◆ resetProgress()

void QGCStateMachine::resetProgress ( )

Reset progress tracking (call when restarting the machine).

Definition at line 895 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 342 of file QGCStateMachine.cc.

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

Referenced by attemptRecovery().

◆ restart()

void QGCStateMachine::restart ( )

Restart the machine (stop then start).

Definition at line 416 of file QGCStateMachine.cc.

References inProgress(), and start().

Referenced by clearError().

◆ setCallbacks()

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

Set both entry and exit callbacks.

Definition at line 951 of file QGCStateMachine.cc.

References onEntry(), and onExit().

◆ setEventHandler()

void QGCStateMachine::setEventHandler ( EventHandlerEventHandler handler)
inline

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

Definition at line 134 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 95 of file QGCStateMachine.cc.

◆ setHistoryRecordingEnabled()

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

Enable/disable structured transition history recording.

Definition at line 603 of file QGCStateMachine.cc.

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 208 of file QGCStateMachine.cc.

References start().

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

◆ setOnEntry()

void QGCStateMachine::setOnEntry ( EntryCallback callback)
inline

Set a callback to be invoked when the machine starts.

Definition at line 120 of file QGCStateMachine.h.

◆ setOnExit()

void QGCStateMachine::setOnExit ( ExitCallback callback)
inline

Set a callback to be invoked when the machine stops.

Definition at line 123 of file QGCStateMachine.h.

◆ setProfilingEnabled()

void QGCStateMachine::setProfilingEnabled ( bool enabled)

Enable/disable state timing profiler.

Definition at line 627 of file QGCStateMachine.cc.

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 825 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 366 of file QGCStateMachine.h.

◆ setRunning()

void QGCStateMachine::setRunning ( bool running)
delete

Use start() and stop() instead: setRunning() calls QStateMachine::start() and bypasses start().

◆ setStateHistoryLimit()

void QGCStateMachine::setStateHistoryLimit ( int limit)
inline

Set the maximum number of state history entries to keep.

Definition at line 113 of file QGCStateMachine.h.

◆ setStructuredLoggingEnabled()

void QGCStateMachine::setStructuredLoggingEnabled ( bool enabled)

Enable/disable structured state-machine logger.

Definition at line 645 of file QGCStateMachine.cc.

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 879 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 924 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 110 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 410 of file QGCStateMachine.cc.

◆ structuredLoggingEnabled()

bool QGCStateMachine::structuredLoggingEnabled ( ) const

Definition at line 653 of file QGCStateMachine.cc.

◆ timeoutOverride()

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

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

Definition at line 935 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 667 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 462 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 471 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 724 of file QGCStateMachine.cc.

References reachableFrom().

◆ vehicle()


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