-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfusion.py
More file actions
executable file
·661 lines (580 loc) · 26.3 KB
/
Copy pathfusion.py
File metadata and controls
executable file
·661 lines (580 loc) · 26.3 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
#!/usr/bin/env python3
"""
Fantom Finder fusion service.
Listens for OpenDroneID Remote ID broadcasts (Wi-Fi NAN beacons + BLE 5
extended advertisements via libopendroneid_receiver-android-style scan) and
matches them against blah2 radar tracks. Emits verdicts:
CONFIRMED broadcast matches a radar track at the claimed lat/lon
PHANTOM broadcast claims a position with no radar track nearby
DECEPTION radar track present but rotor signature contradicts the
claimed UAV class (e.g. "Cessna" claim with quadrotor harmonics)
Verdicts are persisted to the existing nemesis-tracker alerts table and
streamed to the dashboard via SSE.
Designed to run on the Pi alongside nemesis-tracker. Receives Remote ID via
either:
(a) `python3 -m opendroneid_recv` over UDP localhost (preferred — uses
libopendroneid Python bindings if installed)
(b) ESP32-S3 sketch in firmware/esp32_droneid.ino streaming JSON over
USB-CDC at 115200 baud.
Usage:
python3 fusion.py --tracker http://localhost:3000 --droneid-port 7878
"""
import argparse
import asyncio
import json
import logging
import math
import time
from collections import defaultdict, deque
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Optional
import aiohttp
from aiohttp import web
logger = logging.getLogger("phantom-proof")
# Where the standalone dashboard lives — served at GET / on the fusion port.
DASHBOARD_HTML = Path(__file__).parent / "dashboard.html"
# -----------------------------------------------------------------------------
# Geo helpers
# -----------------------------------------------------------------------------
EARTH_R = 6_371_000.0 # meters
def haversine_m(lat1, lon1, lat2, lon2) -> float:
"""Great-circle distance in meters."""
p1, p2 = math.radians(lat1), math.radians(lat2)
dp = math.radians(lat2 - lat1)
dl = math.radians(lon2 - lon1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * EARTH_R * math.asin(math.sqrt(a))
# -----------------------------------------------------------------------------
# Remote ID model (subset of the ASD-STAN / ASTM F3411 message set)
# -----------------------------------------------------------------------------
@dataclass
class RemoteIDClaim:
uas_id: str # UA serial / session ID
timestamp: float # epoch seconds when received
latitude: Optional[float] = None
longitude: Optional[float] = None
altitude_m: Optional[float] = None
speed_m_s: Optional[float] = None
heading_deg: Optional[float] = None
operator_id: Optional[str] = None
ua_type: Optional[str] = None # e.g. "Helicopter_Multirotor", "Aeroplane"
ua_class: Optional[str] = None # EU UA class C0..C6
raw: dict = field(default_factory=dict)
@classmethod
def from_json(cls, msg: dict) -> "RemoteIDClaim":
loc = msg.get("location", {})
basic = msg.get("basic_id", {})
return cls(
uas_id=basic.get("uas_id") or msg.get("uas_id") or "unknown",
timestamp=msg.get("ts", time.time()),
latitude=loc.get("latitude"),
longitude=loc.get("longitude"),
altitude_m=loc.get("altitude_m"),
speed_m_s=loc.get("speed_m_s"),
heading_deg=loc.get("heading_deg"),
operator_id=msg.get("operator_id", {}).get("operator_id"),
ua_type=basic.get("ua_type"),
ua_class=basic.get("ua_class"),
raw=msg,
)
# -----------------------------------------------------------------------------
# Radar track snapshot pulled from blah2 / nemesis-tracker API
# -----------------------------------------------------------------------------
@dataclass
class RadarTrack:
track_id: str
timestamp: float
bistatic_range_m: float
doppler_hz: float
snr_db: Optional[float] = None
latitude: Optional[float] = None # if multilateration available
longitude: Optional[float] = None
inferred_class: Optional[str] = None # e.g. quadcopter | helicopter | aircraft | person | unknown
rotor_blade_count: Optional[int] = None
raw: dict = field(default_factory=dict)
# -----------------------------------------------------------------------------
# Verdict logic
# -----------------------------------------------------------------------------
@dataclass
class Verdict:
kind: str # CONFIRMED | PHANTOM | DECEPTION
claim: RemoteIDClaim
track: Optional[RadarTrack]
reason: str # human-readable "because" string
confidence: float # 0..1
# Tunables
MATCH_RADIUS_M = 80 # how close a radar track must be to the claim
MATCH_TIMEOUT_S = 3.0 # how long a claim waits for a matching track before PHANTOM
# Reverse-pass detector — flag aircraft-class radar tracks that have
# no ADS-B correlation. Operationally: someone is flying without
# identifying themselves (rogue drone, unequipped GA, military, or
# spoofed-off transponder). Mirrors ais_fusion's dark_vessel_loop on
# the airborne side; both publish DECEPTION via the SSE bus so
# cot_emitter exports them to TAK.
ROGUE_SWEEP_S = 5.0 # how often to walk the live track set
ROGUE_REALERT_S = 60.0 # don't re-fire on the same track within this window
SPEED_OF_LIGHT_MPS = 299_792_458.0
AIRCRAFT_RADIAL_MS = 60.0 # > this radial speed is aircraft territory (cars don't sustain it)
CLASS_CONTRADICTIONS = {
# (claim_ua_type, observed_class) -> "DECEPTION because"
("Aeroplane", "quadcopter"): "claim=fixed-wing, rotor harmonics show quadcopter",
("Aeroplane", "helicopter"): "claim=fixed-wing, rotor harmonics show helicopter",
("Helicopter_Multirotor", "fixed-wing"):
"claim=multirotor, no rotor harmonics observed",
}
def evaluate(claim: RemoteIDClaim, tracks: list[RadarTrack]) -> Verdict:
"""Decide a verdict for a Remote ID claim given current radar tracks.
Matching strategy:
A. Claim has lat/lon AND tracks have lat/lon → geographic match (haversine).
If NO tracks within MATCH_RADIUS_M of the claim → PHANTOM (do NOT fall
back to time-only matching; that defeats the whole point).
B. Claim has no lat/lon → fall back to time-window match: any active
track within MATCH_TIMEOUT_S. PHANTOM if there's no active track.
"""
geolocated_tracks = [t for t in tracks if t.latitude is not None and t.longitude is not None]
claim_has_geo = claim.latitude is not None and claim.longitude is not None
candidates: list[RadarTrack] = []
if claim_has_geo and geolocated_tracks:
# Mode A: geographic match. PHANTOM if nothing nearby.
for t in geolocated_tracks:
d = haversine_m(claim.latitude, claim.longitude, t.latitude, t.longitude)
if d <= MATCH_RADIUS_M:
candidates.append((d, t))
if not candidates:
nearest = min(
(haversine_m(claim.latitude, claim.longitude, t.latitude, t.longitude) for t in geolocated_tracks),
default=None,
)
return Verdict(
kind="PHANTOM",
claim=claim,
track=None,
reason=(
f"Remote ID claims UA {claim.uas_id} at "
f"({claim.latitude:.5f},{claim.longitude:.5f}); "
f"nearest radar track is {nearest:.0f} m away "
f"(threshold {MATCH_RADIUS_M} m)"
if nearest is not None else
f"no radar tracks present"
),
confidence=0.95,
)
# Pick the geographically nearest as the matched track.
candidates.sort(key=lambda x: x[0])
candidates = [t for _, t in candidates]
else:
# Mode B: no geo on claim — time-window fallback.
candidates = [t for t in tracks if abs(t.timestamp - claim.timestamp) < MATCH_TIMEOUT_S]
if not candidates:
return Verdict(
kind="PHANTOM",
claim=claim,
track=None,
reason=(
f"Remote ID claims UA {claim.uas_id} but no active radar "
f"track within {MATCH_TIMEOUT_S} s"
),
confidence=0.85,
)
# Pick the closest candidate. For DECEPTION we still need a candidate.
track = candidates[0]
if claim.ua_type and track.inferred_class:
key = (claim.ua_type, track.inferred_class)
if key in CLASS_CONTRADICTIONS:
return Verdict(
kind="DECEPTION",
claim=claim,
track=track,
reason=CLASS_CONTRADICTIONS[key],
confidence=0.85,
)
return Verdict(
kind="CONFIRMED",
claim=claim,
track=track,
reason=(
f"Remote ID UA {claim.uas_id} ({claim.ua_type or '?'}) matches "
f"radar track {track.track_id} ({track.inferred_class or '?'}) "
f"within {MATCH_RADIUS_M} m"
),
confidence=0.9,
)
# -----------------------------------------------------------------------------
# Tracker API client
# -----------------------------------------------------------------------------
class TrackerClient:
def __init__(self, base_url: str):
self.base_url = base_url.rstrip("/")
self._session: Optional[aiohttp.ClientSession] = None
async def __aenter__(self):
self._session = aiohttp.ClientSession()
return self
async def __aexit__(self, *exc):
if self._session:
await self._session.close()
async def list_tracks(self) -> list[RadarTrack]:
"""GET /api/tracks/live → {tracks: [...], total: N}.
Track dict shape (per nemesis-tracker tracker.py):
track_id, delay (km, bistatic), doppler (Hz), snr (dB),
category ('unknown' / 'aircraft' / ...), adsb_correlated (bool),
adsb_icao, adsb_flight, last_update (ts), etc.
"""
url = f"{self.base_url}/api/tracks/live"
async with self._session.get(url) as resp:
if resp.status != 200:
logger.warning("tracker GET %s -> %s", url, resp.status)
return []
data = await resp.json()
tracks: list[RadarTrack] = []
for row in data.get("tracks", []):
# nemesis-tracker fields: range_km, doppler_hz, snr_db,
# approx_location.{lat,lon}, adsb_correlated_icao, category.
# Older shape used: delay, doppler, snr, latitude, longitude.
# We accept both so the same client works against fake_tracker
# (legacy shape) and live nemesis-tracker (current shape).
range_km = row.get("range_km")
if range_km is None:
range_km = row.get("delay", 0) # legacy
loc = row.get("approx_location") or {}
lat = loc.get("lat") if loc else row.get("latitude")
lon = loc.get("lon") if loc else row.get("longitude")
tracks.append(RadarTrack(
track_id=str(row.get("track_id") or row.get("id") or "?"),
timestamp=row.get("last_seen") or row.get("last_update") or time.time(),
bistatic_range_m=float(range_km) * 1000.0,
doppler_hz=float(row.get("doppler_hz") or row.get("doppler") or 0),
snr_db=row.get("snr_db") or row.get("snr"),
latitude=lat,
longitude=lon,
inferred_class=row.get("category") or row.get("class"),
rotor_blade_count=row.get("blade_count"),
raw=row,
))
return tracks
async def post_alert(self, verdict: Verdict):
"""nemesis-tracker has no POST /api/alerts — verdicts live in fusion's
own SSE feed and dashboard. Kept as a no-op so callers don't break."""
return
# -----------------------------------------------------------------------------
# Remote ID listener (UDP JSON server)
# -----------------------------------------------------------------------------
class DroneIDListener(asyncio.DatagramProtocol):
def __init__(self, queue: asyncio.Queue):
self.queue = queue
def datagram_received(self, data, addr):
try:
msg = json.loads(data.decode("utf-8"))
self.queue.put_nowait(RemoteIDClaim.from_json(msg))
except Exception as e:
logger.warning("bad droneid msg from %s: %s", addr, e)
# -----------------------------------------------------------------------------
# Verdict ring buffer + SSE bus
# -----------------------------------------------------------------------------
class VerdictBus:
"""Holds the last N verdicts for the dashboard, plus an SSE fan-out."""
def __init__(self, capacity: int = 200):
self.history: deque[dict] = deque(maxlen=capacity)
self.subscribers: list[asyncio.Queue] = []
async def publish(self, verdict: Verdict):
now = time.time()
item = {
"kind": verdict.kind,
"uas_id": verdict.claim.uas_id,
"ua_type": verdict.claim.ua_type,
"claim_lat": verdict.claim.latitude,
"claim_lon": verdict.claim.longitude,
"claim_alt_m": verdict.claim.altitude_m,
"claim_speed_m_s": verdict.claim.speed_m_s,
"claim_heading_deg": verdict.claim.heading_deg,
"track_id": verdict.track.track_id if verdict.track else None,
"track_class": verdict.track.inferred_class if verdict.track else None,
"reason": verdict.reason,
"confidence": verdict.confidence,
"ts": now,
"claim_ts": verdict.claim.timestamp,
"processing_ms": max(0.0, (now - verdict.claim.timestamp) * 1000.0),
}
self.history.append(item)
for q in list(self.subscribers):
try:
q.put_nowait(item)
except asyncio.QueueFull:
pass
def subscribe(self) -> asyncio.Queue:
q: asyncio.Queue = asyncio.Queue(maxsize=64)
self.subscribers.append(q)
# Replay the last 20 so a fresh dashboard shows context immediately.
for item in list(self.history)[-20:]:
try: q.put_nowait(item)
except asyncio.QueueFull: pass
return q
def unsubscribe(self, q: asyncio.Queue):
if q in self.subscribers:
self.subscribers.remove(q)
# -----------------------------------------------------------------------------
# HTTP / SSE endpoints — make fusion self-serve so the dashboard works without
# requiring nemesis-tracker integration.
# -----------------------------------------------------------------------------
async def http_root(request: web.Request):
if DASHBOARD_HTML.exists():
return web.FileResponse(str(DASHBOARD_HTML))
return web.Response(text=("Fantom Finder fusion is running. "
"GET /verdicts for JSON, /events for SSE."),
content_type="text/plain")
async def http_verdicts(request: web.Request):
bus: VerdictBus = request.app["bus"]
return web.json_response(list(bus.history))
async def http_events(request: web.Request):
"""Server-Sent Events feed — the dashboard subscribes here."""
bus: VerdictBus = request.app["bus"]
resp = web.StreamResponse(headers={
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Access-Control-Allow-Origin": "*",
})
await resp.prepare(request)
q = bus.subscribe()
try:
while True:
try:
item = await asyncio.wait_for(q.get(), timeout=15)
except asyncio.TimeoutError:
# heartbeat to keep the connection alive on flaky LANs
await resp.write(b": ping\n\n")
continue
payload = json.dumps(item).encode("utf-8")
await resp.write(b"data: " + payload + b"\n\n")
except (asyncio.CancelledError, ConnectionResetError):
pass
finally:
bus.unsubscribe(q)
return resp
async def http_health(request: web.Request):
bus: VerdictBus = request.app["bus"]
return web.json_response({
"ok": True,
"verdict_count": len(bus.history),
"subscribers": len(bus.subscribers),
"uptime_s": time.time() - request.app["started_at"],
"track_count": len(request.app.get("tracks", [])),
})
async def http_tracks(request: web.Request):
"""Dashboard convenience endpoint: returns the same tracks fusion saw last poll."""
tracks = request.app.get("tracks", [])
return web.json_response({
"tracks": [
{
"track_id": t.track_id,
"ts": t.timestamp,
"range_m": t.bistatic_range_m,
"doppler_hz": t.doppler_hz,
"snr_db": t.snr_db,
"latitude": t.latitude,
"longitude": t.longitude,
"class": t.inferred_class,
"blade_count": t.rotor_blade_count,
} for t in tracks
],
"total": len(tracks),
})
async def http_demo_trigger(request: web.Request):
"""One-click demo: fire a scripted CONFIRMED → 3×PHANTOM → DECEPTION sequence
by injecting RemoteIDClaim objects directly. Used by the dashboard 'Run demo'
button so the operator doesn't need a separate terminal during the pitch."""
queue: asyncio.Queue = request.app["claim_queue"]
bus: VerdictBus = request.app["bus"]
# Geo schedule mirrors demo_show.py SCHEDULE; offsets relative to the
# fake_tracker's anchor (Shack15). Real radar tracks would substitute live.
ANCHOR = (37.79504, -122.39349)
R = 6_371_000.0
def latlon(dn, de):
return (ANCHOR[0] + (dn / R) * 57.2958,
ANCHOR[1] + (de / (R * 0.7)) * 57.2958)
schedule = [
(0.0, "VENDOR-MAVIC-2A", "Helicopter_Multirotor", *latlon(-50, 120)),
(1.5, "PHANTOM-A1B2C3", "Aeroplane", *latlon(400, -300)),
(2.0, "PHANTOM-D4E5F6", "Helicopter_Multirotor", *latlon(-200, -400)),
(2.5, "PHANTOM-G7H8I9", "Helicopter_Multirotor", *latlon(50, -250)),
(4.0, "FAKE-CESSNA-99", "Aeroplane", *latlon(-50, 120)),
(5.5, "REAL-N12345", "Aeroplane", *latlon(0, 150)),
]
async def fire():
t0 = time.time()
for delay, uas_id, ua_type, lat, lon in schedule:
await asyncio.sleep(max(0, t0 + delay - time.time()))
claim = RemoteIDClaim(
uas_id=uas_id,
timestamp=time.time(),
latitude=lat, longitude=lon,
altitude_m=30, speed_m_s=4, heading_deg=180,
ua_type=ua_type, ua_class="C0",
operator_id=f"OP-{uas_id[:6]}",
raw={"_demo_trigger": True, "uas_id": uas_id, "ua_type": ua_type,
"location": {"latitude": lat, "longitude": lon}},
)
queue.put_nowait(claim)
asyncio.create_task(fire())
return web.json_response({"ok": True, "events_queued": len(schedule),
"duration_s": schedule[-1][0]})
async def http_clear(request: web.Request):
"""Clear verdict history — useful between demo runs."""
bus: VerdictBus = request.app["bus"]
bus.history.clear()
return web.json_response({"ok": True})
def _track_is_aircraft_class(t: RadarTrack, fc_mhz: float = 605.0) -> bool:
"""Cheap classifier: True if radial speed > AIRCRAFT_RADIAL_MS, OR
the upstream tracker tagged it 'aircraft' / 'helicopter' / 'plane'."""
cat = (t.inferred_class or "").lower()
if cat in ("aircraft", "airplane", "helicopter", "plane", "uav", "drone"):
return True
# v_radial = |f_d| · λ / 2 with λ = c / fc
v = abs(t.doppler_hz) * SPEED_OF_LIGHT_MPS / (fc_mhz * 1e6) / 2.0
return v > AIRCRAFT_RADIAL_MS
def _track_has_adsb(t: RadarTrack) -> bool:
"""Did the upstream tracker (adsb2dd / blah2) cross-correlate this
track to a transponder squitter?"""
raw = t.raw or {}
return bool(
raw.get("adsb_correlated")
or raw.get("adsb_correlated_icao")
or raw.get("adsb_icao")
)
async def aircraft_no_adsb_loop(bus: VerdictBus, get_tracks):
"""Reverse-pass: every ROGUE_SWEEP_S, walk the live track snapshot
and emit DECEPTION for each aircraft-class track without ADS-B
correlation. Dedup keyed by track_id with ROGUE_REALERT_S window
so we don't flood. Synthetic RemoteIDClaim wraps the alert (mmsi=0
style, no broadcaster) so the verdict shape stays consistent."""
last_alert_ts: dict[str, float] = {}
while True:
await asyncio.sleep(ROGUE_SWEEP_S)
try:
tracks = list(get_tracks())
except Exception:
continue
now = time.time()
# Evict dedup entries for tracks no longer present
live_ids = {t.track_id for t in tracks}
for tid in list(last_alert_ts.keys()):
if tid not in live_ids:
last_alert_ts.pop(tid, None)
for t in tracks:
if not _track_is_aircraft_class(t):
continue
if _track_has_adsb(t):
continue
if now - last_alert_ts.get(t.track_id, 0.0) < ROGUE_REALERT_S:
continue
last_alert_ts[t.track_id] = now
synthetic = RemoteIDClaim(
uas_id=f"NON-COOPERATOR/{t.track_id}",
timestamp=now,
latitude=t.latitude,
longitude=t.longitude,
ua_type="unknown",
raw={"_synthetic": True, "source": "aircraft_no_adsb_sweep"},
)
verdict = Verdict(
kind="DECEPTION",
claim=synthetic,
track=t,
reason=(
f"Aircraft-class radar track {t.track_id} "
f"(radial {abs(t.doppler_hz)*SPEED_OF_LIGHT_MPS/605e6/2:.0f} m/s, "
f"SNR {t.snr_db or 0:.1f} dB) with no ADS-B correlation — "
"non-cooperator (rogue drone / unequipped GA / spoofed-off transponder)"
),
confidence=0.65,
)
await bus.publish(verdict)
logger.info(
"DECEPTION (rogue aircraft) track=%s pos=%s",
t.track_id,
f"({t.latitude:.4f},{t.longitude:.4f})" if t.latitude is not None else "?",
)
# -----------------------------------------------------------------------------
# Main loop
# -----------------------------------------------------------------------------
async def run(args):
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
queue: asyncio.Queue[RemoteIDClaim] = asyncio.Queue()
bus = VerdictBus()
loop = asyncio.get_running_loop()
logger.info("listening for Remote ID JSON on udp://0.0.0.0:%d", args.droneid_port)
await loop.create_datagram_endpoint(
lambda: DroneIDListener(queue),
local_addr=("0.0.0.0", args.droneid_port),
)
# HTTP app for dashboard + SSE.
app = web.Application()
app["bus"] = bus
app["started_at"] = time.time()
app["claim_queue"] = queue
app.router.add_get("/", http_root)
app.router.add_get("/dashboard.html", http_root)
app.router.add_get("/verdicts", http_verdicts)
app.router.add_get("/events", http_events)
app.router.add_get("/health", http_health)
app.router.add_get("/tracks", http_tracks)
app.router.add_post("/demo", http_demo_trigger)
app.router.add_post("/clear", http_clear)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, "0.0.0.0", args.dashboard_port)
await site.start()
logger.info("dashboard + SSE on http://0.0.0.0:%d/", args.dashboard_port)
async with TrackerClient(args.tracker) as tc:
last_tracks: list[RadarTrack] = []
async def refresh_tracks():
nonlocal last_tracks
consecutive_failures = 0
while True:
try:
last_tracks = await tc.list_tracks()
app["tracks"] = last_tracks # expose to /tracks endpoint
consecutive_failures = 0
except Exception as e:
consecutive_failures += 1
if consecutive_failures == 1 or consecutive_failures % 40 == 0:
logger.warning("track fetch failed (%dx): %s",
consecutive_failures, e)
await asyncio.sleep(args.poll_interval)
asyncio.create_task(refresh_tracks())
# Reverse-pass — flag aircraft tracks the Jetson radar sees
# but ADS-B doesn't cover. Closure captures last_tracks via a
# getter so it sees the latest snapshot each sweep.
asyncio.create_task(aircraft_no_adsb_loop(bus, lambda: last_tracks))
logger.info(
"Reverse-pass: flag aircraft-class tracks without ADS-B every %.0fs",
ROGUE_SWEEP_S,
)
print("# Fantom Finder verdicts (stdout)")
print("# kind\tuas_id\ttrack_id\treason")
while True:
claim = await queue.get()
verdict = evaluate(claim, last_tracks)
tag = {"CONFIRMED": "✓", "PHANTOM": "✗", "DECEPTION": "⚠"}.get(verdict.kind, "?")
print(f"{tag} {verdict.kind}\t{claim.uas_id}\t"
f"{verdict.track.track_id if verdict.track else '-'}\t{verdict.reason}",
flush=True)
await bus.publish(verdict)
try:
await tc.post_alert(verdict)
except Exception as e:
if "Cannot connect" not in str(e):
logger.warning("alert post failed: %s", e)
def main():
p = argparse.ArgumentParser()
p.add_argument("--tracker", default="http://localhost:49156",
help="nemesis-tracker API base URL (default port 49156)")
p.add_argument("--droneid-port", type=int, default=7878,
help="UDP port to receive Remote ID JSON on")
p.add_argument("--dashboard-port", type=int, default=7879,
help="HTTP port for the dashboard + SSE feed")
p.add_argument("--poll-interval", type=float, default=0.25,
help="seconds between track-list refreshes")
args = p.parse_args()
asyncio.run(run(args))
if __name__ == "__main__":
main()