Repository navigation
Expand file tree
/
Copy pathSmartSessionController.cpp
More file actions
1419 lines (1284 loc) · 57.3 KB
/
Copy pathSmartSessionController.cpp
File metadata and controls
1419 lines (1284 loc) · 57.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-3.0-or-later
#include "SmartSessionController.hpp"
#include "DeviceController.hpp"
#include "FirmwareManager.hpp"
#include "SclProfileModel.hpp"
#include <QVariantMap>
#include <QStringList>
#include <algorithm>
#include <limits>
#include <utility>
#ifndef ARSTACK_STUDIO_VERSION
#define ARSTACK_STUDIO_VERSION "0.1.0"
#endif
namespace {
constexpr int kMaxUpdateReconnectAttempts = 6;
}
QString SmartSessionController::chooseRecoveryPort(
const QString& recommendedPort,
const QStringList& visiblePorts) {
const QString recommended = recommendedPort.trimmed();
if (!recommended.isEmpty() && visiblePorts.contains(recommended, Qt::CaseInsensitive)) {
return recommended;
}
if (visiblePorts.size() != 1) return {};
return visiblePorts.front().trimmed();
}
quint64 SmartSessionController::nextSessionGeneration(const quint64 current) noexcept {
if (current == std::numeric_limits<quint64>::max()) return 1;
return current + 1;
}
bool SmartSessionController::profileGenerationAdvanced(
const QString& baseline,
const QString& observed) noexcept {
bool observedOk = false;
const qulonglong observedGeneration = observed.trimmed().toULongLong(&observedOk);
if (!observedOk) return false;
bool baselineOk = false;
const qulonglong baselineGeneration = baseline.trimmed().toULongLong(&baselineOk);
if (!baselineOk) return true;
// Within one verified boot epoch, a committed profile generation must
// strictly advance. Rollback is stale evidence, not a successful sync.
return observedGeneration > baselineGeneration;
}
SmartSessionController::SmartSessionController(QObject* parent) : QObject(parent) {
discoveryTimer_.setInterval(2500);
discoveryTimer_.setSingleShot(false);
connect(&discoveryTimer_, &QTimer::timeout, this, [this] {
if (!started_ || device_ == nullptr || updateRequested_ || blankBoardDetected_ || setupError_) return;
if (firmware_ != nullptr && firmware_->busy()) return;
// A slow serial reply is NOT evidence that firmware is absent.
// Retry semantic discovery after a bounded 5s cool-down; do not
// endlessly hold the single COM port or auto-flash a live board.
if (device_->identificationState() == DeviceController::IdentificationState::Unidentified) {
if (manualRecoveryArmed_) return;
++unidentifiedDiscoveryTicks_;
if (unidentifiedDiscoveryTicks_ < 2) return;
}
if (!device_->deviceVerified() && !device_->discovering() && !device_->connected()) {
unidentifiedDiscoveryTicks_ = 0;
static_cast<void>(startDeviceDiscovery());
}
});
prepareTimer_.setInterval(650);
prepareTimer_.setSingleShot(true);
connect(&prepareTimer_, &QTimer::timeout, this, &SmartSessionController::reconcile);
profileSyncTimer_.setInterval(profileSyncTimeoutMs());
profileSyncTimer_.setSingleShot(true);
connect(&profileSyncTimer_, &QTimer::timeout, this, [this] {
if (profileSyncStage_ != ProfileSyncStage::deploying) return;
const QString progress = device_ == nullptr ? QStringLiteral("device unavailable")
: device_->profileDeploymentProgressSummary();
handleProfileSyncAttemptFailure(QStringLiteral(
"Firmware profile acknowledgement timed out (%1).").arg(progress));
reconcile();
});
// Retry timer never grants START; it only re-enters the verified
// profile handshake with bounded exponential-like backoff.
profileRetryTimer_.setSingleShot(true);
connect(&profileRetryTimer_, &QTimer::timeout, this, &SmartSessionController::reconcile);
// ACK progress alone must never keep PREPARING forever.
profileSyncTotalTimer_.setInterval(profileSyncHardDeadlineMs());
profileSyncTotalTimer_.setSingleShot(true);
connect(&profileSyncTotalTimer_, &QTimer::timeout, this, [this] {
if (profileSyncStage_ != ProfileSyncStage::deploying) return;
handleProfileSyncAttemptFailure(QStringLiteral(
"Profile preparation exceeded the absolute %1 ms safety deadline (%2).")
.arg(profileSyncHardDeadlineMs())
.arg(device_ == nullptr ? QStringLiteral("device missing")
: device_->profileDeploymentProgressSummary()));
reconcile();
});
reconnectTimer_.setInterval(3000);
reconnectTimer_.setSingleShot(true);
connect(&reconnectTimer_, &QTimer::timeout, this, [this] {
if (device_ == nullptr || !updateRequested_ || updateStage_ != UpdateStage::reconnecting) return;
if (device_->deviceVerified()) {
reconcile();
return;
}
if (device_->discovering() || device_->connected()) {
reconnectTimer_.start();
return;
}
if (updateReconnectAttempts_ >= kMaxUpdateReconnectAttempts) {
latchFirmwareFailure(QStringLiteral(
"Firmware was written, but Studio could not reconnect and verify the ESP32-P4. Reconnect USB and retry firmware setup."));
emit firmwareUpdateFinished(false);
reconcile();
return;
}
++updateReconnectAttempts_;
static_cast<void>(startDeviceDiscovery());
reconnectTimer_.start();
reconcile();
});
}
SmartSessionController::~SmartSessionController() {
shutdown();
}
void SmartSessionController::shutdown() {
if (shuttingDown_) return;
shuttingDown_ = true;
started_ = false;
discoveryTimer_.stop();
prepareTimer_.stop();
reconnectTimer_.stop();
profileSyncTimer_.stop();
profileRetryTimer_.stop();
profileSyncTotalTimer_.stop();
firmwareHandoffWatchdog_.shutdown();
deviceRecoveryMonitor_.shutdown();
updateRequested_ = false;
pendingReleaseGeneration_ = 0;
profileSyncStage_ = ProfileSyncStage::idle;
if (device_ != nullptr) QObject::disconnect(device_, nullptr, this, nullptr);
if (profiles_ != nullptr) QObject::disconnect(profiles_, nullptr, this, nullptr);
if (firmware_ != nullptr) QObject::disconnect(firmware_, nullptr, this, nullptr);
device_ = nullptr;
profiles_ = nullptr;
firmware_ = nullptr;
}
QObject* SmartSessionController::device() const noexcept { return device_; }
QObject* SmartSessionController::profiles() const noexcept { return profiles_; }
QObject* SmartSessionController::firmware() const noexcept { return firmware_; }
QString SmartSessionController::state() const { return state_; }
QString SmartSessionController::statusText() const { return statusText_; }
bool SmartSessionController::startReady() const noexcept { return startReady_; }
bool SmartSessionController::canDeployProfile() const noexcept {
if (!deviceControlAvailable() || profiles_ == nullptr || device_->running() || device_->profileDeploying()) {
return false;
}
const QVariantMap profile = profiles_->selectedProfile();
return profile.value(QStringLiteral("compatibilityClass")).toString() == QStringLiteral("A") &&
profile.value(QStringLiteral("deviceSupport")).toString() == QStringLiteral("ready");
}
bool SmartSessionController::liveControlReady() const noexcept {
return deviceControlAvailable() && !device_->profileDeploying() &&
(startReady_ || device_->running());
}
bool SmartSessionController::engineeringEditable() const noexcept {
return device_ != nullptr && !device_->running() && !updateRequested_ &&
portOwner_ != PortOwner::firmwareTool && (firmware_ == nullptr || !firmware_->busy());
}
bool SmartSessionController::firmwareUpdateRequired() const noexcept { return firmwareUpdateRequired_; }
bool SmartSessionController::firmwareUpdateAvailable() const noexcept {
return device_ != nullptr && firmware_ != nullptr && device_->deviceVerified() &&
firmware_->bundleReady() && !firmware_->busy() && !updateRequested_ &&
firmwareIsCompatible() && !firmwareIsCurrent();
}
bool SmartSessionController::firmwareUpdateCanCancel() const noexcept {
return updateRequested_ && updateWasOptional_ && updateStage_ == UpdateStage::waitingForBootloader &&
firmware_ != nullptr && !firmware_->busy();
}
bool SmartSessionController::firmwareReinstallAvailable() const noexcept {
return device_ != nullptr && firmware_ != nullptr && device_->deviceVerified() &&
firmware_->bundleReady() && !firmware_->busy() && !updateRequested_ && firmwareIsCurrent();
}
bool SmartSessionController::firmwareInstallRequired() const noexcept {
return blankBoardDetected_ && !updateRequested_;
}
bool SmartSessionController::firmwareRetryAvailable() const noexcept {
return setupError_ && !updatePort_.trimmed().isEmpty() && firmware_ != nullptr && !firmware_->busy();
}
bool SmartSessionController::profileSyncRetryAvailable() const noexcept {
return profileSyncStage_ == ProfileSyncStage::failed && device_ != nullptr &&
device_->deviceVerified() && !device_->running() && portOwner_ == PortOwner::deviceSession;
}
bool SmartSessionController::updatingFirmware() const noexcept {
return updateStage_ == UpdateStage::stopping || updateStage_ == UpdateStage::releasingPort ||
updateStage_ == UpdateStage::probing || updateStage_ == UpdateStage::flashing ||
updateStage_ == UpdateStage::reconnecting;
}
bool SmartSessionController::updateNeedsBootloaderHelp() const noexcept {
return updateStage_ == UpdateStage::waitingForBootloader;
}
int SmartSessionController::firmwareProgress() const noexcept {
if (firmware_ == nullptr || updateStage_ != UpdateStage::flashing) return -1;
return firmware_->flashProgress();
}
QString SmartSessionController::updateStatus() const {
if (firmware_ == nullptr) return {};
switch (updateStage_) {
case UpdateStage::stopping:
return QStringLiteral("Stopping SMV output safely…");
case UpdateStage::releasingPort:
return QStringLiteral("Releasing the device serial session before firmware access…");
case UpdateStage::probing:
case UpdateStage::flashing:
return firmware_->status();
case UpdateStage::reconnecting:
return QStringLiteral("Firmware written. Reconnecting and verifying the board… %1/%2")
.arg(std::min(updateReconnectAttempts_ + 1, kMaxUpdateReconnectAttempts))
.arg(kMaxUpdateReconnectAttempts);
case UpdateStage::waitingForBootloader:
return QStringLiteral("Put the board in Download mode: hold BOOT, press and release RESET, then release BOOT.");
case UpdateStage::idle:
return {};
}
return {};
}
QString SmartSessionController::firmwareSetupPort() const { return blankBoardPort_; }
QString SmartSessionController::expectedFirmwareVersion() const { return QStringLiteral(ARSTACK_STUDIO_VERSION); }
QString SmartSessionController::expectedFirmwareBuildId() const {
return firmware_ != nullptr ? firmware_->firmwareBuildId() : QString{};
}
QString SmartSessionController::deviceFirmwareVersion() const { return deviceFirmwareVersion_; }
QString SmartSessionController::deviceFirmwareBuildId() const { return deviceFirmwareBuildId_; }
quint64 SmartSessionController::advanceSessionGeneration() {
sessionGeneration_ = nextSessionGeneration(sessionGeneration_);
if (device_ != nullptr) device_->setSessionGeneration(sessionGeneration_);
if (firmware_ != nullptr) firmware_->setSessionGeneration(sessionGeneration_);
emit stateChanged();
return sessionGeneration_;
}
void SmartSessionController::setPortOwner(const PortOwner owner) {
if (portOwner_ == owner) return;
portOwner_ = owner;
emit stateChanged();
}
bool SmartSessionController::startDeviceDiscovery() {
if (device_ == nullptr || portOwner_ == PortOwner::firmwareTool ||
device_->connected() || device_->discovering()) {
return false;
}
manualRecoveryArmed_ = false;
advanceSessionGeneration();
setPortOwner(PortOwner::deviceSession);
return device_->autoDetectAndConnect();
}
void SmartSessionController::setDevice(QObject* object) {
auto* next = qobject_cast<DeviceController*>(object);
if (device_ == next) return;
if (device_ != nullptr) disconnect(device_, nullptr, this, nullptr);
device_ = next;
deviceFirmwareVersion_.clear();
profileSyncBootId_.clear();
resetProfileSync(true);
clearBlankBoardContext();
if (device_ != nullptr) {
advanceSessionGeneration();
}
reconnectDeviceSignals();
emit dependenciesChanged();
reconcile();
}
void SmartSessionController::setProfiles(QObject* object) {
auto* next = qobject_cast<SclProfileModel*>(object);
if (profiles_ == next) return;
if (profiles_ != nullptr) disconnect(profiles_, nullptr, this, nullptr);
profiles_ = next;
resetProfileSync(true);
reconnectProfileSignals();
emit dependenciesChanged();
reconcile();
}
void SmartSessionController::setFirmware(QObject* object) {
auto* next = qobject_cast<FirmwareManager*>(object);
if (firmware_ == next) return;
if (firmware_ != nullptr) disconnect(firmware_, nullptr, this, nullptr);
firmware_ = next;
if (firmware_ != nullptr) {
if (sessionGeneration_ == 0) advanceSessionGeneration();
else firmware_->setSessionGeneration(sessionGeneration_);
}
clearBlankBoardContext();
reconnectFirmwareSignals();
emit dependenciesChanged();
reconcile();
}
void SmartSessionController::start() {
if (started_ || shuttingDown_) return;
started_ = true;
if (profiles_ != nullptr) static_cast<void>(ensureDefaultProfile());
discoveryTimer_.start();
QTimer::singleShot(0, this, [this] {
if (!started_ || device_ == nullptr || updateRequested_) return;
if (!device_->deviceVerified() && !device_->discovering() && !device_->connected()) {
static_cast<void>(startDeviceDiscovery());
}
refreshRecoveryOfferFromIdentity();
reconcile();
});
}
bool SmartSessionController::requestStart() {
// Legacy callers must not bypass the fresh scenario snapshot supplied by the UI.
// requestStartWithScenario remains the only guided START entry point.
return false;
}
bool SmartSessionController::requestStartWithScenario(const QVariantMap& scenario) {
if (!startReady_ || !deviceControlAvailable() || device_ == nullptr || device_->running()) return false;
return device_->startWithScenario(scenario);
}
bool SmartSessionController::requestStop() {
if (device_ == nullptr) return false;
// STOP is a cancellation authority even before SV RUNNING telemetry: an
// ACKed staging transaction may still be advancing toward START.
if (!device_->running() && !device_->scenarioApplying()) return true;
if (portOwner_ != PortOwner::deviceSession || updateRequested_) return false;
return device_->stop();
}
bool SmartSessionController::requestConnect() {
if (!started_ || device_ == nullptr || updateRequested_ ||
portOwner_ == PortOwner::firmwareTool || device_->discovering()) {
return false;
}
if (device_->deviceVerified()) return true;
if (device_->connected()) return false;
if (firmware_ != nullptr && firmware_->busy()) return false;
clearBlankBoardContext();
const bool accepted = startDeviceDiscovery();
reconcile();
return accepted;
}
void SmartSessionController::requestRefreshPorts() {
if (device_ == nullptr || updateRequested_ || portOwner_ == PortOwner::firmwareTool ||
(firmware_ != nullptr && firmware_->busy())) {
return;
}
device_->refreshPorts();
}
bool SmartSessionController::requestConnectPort(const QString& portName) {
const QString requested = portName.trimmed();
if (!started_ || device_ == nullptr || requested.isEmpty() || updateRequested_ ||
portOwner_ == PortOwner::firmwareTool || device_->connected() || device_->discovering() ||
(firmware_ != nullptr && firmware_->busy())) {
return false;
}
clearBlankBoardContext();
manualRecoveryArmed_ = true;
advanceSessionGeneration();
setPortOwner(PortOwner::deviceSession);
const bool accepted = device_->connectPort(requested);
reconcile();
return accepted;
}
bool SmartSessionController::requestDisconnect() {
if (device_ == nullptr || updateRequested_ || portOwner_ != PortOwner::deviceSession) return false;
if (!device_->connected()) return true;
if (device_->running()) return false;
device_->disconnectPort();
return true;
}
bool SmartSessionController::requestProfileSync() {
if (!canDeployProfile()) return false;
resetProfileSync(true);
QTimer::singleShot(0, this, &SmartSessionController::reconcile);
return true;
}
bool SmartSessionController::requestSetFrequency(const double hz) {
return liveControlReady() && device_ != nullptr && device_->setFrequency(hz);
}
bool SmartSessionController::requestSetSignal(
const QString& signalId,
const double magnitude,
const double phaseDegrees,
const quint32 quality,
const double currentCountsPerAmp,
const double voltageCountsPerVolt) {
return liveControlReady() && device_ != nullptr &&
device_->setSignal(
signalId,
magnitude,
phaseDegrees,
quality,
currentCountsPerAmp,
voltageCountsPerVolt);
}
bool SmartSessionController::requestSetQuality(const QString& signalId, const quint32 quality) {
return liveControlReady() && device_ != nullptr && device_->setQuality(signalId, quality);
}
bool SmartSessionController::requestSetCtSaturation(
const bool enabled,
const double dcOffsetPercent,
const double harmonicPercent,
const int harmonicOrder,
const double clipPercent) {
return liveControlReady() && device_ != nullptr &&
device_->setCtSaturation(
enabled,
dcOffsetPercent,
harmonicPercent,
harmonicOrder,
clipPercent);
}
bool SmartSessionController::requestZero() {
return liveControlReady() && device_ != nullptr && device_->zero();
}
bool SmartSessionController::requestPtpRefresh() {
// A guided START owns its ACK/readback order; do not interleave SHOWs.
if (!deviceControlAvailable() || device_ == nullptr || device_->ptpStarting() ||
device_->profileDeploying() || profileSyncStage_ == ProfileSyncStage::deploying ||
device_->scenarioApplying()) return false;
const bool ptp = device_->sendPtpShow();
const bool sync = device_->sendSmpSynchShow();
return ptp && sync;
}
bool SmartSessionController::requestSyncDiagnostics() {
// Read-only operator request; serialize behind the existing device
// session. Never interleave with START/CFG or firmware port handoff.
if (!deviceControlAvailable() || device_ == nullptr ||
device_->ptpStarting() || device_->profileDeploying() ||
profileSyncStage_ == ProfileSyncStage::deploying ||
device_->scenarioApplying() || updateRequested_) return false;
return device_->sendPtpDiagnostics();
}
bool SmartSessionController::requestPtpRole(const QString& role) {
return deviceControlAvailable() && device_ != nullptr && device_->setPtpRole(role);
}
bool SmartSessionController::requestSmpSynch(const QString& mode) {
return deviceControlAvailable() && device_ != nullptr && device_->setSmpSynchPolicy(mode);
}
bool SmartSessionController::requestConfigurePtp(const QVariantMap& profile) {
return deviceControlAvailable() && device_ != nullptr && device_->configurePtp(profile);
}
bool SmartSessionController::requestStartPtp() {
return deviceControlAvailable() && device_ != nullptr && device_->startPtp();
}
bool SmartSessionController::requestStartPtpConfigured(const QString& role,
const QVariantMap& profile) {
return deviceControlAvailable() && device_ != nullptr &&
device_->startPtpConfigured(role, profile);
}
bool SmartSessionController::requestStopPtp() {
return deviceControlAvailable() && device_ != nullptr && device_->stopPtp();
}
bool SmartSessionController::beginFirmwareUpdate() {
if (device_ == nullptr || firmware_ == nullptr || !device_->deviceVerified() ||
!firmware_->bundleReady() || firmware_->busy()) {
return false;
}
updateWasOptional_ = firmwareUpdateAvailable() && !firmwareUpdateRequired_;
return beginFirmwareOperation(device_->portName());
}
bool SmartSessionController::beginFirmwareReinstall() {
if (!firmwareReinstallAvailable() || device_ == nullptr) return false;
updateWasOptional_ = true;
return beginFirmwareOperation(device_->portName());
}
bool SmartSessionController::beginFirmwareInstall() {
updateWasOptional_ = false;
refreshRecoveryOfferFromIdentity();
if (device_ == nullptr || firmware_ == nullptr || !blankBoardDetected_ ||
!firmware_->bundleReady() || firmware_->busy() || blankBoardPort_.isEmpty()) {
return false;
}
return beginFirmwareOperation(blankBoardPort_);
}
bool SmartSessionController::beginFirmwareOperation(const QString& portName) {
const QString port = portName.trimmed();
if (device_ == nullptr || firmware_ == nullptr || port.isEmpty() || firmware_->busy()) return false;
updatePort_ = port;
updateRequested_ = true;
updateReconnectAttempts_ = 0;
pendingReleaseGeneration_ = 0;
profileSyncBootId_.clear();
resetProfileSync(true);
setupError_ = false;
setupErrorStatus_.clear();
lastFirmwareUpdateResult_.clear();
if (device_->running()) {
updateStage_ = UpdateStage::stopping;
setPresentation(
QStringLiteral("UPDATING FIRMWARE"),
QStringLiteral("Stopping SMV output before firmware installation…"),
false,
false);
if (!device_->stop()) {
updateRequested_ = false;
updateStage_ = UpdateStage::idle;
reconcile();
return false;
}
return true;
}
continueFirmwareUpdate();
return true;
}
bool SmartSessionController::retryFirmwareUpdate() {
if (device_ == nullptr || firmware_ == nullptr || updatePort_.isEmpty() || firmware_->busy()) return false;
setupError_ = false;
setupErrorStatus_.clear();
lastFirmwareUpdateResult_.clear();
blankBoardDetected_ = false;
updateRequested_ = true;
updateReconnectAttempts_ = 0;
pendingReleaseGeneration_ = 0;
continueFirmwareUpdate();
return updateRequested_;
}
bool SmartSessionController::cancelFirmwareUpdate() {
if (!firmwareUpdateCanCancel() || device_ == nullptr) return false;
reconnectTimer_.stop();
updateRequested_ = false;
updateWasOptional_ = false;
updateStage_ = UpdateStage::idle;
updateReconnectAttempts_ = 0;
pendingReleaseGeneration_ = 0;
setupError_ = false;
setupErrorStatus_.clear();
blankBoardDetected_ = false;
blankBoardPort_.clear();
if (portOwner_ == PortOwner::firmwareTool) setPortOwner(PortOwner::none);
if (started_ && !device_->connected() && !device_->discovering()) {
QTimer::singleShot(0, this, [this] {
if (!started_ || updateRequested_ || device_ == nullptr || device_->connected() || device_->discovering()) return;
static_cast<void>(startDeviceDiscovery());
reconcile();
});
} else {
reconcile();
}
return true;
}
bool SmartSessionController::retryFirmwareSetup() {
if (!firmwareRetryAvailable()) return false;
return retryFirmwareUpdate();
}
bool SmartSessionController::retryIdentification() {
if (!started_ || device_ == nullptr || updateRequested_ || device_->connected() ||
device_->discovering() || (firmware_ != nullptr && firmware_->busy())) {
return false;
}
clearBlankBoardContext();
const bool started = startDeviceDiscovery();
reconcile();
return started;
}
bool SmartSessionController::retryProfileSync() {
if (!profileSyncRetryAvailable()) return false;
resetProfileSync(true);
QTimer::singleShot(0, this, &SmartSessionController::reconcile);
return true;
}
bool SmartSessionController::startFirmwareProbe() {
if (!updateRequested_ || device_ == nullptr || firmware_ == nullptr ||
firmware_->busy() || device_->connected()) {
return false;
}
// A new firmware attempt gets a fresh generation after the serial handle is
// proven released. This retires every late serial callback before espflash.
advanceSessionGeneration();
setPortOwner(PortOwner::firmwareTool);
firmware_->setSessionGeneration(sessionGeneration_);
updateStage_ = UpdateStage::probing;
setPresentation(
QStringLiteral("UPDATING FIRMWARE"),
QStringLiteral("Verifying ESP32-P4 before firmware installation…"),
false,
false);
if (!firmwareOwnershipValid(portOwner_, device_->connected())) {
latchFirmwareFailure(QStringLiteral("Firmware tool ownership was not established after serial release."));
emit firmwareUpdateFinished(false);
reconcile();
return false;
}
if (!firmware_->probeTarget(updatePort_)) {
latchFirmwareFailure(firmware_->status());
emit firmwareUpdateFinished(false);
reconcile();
return false;
}
return true;
}
void SmartSessionController::continueFirmwareUpdate() {
if (!updateRequested_ || device_ == nullptr || firmware_ == nullptr) return;
if (device_->running()) {
updateStage_ = UpdateStage::stopping;
return;
}
if (portOwner_ == PortOwner::firmwareTool) {
static_cast<void>(startFirmwareProbe());
return;
}
if (device_->connected()) {
updateStage_ = UpdateStage::releasingPort;
pendingReleaseGeneration_ = sessionGeneration_;
setPresentation(
QStringLiteral("UPDATING FIRMWARE"),
QStringLiteral("Releasing the device serial session before firmware access…"),
false,
false);
device_->disconnectPort();
return;
}
pendingReleaseGeneration_ = 0;
setPortOwner(PortOwner::none);
static_cast<void>(startFirmwareProbe());
}
void SmartSessionController::reconnectDeviceSignals() {
if (device_ == nullptr) return;
connect(device_, &DeviceController::deviceVerifiedChanged, this, [this] {
if (device_ != nullptr && device_->deviceVerified()) {
if (portOwner_ != PortOwner::firmwareTool) setPortOwner(PortOwner::deviceSession);
clearBlankBoardContext();
refreshFirmwareIdentity();
profileSyncBootId_.clear();
resetProfileSync(true);
prepareTimer_.start();
} else {
deviceFirmwareVersion_.clear();
deviceFirmwareBuildId_.clear();
profileSyncBootId_.clear();
resetProfileSync(true);
}
reconcile();
});
connect(device_, &DeviceController::identificationStateChanged, this, [this] {
refreshRecoveryOfferFromIdentity();
reconcile();
});
connect(device_, &DeviceController::deviceIdentityChanged, this, [this] {
if (device_ != nullptr && device_->deviceVerified() &&
!profileSyncBootId_.isEmpty() && !device_->bootId().isEmpty() &&
profileSyncBootId_ != device_->bootId()) {
// A new firmware boot on an unchanged COM is a new authority
// epoch. Do not carry a READY/profile proof across the reset.
resetProfileSync(true);
profileSyncBootId_.clear();
}
refreshFirmwareIdentity();
emit stateChanged();
reconcile();
});
connect(device_, &DeviceController::connectedChanged, this, [this] {
if (device_ != nullptr && device_->connected() && portOwner_ != PortOwner::firmwareTool) {
setPortOwner(PortOwner::deviceSession);
}
refreshRecoveryOfferFromIdentity();
reconcile();
});
connect(device_, &DeviceController::discoveryChanged, this, [this] {
refreshRecoveryOfferFromIdentity();
reconcile();
});
connect(device_, &DeviceController::portsChanged, this, [this] {
refreshRecoveryOfferFromIdentity();
reconcile();
});
connect(device_, &DeviceController::runningChanged, this, [this] {
if (updateRequested_ && updateStage_ == UpdateStage::stopping &&
device_ != nullptr && !device_->running()) {
QTimer::singleShot(0, this, [this] { continueFirmwareUpdate(); });
}
reconcile();
});
connect(device_, &DeviceController::portReleased, this,
[this](const quint64 generation, const QString&) {
if (!updateRequested_ || updateStage_ != UpdateStage::releasingPort ||
!generationIsCurrent(sessionGeneration_, generation) ||
generation != pendingReleaseGeneration_) {
return;
}
pendingReleaseGeneration_ = 0;
setPortOwner(PortOwner::none);
QTimer::singleShot(0, this, [this] { continueFirmwareUpdate(); });
});
connect(device_, &DeviceController::profileStateChanged, this, [this] {
handleProfileStateChanged();
reconcile();
});
connect(device_, &DeviceController::profileDeploymentProgress, this, [this] {
if (profileSyncStage_ == ProfileSyncStage::deploying) {
profileSyncTimer_.start();
}
});
}
void SmartSessionController::reconnectProfileSignals() {
if (profiles_ == nullptr) return;
connect(profiles_, &SclProfileModel::sourceChanged, this, [this] {
resetProfileSync(true);
QTimer::singleShot(0, this, &SmartSessionController::reconcile);
});
connect(profiles_, &SclProfileModel::selectedProfileChanged, this, [this] {
resetProfileSync(true);
QTimer::singleShot(0, this, &SmartSessionController::reconcile);
});
}
void SmartSessionController::reconnectFirmwareSignals() {
if (firmware_ == nullptr) return;
connect(firmware_, &FirmwareManager::stateChanged, this, [this] {
if (!updateRequested_) {
reconcile();
return;
}
if (firmware_->sessionGeneration() != sessionGeneration_ ||
portOwner_ != PortOwner::firmwareTool) {
return;
}
if (updateStage_ == UpdateStage::probing && !firmware_->busy()) {
if (firmware_->targetVerified()) {
updateStage_ = UpdateStage::flashing;
setPresentation(
QStringLiteral("UPDATING FIRMWARE"),
QStringLiteral("Installing verified ARStack firmware…"),
false,
false);
QTimer::singleShot(0, this, [this] {
if (firmware_ == nullptr || device_ == nullptr ||
firmware_->sessionGeneration() != sessionGeneration_ ||
!firmwareOwnershipValid(portOwner_, device_->connected())) {
latchFirmwareFailure(QStringLiteral("Firmware ownership changed before installation could start."));
emit firmwareUpdateFinished(false);
reconcile();
return;
}
if (!firmware_->installFirmware(updatePort_)) {
if (firmware_->bootloaderHelpNeeded()) {
updateStage_ = UpdateStage::waitingForBootloader;
} else {
latchFirmwareFailure(firmware_->status());
emit firmwareUpdateFinished(false);
}
reconcile();
}
});
return;
}
if (firmware_->bootloaderHelpNeeded()) {
updateStage_ = UpdateStage::waitingForBootloader;
} else {
latchFirmwareFailure(firmware_->status());
emit firmwareUpdateFinished(false);
}
} else if (updateStage_ == UpdateStage::flashing && !firmware_->busy() &&
firmware_->bootloaderHelpNeeded()) {
updateStage_ = UpdateStage::waitingForBootloader;
}
reconcile();
});
connect(firmware_, &FirmwareManager::operationFailed, this,
[this](const QString& message, const bool bootloaderHelpNeeded) {
if (!updateRequested_ || firmware_ == nullptr ||
firmware_->sessionGeneration() != sessionGeneration_ ||
portOwner_ != PortOwner::firmwareTool) {
reconcile();
return;
}
if (bootloaderHelpNeeded) {
updateStage_ = UpdateStage::waitingForBootloader;
} else {
latchFirmwareFailure(message);
emit firmwareUpdateFinished(false);
}
reconcile();
});
connect(firmware_, &FirmwareManager::installationFinished, this, [this](const bool resetSucceeded) {
if (!updateRequested_ || firmware_ == nullptr ||
firmware_->sessionGeneration() != sessionGeneration_ ||
portOwner_ != PortOwner::firmwareTool) {
return;
}
updateReconnectAttempts_ = 0;
setPortOwner(PortOwner::none);
if (resetSucceeded) {
updateStage_ = UpdateStage::reconnecting;
setPresentation(
QStringLiteral("UPDATING FIRMWARE"),
QStringLiteral("Firmware written. Reconnecting to ESP32-P4…"),
false,
false);
reconnectTimer_.start();
return;
}
if (firmware_->bootloaderHelpNeeded()) {
setPortOwner(PortOwner::firmwareTool);
updateStage_ = UpdateStage::waitingForBootloader;
reconcile();
return;
}
updateStage_ = UpdateStage::reconnecting;
reconnectTimer_.start();
reconcile();
});
}
void SmartSessionController::refreshRecoveryOfferFromIdentity() {
if (device_ == nullptr || updateRequested_ || setupError_ || device_->deviceVerified()) {
blankBoardDetected_ = false;
blankBoardPort_.clear();
if (device_ == nullptr || device_->deviceVerified()) manualRecoveryArmed_ = false;
return;
}
// A terminal semantic-identification timeout on the *single* high-confidence
// Espressif/ESP32 candidate is a safe legacy/blank-firmware recovery signal.
// This does not authorize a write: FirmwareManager still releases the serial
// session and requires espflash ROM identity + ESP32-P4 pre-v3 verification
// before write-bin can start. Generic or ambiguous serial ports remain closed.
if (device_->identificationState() != DeviceController::IdentificationState::Unidentified) {
blankBoardDetected_ = false;
blankBoardPort_.clear();
return;
}
// Semantic timeout on an auto-detected port proves *nothing* about
// flash contents. Present firmware recovery only after the operator
// explicitly selected this port. ROM chip checks still precede flash.
if (recoveryPending_ || !manualRecoveryArmed_) {
blankBoardDetected_ = false;
blankBoardPort_.clear();
return;
}
QString recoveryPort = device_->recoveryCandidatePort().trimmed();
if (recoveryPort.isEmpty()) {
recoveryPort = chooseRecoveryPort(device_->recommendedPort(), device_->ports());
}
if (recoveryPort.isEmpty() || !device_->ports().contains(recoveryPort, Qt::CaseInsensitive)) {
blankBoardDetected_ = false;
blankBoardPort_.clear();
return;
}
blankBoardPort_ = recoveryPort;
blankBoardDetected_ = true;
}
void SmartSessionController::clearBlankBoardContext() {
blankBoardDetected_ = false;
blankBoardPort_.clear();
manualRecoveryArmed_ = false;
unidentifiedDiscoveryTicks_ = 0;
setupError_ = false;
setupErrorStatus_.clear();
}
QString SmartSessionController::diagnosticsText() const {
// Operator-triggered read-only snapshot; does not touch serial ownership.
QStringList rows;
auto add = [&rows](const QString& key, const QString& value) {
rows << key + QStringLiteral(": ") + (value.isEmpty() ? QStringLiteral("-") : value);
};
rows << QStringLiteral("ARStack Studio field diagnostics")
<< QStringLiteral("Device telemetry is reported, not independently verified on wire.");
add(QStringLiteral("Studio version"), expectedFirmwareVersion());
add(QStringLiteral("Session state"), state_);
add(QStringLiteral("Session status"), statusText_);
add(QStringLiteral("Session generation"), QString::number(sessionGeneration_));
add(QStringLiteral("Serial owner"), portOwner_ == PortOwner::deviceSession
? QStringLiteral("device session") : portOwner_ == PortOwner::firmwareTool
? QStringLiteral("firmware tool") : QStringLiteral("none"));
add(QStringLiteral("Firmware update stage"), firmwareUpdateStage());
add(QStringLiteral("Last firmware update result"), lastFirmwareUpdateResult_);
add(QStringLiteral("Setup error"), setupErrorStatus_);
if (firmware_ != nullptr) {
add(QStringLiteral("Bundled firmware version"), firmware_->firmwareVersion());
add(QStringLiteral("Bundled build ID"), firmware_->firmwareBuildId());
add(QStringLiteral("Bundled firmware SHA256"), firmware_->firmwareSha256());
add(QStringLiteral("Firmware service status"), firmware_->status());
add(QStringLiteral("Firmware target"), firmware_->targetChip());
add(QStringLiteral("Firmware operation busy"), firmware_->busy() ? QStringLiteral("yes") : QStringLiteral("no"));
}
if (profiles_ != nullptr && profiles_->hasProfiles()) {
const QVariantMap profile = profiles_->selectedProfile();
add(QStringLiteral("Configured SV ID"), profile.value(QStringLiteral("svId")).toString());
add(QStringLiteral("Configured APPID"), profile.value(QStringLiteral("appId")).toString());
add(QStringLiteral("Configured publisher fps"), profile.value(QStringLiteral("publisherRate")).toString());
add(QStringLiteral("Configured counter wrap"), profile.value(QStringLiteral("counterModulus")).toString());
add(QStringLiteral("Configured payload bytes"), profile.value(QStringLiteral("payloadBytes")).toString());
}
if (device_ != nullptr) {
add(QStringLiteral("Device verified"), device_->deviceVerified() ? QStringLiteral("yes") : QStringLiteral("no"));
add(QStringLiteral("COM port"), device_->portName());
add(QStringLiteral("Device product"), device_->deviceProduct());
add(QStringLiteral("Device target"), device_->deviceTarget());
add(QStringLiteral("Device ID"), device_->deviceId());
add(QStringLiteral("Device firmware version"), device_->firmwareVersion());
add(QStringLiteral("Device firmware build ID"), device_->firmwareBuildId());
add(QStringLiteral("Device protocol"), device_->protocolVersion());
add(QStringLiteral("Device capabilities"), device_->capabilities().join(QStringLiteral(", ")));
add(QStringLiteral("Exact bundled build match"), firmwareIsCurrent() ? QStringLiteral("yes") : QStringLiteral("NOT VERIFIED"));
add(QStringLiteral("Firmware protocol compatible"), !device_->deviceVerified()
? QStringLiteral("UNKNOWN (identity not verified)")
: firmwareIsCompatible() ? QStringLiteral("yes") : QStringLiteral("no"));
add(QStringLiteral("Profile generation"), device_->profileGeneration());
add(QStringLiteral("Profile armed"), device_->profileArmed() ? QStringLiteral("yes") : QStringLiteral("no"));
add(QStringLiteral("SMV running"), device_->running() ? QStringLiteral("yes") : QStringLiteral("no"));
add(QStringLiteral("SMV FPS reported"), device_->fps());
add(QStringLiteral("SMV missed reported"), device_->missed());
add(QStringLiteral("SMV TX failures reported"), device_->txFailures());
add(QStringLiteral("PTP status reported"), device_->ptpStatus());
add(QStringLiteral("SV sync internal flight recorder (not physical proof)"),
device_->syncDiagnostics());
add(QStringLiteral("PTP role reported"), device_->ptpRole());
add(QStringLiteral("PTP discipline reported"), device_->ptpDiscipline());
add(QStringLiteral("SMPSYNCH value reported"), device_->smpSynchValue());
add(QStringLiteral("Device last error"), device_->lastError());
rows << QStringLiteral("--- Device serial log, last 12000 chars ---")
<< device_->logText().right(12000);
}
if (firmware_ != nullptr) {
rows << QStringLiteral("--- Firmware service log, last 12000 chars ---")
<< firmware_->logText().right(12000);
}
rows << QStringLiteral("Review and redact site identifiers or addresses before sharing.");
return rows.join(QLatin1Char('\n'));