QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
QGCStateMachine.cc
Go to the documentation of this file.
1#include "QGCStateMachine.h"
5#include "AudioOutput.h"
7#include "Vehicle.h"
8
9#include <QtCore/QTimer>
10#include <QtStateMachine/QFinalState>
11#include <QtStateMachine/QSignalTransition>
12
13#include <memory>
14
16 : QStateMachine (parent)
17 , _vehicle (vehicle)
18{
19 setObjectName(machineName);
20
21 connect(this, &QGCStateMachine::started, this, [this] () {
22 qCDebug(QGCStateMachineLog) << "State machine started:" << objectName();
23 if (!_inProgress) {
24 qCCritical(QGCStateMachineLog)
25 << objectName()
26 << "started without QGCStateMachine::start() - QStateMachine::start() or setRunning() was used";
27 _setInProgress(true);
28 }
29 });
30 // Cleared before anything else reacts to stopped/finished so handlers, including the final progress update,
31 // already see the machine as no longer in progress
32 connect(this, &QGCStateMachine::stopped, this, [this]() {
33 _setInProgress(false);
34 qCDebug(QGCStateMachineLog) << "State machine stopped:" << objectName();
35 if (_deleteOnStop) {
36 deleteLater();
37 }
38 });
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;
44 emit progressUpdate(1.0f);
45 }
46 });
47
48 if (qEnvironmentVariableIsSet("QGC_STATEMACHINE_HISTORY")) {
50 }
51 if (qEnvironmentVariableIsSet("QGC_STATEMACHINE_PROFILE")) {
53 }
54 if (qEnvironmentVariableIsSet("QGC_STATEMACHINE_LOG")) {
56 }
57}
58
60{
61 const auto activeStates = configuration();
62 if (activeStates.isEmpty()) {
63 return QString();
64 }
65 // Return the name of the first (deepest) active state
66 QAbstractState* active = *activeStates.begin();
67 return active ? active->objectName() : QString();
68}
69
71{
72 if (_inProgress) {
73 qCCritical(QGCStateMachineLog) << objectName()
74 << "start() called but already in progress - check signal connections";
75 return;
76 }
77 if ((childMode() == QState::ExclusiveStates) && !initialState()) {
78 qCCritical(QGCStateMachineLog) << objectName() << "start() called without an initial state";
79 return;
80 }
81 _inProgress = true;
82 QStateMachine::start();
83 // Emitted after Qt's start so a stop() from a listener is honored
84 emit inProgressChanged();
85}
86
87void QGCStateMachine::_setInProgress(bool inProgress)
88{
89 if (_inProgress != inProgress) {
90 _inProgress = inProgress;
91 emit inProgressChanged();
92 }
93}
94
95void QGCStateMachine::setGlobalErrorState(QAbstractState* errorState)
96{
97 _globalErrorState = errorState;
98}
99
101{
102 setGlobalRestorePolicy(QState::RestoreProperties);
103 qCDebug(QGCStateMachineLog) << objectName() << "property restore enabled";
104}
105
107{
108 return globalRestorePolicy() == QState::RestoreProperties;
109}
110
112{
113 // Only add global error transition if no local error state is set
114 if (_globalErrorState && !state->localErrorState()) {
115 state->addTransition(state, &QGCState::error, _globalErrorState);
116 }
117}
118
120{
121 // QGCAbstractState cannot have local error-state helpers, so wire to global.
122 if (_globalErrorState) {
123 state->addTransition(state, &QGCAbstractState::error, _globalErrorState);
124 }
125}
126
127FunctionState* QGCStateMachine::addFunctionState(const QString& stateName, std::function<void()> function)
128{
129 auto* state = new FunctionState(stateName, this, std::move(function));
130 registerState(state);
131 return state;
132}
133
136 int timeoutMsecs)
137{
138 auto* state = new AsyncFunctionState(stateName, this, std::move(setupFunction), timeoutMsecs);
139 registerState(state);
140 return state;
141}
142
145 int maxRetries,
146 int retryDelayMsecs,
150 int timeoutMsecs)
151{
152 ErrorRecoveryBuilder builder(this, stateName);
153 builder.withAction(std::move(action))
154 .retry(maxRetries, retryDelayMsecs)
155 .onExhausted(exhaustedBehavior);
156
157 if (fallback) {
158 builder.withFallback(std::move(fallback));
159 }
160 if (rollback) {
161 builder.withRollback(std::move(rollback));
162 }
163 if (timeoutMsecs > 0) {
164 builder.withTimeout(timeoutMsecs);
165 }
166
167 return builder.build();
168}
169
171{
172 auto* state = new DelayState(this, delayMsecs);
173 registerState(state);
174 return state;
175}
176
178{
179 auto* state = new ParallelState(stateName, this);
180 registerState(state);
181 return state;
182}
183
184void QGCStateMachine::postEvent(const QString& eventName, const QVariant& data, EventPriority priority)
185{
186 qCDebug(QGCStateMachineLog) << objectName() << "posting event:" << eventName
187 << (priority == HighPriority ? "(high priority)" : "");
188 emit machineEvent(eventName);
189 QStateMachine::postEvent(new QGCStateMachineEvent(eventName, data), priority);
190}
191
192int QGCStateMachine::postDelayedEvent(const QString& eventName, int delayMsecs, const QVariant& data)
193{
194 qCDebug(QGCStateMachineLog) << objectName() << "posting delayed event:" << eventName << "delay:" << delayMsecs << "ms";
195 return QStateMachine::postDelayedEvent(new QGCStateMachineEvent(eventName, data), delayMsecs);
196}
197
199{
200 qCDebug(QGCStateMachineLog) << objectName() << "cancelling delayed event id:" << eventId;
201 return QStateMachine::cancelDelayedEvent(eventId);
202}
203
204// -----------------------------------------------------------------------------
205// State Configuration
206// -----------------------------------------------------------------------------
207
208void QGCStateMachine::setInitialState(QAbstractState* state, bool autoStart)
209{
210 QStateMachine::setInitialState(state);
211 if (autoStart) {
212 start();
213 }
214}
215
217{
218 auto* state = new QGCFinalState(stateName.isEmpty() ? QStringLiteral("Final") : stateName, this);
219 return state;
220}
221
225{
226 auto* state = new ConditionalState(stateName, this, std::move(predicate), std::move(action));
227 registerState(state);
228 return state;
229}
230
232{
233 auto* state = new SubMachineState(stateName, this, std::move(factory));
234 registerState(state);
235 return state;
236}
237
239 const QString& eventName,
240 int timeoutMsecs)
241{
242 auto* state = new EventQueuedState(stateName, this, eventName, timeoutMsecs);
243 registerState(state);
244 return state;
245}
246
247QState* QGCStateMachine::createTimedActionState(const QString& stateName,
248 int durationMsecs,
249 std::function<void()> onEntry,
250 std::function<void()> onExit)
251{
252 // Create the composite parent state
253 auto* parentState = new QState(this);
254 parentState->setObjectName(stateName);
255
256 // Create a timer owned by the parent state (auto-cleanup)
257 auto* timer = new QTimer(parentState);
258 timer->setInterval(durationMsecs);
259 timer->setSingleShot(true);
260
261 // Create internal timing state (active while timer runs)
262 auto* timingState = new QState(parentState);
263 timingState->setObjectName(stateName + QStringLiteral("_Timing"));
264
265 // Create internal final state (signals completion)
266 auto* doneState = new QFinalState(parentState);
267
268 // Wire up the timing state
269 if (onEntry) {
270 connect(timingState, &QState::entered, this, onEntry);
271 }
272 connect(timingState, &QState::entered, timer, qOverload<>(&QTimer::start));
273
274 if (onExit) {
275 connect(timingState, &QState::exited, this, onExit);
276 }
277
278 // Timer timeout transitions to done state
279 timingState->addTransition(timer, &QTimer::timeout, doneState);
280
281 // Set initial state
282 parentState->setInitialState(timingState);
283
284 qCDebug(QGCStateMachineLog) << "Created timed action state:" << stateName
285 << "duration:" << durationMsecs << "ms";
286
287 return parentState;
288}
289
290// -----------------------------------------------------------------------------
291// State Queries
292// -----------------------------------------------------------------------------
293
294bool QGCStateMachine::isStateActive(QAbstractState* state) const
295{
296 return configuration().contains(state);
297}
298
299QAbstractState* QGCStateMachine::findState(const QString& stateName) const
300{
301 // Use findChild with name parameter - more efficient than findChildren + loop
302 return findChild<QAbstractState*>(stateName);
303}
304
305// -----------------------------------------------------------------------------
306// Error Handling
307// -----------------------------------------------------------------------------
308
310{
311 if (_globalErrorState) {
312 return configuration().contains(_globalErrorState);
313 }
314 return false;
315}
316
318 QAbstractState* nextState,
319 const QString& message)
320{
321 auto* state = ErrorHandlers::logAndContinue(this, stateName, nextState, message);
322 registerState(state);
323 return state;
324}
325
327 const QString& message)
328{
329 auto* state = ErrorHandlers::logAndStop(this, stateName, message);
330 registerState(state);
331 return state;
332}
333
335{
336 if (restart) {
337 stop();
338 start();
339 }
340}
341
342bool QGCStateMachine::resetToState(QAbstractState* state)
343{
344 if (!state) {
345 qCCritical(QGCStateMachineLog) << objectName() << "resetToState: null state";
346 return false;
347 }
348
349 // Verify the state belongs to this machine
350 if (state->parentState() != this && state->parent() != this) {
351 qCCritical(QGCStateMachineLog) << objectName() << "resetToState: state does not belong to this machine";
352 return false;
353 }
354
355 qCDebug(QGCStateMachineLog) << objectName() << "resetting to state:" << state->objectName();
356
357 // Stop the machine, change initial state, and restart
358 if (inProgress()) {
359 auto conn = std::make_shared<QMetaObject::Connection>();
360 *conn = connect(this, &QStateMachine::stopped, this, [this, state, conn]() {
361 disconnect(*conn);
362 setInitialState(state);
364 start();
365 });
366 stop();
367 } else {
368 setInitialState(state);
370 start();
371 }
372
373 return true;
374}
375
377{
378 if (!isInErrorState()) {
379 qCDebug(QGCStateMachineLog) << objectName() << "recoverFromError: not in error state";
380 return false;
381 }
382
383 qCDebug(QGCStateMachineLog) << objectName() << "recovering from error, restarting";
384 clearError(true);
385 return true;
386}
387
389{
390 if (!_recoveryState) {
391 qCDebug(QGCStateMachineLog) << objectName() << "attemptRecovery: no recovery state set";
392 return false;
393 }
394
395 qCDebug(QGCStateMachineLog) << objectName() << "attempting recovery to:" << _recoveryState->objectName();
396 return resetToState(_recoveryState);
397}
398
399// -----------------------------------------------------------------------------
400// Lifecycle Helpers
401// -----------------------------------------------------------------------------
402
404{
405 if (!inProgress()) {
406 start();
407 }
408}
409
410void QGCStateMachine::stopMachine(bool deleteOnStop)
411{
412 _deleteOnStop = deleteOnStop;
413 stop();
414}
415
417{
418 if (inProgress()) {
419 // stop() is asynchronous, so connect to stopped signal to start again
420 auto conn = std::make_shared<QMetaObject::Connection>();
421 *conn = connect(this, &QStateMachine::stopped, this, [this, conn]() {
422 disconnect(*conn);
423 start();
424 });
425 stop();
426 } else {
427 start();
428 }
429}
430
431// -----------------------------------------------------------------------------
432// Transition Helpers
433// -----------------------------------------------------------------------------
434
435MachineEventTransition* QGCStateMachine::addEventTransition(QState* from, const QString& eventName, QAbstractState* to,
436 QAbstractAnimation* animation)
437{
438 auto* transition = new MachineEventTransition(eventName, to);
439 if (animation) {
440 transition->addAnimation(animation);
441 }
442 from->addTransition(transition);
443 return transition;
444}
445
446TimeoutTransition* QGCStateMachine::addTimeoutTransition(QState* from, int timeoutMsecs, QAbstractState* to,
447 QAbstractAnimation* animation)
448{
449 auto* transition = new TimeoutTransition(timeoutMsecs, to);
450 transition->attachToSourceState(from);
451 if (animation) {
452 transition->addAnimation(animation);
453 }
454 from->addTransition(transition);
455 return transition;
456}
457
458// -----------------------------------------------------------------------------
459// State Introspection
460// -----------------------------------------------------------------------------
461
462QList<QAbstractTransition*> QGCStateMachine::transitionsFrom(QAbstractState* state) const
463{
464 QList<QAbstractTransition*> result;
465 if (auto* qstate = qobject_cast<QState*>(state)) {
466 result = qstate->transitions();
467 }
468 return result;
469}
470
471QList<QAbstractTransition*> QGCStateMachine::transitionsTo(QAbstractState* state) const
472{
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);
479 }
480 }
481 return result;
482}
483
484QList<QAbstractState*> QGCStateMachine::reachableFrom(QAbstractState* state) const
485{
486 QList<QAbstractState*> result;
487 for (QAbstractTransition* transition : transitionsFrom(state)) {
488 for (QAbstractState* target : transition->targetStates()) {
489 if (!result.contains(target)) {
490 result.append(target);
491 }
492 }
493 }
494 return result;
495}
496
497QList<QAbstractState*> QGCStateMachine::predecessorsOf(QAbstractState* state) const
498{
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);
504 }
505 }
506 }
507 return result;
508}
509
510// -----------------------------------------------------------------------------
511// Debugging & Visualization
512// -----------------------------------------------------------------------------
513
515{
516 QString result = objectName() + QStringLiteral(": ");
517
518 if (!inProgress()) {
519 result += QStringLiteral("(not running)");
520 return result;
521 }
522
523 const auto active = configuration();
524 if (active.isEmpty()) {
525 result += QStringLiteral("(no active state)");
526 } else {
527 QStringList stateNames;
528 for (QAbstractState* state : active) {
529 stateNames.append(state->objectName().isEmpty()
530 ? QStringLiteral("<unnamed>")
531 : state->objectName());
532 }
533 result += stateNames.join(QStringLiteral(", "));
534 result += QStringLiteral(" (running)");
535 }
536
537 return result;
538}
539
541{
542 QString result;
543 result += QStringLiteral("State Machine: %1\n").arg(objectName());
544 result += QStringLiteral("================\n");
545
546 // Get all states
547 const auto allStates = findChildren<QAbstractState*>();
548 result += QStringLiteral("States (%1):\n").arg(allStates.size());
549
550 for (QAbstractState* state : allStates) {
551 QString stateName = state->objectName().isEmpty()
552 ? QStringLiteral("<unnamed>")
553 : state->objectName();
554
555 // Mark special states
556 QString marker;
557 if (state == initialState()) {
558 marker = QStringLiteral(" [initial]");
559 }
560 if (qobject_cast<QFinalState*>(state)) {
561 marker += QStringLiteral(" [final]");
562 }
563 if (state == _globalErrorState) {
564 marker += QStringLiteral(" [error]");
565 }
566 if (configuration().contains(state)) {
567 marker += QStringLiteral(" [active]");
568 }
569
570 result += QStringLiteral(" - %1%2\n").arg(stateName, marker);
571
572 // Show transitions from this state
573 auto transitions = transitionsFrom(state);
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);
581 }
582 }
583 }
584
585 return result;
586}
587
589{
590 qCDebug(QGCStateMachineLog) << dumpCurrentState();
591}
592
594{
595 const auto lines = dumpConfiguration().split('\n');
596 for (const QString& line : lines) {
597 if (!line.isEmpty()) {
598 qCDebug(QGCStateMachineLog) << line;
599 }
600 }
601}
602
603void QGCStateMachine::setHistoryRecordingEnabled(bool enabled, int maxEntries)
604{
605 if (!_historyRecorder) {
606 _historyRecorder = new StateHistoryRecorder(this, maxEntries);
607 }
608 _historyRecorder->setMaxEntries(maxEntries);
609 _historyRecorder->setEnabled(enabled);
610}
611
613{
614 return _historyRecorder && _historyRecorder->isEnabled();
615}
616
618{
619 return _historyRecorder ? _historyRecorder->dumpHistory() : QString();
620}
621
623{
624 return _historyRecorder ? _historyRecorder->toJson() : QJsonArray();
625}
626
628{
629 if (!_profiler) {
630 _profiler = new StateMachineProfiler(this);
631 }
632 _profiler->setEnabled(enabled);
633}
634
636{
637 return _profiler && _profiler->isEnabled();
638}
639
641{
642 return _profiler ? _profiler->summary() : QString();
643}
644
646{
647 if (!_logger) {
648 _logger = new StateMachineLogger(this, this);
649 }
650 _logger->setEnabled(enabled);
651}
652
654{
655 return _logger && _logger->isEnabled();
656}
657
659{
660 QString dot;
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");
665
666 const auto allStates = findChildren<QAbstractState*>();
667
668 // Define nodes with special styling
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();
673
674 QStringList attrs;
675 if (state == initialState()) {
676 attrs << QStringLiteral("style=\"rounded,bold\"");
677 attrs << QStringLiteral("peripheries=2");
678 }
679 if (qobject_cast<QFinalState*>(state)) {
680 attrs << QStringLiteral("shape=doublecircle");
681 }
682 if (state == _globalErrorState) {
683 attrs << QStringLiteral("color=red");
684 }
685
686 if (attrs.isEmpty()) {
687 dot += QStringLiteral(" \"%1\";\n").arg(name);
688 } else {
689 dot += QStringLiteral(" \"%1\" [%2];\n").arg(name, attrs.join(", "));
690 }
691 }
692
693 dot += QStringLiteral("\n");
694
695 // Define edges
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();
700
701 auto transitions = transitionsFrom(state);
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();
708
709 // Try to get transition label from object name
710 QString label = transition->objectName();
711 if (label.isEmpty()) {
712 dot += QStringLiteral(" \"%1\" -> \"%2\";\n").arg(fromName, toName);
713 } else {
714 dot += QStringLiteral(" \"%1\" -> \"%2\" [label=\"%3\"];\n").arg(fromName, toName, label);
715 }
716 }
717 }
718 }
719
720 dot += QStringLiteral("}\n");
721 return dot;
722}
723
724QList<QAbstractState*> QGCStateMachine::unreachableStates() const
725{
726 QList<QAbstractState*> unreachable;
727
728 if (!initialState()) {
729 return unreachable;
730 }
731
732 // BFS from initial state
733 QSet<QAbstractState*> visited;
734 QList<QAbstractState*> queue;
735 queue.append(initialState());
736 visited.insert(initialState());
737
738 while (!queue.isEmpty()) {
739 QAbstractState* current = queue.takeFirst();
740 auto reachable = reachableFrom(current);
741 for (QAbstractState* next : reachable) {
742 if (!visited.contains(next)) {
743 visited.insert(next);
744 queue.append(next);
745 }
746 }
747 }
748
749 // Find states not visited
750 const auto allStates = findChildren<QAbstractState*>();
751 for (QAbstractState* state : allStates) {
752 if (!visited.contains(state)) {
753 unreachable.append(state);
754 }
755 }
756
757 return unreachable;
758}
759
761{
762 if (!initialState()) {
763 return -1;
764 }
765
766 // BFS with depth tracking
767 QHash<QAbstractState*, int> depth;
768 QList<QAbstractState*> queue;
769
770 queue.append(initialState());
771 depth[initialState()] = 0;
772 int maxDepth = 0;
773
774 const int stateCount = findChildren<QAbstractState*>().size();
775 const int maxSearchDepth = qMax(stateCount * 2, 100);
776
777 while (!queue.isEmpty()) {
778 QAbstractState* current = queue.takeFirst();
779 int currentDepth = depth[current];
780
781 if (currentDepth >= maxSearchDepth) {
782 continue;
783 }
784
785 auto reachable = reachableFrom(current);
786 for (QAbstractState* next : reachable) {
787 int newDepth = currentDepth + 1;
788 // Only update if we found a longer path
789 if (!depth.contains(next) || depth[next] < newDepth) {
790 depth[next] = newDepth;
791 maxDepth = qMax(maxDepth, newDepth);
792 queue.append(next);
793 }
794 }
795 }
796
797 return maxDepth;
798}
799
800QList<QAbstractState*> QGCStateMachine::deadEndStates() const
801{
802 QList<QAbstractState*> deadEnds;
803
804 const auto allStates = findChildren<QAbstractState*>();
805 for (QAbstractState* state : allStates) {
806 // Skip final states - they're supposed to be dead ends
807 if (qobject_cast<QFinalState*>(state)) {
808 continue;
809 }
810
811 // Check if state has any outgoing transitions
812 auto transitions = transitionsFrom(state);
813 if (transitions.isEmpty()) {
814 deadEnds.append(state);
815 }
816 }
817
818 return deadEnds;
819}
820
821// -----------------------------------------------------------------------------
822// Progress Tracking
823// -----------------------------------------------------------------------------
824
825void QGCStateMachine::setProgressWeights(const QList<QPair<QAbstractState*, int>>& stateWeights)
826{
827 // Disconnect old connections before re-wiring
828 for (auto* state : _progressStates) {
829 disconnect(state, &QAbstractState::entered, this, &QGCStateMachine::_onStateEntered);
830 }
831
832 _progressStates.clear();
833 _progressWeights.clear();
834 _progressTotalWeight = 0;
835
836 for (const auto& pair : stateWeights) {
837 _progressStates.append(pair.first);
838 _progressWeights.append(pair.second);
839 _progressTotalWeight += pair.second;
840
841 // Connect to state's entered signal to auto-update progress index
842 connect(pair.first, &QAbstractState::entered, this, &QGCStateMachine::_onStateEntered);
843 }
844
845 qCDebug(QGCStateMachineLog) << objectName() << "progress tracking enabled for"
846 << _progressStates.size() << "states, total weight:" << _progressTotalWeight;
847}
848
849void QGCStateMachine::_onStateEntered()
850{
851 auto* state = qobject_cast<QAbstractState*>(sender());
852 if (!state) return;
853
854 // Update QML state history
855 QString stateName = state->objectName();
856 if (!stateName.isEmpty()) {
857 _stateHistory.append(stateName);
858 while (_stateHistory.size() > _stateHistoryLimit) {
859 _stateHistory.removeFirst();
860 }
861 emit stateHistoryChanged();
863 }
864
865 // Update progress tracking
866 int index = _progressStates.indexOf(state);
867 if (index >= 0 && index != _progressCurrentIndex) {
868 _progressCurrentIndex = index;
869 _progressSubProgress = 0.0f;
870
871 float newProgress = _calculateProgress();
872 if (newProgress > _progressLastEmitted) {
873 _progressLastEmitted = newProgress;
874 emit progressUpdate(newProgress);
875 }
876 }
877}
878
879void QGCStateMachine::setSubProgress(float subProgress)
880{
881 _progressSubProgress = qBound(0.0f, subProgress, 1.0f);
882
883 float newProgress = _calculateProgress();
884 if (newProgress > _progressLastEmitted) {
885 _progressLastEmitted = newProgress;
886 emit progressUpdate(newProgress);
887 }
888}
889
891{
892 return _progressLastEmitted;
893}
894
896{
897 _progressCurrentIndex = -1;
898 _progressSubProgress = 0.0f;
899 _progressLastEmitted = 0.0f;
900}
901
902float QGCStateMachine::_calculateProgress() const
903{
904 if (_progressTotalWeight <= 0 || _progressCurrentIndex < 0) {
905 return 0.0f;
906 }
907
908 int completedWeight = 0;
909 for (int i = 0; i < _progressCurrentIndex && i < _progressWeights.size(); ++i) {
910 completedWeight += _progressWeights[i];
911 }
912
913 int currentWeight = (_progressCurrentIndex < _progressWeights.size())
914 ? _progressWeights[_progressCurrentIndex]
915 : 1;
916
917 return (completedWeight + currentWeight * _progressSubProgress) / static_cast<float>(_progressTotalWeight);
918}
919
920// -----------------------------------------------------------------------------
921// Timeout Configuration
922// -----------------------------------------------------------------------------
923
924void QGCStateMachine::setTimeoutOverride(const QString& stateName, int timeoutMsecs)
925{
926 _timeoutOverrides[stateName] = timeoutMsecs;
927 qCDebug(QGCStateMachineLog) << objectName() << "timeout override set for" << stateName << ":" << timeoutMsecs << "ms";
928}
929
930void QGCStateMachine::removeTimeoutOverride(const QString& stateName)
931{
932 _timeoutOverrides.remove(stateName);
933}
934
935int QGCStateMachine::timeoutOverride(const QString& stateName) const
936{
937 return _timeoutOverrides.value(stateName, -1);
938}
939
940void QGCStateMachine::recordTimeout(const QString& stateName)
941{
942 _timeoutStats[stateName]++;
943 qCDebug(QGCStateMachineLog) << objectName() << "timeout recorded for" << stateName
944 << "total:" << _timeoutStats[stateName];
945}
946
947// -----------------------------------------------------------------------------
948// Entry/Exit Callbacks
949// -----------------------------------------------------------------------------
950
952{
953 _entryCallback = std::move(onEntry);
954 _exitCallback = std::move(onExit);
955}
956
957// -----------------------------------------------------------------------------
958// QStateMachine Overrides
959// -----------------------------------------------------------------------------
960
962{
963 QStateMachine::onEntry(event);
964
965 if (_entryCallback) {
966 _entryCallback();
967 }
968
969 onEnter();
970}
971
973{
974 onLeave();
975
976 if (_exitCallback) {
977 _exitCallback();
978 }
979
980 QStateMachine::onExit(event);
981}
982
984{
985 // Only allow handler to intercept custom events, not internal state machine events
986 if (_eventHandler && event->type() >= QEvent::User) {
987 if (_eventHandler(event)) {
988 return true;
989 }
990 }
991
992 return QStateMachine::event(event);
993}
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
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).
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.
bool inProgress() const
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.
Definition QGCState.h:23
QAbstractState * localErrorState() const
Get the per-state error state (nullptr if using global).
Definition QGCState.h:43
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)