Repository navigation
Expand file tree
/
Copy pathmesh-mapper.py
More file actions
2362 lines (2247 loc) · 96.5 KB
/
Copy pathmesh-mapper.py
File metadata and controls
2362 lines (2247 loc) · 96.5 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
#!/usr/bin/env python3
import requests
import json
import logging
import threading
import serial
import serial.tools.list_ports
import time
import csv
import os
from datetime import datetime
from flask import Flask, request, jsonify, redirect, url_for, render_template_string, send_file
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import zmq
from zmq.error import ZMQError
# Ensure file paths are absolute
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
# ----------------------
# Global Variables & Files
# ----------------------
tracked_pairs = {}
detection_history = [] # For CSV logging and KML generation
# Changed: Instead of one selected port, we allow up to three.
SELECTED_PORTS = {} # key will be 'port1', 'port2', 'port3'
BAUD_RATE = 115200
staleThreshold = 60 # Global stale threshold in seconds (changed from 300 seconds -> 1 minute)
# For each port, we track its connection status.
serial_connected_status = {} # e.g. {"port1": True, "port2": False, ...}
# Mapping to merge fragmented detections: port -> last seen mac
last_mac_by_port = {}
# Track open serial objects for cleanup
serial_objs = {}
serial_objs_lock = threading.Lock()
startup_timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Updated detections CSV header to include faa_data.
CSV_FILENAME = os.path.join(BASE_DIR, f"detections_{startup_timestamp}.csv")
KML_FILENAME = os.path.join(BASE_DIR, f"detections_{startup_timestamp}.kml")
FAA_LOG_FILENAME = os.path.join(BASE_DIR, "faa_log.csv") # FAA log CSV remains basic
# Write CSV header for detections.
with open(CSV_FILENAME, mode='w', newline='') as csvfile:
fieldnames = [
'timestamp', 'mac', 'rssi', 'drone_lat', 'drone_long',
'drone_altitude', 'pilot_lat', 'pilot_long', 'basic_id', 'faa_data'
]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
# Create FAA log CSV with header if not exists.
if not os.path.exists(FAA_LOG_FILENAME):
with open(FAA_LOG_FILENAME, mode='w', newline='') as csvfile:
fieldnames = ['timestamp', 'mac', 'remote_id', 'faa_response']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
# --- Alias Persistence ---
ALIASES_FILE = os.path.join(BASE_DIR, "aliases.json")
ALIASES = {}
if os.path.exists(ALIASES_FILE):
try:
with open(ALIASES_FILE, "r") as f:
ALIASES = json.load(f)
except Exception as e:
print("Error loading aliases:", e)
def save_aliases():
global ALIASES
try:
with open(ALIASES_FILE, "w") as f:
json.dump(ALIASES, f)
except Exception as e:
print("Error saving aliases:", e)
# ----------------------
# FAA Cache Persistence
# ----------------------
FAA_CACHE_FILE = os.path.join(BASE_DIR, "faa_cache.csv")
FAA_CACHE = {}
# Load FAA cache from file
if os.path.exists(FAA_CACHE_FILE):
try:
with open(FAA_CACHE_FILE, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
key = (row['mac'], row['remote_id'])
FAA_CACHE[key] = json.loads(row['faa_response'])
except Exception as e:
print("Error loading FAA cache:", e)
def write_to_faa_cache(mac, remote_id, faa_data):
key = (mac, remote_id)
FAA_CACHE[key] = faa_data
try:
file_exists = os.path.isfile(FAA_CACHE_FILE)
with open(FAA_CACHE_FILE, "a", newline='') as csvfile:
fieldnames = ["mac", "remote_id", "faa_response"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not file_exists:
writer.writeheader()
writer.writerow({
"mac": mac,
"remote_id": remote_id,
"faa_response": json.dumps(faa_data)
})
except Exception as e:
print("Error writing to FAA cache:", e)
# ----------------------
# KML Generation (including FAA data)
# ----------------------
def generate_kml():
kml_lines = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<kml xmlns="http://www.opengis.net/kml/2.2">',
'<Document>',
f'<name>Detections {startup_timestamp}</name>'
]
for mac, det in tracked_pairs.items():
remoteIdStr = ""
if det.get("basic_id"):
remoteIdStr = " (RemoteID: " + det.get("basic_id") + ")"
if det.get("faa_data"):
remoteIdStr += " FAA: " + json.dumps(det.get("faa_data"))
# Drone placemark
kml_lines.append(f'<Placemark><name>Drone {mac}{remoteIdStr}</name>')
kml_lines.append('<Style><IconStyle><scale>1.2</scale>'
'<Icon><href>http://maps.google.com/mapfiles/kml/shapes/heliport.png</href></Icon>'
'</IconStyle></Style>')
kml_lines.append(f'<Point><coordinates>{det.get("drone_long",0)},{det.get("drone_lat",0)},0</coordinates></Point>')
kml_lines.append('</Placemark>')
# Pilot placemark
kml_lines.append(f'<Placemark><name>Pilot {mac}{remoteIdStr}</name>')
kml_lines.append('<Style><IconStyle><scale>1.2</scale>'
'<Icon><href>http://maps.google.com/mapfiles/kml/shapes/man.png</href></Icon>'
'</IconStyle></Style>')
kml_lines.append(f'<Point><coordinates>{det.get("pilot_long",0)},{det.get("pilot_lat",0)},0</coordinates></Point>')
kml_lines.append('</Placemark>')
kml_lines.append('</Document></kml>')
with open(KML_FILENAME, "w") as f:
f.write("\n".join(kml_lines))
print("Updated KML file:", KML_FILENAME)
# Generate initial KML so the file exists from startup
generate_kml()
# ----------------------
# Detection Update & CSV Logging
# ----------------------
def update_detection(detection):
mac = detection.get("mac")
if not mac:
return
# Retrieve new drone coordinates from the detection
new_drone_lat = detection.get("drone_lat", 0)
new_drone_long = detection.get("drone_long", 0)
valid_drone = (new_drone_lat != 0 and new_drone_long != 0)
# If the new detection has invalid (0) drone coordinates...
if not valid_drone:
# If there is an existing record with valid coordinates, update only non-coordinate fields.
if mac in tracked_pairs:
existing = tracked_pairs[mac]
if existing.get("drone_lat", 0) != 0 and existing.get("drone_long", 0) != 0:
# Update fields other than drone coordinates
for field in ['rssi', 'basic_id', 'drone_altitude']:
if field in detection:
existing[field] = detection[field]
# Update pilot coordinates only if they are valid (non zero)
new_pilot_lat = detection.get("pilot_lat", 0)
new_pilot_long = detection.get("pilot_long", 0)
if new_pilot_lat != 0:
existing["pilot_lat"] = new_pilot_lat
if new_pilot_long != 0:
existing["pilot_long"] = new_pilot_long
existing["last_update"] = time.time()
print(f"Ignored update for {mac} due to invalid drone coordinates, preserving previous valid coordinates.")
return
# No previous valid record exists: ignore the detection entirely.
print(f"Ignored detection for {mac} because drone coordinates are zero.")
return
# Otherwise, use the provided non-zero coordinates.
detection["drone_lat"] = new_drone_lat
detection["drone_long"] = new_drone_long
detection["drone_altitude"] = detection.get("drone_altitude", 0)
detection["pilot_lat"] = detection.get("pilot_lat", 0)
detection["pilot_long"] = detection.get("pilot_long", 0)
detection["last_update"] = time.time()
remote_id = detection.get("basic_id")
# Try exact cache lookup by (mac, remote_id), then fallback to any cached data for this mac, then to previous tracked_pairs entry
if mac:
# Exact match if basic_id provided
if remote_id:
key = (mac, remote_id)
if key in FAA_CACHE:
detection["faa_data"] = FAA_CACHE[key]
# Fallback: any cached FAA data for this mac
if "faa_data" not in detection:
for (c_mac, _), faa_data in FAA_CACHE.items():
if c_mac == mac:
detection["faa_data"] = faa_data
break
# Fallback: last known FAA data in tracked_pairs
if "faa_data" not in detection and mac in tracked_pairs and "faa_data" in tracked_pairs[mac]:
detection["faa_data"] = tracked_pairs[mac]["faa_data"]
tracked_pairs[mac] = detection
detection_history.append(detection.copy())
print("Updated tracked_pairs:", tracked_pairs)
with open(CSV_FILENAME, mode='a', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=[
'timestamp', 'mac', 'rssi', 'drone_lat', 'drone_long',
'drone_altitude', 'pilot_lat', 'pilot_long', 'basic_id', 'faa_data'
])
writer.writerow({
'timestamp': datetime.now().isoformat(),
'mac': mac,
'rssi': detection.get('rssi', ''),
'drone_lat': detection.get('drone_lat', ''),
'drone_long': detection.get('drone_long', ''),
'drone_altitude': detection.get('drone_altitude', ''),
'pilot_lat': detection.get('pilot_lat', ''),
'pilot_long': detection.get('pilot_long', ''),
'basic_id': detection.get('basic_id', ''),
'faa_data': json.dumps(detection.get('faa_data', {}))
})
generate_kml()
# ----------------------
# Global Follow Lock & Color Overrides
# ----------------------
followLock = {"type": None, "id": None, "enabled": False}
colorOverrides = {}
# ----------------------
# FAA Query Helper Functions
# ----------------------
def create_retry_session(retries=3, backoff_factor=2, status_forcelist=(502, 503, 504)):
logging.debug("Creating retry-enabled session with custom headers for FAA query.")
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:137.0) Gecko/20100101 Firefox/137.0",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "en-US,en;q=0.5",
"Referer": "https://uasdoc.faa.gov/listdocs",
"client": "external"
})
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
raise_on_status=False
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("https://", adapter)
return session
def refresh_cookie(session):
homepage_url = "https://uasdoc.faa.gov/listdocs"
logging.debug("Refreshing FAA cookie by requesting homepage: %s", homepage_url)
try:
response = session.get(homepage_url, timeout=30)
logging.debug("FAA homepage response code: %s", response.status_code)
except requests.exceptions.RequestException as e:
logging.exception("Error refreshing FAA cookie: %s", e)
def query_remote_id(session, remote_id):
endpoint = "https://uasdoc.faa.gov/api/v1/serialNumbers"
params = {
"itemsPerPage": 8,
"pageIndex": 0,
"orderBy[0]": "updatedAt",
"orderBy[1]": "DESC",
"findBy": "serialNumber",
"serialNumber": remote_id
}
logging.debug("Querying FAA API endpoint: %s with params: %s", endpoint, params)
try:
response = session.get(endpoint, params=params, timeout=30)
logging.debug("FAA Request URL: %s", response.url)
if response.status_code != 200:
logging.error("FAA HTTP error: %s - %s", response.status_code, response.reason)
return None
return response.json()
except Exception as e:
logging.exception("Error querying FAA API: %s", e)
return None
# ----------------------
# New FAA Query API Endpoint
# ----------------------
@app.route('/api/query_faa', methods=['POST'])
def api_query_faa():
data = request.get_json()
mac = data.get("mac")
remote_id = data.get("remote_id")
if not mac or not remote_id:
return jsonify({"status": "error", "message": "Missing mac or remote_id"}), 400
session = create_retry_session()
refresh_cookie(session)
faa_result = query_remote_id(session, remote_id)
if faa_result is None:
return jsonify({"status": "error", "message": "FAA query failed"}), 500
if mac in tracked_pairs:
tracked_pairs[mac]["faa_data"] = faa_result
else:
tracked_pairs[mac] = {"basic_id": remote_id, "faa_data": faa_result}
write_to_faa_cache(mac, remote_id, faa_result)
timestamp = datetime.now().isoformat()
try:
with open(FAA_LOG_FILENAME, "a", newline='') as csvfile:
fieldnames = ["timestamp", "mac", "remote_id", "faa_response"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({
"timestamp": timestamp,
"mac": mac,
"remote_id": remote_id,
"faa_response": json.dumps(faa_result)
})
except Exception as e:
print("Error writing to FAA log CSV:", e)
generate_kml()
return jsonify({"status": "ok", "faa_data": faa_result})
# ----------------------
# HTML & JS (UI) Section
# ----------------------
# Updated: The selection page now has three dropdowns.
PORT_SELECTION_PAGE = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Select USB Serial Ports</title>
<style>
/* Hide tile seams */
.leaflet-tile {
border: none !important;
box-shadow: none !important;
background-color: transparent !important;
image-rendering: crisp-edges !important;
}
.leaflet-container {
background-color: black !important;
}
body { background-color: black; color: lime; font-family: monospace; text-align: center;
zoom: 1.15;
}
pre { font-size: 16px; margin: 20px auto; }
form {
display: inline-block;
text-align: left;
}
li { list-style: none; margin: 10px 0; }
select { background-color: #333; color: lime; border: none; padding: 3px; margin-bottom: 10px; }
label { font-size: 18px; }
/* Style and center the select-ports submit button */
button[type="submit"] {
display: block;
margin: 10px auto;
padding: 5px;
border: 1px solid lime;
background: linear-gradient(to right, lime, yellow);
color: black;
font-family: monospace;
cursor: pointer;
outline: none;
border-radius: 10px;
}
/* Shrink only the logo ASCII block */
pre.logo-art {
display: inline-block;
margin: 2px auto 0;
}
/* Gradient styling for ASCII art below the button */
pre.ascii-art {
background: linear-gradient(to right, blue, purple, pink, lime, green);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-family: monospace;
padding: 10px;
font-size: 90%;
}
h1 {
background: linear-gradient(to right, lime, yellow);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin: 2px 0;
}
</style>
</head>
<body>
<pre class="ascii-art logo-art">{{ logo_ascii }}</pre>
<h1>Select Up to 3 USB Serial Ports</h1>
<form method="POST" action="/select_ports">
<label>Port 1:</label><br>
<select id="port1" name="port1">
<option value="">--None--</option>
{% for port in ports %}
<option value="{{ port.device }}">{{ port.device }} - {{ port.description }}</option>
{% endfor %}
</select><br>
<label>Port 2:</label><br>
<select id="port2" name="port2">
<option value="">--None--</option>
{% for port in ports %}
<option value="{{ port.device }}">{{ port.device }} - {{ port.description }}</option>
{% endfor %}
</select><br>
<label>Port 3:</label><br>
<select id="port3" name="port3">
<option value="">--None--</option>
{% for port in ports %}
<option value="{{ port.device }}">{{ port.device }} - {{ port.description }}</option>
{% endfor %}
</select><br>
<button type="submit">Select Ports</button>
</form>
<pre class="ascii-art">{{ bottom_ascii }}</pre>
<script>
// Dynamically refresh available USB port list every 0.5 seconds
function refreshPortOptions() {
fetch('/api/ports')
.then(res => res.json())
.then(data => {
['port1','port2','port3'].forEach(name => {
const select = document.getElementById(name);
if (!select) return;
const current = select.value;
// rebuild options
select.innerHTML = '<option value="">--None--</option>' +
data.ports.map(p => `<option value="${p.device}">${p.device} - ${p.description}</option>`).join('');
select.value = current;
});
})
.catch(err => console.error('Error refreshing ports:', err));
}
// Refresh ports every 500ms until the user interacts
var refreshInterval = setInterval(refreshPortOptions, 500);
['port1','port2','port3'].forEach(function(name) {
var select = document.getElementById(name);
if (select) {
// Stop auto-refresh on user interaction (focus, mouse, or touch)
['focus', 'mousedown', 'touchstart'].forEach(function(evt) {
select.addEventListener(evt, function() { clearInterval(refreshInterval); });
});
select.addEventListener('change', function() { clearInterval(refreshInterval); });
}
});
window.onload = function() {
refreshPortOptions();
}
</script>
</body>
</html>
'''
# Updated: The main mapping page now shows serial statuses for all selected USB devices.
HTML_PAGE = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mesh Mapper</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin=""></script>
<style>
/* Hide tile seams on all map layers */
.leaflet-tile {
border: none !important;
box-shadow: none !important;
background-color: transparent !important;
image-rendering: crisp-edges !important;
transition: none !important;
}
.leaflet-container {
background-color: black !important;
}
/* Toggle switch styling */
.switch { position: relative; display: inline-block; vertical-align: middle; width: 40px; height: 20px; }
.switch input { opacity: 0; width: 0; height: 0; }
.slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #555; transition: .4s; border-radius: 20px; }
.slider:before {
position: absolute;
content: "";
height: 16px;
width: 16px;
left: 2px;
top: 50%;
background-color: lime;
border: 1px solid #9B30FF;
transition: .4s;
border-radius: 50%;
transform: translateY(-50%);
}
.switch input:checked + .slider { background-color: lime; }
.switch input:checked + .slider:before {
transform: translateX(20px) translateY(-50%);
border: 1px solid #9B30FF;
}
body, html { margin: 0; padding: 0; background-color: black; }
#map { height: 100vh; }
/* Layer control styling (bottom left) reduced by 30% */
#layerControl {
position: absolute;
bottom: 10px;
left: 10px;
background: rgba(0,0,0,0.8);
padding: 3.5px; /* reduced from 5px */
border: 0.7px solid lime; /* reduced border thickness */
border-radius: 7px; /* reduced from 10px */
color: #FF00FF;
font-family: monospace;
font-size: 0.7em; /* scale font by 70% */
z-index: 1000;
}
/* Basemap label always neon pink */
#layerControl > label {
color: #FF00FF;
}
#layerControl select,
#layerControl select option {
background-color: #333;
color: lime;
border: none;
padding: 2.1px;
font-size: 0.7em;
}
#filterBox {
position: absolute;
top: 10px;
right: 10px;
background: rgba(0,0,0,0.8);
padding: 8px;
border: 1px solid lime;
border-radius: 10px;
color: lime;
font-family: monospace;
max-width: 300px;
max-height: 80vh;
z-index: 1000;
}
#filterBox.collapsed #filterContent {
display: none;
}
#filterBox:not(.collapsed) #filterHeader h3 {
visibility: hidden;
}
#filterHeader {
display: flex;
align-items: center;
}
#filterHeader h3 {
flex: 1;
text-align: center;
margin: 0;
font-size: 1em;
display: block;
width: 100%;
color: #FF00FF;
}
/* USB status box styling (bottom right) - now even with the map layer select */
#serialStatus {
position: absolute;
bottom: 10px;
right: 10px;
background: rgba(0,0,0,0.8);
padding: 3px; /* reduced from 5px */
border: 0.7px solid lime; /* reduced border thickness */
border-radius: 7px; /* reduced from 10px */
color: lime;
font-family: monospace;
font-size: 0.7em; /* scale font by 70% */
z-index: 1000;
}
#serialStatus div { margin-bottom: 5px; }
/* Remove extra bottom padding from the last USB item */
#serialStatus div:last-child { margin-bottom: 0; }
.usb-name { color: #FF00FF; } /* Neon pink for device names */
.drone-item {
display: inline-block;
border: 1px solid;
margin: 2px;
padding: 3px;
cursor: pointer;
}
.placeholder {
border: 2px solid transparent;
border-image: linear-gradient(to right, lime 85%, yellow 15%) 1;
border-radius: 5px;
min-height: 100px;
margin-top: 5px;
overflow-y: auto;
max-height: 200px;
}
.selected { background-color: rgba(255,255,255,0.2); }
.leaflet-popup-content-wrapper { background-color: black; color: lime; font-family: monospace; border: 2px solid lime; border-radius: 10px;
width: 220px !important;
max-width: 220px;
zoom: 1.15;
}
.leaflet-popup-content {
font-size: 0.75em;
line-height: 1.2em;
white-space: normal;
}
.leaflet-popup-tip { background: lime; }
button { margin-top: 4px; padding: 3px; font-size: 0.8em; border: none; background-color: #333; color: lime; cursor: pointer; }
select { background-color: #333; color: lime; border: none; padding: 3px; }
.leaflet-control-zoom-in, .leaflet-control-zoom-out {
background: rgba(0,0,0,0.8);
color: lime;
border: 1px solid lime;
border-radius: 5px;
}
/* Style zoom control container to match drone box */
.leaflet-control-zoom.leaflet-bar {
background: rgba(0,0,0,0.8);
border: 1px solid lime;
border-radius: 10px;
}
.leaflet-control-zoom.leaflet-bar a {
background: transparent;
color: lime;
border: none;
width: 30px;
height: 30px;
line-height: 30px;
text-align: center;
padding: 0;
user-select: none;
caret-color: transparent;
cursor: pointer;
outline: none;
}
.leaflet-control-zoom.leaflet-bar a:focus {
outline: none;
caret-color: transparent;
}
.leaflet-control-zoom.leaflet-bar a:hover {
background: rgba(255,255,255,0.1);
}
.leaflet-control-zoom-in:hover, .leaflet-control-zoom-out:hover { background-color: #222; }
input#aliasInput {
background-color: #222;
color: #87CEEB; /* pastel blue (updated) */
border: 1px solid #FF00FF;
padding: 4px;
font-size: 1.06em;
caret-color: #87CEEB;
outline: none;
}
.leaflet-popup-content-wrapper input:not(#aliasInput) {
caret-color: transparent;
}
/* Popup button and input sizing */
.leaflet-popup-content-wrapper button {
font-size: 1.19em;
padding: 6px;
margin-top: 7px;
}
.leaflet-popup-content-wrapper input[type="text"],
.leaflet-popup-content-wrapper input[type="range"] {
font-size: 0.75em;
padding: 2px;
}
/* Disable tile transitions to prevent blur and hide tile seams */
.leaflet-tile {
display: block;
margin: 0;
padding: 0;
transition: none !important;
image-rendering: crisp-edges;
background-color: black;
border: none !important;
box-shadow: none !important;
}
.leaflet-container {
background-color: black;
}
/* Disable text cursor in drone list and filter toggle */
.drone-item, #filterToggle {
user-select: none;
caret-color: transparent;
outline: none;
}
.drone-item:focus, #filterToggle:focus {
outline: none;
caret-color: transparent;
}
/* Cyberpunk styling for filter headings */
#filterContent > h3:nth-of-type(1) {
color: #FF00FF; /* Active Drones in magenta */
text-align: center; /* center text */
font-size: 1.1em; /* slightly larger font */
}
#filterContent > h3:nth-of-type(2) {
color: #FF00FF; /* more magenta */
text-align: center; /* center text */
font-size: 1.1em; /* slightly larger font */
}
/* Lime-green hacky dashes around filter headers */
#filterContent > h3 {
display: block;
width: 100%;
text-align: center;
margin: 0.5em 0;
}
#filterContent > h3::before,
#filterContent > h3::after {
content: '---';
color: lime;
margin: 0 6px;
}
/* Download buttons styling */
#downloadButtons {
display: flex;
justify-content: space-between;
margin-top: 8px;
}
#downloadButtons button {
flex: 1;
margin: 0 4px;
padding: 4px;
font-size: 0.8em;
border: 1px solid lime;
border-radius: 5px;
background: #333;
color: lime;
font-family: monospace;
cursor: pointer;
}
#downloadButtons button:focus {
outline: none;
caret-color: transparent;
}
/* Gradient blue border flush with heading */
#downloadSection {
padding: 0 8px 8px 8px; /* no top padding so border is flush with heading */
margin-top: 12px;
}
/* Gradient for Download Logs header */
#downloadSection .downloadHeader {
margin: 10px 0 5px 0;
text-align: center;
background: linear-gradient(to right, lime, yellow);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
/* Staleout slider styling – match popup sliders */
#staleoutSlider {
-webkit-appearance: none;
width: 80%;
height: 3px;
background: transparent;
border: none;
outline: none;
}
#staleoutSlider::-webkit-slider-runnable-track {
width: 100%;
height: 3px;
background: #9B30FF;
border: none;
border-radius: 0;
}
#staleoutSlider::-webkit-slider-thumb {
-webkit-appearance: none;
height: 16px;
width: 16px;
background: lime;
border: 1px solid #9B30FF;
margin-top: -6.5px;
border-radius: 50%;
cursor: pointer;
}
/* Firefox */
#staleoutSlider::-moz-range-track {
width: 100%;
height: 3px;
background: #9B30FF;
border: none;
border-radius: 0;
}
#staleoutSlider::-moz-range-thumb {
height: 16px;
width: 16px;
background: lime;
border: 1px solid #9B30FF;
margin-top: -6.5px;
border-radius: 50%;
cursor: pointer;
}
/* IE */
#staleoutSlider::-ms-fill-lower,
#staleoutSlider::-ms-fill-upper {
background: #9B30FF;
border: none;
border-radius: 2px;
}
#staleoutSlider::-ms-thumb {
height: 16px;
width: 16px;
background: lime;
border: 1px solid #9B30FF;
border-radius: 50%;
cursor: pointer;
margin-top: -6.5px;
}
/* Popup range sliders styling */
.leaflet-popup-content-wrapper input[type="range"] {
-webkit-appearance: none;
width: 100%;
height: 3px;
background: transparent;
border: none;
}
.leaflet-popup-content-wrapper input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
height: 16px;
width: 16px;
background: lime;
border: 1px solid #9B30FF;
margin-top: -6.5px;
border-radius: 50%;
cursor: pointer;
}
.leaflet-popup-content-wrapper input[type="range"]::-moz-range-thumb {
height: 16px;
width: 16px;
background: lime;
border: 1px solid #9B30FF;
margin-top: -6.5px;
border-radius: 50%;
cursor: pointer;
}
/* Ensure popup sliders have the same track styling */
.leaflet-popup-content-wrapper input[type="range"]::-webkit-slider-runnable-track {
width: 100%;
height: 3px;
background: #9B30FF;
border: 1px solid lime;
border-radius: 0;
}
.leaflet-popup-content-wrapper input[type="range"]::-moz-range-track {
width: 100%;
height: 3px;
background: #9B30FF;
border: 1px solid lime;
border-radius: 0;
}
/* 1) Remove rounded corners from all sliders */
/* WebKit */
input[type="range"]::-webkit-slider-runnable-track,
input[type="range"]::-webkit-slider-thumb {
border-radius: 0;
}
/* Firefox */
input[type="range"]::-moz-range-track,
input[type="range"]::-moz-range-thumb {
border-radius: 0;
}
/* IE */
input[type="range"]::-ms-fill-lower,
input[type="range"]::-ms-fill-upper,
input[type="range"]::-ms-thumb {
border-radius: 0;
}
/* 2) Smaller, side-by-side Observer buttons */
.leaflet-popup-content-wrapper #lock-observer,
.leaflet-popup-content-wrapper #unlock-observer {
display: inline-block;
font-size: 0.9em;
padding: 4px 6px;
margin: 2px 4px 2px 0;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="layerControl">
<label>Basemap:</label>
<select id="layerSelect">
<option value="osmStandard">OSM Standard</option>
<option value="osmHumanitarian">OSM Humanitarian</option>
<option value="cartoPositron">CartoDB Positron</option>
<option value="cartoDarkMatter">CartoDB Dark Matter</option>
<option value="esriWorldImagery" selected>Esri World Imagery</option>
<option value="esriWorldTopo">Esri World TopoMap</option>
<option value="esriDarkGray">Esri Dark Gray Canvas</option>
<option value="openTopoMap">OpenTopoMap</option>
</select>
</div>
<div id="filterBox">
<div id="filterHeader">
<h3>Drones</h3>
<span id="filterToggle" style="cursor: pointer; font-size: 20px;">[-]</span>
</div>
<div id="filterContent">
<h3>Active Drones</h3>
<div id="activePlaceholder" class="placeholder"></div>
<h3>Inactive Drones</h3>
<div id="inactivePlaceholder" class="placeholder"></div>
<!-- Downloads Section -->
<div id="downloadSection">
<h4 class="downloadHeader">Download Logs</h4>
<div id="downloadButtons">
<button id="downloadCsv">CSV</button>
<button id="downloadKml">KML</button>
<button id="downloadAliases">Aliases</button>
</div>
</div>
<div style="margin-top:8px; display:flex; align-items:center; justify-content:center; height:20px;">
<label style="color:lime; font-family:monospace; margin-right:8px;">Node Mode</label>
<label class="switch">
<input type="checkbox" id="nodeModeMainSwitch">
<span class="slider"></span>
</label>
</div>
<div style="color:#FF00FF; font-family:monospace; font-size:0.75em; white-space:normal; line-height:1.2; margin-top:4px; text-align:center;">
Polls detections every second instead of every 200 ms to reduce CPU/battery use and optimizes API for Node Mode.
</div>
<div id="zmqSection" style="margin-top:8px; text-align:center;">
<div style="margin-top:8px; display:flex; align-items:center; justify-content:center; height:20px;">
<label style="color:lime; font-family:monospace; margin-right:8px;">ZMQ Mode</label>
<label class="switch">
<input type="checkbox" id="zmqModeSwitch">
<span class="slider"></span>
</label>
</div>
<div style="margin-top:5px;">
<div style="display:flex; justify-content:center; align-items:center; margin-top:5px;">
<input type="text" id="zmqIP" placeholder="127.0.0.1" style="background-color:#222;color:#FF00FF;border:1px solid #FF00FF;width:55%;padding:4px;margin-right:5px;">
<span style="color:lime;">:</span>
<input type="text" id="zmqPort" placeholder="4224" style="background-color:#222;color:#FF00FF;border:1px solid #FF00FF;width:25%;padding:4px;margin-left:5px;">
</div>
<button id="applyZmqSettings" style="margin-top:5px;width:40%;padding:5px;border:1px solid lime;background:#333;color:lime;font-family:monospace;cursor:pointer;border-radius:5px;">Update ZMQ</button>
</div>
<div style="color:#FF00FF;font-family:monospace;font-size:0.75em;white-space:normal;line-height:1.2;margin-top:4px;text-align:center;">
Connect to ZMQ decoder via direct IP connection
</div>
</div>
<!-- Staleout Slider -->
<div style="margin-top:8px; text-align:center;">
<label style="color:lime; font-family:monospace; margin-bottom:4px; display:block;">Staleout Time</label>
<input type="range" id="staleoutSlider" min="1" max="5" step="1" value="1"
style="width:80%; border:1px solid lime; margin-bottom:4px;">
<div id="staleoutValue" style="color:lime; font-family:monospace;">1 min</div>
</div>
</div>
</div>
<div id="serialStatus">
<!-- USB port statuses will be injected here -->
</div>
<script>
// Round tile positions to integer pixels to eliminate seams
L.DomUtil.setPosition = (function() {
var original = L.DomUtil.setPosition;
return function(el, point) {
var rounded = L.point(Math.round(point.x), Math.round(point.y));
original.call(this, el, rounded);
};
})();
// --- Node Mode Main Switch & Polling Interval Sync ---
document.addEventListener('DOMContentLoaded', () => {
// restore follow-lock on reload
const storedLock = localStorage.getItem('followLock');
if (storedLock) {
try {
followLock = JSON.parse(storedLock);
if (followLock.type === 'observer') {
updateObserverPopupButtons();
} else if (followLock.type === 'drone' || followLock.type === 'pilot') {
updateMarkerButtons(followLock.type, followLock.id);
}
} catch (e) { console.error('Failed to restore followLock', e); }
}
// Ensure Node Mode default is off if unset
if (localStorage.getItem('nodeMode') === null) {