-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1277 lines (1101 loc) · 60.6 KB
/
Copy pathmain.py
File metadata and controls
1277 lines (1101 loc) · 60.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
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
import sys
import os
import time
import json
import math
from core.utils import find_binary
# 🛰️ BUNDLE PATH FIX: Ensure the app always finds its models and icons
# regardless of where it was launched from (Finder, Terminal, or Applications).
if getattr(sys, 'frozen', False):
# PyInstaller creates a temp folder and stores path in _MEIPASS
# On Mac onedir, this is typically Contents/Resources
if hasattr(sys, '_MEIPASS'):
base_path = sys._MEIPASS
else:
base_path = os.path.dirname(sys.executable)
os.chdir(base_path)
else:
# If running in development mode
base_path = os.path.dirname(os.path.abspath(__file__))
from PySide6.QtWidgets import QApplication, QMessageBox
from ui.main_window import GCSMainWindow
from video.video_thread import VideoThread
from telemetry.mavlink_thread import TelemetryThread
from PySide6.QtCore import QTimer, QObject, Signal, QFileSystemWatcher
from gimbal.mount_tracker import MountTrackerController, MountTrackerConfig
from core.fleet_brain_observer import FleetBrainObserver
from core.camera_footprint_manager import CameraFootprintManager, CameraFootprintConfig
from core.fleet_config import get_ai_safety
class LogSignaler(QObject):
log_ready = Signal(str)
class LogRedirector:
def __init__(self, signaler):
self.signaler = signaler
# Write log to a writable user directory or the app folder if possible
try:
self.log_file = open("gcs_crash.log", "w", encoding="utf-8")
except:
# Fallback to a temp location if the app folder is read-only
import tempfile
log_path = os.path.join(tempfile.gettempdir(), "truegcs_crash.log")
self.log_file = open(log_path, "w", encoding="utf-8")
def write(self, text):
try:
self.signaler.log_ready.emit(text)
self.log_file.write(text)
self.log_file.flush()
except: pass
def flush(self): pass
def find_gstreamer():
return find_binary("gst-launch-1.0")
def main():
if sys.platform == "win32":
base_gst = r"C:\ProgramData\Mission Planner\gstreamer\1.0\x86_64"
dll_path = os.path.join(base_gst, "bin")
plugin_path = os.path.join(base_gst, "lib", "gstreamer-1.0")
if os.path.exists(dll_path):
try:
if sys.version_info >= (3, 8):
os.add_dll_directory(dll_path)
os.environ["GST_PLUGIN_PATH"] = plugin_path
os.environ["PATH"] = dll_path + os.pathsep + os.environ.get("PATH", "")
print(f"Mission: GStreamer DLLs Ingested from Mission Planner Path.")
except Exception as e:
print(f"Mission: Failed to add DLL directory: {e}")
app = QApplication(sys.argv)
window = GCSMainWindow()
window.log_signaler = LogSignaler()
window.log_signaler.log_ready.connect(lambda t: [window.log_console.insertPlainText(t), window.log_console.ensureCursorVisible()])
sys.stdout = LogRedirector(window.log_signaler); sys.stderr = LogRedirector(window.log_signaler)
global current_ai_engine, current_ai_model
current_ai_engine = "CPU"
current_ai_model = "YOLO26n"
window.video_thread = None
window.tab_ops.video_label.video_thread = None
window.relay_process = None
window.mount_tracker = MountTrackerController(MountTrackerConfig())
# ---- CAMERA FOOTPRINT MANAGER 📍 ----
# Create footprint manager with custom camera config (adjust FOV for your camera)
footprint_config = CameraFootprintConfig(
hfov_deg=60.0, # Horizontal FOV (adjust for your camera)
vfov_deg=45.0, # Vertical FOV (adjust for your camera)
)
window.footprint_manager = CameraFootprintManager(
window.tab_ops.map_widget,
config=footprint_config
)
# Connect footprint manager signals to map widget and 3D globe
window.footprint_manager.footprint_updated.connect(
window.tab_ops.map_widget.add_footprint
)
window.footprint_manager.footprint_updated.connect(
window.tab_ops.cesium_widget.add_footprint
)
window.footprint_manager.footprint_cleared.connect(
window.tab_ops.map_widget.clear_footprint
)
window.footprint_manager.footprint_cleared.connect(
window.tab_ops.cesium_widget.clear_footprint
)
# ---- GLOBAL NODE MANAGER ----
window.telemetry_nodes = {}
window.fleet_observer = FleetBrainObserver(window)
window.fleet_observer.status_changed.connect(window.tab_cfg.set_peer_sync_status)
window._ai_safety = get_ai_safety()
window.bridge_timer = QTimer()
window.bridge_timer.setInterval(500)
def on_peer_sync_apply(peer, safety):
window.fleet_observer.apply_and_save(peer, safety)
window._ai_safety = safety
if safety.get("enable_remote_pilot_bridge"):
if not window.bridge_timer.isActive():
window.bridge_timer.start()
else:
window.bridge_timer.stop()
window.tab_cfg.peer_sync_apply_requested.connect(on_peer_sync_apply)
window.fleet_observer.start_from_config()
window.drone_headings = {}
window.drone_armed = {} # { "nid:sid": bool } 🛰️
node_colors = ['#00ddff', '#ff3366', '#33ff55', '#ffaa00', '#aa00ff', '#ffffff']
node_counter = [0]
window.node_adding_lock = False # Lockout to prevent spam 🔐
VTOL_MODES = ["STABILIZE", "FBWA", "AUTO", "QLOITER", "QHOVER", "QRTL", "LOITER", "TAKEOFF", "TRANSITION", "CIRCLE", "RTL", "QLAND"]
def get_active_target():
data = window.combo_target_drone.currentData()
if data:
return data["node_id"], data["sysid"]
return None, None
# ---- SIGNAL ROUTERS ----
def sync_mission_drone_list():
dList = []
for i in range(window.combo_target_drone.count()):
data = window.combo_target_drone.itemData(i)
if data:
nid = data["node_id"]
sid = data["sysid"]
name = window.combo_target_drone.itemText(i)
color = "#00ddff"
node = window.telemetry_nodes.get(nid)
if node: color = node.color
dList.append({"id": f"{nid}:{sid}", "name": name, "color": color})
window.tab_ops.map_widget.update_drone_list(dList)
def r_drone_discovered(node_id, sysid, color):
if window.combo_target_drone.count() == 1 and window.combo_target_drone.itemData(0) is None:
window.combo_target_drone.clear()
# Prevent duplicates
for i in range(window.combo_target_drone.count()):
data = window.combo_target_drone.itemData(i)
if data and data["node_id"] == node_id and data["sysid"] == sysid:
return
conn_method = "Unknown"
node = window.telemetry_nodes.get(node_id)
if node:
conn_method = node.connection_string.replace("udpin:0.0.0.0:", "UDP:")
dt = f"Drone {sysid} via {conn_method} (Node {node_id})"
window.combo_target_drone.addItem(dt, userData={"node_id": node_id, "sysid": sysid})
print(f"NodeManager: Drone Discovered -> {dt}")
window.lbl_status.setText(f"Discovered SysID {sysid}")
window.lbl_status.setStyleSheet(f"color: {color}; font-weight: bold;")
tel = window.telemetry_nodes.get(node_id)
if tel: window.tab_cfg.request_curated_params()
sync_mission_drone_list()
def r_drone_lost(node_id, sysid):
for i in range(window.combo_target_drone.count()):
data = window.combo_target_drone.itemData(i)
if data and data["node_id"] == node_id and data["sysid"] == sysid:
window.combo_target_drone.removeItem(i)
break
window.tab_ops.map_widget.remove_drone(node_id, sysid)
if window.combo_target_drone.count() == 0:
window.combo_target_drone.addItem("No Drones Detected", userData=None)
print(f"NodeManager: Drone Lost -> Node {node_id} SysID {sysid}")
sync_mission_drone_list()
def r_hud_updated(n_id, s_id, speed, batt, alt, mode):
# 🚀 Fleet Routing: Always update the swarm sensor panel for all drones
window.tab_ops.sensor_panel.update_basic(n_id, s_id, mode=mode, alt=alt if alt > -1 else None, batt=batt if batt > -1 else None)
window.tab_ops.sensor_panel.update_sensors(n_id, s_id, airspeed=speed if speed > -1 else None, gps_active=window.tab_ops.chk_gps_enabled.isChecked())
an, as_id = get_active_target()
if n_id == an and s_id == as_id:
# Clean mode display with persistence guard 🛰️
if mode:
window.tab_ops.map_hud.update_telemetry(speed=speed if speed > -1 else None, batt=batt if batt > -1 else None, alt=alt if alt > -1 else None, mode=mode)
else:
window.tab_ops.map_hud.update_telemetry(speed=speed if speed > -1 else None, batt=batt if batt > -1 else None, alt=alt if alt > -1 else None)
# Sync the top-bar dropdown if the mode changed (Clean name only) 🛰️
if mode and mode != "UNKNOWN":
if not window.combo_mode.hasFocus() and not window.combo_mode.view().isVisible():
window.combo_mode.blockSignals(True)
window.combo_mode.setCurrentText(mode)
window.combo_mode.blockSignals(False)
def r_distance_updated(n_id, s_id, dist_m):
window.tab_ops.sensor_panel.update_agl(n_id, s_id, dist_m)
def r_gps2_updated(n_id, s_id, fix, hdop):
window.tab_ops.sensor_panel.update_trn(n_id, s_id, fix_type=fix, hdop=hdop)
def r_ekf_status_updated(n_id, s_id, flags):
window.tab_ops.sensor_panel.update_trn(n_id, s_id, ekf_flags=flags)
def r_nav_updated(n_id, s_id, wp_dist):
window.tab_ops.sensor_panel.update_nav(n_id, s_id, wp_dist=wp_dist)
def r_attitude_updated(n_id, s_id, roll, pitch, yaw):
window.drone_headings[f"{n_id}:{s_id}"] = yaw
an, as_id = get_active_target()
if n_id == an and s_id == as_id:
window.tab_ops.update_attitude(roll, pitch, yaw)
# Feed attitude to footprint manager 📍
window.footprint_manager.update_attitude(n_id, s_id, roll, pitch, yaw)
_pos_throttle = {} # Per-drone timestamp for map update throttling
def r_position_updated(n_id, s_id, lat, lon, alt):
if lat is None or lon is None or not math.isfinite(lat) or not math.isfinite(lon) or abs(lat) > 90.0 or abs(lon) > 180.0:
return
# Feed position to footprint manager 📍
window.footprint_manager.update_position(n_id, s_id, lat, lon, alt if alt is not None else 0.0)
# Throttle map JS updates to max 4Hz per drone to prevent WebView overload 🏎️
key = f"{n_id}:{s_id}"
now = time.time()
if now - _pos_throttle.get(key, 0) < 0.25:
return
_pos_throttle[key] = now
color = window.telemetry_nodes[n_id].color if n_id in window.telemetry_nodes else "#ffffff"
heading = window.drone_headings.get(key, 0.0)
window.tab_ops.map_widget.update_drone_position(n_id, s_id, lat, lon, heading, color)
# Also push to 3D globe 🌐
window.tab_ops.cesium_widget.update_drone_position(n_id, s_id, lat, lon, alt, heading, color)
an, as_id = get_active_target()
if n_id == an and s_id == as_id:
window.tab_ops.update_position(lat, lon, alt)
# 🚀 Fleet Routing: Sync to swarm sensor panel
window.tab_ops.sensor_panel.update_sensors(n_id, s_id, gps_active=window.tab_ops.chk_gps_enabled.isChecked())
def r_status_text(n_id, s_id, txt):
an, as_id = get_active_target()
if n_id == an and s_id == as_id:
window.lbl_status.setText(f"Drone {s_id}: {txt}")
def r_param_updated(n_id, s_id, param, val):
an, as_id = get_active_target()
if n_id == an and s_id == as_id:
window.tab_cfg.update_param_value(param, val)
def r_param_loaded(n_id, s_id):
an, as_id = get_active_target()
if n_id == an and s_id == as_id:
window.on_params_loaded()
def r_param_prog(n_id, s_id, current, total):
an, as_id = get_active_target()
if n_id == an and s_id == as_id:
window.tab_cfg.update_param_progress(current, total)
def r_modes_avail(n_id, s_id, modes):
an, as_id = get_active_target()
if n_id == an and s_id == as_id:
valid_modes = [m for m in modes if m]
if valid_modes:
window.populate_flight_modes(valid_modes)
else:
window.populate_flight_modes(VTOL_MODES)
def r_armed_status(n_id, s_id, is_armed):
window.drone_armed[f"{n_id}:{s_id}"] = is_armed
an, as_id = get_active_target()
if n_id == an and s_id == as_id:
if is_armed:
window.btn_arm.setText("ARMED")
window.btn_arm.setStyleSheet("background-color: rgba(0, 255, 0, 0.15); border: 1px solid #00ff00; color: #fff; font-weight: bold;")
else:
window.btn_arm.setText("DISARMED")
window.btn_arm.setStyleSheet("background-color: rgba(255, 50, 50, 0.1); border: 1px solid #ff3232; color: #fff; font-weight: bold;")
r_hud_updated(n_id, s_id, -1, -1, -1, window.telemetry_nodes[n_id]._last_mode.get(s_id, ""))
def on_arm_clicked():
an, as_id = get_active_target()
if not an: return
tel = window.telemetry_nodes.get(an)
if tel:
currently_armed = window.drone_armed.get(f"{an}:{as_id}", False)
print(f"Commander: {'DISARMING' if currently_armed else 'ARMING'} Drone {as_id}")
tel.arm(as_id, not currently_armed)
def connect_telemetry_signals(tel):
tel.signals.drone_discovered.connect(r_drone_discovered)
tel.signals.drone_lost.connect(r_drone_lost)
tel.signals.hud_updated.connect(r_hud_updated)
tel.signals.distance_sensor_updated.connect(r_distance_updated)
tel.signals.gps2_updated.connect(r_gps2_updated)
tel.signals.ekf_status_updated.connect(r_ekf_status_updated)
tel.signals.nav_updated.connect(r_nav_updated)
tel.signals.attitude_updated.connect(r_attitude_updated)
tel.signals.position_updated.connect(r_position_updated)
tel.signals.status_text_updated.connect(r_status_text)
tel.signals.parameter_updated.connect(r_param_updated)
tel.signals.parameters_loaded.connect(r_param_loaded)
tel.signals.parameter_progress.connect(r_param_prog)
tel.signals.modes_available.connect(r_modes_avail)
tel.signals.armed_status_changed.connect(r_armed_status)
# Connect mount angles to footprint manager 📍
tel.signals.mount_angles_updated.connect(
lambda nid, sid, pitch, yaw: window.footprint_manager.update_mount_angles(nid, sid, pitch, yaw)
)
if hasattr(window, 'fleet_observer'): window.fleet_observer.sync_node(tel)
# ---- NODE MANAGEMENT ----
def add_new_node():
if window.node_adding_lock:
print("Dashboard: Connection attempt already in progress. Please wait.")
return
try:
ctype, device = window.combo_type.currentData()
baud_rate = 115200
try: baud_rate = int(window.txt_p1.text())
except: pass
# Start lockout 🔐
window.node_adding_lock = True
window.btn_add_node.setEnabled(False)
# We assign the ID and color now, but we'll 'undo' it or wait for discovery if needed.
# Usually, assigning it here is fine as long as we block spam.
node_counter[0] += 1
nid = node_counter[0]
color = node_colors[(nid - 1) % len(node_colors)]
if ctype == "serial":
tel = TelemetryThread(nid, color, connection_string=device, baud=baud_rate)
elif ctype == "udp":
port = window.txt_p1.text()
tel = TelemetryThread(nid, color, connection_string=f"udpin:0.0.0.0:{port}")
else:
ip = window.txt_p1.text(); port = window.txt_p2.text()
tel = TelemetryThread(nid, color, connection_string=f"{ctype}:{ip}:{port}")
window.telemetry_nodes[nid] = tel
connect_telemetry_signals(tel)
# Watcher for discovery to unlock the button
def on_discovery(discovered_nid, sysid, c):
if discovered_nid == nid:
window.node_adding_lock = False
window.btn_add_node.setEnabled(True)
window.lbl_status.setText(f"MAVLink: Node {nid} Connected [Drone {sysid}]")
window.lbl_status.setStyleSheet(f"color: {color}; font-weight: bold;")
try: tel.signals.drone_discovered.disconnect(on_discovery)
except: pass
tel.signals.drone_discovered.connect(on_discovery)
tel.start()
window.lbl_status.setText(f"Connecting Node {nid}...")
window.lbl_status.setStyleSheet(f"color: orange; font-size: 14px;")
# Safety Timeout 🛰️
def handle_timeout():
if window.node_adding_lock and nid in window.telemetry_nodes:
# Check if any drones were discovered. If not, it's a true timeout.
if not tel.known_drones:
print(f"Dashboard: Node {nid} connection timed out. Reclaiming color index.")
window.telemetry_nodes.pop(nid).stop()
node_counter[0] -= 1 # Reclaim the index 🎨
window.node_adding_lock = False
window.btn_add_node.setEnabled(True)
window.lbl_status.setText(f"Node {nid}: Connection Timeout")
window.lbl_status.setStyleSheet("color: red; font-size: 14px;")
QTimer.singleShot(10000, handle_timeout) # 10s tactical window for heartbeat discovery
except Exception as e:
node_counter[0] -= 1 # Reclaim the index on crash 🎨
window.node_adding_lock = False
window.btn_add_node.setEnabled(True)
window.lbl_status.setText(f"Node Addition Failed")
window.lbl_status.setStyleSheet("color: red; font-size: 14px;")
print(f"Dashboard Error: {e}")
def disconnect_active_node():
an, as_id = get_active_target()
if an is not None and an in window.telemetry_nodes:
nid = an
tel = window.telemetry_nodes.pop(nid)
tel.stop()
i = 0
while i < window.combo_target_drone.count():
data = window.combo_target_drone.itemData(i)
if data and data["node_id"] == nid:
window.tab_ops.map_widget.remove_drone(nid, data["sysid"])
window.combo_target_drone.removeItem(i)
else: i += 1
if window.combo_target_drone.count() == 0:
window.combo_target_drone.addItem("No Drones Detected", userData=None)
window.lbl_status.setText(f"Disconnected Node {nid}")
window.lbl_status.setStyleSheet("color: #ff3232; font-size: 14px;")
# ---- MISSION UPLOAD ----
def handle_mission_upload_request(target_id, wp_json):
try:
wps = json.loads(wp_json)
if ":" not in target_id: return
nid, sid = map(int, target_id.split(":"))
if nid in window.telemetry_nodes:
window.telemetry_nodes[nid].upload_mission(sid, wps)
window.lbl_status.setText(f"Mission: Uploading {len(wps)} points to Drone {sid}...")
window.lbl_status.setStyleSheet("color: #00ddff; font-weight: bold;")
except Exception as e:
print(f"Mission Upload Error: {e}")
def handle_takeoff_request(target_id):
if ":" not in target_id: return
try:
nid, sid = map(int, target_id.split(":"))
if nid in window.telemetry_nodes:
tel = window.telemetry_nodes[nid]
print(f"Mission: Executing TAKEOFF for Drone {sid}")
# send_takeoff sequences mode/arm/NAV_TAKEOFF on a worker thread
tel.send_takeoff(sid, alt=50.0)
window.lbl_status.setText(f"Mission: Initiating Takeoff (50m) for Drone {sid}...")
window.lbl_status.setStyleSheet("color: #ffaa00; font-weight: bold;")
except Exception as e:
print(f"Takeoff Command Error: {e}")
def handle_start_mission_request(target_id):
if ":" not in target_id: return
try:
nid, sid = map(int, target_id.split(":"))
if nid in window.telemetry_nodes:
window.telemetry_nodes[nid].start_mission(sid)
window.lbl_status.setText(f"Mission: Starting Autonomous Path for Drone {sid}...")
window.lbl_status.setStyleSheet("color: #00ff00; font-weight: bold;")
except Exception as e:
print(f"Start Mission Error: {e}")
def on_gps_toggled(checked):
an, as_id = get_active_target()
if not an: return
tel = window.telemetry_nodes.get(an)
if tel:
tel.set_gps_enabled(checked, is_gps2=False)
def on_gps2_toggled(checked):
an, as_id = get_active_target()
if not an: return
tel = window.telemetry_nodes.get(an)
if tel:
tel.set_gps_enabled(checked, is_gps2=True)
window.tab_ops.chk_gps_enabled.toggled.connect(on_gps_toggled)
window.tab_ops.chk_gps2_enabled.toggled.connect(on_gps2_toggled)
window.btn_add_node.clicked.connect(add_new_node)
window.btn_disconnect_node.clicked.connect(disconnect_active_node)
window.tab_ops.map_widget.waypoint_requested.connect(lambda lat, lon: window.telemetry_nodes[get_active_target()[0]].set_waypoint(get_active_target()[1], lat, lon) if get_active_target()[0] is not None else None)
window.tab_ops.map_widget.mission_upload_requested.connect(handle_mission_upload_request)
window.tab_ops.map_widget.takeoff_requested.connect(handle_takeoff_request)
window.tab_ops.map_widget.start_mission_requested.connect(handle_start_mission_request)
# ---- FLEET-WIDE MISSION COMMANDS ----
def handle_fleet_deploy(deploy_json):
"""Deploy missions to multiple drones in one action."""
try:
missions = json.loads(deploy_json)
count = 0
for m in missions:
target_id = m.get('target_id', '')
wps = m.get('waypoints', [])
if target_id and wps:
handle_mission_upload_request(target_id, json.dumps(wps))
count += 1
window.lbl_status.setText(f"Fleet Deploy: {count} missions uploaded")
window.lbl_status.setStyleSheet("color: #00ddff; font-weight: bold;")
print(f"Fleet Deploy: Sent {count} missions to fleet", flush=True)
except Exception as e:
print(f"Fleet Deploy Error: {e}", flush=True)
def handle_fleet_takeoff(targets_json):
"""Send takeoff to all selected drones."""
try:
target_ids = json.loads(targets_json)
for tid in target_ids:
handle_takeoff_request(tid)
window.lbl_status.setText(f"Fleet Takeoff: {len(target_ids)} drones")
window.lbl_status.setStyleSheet("color: #ffaa00; font-weight: bold;")
except Exception as e:
print(f"Fleet Takeoff Error: {e}", flush=True)
def handle_fleet_auto(targets_json):
"""Start mission for all selected drones."""
try:
target_ids = json.loads(targets_json)
for tid in target_ids:
handle_start_mission_request(tid)
window.lbl_status.setText(f"Fleet AUTO: {len(target_ids)} drones")
window.lbl_status.setStyleSheet("color: #00ff00; font-weight: bold;")
except Exception as e:
print(f"Fleet Auto Error: {e}", flush=True)
window.tab_ops.map_widget.fleet_deploy_requested.connect(handle_fleet_deploy)
window.tab_ops.map_widget.fleet_takeoff_requested.connect(handle_fleet_takeoff)
window.tab_ops.map_widget.fleet_auto_requested.connect(handle_fleet_auto)
window.tab_cfg.write_param_requested.connect(lambda p, v: window.telemetry_nodes[get_active_target()[0]].set_parameter(get_active_target()[1], p, v) if get_active_target()[0] is not None else None)
window.tab_cfg.fetch_params_requested.connect(lambda pl: window.telemetry_nodes[get_active_target()[0]].fetch_parameters(get_active_target()[1], pl) if get_active_target()[0] is not None else None)
window.tab_cfg.fetch_full_list_requested.connect(lambda: window.telemetry_nodes[get_active_target()[0]].request_all_params_list(get_active_target()[1]) if get_active_target()[0] is not None else None)
window.combo_mode.currentTextChanged.connect(lambda m: window.telemetry_nodes[get_active_target()[0]].set_flight_mode(get_active_target()[1], m) if get_active_target()[0] is not None else None)
def on_active_drone_changed(index):
an, as_id = get_active_target()
if an is not None and an in window.telemetry_nodes:
# Sync to Sensor Side-Panel 🛰️
window.tab_ops.sensor_panel.set_active_node(f"NODE {an} (ID:{as_id})")
tel = window.telemetry_nodes[an]
window.tab_cfg.table_params.setRowCount(0)
for p_id, p_val in tel.parameters.get(as_id, {}).items():
window.tab_cfg.update_param_value(p_id, p_val)
if as_id in tel._modes_emitted and tel._modes_emitted[as_id]:
window.populate_flight_modes(list(tel.master.mode_mapping().keys()))
window.combo_mode.blockSignals(True)
window.combo_mode.setCurrentText(tel._last_mode.get(as_id, ""))
window.combo_mode.blockSignals(False)
window.lbl_status.setText(f"Focus: Node {an} SysID {as_id}")
# Sync to Map Mission Planner 🛰️🗺️
active_name = window.combo_target_drone.currentText()
window.tab_ops.map_widget.set_active_drone(an, as_id, active_name)
window.combo_target_drone.currentIndexChanged.connect(on_active_drone_changed)
# ---- LOCKOUT GUARD: Ensures OS/CUDA cleanup is 100% complete 🛡️ ----
window.lockout_remaining = 0
window.lockout_timer = QTimer()
def update_lockout():
if window.lockout_remaining > 0:
window.lockout_remaining -= 1
window.tab_ops.btn_vid_toggle.setText(f"Ready in {window.lockout_remaining}s...")
window.tab_ops.btn_vid_toggle.setEnabled(False)
else:
window.lockout_timer.stop()
window.tab_ops.btn_vid_toggle.setText("Start Video")
window.tab_ops.btn_vid_toggle.setEnabled(True)
window.lockout_timer.timeout.connect(update_lockout)
# ---- VIDEO ----
def toggle_video():
if window.tab_ops.btn_vid_toggle.text() == "Start Video":
if window.video_thread: window.video_thread.stop()
vtype = window.tab_ops.combo_vid_type.currentText()
vport = window.tab_ops.txt_vid_port.text().strip()
host = window.tab_ops.txt_vid_ip.text().strip()
if "USB" in vtype:
# Local hardware index (integer) 🏁
src = int(vport) if (vport and vport.isdigit()) else 0
else:
# Default to UDP Stream
src = f"udp://{host or '0.0.0.0'}:{vport or '5008'}"
brain_client = None
if hasattr(window, "fleet_observer") and window.fleet_observer.brain:
brain_client = window.fleet_observer.brain
window.video_thread = VideoThread(stream_url=src, brain_client=brain_client)
window.video_thread.gst_path = find_gstreamer()
window.tab_ops.video_label.video_thread = window.video_thread
window.video_thread.frame_ready.connect(window.update_video_frame)
window.video_thread.target_status.connect(window.tab_ops.update_target_status)
window.video_thread.target_status.connect(lambda s, ox, oy, c: window.tab_ops.sensor_panel.update_vision(get_active_target()[0], get_active_target()[1], s, c, ox, oy))
window.video_thread.source_frame_size.connect(window.tab_ops.video_label.set_source_frame_size)
window.video_thread.tracking_error.connect(on_tracking_error)
window.video_thread.ai_ready.connect(on_ai_ready)
# Connect footprint frame signal to map widget for video overlay 📍🎥
def route_video_overlay(nid, quality, jpeg_bytes):
window.tab_ops.map_widget.update_footprint_video_bytes(nid, jpeg_bytes)
window.tab_ops.cesium_widget.update_footprint_video_bytes(nid, jpeg_bytes)
window.video_thread.footprint_frame_ready.connect(route_video_overlay)
# Apply any AI engine/model preset from Video tab at startup
eng = window.tab_video.combo_ai_engine.currentText().split()[0]
mdl = window.tab_video.model_combo.currentText().split()[0]
window.video_thread.set_ai_config(eng, mdl)
window.video_thread.set_world_prompt(window.tab_video.txt_search_prompt.text())
# Relocated to OpsTab 🛰️
window.video_thread.set_ai_conf(window.tab_ops.slider_conf.value() / 100.0)
# NOTE: ai_diag_updated is shown on the status bar; SensorPanel now shows per-drone fleet data
window.video_thread.start()
window.video_thread.set_show_detections(window.tab_ops.chk_enable_det.isChecked())
window.video_thread.set_show_labels(window.tab_video.chk_show_labels.isChecked())
window.video_thread.set_box_color(window.tab_video.combo_box_color.currentData())
window.tab_video.labels_toggled.connect(window.video_thread.set_show_labels)
window.tab_video.box_color_changed.connect(window.video_thread.set_box_color)
window.video_thread.set_tracking_mode(window.tab_ops.combo_tracking_mode.currentData())
window.mount_tracker.set_enabled(window.tab_ops.chk_tracking.isChecked() and window.tab_ops.combo_tracking_mode.currentData() != "none")
window.tab_ops.btn_vid_toggle.setText("Stop Video")
# Notify peers: video stream is now active
if hasattr(window, "fleet_observer") and window.fleet_observer.brain:
window.fleet_observer.brain.emit_video_status(True, src)
else:
if window.video_thread:
window.video_thread.stop()
# TRASH THE ZOMBIE: Nulling the thread ensures Port settings and AI logic reset for the next run 🏎️
window.video_thread = None
window.tab_ops.video_label.video_thread = None
window.mount_tracker.set_enabled(False)
window.tab_ops.btn_vid_toggle.setText("Start Video")
window.tab_ops.video_label.clear()
# Notify peers: video stream is now inactive
if hasattr(window, "fleet_observer") and window.fleet_observer.brain:
window.fleet_observer.brain.emit_video_status(False, None)
def on_tracking_error(err_x, err_y):
if not window.video_thread:
return
out = window.mount_tracker.update(err_x, err_y)
if out is None:
return
an, as_id = get_active_target()
if an is None or an not in window.telemetry_nodes:
return
pitch, yaw = out
window.telemetry_nodes[an].mount_control(as_id, pitch, 0.0, yaw)
def on_video_click(x, y):
if not window.video_thread:
return
mode = window.tab_ops.combo_tracking_mode.currentData()
# Simple one-shot slew: move gimbal so clicked point is driven toward screen center.
if mode == "center":
# Provide operator feedback crosshair
try:
window.video_thread.set_click_marker(x, y, ttl_s=1.5)
except Exception:
pass
# Behave like a "click lock": seed the clicked pixel and let the normal
# detection association + PID tracking drive the gimbal to center.
window.video_thread.set_tracking_mode("center")
window.video_thread.handle_click(x, y)
# Auto-enable tracking so the PID loop is active.
window.tab_ops.chk_tracking.setChecked(True)
window.mount_tracker.set_enabled(True)
return
window.video_thread.handle_click(x, y)
enabled = window.tab_ops.chk_tracking.isChecked() and mode not in ("none", "center")
window.mount_tracker.set_enabled(enabled)
def on_detection_toggled(checked):
if window.video_thread:
window.video_thread.set_show_detections(bool(checked))
def on_tracking_mode_changed(index):
mode = window.tab_ops.combo_tracking_mode.itemData(index)
if window.video_thread:
window.video_thread.set_tracking_mode(mode)
enabled = window.tab_ops.chk_tracking.isChecked() and mode != "none"
window.mount_tracker.set_enabled(enabled)
if mode == "none" and window.video_thread:
window.video_thread.set_tracking_point(None, None)
if enabled:
# Align controller internal state to last known mount angles
an, as_id = get_active_target()
if an is not None and an in window.telemetry_nodes:
mp = window.telemetry_nodes[an].mount_angles.get(as_id)
if mp:
pitch_deg, yaw_deg = mp
window.mount_tracker.pitch_deg = float(pitch_deg)
window.mount_tracker.yaw_deg = float(yaw_deg)
def on_tracking_toggled(checked):
mode = window.tab_ops.combo_tracking_mode.currentData()
enabled = bool(checked) and mode != "none"
window.mount_tracker.set_enabled(enabled)
if enabled:
# Align controller internal state to the last known mount angles
an, as_id = get_active_target()
if an is not None and an in window.telemetry_nodes:
mp = window.telemetry_nodes[an].mount_angles.get(as_id)
if mp:
pitch_deg, yaw_deg = mp
window.mount_tracker.pitch_deg = float(pitch_deg)
window.mount_tracker.yaw_deg = float(yaw_deg)
if not checked and window.video_thread:
window.video_thread.set_tracking_point(None, None)
def on_wipe_lock():
if window.video_thread:
window.video_thread.set_tracking_point(None, None)
window.mount_tracker.reset()
window.restarting_for_ai = False
def on_ai_ready(engine, model_name):
try:
window.tab_video.btn_apply_ai.setEnabled(True)
window.tab_video.btn_apply_ai.setText("Apply AI Engine Settings")
window.lbl_status.setText(f"AI Configured: {model_name} on {engine}")
# Mission HUD: Rebuild the class filter grid in the Operations Tab 🚀
window.tab_ops.refresh_class_filters(model_name)
except: pass
def on_ai_settings_applied(engine, model_name):
global current_ai_engine, current_ai_model
# Guard: If already active, skip the destructive reload 🧱
if engine == current_ai_engine and model_name == current_ai_model:
print(f"Mission Loader: {model_name} already active on {engine}. Ignoring.")
return
current_ai_engine = engine
current_ai_model = model_name
print(f"AI Engine/Model Hotswap -> engine={engine}, model={model_name}")
# Throttling firewall: lock the UI while CUDA prepares 🔐
try:
window.tab_video.btn_apply_ai.setEnabled(False)
window.tab_video.btn_apply_ai.setText("SWITCHING...")
except: pass
current_ai_engine = engine
current_ai_model = model_name
print(f"AI Engine/Model Change -> engine={engine}, model={model_name}")
# ---- CLEAN BREAK: Disable detections and stop feed for stability 🎯 ----
window.tab_ops.chk_enable_det.setChecked(False)
window.tab_ops.chk_tracking.setChecked(False)
if window.video_thread and window.video_thread.isRunning():
print("Mission Control: Stopping video feed for clean model transition.")
toggle_video()
# Start the 3-second stability lockout 🧱
# This ensures background taskkills and CUDA purges are 100% finished during the hotswap
window.lockout_remaining = 3
window.tab_ops.btn_vid_toggle.setEnabled(False)
window.tab_ops.btn_vid_toggle.setText(f"Ready in 3s...")
window.lockout_timer.start(1000)
# Reset the "Apply" button state instantly since no live restart will be attempted
on_ai_ready(engine, model_name)
def on_search_prompt_changed(prompt):
if window.video_thread:
window.video_thread.set_world_prompt(prompt)
window.tab_ops.btn_vid_toggle.clicked.connect(toggle_video)
window.tab_ops.video_label.frame_clicked.connect(on_video_click)
window.tab_ops.chk_enable_det.toggled.connect(on_detection_toggled)
window.tab_ops.combo_tracking_mode.currentIndexChanged.connect(on_tracking_mode_changed)
window.tab_ops.chk_tracking.toggled.connect(on_tracking_toggled)
window.tab_ops.btn_wipe_lock.clicked.connect(on_wipe_lock)
window.tab_ops.btn_clear_isr.clicked.connect(lambda: [
window.tab_ops.map_widget.clear_ai_target_markers(),
window.tab_ops.cesium_widget._web.page().runJavaScript("if(typeof clearAITargetMarkers!=='undefined')clearAITargetMarkers();"),
])
window.tab_ops.chk_show_logs.toggled.connect(window.log_console.setVisible)
window.tab_video.ai_settings_applied.connect(on_ai_settings_applied)
# Tactical HUD Connects 🛰️
window.tab_ops.slider_conf.valueChanged.connect(lambda v: window.video_thread.set_ai_conf(v/100.0) if window.video_thread else None)
window.tab_video.search_prompt_changed.connect(on_search_prompt_changed)
window.tab_ops.class_filter_changed.connect(lambda ids: window.video_thread.set_active_classes(ids) if window.video_thread else None)
# ---- CAMERA FOOTPRINT TOGGLE 📍 ----
window.tab_video.footprint_toggled.connect(window.footprint_manager.set_enabled)
# Connect footprint manager state changes to enable/disable video export in VideoThread
def on_footprint_global_toggled(enabled):
"""Enable/disable footprint video export when global footprint toggle changes."""
if window.video_thread:
window.video_thread.set_footprint_enabled(enabled)
# Also connect per-drone footprint state changes to enable/disable video export
def on_drone_footprint_state_changed(nid, sid, is_active):
"""Enable/disable footprint video export for specific drone."""
if window.video_thread:
# Enable export if any drone has footprint active
window.video_thread.set_footprint_enabled(is_active)
window.footprint_manager.enabled_changed.connect(on_footprint_global_toggled)
window.footprint_manager.footprint_state_changed.connect(on_drone_footprint_state_changed)
# ---- MISSION PLANNER INTEGRATION ----
# ---- FLIGHT MODE & CONTEXT MENU INTEGRATION ----
def parse_target(tid):
if not tid: return None, None
if isinstance(tid, dict):
return tid.get('node_id'), tid.get('sysid')
if isinstance(tid, str) and ":" in tid:
nid, sid = tid.split(":")
return int(nid), int(sid)
return None, None
def apply_mode_change(target_id, mode_name):
nid, sid = parse_target(target_id)
if nid is None: return
tel = window.telemetry_nodes.get(nid)
if tel:
print(f"Mission: Setting Drone {sid} to MODE: {mode_name}")
tel.set_flight_mode(sid, mode_name)
def on_set_mode_clicked():
import json
target_id = window.combo_target_drone.currentData()
if not target_id: return
mode_name = window.combo_mode.currentText()
apply_mode_change(target_id, mode_name)
def on_drone_context_menu(target_id):
from PySide6.QtWidgets import QMenu
from PySide6.QtGui import QAction, QCursor
nid, sid = parse_target(target_id)
menu = QMenu(window)
menu.setTitle(f"Tactical Drone {sid}")
menu.setStyleSheet("background-color: #09151c; color: #00ddff; border: 1px solid #111a22; padding: 5px;")
# Mode Section
mode_menu = menu.addMenu("Set Mode")
for mode in VTOL_MODES:
action = mode_menu.addAction(mode)
# Use non-lambda capturing or pass mode as argument to avoid closure issues
def trigger_factory(target=target_id, m=mode):
return lambda: apply_mode_change(target, m)
action.triggered.connect(trigger_factory())
menu.addSeparator()
# Action Section
arm_action = menu.addAction("ARM DRONE")
arm_action.triggered.connect(lambda: window.telemetry_nodes[nid].arm(sid, True) if nid in window.telemetry_nodes else None)
disarm_action = menu.addAction("DISARM DRONE")
disarm_action.triggered.connect(lambda: window.telemetry_nodes[nid].arm(sid, False) if nid in window.telemetry_nodes else None)
menu.addSeparator()
# Camera Footprint Toggle
fp_action = menu.addAction("📷 TOGGLE CAMERA FOOTPRINT ON MAP")
fp_action.triggered.connect(lambda: window.tab_ops.map_widget.footprint_toggle_requested.emit(target_id))
menu.exec(QCursor.pos())
def on_footprint_toggle_from_map(target_id):
"""Toggle footprint visibility for a specific drone from the map context menu."""
nid, sid = parse_target(target_id)
if nid is None or sid is None:
return
map_widget = window.tab_ops.map_widget
# Check current Python state to determine new state
was_active = window.footprint_manager.is_drone_footprint_active(nid, sid)
new_state = "ON" if not was_active else "OFF"
print(f"[Python] on_footprint_toggle_from_map: target_id={target_id}, nid={nid}, sid={sid}, new_state={new_state}")
# First, set JavaScript per-drone state BEFORE emitting Python signals
# This ensures updateFootprint() will render when called from telemetry signals
if map_widget and hasattr(map_widget, '_web_view'):
# Build JS string using concatenation to avoid f-string brace conflicts
is_active_js = "true" if new_state == "ON" else "false"
js = (
"// Set per-drone footprint state in JavaScript FIRST\n"
"var fpKey = '" + str(nid) + "_" + str(sid) + "';\n"
"activeFootprints[fpKey] = " + is_active_js + ";\n"
"console.log('[JS] Set activeFootprints[' + fpKey + '] = ' + activeFootprints[fpKey]);\n"
"\n"
"// Update button appearance\n"
"var fpBtn = document.getElementById('fp-btn-" + str(nid) + ":" + str(sid) + "');\n"
"if (fpBtn) {\n"
" fpBtn.textContent = '📷 FOOTPRINT " + new_state + "';\n"
" if ('" + new_state + "' === 'ON') {\n"
" fpBtn.style.background = 'rgba(255,170,0,0.4)';\n"
" fpBtn.style.borderColor = '#ffcc00';\n"
" } else {\n"
" fpBtn.style.background = 'rgba(255,170,0,0.2)';\n"
" fpBtn.style.borderColor = '#ffaa00';\n"
" }\n"
"}\n"
"\n"
"// Trigger footprint recalculation if enabling\n"
"if (activeFootprints[fpKey]) {\n"
" console.log('[JS] Triggering footprint recalculation for ' + fpKey);\n"
"}\n"
)
map_widget._web_view.page().runJavaScript(js)
# Track active footprint target for video overlay routing
if new_state == "ON":
map_widget._active_fp_target = target_id
window.tab_ops.cesium_widget._active_fp_target = target_id
print(f"[Python] Set _active_fp_target = {target_id}")
elif map_widget._active_fp_target == target_id:
map_widget._active_fp_target = None
window.tab_ops.cesium_widget._active_fp_target = None
print(f"[Python] Cleared _active_fp_target (was {target_id})")
# Now toggle the per-drone footprint state in Python (emits signals that will render)
if was_active:
print(f"[Python] Disabling drone footprint for {nid}:{sid}")
window.footprint_manager.disable_drone_footprint(nid, sid)
else:
print(f"[Python] Enabling drone footprint for {nid}:{sid}")
window.footprint_manager.enable_drone_footprint(nid, sid)
# Mission Planner Handlers
def on_takeoff(target_id):
nid, sid = parse_target(target_id)
tel = window.telemetry_nodes.get(nid)
if tel:
print(f"Mission: Executing TAKEOFF for Drone {sid}")
tel.send_takeoff(sid, 50.0)
def on_start_mission(target_id):
nid, sid = parse_target(target_id)
tel = window.telemetry_nodes.get(nid)
if tel: tel.start_mission(sid)
def on_mission_upload(target_id, wp_json):
import json
nid, sid = parse_target(target_id)
tel = window.telemetry_nodes.get(nid)
if tel:
wps = json.loads(wp_json)
tel.upload_mission(sid, wps)
# Initial population and signals
window.populate_flight_modes(VTOL_MODES)
window.btn_set_mode.clicked.connect(on_set_mode_clicked)
window.btn_arm.clicked.connect(on_arm_clicked)
window.tab_ops.map_widget.drone_context_menu_requested.connect(on_drone_context_menu)
# Duplicate bindings commented out to prevent double-execution:
# window.tab_ops.map_widget.takeoff_requested.connect(on_takeoff)
# window.tab_ops.map_widget.start_mission_requested.connect(on_start_mission)
# window.tab_ops.map_widget.mission_upload_requested.connect(on_mission_upload)
# Camera Footprint toggle from map context menu
window.tab_ops.map_widget.footprint_toggle_requested.connect(on_footprint_toggle_from_map)
window.tab_ops.cesium_widget.footprint_toggle_requested.connect(on_footprint_toggle_from_map)
# 3D view drone popup actions
window.tab_ops.cesium_widget.takeoff_requested.connect(on_takeoff)
window.tab_ops.cesium_widget.start_mission_requested.connect(on_start_mission)
# ---- TACTICAL LLM INTEGRATION ----
from core.llm_client import TacticalLLMClient
llm_client = TacticalLLMClient()
def handle_llm_response(response_json):
import json
reasoning = response_json.get("reasoning", "")
if reasoning:
window.tab_ops.ai_panel.append_chat(f"<b>[AI]</b> {reasoning}", "#33ff55")
formatted_str = json.dumps(response_json, indent=2)
window.tab_ops.ai_panel.show_preview(formatted_str)
commands = response_json.get("commands", [])
if not commands: