-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgui.py
1747 lines (1415 loc) · 65.6 KB
/
gui.py
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
# gui.py
import os
import csv
import numpy as np
from datetime import datetime
from dataclasses import asdict
from PyQt5.QtWidgets import (
QMainWindow, QStackedWidget, QLabel, QToolBar,
QStatusBar, QVBoxLayout, QWidget, QGridLayout,
QFrame, QHBoxLayout, QPushButton, QApplication,
QDialog, QFormLayout, QLineEdit, QSpinBox, QDoubleSpinBox, # Added QDoubleSpinBox
QCheckBox, QComboBox, QFileDialog, QGroupBox, QTextEdit,
QProgressBar, QSplitter, QScrollArea, QShortcut,
QTabWidget, QMessageBox
)
from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot, QTimer, QThread
from PyQt5.QtGui import (
QFont, QColor, QPainter, QPen, QBrush, QPainterPath,
QKeySequence
)
import pyqtgraph as pg
import time
from visualisation_core import PlotManager, BasePlotWidget, LivePlotWidget
from track_visualizer import TrackVisualizer as TrackVisualizerCore
from visualisation_core import TrackVisualizer as TrackVisualizerWidget
import logging
class ClickableLabel(QLabel):
"""Label that emits a signal when clicked, useful for interactive data displays"""
clicked = pyqtSignal(str)
def __init__(self, text: str, parent=None):
super().__init__(text, parent)
self.setCursor(Qt.PointingHandCursor)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.clicked.emit(self.objectName())
# CustomPlotWidget class specifically designed for PyQt5
class CustomPlotWidget(pg.PlotWidget):
"""Enhanced plot widget with optimized settings for race telemetry"""
def __init__(self, title=None, parent=None):
# Initialize with specific view settings for PyQt5
super().__init__(parent=parent)
# Configure background based on theme
if parent and parent.dark_mode:
self.setBackground('k') # Dark theme
else:
self.setBackground('w') # Light theme
# Add grid with slight transparency
self.showGrid(x=True, y=True, alpha=0.3)
# Set up the title if provided
if title:
self.setTitle(title, size='12pt')
# Configure the view box for better interaction
view_box = self.getPlotItem().getViewBox()
view_box.setMouseMode(pg.ViewBox.RectMode)
# Set up reasonable axis defaults
self.getPlotItem().setDownsampling(mode='peak')
self.getPlotItem().setClipToView(True)
# Configure for performance
self.maxPoints = 1000 # Limit the number of points to display
# Initialize plot curves dictionary
self.curves = {}
def plot(self, x, y, pen='b', name=None, clear=False, **kwargs):
"""Enhanced plotting method that reuses plot curves"""
try:
# Convert inputs to numpy arrays if they aren't already
x = np.array(x, dtype=np.float32)
y = np.array(y, dtype=np.float32)
# Ensure x and y have the same shape
if x.shape != y.shape:
print(f"Shape mismatch: x={x.shape}, y={y.shape}")
return None
# Clear all curves if requested
if clear:
self.clear()
self.curves = {}
# Create or update curve
curve_key = name if name else 'default'
if curve_key not in self.curves:
# Create new curve
self.curves[curve_key] = self.getPlotItem().plot(
x=x,
y=y,
pen=pen,
name=name,
**kwargs
)
else:
# Update existing curve
self.curves[curve_key].setData(x=x, y=y)
return self.curves[curve_key]
except Exception as e:
print(f"Error plotting data: {str(e)}")
return None
def clear(self):
"""Clear all plots"""
self.getPlotItem().clear()
self.curves = {}
class TabWidget(QWidget):
"""Base class for tab widgets with common functionality"""
def __init__(self, config_manager, plot_manager, parent=None):
super().__init__(parent)
self.config = config_manager
self.plot_manager = plot_manager
self.dark_mode = self.config.get("display", "dark_mode")
# Create a main layout for the tab
self.main_layout = QVBoxLayout(self)
self.main_layout.setContentsMargins(8, 8, 8, 8)
# Create a content widget to hold the actual tab content
self.content_widget = QWidget(self)
self.content_layout = QVBoxLayout(self.content_widget)
# Add content widget to main layout
self.main_layout.addWidget(self.content_widget)
# Set up the UI (will be implemented by subclasses)
self.setup_ui()
self.apply_theme()
def setup_ui(self):
"""Setup UI elements - to be implemented by subclasses"""
pass
def apply_theme(self):
"""Apply current theme to all widgets"""
if self.dark_mode:
self.setStyleSheet("""
QWidget { background-color: #2b2b2b; color: #ffffff; }
QGroupBox { border: 1px solid #404040; margin-top: 6px; }
QGroupBox::title { color: #ffffff; }
""")
else:
self.setStyleSheet("")
# Update plot backgrounds if any
for plot in self.findChildren(pg.PlotWidget):
plot.setBackground(self.palette().color(self.backgroundRole()))
def get_theme_palette(self):
"""Get color palette based on current theme"""
palette = self.palette()
if self.dark_mode:
# Dark theme colors
palette.setColor(self.backgroundRole(), QColor(25, 25, 25))
palette.setColor(self.foregroundRole(), QColor(255, 255, 255))
else:
# Light theme colors
palette.setColor(self.backgroundRole(), QColor(240, 240, 240))
palette.setColor(self.foregroundRole(), QColor(0, 0, 0))
return palette
class RaceViewTab(TabWidget):
"""Primary race visualization tab showing track view and real-time telemetry"""
def __init__(self, config_manager, track_visualizer, parent=None):
# Initialize instance variables before super().__init__
self.track_visualizer = track_visualizer
self.plot_items_initialized = False
self.path_points = []
self.vehicle_path = None
self.vehicle_marker = None
self.track_plot = None
self.camera_left = None
self.camera_right = None
self.speed_plot = None
self.steering_plot = None
# Now call super().__init__ which will call setup_ui
super().__init__(config_manager, parent)
# Connect visualization updates after everything is initialized
self.track_visualizer.visualization_updated.connect(self.update_visualization)
def setup_ui(self):
# Create horizontal layout for main content
content_split = QHBoxLayout()
self.content_layout.addLayout(content_split)
# Create left panel for track visualization
left_panel = QFrame()
left_layout = QVBoxLayout(left_panel)
# Create track visualization widget
self.track_plot = pg.PlotWidget()
self.track_plot.setAspectLocked(True)
self.track_plot.showGrid(x=True, y=True, alpha=0.3)
self.track_plot.setLabel('left', 'Y Position', units='m')
self.track_plot.setLabel('bottom', 'X Position', units='m')
# Store plot items as instance variables
self.plot_items = {}
self._init_plot_items()
left_layout.addWidget(self.track_plot)
# Create camera visualization frame
camera_frame = QFrame()
camera_layout = QHBoxLayout(camera_frame)
# Initialize camera plots with stored curves
self.camera_left = pg.PlotWidget(title="Left Camera")
self.camera_right = pg.PlotWidget(title="Right Camera")
self.camera_left_curve = self.camera_left.plot([], [])
self.camera_right_curve = self.camera_right.plot([], [])
for camera in [self.camera_left, self.camera_right]:
camera.setFixedHeight(150)
camera.hideAxis('left')
camera.setLabel('bottom', 'Pixel')
camera_layout.addWidget(camera)
left_layout.addWidget(camera_frame)
# Create right panel for telemetry display
right_panel = QFrame()
right_layout = QVBoxLayout(right_panel)
# Vehicle dynamics group
dynamics_group = QGroupBox("Vehicle Dynamics")
dynamics_layout = QGridLayout(dynamics_group)
# Initialize plots with stored curves
self.speed_plot = CustomPlotWidget("Speed", self)
self.steering_plot = CustomPlotWidget("Steering Angle", self)
self.speed_curve = self.speed_plot.plot([], [], pen='b')
self.steering_curve = self.steering_plot.plot([], [], pen='r')
dynamics_layout.addWidget(self.speed_plot, 0, 0)
dynamics_layout.addWidget(self.steering_plot, 0, 1)
# Add layouts to groups
dynamics_group.setLayout(dynamics_layout)
# Add groups to layouts
right_layout.addWidget(dynamics_group)
right_panel.setLayout(right_layout)
# Add panels to main content layout
content_split.addWidget(left_panel, stretch=2)
content_split.addWidget(right_panel, stretch=1)
def _init_plot_items(self):
"""Initialize plot items only once"""
if not hasattr(self, 'plot_items_initialized') or not self.plot_items_initialized:
# Vehicle path curve
self.path_curve = pg.PlotCurveItem(
pen=pg.mkPen('y', width=2),
name='Vehicle Path'
)
self.track_plot.addItem(self.path_curve)
# Vehicle marker (scatter plot)
self.vehicle_marker = pg.ScatterPlotItem(
pen=pg.mkPen('r', width=2),
brush=pg.mkBrush('r'),
symbol='t',
size=20,
name='Vehicle Position'
)
self.track_plot.addItem(self.vehicle_marker)
self.plot_items_initialized = True
def update_display(self, sensor_data):
"""Update all display elements with new sensor data"""
if not sensor_data:
return
try:
# Update vehicle position and path
self.path_points.append((sensor_data.position_x, sensor_data.position_y))
if len(self.path_points) > 1000: # Limit path length
self.path_points.pop(0)
# Convert points to numpy arrays for plotting
if self.path_points:
points = np.array(self.path_points)
self.logger.debug(f"Updating path plot with {len(points)} points")
self.path_curve.setData(
x=points[:, 0].astype(np.float32),
y=points[:, 1].astype(np.float32)
)
# Update vehicle marker
self.vehicle_marker.setData(
x=[sensor_data.position_x],
y=[sensor_data.position_y]
)
# Update dynamics plots
current_time = np.array([sensor_data.timestamp], dtype=np.float32)
# Speed plot
self.speed_curve.setData(
x=current_time,
y=np.array([sensor_data.speed], dtype=np.float32)
)
# Steering plot
self.steering_curve.setData(
x=current_time,
y=np.array([sensor_data.steering_angle], dtype=np.float32)
)
if self.playback_index % 100 == 0:
self.logger.debug(f"Display updated: Speed={sensor_data.speed:.2f}, Position=({sensor_data.position_x:.2f}, {sensor_data.position_y:.2f})")
except Exception as e:
self.logger.error(f"Error updating display: {str(e)}", exc_info=True)
def _update_dynamics_plots(self, sensor_data):
"""Update vehicle dynamics plots"""
try:
# Get current time for x-axis
current_time = np.array([sensor_data.timestamp], dtype=np.float32)
# Speed plot
self.speed_plot.plot(
x=current_time,
y=np.array([sensor_data.speed], dtype=np.float32),
clear=True
)
# Steering plot
self.steering_plot.plot(
x=current_time,
y=np.array([sensor_data.steering_angle], dtype=np.float32),
clear=True
)
except Exception as e:
print(f"Error updating dynamics plots: {str(e)}")
def reset_display(self):
"""Reset all display elements"""
if not self.plot_items_initialized:
return
self.path_points.clear()
if self.vehicle_path:
self.vehicle_path.setData(x=np.array([]), y=np.array([]))
if self.vehicle_marker:
self.vehicle_marker.setData(x=np.array([]), y=np.array([]))
def reset_display(self):
"""Reset all display elements"""
self.path_points.clear()
if self.vehicle_path:
self.vehicle_path.setData(x=np.array([]), y=np.array([]))
if self.vehicle_marker:
self.vehicle_marker.setData(x=np.array([]), y=np.array([]))
def update_visualization(self, plot_items):
"""Update the visualization with new plot items"""
if 'vehicle' in plot_items:
self.track_plot.addItem(plot_items['vehicle'])
if 'path' in plot_items:
self.track_plot.addItem(plot_items['path'])
if 'predicted_path' in plot_items:
self.track_plot.addItem(plot_items['predicted_path'])
if 'left_boundary' in plot_items:
self.track_plot.addItem(plot_items['left_boundary'])
if 'right_boundary' in plot_items:
self.track_plot.addItem(plot_items['right_boundary'])
def setup_plot_colors(self):
"""Configure plot colors based on theme"""
if self.dark_mode:
self.plot_colors = {
'speed': 'g',
'steering': 'y',
'motor_left': 'c',
'motor_right': 'm',
'battery': 'r'
}
else:
self.plot_colors = {
'speed': 'darkGreen',
'steering': 'darkBlue',
'motor_left': 'darkCyan',
'motor_right': 'darkMagenta',
'battery': 'darkRed'
}
def _update_system_plots(self, sensor_data):
"""Update system status plots"""
# Motor plot
self.motors_plot.plot(
[sensor_data.timestamp],
[sensor_data.motor_left.duty],
pen=self.plot_colors['motor_left'],
name="Left Motor",
clear=True
)
self.motors_plot.plot(
[sensor_data.timestamp],
[sensor_data.motor_right.duty],
pen=self.plot_colors['motor_right'],
name="Right Motor"
)
# Battery plot
self.battery_plot.plot(
[sensor_data.timestamp],
[sensor_data.battery_power],
pen=self.plot_colors['battery'],
clear=True
)
class SystemHealthTab(TabWidget):
"""Tab for detailed system health monitoring"""
def __init__(self, config_manager, plot_manager, parent=None):
# Initialize instance variables
self.plot_items = {}
self.cpu_plots = []
self.motor_temp_plot = None
self.board_temp_plot = None
self.can_error_plot = None
self.plot_manager = plot_manager
super().__init__(config_manager, parent)
def setup_ui(self):
# CPU monitoring section
cpu_group = QGroupBox("CPU Load")
cpu_layout = QHBoxLayout(cpu_group)
self.cpu_plots = []
for i in range(3):
plot = CustomPlotWidget(f"CPU {i+1}", self)
self.cpu_plots.append(plot)
# Initialize plot items for each CPU
self.plot_items[f'cpu_{i}'] = plot.plot([], [],
pen='b',
name=f'CPU {i+1}')
cpu_layout.addWidget(plot)
self.content_layout.addWidget(cpu_group)
# Temperature monitoring section
temp_group = QGroupBox("Temperature Monitoring")
temp_layout = QGridLayout(temp_group)
self.motor_temp_plot = CustomPlotWidget("Motor Temperatures", self)
self.board_temp_plot = CustomPlotWidget("Board Temperatures", self)
# Initialize motor temperature plot items
self.plot_items['motor_left'] = self.motor_temp_plot.plot([], [],
pen='r',
name="Left Motor")
self.plot_items['motor_right'] = self.motor_temp_plot.plot([], [],
pen='g',
name="Right Motor")
# Initialize board temperature plot items
for i in range(3):
self.plot_items[f'board_temp_{i}'] = self.board_temp_plot.plot(
[], [],
pen=pg.intColor(i, 3),
name=f"Board {i+1}"
)
temp_layout.addWidget(self.motor_temp_plot, 0, 0)
temp_layout.addWidget(self.board_temp_plot, 0, 1)
self.content_layout.addWidget(temp_group)
# CAN bus monitoring section
can_group = QGroupBox("CAN Bus Status")
can_layout = QHBoxLayout(can_group)
self.can_error_plot = CustomPlotWidget("CAN Error Rate", self)
# Initialize CAN error plot items
for i in range(2):
self.plot_items[f'can_error_{i}'] = self.can_error_plot.plot(
[], [],
pen=pg.intColor(i, 2),
name=f"CAN {i+1}"
)
can_layout.addWidget(self.can_error_plot)
self.content_layout.addWidget(can_group)
def update_display(self, sensor_data):
"""Update system health displays"""
if not sensor_data or not hasattr(sensor_data, 'system_health'):
return
try:
health = sensor_data.system_health
current_time = np.array([sensor_data.timestamp], dtype=np.float32)
# Update CPU loads
for i, load in enumerate(health.cpu_load):
self.plot_items[f'cpu_{i}'].setData(
x=current_time,
y=np.array([load], dtype=np.float32)
)
# Update motor temperatures
self.plot_items['motor_left'].setData(
x=current_time,
y=np.array([sensor_data.motor_left.temperature], dtype=np.float32)
)
self.plot_items['motor_right'].setData(
x=current_time,
y=np.array([sensor_data.motor_right.temperature], dtype=np.float32)
)
# Update board temperatures
for i, temp in enumerate(health.board_temps):
self.plot_items[f'board_temp_{i}'].setData(
x=current_time,
y=np.array([temp], dtype=np.float32)
)
# Update CAN error plots - handle each error count separately
for i, error_count in enumerate(health.can_errors):
self.plot_items[f'can_error_{i}'].setData(
x=current_time,
y=np.array([error_count], dtype=np.float32)
)
except Exception as e:
print(f"Error updating health display: {str(e)}")
def reset_display(self):
"""Reset all plot data"""
try:
for plot_item in self.plot_items.values():
plot_item.setData([], [])
except Exception as e:
print(f"Error resseting display: {str(e)}")
class PerformanceTab(TabWidget):
"""Tab for analyzing race performance metrics and trends"""
def setup_ui(self):
# Top section for lap timing and speed profile
timing_group = QGroupBox("Lap Performance")
timing_layout = QHBoxLayout(timing_group)
# Lap time display and history
self.lap_time_plot = CustomPlotWidget("Lap Times", self)
self.speed_profile_plot = CustomPlotWidget("Speed Profile", self)
timing_layout.addWidget(self.lap_time_plot)
timing_layout.addWidget(self.speed_profile_plot)
self.content_layout.addWidget(timing_group)
# Middle section for acceleration and steering analysis
dynamics_group = QGroupBox("Vehicle Dynamics")
dynamics_layout = QGridLayout(dynamics_group)
self.accel_plot = CustomPlotWidget("Acceleration Profile", self)
self.steering_response_plot = CustomPlotWidget("Steering Response", self)
dynamics_layout.addWidget(self.accel_plot, 0, 0)
dynamics_layout.addWidget(self.steering_response_plot, 0, 1)
self.content_layout.addWidget(dynamics_group)
# Bottom section for track detection and system performance
analysis_group = QGroupBox("System Analysis")
analysis_layout = QGridLayout(analysis_group)
self.track_detection_plot = CustomPlotWidget("Track Detection Confidence", self)
self.power_efficiency_plot = CustomPlotWidget("Power Efficiency", self)
analysis_layout.addWidget(self.track_detection_plot, 0, 0)
analysis_layout.addWidget(self.power_efficiency_plot, 0, 1)
self.content_layout.addWidget(analysis_group)
# Initialize data storage for analysis
self.lap_times = []
self.speed_data = []
self.last_lap_start = None
def update_display(self, sensor_data):
"""Update performance analysis displays"""
if not sensor_data:
return
# Update lap timing if we detect a lap completion
# This is a simplified example - you'll need to implement actual lap detection
if self._check_lap_completion(sensor_data):
if self.last_lap_start is not None:
lap_time = sensor_data.timestamp - self.last_lap_start
self.lap_times.append(lap_time)
# Update lap time plot
self.lap_time_plot.plot(
range(len(self.lap_times)),
self.lap_times,
pen='b',
symbol='o',
clear=True
)
self.last_lap_start = sensor_data.timestamp
# Update speed profile
self.speed_profile_plot.plot(
[sensor_data.timestamp],
[sensor_data.speed],
pen='g',
clear=True
)
# Calculate acceleration from speed changes
if len(self.speed_data) > 1:
dt = sensor_data.timestamp - self.speed_data[-1][0]
dv = sensor_data.speed - self.speed_data[-1][1]
acceleration = dv / dt if dt > 0 else 0
self.accel_plot.plot(
[sensor_data.timestamp],
[acceleration],
pen='r',
clear=True
)
self.speed_data.append((sensor_data.timestamp, sensor_data.speed))
# Update steering response plot
self.steering_response_plot.plot(
[sensor_data.timestamp],
[sensor_data.steering_angle],
pen='y',
clear=True
)
# Update track detection confidence
self.track_detection_plot.plot(
[sensor_data.timestamp],
[sensor_data.track_confidence],
pen='c',
clear=True
)
# Calculate and plot power efficiency
power_efficiency = (sensor_data.speed * 100) / max(0.1, sensor_data.battery_power)
self.power_efficiency_plot.plot(
[sensor_data.timestamp],
[power_efficiency],
pen='m',
clear=True
)
def _check_lap_completion(self, sensor_data):
"""Detect if a lap has been completed based on position and heading"""
# This is a placeholder - implement actual lap detection logic
# Could use position near start/finish line and correct heading
return False
class DebugConsoleTab(TabWidget):
"""Tab for technical debugging and detailed system information"""
def setup_ui(self):
# Create split view for log display and control panel
content_split = QHBoxLayout()
self.content_layout.addLayout(content_split)
# Left side - Log display and filtering
log_panel = QVBoxLayout()
# Filter controls
filter_group = QGroupBox("Log Filters")
filter_layout = QHBoxLayout(filter_group)
self.filter_input = QLineEdit()
self.filter_input.setPlaceholderText("Filter logs...")
self.filter_input.textChanged.connect(self._apply_filter)
self.level_combo = QComboBox()
self.level_combo.addItems(["All", "Info", "Warning", "Error"])
self.level_combo.currentTextChanged.connect(self._apply_filter)
filter_layout.addWidget(self.filter_input)
filter_layout.addWidget(self.level_combo)
# Log display
self.log_text = QTextEdit()
self.log_text.setReadOnly(True)
self.log_text.setLineWrapMode(QTextEdit.NoWrap)
log_panel_widget = QWidget()
log_panel_widget.setLayout(log_panel)
log_panel.addWidget(filter_group)
log_panel.addWidget(self.log_text)
# Right side - System state and controls
state_panel = QVBoxLayout()
# PID state visualization
pid_group = QGroupBox("PID Controllers")
pid_layout = QGridLayout(pid_group)
self.pid_displays = {}
pid_names = ["Speed", "Steering", "Stability"]
for i, name in enumerate(pid_names):
display = QLabel()
display.setStyleSheet("border: 1px solid gray; padding: 5px;")
self.pid_displays[name] = display
pid_layout.addWidget(QLabel(f"{name}:"), i, 0)
pid_layout.addWidget(display, i, 1)
# Control mode display
mode_group = QGroupBox("Control Mode")
mode_layout = QVBoxLayout(mode_group)
self.mode_label = QLabel()
mode_layout.addWidget(self.mode_label)
# Error counter display
error_group = QGroupBox("Error Counters")
error_layout = QGridLayout(error_group)
self.error_counters = {}
error_types = ["CAN", "Sensor", "Control", "System"]
for i, error_type in enumerate(error_types):
counter = QLabel("0")
counter.setStyleSheet("color: red;")
self.error_counters[error_type] = counter
error_layout.addWidget(QLabel(f"{error_type}:"), i, 0)
error_layout.addWidget(counter, i, 1)
state_panel_widget = QWidget()
state_panel_widget.setLayout(state_panel)
state_panel.addWidget(pid_group)
state_panel.addWidget(mode_group)
state_panel.addWidget(error_group)
# Add panels to content split
content_split.addWidget(log_panel_widget, stretch=2)
content_split.addWidget(state_panel_widget, stretch=1)
# Initialize log buffer and counters
self.log_buffer = []
self.error_counts = {error_type: 0 for error_type in error_types}
def update_display(self, sensor_data):
"""Update debug information display"""
if not sensor_data:
return
# Update PID state displays
pid_state = sensor_data.system_health.pid_state
for name, display in self.pid_displays.items():
# Extract relevant bits for each PID controller
# This is a placeholder - implement actual bit parsing
state = "Active" if pid_state & 1 else "Inactive"
display.setText(state)
pid_state >>= 1
# Update control mode
mode_names = {
0: "Manual",
1: "Autonomous",
2: "Safety",
3: "Calibration"
}
mode = mode_names.get(sensor_data.system_health.control_mode, "Unknown")
self.mode_label.setText(f"Mode: {mode}")
# Log any new errors or warnings
self._check_and_log_errors(sensor_data)
def _check_and_log_errors(self, sensor_data):
"""Check for and log any error conditions"""
timestamp = datetime.fromtimestamp(sensor_data.timestamp).strftime('%H:%M:%S.%f')[:-3]
# Check various error conditions
if sensor_data.error_flags:
self._add_log(f"{timestamp} [ERROR] System error flags: {sensor_data.error_flags}", "Error")
self.error_counts["System"] += 1
if any(err > 0 for err in sensor_data.system_health.can_errors):
self._add_log(f"{timestamp} [ERROR] CAN bus errors detected", "Error")
self.error_counts["CAN"] += 1
# Update error counter displays
for error_type, count in self.error_counts.items():
self.error_counters[error_type].setText(str(count))
def _add_log(self, message: str, level: str):
"""Add a message to the log buffer"""
self.log_buffer.append((level, message))
if len(self.log_buffer) > 1000: # Limit buffer size
self.log_buffer.pop(0)
self._apply_filter()
def _apply_filter(self):
"""Apply current filters to log display"""
filter_text = self.filter_input.text().lower()
level_filter = self.level_combo.currentText()
filtered_logs = []
for level, message in self.log_buffer:
if level_filter != "All" and level != level_filter:
continue
if filter_text and filter_text not in message.lower():
continue
filtered_logs.append(message)
self.log_text.setText("\n".join(filtered_logs))
# Scroll to bottom
scrollbar = self.log_text.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
class MainWindow(QMainWindow):
def __init__(self, config_manager, data_handler=None, track_visualizer=None):
"""Initialize the main window with all necessary components."""
super().__init__()
# Set up logging first
self.logger = logging.getLogger('race_ground_station.gui')
self.logger.debug("Initializing MainWindow")
# Store configuration and components
self.config = config_manager
self.data_handler = data_handler
self.track_visualizer = track_visualizer
# Initialize plot manager
self.plot_manager = PlotManager(self)
# Initialize UI
self.setup_window()
self.create_tabs()
self.setup_toolbar()
self.setup_statusbar()
# Initialize timers
self.setup_timers()
# Connect signals LAST after everything is set up
self.connect_signals()
self.logger.debug("MainWindow initialization complete")
def create_tabs(self):
"""Create application tabs with new plotting widgets"""
self.tabs = {}
# Create tab container
self.tab_widget = QTabWidget(self)
self.setCentralWidget(self.tab_widget)
# Create specialized plotting widgets
self.tabs['race'] = LivePlotWidget(self.plot_manager, self)
self.tabs['track'] = TrackVisualizerWidget(self.plot_manager, self)
self.tabs['health'] = SystemHealthTab(self.config, self.plot_manager, self)
self.tabs['performance'] = PerformanceTab(self.config, self.plot_manager, self)
self.tabs['debug'] = DebugConsoleTab(self.config, self)
# Add tabs
self.tab_widget.addTab(self.tabs['race'], "Race View")
self.tab_widget.addTab(self.tabs['track'], "Track View")
self.tab_widget.addTab(self.tabs['health'], "System Health")
self.tab_widget.addTab(self.tabs['performance'], "Performance")
self.tab_widget.addTab(self.tabs['debug'], "Debug Console")
def connect_signals(self):
"""Connect all signals between components"""
# Data handler signals
self.data_handler.data_ready.connect(self.handle_new_data)
self.data_handler.error_occurred.connect(self.handle_error)
self.data_handler.connection_status.connect(self.update_connection_status)
self.data_handler.playback_finished.connect(self.handle_playback_finished)
# Plot manager signals
self.plot_manager.error_occurred.connect(self.handle_error)
# Track visualizer signals
if self.track_visualizer:
self.track_visualizer.error_occurred.connect(self.handle_error)
self.logger.debug("Signal connections established")
def closeEvent(self, event):
"""Handle application shutdown with proper thread cleanup"""
self.logger.debug("Starting MainWindow cleanup")
try:
# Stop all timers first
if hasattr(self, 'update_timer'):
self.logger.debug("Stopping update timer")
self.update_timer.stop()
if hasattr(self, 'status_timer'):
self.logger.debug("Stopping status timer")
self.status_timer.stop()
# Stop data handler and wait for threads
if hasattr(self, 'data_handler'):
self.logger.debug("Stopping data handler")
self.data_handler.stop()
# Give threads time to stop
QThread.msleep(100)
# Clean up plot manager
if hasattr(self, 'plot_manager'):
self.logger.debug("Cleaning up plot manager")
self.plot_manager.cleanup()
# Clean up tab widgets
if hasattr(self, 'tabs'):
self.logger.debug("Cleaning up tabs")
for tab in self.tabs.values():
if hasattr(tab, 'cleanup'):
tab.cleanup()
# Save configuration
self.logger.debug("Saving configuration")
self.config.save_config()
self.logger.info("MainWindow cleanup completed successfully")
event.accept()
except Exception as e:
self.logger.error(f"Error during cleanup: {str(e)}")
event.accept() # Accept anyway to ensure application can close
def handle_new_data(self, sensor_data):
"""Process new sensor data updates"""
try:
# Update all active tabs
if hasattr(self, 'tabs'):
# Update current tab
current_tab = self.tab_widget.currentWidget()
if hasattr(current_tab, 'update_display'):
current_tab.update_display(sensor_data)
# Update status bar with latest data
self.update_status_bar(sensor_data)
except Exception as e:
self.handle_error(f"Error handling new data: {str(e)}")
def setup_timers(self):
"""Configure update timers"""
# Status update timer
self.status_timer = QTimer(self)
self.status_timer.timeout.connect(self.check_status)
self.status_timer.start(1000) # Check status every second
def update_displays(self):
"""Update all display elements with current data"""
try:
current_tab = self.central_widget.currentWidget()
latest_data = self.data_handler.get_latest_data()
if latest_data:
# Update current tab
if hasattr(current_tab, 'update_display'):
current_tab.update_display(latest_data)
# Update track visualizer
self.track_visualizer.update_vehicle_state(latest_data)
# Always update status bar
self.update_status_bar(latest_data)
except Exception as e:
self.handle_error(f"Error updating displays: {str(e)}")
def calculate_metrics(self):
"""Calculate and update performance metrics"""
try:
latest_data = self.data_handler.get_latest_data()
if not latest_data:
return
# Get raw data from buffers
speed_values = self.data_handler.get_buffer_data('speed')[1]
accel_values = self.data_handler.get_buffer_data('accel_y')[1]
# Calculate metrics
metrics = {