9#include <QtCore/QTimer>
10#include <QtStateMachine/QFinalState>
11#include <QtStateMachine/QSignalTransition>
16 : QStateMachine (parent)
21 connect(
this, &QGCStateMachine::started,
this, [
this] () {
22 qCDebug(QGCStateMachineLog) <<
"State machine started:" << objectName();
24 qCCritical(QGCStateMachineLog)
26 <<
"started without QGCStateMachine::start() - QStateMachine::start() or setRunning() was used";
32 connect(
this, &QGCStateMachine::stopped,
this, [
this]() {
33 _setInProgress(
false);
34 qCDebug(QGCStateMachineLog) <<
"State machine stopped:" << objectName();
39 connect(
this, &QGCStateMachine::finished,
this, [
this]() {
40 _setInProgress(
false);
41 qCDebug(QGCStateMachineLog) <<
"State machine finished:" << objectName();
42 if (_progressTotalWeight > 0 && _progressLastEmitted < 1.0f) {
43 _progressLastEmitted = 1.0f;
48 if (qEnvironmentVariableIsSet(
"QGC_STATEMACHINE_HISTORY")) {
51 if (qEnvironmentVariableIsSet(
"QGC_STATEMACHINE_PROFILE")) {
54 if (qEnvironmentVariableIsSet(
"QGC_STATEMACHINE_LOG")) {
67 return active ? active->objectName() : QString();
73 qCCritical(QGCStateMachineLog) << objectName()
74 <<
"start() called but already in progress - check signal connections";
77 if ((childMode() == QState::ExclusiveStates) && !initialState()) {
78 qCCritical(QGCStateMachineLog) << objectName() <<
"start() called without an initial state";
82 QStateMachine::start();
87void QGCStateMachine::_setInProgress(
bool inProgress)
97 _globalErrorState = errorState;
102 setGlobalRestorePolicy(QState::RestoreProperties);
103 qCDebug(QGCStateMachineLog) << objectName() <<
"property restore enabled";
108 return globalRestorePolicy() == QState::RestoreProperties;
122 if (_globalErrorState) {
129 auto* state =
new FunctionState(stateName,
this, std::move(function));
138 auto* state =
new AsyncFunctionState(stateName,
this, std::move(setupFunction), timeoutMsecs);
154 .
retry(maxRetries, retryDelayMsecs)
163 if (timeoutMsecs > 0) {
167 return builder.
build();
172 auto* state =
new DelayState(
this, delayMsecs);
186 qCDebug(QGCStateMachineLog) << objectName() <<
"posting event:" << eventName
187 << (priority == HighPriority ?
"(high priority)" :
"");
194 qCDebug(QGCStateMachineLog) << objectName() <<
"posting delayed event:" << eventName <<
"delay:" << delayMsecs <<
"ms";
200 qCDebug(QGCStateMachineLog) << objectName() <<
"cancelling delayed event id:" << eventId;
201 return QStateMachine::cancelDelayedEvent(eventId);
210 QStateMachine::setInitialState(state);
218 auto* state =
new QGCFinalState(stateName.isEmpty() ? QStringLiteral(
"Final") : stateName,
this);
226 auto* state =
new ConditionalState(stateName,
this, std::move(predicate), std::move(action));
233 auto* state =
new SubMachineState(stateName,
this, std::move(factory));
239 const QString& eventName,
242 auto* state =
new EventQueuedState(stateName,
this, eventName, timeoutMsecs);
250 std::function<
void()>
onExit)
253 auto* parentState =
new QState(
this);
254 parentState->setObjectName(stateName);
257 auto* timer =
new QTimer(parentState);
258 timer->setInterval(durationMsecs);
259 timer->setSingleShot(
true);
262 auto* timingState =
new QState(parentState);
263 timingState->setObjectName(stateName + QStringLiteral(
"_Timing"));
266 auto* doneState =
new QFinalState(parentState);
270 connect(timingState, &QState::entered,
this,
onEntry);
272 connect(timingState, &QState::entered, timer, qOverload<>(&QTimer::start));
275 connect(timingState, &QState::exited,
this,
onExit);
279 timingState->addTransition(timer, &QTimer::timeout, doneState);
282 parentState->setInitialState(timingState);
284 qCDebug(QGCStateMachineLog) <<
"Created timed action state:" << stateName
285 <<
"duration:" << durationMsecs <<
"ms";
296 return configuration().contains(state);
302 return findChild<QAbstractState*>(stateName);
311 if (_globalErrorState) {
312 return configuration().contains(_globalErrorState);
318 QAbstractState* nextState,
319 const QString& message)
327 const QString& message)
345 qCCritical(QGCStateMachineLog) << objectName() <<
"resetToState: null state";
350 if (state->parentState() !=
this && state->parent() !=
this) {
351 qCCritical(QGCStateMachineLog) << objectName() <<
"resetToState: state does not belong to this machine";
355 qCDebug(QGCStateMachineLog) << objectName() <<
"resetting to state:" << state->objectName();
359 auto conn = std::make_shared<QMetaObject::Connection>();
360 *conn = connect(
this, &QStateMachine::stopped,
this, [
this, state, conn]() {
379 qCDebug(QGCStateMachineLog) << objectName() <<
"recoverFromError: not in error state";
383 qCDebug(QGCStateMachineLog) << objectName() <<
"recovering from error, restarting";
390 if (!_recoveryState) {
391 qCDebug(QGCStateMachineLog) << objectName() <<
"attemptRecovery: no recovery state set";
395 qCDebug(QGCStateMachineLog) << objectName() <<
"attempting recovery to:" << _recoveryState->objectName();
412 _deleteOnStop = deleteOnStop;
420 auto conn = std::make_shared<QMetaObject::Connection>();
421 *conn = connect(
this, &QStateMachine::stopped,
this, [
this, conn]() {
436 QAbstractAnimation* animation)
440 transition->addAnimation(animation);
442 from->addTransition(transition);
447 QAbstractAnimation* animation)
450 transition->attachToSourceState(from);
452 transition->addAnimation(animation);
454 from->addTransition(transition);
464 QList<QAbstractTransition*> result;
465 if (
auto* qstate = qobject_cast<QState*>(state)) {
466 result = qstate->transitions();
473 QList<QAbstractTransition*> result;
474 const auto allTransitions = findChildren<QAbstractTransition*>();
475 for (QAbstractTransition* transition : allTransitions) {
476 const auto targets = transition->targetStates();
477 if (targets.contains(state)) {
478 result.append(transition);
486 QList<QAbstractState*> result;
488 for (QAbstractState* target : transition->targetStates()) {
489 if (!result.contains(target)) {
490 result.append(target);
499 QList<QAbstractState*> result;
500 for (QAbstractTransition* transition :
transitionsTo(state)) {
501 if (
auto* source = transition->sourceState()) {
502 if (!result.contains(source)) {
503 result.append(source);
516 QString result = objectName() + QStringLiteral(
": ");
519 result += QStringLiteral(
"(not running)");
523 const auto active = configuration();
524 if (active.isEmpty()) {
525 result += QStringLiteral(
"(no active state)");
527 QStringList stateNames;
528 for (QAbstractState* state : active) {
529 stateNames.append(state->objectName().isEmpty()
530 ? QStringLiteral(
"<unnamed>")
531 : state->objectName());
533 result += stateNames.join(QStringLiteral(
", "));
534 result += QStringLiteral(
" (running)");
543 result += QStringLiteral(
"State Machine: %1\n").arg(objectName());
544 result += QStringLiteral(
"================\n");
547 const auto allStates = findChildren<QAbstractState*>();
548 result += QStringLiteral(
"States (%1):\n").arg(allStates.size());
550 for (QAbstractState* state : allStates) {
551 QString stateName = state->objectName().isEmpty()
552 ? QStringLiteral(
"<unnamed>")
553 : state->objectName();
557 if (state == initialState()) {
558 marker = QStringLiteral(
" [initial]");
560 if (qobject_cast<QFinalState*>(state)) {
561 marker += QStringLiteral(
" [final]");
563 if (state == _globalErrorState) {
564 marker += QStringLiteral(
" [error]");
566 if (configuration().contains(state)) {
567 marker += QStringLiteral(
" [active]");
570 result += QStringLiteral(
" - %1%2\n").arg(stateName, marker);
574 for (QAbstractTransition* transition : transitions) {
575 const auto targets = transition->targetStates();
576 for (QAbstractState* target : targets) {
577 QString targetName = target->objectName().isEmpty()
578 ? QStringLiteral(
"<unnamed>")
579 : target->objectName();
580 result += QStringLiteral(
" -> %1\n").arg(targetName);
596 for (
const QString& line : lines) {
597 if (!line.isEmpty()) {
598 qCDebug(QGCStateMachineLog) << line;
605 if (!_historyRecorder) {
608 _historyRecorder->setMaxEntries(maxEntries);
609 _historyRecorder->setEnabled(enabled);
614 return _historyRecorder && _historyRecorder->isEnabled();
619 return _historyRecorder ? _historyRecorder->dumpHistory() : QString();
624 return _historyRecorder ? _historyRecorder->toJson() : QJsonArray();
632 _profiler->setEnabled(enabled);
637 return _profiler && _profiler->isEnabled();
642 return _profiler ? _profiler->summary() : QString();
650 _logger->setEnabled(enabled);
655 return _logger && _logger->isEnabled();
661 dot += QStringLiteral(
"digraph \"%1\" {\n").arg(objectName());
662 dot += QStringLiteral(
" rankdir=TB;\n");
663 dot += QStringLiteral(
" node [shape=box, style=rounded];\n");
664 dot += QStringLiteral(
"\n");
666 const auto allStates = findChildren<QAbstractState*>();
669 for (QAbstractState* state : allStates) {
670 QString name = state->objectName().isEmpty()
671 ? QStringLiteral(
"state_%1").arg(
reinterpret_cast<quintptr
>(state), 0, 16)
672 : state->objectName();
675 if (state == initialState()) {
676 attrs << QStringLiteral(
"style=\"rounded,bold\"");
677 attrs << QStringLiteral(
"peripheries=2");
679 if (qobject_cast<QFinalState*>(state)) {
680 attrs << QStringLiteral(
"shape=doublecircle");
682 if (state == _globalErrorState) {
683 attrs << QStringLiteral(
"color=red");
686 if (attrs.isEmpty()) {
687 dot += QStringLiteral(
" \"%1\";\n").arg(name);
689 dot += QStringLiteral(
" \"%1\" [%2];\n").arg(name, attrs.join(
", "));
693 dot += QStringLiteral(
"\n");
696 for (QAbstractState* state : allStates) {
697 QString fromName = state->objectName().isEmpty()
698 ? QStringLiteral(
"state_%1").arg(
reinterpret_cast<quintptr
>(state), 0, 16)
699 : state->objectName();
702 for (QAbstractTransition* transition : transitions) {
703 const auto targets = transition->targetStates();
704 for (QAbstractState* target : targets) {
705 QString toName = target->objectName().isEmpty()
706 ? QStringLiteral(
"state_%1").arg(
reinterpret_cast<quintptr
>(target), 0, 16)
707 : target->objectName();
710 QString label = transition->objectName();
711 if (label.isEmpty()) {
712 dot += QStringLiteral(
" \"%1\" -> \"%2\";\n").arg(fromName, toName);
714 dot += QStringLiteral(
" \"%1\" -> \"%2\" [label=\"%3\"];\n").arg(fromName, toName, label);
720 dot += QStringLiteral(
"}\n");
726 QList<QAbstractState*> unreachable;
728 if (!initialState()) {
733 QSet<QAbstractState*> visited;
734 QList<QAbstractState*> queue;
735 queue.append(initialState());
736 visited.insert(initialState());
738 while (!queue.isEmpty()) {
739 QAbstractState* current = queue.takeFirst();
741 for (QAbstractState* next : reachable) {
742 if (!visited.contains(next)) {
743 visited.insert(next);
750 const auto allStates = findChildren<QAbstractState*>();
751 for (QAbstractState* state : allStates) {
752 if (!visited.contains(state)) {
753 unreachable.append(state);
762 if (!initialState()) {
767 QHash<QAbstractState*, int> depth;
768 QList<QAbstractState*> queue;
770 queue.append(initialState());
771 depth[initialState()] = 0;
774 const int stateCount = findChildren<QAbstractState*>().size();
775 const int maxSearchDepth = qMax(stateCount * 2, 100);
777 while (!queue.isEmpty()) {
778 QAbstractState* current = queue.takeFirst();
779 int currentDepth = depth[current];
781 if (currentDepth >= maxSearchDepth) {
786 for (QAbstractState* next : reachable) {
787 int newDepth = currentDepth + 1;
789 if (!depth.contains(next) || depth[next] < newDepth) {
790 depth[next] = newDepth;
791 maxDepth = qMax(maxDepth, newDepth);
802 QList<QAbstractState*> deadEnds;
804 const auto allStates = findChildren<QAbstractState*>();
805 for (QAbstractState* state : allStates) {
807 if (qobject_cast<QFinalState*>(state)) {
813 if (transitions.isEmpty()) {
814 deadEnds.append(state);
828 for (
auto* state : _progressStates) {
829 disconnect(state, &QAbstractState::entered,
this, &QGCStateMachine::_onStateEntered);
832 _progressStates.clear();
833 _progressWeights.clear();
834 _progressTotalWeight = 0;
836 for (
const auto& pair : stateWeights) {
837 _progressStates.append(pair.first);
838 _progressWeights.append(pair.second);
839 _progressTotalWeight += pair.second;
842 connect(pair.first, &QAbstractState::entered,
this, &QGCStateMachine::_onStateEntered);
845 qCDebug(QGCStateMachineLog) << objectName() <<
"progress tracking enabled for"
846 << _progressStates.size() <<
"states, total weight:" << _progressTotalWeight;
849void QGCStateMachine::_onStateEntered()
851 auto* state = qobject_cast<QAbstractState*>(sender());
855 QString stateName = state->objectName();
856 if (!stateName.isEmpty()) {
857 _stateHistory.append(stateName);
858 while (_stateHistory.size() > _stateHistoryLimit) {
859 _stateHistory.removeFirst();
866 int index = _progressStates.indexOf(state);
867 if (index >= 0 && index != _progressCurrentIndex) {
868 _progressCurrentIndex = index;
869 _progressSubProgress = 0.0f;
871 float newProgress = _calculateProgress();
872 if (newProgress > _progressLastEmitted) {
873 _progressLastEmitted = newProgress;
881 _progressSubProgress = qBound(0.0f, subProgress, 1.0f);
883 float newProgress = _calculateProgress();
884 if (newProgress > _progressLastEmitted) {
885 _progressLastEmitted = newProgress;
892 return _progressLastEmitted;
897 _progressCurrentIndex = -1;
898 _progressSubProgress = 0.0f;
899 _progressLastEmitted = 0.0f;
902float QGCStateMachine::_calculateProgress()
const
904 if (_progressTotalWeight <= 0 || _progressCurrentIndex < 0) {
908 int completedWeight = 0;
909 for (
int i = 0; i < _progressCurrentIndex && i < _progressWeights.size(); ++i) {
910 completedWeight += _progressWeights[i];
913 int currentWeight = (_progressCurrentIndex < _progressWeights.size())
914 ? _progressWeights[_progressCurrentIndex]
917 return (completedWeight + currentWeight * _progressSubProgress) /
static_cast<float>(_progressTotalWeight);
926 _timeoutOverrides[stateName] = timeoutMsecs;
927 qCDebug(QGCStateMachineLog) << objectName() <<
"timeout override set for" << stateName <<
":" << timeoutMsecs <<
"ms";
932 _timeoutOverrides.remove(stateName);
937 return _timeoutOverrides.value(stateName, -1);
942 _timeoutStats[stateName]++;
943 qCDebug(QGCStateMachineLog) << objectName() <<
"timeout recorded for" << stateName
944 <<
"total:" << _timeoutStats[stateName];
953 _entryCallback = std::move(
onEntry);
954 _exitCallback = std::move(
onExit);
963 QStateMachine::onEntry(
event);
965 if (_entryCallback) {
980 QStateMachine::onExit(
event);
986 if (_eventHandler &&
event->type() >= QEvent::User) {
987 if (_eventHandler(
event)) {
992 return QStateMachine::event(
event);
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.
Fluent builder for creating error recovery states.
ErrorRecoveryBuilder & retry(int maxRetries, int delayMsecs=1000)
ErrorRecoveryBuilder & withFallback(Action fallback)
Add a fallback action to try if primary fails.
ErrorRecoveryBuilder & withAction(Action action)
Set the primary action to execute.
ExhaustedBehavior
What to do when all recovery options are exhausted.
std::function< bool()> Action
std::function< void()> VoidAction
ErrorRecoveryBuilder & onExhausted(ExhaustedBehavior behavior)
Configure what happens when all options are exhausted.
ErrorRecoveryBuilder & withRollback(VoidAction rollback)
Add a rollback action to execute on failure.
QGCState * build()
Build and return the configured state.
ErrorRecoveryBuilder & withTimeout(int timeoutMsecs)
Set a timeout for the entire operation.
A state that waits for one or more named events before advancing.
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.
Custom event for QGCStateMachine delayed/scheduled events.
FunctionState * addFunctionState(const QString &stateName, std::function< void()> function)
void recordTimeout(const QString &stateName)
Record a timeout for statistics.
void stopMachine(bool deleteOnStop=true)
bool structuredLoggingEnabled() const
void clearError(bool restart=false)
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).
void enablePropertyRestore()
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)
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 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
int postDelayedEvent(const QString &eventName, int delayMsecs, const QVariant &data=QVariant())
QList< QAbstractState * > unreachableStates() const
QGCStateMachine(const QString &machineName, Vehicle *vehicle, QObject *parent=nullptr)
QString machineName() const
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
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 setProgressWeights(const QList< QPair< QAbstractState *, int > > &stateWeights)
DelayState * addDelayState(int delayMsecs)
void ensureRunning()
Start the machine if not already in progress.
QString dumpConfiguration() const
QList< QAbstractTransition * > transitionsTo(QAbstractState *state) const
QString currentStateName() const
QGCFinalState * addFinalState(const QString &stateName=QString())
void resetProgress()
Reset progress tracking (call when restarting the machine).
bool isInErrorState() const
Check if the machine is in an error state.
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.
void stateHistoryChanged()
Emitted when the state history changes (for QML binding).
void setCallbacks(EntryCallback onEntry, ExitCallback onExit=nullptr)
Set both entry and exit callbacks.
QString profilingSummary() const
void removeTimeoutOverride(const QString &stateName)
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)
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.
QString dumpCurrentState() const
Full-featured base class for QGroundControl state machine states.
QAbstractState * localErrorState() const
Get the per-state error state (nullptr if using global).
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.
FunctionState * logAndContinue(QGCStateMachine *machine, const QString &stateName, QAbstractState *nextState, const QString &message)
FunctionState * logAndStop(QGCStateMachine *machine, const QString &stateName, const QString &message)