-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathliveMap.html
More file actions
649 lines (630 loc) · 32.6 KB
/
liveMap.html
File metadata and controls
649 lines (630 loc) · 32.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<title>Beacon Live Map</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0d1117;color:#e6edf3;font-family:'Segoe UI',sans-serif}
.badge{display:inline-block;padding:2px 8px;border-radius:12px;font-size:.71rem;font-weight:600}
.moving{background:#1a4a2e;color:#3fb950;border:1px solid #2ea043}
.stopped{background:#3d1a1a;color:#f85149;border:1px solid #da3633}
.live{background:#1a4a2e;color:#3fb950;border:1px solid #2ea043}
.stale{background:#4a2a1a;color:#ffa657;border:1px solid #f0883e}
.lost{background:#3d1a1a;color:#f85149;border:1px solid #da3633}
.fallback{background:#1a365d;color:#79c0ff;border:1px solid #58a6ff}
.coord a{color:#79c0ff;font-family:monospace;font-size:.77rem;text-decoration:none}
.coord a:hover{text-decoration:underline}
#live-map{height:100vh;width:100%}
.map-tools{position:absolute;top:10px;left:56px;z-index:900;display:flex;gap:6px;align-items:center;flex-wrap:wrap;
background:rgba(13,17,23,.88);border:1px solid #30363d;border-radius:8px;padding:6px 10px;backdrop-filter:blur(2px)}
.map-tools button{background:#1c2128;color:#c9d1d9;border:1px solid #30363d;border-radius:6px;padding:4px 8px;cursor:pointer;font-size:.74rem}
.map-tools button:hover{border-color:#58a6ff;color:#f0f6fc}
.map-tools label{font-size:.74rem;color:#8b949e;display:flex;align-items:center;gap:4px}
.map-legend{background:rgba(13,17,23,.9);border:1px solid #30363d;border-radius:6px;padding:6px 8px;font-size:.72rem;color:#c9d1d9;z-index:700}
.map-legend .row{display:flex;align-items:center;gap:6px;margin:2px 0}
.swatch{width:10px;height:10px;border-radius:50%}
.livemap-hud{position:absolute;right:14px;top:14px;z-index:800;background:rgba(13,17,23,.88);border:1px solid #30363d;border-radius:10px;padding:8px 10px;font-size:.76rem;color:#c9d1d9;backdrop-filter:blur(2px)}
.livemap-hud .chip{display:inline-block;margin:0 6px 0 0;padding:3px 8px;border-radius:999px;border:1px solid #30363d;background:#161b22}
.livemap-hud .title{display:block;color:#8b949e;font-size:.68rem;margin-bottom:6px}
.beacon-popup{min-width:280px;line-height:1.35}
.beacon-popup .card{background:#fff;border-radius:14px;box-shadow:0 8px 24px rgba(0,0,0,.2);overflow:hidden;color:#0f172a}
.beacon-popup .head{padding:10px 14px;border-bottom:1px solid #e5e7eb;font-weight:700;font-size:.95rem}
.beacon-popup .head.safety{background:#f97316;color:#fff}
.beacon-popup .head.equipment{background:#2563eb;color:#fff}
.beacon-popup .head.towed{background:#7c3aed;color:#fff}
.beacon-popup .head.uncat{background:#1f2937;color:#fff}
.beacon-popup .body{padding:10px 14px}
.beacon-popup .cat{display:inline-block;padding:2px 9px;border-radius:999px;background:#0f172a1a;color:#0f172a;font-size:.72rem;margin-left:6px}
.beacon-popup .sec{font-size:.74rem;color:#64748b;font-weight:700;margin:6px 0 4px}
.beacon-popup .kv{display:grid;grid-template-columns:88px 1fr;gap:3px 8px;font-size:.8rem}
.beacon-popup .k{color:#64748b}
.beacon-popup .warn{margin-top:8px;color:#dc2626;font-weight:800}
.beacon-popup .actions{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}
.beacon-popup .btn{font-size:.72rem;padding:4px 8px;border-radius:6px;border:1px solid #cbd5e1;background:#f8fafc;color:#0f172a}
.shape{display:inline-block}
.shape-square{width:14px;height:14px;background:#2563eb;border:2px solid #fff;border-radius:2px}
.shape-diamond{width:14px;height:14px;background:#a855f7;border:2px solid #fff;transform:rotate(45deg);border-radius:2px}
.shape-star{color:#f97316;font-size:17px;line-height:14px}
.shape-circle{width:14px;height:14px;background:#f97316;border:2px solid #fff;border-radius:50%}
.shape-hex{width:14px;height:14px;background:#8b5cf6;border:2px solid #fff;clip-path:polygon(25% 5%,75% 5%,100% 50%,75% 95%,25% 95%,0 50%)}
.gse-popup{min-width:310px;max-width:380px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif;line-height:1.3;color:#0f172a}
.gse-popup *{box-sizing:border-box}
.gse-popup .gse-card{background:#fff;border-radius:6px;box-shadow:0 4px 20px rgba(0,0,0,.25);overflow:hidden;border:1px solid #cbd5e1}
.gse-popup .gse-hdr{display:flex;align-items:center;gap:8px;padding:10px 14px;background:#1e293b;color:#f1f5f9}
.gse-popup .gse-led{width:10px;height:10px;border-radius:50%;flex-shrink:0;border:1px solid rgba(255,255,255,.3)}
.gse-popup .gse-led.moving{background:#22c55e;box-shadow:0 0 6px #22c55e}
.gse-popup .gse-led.stopped{background:#f59e0b;box-shadow:0 0 6px #f59e0b}
.gse-popup .gse-led.stale{background:#ef4444;box-shadow:0 0 6px #ef4444}
.gse-popup .gse-thumb{width:36px;height:36px;object-fit:contain;border-radius:4px;background:#0f172a;padding:2px;flex-shrink:0}
.gse-popup .gse-gsenum{font-size:.72rem;font-weight:600;color:#38bdf8;margin-left:4px}
.gse-popup .gse-name{font-weight:700;font-size:.92rem;flex:1}
.gse-popup .gse-badge{font-size:.62rem;padding:2px 8px;border-radius:999px;font-weight:600;text-transform:uppercase;letter-spacing:.5px}
.gse-popup .gse-badge.direct{background:#166534;color:#bbf7d0}
.gse-popup .gse-badge.navixy{background:#1e40af;color:#bfdbfe}
.gse-popup .gse-badge.combined{background:#6d28d9;color:#ddd6fe}
.gse-popup .gse-imei{padding:0 14px 8px;font-size:.7rem;color:#94a3b8;background:#1e293b;font-family:'Courier New',monospace;letter-spacing:.5px}
.gse-popup .gse-sec{display:flex;justify-content:space-between;align-items:center;padding:6px 14px 4px;border-bottom:1px solid #e2e8f0;background:#f8fafc}
.gse-popup .gse-sec-label{font-size:.62rem;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:#475569}
.gse-popup .gse-sec-ts{font-size:.58rem;font-family:'Courier New',monospace;color:#94a3b8}
.gse-popup .gse-body{padding:5px 14px 8px}
.gse-popup .gse-kv{display:grid;grid-template-columns:100px 1fr;gap:2px 8px;font-size:.76rem}
.gse-popup .gse-k{color:#64748b;font-size:.68rem;padding-top:1px}
.gse-popup .gse-v{font-weight:600;font-family:'Courier New',monospace;font-size:.74rem}
.gse-popup .gse-v.on{color:#16a34a}
.gse-popup .gse-v.off{color:#dc2626}
.gse-popup .gse-v.na{color:#94a3b8;font-weight:400;font-style:italic}
.gse-popup .gse-v .gse-fts{font-size:.56rem;color:#94a3b8;font-weight:400;margin-left:4px;font-style:normal}
.gse-popup .gse-conflict{margin:4px 14px 6px;padding:4px 8px;background:#fef2f2;border:1px solid #fecaca;border-radius:4px;font-size:.7rem;color:#dc2626;font-weight:600}
.gse-popup .gse-tow{margin:0 14px 8px;padding:5px 8px;border-radius:4px;font-size:.72rem;font-weight:600}
.gse-popup .gse-tow.towing{background:#fef3c7;border:1px solid #fde68a;color:#92400e}
.gse-popup .gse-tow.idle{background:#f0fdf4;border:1px solid #bbf7d0;color:#166534}
.leaflet-popup-content .gse-popup{margin:-4px -6px}
.status-bar{position:absolute;bottom:8px;left:50%;transform:translateX(-50%);z-index:800;background:rgba(13,17,23,.85);border:1px solid #30363d;border-radius:8px;padding:4px 12px;font-size:.72rem;color:#8b949e;backdrop-filter:blur(2px)}
.status-bar.error{border-color:#f85149;color:#f85149}
@media(max-width:768px){
.map-tools{left:10px;right:10px;top:auto;bottom:40px;justify-content:center}
.livemap-hud{right:8px;top:8px}
.beacon-popup{min-width:196px;max-width:220px;line-height:1.22}
.beacon-popup .card{border-radius:10px}
.beacon-popup .head{padding:7px 10px;font-size:.8rem}
.beacon-popup .body{padding:7px 10px}
.beacon-popup .cat{font-size:.6rem;padding:1px 6px;margin-left:4px}
.beacon-popup .sec{font-size:.66rem;margin:4px 0 3px}
.beacon-popup .kv{grid-template-columns:62px 1fr;gap:2px 6px;font-size:.7rem}
.beacon-popup .warn{margin-top:6px;font-size:.72rem}
.beacon-popup .actions{gap:4px;margin-top:6px}
.beacon-popup .btn{font-size:.64rem;padding:3px 6px;border-radius:5px}
.gse-popup{min-width:220px;max-width:300px}
.gse-popup .gse-hdr{padding:7px 10px;gap:6px}
.gse-popup .gse-name{font-size:.82rem}
.gse-popup .gse-imei{padding:0 10px 6px;font-size:.62rem}
.gse-popup .gse-sec{padding:4px 10px 3px}
.gse-popup .gse-body{padding:4px 10px 6px}
.gse-popup .gse-kv{grid-template-columns:72px 1fr;gap:2px 6px;font-size:.7rem}
.gse-popup .gse-k{font-size:.62rem}
.gse-popup .gse-v{font-size:.66rem}
.gse-popup .gse-tow{margin:0 10px 6px;font-size:.66rem}
}
</style>
</head>
<body>
<div id="live-map"></div>
<div class="map-tools" id="map-toolbar">
<button id="map-fit-btn" type="button">Fit Bounds</button>
<button id="map-skoda-btn" type="button">Center Skoda</button>
<button id="map-legend-btn" type="button">Hide Legend</button>
<label><input id="map-trackers-toggle" type="checkbox" checked>Trackers</label>
<label><input id="map-beacons-toggle" type="checkbox" checked>Beacons</label>
</div>
<div class="livemap-hud" id="livemap-hud">
<span class="title">LiveMap</span>
<span class="chip" id="hud-trackers">Trackers: 0</span>
<span class="chip" id="hud-beacons">Beacons: 0</span>
<span class="chip" id="hud-source">Source: aggregate</span>
</div>
<div class="status-bar" id="status-bar">Connecting...</div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
let API_BASE = "https://2plusnavixy.ngrok.app";
let API_FALLBACK = "https://beacons2plus.loca.lt";
let API_GIST = "https://gist.githubusercontent.com/GolanMoyal2023/8c421ecba6ec4dcd9b7b87c24dd723a1/raw/state.json";
let API_STATE = API_BASE + "/liveMap/api/state";
let API_STATE_FB = API_FALLBACK + "/liveMap/api/state";
let configLoaded = false;
(async function loadConfig(){
try {
const cfg = await (await fetch("api-url.json", {cache:"no-store"})).json();
if (cfg.api_base) {
API_BASE = cfg.api_base.replace(/\/+$/, "");
API_STATE = API_BASE + "/liveMap/api/state";
}
if (cfg.api_fallback) {
API_FALLBACK = cfg.api_fallback.replace(/\/+$/, "");
API_STATE_FB = API_FALLBACK + "/liveMap/api/state";
}
if (cfg.api_gist) API_GIST = cfg.api_gist;
} catch(e) { /* use defaults */ }
configLoaded = true;
})();
let activeSource = "none";
function esc(s){
if(s==null) return "\u2014";
return String(s).replace(/&/g,"&").replace(/</g,"<");
}
function coord(lat,lon){
if(lat==null||lon==null) return "\u2014";
return '<div class="coord"><a href="https://maps.google.com/?q='+lat+','+lon+'" target="_blank">'+lat.toFixed(6)+', '+lon.toFixed(6)+'</a></div>';
}
function categoryStyle(category){
const c=String(category||'Uncategorized').toLowerCase();
if(c==='equipment') return {shape:'square', color:'#2563eb', glyph:'\u25A0'};
if(c==='towed device') return {shape:'diamond', color:'#a855f7', glyph:'\u25C6'};
if(c==='safety') return {shape:'star', color:'#f97316', glyph:'\u2605'};
if(c==='container') return {shape:'circle', color:'#f97316', glyph:'\u25CF'};
if(c==='vehicle') return {shape:'hex', color:'#8b5cf6', glyph:'\u2B22'};
return {shape:'square', color:'#6b7280', glyph:'\u25A0'};
}
function popupHeadClass(category){
const c=String(category||'Uncategorized').toLowerCase();
if(c==='safety') return 'safety';
if(c==='equipment') return 'equipment';
if(c==='towed device') return 'towed';
return 'uncat';
}
function beaconShapeHtml(category){
const s=categoryStyle(category);
if(s.shape==='star') return '<span class="shape shape-star">\u2605</span>';
if(s.shape==='diamond') return '<span class="shape shape-diamond"></span>';
if(s.shape==='circle') return '<span class="shape shape-circle"></span>';
if(s.shape==='hex') return '<span class="shape shape-hex"></span>';
return '<span class="shape shape-square"></span>';
}
function sourceColor(source){
if(source==='towed_sync') return '#f85149';
if(source==='attached_sync') return '#e3b341';
if(source==='combined') return '#a371f7';
if(source==='navixy') return '#58a6ff';
return '#3fb950';
}
function sourceIconGlyph(source){
if(source==='towed_sync') return 'T';
if(source==='attached_sync') return 'A';
if(source==='combined') return 'C';
if(source==='navixy') return 'N';
return 'D';
}
function computeConfidence(source, speed){
if(source==='combined') return 'High';
if(source==='direct') return (speed!=null && Number(speed)>2)?'High':'Medium';
return 'Medium';
}
function sourceReasonText(reason){
const m={
direct_fresher:'Direct is fresher',
navixy_fresher:'Navixy is fresher',
direct_missing:'Direct missing position',
navixy_missing:'Navixy missing position',
direct_has_timestamp:'Direct has newer timestamp signal',
navixy_has_timestamp:'Navixy has newer timestamp signal',
blended_close_time_and_distance:'Blended (time+distance matched)',
sticky_last_known_position:'Using sticky last known position',
attached_live_sync:'Attached live sync to host tracker',
towed_sync_override:'Towed sync override'
};
return m[reason]||reason||'';
}
let map=null, mapLayer=null, mapInit=false;
let markerGroups={trackers:null,beacons:null};
let latestAggregate=null;
let mapStickyPos={trackers:{},beacons:{}};
const LIVE_STICKY_HOLD_MS=45000;
let lastGoodAggregate=null;
let lastGoodAggregateAt=0;
let activeBeaconPopupMac=null;
let activeTrackerPopupImei=null;
let ignorePopupClose=false;
let legendCtl=null;
let legendVisible=true;
function initMap(){
if(map) return;
const mapDiv=document.getElementById("live-map");
if(!mapDiv || typeof L==='undefined') return;
map=L.map("live-map",{zoomControl:true}).setView([32.1,34.9],10);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{maxZoom:19,attribution:"© OpenStreetMap"}).addTo(map);
mapLayer=L.layerGroup().addTo(map);
markerGroups.trackers=L.layerGroup().addTo(map);
markerGroups.beacons=L.layerGroup().addTo(map);
legendCtl=L.control({position:'bottomright'});
legendCtl.onAdd=function(){
const div=L.DomUtil.create('div','map-legend');
div.innerHTML=
'<div class="row"><span class="swatch" style="background:#3fb950"></span>Direct</div>'+
'<div class="row"><span class="swatch" style="background:#58a6ff"></span>Navixy</div>'+
'<div class="row"><span class="swatch" style="background:#a371f7"></span>Combined</div>'+
'<div class="row"><span class="swatch" style="background:#e3b341"></span>Attached sync</div>'+
'<div class="row"><span class="swatch" style="background:#f85149"></span>Towed sync</div>'+
'<div class="row"><span class="shape shape-square"></span> Equipment</div>'+
'<div class="row"><span class="shape shape-diamond"></span> Towed Device</div>'+
'<div class="row"><span class="shape shape-star">\u2605</span> Safety</div>';
L.DomEvent.disableClickPropagation(div);
return div;
};
legendCtl.addTo(map);
}
initMap();
function renderAggregateMap(d){
const strictLive=true;
initMap();
if(!map) return;
ignorePopupClose=true;
mapLayer.clearLayers();
markerGroups.trackers.clearLayers();
markerGroups.beacons.clearLayers();
const ag=d.map_aggregate||{};
const tr=ag.trackers||[];
const bc=ag.beacons||[];
latestAggregate=ag;
const pts=[];
const trackerMarkerByImei={};
const beaconMarkerByMac={};
const beaconPointSeen={};
const beaconPointCount={};
function spreadPoint(lat,lon,key){
const idx=(beaconPointSeen[key]||0);
const total=(beaconPointCount[key]||1);
beaconPointSeen[key]=idx+1;
if(total<=1) return [lat,lon];
const angle=((360/Math.max(2,total))*idx)%360;
let baseM=18;
const z=(map&&typeof map.getZoom==='function')?map.getZoom():13;
if(z<=9) baseM=70;
else if(z<=11) baseM=48;
else if(z<=13) baseM=30;
else if(z<=15) baseM=24;
else baseM=14;
const zoomSpreadFactor=Math.max(0.7, Math.min(1.8, 1 + ((13 - z) * 0.05)));
const radiusM=(baseM*zoomSpreadFactor) + (Math.floor(idx/6)*Math.max(6,Math.round((baseM*zoomSpreadFactor)*0.35)));
const dLat=(radiusM/111111.0);
const dLon=(radiusM/(111111.0*Math.max(0.2,Math.cos((lat*Math.PI)/180.0))));
const r=(angle*Math.PI)/180.0;
return [lat + (Math.sin(r)*dLat), lon + (Math.cos(r)*dLon)];
}
const trackersOn=document.getElementById("map-trackers-toggle").checked;
const beaconsOn=document.getElementById("map-beacons-toggle").checked;
let visibleTrackers=0;
let visibleBeacons=0;
tr.forEach(t=>{
let tLat=t.lat, tLon=t.lon;
const tKey=String(t.imei||'');
if(tLat==null||tLon==null){
const s=mapStickyPos.trackers[tKey];
if(s && (Date.now() - (s.seenAt||0) <= LIVE_STICKY_HOLD_MS)){
tLat=s.lat; tLon=s.lon;
}
}else{
mapStickyPos.trackers[tKey]={lat:tLat, lon:tLon, seenAt:Date.now()};
}
if(tLat==null||tLon==null) return;
if(!trackersOn) return;
const heading=(t.heading!=null)?Number(t.heading):0;
const markerHtml='<div style="position:relative;width:24px;height:24px">'+
'<div style="position:absolute;left:1px;top:3px;width:22px;height:16px;border-radius:8px;background:'+sourceColor(t.source)+';border:2px solid #0d1117;color:#fff;font-weight:700;font-size:10px;line-height:12px;text-align:center">'+sourceIconGlyph(t.source)+'</div>'+
'<div style="position:absolute;left:9px;top:-1px;width:0;height:0;border-left:4px solid transparent;border-right:4px solid transparent;border-bottom:8px solid '+sourceColor(t.source)+';transform:rotate('+heading+'deg);transform-origin:50% 14px"></div>'+
'</div>';
const icon=L.divIcon({html:markerHtml,className:'',iconSize:[24,24],iconAnchor:[12,12]});
const m=L.marker([tLat,tLon],{icon:icon}).addTo(markerGroups.trackers);
const _ledCls=t.is_stale?'stale':(Number(t.speed||0)>1?'moving':'stopped');
const _srcBadge=esc(t.source||'--');
const _srcCls=(t.source==='direct'?'direct':(t.source==='navixy'?'navixy':'combined'));
const _fts=function(v){if(!v) return '--'; return esc(v);};
const _ign=t.ignition===true?'ON':t.ignition===false?'OFF':'--';
const _ignCls=t.ignition===true?'on':t.ignition===false?'off':'na';
const _extV=(t.ext_v!=null)?esc(t.ext_v)+'V':'--';
const _battV=(t.batt_v!=null)?esc(t.batt_v)+'V':'--';
const _fuel=(t.fuel_level!=null)?esc(t.fuel_level)+'%':'N/A';
const _fuelNote=(t.fuel_level!=null)?'':'(CAN not configured)';
const _odoKm=(t.total_odo_m!=null)?esc((t.total_odo_m/1000).toFixed(1))+' km':'N/A';
const _odoNote=(t.total_odo_m!=null)?'':'(CAN not configured)';
const _towStat=esc(t.tow_status||'Not Towing');
const _towCls=(t.tow_status&&t.tow_status.startsWith('Towing'))?'towing':'idle';
const _gseNum=t.gse_number||'';
const _imgUrl=t.image||'';
const _thumbHtml=_imgUrl?'<img class="gse-thumb" src="'+esc(_imgUrl)+'" alt="">':'';
const _engH='--';
const _dTs=_fts(t.direct_ts_str);
const _nTs=_fts(t.navixy_ts_str);
const _conf=computeConfidence(t.source,t.speed);
const _gap=(t.freshness_gap_sec!=null)?esc(t.freshness_gap_sec)+' sec':'--';
m.bindPopup(
'<div class="gse-popup"><div class="gse-card">'+
'<div class="gse-hdr">'+_thumbHtml+'<span class="gse-led '+_ledCls+'"></span>'+
'<span class="gse-name">'+esc(t.name)+(_gseNum?' <span class="gse-gsenum">#'+esc(_gseNum)+'</span>':'')+'</span>'+
'<span class="gse-badge '+_srcCls+'">'+_srcBadge+'</span></div>'+
'<div class="gse-imei">IMEI: '+esc(t.imei)+'</div>'+
'<div class="gse-sec"><span class="gse-sec-label">Classification</span></div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Category</span><span class="gse-v">'+esc(t.category||'--')+'</span>'+
'<span class="gse-k">Sub-Category</span><span class="gse-v">'+esc(t.sub_category||'--')+'</span>'+
'<span class="gse-k">GSE Number</span><span class="gse-v">'+(_gseNum?esc(_gseNum):'--')+'</span>'+
'</div></div>'+
'<div class="gse-sec"><span class="gse-sec-label">Position</span><span class="gse-sec-ts">ts: '+_fts(t.chosen_ts)+'</span></div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Lat / Long</span><span class="gse-v">'+esc(t.lat)+', '+esc(t.lon)+'</span>'+
'<span class="gse-k">Heading</span><span class="gse-v">'+esc(t.heading)+'°</span>'+
'<span class="gse-k">Speed</span><span class="gse-v">'+esc(t.speed)+' km/h</span>'+
'<span class="gse-k">Source</span><span class="gse-v">'+_srcBadge+'</span>'+
'<span class="gse-k">Confidence</span><span class="gse-v">'+_conf+'</span>'+
'</div></div>'+
((t.position_conflict&&t.position_conflict_m!=null)?('<div class="gse-conflict">Position conflict: '+esc(t.position_conflict_m)+' m</div>'):'')+
'<div class="gse-sec"><span class="gse-sec-label">Last Seen</span></div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Active</span><span class="gse-v">'+_fts(t.display_last_update)+'</span>'+
'<span class="gse-k">Direct</span><span class="gse-v">'+_dTs+'</span>'+
'<span class="gse-k">Navixy</span><span class="gse-v">'+_nTs+'</span>'+
'<span class="gse-k">Gap</span><span class="gse-v">'+_gap+'</span>'+
'</div></div>'+
'<div class="gse-sec"><span class="gse-sec-label">CAN Bus / Sensors</span><span class="gse-sec-ts">ts: '+_dTs+'</span></div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Ignition</span><span class="gse-v '+_ignCls+'">'+_ign+'</span>'+
'<span class="gse-k">Ext Power</span><span class="gse-v">'+_extV+'</span>'+
'<span class="gse-k">Battery</span><span class="gse-v">'+_battV+'</span>'+
'<span class="gse-k">Engine Hours</span><span class="gse-v na">'+_engH+'</span>'+
'</div></div>'+
'<div class="gse-sec"><span class="gse-sec-label">Fuel</span><span class="gse-sec-ts">ts: '+(t.fuel_level!=null?_dTs:'--')+'</span></div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Level</span><span class="gse-v'+(t.fuel_level==null?' na':'')+'">'+ _fuel+(_fuelNote?' <span class="gse-fts">'+_fuelNote+'</span>':'')+'</span>'+
'</div></div>'+
'<div class="gse-sec"><span class="gse-sec-label">Odometer (ODM)</span><span class="gse-sec-ts">ts: '+(t.total_odo_m!=null?_dTs:'--')+'</span></div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Reading</span><span class="gse-v'+(t.total_odo_m==null?' na':'')+'">'+ _odoKm+(_odoNote?' <span class="gse-fts">'+_odoNote+'</span>':'')+'</span>'+
'</div></div>'+
'<div class="gse-sec"><span class="gse-sec-label">Next Service</span></div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Scheduled</span><span class="gse-v na">--</span>'+
'</div></div>'+
'<div class="gse-tow '+_towCls+'">Tow: '+_towStat+'</div>'+
'</div></div>', {maxWidth:400,autoClose:false,closeOnClick:false}
);
trackerMarkerByImei[String(t.imei||'')]=m;
m.on('popupopen', ()=>{ activeTrackerPopupImei=String(t.imei||''); });
m.on('popupclose', ()=>{
if(!ignorePopupClose && activeTrackerPopupImei===String(t.imei||'')){
activeTrackerPopupImei=null;
}
});
pts.push([tLat,tLon]);
visibleTrackers += 1;
});
const visibleBeaconRows=[];
bc.forEach(b=>{
const bLifecycle=String(b.lifecycle_state||'');
let bLat=b.lat, bLon=b.lon;
const bKey=String(b.mac||'').toUpperCase();
const isDropped=bLifecycle.includes('DROPPED');
if(bLat==null||bLon==null){
const s=mapStickyPos.beacons[bKey];
if(s){
const stickyOk = isDropped || (Date.now() - (s.seenAt||0) <= LIVE_STICKY_HOLD_MS);
if(stickyOk){ bLat=s.lat; bLon=s.lon; }
}
}else{
mapStickyPos.beacons[bKey]={lat:bLat, lon:bLon, seenAt:Date.now(), lifecycle:bLifecycle};
}
if(bLat==null||bLon==null) return;
if(!beaconsOn) return;
visibleBeaconRows.push({b:b, bLat:Number(bLat), bLon:Number(bLon), bLifecycle:bLifecycle});
});
tr.forEach(t=>{
if(t.lat!=null&&t.lon!=null){
const k=(Number(t.lat).toFixed(6)+','+Number(t.lon).toFixed(6));
beaconPointCount[k]=(beaconPointCount[k]||0)+1;
}
});
visibleBeaconRows.forEach(row=>{
const k=(Number(row.bLat).toFixed(6)+','+Number(row.bLon).toFixed(6));
beaconPointCount[k]=(beaconPointCount[k]||0)+1;
});
visibleBeaconRows.forEach(row=>{
const b=row.b;
const bLat=row.bLat;
const bLon=row.bLon;
const bLifecycle=row.bLifecycle;
const k=(Number(bLat).toFixed(6)+','+Number(bLon).toFixed(6));
const pxy=spreadPoint(bLat,bLon,k);
const cat=categoryStyle(b.category);
const icon=L.divIcon({
html:'<div style="width:22px;height:22px;display:flex;align-items:center;justify-content:center">'+beaconShapeHtml(b.category)+'</div>',
className:'',
iconSize:[22,22],
iconAnchor:[11,11]
});
const isDropped=bLifecycle.includes('DROPPED');
const c=L.marker([pxy[0],pxy[1]],{icon:icon,opacity:(isDropped?0.75:1.0),zIndexOffset:(isDropped?-100:0)}).addTo(markerGroups.beacons);
beaconMarkerByMac[String(b.mac||'').toUpperCase()] = c;
const _bLedCls=bLifecycle.includes('DROPPED')?'stale':(b.is_stale?'stale':'stopped');
const _bSrcBadge=esc(b.source||'direct');
const _bSrcCls=(b.source==='navixy'?'navixy':(b.source==='combined'?'combined':'direct'));
const _bBatt=(b.battery_mv!=null)?esc(b.battery_mv)+' mV':'N/A';
const _bCoord=(b.lat!=null&&b.lon!=null)?(Number(b.lat).toFixed(6)+', '+Number(b.lon).toFixed(6)):'--';
const _bLc=esc(b.lifecycle_state||'UNKNOWN');
const _bLcCls=bLifecycle.includes('DROPPED')?'off':(bLifecycle==='TOWING'?'on':'na');
c.bindPopup(
'<div class="gse-popup"><div class="gse-card">'+
'<div class="gse-hdr"><span class="gse-led '+_bLedCls+'"></span>'+
'<span class="gse-name">'+esc(b.label)+'</span>'+
'<span class="gse-badge '+_bSrcCls+'">'+_bSrcBadge+'</span></div>'+
'<div class="gse-imei">MAC: '+esc(b.mac)+'</div>'+
'<div class="gse-sec"><span class="gse-sec-label">Device Info</span></div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Type</span><span class="gse-v">Eye Beacon</span>'+
'<span class="gse-k">Category</span><span class="gse-v">'+esc(b.category||'Uncategorized')+'</span>'+
'<span class="gse-k">Battery</span><span class="gse-v'+(b.battery_mv==null?' na':'')+'">'+_bBatt+'</span>'+
'</div></div>'+
'<div class="gse-sec"><span class="gse-sec-label">Position</span><span class="gse-sec-ts">ts: '+esc(b.last_seen_ts||'--')+'</span></div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Lat / Long</span><span class="gse-v">'+esc(_bCoord)+'</span>'+
'<span class="gse-k">Set by</span><span class="gse-v">'+esc(b.last_seen_name||'--')+'</span>'+
'</div></div>'+
'<div class="gse-sec"><span class="gse-sec-label">BLE Status</span></div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Last Seen</span><span class="gse-v">'+esc(b.last_seen_ts||'--')+'</span>'+
'<span class="gse-k">Lifecycle</span><span class="gse-v '+_bLcCls+'">'+_bLc+'</span>'+
'<span class="gse-k">Source</span><span class="gse-v">'+_bSrcBadge+'</span>'+
'</div></div>'+
(bLifecycle.includes('DROPPED')?(
'<div class="gse-conflict">DROPPED IN FIELD</div>'+
'<div class="gse-body"><div class="gse-kv">'+
'<span class="gse-k">Dropped at</span><span class="gse-v">'+esc(b.drop_ts||'--')+'</span>'+
'<span class="gse-k">Dropped by</span><span class="gse-v">'+esc(b.last_seen_name||b.drop_by||'--')+'</span>'+
'</div></div>'):'')+
'</div></div>',
{offset:L.point(0,-28),maxWidth:400,autoClose:false,closeOnClick:false,autoPanPaddingTopLeft:L.point(30,30),autoPanPaddingBottomRight:L.point(30,30)}
);
c.on('popupopen', ()=>{ activeBeaconPopupMac = String(b.mac||'').toUpperCase(); });
c.on('popupclose', ()=>{
if(!ignorePopupClose && activeBeaconPopupMac === String(b.mac||'').toUpperCase()){
activeBeaconPopupMac = null;
}
});
pts.push([pxy[0],pxy[1]]);
visibleBeacons += 1;
});
const hudT=document.getElementById('hud-trackers');
const hudB=document.getElementById('hud-beacons');
const hudS=document.getElementById('hud-source');
if(hudT) hudT.textContent='Trackers: '+visibleTrackers;
if(hudB) hudB.textContent='Beacons: '+visibleBeacons;
if(hudS) hudS.textContent='Source: aggregate';
if(pts.length){
const bounds=L.latLngBounds(pts);
if(!mapInit){
map.fitBounds(bounds.pad(0.25));
mapInit=true;
}
}
if(activeTrackerPopupImei && trackerMarkerByImei[activeTrackerPopupImei]){
trackerMarkerByImei[activeTrackerPopupImei].openPopup();
}
if(activeBeaconPopupMac && beaconMarkerByMac[activeBeaconPopupMac]){
beaconMarkerByMac[activeBeaconPopupMac].openPopup();
}
ignorePopupClose=false;
}
function mapFitBounds(){
if(!map || !latestAggregate) return;
const pts=[];
(latestAggregate.trackers||[]).forEach(t=>{ if(t.lat!=null&&t.lon!=null) pts.push([t.lat,t.lon]); });
(latestAggregate.beacons||[]).forEach(b=>{ if(b.lat!=null&&b.lon!=null) pts.push([b.lat,b.lon]); });
if(pts.length) map.fitBounds(L.latLngBounds(pts).pad(0.25));
}
function mapCenterSkoda(){
if(!map || !latestAggregate) return;
const s=(latestAggregate.trackers||[]).find(x=>String(x.imei)==='864275078490847' || String(x.name).toLowerCase().includes('skoda'));
if(s && s.lat!=null && s.lon!=null){
map.setView([s.lat,s.lon],14);
}
}
let errCount=0;
let dataLoaded=false;
function processState(d, via){
const bar=document.getElementById("status-bar");
dataLoaded=true;
errCount=0;
const agg=d.map_aggregate||{};
let renderAggregate=agg;
const now=Date.now();
const nowCount=((agg.trackers||[]).length + (agg.beacons||[]).length);
if(nowCount>0){
lastGoodAggregate=agg;
lastGoodAggregateAt=now;
}else if(lastGoodAggregate && (now - lastGoodAggregateAt) <= LIVE_STICKY_HOLD_MS){
renderAggregate=lastGoodAggregate;
}
renderAggregateMap({map_aggregate:renderAggregate});
bar.className="status-bar";
bar.textContent="Live ("+via+") \u2022 "+new Date().toLocaleTimeString();
}
function handleJsonpData(d){ processState(d, "ngrok"); }
function fetchWithTimeout(url, opts, ms){
const ctrl=new AbortController();
const timer=setTimeout(()=>ctrl.abort(), ms);
return fetch(url, {...opts, signal:ctrl.signal}).finally(()=>clearTimeout(timer));
}
async function tryFetch(url, bypassHeader){
try{
const resp=await fetchWithTimeout(url, {
headers: {"Accept":"application/json", [bypassHeader]:"1"},
mode:"cors", cache:"no-store"
}, 6000);
if(!resp.ok) return null;
const txt=await resp.text();
if(txt.trim().charAt(0)!=='{') return null;
return JSON.parse(txt);
}catch(e){ return null; }
}
async function tryGist(){
try{
const resp=await fetchWithTimeout(API_GIST+"?_t="+Date.now(), {cache:"no-store"}, 8000);
if(!resp.ok) return null;
const d=await resp.json();
return (d&&d.map_aggregate)?d:null;
}catch(e){ return null; }
}
function raceSource(name, fn){
return fn().then(d=>d?{name,data:d}:Promise.reject("no data"));
}
async function refresh(){
if(!configLoaded) return;
const bar=document.getElementById("status-bar");
if(activeSource!=="none"){
let fn=null;
if(activeSource==="ngrok") fn=()=>tryFetch(API_STATE,"ngrok-skip-browser-warning");
else if(activeSource==="tunnel") fn=()=>tryFetch(API_STATE_FB,"Bypass-Tunnel-Reminder");
else if(activeSource==="gist") fn=tryGist;
if(fn){
const d=await fn();
if(d){ processState(d,activeSource); return; }
}
activeSource="none";
}
try{
const winner=await Promise.any([
raceSource("ngrok",()=>tryFetch(API_STATE,"ngrok-skip-browser-warning")),
raceSource("tunnel",()=>tryFetch(API_STATE_FB,"Bypass-Tunnel-Reminder")),
raceSource("gist",tryGist)
]);
activeSource=winner.name;
processState(winner.data,winner.name);
return;
}catch(e){}
errCount++;
bar.className="status-bar error";
bar.textContent="Connecting ("+errCount+")...";
}
refresh();
setInterval(refresh,4000);
document.getElementById("map-fit-btn").addEventListener("click", mapFitBounds);
document.getElementById("map-skoda-btn").addEventListener("click", mapCenterSkoda);
document.getElementById("map-legend-btn").addEventListener("click", ()=>{
if(!legendCtl || !map) return;
if(legendVisible){
map.removeControl(legendCtl);
legendVisible=false;
document.getElementById("map-legend-btn").textContent='Show Legend';
}else{
legendCtl.addTo(map);
legendVisible=true;
document.getElementById("map-legend-btn").textContent='Hide Legend';
}
});
document.getElementById("map-trackers-toggle").addEventListener("change", ()=>{ if(latestAggregate) renderAggregateMap({map_aggregate:latestAggregate}); });
document.getElementById("map-beacons-toggle").addEventListener("change", ()=>{ if(latestAggregate) renderAggregateMap({map_aggregate:latestAggregate}); });
</script>
</body>
</html>