-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdrone_launcher.py
More file actions
1208 lines (1023 loc) · 57.2 KB
/
Copy pathdrone_launcher.py
File metadata and controls
1208 lines (1023 loc) · 57.2 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
"""
DELSYS - UNIMORE DRONE LAUNCHER & HUD INTEGRATED (UNIFIED WITH EMBEDDED GODOT)
"""
import sys, os, subprocess, threading, time, json, signal, socket as _socket
from pyparsing import line
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QProgressBar, QFrame, QGridLayout, QMessageBox, QSizePolicy
)
from PyQt5.QtCore import Qt, QTimer, pyqtSignal, QPoint, QProcess
from PyQt5.QtGui import QPainter, QPolygon, QColor, QWindow, QGuiApplication, QFont, QPixmap
import rclpy
from rclpy.node import Node
from std_msgs.msg import Int32, Bool, String
from geometry_msgs.msg import Twist
from std_msgs.msg import Float32MultiArray
from rclpy.qos import QoSProfile, DurabilityPolicy, HistoryPolicy, ReliabilityPolicy
import re
# ─────────────────────────────────────────────
# PORTS, PATHS AND IMAGES CONFIG
# ─────────────────────────────────────────────
HOME = os.path.expanduser("~")
DELSYS_DIR = os.path.join(HOME, "delsys-unimore")
ROS_WS = os.path.join(DELSYS_DIR, "ros2_ws")
BRIDGE_DIR = os.path.join(DELSYS_DIR, "delsys_bridge")
ROS_SETUP = "/opt/ros/humble/setup.bash"
WS_SETUP = os.path.join(ROS_WS, "install/setup.bash")
GODOT_BIN = os.path.join(BRIDGE_DIR, "Godot_v4.3-stable_linux.x86_64")
GODOT_PROJECT_DIR = os.path.join(DELSYS_DIR, "drone-game")
LOGO_EMG_PATH = "delsys_symbol.png"
LOGO_ARS_PATH = "arscontrol_symbol.png"
BOTTOM_LOGO_DELSYS = "DELSYS.png"
BOTTOM_LOGO_ARS = "arscontrol.jpeg"
# Configuration constants for calibration sequences (seconds)
CALIB_DURATION_IMU = 3.0
CALIB_DURATION_EMG = 3.0
# TCP Loopback Ports assigned for programmatic process adjustments outside ROS2
IMU_PORT = 9001
EMG_PORT = 9002
CTRL_PORT = 9003
BRIDGE_CMD_PORT = 9004
DEAD_THRESH = 0.2
BOOST_THRESH = 0.7
BG = "#0a0f1e"
PANEL_BG = "#111827"
ACCENT = "#00d4ff"
GREEN = "#00ff88"
ORANGE = "#ff8c00"
RED_C = "#ff3355"
WHITE = "#f0f4ff"
GREY = "#3a4560"
ARROW_OFF = "#1a2540"
ARROW_ON = "#00d4ff"
def get_stylesheet(scale=1.0):
"""
Generates a QSS (Qt Style Sheet) string dynamically modified by a scale coefficient.
Ensures that borders, padding, and layout geometries stay perfectly crisp on responsive screens.
"""
f_base = lambda size: max(8, int(size * scale))
return f"""
* {{ font-family: 'Courier New', monospace; }}
QMainWindow, QWidget#root {{ background: {BG}; }}
QWidget {{ background: {BG}; color: {WHITE}; }}
QFrame#card {{ background: {PANEL_BG}; border: 1px solid {GREY}; border-radius: {max(4, int(8*scale))}px; }}
QPushButton {{
background: {PANEL_BG}; color: {ACCENT}; border: 1px solid {ACCENT}; border-radius: {max(3, int(5*scale))}px;
padding: {int(10*scale)}px {int(14*scale)}px; font-size: {f_base(11)}px; font-weight: bold; letter-spacing: 1px; min-height: {int(36*scale)}px;
}}
QPushButton:hover {{ background: {ACCENT}; color: {BG}; }}
QPushButton:disabled {{ color: {GREY}; border-color: {GREY}; background: {PANEL_BG}; }}
QPushButton#red {{ border-color: {RED_C}; color: {RED_C}; }}
QPushButton#red:hover {{ background: {RED_C}; color: {WHITE}; }}
QPushButton#green {{ border-color: {GREEN}; color: {GREEN}; }}
QPushButton#green:hover {{ background: {GREEN}; color: {BG}; }}
QPushButton#orange {{ border-color: {ORANGE}; color: {ORANGE}; }}
QPushButton#orange:hover {{ background: {ORANGE}; color: {BG}; }}
QProgressBar {{ background: {GREY}; border: none; border-radius: 3px; height: {int(6*scale)}px; }}
QProgressBar::chunk {{ background: {ACCENT}; border-radius: 3px; }}
QLabel {{ background: transparent; border: none; }}
"""
def sep():
"""Returns a visual divider line widget (horizontal line frame)."""
f = QFrame()
f.setFrameShape(QFrame.HLine)
f.setStyleSheet(f"background: {GREY}; max-height: 1px; border: none;")
return f
def lbl(text, color=WHITE, size=10, bold=False, spacing=0):
"""Factory helper to construct highly uniform and trackable UI text blocks."""
l = QLabel(text)
l.setProperty("base_size", size)
w = "bold" if bold else "normal"
ls = f"letter-spacing: {spacing}px;" if spacing else ""
l.setStyleSheet(f"color: {color}; font-size: {size}px; font-weight: {w}; {ls}")
return l
def card():
"""Constructs a standard modular panel container for the multi-column interface."""
f = QFrame()
f.setObjectName("card")
f.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
return f
def send_ctrl(payload: dict, port=CTRL_PORT) -> bool:
"""
Fires off JSON payloads over raw TCP sockets on a separate, decoupled thread.
Used to send calibration commands or runtime instructions straight to hardware bridges
without running the risk of stalling the master GUI loop.
"""
def _worker():
try:
s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
s.settimeout(0.5)
s.connect(('127.0.0.1', port))
s.sendall((json.dumps(payload) + '\n').encode('utf-8'))
s.close()
except Exception:
pass
threading.Thread(target=_worker, daemon=True).start()
return True
# ─────────────────────────────────────────────
# RESPONSIVE GRAPHICAL COMPONENTS
# ─────────────────────────────────────────────
class StatusDot(QWidget):
"""
A custom status indicator widget displaying a colored dot and text.
Flashes red automatically when handling critical, pending initialization tasks.
"""
def __init__(self, text: str):
super().__init__()
lay = QHBoxLayout(self); lay.setContentsMargins(0,0,0,0); lay.setSpacing(6)
self._dot = QLabel("⬤"); self._dot.setProperty("base_size", 10)
self._lbl = QLabel(text); self._lbl.setProperty("base_size", 10)
self._dot.setStyleSheet(f"color: {GREY}; font-size: 10px;")
self._lbl.setStyleSheet(f"color: {GREY}; font-size: 10px;")
lay.addWidget(self._dot); lay.addWidget(self._lbl); lay.addStretch()
self._blink_timer = None; self._blink_state = False
self._current_state = 'off'
def set_state(self, state: str, text: str = None):
"""Sets current execution state ('off', 'pending', 'ok', 'error') and styles text."""
self._current_state = state
if self._blink_timer: self._blink_timer.stop(); self._blink_timer = None
c = {'off': GREY, 'pending': ORANGE, 'ok': ACCENT, 'error': RED_C}.get(state, GREY)
if text: self._lbl.setText(text)
sz = self._lbl.property("current_size") or 10
self._lbl.setStyleSheet(f"color: {c}; font-size: {sz}px;")
self._dot.setStyleSheet(f"color: {c}; font-size: {sz}px;")
if state == 'pending':
self._blink_timer = QTimer()
self._blink_timer.timeout.connect(self._blink)
self._blink_timer.start(500)
def _blink(self):
"""Flips dot color to simulate an active alert warning during configuration."""
self._blink_state = not self._blink_state
sz = self._dot.property("current_size") or 10
self._dot.setStyleSheet(f"color: {RED_C if self._blink_state else GREY}; font-size: {sz}px;")
def update_scale(self, scale):
"""Rescales the text and dot icons upon window dimension mutations."""
sz = max(6, int(10 * scale))
self._dot.setProperty("current_size", sz)
self._lbl.setProperty("current_size", sz)
self.set_state(self._current_state)
class CalibBar(QWidget):
"""
A tracking progress bar specifically mapped out to handle visual timing countdowns
during human biometric sensor normalization sequences.
"""
finished = pyqtSignal()
def __init__(self, color=ORANGE, duration=3.0):
super().__init__()
self.color = color
self.duration = duration; self._timer = None
lay = QVBoxLayout(self); lay.setContentsMargins(0, 4, 0, 4); lay.setSpacing(4)
self._lbl = QLabel(""); self._lbl.setProperty("base_size", 9)
self._lbl.setStyleSheet(f"color: {GREY}; font-size: 9px;")
lay.addWidget(self._lbl)
self._bar = QProgressBar(); self._bar.setRange(0, int(duration * 10)); self._bar.setValue(0)
self._bar.setTextVisible(False); self._bar.setFixedHeight(8)
self._bar.setStyleSheet(f"QProgressBar {{ background: {GREY}; border: none; border-radius: 3px; }}"
f"QProgressBar::chunk {{ background: {ACCENT}; border-radius: 3px; }}")
lay.addWidget(self._bar); self.setVisible(False)
def start(self, message: str):
"""Initializes countdown increments mapping physical time directly into value steps."""
self.setVisible(True); self._bar.setValue(0)
sz = self._lbl.property("current_size") or 9
self._lbl.setStyleSheet(f"color: {ACCENT}; font-size: {sz}px;")
self._counter = [0]; total = int(self.duration * 10)
def tick():
self._counter[0] += 1; self._bar.setValue(self._counter[0])
rem = self.duration - self._counter[0] / 10
self._lbl.setText(f"{message} {rem:.1f}s")
if self._counter[0] >= total:
self._timer.stop()
cur_sz = self._lbl.property("current_size") or 9
self._lbl.setText("✓ Complete")
self._lbl.setStyleSheet(f"color: {ACCENT}; font-size: {cur_sz}px;")
self.finished.emit()
self._timer = QTimer(); self._timer.timeout.connect(tick); self._timer.start(100)
def reset(self):
if self._timer: self._timer.stop()
self._bar.setValue(0); self._lbl.setText(""); self.setVisible(False)
def update_scale(self, scale):
self._bar.setFixedHeight(max(4, int(8 * scale)))
sz = max(7, int(9 * scale))
self._lbl.setProperty("current_size", sz)
class EMGNativeCanvas(QWidget):
"""
An optimized, self-painting canvas panel that draws a real-time signal bar
representing normalized muscle input power, complete with visual threshold zones.
"""
def __init__(self):
super().__init__()
self.setFixedSize(330, 36)
self.value = 0.0
self.calibrated = False
def update_value(self, val, calibrated):
self.value = val
self.calibrated = calibrated
self.update() # Triggers paintEvent internally on the next layout cycle
def paintEvent(self, event):
p = QPainter(self); p.setRenderHint(QPainter.Antialiasing)
p.fillRect(self.rect(), QColor(PANEL_BG))
w_val = self.value
# Select colors dynamically based on structural zone thresholds
if not self.calibrated:
bar_color = QColor(GREY)
elif w_val < DEAD_THRESH:
bar_color = QColor(GREY)
elif w_val < BOOST_THRESH:
bar_color = QColor(GREEN)
else:
bar_color = QColor(RED_C)
# Calculate width dynamically based on raw signal activity
fill_width = max(2, int((self.width() - 4) * w_val))
p.fillRect(2, 2, fill_width, self.height() - 4, bar_color)
# Paint Dead Zone marker threshold line
p.setPen(QColor(ORANGE))
dead_x = int(self.width() * DEAD_THRESH)
p.drawLine(dead_x, 0, dead_x, self.height())
# Paint Boost Zone marker threshold line
p.setPen(QColor(RED_C))
boost_x = int(self.width() * BOOST_THRESH)
p.drawLine(boost_x, 0, boost_x, self.height())
class IMUVisualizer(QWidget):
"""
A 2D navigation crosshair component that changes color states to visually reflect
drone navigation directions extracted from spatial IMU sensors (Pitch & Roll angles).
"""
def __init__(self):
super().__init__()
self.setFixedSize(360, 180)
self.pitch = 0.0; self.roll = 0.0; self.th = 0.1 # Activation tilt deadband boundary
def update_angles(self, pitch, roll):
self.pitch = pitch; self.roll = roll; self.update()
def paintEvent(self, event):
p = QPainter(self); p.setRenderHint(QPainter.Antialiasing)
p.fillRect(self.rect(), QColor(PANEL_BG))
w, h = self.width(), self.height()
cx, cy = w // 2, h // 2
# Evaluate target illumination states checking orientation angles against constraints
up_c = QColor(ARROW_ON) if self.pitch < -self.th else QColor(ARROW_OFF)
down_c = QColor(ARROW_ON) if self.pitch > self.th else QColor(ARROW_OFF)
right_c = QColor(ARROW_ON) if self.roll > self.th else QColor(ARROW_OFF)
left_c = QColor(ARROW_ON) if self.roll < -self.th else QColor(ARROW_OFF)
p.setPen(Qt.NoPen)
# UP Arrow
p.setBrush(up_c)
p.drawPolygon(QPolygon([QPoint(cx - 20, cy + 50 + 35), QPoint(cx - 30 - 20, cy + 50), QPoint(cx + 30 - 20, cy + 50)]))
# DOWN Arrow
p.setBrush(down_c)
p.drawPolygon(QPolygon([QPoint(cx - 20, cy - 50 - 35), QPoint(cx - 30 - 20, cy - 50), QPoint(cx + 30 - 20, cy - 50)]))
# LEFT Arrow
p.setBrush(left_c)
p.drawPolygon(QPolygon([QPoint(cx - 50 - 20 - 35, cy), QPoint(cx - 50 - 20, cy + 30), QPoint(cx - 50 - 20, cy - 30)]))
# RIGHT Arrow
p.setBrush(right_c)
p.drawPolygon(QPolygon([QPoint(cx + 50 - 20 + 35, cy), QPoint(cx + 50 - 20, cy + 30), QPoint(cx + 50 - 20, cy - 30)]))
# ─────────────────────────────────────────────
# ROS2 INTEGRATED NODE
# ─────────────────────────────────────────────
class ROS2HUDListener(Node):
"""
Subclass of a native ROS2 node execution instance. Handles asynchronous topic discovery,
unmarshals multi-sensor frames, and maps data streams directly into GUI telemetry channels.
"""
def __init__(self, win_handle):
super().__init__('launcher_hud_listener')
self.win = win_handle
self._subs = {}
self._sub_lock = threading.Lock()
# Relaxed Quality of Service profile configuration tuned to capture lossy, fast telemetry data feeds
qos_sensor = QoSProfile(
history=HistoryPolicy.KEEP_LAST,
depth=10,
reliability=ReliabilityPolicy.BEST_EFFORT
)
# Standard subscription definitions mapping directly to HUD updating operations
self.create_subscription(Int32, '/score', self._score_cb, 10)
self.create_subscription(Twist, '/drone/cmd_vel', self._cmd_vel_cb, 10)
self.create_subscription(Float32MultiArray, '/drone/orientation', self._orient_cb, qos_sensor)
self.create_subscription(String, '/emg_calibration_status', self._emg_calib_status_cb, 10)
# Master publisher interfaces intended to inject control flow back inside the simulation environment
self.game_over_pub = self.create_publisher(Bool, '/game_over', 10)
self.game_reset_pub = self.create_publisher(Bool, '/game_reset', 10)
# Periodic scanning task to safely lock on to variable, dynamic hardware muscle sensor data topics
self.discovery_timer = self.create_timer(1.0, self._discover_emg_topic_safely)
def _discover_emg_topic_safely(self):
"""
Dynamically probes the running ROS graph for active EMG topic configurations,
safely attaching custom interface subscribers when a match emerges.
"""
with self._sub_lock:
if self._subs:
return # Skip discovery if an active muscle stream hook has already been bound
all_topics = self.get_topic_names_and_types()
for topic_name, topic_types in all_topics:
if 'emg' not in topic_name.lower(): continue
if 'calibration' in topic_name or 'status' in topic_name: continue
type_str = topic_types[0] if topic_types else ''
# Check for standard data wrapper array objects
if type_str == 'std_msgs/msg/Float32':
from std_msgs.msg import Float32
self._subs[topic_name] = self.create_subscription(
Float32, topic_name,
lambda msg: self.win.sig_emg_raw.emit(max(0.0, min(1.0, float(msg.data)))), 10
)
self.discovery_timer.cancel()
break
# Support interface structural specifications for custom messages
if 'DelsysSensorData' in type_str or 'delsys_interfaces' in type_str:
try:
from delsys_interfaces.msg import DelsysSensorData
self._subs[topic_name] = self.create_subscription(DelsysSensorData, topic_name, self._emg_native_msg_cb, 200)
self.discovery_timer.cancel()
break
except ImportError: continue
def _emg_native_msg_cb(self, msg):
try:
self.win.sig_emg_raw.emit(max(0.0, min(1.0, float(msg.data_value))))
except Exception: pass
def _emg_calib_status_cb(self, msg):
keywords = ["calibrated", "MVC", "Completed", "saved", "CALIB"]
if any(k in msg.data for k in keywords): self.win.sig_emg.emit(999.0)
def _score_cb(self, msg):
self.win.sig_score.emit(msg.data)
def _cmd_vel_cb(self, msg):
self.win.sig_twist.emit(msg.linear.x, msg.linear.y, msg.linear.z)
def _orient_cb(self, msg):
if len(msg.data) >= 2: self.win.sig_imu.emit(msg.data[0], msg.data[1])
def publish_game_over(self):
m = Bool(); m.data = True; self.game_over_pub.publish(m)
def publish_game_reset(self):
m = Bool(); m.data = True; self.game_reset_pub.publish(m)
# ─────────────────────────────────────────────
# PROCESS MANAGER
# ─────────────────────────────────────────────
print_lock = threading.Lock()
class ProcessManager:
"""
Subprocess execution architecture that coordinates sourcing ROS environments,
spinning up nodes, trapping stdout diagnostic logs, and performing group termination.
"""
def __init__(self, ready_cb=None):
self.procs = {}
self.ready_cb = ready_cb
self._ros_env = None
def _get_ros_env(self):
"""
Dynamically spins up a quick shell task to source ROS2 environment parameters,
exporting standard dependency environment tables straight into localized dictionary keys.
"""
if self._ros_env is None:
env = os.environ.copy()
try:
cmd = f"bash -c 'source {ROS_SETUP} && source {WS_SETUP} && env'"
out = subprocess.check_output(cmd, shell=True, text=True, timeout=5)
for line in out.splitlines():
if '=' in line:
k, _, v = line.partition('=')
env[k] = v
self._ros_env = env
except Exception: pass
return self._ros_env if self._ros_env else os.environ.copy()
def start(self, name: str, cmd: str, sudo=False, ready_trigger=None) -> subprocess.Popen:
"""
Spins up non-blocking child background shell commands. Employs stream scraping
threads to trigger ready signals whenever specific log signatures are matched.
"""
full = f"sudo -E bash -c '{cmd}'" if sudo else f"bash -c '{cmd}'"
env = self._get_ros_env()
env["TERM"] = "dumb"
env["PYTHONUNBUFFERED"] = "1"
if name == "godot":
env["QT_QPA_PLATFORM"] = "xcb"
env["DISPLAY"] = os.environ.get("DISPLAY", ":0")
proc = subprocess.Popen(full, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, universal_newlines=True, bufsize=0, errors='ignore', env=env)
self.procs[name] = proc
def _read():
ansi_escape = re.compile(r'\x1B[@-_][0-?]*[ -/]*[@-~]')
for raw_line in iter(proc.stdout.readline, ''):
# Rimuove ANSI escape codes
raw_line = ansi_escape.sub('', raw_line)
# Splitta su \r e prende l'ultimo pezzo non vuoto
parts = [p.strip() for p in raw_line.split('\r') if p.strip()]
if not parts:
continue
line = parts[-1]
if line:
prefisso = f"[{name}]"
with print_lock:
print(f"{prefisso:<15} {line}", flush=True)
# Unblock launcher state machines if target keyword matches console log output
if ready_trigger and ready_trigger in line:
if self.ready_cb:
self.ready_cb(name)
threading.Thread(target=_read, daemon=True).start()
return proc
def stop_all(self):
"""Forces hard cleanups across child task trees using kernel SIGKILL calls."""
for name, proc in list(self.procs.items()):
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
proc.wait(timeout=0.2)
except Exception:
try: proc.kill()
except Exception: pass
self.procs.clear()
# Hard terminate loose background scripts or stray engine windows running on known ports
try:
subprocess.call("pkill -9 -f emg_processing_node 2>/dev/null", shell=True)
subprocess.call("pkill -9 -f imu_processing_node 2>/dev/null", shell=True)
subprocess.call("pkill -9 -f drone_controller_node 2>/dev/null", shell=True)
subprocess.call("pkill -9 -f rosbridge_websocket 2>/dev/null", shell=True)
subprocess.call("sudo pkill -9 -f delsys_connector_socket_ros.py 2>/dev/null", shell=True)
subprocess.call("pkill -9 -f Godot_v4.3 2>/dev/null", shell=True)
except Exception: pass
time.sleep(0.2)
# ─────────────────────────────────────────────
# MAIN WINDOW
# ─────────────────────────────────────────────
class MainWindow(QMainWindow):
# Thread-safe signal slots designed to route back into main GUI update routines
sig_step = pyqtSignal(int, str, str, str, str)
sig_emg = pyqtSignal(float)
sig_emg_raw = pyqtSignal(float)
sig_imu = pyqtSignal(float, float)
sig_score = pyqtSignal(int)
sig_twist = pyqtSignal(float, float, float)
sig_embed_godot = pyqtSignal(int)
sig_ready = pyqtSignal()
def __init__(self):
os.environ["QT_QPA_PLATFORM"] = "xcb" # Assures stable Linux display coordination
super().__init__()
self.setWindowTitle("DELSYS SENSOR IN ROS2 FRAMEWORK BY UNIMORE - DRONE CONTROL DEMO")
self.setMinimumSize(1340, 760)
# Runtime internal tracking metrics
self._recording = False
self._system_ready = False
self._imu_done = False
self._emg_done = False
self._emg_calibrated = False
self._emg_value = 0.0
self._current_score = 0
self._game_start_time = None
self._step_event = threading.Event()
self._godot_process = None
self._pm = ProcessManager(ready_cb=self._on_process_ready)
self.setStyleSheet(get_stylesheet(1.0))
self._build_ui()
# Establish thread-safe internal signal connections
self.sig_step.connect(self._handle_step_update)
self.sig_emg.connect(self._update_emg_hud)
self.sig_emg_raw.connect(self._update_emg_raw_hud)
self.sig_imu.connect(self._update_imu_hud)
self.sig_score.connect(self._update_score_hud)
self.sig_twist.connect(self._update_twist_hud)
self.sig_ready.connect(self._on_system_ready)
# Setup real-time system clock heartbeat for tracking match session lengths
self._gui_timer = QTimer()
self._gui_timer.timeout.connect(self._gui_tick)
self._gui_timer.start(50)
# Setup structural window-docking loops to snap the external game process into place
self._godot_wid = None
self._dock_timer = QTimer()
self._dock_timer.timeout.connect(self._sync_godot_window)
self._dock_timer.start(30)
self._last_geom = None
# Asynchronously spin up the background ROS2 worker thread
threading.Thread(target=self._ros2_spin_worker, daemon=True).start()
def _ros2_spin_worker(self):
rclpy.init()
self._ros_listener = ROS2HUDListener(self)
try: rclpy.spin(self._ros_listener)
except Exception: pass
def _on_process_ready(self, name: str):
self._step_event.set()
def _find_godot_window(self):
"""Queries the Linux X11 display manager via wmctrl to track the native Godot window ID."""
try:
out = subprocess.check_output("wmctrl -l", shell=True).decode()
for line in out.splitlines():
if "drone-game" in line.lower(): return line.split()[0]
except: pass
return None
def _move_resize_godot(self):
"""
Tracks the global layout position coordinates of the master host widget,
forcing the X11 system engine to move the standalone Godot app directly into those bounds.
"""
if not self._godot_wid: return
top_left = self.godot_host.mapToGlobal(self.godot_host.rect().topLeft())
x, y = top_left.x(), top_left.y()
w, h = self.godot_host.width(), self.godot_host.height()
geom = (x, y, w, h)
if geom == self._last_geom: return
self._last_geom = geom
# Issue system control command resizing the external canvas window frame
subprocess.call(f"wmctrl -i -r {self._godot_wid} -e 0,{x},{y},{w},{h}", shell=True, stderr=subprocess.DEVNULL)
def _raise_godot(self):
"""Brings the Godot simulation app directly to the top layer of the display stacking order."""
if self._godot_wid:
subprocess.call(f"wmctrl -i -r {self._godot_wid} -b add,above", shell=True, stderr=subprocess.DEVNULL)
subprocess.call(f"xdotool windowraise {self._godot_wid}", shell=True, stderr=subprocess.DEVNULL)
def _build_ui(self):
"""Assembles structural panels, asset nodes, and buttons into the dashboard UI layout."""
root = QWidget(); root.setObjectName("root"); self.setCentralWidget(root)
base_layout = QHBoxLayout(root); base_layout.setContentsMargins(12, 12, 12, 12); base_layout.setSpacing(12)
left_side_layout = QVBoxLayout(); left_side_layout.setSpacing(12)
# Build Upper Brand Banner Panel Section
self.f_header_extended = card()
self.f_header_extended.setFixedSize(340 + 360 + 12, 75)
l_hdr = QHBoxLayout(self.f_header_extended); l_hdr.setContentsMargins(16, 8, 16, 8)
self.lbl_logo_emg = QLabel()
if os.path.exists(LOGO_EMG_PATH):
pix_emg = QPixmap(LOGO_EMG_PATH).scaled(42, 42, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.lbl_logo_emg.setPixmap(pix_emg)
l_hdr.addWidget(self.lbl_logo_emg)
l_hdr.addSpacing(12)
v_txt = QVBoxLayout()
self.lbl_brand1 = lbl("DELSYS SENSORS - ROS2 FRAMEWORK UNIMORE", ACCENT, 14, bold=True, spacing=1)
self.lbl_brand1.setAlignment(Qt.AlignCenter)
v_txt.addWidget(self.lbl_brand1)
l_hdr.addLayout(v_txt)
l_hdr.addSpacing(12)
self.lbl_logo_ars = QLabel()
if os.path.exists(LOGO_ARS_PATH):
pix_ars = QPixmap(LOGO_ARS_PATH).scaled(80, 42, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.lbl_logo_ars.setPixmap(pix_ars)
l_hdr.addWidget(self.lbl_logo_ars)
left_side_layout.addWidget(self.f_header_extended)
# Combine Left Parameter Panels and HUD Side-by-Side
cols_sub_layout = QHBoxLayout(); cols_sub_layout.setSpacing(12)
self.col_left = self._build_col_left()
self.col_center = self._build_col_center()
self.col_left.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
self.col_left.setFixedWidth(340)
self.col_center.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
self.col_center.setFixedWidth(340)
cols_sub_layout.addWidget(self.col_left)
cols_sub_layout.addWidget(self.col_center)
left_side_layout.addLayout(cols_sub_layout)
# Build Right Side Area dedicated to housing the Godot simulation engine view
self.right_side_container = QWidget()
v_right = QVBoxLayout(self.right_side_container); v_right.setContentsMargins(0, 0, 0, 0); v_right.setSpacing(12)
# The targeted bounding viewport container where the Godot window frame snaps into place
self.godot_host = QWidget()
self.godot_host.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
v_right.addWidget(self.godot_host, stretch=4)
self.f_bottom_logos = card()
self.f_bottom_logos.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
l_bottom_imgs = QHBoxLayout(self.f_bottom_logos); l_bottom_imgs.setContentsMargins(12, 8, 12, 8); l_bottom_imgs.setSpacing(20)
self.lbl_bottom_delsys = QLabel()
self.lbl_bottom_delsys.setAlignment(Qt.AlignCenter)
self.lbl_bottom_ars = QLabel()
self.lbl_bottom_ars.setAlignment(Qt.AlignCenter)
l_bottom_imgs.addWidget(self.lbl_bottom_delsys, stretch=1)
l_bottom_imgs.addWidget(self.lbl_bottom_ars, stretch=1)
v_right.addWidget(self.f_bottom_logos, stretch=1)
base_layout.addLayout(left_side_layout, stretch=0)
base_layout.addWidget(self.right_side_container, stretch=1)
def _build_col_left(self):
"""Assembles the deployment sequencer tracking column, calibration handles, and primary buttons."""
w = QWidget()
lay = QVBoxLayout(w); lay.setContentsMargins(0,0,0,0); lay.setSpacing(10)
self.f_sys = card(); l_sys = QVBoxLayout(self.f_sys); l_sys.setSpacing(6)
self.lbl_title_sys = lbl("SERVICES SYSTEM", ACCENT, 12, spacing=2, bold=True)
l_sys.addWidget(self.lbl_title_sys); l_sys.addWidget(sep())
self._dots = {}
services = [("build", "colcon build"), ("rosbridge", "rosbridge server"),
("emg", "emg_processing_node"), ("imu", "imu_processing_node"),
("controller", "drone_controller"), ("bridge", "delsys_bridge (sudo)"),
("godot", "godot engine")]
for key, name in services:
dot = StatusDot(name); self._dots[key] = dot; l_sys.addWidget(dot)
l_sys.addWidget(sep())
self._build_progress = QProgressBar(); self._build_progress.setRange(0, 7); self._build_progress.setFixedHeight(6); self._build_progress.setVisible(False); l_sys.addWidget(self._build_progress)
self._build_lbl = lbl("", WHITE, 9) # Testo bianco base
self._build_lbl.setVisible(False); l_sys.addWidget(self._build_lbl)
self._build_progress = QProgressBar(); self._build_progress.setRange(0, 7)
self._build_progress.setTextVisible(False)
self._build_progress.setFixedHeight(6); self._build_progress.setVisible(False); l_sys.addWidget(self._build_progress)
btn_row = QHBoxLayout()
self.btn_start = QPushButton("▶ START SYSTEM")
self.btn_start.setObjectName("green")
self.btn_start.clicked.connect(self._start_system)
btn_row.addWidget(self.btn_start)
l_sys.addLayout(btn_row)
lay.addWidget(self.f_sys, stretch=5)
# Section containing hardware calibration triggers
f_cal = card(); l_cal = QVBoxLayout(f_cal); l_cal.setSpacing(4)
hdr_c = QHBoxLayout()
self.lbl_title_cal = lbl("CALIBRATIONS", ACCENT, 12, spacing=2, bold=True)
hdr_c.addWidget(self.lbl_title_cal); hdr_c.addStretch()
self._calib_status = lbl("TO DO", ORANGE, 9); hdr_c.addWidget(self._calib_status); l_cal.addLayout(hdr_c)
l_cal.addWidget(sep())
self.lbl_sub_imu = lbl("Neutral Wrist (odd number sensor)", GREY, 11)
self.lbl_sub_imu.setAlignment(Qt.AlignCenter)
self.btn_imu = QPushButton(" IMU CALIBRATION"); self.btn_imu.setEnabled(False); self.btn_imu.clicked.connect(self._calib_imu)
self._imu_bar = CalibBar(ACCENT, CALIB_DURATION_IMU); self._imu_bar.finished.connect(self._on_imu_calib_done)
l_cal.addWidget(self.lbl_sub_imu); l_cal.addWidget(self.btn_imu); l_cal.addWidget(self._imu_bar)
l_cal.addSpacing(4)
self.lbl_sub_emg = lbl("Max contraction (even number sensor)", GREY, 11)
self.lbl_sub_emg.setAlignment(Qt.AlignCenter)
self.btn_emg = QPushButton(" EMG CALIBRATION"); self.btn_emg.setEnabled(False); self.btn_emg.clicked.connect(self._calib_emg)
self._emg_bar = CalibBar(ORANGE, CALIB_DURATION_EMG); self._emg_bar.finished.connect(self._on_emg_calib_done)
l_cal.addWidget(self.lbl_sub_emg); l_cal.addWidget(self.btn_emg); l_cal.addWidget(self._emg_bar)
lay.addWidget(f_cal, stretch=5)
# Section containing game control buttons
f_rec = card(); l_rec = QVBoxLayout(f_rec)
self.lbl_title_rec = lbl("GAMEPLAY", ACCENT, 12, spacing=2, bold=True)
l_rec.addWidget(self.lbl_title_rec); l_rec.addWidget(sep())
rec_btn_layout = QHBoxLayout()
self.btn_record = QPushButton("▶ START")
self.btn_restart = QPushButton("⟳ RESTART")
for btn in [self.btn_record, self.btn_restart]:
btn.setEnabled(False)
self.btn_record.clicked.connect(self._toggle_recording)
self.btn_restart.clicked.connect(self._restart_gameplay)
rec_btn_layout.addWidget(self.btn_record)
rec_btn_layout.addWidget(self.btn_restart)
l_rec.addLayout(rec_btn_layout)
self._rec_lbl = lbl("Waiting for system...", WHITE, 9)
l_rec.addWidget(self._rec_lbl)
lay.addWidget(f_rec, stretch=3)
return w
def _build_col_center(self):
"""Constructs the central dashboard column displaying live flight telemetry meters."""
w = QWidget()
lay = QVBoxLayout(w); lay.setContentsMargins(0,0,0,0); lay.setSpacing(12)
f_hud = QFrame(); f_hud.setObjectName("card")
l_hud = QVBoxLayout(f_hud); l_hud.setContentsMargins(16, 16, 16, 16); l_hud.setSpacing(12)
self.lbl_title_hud = lbl("REALTIME FLIGHT HUD", ACCENT, 15, bold=True, spacing=2)
l_hud.addWidget(self.lbl_title_hud); l_hud.addWidget(sep())
# Match Score and Session Timer indicators
st_row = QHBoxLayout()
v_sc = QVBoxLayout()
self.lbl_sc_title = lbl("SCORE", GREY, 13, bold=True)
v_sc.addWidget(self.lbl_sc_title); self.hud_score = lbl("0", GREEN, 36, bold=True); v_sc.addWidget(self.hud_score); st_row.addLayout(v_sc)
st_row.addStretch()
v_tm = QVBoxLayout()
self.lbl_tm_title = lbl("TIMER", GREY, 13, bold=True)
v_tm.addWidget(self.lbl_tm_title); self.hud_timer = lbl("60", WHITE, 36, bold=True); v_tm.addWidget(self.hud_timer); st_row.addLayout(v_tm)
l_hud.addLayout(st_row); l_hud.addWidget(sep())
# Live EMG Muscle Activity Bar indicators
hdr_b = QHBoxLayout()
l_hud.addWidget(lbl("VELOCITY", ACCENT, 13, bold=True))
l_hud.addWidget(lbl("EMG", WHITE, 14, bold=True))
hdr_b = QHBoxLayout()
hdr_b.addStretch()
self.lbl_emg_pct = lbl("0%", WHITE, 10, bold=True)
hdr_b.addWidget(self.lbl_emg_pct)
l_hud.addLayout(hdr_b)
self.emg_canvas = EMGNativeCanvas()
l_hud.addWidget(self.emg_canvas)
self.hud_emg_status = lbl("STATUS: UNCALIBRATED", GREY, 11, bold=True)
l_hud.addWidget(self.hud_emg_status)
l_hud.addWidget(sep())
# 2D Spatial Crosshair Direction Indicators
l_hud.addWidget(lbl("DIRECTION", ACCENT, 13, bold=True))
l_hud.addWidget(lbl("IMU", WHITE, 13, bold=True))
l_hud.addStretch()
self.imu_visualizer = IMUVisualizer()
l_hud.addWidget(self.imu_visualizer, alignment=Qt.AlignCenter)
l_hud.addStretch()
l_hud.addWidget(sep())
# Exact Cartesian Twist Vector Value Fields
self.lbl_tele_title = lbl("CURRENT TWIST TELEMETRY", ACCENT, 13, bold=True)
l_hud.addWidget(self.lbl_tele_title)
self.lbl_telemetria_x = lbl("X: +0.000", GREY, 14)
self.lbl_telemetria_y = lbl("Y: +0.000", GREY, 14)
self.lbl_telemetria_z = lbl("Z: +0.000", GREY, 14)
for lbl_t in [self.lbl_telemetria_x, self.lbl_telemetria_y, self.lbl_telemetria_z]:
lbl_t.setAlignment(Qt.AlignCenter)
l_hud.addWidget(lbl_t)
lay.addWidget(f_hud)
return w
def _update_emg_hud(self, value: float):
"""Processes incoming muscle data stream inputs to update threshold zones and statuses."""
if value == 999.0: # Magic state string payload flagging a calibration step complete
self._emg_calibrated = True
self._emg_done = True
self.hud_emg_status.setText("STATUS: CALIBRATED ✓")
self.hud_emg_status.setStyleSheet(f"color: {ACCENT}; font-weight: bold;")
self._update_calib_status_string()
return
self._emg_value = value
self.emg_canvas.update_value(self._emg_value, self._emg_calibrated)
if not self._emg_calibrated:
self.lbl_emg_pct.setText(f"{int(self._emg_value * 100)}% (raw)")
self.hud_emg_status.setText("STATUS: UNCALIBRATED")
target_color = WHITE if self._system_ready else GREY
self.hud_emg_status.setStyleSheet(f"color: {target_color}; font-weight: bold;")
return
# Style active metrics checking output flags against internal thresholds
self.lbl_emg_pct.setText(f"{int(self._emg_value * 100)}%")
if self._emg_value < DEAD_THRESH:
self.hud_emg_status.setText("STATUS: DEAD ZONE")
self.hud_emg_status.setStyleSheet(f"color: {WHITE}; font-weight: bold;")
elif self._emg_value < BOOST_THRESH:
self.hud_emg_status.setText("STATUS: ▶ NORMAL")
self.hud_emg_status.setStyleSheet(f"color: {GREEN}; font-weight: bold;")
else:
self.hud_emg_status.setText("STATUS: ⚡ BOOST")
self.hud_emg_status.setStyleSheet(f"color: {RED_C}; font-weight: bold;")
def _update_emg_raw_hud(self, value: float):
self._update_emg_hud(value)
def _update_imu_hud(self, pitch: float, roll: float):
self.imu_visualizer.update_angles(pitch, roll)
def _update_score_hud(self, score: int):
"""Tracks, updates, and updates the layout text color based on points accumulated."""
self._current_score += score
self.hud_score.setText(str(self._current_score))
if self._current_score > 0:
self.hud_score.setStyleSheet(f"color: {GREEN}; font-size: 36px; font-weight: bold;")
elif self._current_score < 0:
self.hud_score.setStyleSheet(f"color: {RED_C}; font-size: 36px; font-weight: bold;")
else:
self.hud_score.setStyleSheet(f"color: {WHITE}; font-size: 36px; font-weight: bold;")
def _update_twist_hud(self, lx: float, ly: float, lz: float):
self.lbl_telemetria_x.setText(f"X: {lx:+.3f}")
self.lbl_telemetria_y.setText(f"Y: {ly:+.3f}")
self.lbl_telemetria_z.setText(f"Z: {lz:+.3f}")
def _gui_tick(self):
"""Runs periodic match countdown calculations inside the primary thread loop."""
if self._recording:
elapsed = time.time() - self._game_start_time
rem = max(0, 60 - int(elapsed))
self.hud_timer.setText(str(rem))
self.hud_timer.setStyleSheet(f"color: {RED_C if rem < 10 else WHITE}; font-size: 36px; font-weight: bold;")
if rem <= 0: # Stop session recording when time hits zero
self._recording = False
self._game_start_time = None
send_ctrl({'DataType': 'RECORDING_STOP'}, port=CTRL_PORT)
if self._ros_listener: self._ros_listener.publish_game_over()
self.btn_record.setText("▶ START")
self.btn_record.setObjectName("green")
self._rec_lbl.setText("TIME IS UP! Press START or RESTART.")
self._rec_lbl.setStyleSheet(f"color: {RED_C}; font-weight: bold;")
def _start_system(self):
"""
Handles ecosystem bootstrapping. If the ecosystem is already active,
it performs a full restart by clean-forking the process tree.
"""
if self._system_ready:
setup_ws = os.path.join(os.path.expanduser("~"), "delsys_demo/ros2_ws/install/setup.bash")
script_path = os.path.abspath(sys.argv[0])
cmd = f"source /opt/ros/humble/setup.bash && source {setup_ws} && {sys.executable} {script_path}"
if self._godot_process:
self._godot_process.kill()
self._godot_process = None
pid = os.fork()
if pid == 0:
os.setsid() # Break process association to separate it from the current terminal group
try:
subprocess.call("pkill -9 -f emg_processing_node 2>/dev/null", shell=True)
subprocess.call("pkill -9 -f imu_processing_node 2>/dev/null", shell=True)
subprocess.call("pkill -9 -f drone_controller_node 2>/dev/null", shell=True)
subprocess.call("pkill -9 -f rosbridge_websocket 2>/dev/null", shell=True)
subprocess.call("sudo pkill -9 -f delsys_connector_socket_ros.py 2>/dev/null", shell=True)
subprocess.call("sudo fuser -k -9 9001/tcp 9002/tcp 9003/tcp 9090/tcp 2>/dev/null", shell=True)
except Exception: pass
time.sleep(0.3)
subprocess.Popen(cmd, shell=True, executable="/bin/bash")
sys.exit(0)
else:
QApplication.quit()
sys.exit(0)
# Clear active interface tracker profiles to default values
self._system_ready = False
self._recording = False
self._imu_done = False
self._emg_done = False
self._emg_calibrated = False
self._current_score = 0
self._godot_wid = None
self._last_geom = None
self.hud_score.setText("0")
self.hud_score.setStyleSheet(f"color: {WHITE}; font-size: 36px; font-weight: bold;")
self.hud_timer.setText("60")
self.btn_start.setEnabled(False)
self._build_progress.setVisible(True)
self._build_progress.setValue(0)
self._build_lbl.setVisible(True)
self._imu_bar.reset(); self._emg_bar.reset()
self.emg_canvas.update_value(0.0, False)
self._calib_status.setText("TO DO")
for dot in self._dots.values(): dot.set_state("off")
self._step_event.clear()
# Unroll initialization sequences via an independent execution background worker thread
threading.Thread(target=self._launch_sequence, daemon=True).start()
def _kill_system_procs(self):
if self._godot_process: self._godot_process.kill(); self._godot_process = None
self._pm.stop_all()
time.sleep(0.3)
def _sync_godot_window(self):
"""
Runs continuously in the background to handle the X11 embedding logic.
Snaps the external Godot simulation window into the designated PyQt container layout.
"""
if not self._godot_wid:
self._godot_wid = self._find_godot_window()
if self._godot_wid: self._raise_godot()
return
self._move_resize_godot()
def _launch_sequence(self):
"""
The master ecosystem initialization chain. Sources paths, builds custom packages,
launches ROS nodes step-by-step, and verifies the hardware connections.
"""
ros = f"source {ROS_SETUP} && source {WS_SETUP}"
self._pm.stop_all(); time.sleep(0.4)
# Step 1: Recompile the workspace and build custom ROS2 messages
self.sig_step.emit(0, "build", "pending", "building...", "colcon build...")
proc = self._pm.start("build", f"cd {ROS_WS} && source {ROS_SETUP} && rm -rf {ROS_WS}/build/delsys_interfaces && colcon build --symlink-install --event-handlers console_cohesion+ status+ 2>&1")
proc.wait()
if proc.returncode != 0: self.sig_step.emit(1, "build", "error", "FAIL", "Build failed"); return
self.sig_step.emit(1, "build", "ok", "colcon build ✓", "✓ colcon build complete")
# Step 2: Spin up the ROSBridge WebSocket Server for browser/engine integration
self.sig_step.emit(1, "rosbridge", "pending", "running...", "ROSBridge...")
self._pm.start("rosbridge", f"{ros} && ros2 launch rosbridge_server rosbridge_websocket_launch.xml", ready_trigger="started on port")
self._step_event.wait(timeout=6.0); self._step_event.clear()
self.sig_step.emit(2, "rosbridge", "ok", "rosbridge ✓", "✓ ROSBridge activated")
# Step 3: Launch the EMG signal filtering and processing node
self.sig_step.emit(2, "emg", "pending", "running...", "EMG node...")
self._pm.start("emg", f"{ros} && ros2 run emg_processing emg_processing_node", ready_trigger="listening")
self._step_event.wait(timeout=6.0); self._step_event.clear()
self.sig_step.emit(3, "emg", "ok", "emg_processing ✓", "✓ EMG server activated")
# Step 4: Launch the IMU kinematic processing node
self.sig_step.emit(3, "imu", "pending", "running...", "IMU node...")
self._pm.start("imu", f"{ros} && ros2 run imu_processing imu_processing_node", ready_trigger="listening")
self._step_event.wait(timeout=6.0); self._step_event.clear()
self.sig_step.emit(4, "imu", "ok", "imu_processing ✓", "✓ IMU server activated")