-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPathShield.ino
More file actions
2104 lines (1792 loc) · 60.9 KB
/
PathShield.ino
File metadata and controls
2104 lines (1792 loc) · 60.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 <M5Unified.h>
#include <NimBLEDevice.h>
#include "MacPrefixes.h"
#include <algorithm>
#include <SPIFFS.h>
#include <WiFi.h>
#include <esp_task_wdt.h>
#define SCREEN_WIDTH 240
#define SCREEN_HEIGHT 135
#define DEFAULT_SCREEN_TIMEOUT 30000
// Memory constants — scaled at runtime based on free heap
#define MIN_DEVICES 25
#define MAX_DEVICES_CAP 70
#define MIN_WIFI_DEVICES 25
#define MAX_WIFI_DEVICES_CAP 50
#define DETECTION_WINDOW 300
#define IDLE_TIMEOUT 30000
#define MAX_TIMESTAMPS 20
// Runtime device limits (set dynamically at boot based on free heap)
int maxDevices = MIN_DEVICES;
int maxWifiDevices = MIN_WIFI_DEVICES;
bool hasPsram = false;
#define BLUE_GREY 0x5D9B
#define WIFI_NAME_COLOR GREEN
#define BLE_NAME_COLOR CYAN
#define WINDOW_RECENT 300
#define WINDOW_MEDIUM 600
#define WINDOW_OLD 900
#define WINDOW_OLDEST 1200
#define MIN_DETECTIONS 12
#define MIN_WINDOWS 3
#define PERSISTENCE_THRESHOLD 0.75
#define RSSI_STABILITY_THRESHOLD 10
#define RSSI_VARIATION_THRESHOLD 15
#define EPSILON_CONNECTED_GAP 180
#define MIN_RSSI_RANGE 12
#define RSSI_FLOOR -80
#define ESTIMATED_APP_RESERVE_KB 40
const int MEMORY_CRITICAL = 50;
const int MEMORY_WARNING = 80;
const int MEMORY_GOOD = 150;
unsigned long lastBtnAPress = 0;
unsigned long lastBtnBPress = 0;
unsigned long lastComboCheck = 0;
const unsigned long DEBOUNCE_DELAY = 200;
bool inMenu = false;
int menuIndex = 0;
int menuBaseY = 0;
bool highBrightness = true;
bool currentlyBright = true;
bool paused = false;
bool filterByName = false;
bool screenDimmed = false;
unsigned long lastButtonPressTime = 0;
unsigned long lastActivityTime = 0;
bool screenOn = true;
unsigned long screenTimeoutMs = DEFAULT_SCREEN_TIMEOUT;
volatile bool deviceDataChanged = false;
static uint32_t lastStateHash = 0;
unsigned long lastDisplayRender = 0;
unsigned long lastMenuRender = 0;
bool alertActive = false;
unsigned long alertStartTime = 0;
const unsigned long ALERT_DURATION = 5000;
struct WiFiDeviceInfo {
char ssid[33];
char bssid[18];
int rssi;
int channel;
int encryptionType;
unsigned long lastSeen;
int detectionCount;
};
WiFiDeviceInfo *wifiDevices = NULL;
int wifiDeviceIndex = 0;
bool scanningWiFi = true;
unsigned long lastScanSwitch = 0;
const unsigned long SCAN_SWITCH_INTERVAL = 3000;
// Privacy Invader Defaults: Axon cameras, Liteon Technology (Flock), Utility Inc (Flock) OUIs
const char *specialMacs[] = {"00:25:DF", "14:5A:FC", "00:09:BC"};
// BLE Tracker Type Detection
enum TrackerType : uint8_t {
TRACKER_NONE = 0,
TRACKER_AIRTAG,
TRACKER_TILE,
TRACKER_SMARTTAG,
TRACKER_CHIPOLO,
TRACKER_GOOGLE_FMDN,
TRACKER_PRIVACY_INVADER,
TRACKER_PERSISTENCE
};
const char* trackerTypeName(uint8_t type) {
switch (type) {
case TRACKER_AIRTAG: return "AirTag";
case TRACKER_TILE: return "Tile";
case TRACKER_SMARTTAG: return "SmartTag";
case TRACKER_CHIPOLO: return "Chipolo";
case TRACKER_GOOGLE_FMDN: return "Google FMDN";
case TRACKER_PRIVACY_INVADER:return "Privacy Inv";
case TRACKER_PERSISTENCE: return "Persistence";
default: return "Unknown";
}
}
// IGNORE LIST: Add MAC prefixes of YOUR devices here to ignore them
// Example: const char *allowlistMacs[] = {"AA:BB:CC", "DD:EE:FF", "11:22:33"};
// Leave as {""} to track all devices
const char *allowlistMacs[] = {""};
struct TimeWindow {
unsigned long start;
unsigned long end;
int detections;
};
struct DeviceInfo {
char address[18];
char name[21];
char manufacturer[31];
int totalCount;
unsigned long firstSeen;
unsigned long lastSeen;
int rssiSum;
int rssiCount;
int lastRssi;
int minRssi;
int maxRssi;
bool detected;
bool isSpecial;
bool alertTriggered;
int stableRssiCount;
int variationCount;
float persistenceScore;
TimeWindow windows[4];
unsigned long timestamps[MAX_TIMESTAMPS];
uint8_t tsIdx;
uint8_t tsCount;
uint8_t trackerType;
};
DeviceInfo *trackedDevices = NULL;
int deviceIndex = 0;
void updateTimeWindows(DeviceInfo &device, unsigned long currentTime);
float calculatePersistenceScore(DeviceInfo &device, unsigned long currentTime);
NimBLEScan *pBLEScan;
int scrollIndex = 0;
// Known device ring buffer — compact storage for stable-RSSI devices
#define MIN_KNOWN 40
#define MAX_KNOWN_CAP 80
#define KNOWN_PROMOTE_COUNT 8
#define KNOWN_RSSI_DRIFT 20
#define KNOWN_EXPIRY_WINDOW (DETECTION_WINDOW * 2)
struct KnownDevice {
char address[18];
unsigned long lastSeen;
int avgRssi;
uint8_t seenCount;
};
KnownDevice *knownDevices = NULL;
int knownDeviceCount = 0;
int maxKnownDevices = MIN_KNOWN;
SemaphoreHandle_t deviceMutex = NULL;
TaskHandle_t scanTaskHandle = NULL;
volatile bool scanTaskRunning = true;
uint32_t initialFreeHeapKB = 40; // Set after allocations in setup()
class MyScanCallbacks : public NimBLEScanCallbacks {
void onResult(const NimBLEAdvertisedDevice* advertisedDevice) override {}
};
bool isSpecialMac(const char *address) {
for (size_t i = 0; i < sizeof(specialMacs) / sizeof(specialMacs[0]); i++) {
if (strncmp(address, specialMacs[i], strlen(specialMacs[i])) == 0) {
return true;
}
}
return false;
}
bool isAllowlistedMac(const char *address) {
for (size_t i = 0; i < sizeof(allowlistMacs) / sizeof(allowlistMacs[0]); i++) {
if (strlen(allowlistMacs[i]) > 0 &&
strncmp(address, allowlistMacs[i], strlen(allowlistMacs[i])) == 0) {
return true;
}
}
return false;
}
// Detect known BLE tracker types from advertisement data
uint8_t detectTrackerType(const NimBLEAdvertisedDevice &device) {
// Check manufacturer data (company ID is first 2 bytes, little-endian)
if (device.haveManufacturerData()) {
std::string mfgData = device.getManufacturerData();
if (mfgData.length() >= 2) {
uint16_t companyId = (uint8_t)mfgData[0] | ((uint8_t)mfgData[1] << 8);
// Apple AirTag: company ID 0x004C with 25+ bytes of payload after company ID
// Also catches Find My network accessories (Chipolo ONE Spot, Eufy in FM mode)
if (companyId == 0x004C && mfgData.length() >= 27) {
// AirTag/Find My devices have specific payload type byte at offset 2
uint8_t payloadType = (uint8_t)mfgData[2];
if (payloadType == 0x12 || payloadType == 0x07) {
return TRACKER_AIRTAG;
}
}
// Samsung SmartTag: company ID 0x0075
if (companyId == 0x0075) {
return TRACKER_SMARTTAG;
}
// Chipolo (native mode, not Find My): company ID 0x0133
if (companyId == 0x0133) {
return TRACKER_CHIPOLO;
}
// Google Find My Device Network: company ID 0x00E0
if (companyId == 0x00E0) {
return TRACKER_GOOGLE_FMDN;
}
}
}
// Check service UUIDs
if (device.haveServiceUUID()) {
// Tile: service UUID 0xFD51 or 0xFD52
if (device.isAdvertisingService(NimBLEUUID((uint16_t)0xFD51)) ||
device.isAdvertisingService(NimBLEUUID((uint16_t)0xFD52))) {
return TRACKER_TILE;
}
// Samsung SmartThings/Find: service UUID 0xFD6F
if (device.isAdvertisingService(NimBLEUUID((uint16_t)0xFD6F))) {
return TRACKER_SMARTTAG;
}
}
// Check device name as fallback
std::string devName = device.getName();
if (devName.length() > 0) {
// Convert to lowercase for comparison
char nameLower[21];
size_t len = std::min(devName.length(), (size_t)20);
for (size_t i = 0; i < len; i++) {
nameLower[i] = tolower(devName[i]);
}
nameLower[len] = '\0';
if (strstr(nameLower, "tile")) return TRACKER_TILE;
if (strstr(nameLower, "smarttag")) return TRACKER_SMARTTAG;
if (strstr(nameLower, "chipolo")) return TRACKER_CHIPOLO;
}
return TRACKER_NONE;
}
void trackWiFiDevice(const char *ssid, const char *bssid, int rssi, int channel,
int encType, unsigned long currentTime) {
for (int i = 0; i < wifiDeviceIndex; i++) {
if (strcmp(wifiDevices[i].bssid, bssid) == 0) {
wifiDevices[i].rssi = rssi;
wifiDevices[i].lastSeen = currentTime;
wifiDevices[i].detectionCount++;
return;
}
}
if (wifiDeviceIndex < maxWifiDevices) {
strncpy(wifiDevices[wifiDeviceIndex].ssid, ssid, 32);
wifiDevices[wifiDeviceIndex].ssid[32] = '\0';
strncpy(wifiDevices[wifiDeviceIndex].bssid, bssid, 17);
wifiDevices[wifiDeviceIndex].bssid[17] = '\0';
wifiDevices[wifiDeviceIndex].rssi = rssi;
wifiDevices[wifiDeviceIndex].channel = channel;
wifiDevices[wifiDeviceIndex].encryptionType = encType;
wifiDevices[wifiDeviceIndex].lastSeen = currentTime;
wifiDevices[wifiDeviceIndex].detectionCount = 1;
wifiDeviceIndex++;
} else {
int oldestIndex = -1;
unsigned long oldestTime = currentTime;
for (int i = 0; i < wifiDeviceIndex; i++) {
if (wifiDevices[i].lastSeen < oldestTime) {
oldestTime = wifiDevices[i].lastSeen;
oldestIndex = i;
}
}
if (oldestIndex != -1) {
strncpy(wifiDevices[oldestIndex].ssid, ssid, 32);
wifiDevices[oldestIndex].ssid[32] = '\0';
strncpy(wifiDevices[oldestIndex].bssid, bssid, 17);
wifiDevices[oldestIndex].bssid[17] = '\0';
wifiDevices[oldestIndex].rssi = rssi;
wifiDevices[oldestIndex].channel = channel;
wifiDevices[oldestIndex].encryptionType = encType;
wifiDevices[oldestIndex].lastSeen = currentTime;
wifiDevices[oldestIndex].detectionCount = 1;
}
}
}
void removeOldWiFiEntries(unsigned long currentTime) {
for (int i = 0; i < wifiDeviceIndex; i++) {
if (currentTime - wifiDevices[i].lastSeen > DETECTION_WINDOW) {
for (int j = i; j < wifiDeviceIndex - 1; j++) {
wifiDevices[j] = wifiDevices[j + 1];
}
wifiDeviceIndex--;
i--;
}
}
}
void updateTimeWindows(DeviceInfo &device, unsigned long currentTime) {
device.windows[0].start =
currentTime >= WINDOW_RECENT ? currentTime - WINDOW_RECENT : 0;
device.windows[0].end = currentTime;
device.windows[1].start =
currentTime >= WINDOW_MEDIUM ? currentTime - WINDOW_MEDIUM : 0;
device.windows[1].end = device.windows[0].start;
device.windows[2].start =
currentTime >= WINDOW_OLD ? currentTime - WINDOW_OLD : 0;
device.windows[2].end = device.windows[1].start;
device.windows[3].start =
currentTime >= WINDOW_OLDEST ? currentTime - WINDOW_OLDEST : 0;
device.windows[3].end = device.windows[2].start;
for (int w = 0; w < 4; w++) {
device.windows[w].detections = 0;
for (int i = 0; i < device.tsCount; i++) {
if (device.timestamps[i] >= device.windows[w].start &&
device.timestamps[i] < device.windows[w].end) {
device.windows[w].detections++;
}
}
}
}
float calculatePersistenceScore(DeviceInfo &device, unsigned long currentTime) {
float score = 0.0f;
int rssiRange = device.maxRssi - device.minRssi;
if (rssiRange < MIN_RSSI_RANGE) {
return 0.0f;
}
if (device.totalCount >= MIN_DETECTIONS) {
score += 0.20f * (float)std::min(device.totalCount, 30) / 30.0f;
} else {
return 0.0f;
}
int windowsActive = 0;
for (int i = 0; i < 4; i++) {
if (device.windows[i].detections > 0) windowsActive++;
}
if (windowsActive >= MIN_WINDOWS) {
score += 0.25f * (float)windowsActive / 4.0f;
} else {
return 0.0f;
}
bool isConnected = true;
if (device.tsCount >= 3) {
for (int i = 1; i < device.tsCount; i++) {
int prev =
(device.tsIdx - device.tsCount + i - 1 + MAX_TIMESTAMPS) % MAX_TIMESTAMPS;
int curr =
(device.tsIdx - device.tsCount + i + MAX_TIMESTAMPS) % MAX_TIMESTAMPS;
if (device.timestamps[curr] - device.timestamps[prev] >
EPSILON_CONNECTED_GAP) {
isConnected = false;
break;
}
}
if (isConnected) {
score += 0.25f;
}
}
if (device.variationCount >= 3) { // sketchy variance
score += 0.30f * (float)std::min(device.variationCount, 10) / 10.0f;
}
return score;
}
void moveToTop(int index) {
if (index <= 0) return;
DeviceInfo temp = trackedDevices[index];
for (int i = index; i > 0; i--) {
trackedDevices[i] = trackedDevices[i - 1];
}
trackedDevices[0] = temp;
}
int findEvictionCandidate() {
int bestCandidate = -1;
float minScore = 100.0f;
unsigned long oldestSeen = 0xFFFFFFFF;
for (int i = 0; i < deviceIndex; i++) {
if (trackedDevices[i].isSpecial || trackedDevices[i].alertTriggered) continue;
if (trackedDevices[i].persistenceScore < minScore) {
minScore = trackedDevices[i].persistenceScore;
bestCandidate = i;
oldestSeen = trackedDevices[i].lastSeen;
} else if (trackedDevices[i].persistenceScore == minScore) {
if (trackedDevices[i].lastSeen < oldestSeen) {
bestCandidate = i;
oldestSeen = trackedDevices[i].lastSeen;
}
}
}
if (bestCandidate == -1 && deviceIndex > 0) {
oldestSeen = 0xFFFFFFFF;
for (int i = 0; i < deviceIndex; i++) {
if (trackedDevices[i].lastSeen < oldestSeen) {
bestCandidate = i;
oldestSeen = trackedDevices[i].lastSeen;
}
}
}
return bestCandidate;
}
bool trackDevice(const char *address, int rssi, unsigned long currentTime,
const char *name, uint8_t detectedTracker = TRACKER_NONE) {
bool newTracker = false;
for (int i = 0; i < deviceIndex; i++) {
if (strcmp(trackedDevices[i].address, address) == 0) {
// Update tracker type if newly identified
if (detectedTracker != TRACKER_NONE && trackedDevices[i].trackerType == TRACKER_NONE) {
trackedDevices[i].trackerType = detectedTracker;
}
trackedDevices[i].totalCount++;
trackedDevices[i].lastSeen = currentTime;
trackedDevices[i].rssiSum += rssi;
trackedDevices[i].rssiCount++;
// Track RSSI range for movement detection
if (rssi < trackedDevices[i].minRssi) trackedDevices[i].minRssi = rssi;
if (rssi > trackedDevices[i].maxRssi) trackedDevices[i].maxRssi = rssi;
trackedDevices[i].timestamps[trackedDevices[i].tsIdx] = currentTime;
trackedDevices[i].tsIdx =
(trackedDevices[i].tsIdx + 1) % MAX_TIMESTAMPS;
if (trackedDevices[i].tsCount < MAX_TIMESTAMPS)
trackedDevices[i].tsCount++;
int rssiDiff = abs(trackedDevices[i].lastRssi - rssi);
if (rssiDiff <= RSSI_STABILITY_THRESHOLD) {
trackedDevices[i].stableRssiCount++;
} else {
trackedDevices[i].stableRssiCount = 0;
}
if (rssiDiff >= RSSI_VARIATION_THRESHOLD) {
trackedDevices[i].variationCount++;
}
trackedDevices[i].lastRssi = rssi;
if (name && strlen(name) > 0) {
strncpy(trackedDevices[i].name, name, 20);
trackedDevices[i].name[20] = '\0';
}
getManufacturer(address, trackedDevices[i].manufacturer, 31);
updateTimeWindows(trackedDevices[i], currentTime);
trackedDevices[i].persistenceScore =
calculatePersistenceScore(trackedDevices[i], currentTime);
if (isSpecialMac(address)) {
trackedDevices[i].detected = true;
trackedDevices[i].isSpecial = true;
if (trackedDevices[i].trackerType == TRACKER_NONE)
trackedDevices[i].trackerType = TRACKER_PRIVACY_INVADER;
if (!trackedDevices[i].alertTriggered) {
trackedDevices[i].alertTriggered = true;
newTracker = true;
}
moveToTop(i);
} else if (trackedDevices[i].trackerType != TRACKER_NONE) {
// Known tracker type detected via BLE signature — immediate alert
trackedDevices[i].detected = true;
trackedDevices[i].isSpecial = true;
if (!trackedDevices[i].alertTriggered) {
trackedDevices[i].alertTriggered = true;
newTracker = true;
}
moveToTop(i);
} else if (trackedDevices[i].persistenceScore >= PERSISTENCE_THRESHOLD) {
trackedDevices[i].detected = true;
trackedDevices[i].isSpecial = false;
trackedDevices[i].trackerType = TRACKER_PERSISTENCE;
if (!trackedDevices[i].alertTriggered) {
trackedDevices[i].alertTriggered = true;
newTracker = true;
}
moveToTop(i);
}
return newTracker;
}
}
int targetIndex = -1;
if (deviceIndex < maxDevices) {
for (int j = deviceIndex; j > 0; j--) {
trackedDevices[j] = trackedDevices[j - 1];
}
targetIndex = 0;
deviceIndex++;
} else {
int evictIdx = findEvictionCandidate();
if (evictIdx != -1) {
for (int j = evictIdx; j > 0; j--) {
trackedDevices[j] = trackedDevices[j - 1];
}
targetIndex = 0;
}
}
if (targetIndex == 0) {
memset(&trackedDevices[0], 0, sizeof(DeviceInfo));
strncpy(trackedDevices[0].address, address, 17);
trackedDevices[0].address[17] = '\0';
if (name && strlen(name) > 0) {
strncpy(trackedDevices[0].name, name, 20);
trackedDevices[0].name[20] = '\0';
}
getManufacturer(address, trackedDevices[0].manufacturer, 31);
trackedDevices[0].totalCount = 1;
trackedDevices[0].firstSeen = currentTime;
trackedDevices[0].lastSeen = currentTime;
trackedDevices[0].rssiSum = rssi;
trackedDevices[0].rssiCount = 1;
trackedDevices[0].lastRssi = rssi;
trackedDevices[0].minRssi = rssi;
trackedDevices[0].maxRssi = rssi;
trackedDevices[0].timestamps[0] = currentTime;
trackedDevices[0].tsIdx = 1;
trackedDevices[0].tsCount = 1;
trackedDevices[0].trackerType = detectedTracker;
if (isSpecialMac(address)) {
trackedDevices[0].detected = true;
trackedDevices[0].isSpecial = true;
trackedDevices[0].alertTriggered = true;
if (trackedDevices[0].trackerType == TRACKER_NONE)
trackedDevices[0].trackerType = TRACKER_PRIVACY_INVADER;
newTracker = true;
} else if (detectedTracker != TRACKER_NONE) {
// Known tracker type on first sight — immediate alert
trackedDevices[0].detected = true;
trackedDevices[0].isSpecial = true;
trackedDevices[0].alertTriggered = true;
newTracker = true;
}
}
return newTracker;
}
void removeOldEntries(unsigned long currentTime) {
for (int i = 0; i < deviceIndex; i++) {
if (trackedDevices[i].alertTriggered) continue;
if (currentTime - trackedDevices[i].lastSeen > DETECTION_WINDOW) {
for (int j = i; j < deviceIndex - 1; j++) {
trackedDevices[j] = trackedDevices[j + 1];
}
deviceIndex--;
i--;
}
}
// Promote stable devices to known buffer
for (int i = 0; i < deviceIndex; i++) {
if (trackedDevices[i].alertTriggered || trackedDevices[i].isSpecial) continue;
if (trackedDevices[i].totalCount >= KNOWN_PROMOTE_COUNT &&
(trackedDevices[i].maxRssi - trackedDevices[i].minRssi) < MIN_RSSI_RANGE) {
promoteToKnown(i, currentTime);
i--;
}
}
}
// --- Known device ring buffer functions ---
int findKnownDevice(const char *address) {
for (int i = 0; i < knownDeviceCount; i++) {
if (strcmp(knownDevices[i].address, address) == 0) return i;
}
return -1;
}
void promoteToKnown(int trackedIdx, unsigned long currentTime) {
int ki = findKnownDevice(trackedDevices[trackedIdx].address);
if (ki == -1) {
// Find slot: use next empty or evict oldest
if (knownDeviceCount < maxKnownDevices) {
ki = knownDeviceCount++;
} else {
ki = 0;
unsigned long oldest = knownDevices[0].lastSeen;
for (int i = 1; i < knownDeviceCount; i++) {
if (knownDevices[i].lastSeen < oldest) {
oldest = knownDevices[i].lastSeen;
ki = i;
}
}
}
}
strncpy(knownDevices[ki].address, trackedDevices[trackedIdx].address, 17);
knownDevices[ki].address[17] = '\0';
knownDevices[ki].lastSeen = currentTime;
knownDevices[ki].avgRssi = trackedDevices[trackedIdx].rssiSum /
trackedDevices[trackedIdx].rssiCount;
knownDevices[ki].seenCount = (uint8_t)std::min(trackedDevices[trackedIdx].totalCount, 255);
// Remove from tracked array
for (int j = trackedIdx; j < deviceIndex - 1; j++) {
trackedDevices[j] = trackedDevices[j + 1];
}
deviceIndex--;
}
// Returns true if device was handled as known (caller should skip trackDevice)
bool handleKnownDevice(const char *address, int rssi, unsigned long currentTime) {
int ki = findKnownDevice(address);
if (ki == -1) return false;
// Check if RSSI drifted significantly — device or user is moving
if (abs(rssi - knownDevices[ki].avgRssi) > KNOWN_RSSI_DRIFT) {
// De-promote: remove from known, let it enter full tracking
knownDevices[ki] = knownDevices[knownDeviceCount - 1];
knownDeviceCount--;
return false;
}
// Still stable — just update and skip full tracking
knownDevices[ki].lastSeen = currentTime;
if (knownDevices[ki].seenCount < 255) knownDevices[ki].seenCount++;
// Exponential moving average for RSSI
knownDevices[ki].avgRssi = (knownDevices[ki].avgRssi * 3 + rssi) / 4;
return true;
}
void removeOldKnownEntries(unsigned long currentTime) {
for (int i = 0; i < knownDeviceCount; i++) {
if (currentTime - knownDevices[i].lastSeen > KNOWN_EXPIRY_WINDOW) {
knownDevices[i] = knownDevices[knownDeviceCount - 1];
knownDeviceCount--;
i--;
}
}
}
void alertUser(bool isSpecial, const char *name, const char *mac,
float persistence, uint8_t tType = TRACKER_NONE) {
screenOn = true;
lastActivityTime = millis();
M5.Display.setBrightness(204);
if (isSpecial) {
for (int i = 0; i < 5; i++) {
M5.Display.fillScreen(RED);
delay(200);
M5.Display.fillScreen(BLUE);
delay(200);
}
} else {
M5.Display.fillScreen(RED);
}
M5.Display.setCursor(0, 10);
M5.Display.setTextColor(WHITE);
M5.Display.setTextSize(2);
M5.Display.print("Tracker Detected!");
M5.Display.setTextSize(1);
M5.Display.setCursor(0, 40);
M5.Display.print("Type: ");
if (tType != TRACKER_NONE) {
M5.Display.setTextColor(RED);
M5.Display.print(trackerTypeName(tType));
} else {
M5.Display.print(isSpecial ? "KNOWN" : "SUSPECTED");
}
M5.Display.setTextColor(WHITE);
M5.Display.setCursor(0, 55);
M5.Display.print("Name: ");
M5.Display.print(strlen(name) > 0 ? name : "Unknown");
M5.Display.setCursor(0, 70);
M5.Display.print("MAC: ");
M5.Display.print(mac);
M5.Display.setCursor(0, 85);
M5.Display.print("Score: ");
M5.Display.print(persistence, 2);
M5.Display.setCursor(0, 105);
M5.Display.setTextColor(YELLOW);
M5.Display.print("Press any button");
while (!M5.BtnA.wasPressed() && !M5.BtnB.wasPressed()) {
M5.update();
delay(50);
}
// Force display reset after alert dismissal to prevent race condition
M5.Display.fillScreen(BLACK);
M5.Display.setTextColor(WHITE);
M5.Display.setTextSize(1);
lastStateHash = 0;
screenOn = true;
lastActivityTime = millis();
M5.Display.setBrightness(highBrightness ? 204 : 77);
}
void showFeedback(const char* msg, uint16_t color, const char* sub = NULL) {
M5.Display.fillScreen(BLACK);
for (int i = 0; i < 15; i++) {
M5.Display.drawFastHLine(random(0, SCREEN_WIDTH), random(0, SCREEN_HEIGHT),
random(5, 40), random(0x0000, 0x1111));
}
M5.Display.drawFastHLine(0, 35, SCREEN_WIDTH, CYAN);
M5.Display.drawFastHLine(0, 36, SCREEN_WIDTH, CYAN);
M5.Display.setTextSize(3);
M5.Display.setTextColor(color);
int xPos = (SCREEN_WIDTH - strlen(msg) * 18) / 2;
M5.Display.setCursor(xPos, 50);
M5.Display.print(msg);
if (sub) {
M5.Display.setTextSize(1);
M5.Display.setTextColor(YELLOW);
M5.Display.setCursor((SCREEN_WIDTH - strlen(sub) * 6) / 2, 80);
M5.Display.print(sub);
}
M5.Display.drawFastHLine(0, 95, SCREEN_WIDTH, MAGENTA);
M5.Display.drawFastHLine(0, 96, SCREEN_WIDTH, MAGENTA);
}
void displayStartupMessage() {
M5.Display.fillScreen(BLACK);
for (int i = 0; i < 20; i++) {
int x = random(0, SCREEN_WIDTH);
int y = random(0, SCREEN_HEIGHT);
int w = random(5, 40);
M5.Display.drawFastHLine(x, y, w, random(0x0000, 0x1111));
}
M5.Display.drawFastHLine(0, 20, SCREEN_WIDTH, CYAN);
M5.Display.drawFastHLine(0, 21, SCREEN_WIDTH, CYAN);
M5.Display.setTextSize(3);
M5.Display.setTextColor(CYAN);
M5.Display.setCursor(15, 30);
M5.Display.print("PATH");
M5.Display.setTextColor(MAGENTA);
M5.Display.print("SHIELD");
M5.Display.setTextColor(0x07E0);
M5.Display.setCursor(16, 31);
M5.Display.print("PATH");
M5.Display.setTextSize(1);
M5.Display.setTextColor(YELLOW);
M5.Display.setCursor(50, 60);
M5.Display.print("TRACKER DETECTION");
M5.Display.setTextColor(DARKGREY);
M5.Display.setCursor(85, 72);
M5.Display.print("v1.2.1");
M5.Display.drawFastHLine(0, 85, SCREEN_WIDTH, MAGENTA);
M5.Display.setTextSize(1);
M5.Display.setTextColor(GREEN);
M5.Display.setCursor(10, 95);
M5.Display.print("> Initializing BLE/WiFi");
delay(400);
M5.Display.setCursor(190, 95);
M5.Display.setTextColor(CYAN);
M5.Display.print("[OK]");
delay(300);
M5.Display.setTextColor(GREEN);
M5.Display.setCursor(10, 107);
M5.Display.print("> Loading SPIFFS");
delay(400);
M5.Display.setCursor(190, 107);
M5.Display.setTextColor(CYAN);
M5.Display.print("[OK]");
delay(300);
M5.Display.setTextColor(GREEN);
M5.Display.setCursor(10, 119);
M5.Display.print("> System Ready");
delay(300);
M5.Display.setCursor(190, 119);
M5.Display.setTextColor(CYAN);
M5.Display.print("[OK]");
delay(400);
M5.Display.fillScreen(CYAN);
delay(50);
M5.Display.fillScreen(BLACK);
delay(50);
}
void drawTopBar() {
M5.Display.drawFastHLine(0, 0, SCREEN_WIDTH, CYAN);
M5.Display.drawFastHLine(0, 1, SCREEN_WIDTH, CYAN);
M5.Display.setTextSize(1);
M5.Display.setCursor(4, 3);
M5.Display.setTextColor(paused ? RED : GREEN);
M5.Display.print(paused ? "PAUSE" : (scanningWiFi ? "WiFi" : "BLE"));
static float lastValidBatVoltage = 3.7f;
float batVoltage = M5.Power.getBatteryVoltage() / 1000.0f;
// Filter out obviously bad readings (sensor errors), but allow real low battery
if (batVoltage > 2.0f && batVoltage < 4.5f) {
lastValidBatVoltage = batVoltage;
} else {
batVoltage = lastValidBatVoltage;
}
// Critical battery check - force shutdown if critically low
if (batVoltage < 3.0f && batVoltage > 2.0f) {
M5.Display.fillScreen(RED);
M5.Display.setTextSize(2);
M5.Display.setTextColor(WHITE);
M5.Display.setCursor(10, 50);
M5.Display.print("LOW BATTERY!");
M5.Display.setCursor(20, 80);
M5.Display.print("SHUTTING DOWN");
delay(3000);
M5.Power.powerOff();
}
int batPercent = (int)((batVoltage - 3.0f) / 1.2f * 100.0f);
if (batPercent > 100) batPercent = 100;
if (batPercent < 0) batPercent = 0;
int barWidth = 30;
int barX = 75;
int barY = 4;
uint16_t barColor = GREEN;
if (batPercent < 50) barColor = YELLOW;
if (batPercent < 25) barColor = RED;
M5.Display.setTextColor(BLUE_GREY);
M5.Display.setCursor(45, 3);
M5.Display.print("BATT:");
M5.Display.drawRect(barX, barY, barWidth, 6, BLUE_GREY);
int filledWidth = (barWidth - 2) * batPercent / 100;
M5.Display.fillRect(barX + 1, barY + 1, filledWidth, 4, barColor);
M5.Display.setTextColor(DARKGREY);
M5.Display.setCursor(110, 3);
M5.Display.print(batPercent);
M5.Display.print("%");
uint32_t freeHeap = ESP.getFreeHeap();
uint32_t freeKB = freeHeap / 1024;
// Scale memory display dynamically: initialFreeHeapKB = 100%, 0 = 0%
int memPercent = (initialFreeHeapKB > 0) ? (freeKB * 100) / initialFreeHeapKB : 0;
if (memPercent > 100) memPercent = 100;
if (memPercent < 0) memPercent = 0;
barX = 155;
uint16_t memColor = GREEN;
if (freeKB < MEMORY_WARNING) memColor = YELLOW;
if (freeKB < MEMORY_CRITICAL) memColor = RED;
M5.Display.setCursor(135, 3);
M5.Display.setTextColor(BLUE_GREY);
M5.Display.print("MEM:");
M5.Display.drawRect(barX, barY, barWidth, 6, BLUE_GREY);
filledWidth = (barWidth - 2) * memPercent / 100;
M5.Display.fillRect(barX + 1, barY + 1, filledWidth, 4, memColor);
M5.Display.setTextColor(memColor);
M5.Display.setCursor(190, 3);
M5.Display.print(freeKB);
M5.Display.print("KB");
M5.Display.drawFastHLine(0, 11, SCREEN_WIDTH, CYAN);
M5.Display.drawFastHLine(0, 12, SCREEN_WIDTH, CYAN);
}
// Generate hashed display state
uint32_t getDisplayStateHash() {
uint32_t hash = 1;
hash = hash * 31 + deviceIndex;
hash = hash * 31 + wifiDeviceIndex;
hash = hash * 31 + scrollIndex;
hash = hash * 31 + (scanningWiFi ? 1 : 0);
hash = hash * 31 + (paused ? 1 : 0);
hash = hash * 31 + (filterByName ? 1 : 0);
if (scanningWiFi) {
for (int i = 0; i < wifiDeviceIndex; i++) {
hash = hash * 31 + (uint32_t)wifiDevices[i].rssi;
hash = hash * 31 + wifiDevices[i].detectionCount;
hash = hash * 31 + wifiDevices[i].channel;
hash = hash * 31 + wifiDevices[i].encryptionType;
for (int j = 0; j < strlen(wifiDevices[i].ssid); j++) {
hash = hash * 31 + wifiDevices[i].ssid[j];
}
}
} else {
for (int i = 0; i < deviceIndex; i++) {
hash = hash * 31 + trackedDevices[i].totalCount;
hash = hash * 31 + (uint32_t)trackedDevices[i].lastRssi;
hash = hash * 31 + (trackedDevices[i].detected ? 1 : 0);
hash = hash * 31 + (trackedDevices[i].isSpecial ? 1 : 0);
for (int j = 0; j < strlen(trackedDevices[i].name); j++) {
hash = hash * 31 + trackedDevices[i].name[j];
}
for (int j = 0; j < strlen(trackedDevices[i].manufacturer); j++) {
hash = hash * 31 + trackedDevices[i].manufacturer[j];
}
}
}
return hash;
}
void displayTrackedDevices() {
unsigned long now = millis();
if (now - lastDisplayRender < 500) {
return;
}
if (xSemaphoreTake(deviceMutex, pdMS_TO_TICKS(100)) != pdTRUE) {
return;
}
uint32_t currentHash = getDisplayStateHash();
if (currentHash == lastStateHash) {
xSemaphoreGive(deviceMutex);
return;
}
// Actually have data to change, go on
lastStateHash = currentHash;
lastDisplayRender = now;
M5.Display.fillScreen(BLACK);