QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
QGCStateMachine.h
Go to the documentation of this file.
1#pragma once
2
5#include "ConditionalState.h"
6#include "DelayState.h"
7#include "EventQueuedState.h"
9#include "FunctionState.h"
10#include "LoopState.h"
12#include "QGCSignalTransition.h"
13#include "GuardedTransition.h"
14#include "InternalTransition.h"
17#include "RetryTransition.h"
18#include "TimeoutTransition.h"
19#include "QGCAbstractState.h"
20#include "QGCEventTransition.h"
22#include "QGCFinalState.h"
23#include "QGCHistoryState.h"
24#include "ParallelState.h"
26#include "RequestMessageState.h"
27#include "RetryState.h"
28#include "RollbackState.h"
31#include "SequenceState.h"
32#include "ShowAppMessageState.h"
33#include "SkippableAsyncState.h"
34#include "SubMachineState.h"
35#include "ProgressState.h"
39#include "WaitForSignalState.h"
40#include "WaitStateBase.h"
41#include "StateContext.h"
43#include "ErrorHandlers.h"
44
45#include <QtStateMachine/QStateMachine>
46#include <QtStateMachine/QFinalState>
47#include <QtStateMachine/QHistoryState>
48#include <QtCore/QAbstractAnimation>
49#include <QtCore/QJsonArray>
50#include <QtCore/QString>
51#include <QtCore/QVariant>
52
53#include <functional>
54
55class Vehicle;
59
62class QGCStateMachine : public QStateMachine
63{
64 Q_OBJECT
65 Q_DISABLE_COPY(QGCStateMachine)
66
67
68 Q_PROPERTY(QString currentStateName READ currentStateName NOTIFY currentStateNameChanged)
69
70
71 Q_PROPERTY(float progress READ progress NOTIFY progressUpdate)
72
73
74 Q_PROPERTY(bool inProgress READ inProgress NOTIFY inProgressChanged)
75
76
77 Q_PROPERTY(QStringList stateHistory READ stateHistory NOTIFY stateHistoryChanged)
78
79public:
80 using EntryCallback = std::function<void()>;
81 using ExitCallback = std::function<void()>;
82 using EventHandler = std::function<bool(QEvent*)>;
83
84 QGCStateMachine(const QString& machineName, Vehicle* vehicle, QObject* parent = nullptr);
85
86 Vehicle *vehicle() const { return _vehicle; }
87 QString machineName() const { return objectName(); }
88
91 StateContext& context() { return _context; }
92 const StateContext& context() const { return _context; }
93
96 bool inProgress() const { return _inProgress; }
97
99 bool isRunning() const = delete;
100
102 void setRunning(bool running) = delete;
103
106 QString currentStateName() const;
107
110 QStringList stateHistory() const { return _stateHistory; }
111
113 void setStateHistoryLimit(int limit) { _stateHistoryLimit = limit; }
114
115 // -------------------------------------------------------------------------
116 // Entry/Exit Callbacks
117 // -------------------------------------------------------------------------
118
120 void setOnEntry(EntryCallback callback) { _entryCallback = std::move(callback); }
121
123 void setOnExit(ExitCallback callback) { _exitCallback = std::move(callback); }
124
127
128 // -------------------------------------------------------------------------
129 // Event Handling
130 // -------------------------------------------------------------------------
131
134 void setEventHandler(EventHandler handler) { _eventHandler = std::move(handler); }
135
140
142 bool isPropertyRestoreEnabled() const;
143
146 void setGlobalErrorState(QAbstractState* errorState);
147
149 QAbstractState* globalErrorState() const { return _globalErrorState; }
150
154 void registerState(QGCState* state);
155
158 void registerState(QGCAbstractState* state);
159
164 FunctionState* addFunctionState(const QString& stateName, std::function<void()> function);
165
171 AsyncFunctionState* addAsyncFunctionState(const QString& stateName,
173 int timeoutMsecs = 0);
174
185 QGCState* addErrorRecoveryState(const QString& stateName,
187 int maxRetries = 0,
188 int retryDelayMsecs = 1000,
190 ErrorRecoveryBuilder::Action fallback = nullptr,
191 ErrorRecoveryBuilder::VoidAction rollback = nullptr,
192 int timeoutMsecs = 0);
193
197 DelayState* addDelayState(int delayMsecs);
198
202 ParallelState* addParallelState(const QString& stateName);
203
208 void postEvent(const QString& eventName, const QVariant& data = QVariant(),
209 EventPriority priority = NormalPriority);
210
216 int postDelayedEvent(const QString& eventName, int delayMsecs, const QVariant& data = QVariant());
217
221 bool cancelDelayedEvent(int eventId);
222
223 // -------------------------------------------------------------------------
224 // State Configuration
225 // -------------------------------------------------------------------------
226
230 void setInitialState(QAbstractState* state, bool autoStart = false);
231
235 QGCFinalState* addFinalState(const QString& stateName = QString());
236
242 ConditionalState* addConditionalState(const QString& stateName,
244 ConditionalState::Action action = nullptr);
245
252 template<typename Func>
253 WaitForSignalState* addWaitForSignalState(const QString& stateName,
254 const QObject* sender,
255 Func signal,
256 int timeoutMsecs = 0)
257 {
258 auto* state = new WaitForSignalState(stateName, this, sender, signal, timeoutMsecs);
259 registerState(state);
260 return state;
261 }
262
267 SubMachineState* addSubMachineState(const QString& stateName, SubMachineState::MachineFactory factory);
268
274 EventQueuedState* addEventQueuedState(const QString& stateName,
275 const QString& eventName,
276 int timeoutMsecs = 0);
277
298 QState* createTimedActionState(const QString& stateName,
299 int durationMsecs,
300 std::function<void()> onEntry = nullptr,
301 std::function<void()> onExit = nullptr);
302
303 // -------------------------------------------------------------------------
304 // State Queries
305 // -------------------------------------------------------------------------
306
310 bool isStateActive(QAbstractState* state) const;
311
314 QSet<QAbstractState*> activeStates() const { return configuration(); }
315
319 QAbstractState* findState(const QString& stateName) const;
320
322 template<typename T>
323 QList<T*> findStates() const
324 {
325 return findChildren<T*>();
326 }
327
328 // -------------------------------------------------------------------------
329 // Error Handling & Recovery
330 // -------------------------------------------------------------------------
331
333 bool isInErrorState() const;
334
336 FunctionState* addLogAndContinueErrorState(const QString& stateName,
337 QAbstractState* nextState,
338 const QString& message = QString());
339
341 FunctionState* addLogAndStopErrorState(const QString& stateName,
342 const QString& message = QString());
343
345 QString lastError() const { return errorString(); }
346
349 void clearError(bool restart = false);
350
355 bool resetToState(QAbstractState* state);
356
360 bool recoverFromError();
361
366 void setRecoveryState(QAbstractState* state) { _recoveryState = state; }
367
369 QAbstractState* recoveryState() const { return _recoveryState; }
370
373 bool attemptRecovery();
374
375 // -------------------------------------------------------------------------
376 // Lifecycle Helpers
377 // -------------------------------------------------------------------------
378
380 void ensureRunning();
381
384 void stopMachine(bool deleteOnStop = true);
385
387 void restart();
388
389 // -------------------------------------------------------------------------
390 // Transition Helpers
391 // -------------------------------------------------------------------------
392
398 template<typename Func>
399 QSignalTransition* addTransition(QState* from, Func signal, QAbstractState* to,
400 QAbstractAnimation* animation = nullptr)
401 {
402 auto* transition = from->addTransition(from, signal, to);
403 if (animation) {
404 transition->addAnimation(animation);
405 }
406 return transition;
407 }
408
415 template<typename Func>
416 GuardedTransition* addGuardedTransition(QState* from, Func signal, QAbstractState* to,
418 QAbstractAnimation* animation = nullptr)
419 {
420 auto* transition = new GuardedTransition(from, signal, to, std::move(guard));
421 from->addTransition(transition);
422 if (animation) {
423 transition->addAnimation(animation);
424 }
425 return transition;
426 }
427
433 MachineEventTransition* addEventTransition(QState* from, const QString& eventName, QAbstractState* to,
434 QAbstractAnimation* animation = nullptr);
435
441 TimeoutTransition* addTimeoutTransition(QState* from, int timeoutMsecs, QAbstractState* to,
442 QAbstractAnimation* animation = nullptr);
443
450 template<typename SenderType, typename Func>
451 RetryTransition* addRetryTransition(SenderType* from, Func signal,
452 QAbstractState* to,
453 std::function<void()> retryAction,
454 int maxRetries = 1)
455 {
456 auto* transition = new RetryTransition(from, signal, to, std::move(retryAction), maxRetries);
457 from->addTransition(transition);
458 return transition;
459 }
460
467 template<typename SenderType, typename Func>
468 GuardedTransition* addConditionalTransition(SenderType* from, Func signal,
469 QAbstractState* to,
470 std::function<bool()> guard)
471 {
472 auto* transition = new GuardedTransition(from, signal, to, std::move(guard));
473 from->addTransition(transition);
474 return transition;
475 }
476
499 template<typename Sender, typename Signal>
500 QSignalTransition* addSelfLoopTransition(QState* state,
501 Sender* sender,
502 Signal signal,
503 std::function<void()> action)
504 {
505 auto* transition = state->addTransition(sender, signal, state);
506 if (action) {
507 connect(transition, &QAbstractTransition::triggered, this, std::move(action));
508 }
509 return transition;
510 }
511
521 template<typename Sender, typename Signal>
523 Sender* sender,
524 Signal signal,
525 std::function<void()> action)
526 {
527 auto* transition = new InternalTransition(sender, signal, std::move(action));
528 state->addTransition(transition);
529 return transition;
530 }
531
532 // -------------------------------------------------------------------------
533 // State Introspection
534 // -------------------------------------------------------------------------
535
539 QList<QAbstractTransition*> transitionsFrom(QAbstractState* state) const;
540
544 QList<QAbstractTransition*> transitionsTo(QAbstractState* state) const;
545
549 QList<QAbstractState*> reachableFrom(QAbstractState* state) const;
550
554 QList<QAbstractState*> predecessorsOf(QAbstractState* state) const;
555
556 // -------------------------------------------------------------------------
557 // Debugging & Visualization
558 // -------------------------------------------------------------------------
559
563 QString dumpCurrentState() const;
564
568 QString dumpConfiguration() const;
569
571 void logCurrentState() const;
572
574 void logConfiguration() const;
575
577 void setHistoryRecordingEnabled(bool enabled, int maxEntries = 1000);
578 bool historyRecordingEnabled() const;
579 QString dumpRecordedHistory() const;
580 QJsonArray recordedHistoryJson() const;
581
583 void setProfilingEnabled(bool enabled);
584 bool profilingEnabled() const;
585 QString profilingSummary() const;
586
588 void setStructuredLoggingEnabled(bool enabled);
589 bool structuredLoggingEnabled() const;
590
594 QString exportAsDot() const;
595
599 QList<QAbstractState*> unreachableStates() const;
600
604 int maxPathLength() const;
605
609 QList<QAbstractState*> deadEndStates() const;
610
611 // -------------------------------------------------------------------------
612 // Progress Tracking
613 // -------------------------------------------------------------------------
614
630 void setProgressWeights(const QList<QPair<QAbstractState*, int>>& stateWeights);
631
635 void setSubProgress(float subProgress);
636
638 float progress() const;
639
641 void resetProgress();
642
643 // -------------------------------------------------------------------------
644 // Timeout Configuration
645 // -------------------------------------------------------------------------
646
651 void setTimeoutOverride(const QString& stateName, int timeoutMsecs);
652
655 void removeTimeoutOverride(const QString& stateName);
656
658 int timeoutOverride(const QString& stateName) const;
659
661 QHash<QString, int> allTimeoutOverrides() const { return _timeoutOverrides; }
662
664 void clearTimeoutOverrides() { _timeoutOverrides.clear(); }
665
667 QHash<QString, int> timeoutStats() const { return _timeoutStats; }
668
670 void recordTimeout(const QString& stateName);
671
673 void clearTimeoutStats() { _timeoutStats.clear(); }
674
675public slots:
677 void start();
678
679signals:
680 void error();
681
685
689 void machineEvent(const QString& eventName);
690
693
696
699
700protected:
702 virtual void onEnter() {}
703
705 virtual void onLeave() {}
706
707 // QStateMachine overrides
708 void onEntry(QEvent* event) override;
709 void onExit(QEvent* event) override;
710 bool event(QEvent* event) override;
711
712private:
713 void _onStateEntered();
714 void _setInProgress(bool inProgress);
715 float _calculateProgress() const;
716
717 Vehicle* _vehicle = nullptr;
718 QAbstractState* _globalErrorState = nullptr;
719 QAbstractState* _recoveryState = nullptr;
720 bool _deleteOnStop = false;
721 bool _inProgress = false;
722 EntryCallback _entryCallback;
723 ExitCallback _exitCallback;
724 EventHandler _eventHandler;
725
726 // Progress tracking
727 QList<QAbstractState*> _progressStates;
728 QList<int> _progressWeights;
729 int _progressTotalWeight = 0;
730 int _progressCurrentIndex = -1;
731 float _progressSubProgress = 0.0f;
732 float _progressLastEmitted = 0.0f;
733
734 // Inter-state data context
735 StateContext _context;
736
737 // QML state history
738 QStringList _stateHistory;
739 int _stateHistoryLimit = 20;
740
741 // Timeout configuration
742 QHash<QString, int> _timeoutOverrides;
743 QHash<QString, int> _timeoutStats;
744
745 // Optional runtime diagnostics helpers (lazy-created)
746 StateHistoryRecorder* _historyRecorder = nullptr;
747 StateMachineProfiler* _profiler = nullptr;
748 StateMachineLogger* _logger = nullptr;
749};
Calls a function when entered and waits for an external trigger to advance.
std::function< void(AsyncFunctionState *state)> SetupFunction
A state that evaluates a predicate on entry and either executes or skips.
std::function< void()> Action
std::function< bool()> Predicate
Delays that state machine for the specified time in milliseconds.
Definition DelayState.h:10
ExhaustedBehavior
What to do when all recovery options are exhausted.
@ EmitError
Emit error() signal (default).
std::function< bool()> Action
std::function< void()> VoidAction
Drives the MAVLink events protocol for a single component.
A state that waits for one or more named events before advancing.
A transition that only fires if a guard predicate returns true.
std::function< bool()> Guard
Transition that fires without exiting/re-entering the current state.
Transition that fires when a named event is posted to the state machine.
State that executes all child states in parallel.
Lightweight base class for simple states.
Final state for a QGCStateMachine with logging support.
QAbstractState * recoveryState() const
Get the recovery state.
QList< T * > findStates() const
Find all states of a specific type.
FunctionState * addFunctionState(const QString &stateName, std::function< void()> function)
GuardedTransition * addGuardedTransition(QState *from, Func signal, QAbstractState *to, GuardedTransition::Guard guard, QAbstractAnimation *animation=nullptr)
void recordTimeout(const QString &stateName)
Record a timeout for statistics.
void stopMachine(bool deleteOnStop=true)
bool structuredLoggingEnabled() const
void clearError(bool restart=false)
QAbstractState * globalErrorState() const
Get the global error state.
MachineEventTransition * addEventTransition(QState *from, const QString &eventName, QAbstractState *to, QAbstractAnimation *animation=nullptr)
FunctionState * addLogAndStopErrorState(const QString &stateName, const QString &message=QString())
Create a logging error handler state that stops the machine.
void inProgressChanged()
Emitted when inProgress() changes (for QML binding).
int timeoutOverride(const QString &stateName) const
Get the timeout override for a state, or -1 if not set.
void start()
Start the state machine with debug logging.
void progressUpdate(float progress)
void setEventHandler(EventHandler handler)
bool isPropertyRestoreEnabled() const
Check if property restoration is enabled.
QList< QAbstractTransition * > transitionsFrom(QAbstractState *state) const
TimeoutTransition * addTimeoutTransition(QState *from, int timeoutMsecs, QAbstractState *to, QAbstractAnimation *animation=nullptr)
void logConfiguration() const
Log the full configuration to debug output.
bool profilingEnabled() const
ParallelState * addParallelState(const QString &stateName)
void setGlobalErrorState(QAbstractState *errorState)
QList< QAbstractState * > reachableFrom(QAbstractState *state) const
void onExit(QEvent *event) override
bool resetToState(QAbstractState *state)
QString dumpRecordedHistory() const
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)
QList< QAbstractState * > predecessorsOf(QAbstractState *state) const
QSet< QAbstractState * > activeStates() const
std::function< void()> ExitCallback
QString exportAsDot() const
void setStructuredLoggingEnabled(bool enabled)
Enable/disable structured state-machine logger.
bool historyRecordingEnabled() const
std::function< void()> EntryCallback
Name of the currently active state (for QML binding).
void clearTimeoutOverrides()
Clear all timeout overrides.
bool isRunning() const =delete
Use inProgress() instead: isRunning() is false until Qt processes the queued start.
void currentStateNameChanged()
Emitted when the current state changes (for QML binding).
EventQueuedState * addEventQueuedState(const QString &stateName, const QString &eventName, int timeoutMsecs=0)
void logCurrentState() const
Log the current state to debug output.
QJsonArray recordedHistoryJson() const
void setSubProgress(float subProgress)
QList< QAbstractState * > deadEndStates() const
const StateContext & context() const
int postDelayedEvent(const QString &eventName, int delayMsecs, const QVariant &data=QVariant())
QList< QAbstractState * > unreachableStates() const
void setStateHistoryLimit(int limit)
Set the maximum number of state history entries to keep.
QGCStateMachine(const QString &machineName, Vehicle *vehicle, QObject *parent=nullptr)
QString machineName() const
QSignalTransition * addSelfLoopTransition(QState *state, Sender *sender, Signal signal, std::function< void()> action)
AsyncFunctionState * addAsyncFunctionState(const QString &stateName, AsyncFunctionState::SetupFunction setupFunction, int timeoutMsecs=0)
bool isStateActive(QAbstractState *state) const
void machineEvent(const QString &eventName)
SubMachineState * addSubMachineState(const QString &stateName, SubMachineState::MachineFactory factory)
int maxPathLength() const
QAbstractState * findState(const QString &stateName) const
StateContext & context()
void setOnEntry(EntryCallback callback)
Set a callback to be invoked when the machine starts.
QHash< QString, int > timeoutStats() const
Get timeout statistics (how often each state timed out).
void setHistoryRecordingEnabled(bool enabled, int maxEntries=1000)
Enable/disable structured transition history recording.
bool event(QEvent *event) override
void setProfilingEnabled(bool enabled)
Enable/disable state timing profiler.
bool cancelDelayedEvent(int eventId)
Vehicle * vehicle() const
void setInitialState(QAbstractState *state, bool autoStart=false)
void setOnExit(ExitCallback callback)
Set a callback to be invoked when the machine stops.
void setProgressWeights(const QList< QPair< QAbstractState *, int > > &stateWeights)
void setRecoveryState(QAbstractState *state)
DelayState * addDelayState(int delayMsecs)
void ensureRunning()
Start the machine if not already in progress.
QString dumpConfiguration() const
void clearTimeoutStats()
Clear timeout statistics.
QString lastError() const
Get the last error message (from Qt's internal error handling).
QList< QAbstractTransition * > transitionsTo(QAbstractState *state) const
QString currentStateName() const
InternalTransition * addInternalTransition(QState *state, Sender *sender, Signal signal, std::function< void()> action)
WaitForSignalState * addWaitForSignalState(const QString &stateName, const QObject *sender, Func signal, int timeoutMsecs=0)
QGCFinalState * addFinalState(const QString &stateName=QString())
void resetProgress()
Reset progress tracking (call when restarting the machine).
QStringList stateHistory() const
bool isInErrorState() const
Check if the machine is in an error state.
bool inProgress() const
QHash< QString, int > allTimeoutOverrides() const
Get all timeout overrides.
void setTimeoutOverride(const QString &stateName, int timeoutMsecs)
QState * createTimedActionState(const QString &stateName, int durationMsecs, std::function< void()> onEntry=nullptr, std::function< void()> onExit=nullptr)
void onEntry(QEvent *event) override
void postEvent(const QString &eventName, const QVariant &data=QVariant(), EventPriority priority=NormalPriority)
virtual void onLeave()
Override to perform actions when machine stops.
RetryTransition * addRetryTransition(SenderType *from, Func signal, QAbstractState *to, std::function< void()> retryAction, int maxRetries=1)
void stateHistoryChanged()
Emitted when the state history changes (for QML binding).
QSignalTransition * addTransition(QState *from, Func signal, QAbstractState *to, QAbstractAnimation *animation=nullptr)
void setCallbacks(EntryCallback onEntry, ExitCallback onExit=nullptr)
Set both entry and exit callbacks.
QString profilingSummary() const
void removeTimeoutOverride(const QString &stateName)
GuardedTransition * addConditionalTransition(SenderType *from, Func signal, QAbstractState *to, std::function< bool()> guard)
float progress() const
Get the current overall progress (0.0 to 1.0).
virtual void onEnter()
Override to perform actions when machine starts.
void registerState(QGCState *state)
void setRunning(bool running)=delete
Use start() and stop() instead: setRunning() calls QStateMachine::start() and bypasses start().
ConditionalState * addConditionalState(const QString &stateName, ConditionalState::Predicate predicate, ConditionalState::Action action=nullptr)
void restart()
Restart the machine (stop then start).
FunctionState * addLogAndContinueErrorState(const QString &stateName, QAbstractState *nextState, const QString &message=QString())
Create a logging error handler state that advances to nextState.
std::function< bool(QEvent *)> EventHandler
QString dumpCurrentState() const
Full-featured base class for QGroundControl state machine states.
Definition QGCState.h:23
Transition that retries an action N times before advancing to target state.
Type-safe context for passing data between states in a state machine.
Records state machine transitions for debugging and analysis.
Extended logging for state machines.
Performance profiler for state machines.
State that invokes a child state machine.
std::function< QGCStateMachine *(SubMachineState *parent)> MachineFactory
Transition that fires automatically after a specified delay.
Waits for a signal from a QObject before advancing.