-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
3910 lines (3599 loc) · 169 KB
/
Copy pathmain.cpp
File metadata and controls
3910 lines (3599 loc) · 169 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 <Arduino.h>
#include <LittleFS.h>
#include <SPI.h>
#include <WebServer.h>
#include <WiFi.h>
#include <driver/rtc_io.h>
#include <driver/twai.h>
#include <esp_sleep.h>
#include <esp_system.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <mcp2515.h>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "core/dbc_parser.hpp"
#include "core/application_extension.hpp"
#include "core/can_trace.hpp"
#include "core/frame_cache.hpp"
#include "core/gateway.hpp"
#include "core/mutation_engine.hpp"
#include "core/observation_manager.hpp"
#include "core/parked_power.hpp"
#include "core/replay_engine.hpp"
#include "core/rule_package.hpp"
#include "core/runtime_memory.hpp"
#include "core/runtime_values.hpp"
#include "core/runtime_tables.hpp"
#include "core/signal_cache.hpp"
#include "core/signal_catalog.hpp"
#include "core/signal_codec.hpp"
#include "core/types.hpp"
#include "fs/persistence.hpp"
#include "fs/session_log.hpp"
// setup() mounts and validates application resources before handing work to
// the dedicated 16 KiB runtime tasks. Match that headroom during boot instead
// of relying on Arduino's smaller 8 KiB loop-task default.
SET_LOOP_TASK_STACK_SIZE(16 * 1024);
using namespace bored::signalscope;
namespace {
constexpr const char* kApSsid = "SignalScope-AP";
constexpr const char* kApPassword = "signalscope";
constexpr size_t kStatusFrameLimit = 40;
constexpr size_t kSignalSnapshotLimit = 384;
constexpr size_t kSignalCatalogDefaultLimit = 48;
constexpr size_t kSignalCatalogMaximumLimit = 96;
constexpr uint32_t kSignalCatalogFreshnessUs = 1500000U;
constexpr size_t kMaxPollFramesPerBus = 128;
constexpr size_t kMaxDecodedSignalsPerFrame = 24;
constexpr size_t kStatusRuleLimit = 48;
constexpr uint32_t kCanHealthPollMs = 100U;
constexpr uint32_t kCanInitialRecoveryRetryMs = 100U;
constexpr uint32_t kMcpRecoveryRetryMs = 5000U;
constexpr uint32_t kTwaiRecoveryRetryMs = 5000U;
constexpr int kBusARxPin = 6;
constexpr int kBusATxPin = 7;
constexpr int kMcpCsPin = 10;
constexpr int kMcpSclkPin = 12;
constexpr int kMcpMosiPin = 11;
constexpr int kMcpMisoPin = 13;
constexpr int kMcpRstPin = 9;
constexpr int kMcpIntPin = 8;
constexpr uint32_t kParkedCanQuietMs = 3U;
constexpr uint32_t kParkedCanQuiesceTimeoutMs = 250U;
constexpr uint32_t kParkedCanHandshakeTimeoutMs = 1500U;
// Keep CAN runtime isolated from UI/server runtime.
// Set false to run both runtime tasks on core 0 (single-core style scheduling).
constexpr bool kUseDualCore = true;
constexpr BaseType_t selectCanCore() {
return (kUseDualCore && (portNUM_PROCESSORS > 1)) ? 1 : 0;
}
constexpr BaseType_t selectUiCore() {
return 0;
}
constexpr bool dualCoreRuntimeEnabled() {
return (kUseDualCore && (portNUM_PROCESSORS > 1));
}
constexpr uint32_t kCanTaskStackBytes = 16384;
constexpr uint32_t kApplicationTaskStackBytes = 16384;
constexpr uint32_t kUiTaskStackBytes = 16384;
constexpr uint32_t kTwaiAlertTaskStackBytes = 3072;
GatewayCore gateway;
CanTraceQueue can_trace;
MutationEngine mutation_engine;
ReplayEngine replay_engine;
FrameCache frame_cache;
SignalCache signal_cache;
ObservationManager observation_manager;
PersistenceStore persistence;
SessionLogRecorder session_log;
ApplicationExtensionRegistry application_registry;
ApplicationServices application_services;
RuntimeValueRegistry runtime_values;
RuntimeTableRegistry runtime_tables;
ParkedPowerController parked_power;
RTC_DATA_ATTR uint32_t parked_deep_sleep_entries = 0U;
DbcDatabase dbc_database;
std::atomic<const DbcDatabase*> active_dbc{nullptr};
WebServer server(80);
MCP2515 can_mcp(kMcpCsPin, 10000000, &SPI);
TaskHandle_t can_task_handle = nullptr;
TaskHandle_t application_task_handle = nullptr;
TaskHandle_t ui_task_handle = nullptr;
TaskHandle_t twai_alert_task_handle = nullptr;
SemaphoreHandle_t application_mutex = nullptr;
SemaphoreHandle_t session_log_mutex = nullptr;
SemaphoreHandle_t replay_mutex = nullptr;
std::atomic<uint8_t> bus_a_ready{0};
std::atomic<uint8_t> bus_b_ready{0};
std::atomic<uint8_t> fs_mounted{0};
std::atomic<uint16_t> frame_rate_fps{0};
std::atomic<uint32_t> ingress_a_frames{0};
std::atomic<uint32_t> ingress_b_frames{0};
std::atomic<uint32_t> can_stack_min_free{0};
std::atomic<uint32_t> application_stack_min_free{0};
std::atomic<uint32_t> ui_stack_min_free{0};
std::atomic<uint32_t> can_runtime_started_us{0};
std::atomic<uint32_t> application_config_ready_us{0};
std::atomic<uint8_t> application_resource_reload_requested{0};
std::atomic<uint8_t> twai_runtime_state{static_cast<uint8_t>(TWAI_STATE_STOPPED)};
std::atomic<uint8_t> twai_driver_installed{0};
std::atomic<uint32_t> twai_recovery_attempts{0};
std::atomic<uint32_t> twai_restarts{0};
std::atomic<uint32_t> twai_rx_missed{0};
std::atomic<uint32_t> twai_rx_overruns{0};
std::atomic<uint8_t> mcp_error_flags{0};
std::atomic<uint32_t> mcp_recoveries{0};
std::atomic<uint32_t> mcp_rx_overruns{0};
std::atomic<uint32_t> last_physical_ingress_ms{0U};
std::atomic<uint8_t> parked_can_quiesce_requested{0U};
std::atomic<uint8_t> parked_can_quiesced{0U};
std::atomic<uint8_t> parked_can_quiesce_failed{0U};
std::atomic<uint8_t> parked_alert_stop_requested{0U};
std::atomic<uint8_t> parked_alert_stopped{0U};
bool twai_recovery_active = false;
uint32_t last_can_health_poll_ms = 0U;
uint32_t last_session_health_ms = 0U;
uint32_t next_twai_recovery_attempt_ms = 0U;
uint32_t next_mcp_recovery_attempt_ms = 0U;
// Formatting a periodic log line can block a USB/UART stream for several CAN
// frame times. The CAN task publishes an atomic snapshot and the lower-priority
// application task performs the actual Serial write.
std::atomic<uint8_t> gateway_log_pending{0};
std::atomic<uint32_t> gateway_log_drops_boot{0};
std::atomic<uint32_t> gateway_log_drops_run{0};
std::atomic<uint32_t> gateway_log_deferred_a_to_b{0};
std::atomic<uint32_t> gateway_log_deferred_b_to_a{0};
std::atomic<uint32_t> gateway_log_egress_a_to_b{0};
std::atomic<uint32_t> gateway_log_egress_b_to_a{0};
std::atomic<uint32_t> gateway_log_passive{0};
std::atomic<uint32_t> gateway_log_decoded{0};
std::atomic<uint32_t> gateway_log_active_rules{0};
std::atomic<uint32_t> gateway_log_stack_free{0};
// HTTP handlers execute serially on ss_ui. Keep their large snapshot buffers
// in runtime memory (PSRAM when available), never on the UI task stack.
RuleListEntry* ui_rule_scratch = nullptr;
FrameCacheSnapshot* ui_frame_scratch = nullptr;
uint16_t* ui_signal_index_scratch = nullptr;
SignalCacheSnapshot* ui_signal_scratch = nullptr;
String ui_index_path = "/index.html";
String active_dbc_path;
String active_rule_package_path;
constexpr const char* kDbcDirPath = "/dbc";
constexpr const char* kActiveDbcPath = "/dbc/active.dbc";
constexpr const char* kRulesDirPath = "/rules";
constexpr const char* kActiveRulePackagePath = "/rules/active.ssrules";
class ApplicationLockGuard {
public:
explicit ApplicationLockGuard(TickType_t wait_ticks = portMAX_DELAY) {
if (application_mutex == nullptr) {
locked_ = true;
return;
}
locked_ = xSemaphoreTakeRecursive(application_mutex, wait_ticks) == pdTRUE;
}
~ApplicationLockGuard() {
release();
}
ApplicationLockGuard(const ApplicationLockGuard&) = delete;
ApplicationLockGuard& operator=(const ApplicationLockGuard&) = delete;
bool locked() const { return locked_; }
void release() {
if (locked_ && application_mutex != nullptr) {
static_cast<void>(xSemaphoreGiveRecursive(application_mutex));
}
locked_ = false;
}
private:
bool locked_ = false;
};
class SessionLogLockGuard {
public:
explicit SessionLogLockGuard(TickType_t wait_ticks = portMAX_DELAY) {
if (session_log_mutex == nullptr) {
locked_ = true;
return;
}
locked_ = xSemaphoreTakeRecursive(session_log_mutex, wait_ticks) == pdTRUE;
}
~SessionLogLockGuard() { release(); }
SessionLogLockGuard(const SessionLogLockGuard&) = delete;
SessionLogLockGuard& operator=(const SessionLogLockGuard&) = delete;
bool locked() const { return locked_; }
void release() {
if (locked_ && session_log_mutex != nullptr) {
static_cast<void>(xSemaphoreGiveRecursive(session_log_mutex));
}
locked_ = false;
}
private:
bool locked_ = false;
};
const char* directionToString(Direction direction) {
return (direction == Direction::A_TO_B) ? "A_TO_B" : "B_TO_A";
}
const char* twaiStateName(uint8_t state) {
switch (static_cast<twai_state_t>(state)) {
case TWAI_STATE_RUNNING: return "running";
case TWAI_STATE_BUS_OFF: return "bus_off";
case TWAI_STATE_RECOVERING: return "recovering";
case TWAI_STATE_STOPPED:
default: return "stopped";
}
}
Direction parseDirectionFromText(const String& text, Direction fallback) {
if (text == "A_TO_B") return Direction::A_TO_B;
if (text == "B_TO_A") return Direction::B_TO_A;
return fallback;
}
const char* observationModeToString(ObservationMode mode) {
switch (mode) {
case ObservationMode::ALL:
return "all";
case ObservationMode::SPECIFIC:
return "specific";
case ObservationMode::NONE:
default:
return "none";
}
}
ObservationMode parseObservationMode(const String& text) {
if (text == "all" || text == "ALL") return ObservationMode::ALL;
if (text == "specific" || text == "SPECIFIC") return ObservationMode::SPECIFIC;
return ObservationMode::NONE;
}
const char* ruleKindToString(RuleKind kind) {
switch (kind) {
case RuleKind::RAW_MASK: return "RAW_MASK";
case RuleKind::COUNTER: return "COUNTER";
case RuleKind::CHECKSUM_XOR: return "CHECKSUM_XOR";
case RuleKind::CHECKSUM_CRC8_AUTOSAR: return "CHECKSUM_CRC8_AUTOSAR";
case RuleKind::SEQUENCE8: return "SEQUENCE8";
case RuleKind::BIT_RANGE:
default: return "BIT_RANGE";
}
}
bool parseBoolText(const String& text, bool fallback) {
if (text == "1" || text == "true" || text == "TRUE" || text == "on") return true;
if (text == "0" || text == "false" || text == "FALSE" || text == "off") return false;
return fallback;
}
bool tryParseUIntArg(const char* name, uint32_t& output) {
if (!server.hasArg(name)) return false;
const String text = server.arg(name);
if (text.length() == 0U || text[0] == '-') return false;
char* end_ptr = nullptr;
const unsigned long long value = std::strtoull(text.c_str(), &end_ptr, 0);
if (end_ptr == text.c_str() || *end_ptr != '\0' || value > 0xFFFFFFFFULL) return false;
output = static_cast<uint32_t>(value);
return true;
}
uint32_t parseUIntArg(const char* name, uint32_t fallback) {
uint32_t value = 0U;
return tryParseUIntArg(name, value) ? value : fallback;
}
bool tryParseUInt64Arg(const char* name, uint64_t& output) {
if (!server.hasArg(name)) return false;
const String text = server.arg(name);
if (text.length() == 0U || text[0] == '-') return false;
char* end_ptr = nullptr;
const unsigned long long value = std::strtoull(text.c_str(), &end_ptr, 0);
if (end_ptr == text.c_str() || *end_ptr != '\0') return false;
output = static_cast<uint64_t>(value);
return true;
}
int32_t parseIntArg(const char* name, int32_t fallback) {
if (!server.hasArg(name)) return fallback;
const String text = server.arg(name);
if (text.length() == 0U) return fallback;
char* end_ptr = nullptr;
const long value = std::strtol(text.c_str(), &end_ptr, 0);
if (end_ptr == text.c_str() || *end_ptr != '\0') return fallback;
return static_cast<int32_t>(value);
}
String uint64ToDecimalString(uint64_t value) {
char text[24] = {};
std::snprintf(text, sizeof(text), "%llu", static_cast<unsigned long long>(value));
return String(text);
}
float parseFloatArg(const char* name, float fallback) {
if (!server.hasArg(name)) return fallback;
return server.arg(name).toFloat();
}
String contentTypeForPath(const String& path) {
if (path.endsWith(".html")) return "text/html";
if (path.endsWith(".css")) return "text/css";
if (path.endsWith(".js")) return "application/javascript";
if (path.endsWith(".json")) return "application/json";
if (path.endsWith(".png")) return "image/png";
if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return "image/jpeg";
if (path.endsWith(".svg")) return "image/svg+xml";
if (path.endsWith(".woff")) return "font/woff";
if (path.endsWith(".woff2")) return "font/woff2";
if (path.endsWith(".ico")) return "image/x-icon";
return "application/octet-stream";
}
String escapeJsonString(const char* input) {
String out;
if (input == nullptr) return out;
for (size_t i = 0; input[i] != '\0'; ++i) {
const char c = input[i];
switch (c) {
case '\\':
out += "\\\\";
break;
case '"':
out += "\\\"";
break;
case '\n':
out += "\\n";
break;
case '\r':
out += "\\r";
break;
case '\t':
out += "\\t";
break;
default:
out += (static_cast<unsigned char>(c) < 0x20U) ? ' ' : c;
break;
}
}
return out;
}
void resolveUiIndexPath() {
ui_index_path = LittleFS.exists("/index.html") ? "/index.html" : "/index.htm";
}
bool loadDbcFromFilePath(const String& fs_path) {
DbcDatabase candidate_database;
SignalCache candidate_cache;
candidate_cache.init();
size_t source_bytes = 0U;
bool candidate_loaded = false;
const ApplicationExtension* const app = application_registry.extension();
if (app != nullptr && app->loadDatabase != nullptr) {
const ApplicationDatabaseLoadResult result =
app->loadDatabase(fs_path.c_str(), &candidate_database, &source_bytes);
if (result == ApplicationDatabaseLoadResult::FAILED) return false;
candidate_loaded = result == ApplicationDatabaseLoadResult::LOADED;
}
String dbc_text;
if (!candidate_loaded) {
if (fs_mounted.load(std::memory_order_acquire) == 0U || !LittleFS.exists(fs_path)) {
return false;
}
File file = LittleFS.open(fs_path, "r");
if (!file || file.isDirectory()) {
if (file) file.close();
return false;
}
dbc_text = file.readString();
file.close();
if (dbc_text.length() == 0U ||
!candidate_database.parseFromText(
dbc_text.c_str(), static_cast<size_t>(dbc_text.length()))) {
return false;
}
source_bytes = static_cast<size_t>(dbc_text.length());
}
if (!candidate_cache.resetForDbc(candidate_database)) {
return false;
}
gateway.pauseSignalDecoding();
const uint32_t wait_started_ms = millis();
while (!gateway.signalDecodingIdle() && millis() - wait_started_ms < 250U) {
vTaskDelay(pdMS_TO_TICKS(1));
}
if (!gateway.signalDecodingIdle()) {
gateway.resumeSignalDecoding();
return false;
}
dbc_database.swap(candidate_database);
signal_cache.swap(candidate_cache);
active_dbc.store(&dbc_database, std::memory_order_release);
signal_cache.clearSubscriptions();
observation_manager.clearSpecific();
observation_manager.clearMandatory();
observation_manager.setMode(ObservationMode::NONE);
if (replay_mutex == nullptr || xSemaphoreTake(replay_mutex, pdMS_TO_TICKS(250)) == pdTRUE) {
replay_engine.stop();
if (replay_mutex != nullptr) xSemaphoreGive(replay_mutex);
}
mutation_engine.clearRules();
active_rule_package_path = "";
active_dbc_path = fs_path;
if (app != nullptr && app->databaseChanged != nullptr) {
ApplicationLockGuard app_lock;
if (app_lock.locked()) app->databaseChanged();
}
gateway.resumeSignalDecoding();
Serial.printf(
"[dbc] auto-loaded %s (%lu bytes, %lu msgs, %lu signals)\n",
fs_path.c_str(),
static_cast<unsigned long>(source_bytes),
static_cast<unsigned long>(dbc_database.messageCount()),
static_cast<unsigned long>(dbc_database.signalCount()));
constexpr uint32_t kDecodeProbeIds[] = {0x1A0U, 0x280U, 0x2A0U, 0x38AU, 0x4A0U};
Serial.print("[dbc] lookup probes");
for (const uint32_t can_id : kDecodeProbeIds) {
const DbcMessageDef* probe = dbc_database.findMessage(can_id);
Serial.printf(" 0x%03lX=%s", static_cast<unsigned long>(can_id),
probe == nullptr ? "MISS" : probe->name);
}
Serial.println();
return true;
}
bool autoLoadDbcFromLittleFs() {
if (fs_mounted.load(std::memory_order_acquire) == 0U) return false;
constexpr const char* kPreferredPaths[] = {
"/dbc/active.dbc",
"/dbc/default.dbc",
};
for (const char* path : kPreferredPaths) {
if (loadDbcFromFilePath(path)) return true;
}
File dir = LittleFS.open("/dbc");
if (!dir || !dir.isDirectory()) {
if (dir) dir.close();
return false;
}
File entry = dir.openNextFile();
while (entry) {
const bool is_dir = entry.isDirectory();
String name = entry.name();
entry.close();
if (!is_dir) {
String lower = name;
lower.toLowerCase();
if (lower.endsWith(".dbc")) {
if (!name.startsWith("/")) {
name = String("/dbc/") + name;
}
if (loadDbcFromFilePath(name)) {
dir.close();
return true;
}
}
}
entry = dir.openNextFile();
}
dir.close();
return false;
}
bool applyApplicationDatabaseRequest() {
const ApplicationExtension* app = application_registry.extension();
if (app == nullptr || app->requestedDatabasePath == nullptr) return true;
const char* requested = app->requestedDatabasePath();
if (requested == nullptr || requested[0] == '\0') return true;
if (active_dbc_path == requested) return true;
return loadDbcFromFilePath(String(requested));
}
bool validRulePackagePath(const String& path) {
return path.length() > 15U && path.length() <= 96U &&
path.startsWith("/rules/") && path.indexOf("..") < 0 &&
path.indexOf("/.") < 0 && path.indexOf('\\') < 0 &&
path.indexOf("//") < 0 && path.endsWith(".ssrules");
}
bool loadRulePackageFromFilePath(const String& path) {
if (active_rule_package_path == path) return true;
if (!validRulePackagePath(path)) return false;
if (fs_mounted.load(std::memory_order_acquire) == 0U || !LittleFS.exists(path)) return false;
File file = LittleFS.open(path, "r");
if (!file || file.isDirectory()) { if (file) file.close(); return false; }
String text = file.readString();
file.close();
if (text.length() == 0U) return false;
char* mutable_text = static_cast<char*>(std::malloc(text.length() + 1U));
if (mutable_text == nullptr) return false;
std::memcpy(mutable_text, text.c_str(), text.length() + 1U);
size_t loaded = 0U;
const bool ok = RulePackageLoader::loadCsv(mutable_text, text.length(), mutation_engine, &loaded);
std::free(mutable_text);
if (!ok) return false;
active_rule_package_path = path;
Serial.printf("[rules] loaded %s (%lu rules)\n", path.c_str(), static_cast<unsigned long>(loaded));
return true;
}
bool autoLoadRulePackageFromLittleFs() {
if (loadRulePackageFromFilePath(kActiveRulePackagePath)) return true;
const String default_path = String(kRulesDirPath) + "/default.ssrules";
if (loadRulePackageFromFilePath(default_path)) return true;
return false;
}
bool applyApplicationRulePackageRequest() {
const ApplicationExtension* app = application_registry.extension();
if (app == nullptr || app->requestedRulePackagePath == nullptr) return true;
const char* requested = app->requestedRulePackagePath();
if (requested == nullptr || requested[0] == '\0') {
if (active_rule_package_path.length() == 0U) return true;
mutation_engine.clearRules();
active_rule_package_path = "";
return true;
}
return loadRulePackageFromFilePath(String(requested));
}
enum class ApplicationResourceApplyResult : uint8_t {
OK,
DATABASE_FAILED,
RULE_PACKAGE_FAILED,
};
// Caller holds application_mutex. Manual DBC replacement and structural
// generic-rule replacement intentionally remain available to expert
// SignalScope users, but they are no longer an application-owned resource
// transaction.
void invalidateApplicationResourcesLocked() {
const ApplicationExtension* app = application_registry.extension();
if (app != nullptr && app->finishConfigure != nullptr) {
app->finishConfigure(false);
}
}
ApplicationResourceApplyResult applyApplicationResourceTransaction() {
const ApplicationExtension* app = application_registry.extension();
const bool database_ok = applyApplicationDatabaseRequest();
const bool rules_ok = database_ok && applyApplicationRulePackageRequest();
const bool resources_ok = database_ok && rules_ok;
if (app != nullptr && app->finishConfigure != nullptr) {
app->finishConfigure(resources_ok);
}
if (!resources_ok) {
// finishConfigure(false) restores the application's previous resource
// selection. If the first half of the staged transaction had already
// become active, put both resources back together before returning.
const bool rollback_database_ok = applyApplicationDatabaseRequest();
const bool rollback_rules_ok = applyApplicationRulePackageRequest();
if (!rollback_database_ok || !rollback_rules_ok) {
Serial.println("[app] configuration resource rollback failed");
}
if (app != nullptr && app->finishConfigure != nullptr) {
app->finishConfigure(rollback_database_ok && rollback_rules_ok);
}
}
if (!database_ok) return ApplicationResourceApplyResult::DATABASE_FAILED;
if (!rules_ok) return ApplicationResourceApplyResult::RULE_PACKAGE_FAILED;
return ApplicationResourceApplyResult::OK;
}
void applyRequestedApplicationResources() {
if (application_resource_reload_requested.exchange(0U, std::memory_order_acq_rel) == 0U) return;
const ApplicationResourceApplyResult result = applyApplicationResourceTransaction();
if (result == ApplicationResourceApplyResult::DATABASE_FAILED) {
Serial.println("[app] deferred requested DBC could not be loaded");
} else if (result == ApplicationResourceApplyResult::RULE_PACKAGE_FAILED) {
Serial.println("[app] deferred requested rule package could not be loaded");
}
}
bool isPublicStaticPath(const String& path) {
if (path.length() == 0U || !path.startsWith("/") ||
path.indexOf("..") >= 0 || path.indexOf('\\') >= 0) {
return false;
}
if (path == "/" || path == "/index.html" || path == "/index.htm" ||
path == "/LICENSE.md") {
return true;
}
if (path.startsWith("/assets/")) return true;
// Only presentation routes are public. DBCs, rule packages, diagnostic
// sources, logs and any future application-private LittleFS files must be
// accessed through their bounded API rather than the static-file fallback.
// Multi-page starter apps can keep public presentation files under this
// explicit root without exposing databases, rules, recordings or other
// application data stored elsewhere on LittleFS.
if (path.startsWith("/pages/") &&
(path.endsWith(".html") || path.endsWith(".css") || path.endsWith(".js"))) return true;
return false;
}
bool serveStaticFile(const String& path) {
if (fs_mounted.load(std::memory_order_acquire) == 0U) return false;
if (!isPublicStaticPath(path)) return false;
String fs_path = (path == "/") ? ui_index_path : path;
if (fs_path == SessionLogRecorder::kLogPath ||
fs_path == SessionLogRecorder::kTemporaryPath ||
fs_path == SessionLogRecorder::kBackupPath ||
fs_path == SessionLogRecorder::kCheckpointPath0 ||
fs_path == SessionLogRecorder::kCheckpointPath1) {
return false;
}
bool gzip_encoded = false;
if (!LittleFS.exists(fs_path) && !fs_path.endsWith("/")) {
const String maybe_index = fs_path + "/index.html";
if (LittleFS.exists(maybe_index)) fs_path = maybe_index;
}
// Public UI assets may be stored once in deterministic gzip form.
if (!LittleFS.exists(fs_path) && !fs_path.endsWith("/")) {
const String compressed = fs_path + ".gz";
if (LittleFS.exists(compressed)) {
fs_path = compressed;
gzip_encoded = true;
}
}
if (!LittleFS.exists(fs_path)) return false;
File file = LittleFS.open(fs_path, "r");
if (!file) return false;
const String content_path = gzip_encoded
? fs_path.substring(0U, fs_path.length() - 3U)
: fs_path;
if (content_path.endsWith(".html") || content_path.endsWith(".js") || content_path.endsWith(".json")) {
server.sendHeader("Cache-Control", "no-store, no-cache, must-revalidate");
server.sendHeader("Pragma", "no-cache");
}
if (gzip_encoded) {
// WebServer::_streamFileCore derives Content-Encoding from the File
// name's .gz suffix. Adding it here too produces two gzip codings and
// browsers attempt to decompress the single gzip envelope twice.
server.sendHeader("Vary", "Accept-Encoding");
}
server.streamFile(file, contentTypeForPath(content_path));
file.close();
return true;
}
String frameDataHex(const FrameCacheSnapshot& frame) {
String out;
out.reserve(24);
for (uint8_t i = 0; i < frame.dlc && i < 8U; ++i) {
if (i > 0U) out += ' ';
char byte_text[3] = {0};
std::snprintf(byte_text, sizeof(byte_text), "%02X", frame.data[i]);
out += byte_text;
}
return out;
}
bool parseHexNibble(char c, uint8_t& out_value) {
if (c >= '0' && c <= '9') {
out_value = static_cast<uint8_t>(c - '0');
return true;
}
if (c >= 'A' && c <= 'F') {
out_value = static_cast<uint8_t>(10 + (c - 'A'));
return true;
}
if (c >= 'a' && c <= 'f') {
out_value = static_cast<uint8_t>(10 + (c - 'a'));
return true;
}
return false;
}
bool parseHexBytes(const String& text, uint8_t out_bytes[8]) {
char hex[32] = {0};
size_t n = 0U;
for (size_t i = 0; i < text.length() && n < sizeof(hex); ++i) {
uint8_t nibble = 0U;
if (parseHexNibble(text[i], nibble)) hex[n++] = text[i];
}
if (n < 16U) return false;
for (uint8_t i = 0; i < 8U; ++i) {
uint8_t hi = 0U;
uint8_t lo = 0U;
if (!parseHexNibble(hex[i * 2U], hi) || !parseHexNibble(hex[(i * 2U) + 1U], lo)) return false;
out_bytes[i] = static_cast<uint8_t>((hi << 4U) | lo);
}
return true;
}
size_t parseU16Csv(const String& csv, uint16_t* out_values, size_t capacity) {
if (out_values == nullptr || capacity == 0U) return 0U;
size_t count = 0U;
int start = 0;
while (start < csv.length() && count < capacity) {
int end = csv.indexOf(',', start);
if (end < 0) end = csv.length();
String token = csv.substring(start, end);
token.trim();
if (token.length() > 0) {
char* end_ptr = nullptr;
const unsigned long value = std::strtoul(token.c_str(), &end_ptr, 0);
if (end_ptr != token.c_str() && value <= 0xFFFFUL) out_values[count++] = static_cast<uint16_t>(value);
}
start = end + 1;
}
return count;
}
size_t parseObservationCsv(const String& csv, ObservationKey* out_keys, size_t capacity) {
if (out_keys == nullptr || capacity == 0U) return 0U;
size_t count = 0U;
int start = 0;
while (start < csv.length() && count < capacity) {
int end = csv.indexOf(',', start);
if (end < 0) end = csv.length();
String token = csv.substring(start, end);
token.trim();
if (token.length() > 0) {
int sep = token.indexOf(':');
String id_text = (sep >= 0) ? token.substring(0, sep) : token;
String dir_text = (sep >= 0) ? token.substring(sep + 1) : "A_TO_B";
char* end_ptr = nullptr;
const unsigned long can_id = std::strtoul(id_text.c_str(), &end_ptr, 0);
if (end_ptr != id_text.c_str()) {
out_keys[count].can_id = static_cast<uint32_t>(can_id);
out_keys[count].direction = parseDirectionFromText(dir_text, Direction::A_TO_B);
++count;
}
}
start = end + 1;
}
return count;
}
bool bodyContains(const String& body, const char* token) {
return body.indexOf(token) >= 0;
}
bool findRuleIdByIdentity(uint32_t can_id, Direction direction, uint16_t start_bit, uint8_t bit_length, uint16_t& out_rule_id);
bool findRuleIdByRawIdentity(uint32_t can_id, Direction direction, uint16_t& out_rule_id);
// API handlers
void handleStatus();
void handleFrameCache();
void handleSignalCache();
void handleSignalCatalog();
void handleObserve();
void handleRuleStage();
void handleRulesAction();
void handleRulesList();
void handleRuleValue();
void handleRuleEnable();
void handleRulePackageRead();
void handleRulePackageWrite();
void handleRulePackageSelect();
void handleReplayLoad();
void handleReplayControl();
void handleReplaySend();
void handleDbcUpload();
void handleDbcAutoload();
void handleDbcSelect();
void handleNotFound();
void configureHttpServer();
void startAccessPoint();
bool initBusA();
bool initBusB();
bool readBusA(CanFrame& out_frame);
bool readBusB(CanFrame& out_frame);
bool writeBusA(const CanFrame& frame);
bool writeBusB(const CanFrame& frame);
bool txDriver(Direction tx_direction, const CanFrame& frame);
bool diagnosticTxDriver(Direction tx_direction, const CanFrame& frame);
bool replayTxBridge(const CanFrame& frame, ReplayDispatchMode dispatch_mode);
void pollCanIngress();
void monitorCanHealth(uint32_t now_ms);
void publishGatewayLogSnapshot();
void flushGatewayLogSnapshot();
void initializeParkedPower();
bool performParkedPowerBootProbe();
bool parkedPowerHostBusy();
void monitorParkedPower(uint32_t now_ms, bool host_busy, bool application_busy);
bool enterParkedSleep(ParkedPowerDecision decision);
void handleParkedCanQuiesce(uint32_t now_ms);
void canRuntimeTask(void* context);
void twaiAlertTask(void* context);
void uiRuntimeTask(void* context);
} // namespace
namespace {
bool recoveryDeadlineReached(uint32_t now_ms, uint32_t deadline_ms) {
return static_cast<int32_t>(now_ms - deadline_ms) >= 0;
}
bool setBusAReady(bool ready) {
const uint8_t next = ready ? 1U : 0U;
const uint8_t previous = bus_a_ready.exchange(next, std::memory_order_acq_rel);
if (previous == next) return false;
// B_TO_A frames are waiting to transmit onto Bus A. Discard them both when
// that destination disappears and immediately before a recovered bus is
// allowed to transmit, so old counters/control values cannot burst later.
gateway.purgeDirection(Direction::B_TO_A);
return true;
}
bool setBusBReady(bool ready) {
const uint8_t next = ready ? 1U : 0U;
const uint8_t previous = bus_b_ready.exchange(next, std::memory_order_acq_rel);
if (previous == next) return false;
// A_TO_B frames target the MCP2515 side and have the same stale-on-recovery
// contract as Bus A traffic above.
gateway.purgeDirection(Direction::A_TO_B);
return true;
}
[[noreturn]] void failCanRuntimeStartup(const char* reason) {
Serial.printf("[runtime] fatal CAN runtime startup failure: %s; restarting\n",
reason == nullptr ? "unknown" : reason);
// Never present a healthy UI while the physical bridge has no owner. A
// restart retries the early, allocation-light CAN startup from a clean
// state and is safer than leaving both vehicle segments disconnected.
esp_restart();
for (;;) delay(1000);
}
bool initBusA() {
// Deep-sleep EXT0 leaves the RX pad under RTC control. Relinquish it before
// TWAI claims the pin again on every CAN/timer wake reset.
rtc_gpio_deinit(static_cast<gpio_num_t>(kBusARxPin));
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(
static_cast<gpio_num_t>(kBusATxPin),
static_cast<gpio_num_t>(kBusARxPin),
TWAI_MODE_NORMAL);
twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
g_config.tx_queue_len = 64;
g_config.rx_queue_len = 128;
esp_err_t err = ESP_OK;
if (twai_driver_installed.load(std::memory_order_acquire) == 0U) {
err = twai_driver_install(&g_config, &t_config, &f_config);
if (err != ESP_OK) {
Serial.printf("[can-a] driver install failed: %s\n", esp_err_to_name(err));
return false;
}
twai_driver_installed.store(1U, std::memory_order_release);
}
err = twai_start();
if (err != ESP_OK) {
Serial.printf("[can-a] start failed: %s\n", esp_err_to_name(err));
return false;
}
twai_runtime_state.store(static_cast<uint8_t>(TWAI_STATE_RUNNING), std::memory_order_release);
twai_recovery_active = false;
Serial.println("[can-a] TWAI started on pins TX=7 RX=6 @500kbps");
return true;
}
constexpr uint32_t twaiWakeAlerts() {
return TWAI_ALERT_RX_DATA | TWAI_ALERT_RX_QUEUE_FULL | TWAI_ALERT_BUS_OFF |
TWAI_ALERT_RECOVERY_IN_PROGRESS | TWAI_ALERT_BUS_RECOVERED |
TWAI_ALERT_ABOVE_ERR_WARN | TWAI_ALERT_ERR_PASS;
}
void configureTwaiWakeAlerts() {
if (twai_driver_installed.load(std::memory_order_acquire) == 0U) return;
uint32_t pending = 0U;
static_cast<void>(twai_reconfigure_alerts(twaiWakeAlerts(), &pending));
}
void ARDUINO_ISR_ATTR notifyCanTaskFromMcp() {
BaseType_t higher_priority_task_woken = pdFALSE;
TaskHandle_t task = can_task_handle;
if (task != nullptr) vTaskNotifyGiveFromISR(task, &higher_priority_task_woken);
if (higher_priority_task_woken == pdTRUE) portYIELD_FROM_ISR();
}
void twaiAlertTask(void* /*context*/) {
for (;;) {
if (parked_alert_stop_requested.load(std::memory_order_acquire) != 0U) break;
uint32_t alerts = 0U;
if (twai_driver_installed.load(std::memory_order_acquire) != 0U &&
twai_read_alerts(&alerts, pdMS_TO_TICKS(50)) == ESP_OK) {
if (can_task_handle != nullptr) xTaskNotifyGive(can_task_handle);
} else {
vTaskDelay(pdMS_TO_TICKS(10));
}
}
parked_alert_stopped.store(1U, std::memory_order_release);
if (can_task_handle != nullptr) xTaskNotifyGive(can_task_handle);
vTaskSuspend(nullptr);
}
bool initBusB() {
pinMode(kMcpRstPin, OUTPUT);
digitalWrite(kMcpRstPin, HIGH);
delay(10);
digitalWrite(kMcpRstPin, LOW);
delay(10);
digitalWrite(kMcpRstPin, HIGH);
delay(10);
SPI.begin(kMcpSclkPin, kMcpMisoPin, kMcpMosiPin, kMcpCsPin);
if (can_mcp.reset() != MCP2515::ERROR_OK) {
Serial.println("[can-b] MCP2515 reset failed");
return false;
}
if (can_mcp.setBitrate(CAN_500KBPS) != MCP2515::ERROR_OK) {
Serial.println("[can-b] MCP2515 bitrate set failed");
return false;
}
if (can_mcp.setNormalMode() != MCP2515::ERROR_OK) {
Serial.println("[can-b] MCP2515 normal mode failed");
return false;
}
mcp_error_flags.store(0U, std::memory_order_release);
Serial.println("[can-b] MCP2515 started @500kbps");
return true;
}
bool readBusA(CanFrame& out_frame) {
twai_message_t rx = {};
if (twai_receive(&rx, 0) != ESP_OK) return false;