Repository navigation
Expand file tree
/
Copy pathPanelBridge.cpp
More file actions
1499 lines (1359 loc) · 52.9 KB
/
Copy pathPanelBridge.cpp
File metadata and controls
1499 lines (1359 loc) · 52.9 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
#include "PanelBridge.h"
#include "AppConfig.h"
#include <driver/uart.h>
#include <esp_idf_version.h>
#include <lwip/sockets.h>
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 5, 0)
#error "GC2 Bridge requires Arduino-ESP32 3.3.x (ESP-IDF 5.5) or newer."
#endif
namespace {
constexpr uint8_t kTelnetIac = 255;
constexpr uint8_t kTelnetDo = 253;
constexpr uint8_t kTelnetDont = 254;
constexpr uint8_t kTelnetWill = 251;
constexpr uint8_t kTelnetWont = 252;
constexpr uint8_t kTelnetSubBegin = 250;
constexpr uint8_t kTelnetSubEnd = 240;
constexpr uint8_t kTelnetEcho = 1;
constexpr uint8_t kTelnetSuppressGoAhead = 3;
bool isHexDigit(char value) {
return (value >= '0' && value <= '9') ||
(value >= 'a' && value <= 'f') ||
(value >= 'A' && value <= 'F');
}
uint8_t hexValue(char value) {
if (value >= '0' && value <= '9') return value - '0';
if (value >= 'a' && value <= 'f') return value - 'a' + 10;
return value - 'A' + 10;
}
bool parseEightHexDigitsAfter(const String& line, const String& marker,
uint32_t& output) {
int position = line.indexOf(marker);
if (position < 0) return false;
position += marker.length();
while (position < static_cast<int>(line.length()) &&
!isHexDigit(line[position])) {
++position;
}
if (position + 8 > static_cast<int>(line.length())) return false;
uint32_t value = 0;
for (int index = 0; index < 8; ++index) {
if (!isHexDigit(line[position + index])) return false;
value = (value << 4) | hexValue(line[position + index]);
}
if (value == 0 || value == 0xFFFFFFFFUL) return false;
output = value;
return true;
}
bool parseRtcDate(const String& line, uint8_t& month, uint8_t& day,
uint16_t& year) {
const int rtcPosition = line.indexOf("RTC");
if (rtcPosition < 0) return false;
for (int position = rtcPosition;
position + 9 < static_cast<int>(line.length()); ++position) {
if (!isDigit(line[position])) continue;
int firstSlash = line.indexOf('/', position);
if (firstSlash < 0 || firstSlash - position > 2) continue;
int secondSlash = line.indexOf('/', firstSlash + 1);
if (secondSlash < 0 || secondSlash - firstSlash > 3) continue;
const int parsedMonth = line.substring(position, firstSlash).toInt();
const int parsedDay =
line.substring(firstSlash + 1, secondSlash).toInt();
int end = secondSlash + 1;
while (end < static_cast<int>(line.length()) && isDigit(line[end])) {
++end;
}
const int parsedYear = line.substring(secondSlash + 1, end).toInt();
if (parsedMonth < 1 || parsedMonth > 12 || parsedDay < 1 ||
parsedDay > 31 || parsedYear < 2000 || parsedYear > 2099) {
continue;
}
month = parsedMonth;
day = parsedDay;
year = parsedYear;
return true;
}
return false;
}
} // namespace
PanelBridge::PanelBridge(CredentialStore& credentials,
Gc2ConsoleParser& parser)
: credentials_(credentials),
parser_(parser),
panel_(Serial1),
server_(AppConfig::kTelnetPort) {}
void PanelBridge::begin() {
// GPIO6 is connected to a live panel bus that may also be driven by the
// 345 MHz receiver. Keep it electrically high-impedance until an
// intentional command is sent; merely avoiding write() is insufficient
// because an attached UART TX actively drives the idle-high state.
panel_.end();
pinMode(AppConfig::kPanelTxPin, INPUT);
bootTime_ = millis();
baudStateStartedAt_ = bootTime_;
panelLine_.reserve(512);
validationLine_.reserve(512);
telnetLine_.reserve(AppConfig::kMaxConsoleCommandLength);
Serial.print(F("[uart] Passive baud detection starts "));
Serial.print(AppConfig::kBaudDetectDelayMs / 1000);
Serial.println(F(" seconds after power-up."));
}
bool PanelBridge::deadlineReached(uint32_t deadline) {
return static_cast<int32_t>(millis() - deadline) >= 0;
}
void PanelBridge::setNetworkReady(bool ready) {
networkReady_ = ready;
if (ready && !serverStarted_) {
server_.begin();
server_.setNoDelay(true);
serverStarted_ = true;
Serial.print(F("[telnet] Listening on port "));
Serial.println(AppConfig::kTelnetPort);
}
if (ready && panelReady()) {
// Re-read retained alarm memory when Home Assistant connectivity
// returns, in case an alarm occurred while MQTT was unavailable.
nextAlarmMemoryPollAt_ = millis() + AppConfig::kCommandIntervalMs;
}
if (!ready) disconnectClient();
}
void PanelBridge::stopNetwork() {
disconnectClient();
if (serverStarted_) {
server_.end();
serverStarted_ = false;
}
networkReady_ = false;
}
void PanelBridge::loop() {
processBaudDetection();
if (baudState_ == BaudState::Validating) {
processBaudValidation();
}
if (panelReady()) {
processPanelInput();
parser_.finishTimedSnapshots();
processUnlock();
processUnlockSupervisor();
processAlarmControl();
processMonitorPolling();
}
processServer();
processManualCommandQueue();
}
void PanelBridge::processBaudDetection() {
switch (baudState_) {
case BaudState::Waiting:
if (millis() - bootTime_ >= AppConfig::kBaudDetectDelayMs) {
startBaudValidation();
}
break;
case BaudState::RetryDelay:
if (millis() - baudStateStartedAt_ >=
AppConfig::kBaudRetryDelayMs) {
startBaudValidation();
}
break;
case BaudState::Validating:
case BaudState::Ready: break;
}
}
bool PanelBridge::validBaud(uint32_t baud) {
return baud > 0 && baud <= UART_BITRATE_MAX;
}
void PanelBridge::addBaudCandidate(uint32_t baud) {
if (!validBaud(baud) || baudCandidateCount_ >= kMaxBaudCandidates) return;
for (uint8_t index = 0; index < baudCandidateCount_; ++index) {
if (baudCandidates_[index] == baud) return;
}
baudCandidates_[baudCandidateCount_++] = baud;
}
void PanelBridge::startBaudValidation() {
baudCandidateCount_ = 0;
baudCandidateIndex_ = 0;
// Hardware edge timing on ordinary ASCII repeatedly produced integer
// harmonics. Automatic selection is therefore based solely on decoded
// panel evidence at the three rates observed on GC2-family bench units.
addBaudCandidate(19200);
addBaudCandidate(115200);
addBaudCandidate(38400);
startCurrentBaudCandidate();
}
void PanelBridge::startCurrentBaudCandidate() {
if (baudCandidateIndex_ >= baudCandidateCount_) {
baudState_ = BaudState::RetryDelay;
baudStateStartedAt_ = millis();
trialBaud_ = 0;
sendClientStatus(
"No baud candidate produced readable panel text; restarting the fixed trial sequence.");
return;
}
panel_.end();
pinMode(AppConfig::kPanelTxPin, INPUT);
panel_.setRxBufferSize(AppConfig::kPanelRxBufferSize);
panel_.setTxBufferSize(AppConfig::kPanelTxBufferSize);
trialBaud_ = baudCandidates_[baudCandidateIndex_];
panel_.begin(trialBaud_, SERIAL_8N1, AppConfig::kPanelRxPin,
-1);
baudState_ = BaudState::Validating;
baudStateStartedAt_ = millis();
validationByteCount_ = 0;
validationPrintableCount_ = 0;
validationLine_ = String();
validationLine_.reserve(512);
Serial.print(F("[uart] Passively validating candidate "));
Serial.print(trialBaud_);
Serial.println(F(" baud for up to 60 seconds; UART transmission remains blocked."));
sendClientStatus(String("Passively testing ") + trialBaud_ +
" baud for readable panel text.");
}
bool PanelBridge::plausiblePanelText(const String& input) {
String line = input;
line.trim();
if (line.length() < 6) return false;
String lowercase = line;
lowercase.toLowerCase();
for (const char* marker : {
"buildinfo:", "sensor --", "pir --", "zone ",
"alarm_", "panel_", "sensors_", "zwave_", "sounder_",
"topegmessage:", "supervisory packet", "powerup ",
"debug_lock_state", "battery", " mv", "firmware",
"version", "serial number"}) {
if (lowercase.indexOf(marker) >= 0) return true;
}
if (lowercase.startsWith("event") ||
lowercase.indexOf(" event ") >= 0 ||
lowercase.indexOf(" event:") >= 0) {
return true;
}
// Most runtime GC2-family logs use [hours:minutes:seconds.fraction].
// Validate the shape rather than any exact timestamp or message text so
// different firmware revisions and panel programming remain compatible.
if (line[0] == '[') {
const int close = line.indexOf(']');
if (close >= 6 && close <= 20) {
uint8_t colons = 0;
bool timestampValid = true;
for (int index = 1; index < close; ++index) {
const char character = line[index];
if (character == ':') {
++colons;
} else if (character != '.' && !isDigit(character)) {
timestampValid = false;
break;
}
}
uint8_t lettersAfterTimestamp = 0;
for (int index = close + 1;
index < static_cast<int>(line.length()); ++index) {
if (isAlpha(line[index])) ++lettersAfterTimestamp;
}
if (timestampValid && colons >= 2 &&
lettersAfterTimestamp >= 3) {
return true;
}
}
}
return false;
}
void PanelBridge::processBaudValidation() {
while (panel_.available() > 0) {
const int value = panel_.read();
if (value < 0) break;
const uint8_t byte = static_cast<uint8_t>(value);
++validationByteCount_;
const bool textual = (byte >= 0x20 && byte <= 0x7E) || byte == '\r' ||
byte == '\n' || byte == '\t';
if (textual) ++validationPrintableCount_;
if (byte == '\r' || byte == '\n') {
if (!validationLine_.isEmpty()) {
const bool streamIsText =
validationPrintableCount_ * 100U >=
validationByteCount_ * 85U;
if (streamIsText && plausiblePanelText(validationLine_)) {
const String evidence = validationLine_;
acceptCurrentBaudCandidate(evidence);
return;
}
validationLine_ = String();
validationLine_.reserve(512);
}
} else if (byte >= 0x20 && byte <= 0x7E) {
if (validationLine_.length() < 511) {
validationLine_ += static_cast<char>(byte);
}
} else if (byte != '\t') {
validationLine_ = String();
validationLine_.reserve(512);
}
}
if (millis() - baudStateStartedAt_ >=
AppConfig::kBaudValidationWindowMs) {
rejectCurrentBaudCandidate(
"no recognizable panel text in the 60-second trial");
}
}
void PanelBridge::rejectCurrentBaudCandidate(const char* reason) {
Serial.print(F("[uart] Candidate "));
Serial.print(trialBaud_);
Serial.print(F(" rejected: "));
Serial.println(reason);
panel_.end();
pinMode(AppConfig::kPanelTxPin, INPUT);
++baudCandidateIndex_;
startCurrentBaudCandidate();
}
void PanelBridge::acceptCurrentBaudCandidate(const String& evidence) {
currentBaud_ = trialBaud_;
baudState_ = BaudState::Ready;
unlockPhase_ = UnlockPhase::NotStarted;
nextUnlockActionAt_ = 0;
nextUnlockSupervisionAt_ =
millis() + AppConfig::kDebugUnlockInitialDelayMs;
nextZoneMetadataPollAt_ =
millis() + AppConfig::kZoneMetadataInitialDelayMs;
nextZoneStatePollAt_ = millis() + AppConfig::kZoneStateInitialDelayMs;
nextZoneTroublePollAt_ =
millis() + AppConfig::kZoneTroubleInitialDelayMs;
nextSounderStatusPollAt_ =
millis() + AppConfig::kSounderStatusInitialDelayMs;
nextPanelStatusPollAt_ =
millis() + AppConfig::kPanelStatusInitialDelayMs;
nextAlarmMemoryPollAt_ =
millis() + AppConfig::kAlarmMemoryInitialDelayMs;
panelLine_ = String();
panelLine_.reserve(512);
Serial.print(F("[uart] Validated "));
Serial.print(currentBaud_);
Serial.print(F(" baud from readable panel text: "));
Serial.println(evidence.substring(0, 120));
sendClientStatus(String("UART validated at ") + currentBaud_ +
" baud from readable panel text.");
inspectPanelLine(evidence);
}
void PanelBridge::restartBaudDetection() {
if (baudState_ == BaudState::Ready ||
baudState_ == BaudState::Validating) {
panel_.end();
}
pinMode(AppConfig::kPanelTxPin, INPUT);
abortAlarmControl("panel UART restarted");
currentBaud_ = 0;
baudState_ = BaudState::RetryDelay;
baudStateStartedAt_ = millis() - AppConfig::kBaudRetryDelayMs;
panelLine_ = String();
panelLine_.reserve(512);
commandQueue_.clear();
unlockPhase_ = UnlockPhase::NotStarted;
nextUnlockActionAt_ = 0;
nextUnlockSupervisionAt_ = 0;
nextZoneMetadataPollAt_ = 0;
nextZoneStatePollAt_ = 0;
nextZoneTroublePollAt_ = 0;
nextSounderStatusPollAt_ = 0;
nextPanelStatusPollAt_ = 0;
nextAlarmMemoryPollAt_ = 0;
trialBaud_ = 0;
validationLine_ = String();
}
void PanelBridge::requestAutoBaud() { restartBaudDetection(); }
bool PanelBridge::setBaudOverride(uint32_t baud) {
if (!validBaud(baud)) return false;
if (panelReady() && currentBaud_ == baud) return true;
startPanelUart(baud);
return true;
}
String PanelBridge::baudState() const {
return panelReady() ? String(currentBaud_) : String("detecting");
}
void PanelBridge::startPanelUart(uint32_t baud) {
if (baudState_ == BaudState::Ready ||
baudState_ == BaudState::Validating) {
panel_.end();
}
pinMode(AppConfig::kPanelTxPin, INPUT);
abortAlarmControl("panel UART restarted");
panel_.setRxBufferSize(AppConfig::kPanelRxBufferSize);
panel_.setTxBufferSize(AppConfig::kPanelTxBufferSize);
panel_.begin(baud, SERIAL_8N1, AppConfig::kPanelRxPin,
-1);
// Count driver-level overflow so lost panel bytes are visible in the
// diagnostics instead of silently missing a zone transition. The
// callback runs on the UART event task; it only bumps a counter.
panel_.onReceiveError([this](hardwareSerial_error_t) {
++uartErrorCount_;
});
currentBaud_ = baud;
baudState_ = BaudState::Ready;
// Monitor mode maintains debug access and permits the narrow, read-only
// zone metadata poll. Strict zero-transmit mode remains available through
// /listen on.
unlockPhase_ = UnlockPhase::NotStarted;
nextUnlockActionAt_ = 0;
nextUnlockSupervisionAt_ =
millis() + AppConfig::kDebugUnlockInitialDelayMs;
nextZoneMetadataPollAt_ =
millis() + AppConfig::kZoneMetadataInitialDelayMs;
nextZoneStatePollAt_ = millis() + AppConfig::kZoneStateInitialDelayMs;
nextZoneTroublePollAt_ =
millis() + AppConfig::kZoneTroubleInitialDelayMs;
nextSounderStatusPollAt_ =
millis() + AppConfig::kSounderStatusInitialDelayMs;
nextPanelStatusPollAt_ =
millis() + AppConfig::kPanelStatusInitialDelayMs;
nextAlarmMemoryPollAt_ =
millis() + AppConfig::kAlarmMemoryInitialDelayMs;
Serial.print(F("[uart] Panel UART set to "));
Serial.print(baud);
Serial.println(F(" baud, 8N1."));
sendClientStatus(String("UART detected at ") + baud + " baud.");
}
void PanelBridge::processPanelInput() {
uint8_t input[512];
while (panel_.available() > 0) {
const int count = panel_.read(input, sizeof(input));
if (count <= 0) break;
lastPanelRxAt_ = millis();
for (int index = 0; index < count; ++index) {
processPanelByte(input[index]);
}
// Parsing/state updates always happen before a potentially slow TCP
// client is serviced, so Telnet backpressure cannot delay conditioning
// of bytes that have already been removed from the UART FIFO.
writePanelDataToClient(input, count);
}
}
void PanelBridge::processPanelByte(uint8_t value) {
if (value == '\r' || value == '\n') {
if (!panelLine_.isEmpty()) {
inspectPanelLine(panelLine_);
panelLine_ = String();
panelLine_.reserve(512);
}
return;
}
if ((value >= 0x20 && value <= 0x7E) || value == '\t') {
if (panelLine_.length() < 511) {
panelLine_ += static_cast<char>(value);
} else {
panelLine_ = String();
panelLine_.reserve(512);
}
}
}
void PanelBridge::inspectPanelLine(const String& line) {
parser_.processLine(line);
if (line.indexOf("TROUBLE_MEMORY_UPDATED") >= 0) {
nextZoneTroublePollAt_ = millis();
}
if (line.indexOf("ALARM_MEMORY_UPDATED") >= 0) {
nextAlarmMemoryPollAt_ = millis();
}
if (line.indexOf("UI TIMER lag") >= 0) {
// The panel's UI task is running behind; sustained load from here is
// what ends in a data abort and reboot. Stop optional polling.
if (deadlineReached(pollBackoffUntil_)) {
Serial.println(F("[panel] UI task lag reported; pausing read-only polls."));
sendClientStatus("Panel reported UI task lag; read-only polling paused for 60 seconds.");
}
pollBackoffUntil_ = millis() + AppConfig::kPanelLagBackoffMs;
}
String lowercase = line;
lowercase.toLowerCase();
if ((unlockPhase_ == UnlockPhase::WaitUnlock ||
unlockPhase_ == UnlockPhase::SendVerification ||
unlockPhase_ == UnlockPhase::WaitVerification) &&
(lowercase.indexOf("unlocked") >= 0 ||
lowercase.indexOf("not locked") >= 0)) {
debugLockState_ = 2;
}
uint32_t serialNumber = 0;
if (line.indexOf("PowerUp Serial Number") < 0 &&
(parseEightHexDigitsAfter(line, " SN ", serialNumber) ||
parseEightHexDigitsAfter(line, "Serial Number", serialNumber) ||
parseEightHexDigitsAfter(line, "XCVR network ID", serialNumber))) {
panelSerialNumber_ = serialNumber;
}
uint8_t month = 0;
uint8_t day = 0;
uint16_t year = 0;
if (parseRtcDate(line, month, day, year)) {
panelMonth_ = month;
panelDay_ = day;
panelYear_ = year;
}
const int lockPosition = line.indexOf("debug_lock_state");
if (lockPosition >= 0) {
int position = lockPosition + strlen("debug_lock_state");
while (position < static_cast<int>(line.length()) &&
!isDigit(line[position])) {
++position;
}
if (position < static_cast<int>(line.length())) {
debugLockState_ = line.substring(position).toInt();
}
}
if (line.indexOf("is not available when debug is locked") >= 0) {
debugLockState_ = 1;
if (unlockPhase_ == UnlockPhase::Complete ||
unlockPhase_ == UnlockPhase::Failed ||
unlockPhase_ == UnlockPhase::NotStarted) {
unlockPhase_ = UnlockPhase::NotStarted;
nextUnlockSupervisionAt_ = millis();
sendClientStatus(
"Panel debug access is locked; automatic re-unlock scheduled.");
}
}
if (lowercase.indexOf("debug is now locked") >= 0) {
debugLockState_ = 1;
unlockPhase_ = UnlockPhase::NotStarted;
nextUnlockSupervisionAt_ = millis();
}
}
bool PanelBridge::attachPanelTx() {
if (!panel_.setPins(-1, AppConfig::kPanelTxPin)) {
Serial.println(F("[uart] Could not attach panel TX pin."));
releasePanelTx();
return false;
}
return true;
}
void PanelBridge::releasePanelTx() {
// pinMode claims the pad from the UART peripheral manager and disconnects
// the output matrix, returning the pin to a true high-impedance input.
pinMode(AppConfig::kPanelTxPin, INPUT);
}
bool PanelBridge::sendPanelCommand(const String& command) {
if (txMode_ != TxMode::Maintenance) return false;
return sendBridgeCommand(command);
}
bool PanelBridge::sendBridgeCommand(const String& command) {
const uint32_t sinceCommand = millis() - lastPanelCommandAt_;
if (txMode_ == TxMode::Passive || !panelReady() ||
sinceCommand < AppConfig::kCommandIntervalMs) {
return false;
}
// Let the previous reply (or unsolicited output) finish first. A console
// that never pauses must not block commands forever, so give up waiting
// for silence after kPanelQuietMaxWaitMs.
if (millis() - lastPanelRxAt_ < AppConfig::kPanelQuietBeforeCommandMs &&
sinceCommand < AppConfig::kCommandIntervalMs +
AppConfig::kPanelQuietMaxWaitMs) {
return false;
}
if (!attachPanelTx()) return false;
panel_.write(reinterpret_cast<const uint8_t*>(command.c_str()),
command.length());
panel_.write('\r');
panel_.flush(true);
releasePanelTx();
lastPanelCommandAt_ = millis();
return true;
}
bool PanelBridge::sendMonitorCommand(const char* command) {
if (txMode_ != TxMode::Monitor || command == nullptr) return false;
return sendBridgeCommand(String(command));
}
void PanelBridge::processMonitorPolling() {
if (txMode_ != TxMode::Monitor ||
alarmControlPhase_ != AlarmControlPhase::Idle ||
(unlockPhase_ != UnlockPhase::NotStarted &&
unlockPhase_ != UnlockPhase::Complete &&
unlockPhase_ != UnlockPhase::Failed)) {
return;
}
// One read-only poll per spacing window, never a burst, and none while
// the panel reports UI lag.
if (millis() - lastPanelCommandAt_ < AppConfig::kMonitorPollSpacingMs ||
!deadlineReached(pollBackoffUntil_)) {
return;
}
if (deadlineReached(nextZoneMetadataPollAt_) &&
sendMonitorCommand("zone_info 1")) {
nextZoneMetadataPollAt_ = millis() + AppConfig::kZoneMetadataRefreshMs;
sendClientStatus(
"Refreshing read-only zone names and programming metadata.");
return;
}
if (deadlineReached(nextZoneStatePollAt_) &&
sendMonitorCommand("zones")) {
nextZoneStatePollAt_ = millis() + AppConfig::kZoneStateRefreshMs;
return;
}
if (deadlineReached(nextZoneTroublePollAt_) &&
sendMonitorCommand("trouble_memory")) {
parser_.beginTroubleSnapshot();
nextZoneTroublePollAt_ = millis() + AppConfig::kZoneTroubleRefreshMs;
return;
}
if (deadlineReached(nextSounderStatusPollAt_) &&
sendMonitorCommand("sounder_status")) {
nextSounderStatusPollAt_ =
millis() + AppConfig::kSounderStatusRefreshMs;
return;
}
if (deadlineReached(nextPanelStatusPollAt_) &&
sendMonitorCommand("panel_status")) {
nextPanelStatusPollAt_ = millis() + AppConfig::kPanelStatusRefreshMs;
return;
}
if (deadlineReached(nextAlarmMemoryPollAt_) &&
sendMonitorCommand("alarm_memory")) {
parser_.beginAlarmMemorySnapshot();
nextAlarmMemoryPollAt_ = millis() + AppConfig::kAlarmMemoryRefreshMs;
}
}
uint32_t PanelBridge::calculateUnlockCode(uint32_t serialNumber, uint8_t day,
uint8_t month, uint16_t year) {
const uint8_t input[] = {
static_cast<uint8_t>(serialNumber >> 24),
static_cast<uint8_t>(serialNumber >> 16),
static_cast<uint8_t>(serialNumber >> 8),
static_cast<uint8_t>(serialNumber),
day,
month,
static_cast<uint8_t>(year % 100),
0x12,
0x34,
0x56,
0x78,
};
uint32_t hash = 0x811C9DC5UL;
for (const uint8_t value : input) {
hash ^= value;
hash *= 0x01000193UL;
}
return hash;
}
void PanelBridge::processUnlock() {
if (!deadlineReached(nextUnlockActionAt_)) return;
switch (unlockPhase_) {
case UnlockPhase::NotStarted:
case UnlockPhase::Complete:
case UnlockPhase::Failed: return;
case UnlockPhase::SendCalibration:
if (sendBridgeCommand("cal_values")) {
unlockPhase_ = UnlockPhase::WaitCalibration;
nextUnlockActionAt_ = millis() + 6500;
}
break;
case UnlockPhase::WaitCalibration:
unlockPhase_ = UnlockPhase::SendBuildInfo;
nextUnlockActionAt_ = millis();
break;
case UnlockPhase::SendBuildInfo:
if (sendBridgeCommand("build_info")) {
unlockPhase_ = UnlockPhase::WaitBuildInfo;
nextUnlockActionAt_ = millis() + 6000;
}
break;
case UnlockPhase::WaitBuildInfo:
unlockPhase_ = UnlockPhase::SendRtc;
nextUnlockActionAt_ = millis();
break;
case UnlockPhase::SendRtc:
if (sendBridgeCommand("rtc")) {
unlockPhase_ = UnlockPhase::WaitRtc;
nextUnlockActionAt_ = millis() + 6500;
}
break;
case UnlockPhase::WaitRtc:
unlockPhase_ = UnlockPhase::EvaluateIdentity;
nextUnlockActionAt_ = millis();
break;
case UnlockPhase::EvaluateIdentity:
if (panelSerialNumber_ != 0 && panelYear_ != 0) {
unlockPhase_ = UnlockPhase::SendUnlock;
nextUnlockActionAt_ = millis();
} else if (++identityAttempts_ < 3) {
unlockPhase_ = UnlockPhase::SendCalibration;
nextUnlockActionAt_ = millis() + 3000;
} else {
unlockPhase_ = UnlockPhase::Failed;
nextUnlockSupervisionAt_ =
millis() + AppConfig::kDebugUnlockRetryIntervalMs;
Serial.println(F("[unlock] Could not obtain panel identity and RTC date."));
sendClientStatus(
"Automatic unlock could not read the panel identity/date; another attempt will be made in 30 seconds.");
}
break;
case UnlockPhase::SendUnlock: {
char command[24];
const uint32_t code = calculateUnlockCode(
panelSerialNumber_, panelDay_, panelMonth_, panelYear_);
snprintf(command, sizeof(command), "unlock %08lx",
static_cast<unsigned long>(code));
if (sendBridgeCommand(command)) {
debugLockState_ = -1;
++unlockAttempts_;
unlockPhase_ = UnlockPhase::WaitUnlock;
nextUnlockActionAt_ = millis() + 1500;
Serial.println(F("[unlock] Daily service code submitted."));
}
memset(command, 0, sizeof(command));
break;
}
case UnlockPhase::WaitUnlock:
unlockPhase_ = UnlockPhase::SendVerification;
nextUnlockActionAt_ = millis();
break;
case UnlockPhase::SendVerification:
if (sendBridgeCommand("panel_misc")) {
++unlockVerificationAttempts_;
unlockPhase_ = UnlockPhase::WaitVerification;
nextUnlockActionAt_ = millis() + 6000;
}
break;
case UnlockPhase::WaitVerification:
if (debugLockState_ == 2) {
unlockPhase_ = UnlockPhase::Complete;
unlockAttempts_ = 0;
unlockVerificationAttempts_ = 0;
nextUnlockSupervisionAt_ =
millis() + AppConfig::kDebugUnlockCheckIntervalMs;
Serial.println(F("[unlock] Panel reports the maintenance console is unlocked."));
sendClientStatus(
"Panel maintenance console unlocked; persistent supervision active.");
} else if (debugLockState_ == 1 && unlockAttempts_ < 3) {
unlockPhase_ = UnlockPhase::SendUnlock;
nextUnlockActionAt_ = millis() + 5000;
} else if (debugLockState_ < 0 &&
unlockVerificationAttempts_ < 3) {
unlockPhase_ = UnlockPhase::SendVerification;
nextUnlockActionAt_ = millis() + 2000;
} else {
unlockPhase_ = UnlockPhase::Failed;
nextUnlockSupervisionAt_ =
millis() + AppConfig::kDebugUnlockRetryIntervalMs;
Serial.println(F("[unlock] Persistent debug unlock could not be verified."));
sendClientStatus(
"Automatic unlock failed; another attempt will be made in 30 seconds.");
}
break;
}
}
void PanelBridge::processUnlockSupervisor() {
if (txMode_ == TxMode::Passive ||
alarmControlPhase_ != AlarmControlPhase::Idle ||
!deadlineReached(nextUnlockSupervisionAt_)) {
return;
}
if (unlockPhase_ != UnlockPhase::NotStarted &&
unlockPhase_ != UnlockPhase::Complete &&
unlockPhase_ != UnlockPhase::Failed) {
return;
}
if (debugLockState_ == 2 && unlockPhase_ == UnlockPhase::Complete) {
debugLockState_ = -1;
unlockVerificationAttempts_ = 0;
unlockPhase_ = UnlockPhase::SendVerification;
nextUnlockActionAt_ = millis();
nextUnlockSupervisionAt_ = UINT32_MAX;
Serial.println(F("[unlock] Verifying persistent debug access."));
return;
}
scheduleAutomaticUnlock();
Serial.println(F("[unlock] Starting persistent debug unlock."));
}
bool PanelBridge::requestAlarmCommand(AlarmCommand command) {
String requestedAction;
String requestedText;
switch (command) {
case AlarmCommand::ArmHome:
requestedAction = F("arm_home");
requestedText = F("arm_stay 0");
break;
case AlarmCommand::ArmAway:
requestedAction = F("arm_away");
requestedText = F("arm_away 0");
break;
case AlarmCommand::Disarm:
requestedAction = F("disarm");
requestedText = F("disarm 0");
break;
}
return beginProtectedCommand(requestedAction, requestedText);
}
bool PanelBridge::requestZoneBypass(uint8_t zone, bool bypassed) {
if (zone == 0 || zone >= Gc2State::kMaxZones) return false;
char action[32];
char command[24];
snprintf(action, sizeof(action), "%s_zone_%02u",
bypassed ? "bypass" : "unbypass", zone);
snprintf(command, sizeof(command), "%s %u",
bypassed ? "bypass" : "unbypass", zone);
return beginProtectedCommand(action, command);
}
bool PanelBridge::requestZoneChime(uint8_t zone, uint8_t mode) {
// zone_chime <zone 0-74> <type>; type 0=none, 1=voice,
// 2=voice+dingdong, 3=loud dingdong, 4=voice+loud dingdong, 5=dingdong.
// The panel commits the zone record to its settings flash, so callers
// must only request a value that differs from the retained one.
if (zone == 0 || zone >= Gc2State::kMaxZones || mode > 5) return false;
char action[32];
char command[24];
snprintf(action, sizeof(action), "zone_chime_%02u_%u", zone, mode);
snprintf(command, sizeof(command), "zone_chime %u %u", zone, mode);
return beginProtectedCommand(action, command);
}
bool PanelBridge::requestSounderVolume(uint8_t percent) {
if (percent > 100) return false;
char action[24];
char command[24];
snprintf(action, sizeof(action), "sounder_volume_%u", percent);
snprintf(command, sizeof(command), "sounder_volume %u", percent);
const bool accepted = beginProtectedCommand(action, command);
if (accepted) {
nextSounderStatusPollAt_ = millis() + AppConfig::kCommandIntervalMs;
}
return accepted;
}
bool PanelBridge::beginProtectedCommand(const String& action,
const String& command) {
if (alarmControlPhase_ != AlarmControlPhase::Idle) {
// Another protected command is in flight. Queue this one so a burst
// (two zone selects changed by one automation) is sent one per
// second instead of being dropped. Identical pending actions are
// collapsed.
for (const ProtectedCommand& pending : protectedQueue_) {
if (pending.action == action) return true;
}
if (protectedQueue_.size() >= AppConfig::kMaxQueuedPanelCommands) {
Serial.print(F("[panel] Command queue full; dropped "));
Serial.println(action);
return false;
}
protectedQueue_.push_back(ProtectedCommand{action, command});
Serial.print(F("[panel] Queued "));
Serial.print(action);
Serial.print(F(" behind "));
Serial.println(alarmCommandAction_);
sendClientStatus(String("MQTT panel action queued: ") + action + '.');
return true;
}
return startProtectedCommand(action, command);
}
bool PanelBridge::startProtectedCommand(const String& action,
const String& command) {
alarmCommandAction_ = action;
alarmCommandText_ = command;
if (!panelReady()) {
setAlarmCommandStatus("rejected", "UART baud is not locked yet");
return false;
}
if (txMode_ == TxMode::Passive) {
setAlarmCommandStatus("rejected", "strict passive mode is active");
return false;
}
alarmCommandTransmitted_ = false;
alarmControlStartedAt_ = millis();
if (unlockPhase_ == UnlockPhase::Complete && debugLockState_ == 2) {
alarmControlPhase_ = AlarmControlPhase::SendCommand;
nextAlarmControlActionAt_ = millis();
setAlarmCommandStatus("sending", "persistent debug unlock verified");
} else {
if (unlockPhase_ == UnlockPhase::NotStarted ||
unlockPhase_ == UnlockPhase::Failed) {
scheduleAutomaticUnlock();
}
alarmControlPhase_ = AlarmControlPhase::Unlocking;
nextAlarmControlActionAt_ = millis();
setAlarmCommandStatus("unlocking", "waiting for persistent debug access");
}
sendClientStatus(String("MQTT panel action accepted: ") +
alarmCommandAction_ + '.');
return true;
}
void PanelBridge::processAlarmControl() {
if (alarmControlPhase_ == AlarmControlPhase::Idle) {
if (!protectedQueue_.empty()) {
const ProtectedCommand next = protectedQueue_.front();
protectedQueue_.pop_front();
startProtectedCommand(next.action, next.command);
}
return;
}
if (alarmControlPhase_ != AlarmControlPhase::WaitCommand &&
millis() - alarmControlStartedAt_ >=
AppConfig::kAlarmControlTimeoutMs) {
abortAlarmControl("timed out waiting for debug access or transmission");
return;
}
if (!deadlineReached(nextAlarmControlActionAt_)) return;
switch (alarmControlPhase_) {
case AlarmControlPhase::Idle: return;
case AlarmControlPhase::Unlocking:
if (unlockPhase_ == UnlockPhase::NotStarted) {
// The panel re-locked (or the sequence was reset) while this
// command waited. The unlock supervisor stands down while a
// command is in flight, so restart the sequence from here.
scheduleAutomaticUnlock();
} else if (unlockPhase_ == UnlockPhase::Complete) {
if (debugLockState_ == 2) {
alarmControlPhase_ = AlarmControlPhase::SendCommand;
setAlarmCommandStatus("sending", "debug unlock verified");
} else {
alarmControlPhase_ = AlarmControlPhase::Idle;
setAlarmCommandStatus("failed", "debug unlock could not be verified");
alarmCommandText_ = String();
}
nextAlarmControlActionAt_ = millis();
} else if (unlockPhase_ == UnlockPhase::Failed) {
alarmControlPhase_ = AlarmControlPhase::Idle;
nextAlarmControlActionAt_ = millis();
setAlarmCommandStatus("failed", "debug unlock failed");
alarmCommandText_ = String();
}
break;