-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobd2_gui.py
More file actions
2346 lines (1927 loc) · 96.5 KB
/
robd2_gui.py
File metadata and controls
2346 lines (1927 loc) · 96.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import sys
import logging
from datetime import datetime
from pathlib import Path
from typing import Optional
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import csv
import time
import threading
from data_store import DataStore
from modern_widgets import ModernFrame, ModernButton, ModernLabelFrame
from windows import ChecklistWindow, ScriptViewerWindow, LoadingIndicator
from serial_comm import SerialCommunicator
from calibration_data import CalibrationMonitor
from Performance import PerformanceMonitor
from COM_serial import DataLogger
from program_manager import ProgramManager
from performance_gui import PerformanceTab
from gas_calculator_tab import GasCalculatorTab
# Create logs directory if it doesn't exist
logs_dir = Path("logs")
logs_dir.mkdir(exist_ok=True)
# Configure comprehensive logging with both file and console handlers
def setup_logging():
"""Setup logging with both file and console handlers"""
# Create file handler for debug logs with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
file_handler = logging.FileHandler(logs_dir / f"robd2_gui_{timestamp}.log")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
))
# Create console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO) # Show INFO and above in console
console_handler.setFormatter(logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
))
# Configure root logger
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[file_handler, console_handler]
)
return file_handler
# Setup logging and get file handler reference
debug_file_handler = setup_logging()
log = logging.getLogger("robd2_gui")
# Log application startup
log.info("ROBD2 GUI Application starting up")
log.info(f"Debug logs will be saved to: {logs_dir}")
log.debug("Debug logging enabled - all debug messages will be saved to file")
class ROBD2GUI:
def __init__(self, root):
"""Initialize the GUI"""
self.root = root
self.root.title("ROBD2 Diagnostic Interface")
self.root.geometry("1200x800")
self.root.minsize(800, 600)
# Initialize scrolling management
self.active_scrollables = []
# Initialize data store
self.data_store = DataStore()
# Initialize serial communicator
self.serial_comm = SerialCommunicator()
# Create the main frame
main_frame = ModernFrame(root)
main_frame.pack(fill=tk.BOTH, expand=True)
# Create the notebook for tabs
self.notebook = ttk.Notebook(main_frame)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Create the menu bar
self.create_menu_bar()
# Create the status bar
status_frame = ttk.Frame(main_frame, relief=tk.SUNKEN)
status_frame.pack(fill=tk.X, side=tk.BOTTOM)
self.status_bar = ttk.Label(status_frame, text="Not connected", anchor=tk.W)
self.status_bar.pack(fill=tk.X, side=tk.LEFT, padx=5)
# Create tabs
self.create_gas_calculator_tab() # Add the gas calculator tab first
self.create_connection_tab()
self.create_calibration_tab()
self.create_performance_tab()
self.create_training_tab()
self.create_dashboard_tab()
self.create_diagnostics_tab()
self.create_programming_tab()
self.create_logging_tab()
# Add tab selection callback to handle starting/stopping data collection
self.notebook.bind("<<NotebookTabChanged>>", self.on_tab_changed)
# Setup keyboard shortcuts
self.add_keyboard_shortcuts()
# Flag for plotting
self.plotting_active = False
# Track the after event ID
self.poll_after_id = None
def enable_scrolling(self, widget):
"""Enable mouse wheel scrolling for a widget"""
def _on_mousewheel(event):
try:
if widget.winfo_exists():
if sys.platform.startswith('win'):
widget.yview_scroll(int(-1*(event.delta/120)), "units")
else:
if event.num == 4:
widget.yview_scroll(-1, "units")
elif event.num == 5:
widget.yview_scroll(1, "units")
except tk.TclError:
pass
if sys.platform.startswith('win'):
widget.bind_all("<MouseWheel>", _on_mousewheel)
else:
widget.bind_all("<Button-4>", _on_mousewheel)
widget.bind_all("<Button-5>", _on_mousewheel)
# Store the widget and its bindings for cleanup
self.active_scrollables.append({
'widget': widget,
'bindings': [
("<MouseWheel>", _on_mousewheel) if sys.platform.startswith('win')
else ("<Button-4>", _on_mousewheel),
("<Button-5>", _on_mousewheel)
]
})
def cleanup_scrolling(self):
"""Clean up all mouse wheel bindings"""
try:
for scrollable in self.active_scrollables:
if isinstance(scrollable, dict):
# Handle dictionary format
widget = scrollable.get('widget')
bindings = scrollable.get('bindings', [])
if widget:
for event, _ in bindings:
try:
widget.unbind_all(event)
except tk.TclError:
pass
elif isinstance(scrollable, tuple):
# Handle tuple format
event, _ = scrollable
try:
self.unbind_all(event)
except tk.TclError:
pass
self.active_scrollables.clear()
except Exception as e:
log.error(f"Error cleaning up scrolling: {e}")
def create_scrollable_frame(self, parent, **kwargs):
"""Create a scrollable frame and return both the canvas and the frame"""
canvas = tk.Canvas(parent, **kwargs)
scrollbar = ttk.Scrollbar(parent, orient="vertical", command=canvas.yview)
scrollable_frame = ModernFrame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
self.enable_scrolling(canvas)
return canvas, scrollable_frame
def create_gas_calculator_tab(self):
"""Create the gas calculator tab"""
gas_calculator_tab = GasCalculatorTab(self.notebook)
self.notebook.add(gas_calculator_tab, text="Gas Calculator")
# Add the gas calculator's scrollable widgets to our tracking
if hasattr(gas_calculator_tab, 'active_scrollables'):
self.active_scrollables.extend(gas_calculator_tab.active_scrollables)
# Bind cleanup to tab destruction
gas_calculator_tab.bind("<Destroy>", lambda e: self.cleanup_scrolling())
def create_menu_bar(self):
"""Create the menu bar"""
self.menu_bar = tk.Menu(self.root)
self.root.config(menu=self.menu_bar)
# File menu
file_menu = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Connect (Ctrl+C)", command=self.connect_to_device)
file_menu.add_command(label="Disconnect (Ctrl+D)", command=self.disconnect_device)
file_menu.add_separator()
file_menu.add_command(label="Export Data (Ctrl+E)", command=self.export_data)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.quit)
# Tools menu
tools_menu = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="Tools", menu=tools_menu)
tools_menu.add_command(label="Refresh Ports (Ctrl+R)", command=self.refresh_ports)
tools_menu.add_command(label="Start Logging (Ctrl+S)", command=self.start_logging)
tools_menu.add_command(label="Stop Logging (Ctrl+X)", command=self.stop_logging)
# Help menu
help_menu = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="Help", menu=help_menu)
help_menu.add_command(label="Documentation", command=self.show_documentation)
help_menu.add_command(label="About", command=self.show_about)
def add_keyboard_shortcuts(self):
"""Add keyboard shortcuts"""
self.root.bind('<Control-r>', lambda e: self.refresh_ports())
self.root.bind('<Control-c>', lambda e: self.connect_to_device() if not self.serial_comm.is_connected else None)
self.root.bind('<Control-d>', lambda e: self.disconnect_device() if self.serial_comm.is_connected else None)
self.root.bind('<Control-e>', lambda e: self.export_data() if hasattr(self, 'data_store') else None)
self.root.bind('<Control-s>', lambda e: self.start_logging() if self.serial_comm.is_connected else None)
self.root.bind('<Control-x>', lambda e: self.stop_logging() if hasattr(self, 'data_logger') else None)
def refresh_ports(self):
"""Refresh available COM ports"""
ports = self.serial_comm.get_available_ports()
self.port_combo['values'] = ports
if ports:
self.port_combo.set(ports[0])
def connect_to_device(self):
"""Connect to the selected COM port"""
try:
port = self.port_var.get()
if not port:
messagebox.showerror("Error", "Please select a COM port")
return
# Show loading indicator
loading = LoadingIndicator(self.root, "Connecting to device...")
self.root.update()
success, message = self.serial_comm.connect(port)
if success:
# Update UI state
self.connect_btn.configure(state=tk.DISABLED)
self.disconnect_btn.configure(state=tk.NORMAL)
self.port_combo.configure(state=tk.DISABLED)
# Enable features
self.start_calibration_btn.configure(state=tk.NORMAL)
self.start_logging_btn.configure(state=tk.NORMAL)
# Update status
self.status_bar.configure(text=f"Connected to {port}")
self.status_text.insert(tk.END, f"{datetime.now().strftime('%H:%M:%S')} - Connected to {port}\n")
# Check if dashboard tab is visible and start data collection
if self.notebook.tab(self.notebook.select(), "text") == "Dashboard":
self.start_data_collection()
else:
messagebox.showerror("Connection Error", message)
self.status_bar.configure(text="Connection Failed")
self.status_text.insert(tk.END, f"{datetime.now().strftime('%H:%M:%S')} - Connection failed: {message}\n")
# Destroy loading indicator
loading.destroy()
except Exception as e:
log.error(f"Unexpected connection error: {e}", exc_info=True)
messagebox.showerror("Error", f"An unexpected error occurred: {str(e)}")
self.status_bar.configure(text="Connection Failed")
self.status_text.insert(tk.END, f"{datetime.now().strftime('%H:%M:%S')} - Unexpected error: {str(e)}\n")
def disconnect_device(self):
"""Disconnect from the COM port"""
success, message = self.serial_comm.disconnect()
if success:
# Update UI state
self.connect_btn.configure(state=tk.NORMAL)
self.disconnect_btn.configure(state=tk.DISABLED)
self.port_combo.configure(state=tk.NORMAL)
# Disable features
self.start_calibration_btn.configure(state=tk.DISABLED)
self.start_logging_btn.configure(state=tk.DISABLED)
# Update status
self.status_bar.configure(text="Disconnected")
self.status_text.insert(tk.END, f"{datetime.now().strftime('%H:%M:%S')} - Disconnected\n")
# Stop data collection if active
self.plotting_active = False
else:
messagebox.showerror("Error", message)
def send_diagnostic_command(self, command):
"""Send a diagnostic command to the device"""
if not self.serial_comm.is_connected:
messagebox.showerror("Error", "Not connected to device")
return
success, message = self.serial_comm.send_command(command)
if success:
self.response_text.insert(tk.END, f"{datetime.now().strftime('%H:%M:%S')} → {command}\n")
else:
messagebox.showerror("Error", message)
def poll_responses(self):
"""Poll for responses from the device"""
try:
response = self.serial_comm.get_response()
if response:
self.response_text.insert(tk.END, f"{datetime.now().strftime('%H:%M:%S')} ← {response}\n")
self.response_text.see(tk.END)
except Exception as e:
log.error(f"Error polling response: {e}")
# Schedule the next poll and store the after ID (reduced frequency to 500ms)
self.poll_after_id = self.root.after(500, self.poll_responses)
def start_calibration(self):
"""Start O2 sensor calibration"""
if not self.serial_comm.is_connected:
messagebox.showerror("Error", "Not connected to device")
return
device_id = self.device_var.get()
if not device_id:
messagebox.showerror("Error", "Please select a device")
return
# Run calibration in a separate thread
def run_calibration():
monitor = CalibrationMonitor(self.serial_comm.serial_port)
monitor.device_id = device_id
# Update UI from the main thread
self.root.after(0, lambda: self.results_text.insert(tk.END, "Starting calibration...\n"))
# This is a blocking call, but it's in a separate thread
monitor.start_calibration()
# Update UI when done
self.root.after(0, lambda: self.results_text.insert(tk.END, "Calibration complete.\n"))
threading.Thread(target=run_calibration, daemon=True).start()
def start_logging(self):
"""Start flight data logging"""
if not self.serial_comm.is_connected:
messagebox.showerror("Error", "Not connected to device")
return
flight_id = self.flight_id_var.get()
if not flight_id:
messagebox.showerror("Error", "Please enter a Flight ID")
return
# Update UI state
self.start_logging_btn.configure(state=tk.DISABLED)
self.stop_logging_btn.configure(state=tk.NORMAL)
# Create logs directory if it doesn't exist
logs_dir = Path("logs")
logs_dir.mkdir(exist_ok=True)
# Create log file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
log_file = logs_dir / f"flight_{flight_id}_{timestamp}.log"
# Configure file handler
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
log.addHandler(file_handler)
# Create a custom list class for communications
class LoggingList(list):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.callback = None
def append(self, item):
super().append(item)
if self.callback:
self.callback(item)
# Run logging in a separate thread
def run_logging():
self.data_logger = DataLogger(self.serial_comm.serial_port, [])
# Create custom list for communications
self.data_logger.communications = LoggingList()
# Update the log display
def update_log(message):
self.log_text.insert(tk.END, f"{message}\n")
self.log_text.see(tk.END)
log.info(message)
# Set the callback for the custom list
self.data_logger.communications.callback = update_log
# Start logging (blocking call in the thread)
self.data_logger.start_logging(flight_id)
threading.Thread(target=run_logging, daemon=True).start()
def stop_logging(self):
"""Stop flight data logging"""
if hasattr(self, 'data_logger'):
self.data_logger.stop_logging()
self.start_logging_btn.configure(state=tk.NORMAL)
self.stop_logging_btn.configure(state=tk.DISABLED)
# Remove file handler
for handler in log.handlers[:]:
if isinstance(handler, logging.FileHandler):
handler.close()
log.removeHandler(handler)
def export_data(self):
"""Export data to CSV file"""
try:
from tkinter import filedialog
# Get filename from user
filename = filedialog.asksaveasfilename(
defaultextension=".csv",
filetypes=[("CSV files", "*.csv")],
initialdir="exports",
title="Export Data"
)
if filename:
success, result = self.data_store.export_to_csv(filename)
if success:
messagebox.showinfo("Success", f"Data exported to {result}")
else:
messagebox.showerror("Error", f"Failed to export data: {result}")
except Exception as e:
messagebox.showerror("Error", f"Failed to export data: {str(e)}")
log.error(f"Export error: {e}", exc_info=True)
def show_about(self):
"""Show the About window"""
about_window = tk.Toplevel(self.root)
about_window.title("About ROBD2 Diagnostic UI")
about_window.geometry("800x700")
# Create a canvas with scrollbar for scrolling
canvas = tk.Canvas(about_window)
scrollbar = ttk.Scrollbar(about_window, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
# Pack the canvas and scrollbar
canvas.pack(side="left", fill="both", expand=True, padx=10, pady=10)
scrollbar.pack(side="right", fill="y")
# Create main container
main_frame = ModernFrame(scrollable_frame)
main_frame.pack(fill=tk.BOTH, expand=True, padx=30, pady=20)
# Title with custom styling
title_frame = ttk.Frame(main_frame)
title_frame.pack(fill=tk.X, pady=(0, 20))
title_label = ttk.Label(
title_frame,
text="ROBD2 Diagnostic UI",
font=('Helvetica', 24, 'bold')
)
title_label.pack()
subtitle_label = ttk.Label(
title_frame,
text="Advanced Control and Analysis Interface for ROBD2 Devices",
font=('Helvetica', 12)
)
subtitle_label.pack(pady=(5, 0))
# Version with custom styling
version_frame = ttk.Frame(main_frame)
version_frame.pack(fill=tk.X, pady=(0, 20))
version_label = ttk.Label(
version_frame,
text="Version 2.0.0",
font=('Helvetica', 14, 'bold')
)
version_label.pack()
# Author information
author_frame = ModernLabelFrame(main_frame, text="Author", padding=15)
author_frame.pack(fill=tk.X, pady=(0, 20))
author_text = """
Diego Malpica MD
Aerospace Medicine Specialist
Aerospace Physiology Instructor
Aerospace Scientific Department
Aerospace Medicine Directorate
Colombian Aerospace Force
Initial work - [strikerdlm](https://github.com/strikerdlm)
Copyright © 2024 Diego Malpica MD. All rights reserved.
License: MIT License
Repository: https://github.com/strikerdlm/ROBD2_GUI
For contributing please read the CONTRIBUTING.md file in the repository.
"""
author_label = ttk.Label(
author_frame,
text=author_text,
wraplength=700,
justify=tk.CENTER,
font=('Helvetica', 11)
)
author_label.pack()
# Description
description_frame = ModernLabelFrame(main_frame, text="Overview", padding=15)
description_frame.pack(fill=tk.X, pady=(0, 20))
description_text = """
The ROBD2 Diagnostic Interface is a comprehensive tool for monitoring, calibrating, and analyzing data from ROBD2 devices. It provides real-time visualization of critical parameters, data logging capabilities, and diagnostic tools for aerospace physiology training.
This software is designed for use in controlled environments under the supervision of trained medical professionals or experts in ROBD devices for aerospace physiology training. It includes advanced features for gas calculations, performance monitoring, and training management.
"""
description_label = ttk.Label(
description_frame,
text=description_text,
wraplength=700,
justify=tk.CENTER,
font=('Helvetica', 11)
)
description_label.pack()
# Features
features_frame = ModernLabelFrame(main_frame, text="Key Features", padding=15)
features_frame.pack(fill=tk.X, pady=(0, 20))
features_text = """
• Advanced gas calculator with physiological parameters, consumption analysis, and capacity planning
• Real-time data visualization with customizable time scales
• Comprehensive data logging and export capabilities
• Device calibration tools with automated procedures
• Performance monitoring with real-time graphs
• Training session management and checklists
• Diagnostic command interface with error handling
• Modern, intuitive user interface with dark mode support
• Automatic data validation and range checking
• CSV data export with timestamps
• Multi-platform support (Windows, Linux)
"""
features_label = ttk.Label(
features_frame,
text=features_text,
wraplength=700,
justify=tk.LEFT,
font=('Helvetica', 11)
)
features_label.pack()
# Requirements
requirements_frame = ModernLabelFrame(main_frame, text="System Requirements", padding=15)
requirements_frame.pack(fill=tk.X, pady=(0, 20))
requirements_text = """
• Python 3.8 or higher
• Windows 10/11 or Linux
• Required Python packages:
- pyserial >= 3.5
- matplotlib >= 3.7
- numpy >= 1.24
- tkinter (included with Python)
- pillow >= 10.0
"""
requirements_label = ttk.Label(
requirements_frame,
text=requirements_text,
wraplength=700,
justify=tk.LEFT,
font=('Helvetica', 11)
)
requirements_label.pack()
# Add mousewheel scrolling support with error handling
def _on_mousewheel(event):
try:
if canvas.winfo_exists():
canvas.yview_scroll(int(-1*(event.delta/120)), "units")
except tk.TclError:
pass
def _on_linux_mousewheel(event):
try:
if canvas.winfo_exists():
if event.num == 4:
canvas.yview_scroll(-1, "units")
elif event.num == 5:
canvas.yview_scroll(1, "units")
except tk.TclError:
pass
# Bind mousewheel events
if sys.platform.startswith('win'):
canvas.bind_all("<MouseWheel>", _on_mousewheel)
else:
canvas.bind_all("<Button-4>", _on_linux_mousewheel)
canvas.bind_all("<Button-5>", _on_linux_mousewheel)
# Define closing function to properly unbind events
def _on_closing():
try:
canvas.unbind_all("<MouseWheel>")
canvas.unbind_all("<Button-4>")
canvas.unbind_all("<Button-5>")
except tk.TclError:
pass
about_window.destroy()
about_window.protocol("WM_DELETE_WINDOW", _on_closing)
# Center the window on the screen
about_window.update_idletasks()
width = about_window.winfo_width()
height = about_window.winfo_height()
x = (about_window.winfo_screenwidth() // 2) - (width // 2)
y = (about_window.winfo_screenheight() // 2) - (height // 2)
about_window.geometry('{}x{}+{}+{}'.format(width, height, x, y))
# Make window modal
about_window.transient(self.root)
about_window.grab_set()
self.root.wait_window(about_window)
def show_documentation(self):
"""Show the documentation window"""
doc_window = tk.Toplevel(self.root)
doc_window.title("Documentation")
doc_window.geometry("800x600")
# Create main container
main_frame = ModernFrame(doc_window)
main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
# Title
title_label = ttk.Label(
main_frame,
text="ROBD2 Diagnostic Interface Documentation",
font=('Helvetica', 16, 'bold')
)
title_label.pack(pady=(0, 20))
# Create scrollable frame for content
canvas = tk.Canvas(main_frame)
scrollbar = ttk.Scrollbar(main_frame, orient="vertical", command=canvas.yview)
scrollable_frame = ModernFrame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
# Pack scrollbar and canvas
scrollbar.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
# Add documentation content
content = """
Keyboard Shortcuts:
------------------
Ctrl+C: Connect to device
Ctrl+D: Disconnect from device
Ctrl+E: Export data
Ctrl+R: Refresh ports
Ctrl+S: Start logging
Ctrl+X: Stop logging
Connection Tab:
--------------
1. Select the COM port where the ROBD2 device is connected
2. Click "Connect" or press Ctrl+C to establish connection
3. Use the pre-flight checklist to verify device setup
Calibration Tab:
---------------
1. Select the device to calibrate
2. Follow the calibration procedure
3. Monitor results in real-time
Performance Tab:
---------------
1. Select the device to monitor
2. Start/stop performance monitoring
3. View real-time data
Training Tab:
------------
1. Access training scripts for different aircraft types
2. Use checklists during and after training
3. Follow proper procedures
Dashboard Tab:
-------------
1. View real-time plots of various parameters
2. Export data for analysis
3. Monitor statistics
Diagnostics Tab:
---------------
1. Send diagnostic commands
2. View device responses
3. Troubleshoot issues
Programming Tab:
---------------
1. Create and modify device programs
2. Add hold and change steps
3. Review program configuration
Logging Tab:
-----------
1. Start/stop data logging
2. Monitor log data
3. Export logs for analysis
For more information, please refer to the ROBD2 Technical Manual.
"""
content_label = ttk.Label(
scrollable_frame,
text=content,
wraplength=700,
justify=tk.LEFT,
font=('Helvetica', 11)
)
content_label.pack(pady=10)
# Add mousewheel scrolling support with error handling
def _on_mousewheel(event):
try:
if canvas.winfo_exists():
canvas.yview_scroll(int(-1*(event.delta/120)), "units")
except tk.TclError:
pass
def _on_linux_mousewheel(event):
try:
if canvas.winfo_exists():
if event.num == 4:
canvas.yview_scroll(-1, "units")
elif event.num == 5:
canvas.yview_scroll(1, "units")
except tk.TclError:
pass
# Bind for Windows
canvas.bind_all("<MouseWheel>", _on_mousewheel)
# Bind for Linux
canvas.bind_all("<Button-4>", _on_linux_mousewheel)
canvas.bind_all("<Button-5>", _on_linux_mousewheel)
# Unbind when window is closed
def _on_closing():
try:
canvas.unbind_all("<MouseWheel>")
canvas.unbind_all("<Button-4>")
canvas.unbind_all("<Button-5>")
except tk.TclError:
pass
doc_window.destroy()
doc_window.protocol("WM_DELETE_WINDOW", _on_closing)
# Center window on screen
doc_window.update_idletasks()
width = doc_window.winfo_width()
height = doc_window.winfo_height()
x = (doc_window.winfo_screenwidth() // 2) - (width // 2)
y = (doc_window.winfo_screenheight() // 2) - (height // 2)
doc_window.geometry(f'{width}x{height}+{x}+{y}')
def update_plots(self):
"""Update the dashboard plots with new data"""
if not self.plotting_active:
return
try:
# Get current data
time_data, altitude_data = self.data_store.get_data('altitude')
_, o2_data = self.data_store.get_data('o2_conc')
_, blp_data = self.data_store.get_data('blp')
_, spo2_data = self.data_store.get_data('spo2')
_, pulse_data = self.data_store.get_data('pulse')
# Update plot data
self.plot_data['time'] = time_data
self.plot_data['altitude'] = altitude_data
self.plot_data['o2_conc'] = o2_data
self.plot_data['blp'] = blp_data
self.plot_data['spo2'] = spo2_data
self.plot_data['pulse'] = pulse_data
# Update plot lines
self.altitude_line.set_data(time_data, altitude_data)
self.o2_line.set_data(time_data, o2_data)
self.blp_line.set_data(time_data, blp_data)
self.spo2_line.set_data(time_data, spo2_data)
self.pulse_line.set_data(time_data, pulse_data)
# Update plot limits
time_scale = float(self.time_scale_var.get())
if time_data:
self.altitude_ax.set_xlim(max(0, time_data[-1] - time_scale), max(time_data[-1], time_scale))
self.o2_ax.set_xlim(max(0, time_data[-1] - time_scale), max(time_data[-1], time_scale))
self.vitals_ax.set_xlim(max(0, time_data[-1] - time_scale), max(time_data[-1], time_scale))
# Update y-axis limits based on data
if altitude_data:
self.altitude_ax.set_ylim(0, max(35000, max(altitude_data) * 1.1))
if o2_data:
self.o2_ax.set_ylim(0, max(30, max(o2_data) * 1.1))
if spo2_data:
max_vitals = max(max(spo2_data) if spo2_data else 100,
max(pulse_data) if pulse_data else 100,
max(blp_data) if blp_data else 10)
self.vitals_ax.set_ylim(0, max_vitals * 1.1)
# Redraw canvas
self.canvas.draw()
except Exception as e:
log.error(f"Error updating plots: {e}", exc_info=True)
def create_connection_tab(self):
"""Create the connection tab"""
connection_frame = ModernFrame(self.notebook)
self.notebook.add(connection_frame, text="Connection")
# Create scrollable frame
canvas, scrollable_frame = self.create_scrollable_frame(connection_frame)
# Port selection
port_frame = ModernLabelFrame(scrollable_frame, text="Port Selection", padding=10)
port_frame.pack(fill=tk.X, padx=10, pady=5)
self.port_var = tk.StringVar()
self.port_combo = ttk.Combobox(port_frame, textvariable=self.port_var)
self.port_combo.pack(side=tk.LEFT, padx=5)
self.connect_btn = ModernButton(
port_frame,
text="Connect",
command=self.connect_to_device,
variant="primary",
)
self.connect_btn.pack(side=tk.LEFT, padx=5)
self.disconnect_btn = ModernButton(
port_frame,
text="Disconnect",
command=self.disconnect_device,
state=tk.DISABLED,
variant="danger",
)
self.disconnect_btn.pack(side=tk.LEFT, padx=5)
self.refresh_btn = ModernButton(port_frame, text="Refresh", command=self.refresh_ports)
self.refresh_btn.pack(side=tk.LEFT, padx=5)
# Status display
status_frame = ModernLabelFrame(scrollable_frame, text="Status", padding=10)
status_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
self.status_text = tk.Text(status_frame, height=10, wrap=tk.WORD)
self.status_text.pack(fill=tk.BOTH, expand=True)
# Enable scrolling for status text
status_scroll = ttk.Scrollbar(status_frame, command=self.status_text.yview)
status_scroll.pack(side=tk.RIGHT, fill=tk.Y)
self.status_text.configure(yscrollcommand=status_scroll.set)
# Pre-flight checklist
checklist_frame = ModernLabelFrame(scrollable_frame, text="Pretraining Setup", padding=10)
checklist_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
checklist_btn = ModernButton(checklist_frame, text="Open Checklist", command=lambda: ChecklistWindow(self.root, "Before Start (Daily) Checklist", [
"Verify ROBD2 system is properly unpacked and installed",
"Remove and store all packaging materials for future use",
"Confirm power connection is correct for region (115V or 230V) and securely grounded",
"Connect air (yellow) and nitrogen (black) at 40-50 PSIG to respective ports",
"Connect 100% oxygen (green) at 20 PSIG",
"Connect pilot mask to Breathing Mask Connector on front panel",
"Ensure pulse oximeter probe is connected",
"Power on system using power switch",
"Allow system warm-up time (10 minutes)",
"Start self-tests by pressing SELFTST key and follow on-screen instructions",
"Allow system to complete self-tests and auto-calibration (do not use mask during this process)",
"Record O₂ sensor voltage values at ambient concentration (~21%) and 100% O₂",
"Manually enter voltage values in ADC 12 table for Bogotá ambient air and 100% O₂",
"Activate 'Bypass Self-Tests' mode as per manual (Programming and Technical Guide – Rev 8)",
"Execute Performance Test (Profile #20 – TEST)",
"Verify O₂ mixtures are within manufacturer's specified ranges (APPENDIX M)"
]))
checklist_btn.pack(pady=5)
def create_calibration_tab(self):
"""Create the calibration tab with self-calibration functionality"""
calibration_frame = ModernFrame(self.notebook)
self.notebook.add(calibration_frame, text="Calibration")
# Create a horizontal paned window for main layout
main_paned = ttk.PanedWindow(calibration_frame, orient=tk.HORIZONTAL)
main_paned.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
# Left side - Controls and inputs
left_frame = ModernFrame(main_paned)
main_paned.add(left_frame, weight=2)
# Right side - Calibration results
right_frame = ModernFrame(main_paned)
main_paned.add(right_frame, weight=1)
# Create scrollable frame for left side
canvas, scrollable_frame = self.create_scrollable_frame(left_frame)
# Warning frame
warning_frame = ModernLabelFrame(scrollable_frame, text="Important Warnings", padding=10)
warning_frame.pack(fill=tk.X, padx=5, pady=5)
warning_text = """
Before starting calibration:
1. Enable administrative credentials on the ROBD2
2. Manually bypass the self-test if required
3. Ensure all gas connections are properly set up
4. For manual calibration, run program #20 to start the tests
"""
warning_label = ttk.Label(
warning_frame,
text=warning_text,
wraplength=500,
justify=tk.LEFT,
font=('Helvetica', 10, 'bold')
)
warning_label.pack(pady=5)
# Status indicator frame
self.calibration_status_frame = ModernLabelFrame(scrollable_frame, text="Calibration Status", padding=10)
self.calibration_status_frame.pack(fill=tk.X, padx=5, pady=5)
self.status_var = tk.StringVar(value="Ready for calibration")