-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2148 lines (1821 loc) · 92.1 KB
/
Copy pathmain.py
File metadata and controls
2148 lines (1821 loc) · 92.1 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 shutil
import customtkinter as ctk
import multiprocessing.shared_memory as sm
from tkinter import Canvas, Frame, Scrollbar, filedialog
from PIL import Image, ImageTk, ImageOps
import webbrowser
import subprocess
import mss
import matplotlib.animation as animation
from pathlib import Path
import joblib
from tkinter import StringVar
import cv2
import queue
import time
import struct
import csv
from collections import defaultdict
from threading import Thread
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pandas as pd
import seaborn as sns
from tkinter import ttk
import matplotlib.ticker as ticker
import datetime
import tkinter as tk
import subprocess
import queue
import traceback
import threading
import sys
import os
import filecmp
import threading
import cairosvg
import xml.etree.ElementTree as ET
from tkinter import messagebox
from PIL import Image, ImageTk
# lps22
import board
import busio
import adafruit_lps2x
import warnings
warnings.filterwarnings(
"ignore",
message="X does not have valid feature names, but StandardScaler was fitted with feature names",
category=UserWarning
)
import numpy as np
# Sensor import
from PressureSensorReader import PressureReceiver
from ValveController import ValveController
from clamp_motor import MotorController
from calibrate_page import CalibratePage
from valve_control_dropdown import ValveControlDropdown
from joblib import load
from calibrating_pressure_transducers.getCalibrationData import PressureCalibrator
from settings_page import SettingsPage
import os
os.environ["DISPLAY"] = ":0"
class ProtocolViewer(ctk.CTkFrame):
def __init__(self, master, protocol_folder, protocol_var, app, *args, **kwargs):
super().__init__(master, *args, **kwargs)
self.app = app
self.protocol_folder = protocol_folder
self.protocol_var = protocol_var
self.protocol_steps = [] # List of parsed protocol steps
self.step_widgets = [] # References to step widgets for updating
# opacity
self.scrollable_frame = ctk.CTkScrollableFrame(self, width=400, height=800)
self.scrollable_frame.pack(fill="both", expand=True)
# Dynamically update current step opacity
self.update_current_step()
def load_protocol(self, protocol_var):
# Clear existing steps
for widget in self.scrollable_frame.winfo_children():
widget.destroy()
self.step_widgets = []
self.protocol_steps = []
print("Loading protocolh:", protocol_var)
# Get the protocol path
protocol_path = os.path.join(self.protocol_folder, protocol_var)
# Read and parse the protocol
if os.path.exists(protocol_path):
with open(protocol_path, "r") as f:
lines = f.readlines()
for i, line in enumerate(lines):
step_num = i + 1
step_details = self.parse_step(line.strip())
self.protocol_steps.append((step_num, *step_details))
self.create_step_widget(step_num, *step_details)
def parse_step(self, line):
"""Parse a protocol step from the line."""
if ":" in line:
step_name, details = line.split(":", 1)
else:
step_name, details = line, ""
return step_name, details.strip()
def create_step_widget(self, step_num, step_name, details):
"""Create a rounded box for a protocol step."""
frame = ctk.CTkFrame(self.scrollable_frame, corner_radius=10, fg_color="transparent")
frame.pack(fill="x", padx=5, pady=5)
# Step number
step_num_label = ctk.CTkLabel(frame, text=f"Step {step_num}", width=10, text_color=("black", "white"))
step_num_label.grid(row=0, column=0, padx=5, pady=5)
# Step name and details
step_name_label = ctk.CTkLabel(frame, text=f"{step_name}: {details}", anchor="w", text_color=("black", "white"))
step_name_label.grid(row=0, column=1, sticky="w", padx=5, pady=5)
# Checkbox
checkbox_var = ctk.BooleanVar(value=True)
checkbox = ctk.CTkCheckBox(
frame,
text="",
variable=checkbox_var
)
# TODO: Add a command for there to be an effect with the check box
checkbox.grid(row=0, column=2, padx=5, pady=5)
self.step_widgets.append((frame, step_num))
def update_current_step(self):
"""Update opacity dynamically based on the current step."""
try:
current_step = self.app.protocol_step
current_step = int(current_step) if current_step else None
except (ValueError, TypeError):
current_step = None
# Update frame background color to simulate opacity
for frame, step_num in self.step_widgets:
if current_step == step_num:
frame.configure(fg_color="lightblue") # Simulate higher opacity
else:
frame.configure(fg_color="lightgray") # Simulate lower opacity
self.after(500, self.update_current_step) # Check every 500ms
def read_settings():
settings = {}
if os.path.exists("settings.txt"):
with open("settings.txt", "r") as file:
for line in file:
line = line.strip()
if line and "=" in line:
key, value = line.split("=", 1)
settings[key.strip()] = value.strip()
return settings
def load_default_settings(app=None):
"""
Copies default_settings.txt to settings.txt and, if an app instance is provided,
updates the app's settings attributes with the defaults.
"""
try:
shutil.copy("default_settings.txt", "settings.txt")
print("Default settings loaded.")
# Read the defaults from the settings file
default_settings = read_settings()
if app is not None:
# Update boolean setting (convert string to bool)
app.no_cap = default_settings.get("no_cap", "False").lower() in ("true", "1", "yes")
# Update tuple setting (using eval to convert string to tuple)
try:
app.graph_y_range = eval(default_settings.get("graph_y_range", str(app.graph_y_range)))
except Exception as e:
print("Error evaluating graph_y_range:", e)
# Update integer setting
try:
app.graph_time_range = int(default_settings.get("graph_time_range", app.graph_time_range))
except Exception as e:
print("Error parsing graph_time_range:", e)
# Update string setting
app.accent_color = default_settings.get("accent_color", app.accent_color)
print("App settings updated with defaults.")
except Exception as e:
print("Error copying default settings:", e)
def save_graph_animation(recorded_times, recorded_input_pressures, recorded_pressure1s, recorded_pressure2s,
file_name="graph_recording.mp4"):
"""
Create and save a matplotlib animation from recorded graph data.
"""
fig, ax = plt.subplots(figsize=(6, 4))
ax.set_xlabel("Time (s)")
ax.set_ylabel("PSI")
# Initialize empty line objects
line_input, = ax.plot([], [], label="Input Pressure")
line_pressure1, = ax.plot([], [], label="Pressure 1")
line_pressure2, = ax.plot([], [], label="Pressure 2")
ax.legend()
# Set x- and y-limits (if data is available)
if recorded_times:
ax.set_xlim(min(recorded_times), max(recorded_times))
ymin = min(min(recorded_input_pressures), min(recorded_pressure1s), min(recorded_pressure2s))
ymax = max(max(recorded_input_pressures), max(recorded_pressure1s), max(recorded_pressure2s))
ax.set_ylim(ymin, ymax)
def update(frame):
# frame is the current index (from 0 to len(recorded_times)-1)
t = recorded_times[:frame + 1]
ip = recorded_input_pressures[:frame + 1]
p1 = recorded_pressure1s[:frame + 1]
p2 = recorded_pressure2s[:frame + 1]
line_input.set_data(t, ip)
line_pressure1.set_data(t, p1)
line_pressure2.set_data(t, p2)
return line_input, line_pressure1, line_pressure2
ani = animation.FuncAnimation(fig, update, frames=len(recorded_times), blit=True, interval=30)
writer = animation.writers['ffmpeg'](fps=30, metadata=dict(artist='YourName'), bitrate=1800)
ani.save(file_name, writer=writer)
plt.close(fig)
print(f"Animation saved as {file_name}")
class App(ctk.CTk):
def __init__(self):
super().__init__() # Initialize the parent class
self.last_graph_update = 0
self.splash_canvas = None
self.graph_y_range = None
self.no_cap = None
self.init = None
self.graph_frame = None
self.graph_frame = None
self.sampleID = None
self.running = True # Initialize the running attribute
self.stop_flag = False # Initialize the stop flag
self.distance_left = 0.0
self.distance_right = 0.0
self.selected_motor = "both"
self.graph_time_range = 30 # Default time range in seconds (can be set to 15 or 60 as needed)
ctk.set_appearance_mode("System") # Options: "System", "Dark", "Light"
self.accent_color = "blue" # Light blue color
# set default color theme
ctk.set_default_color_theme(self.accent_color)
load_default_settings(self)
icon_path = os.path.abspath('./img/ratfav.ico')
png_icon_path = os.path.abspath('./img/ratfav.png')
try:
img = Image.open(icon_path)
img.save(png_icon_path)
self.icon_img = ImageTk.PhotoImage(file=png_icon_path)
self.iconphoto(False, self.icon_img)
except Exception as e:
print(f"Failed to set icon: {e}")
self.show_boot_animation()
# Window configuration
self.title("MeshAlyzer")
self.resizable(False, False)
# Calculate the center of the screen
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
x_coordinate = (screen_width // 2) - (1800 // 2)
y_coordinate = (screen_height // 2) - (920 // 2)
self.geometry(f"1800x920+{x_coordinate}+{y_coordinate}")
# Protocol Handling dictionary inti
self.data_dict = {}
self.protocol_step = None
self.target_pressure = None
self.protocol_command = None
self.target_time = None
self.protocol_running = False # Flag to indicate if the protocol is running
self.total_steps = 0
self.moving_steps_total = 0
self.graph_times = []
self.graph_input_pressures = []
self.graph_pressure1s = []
self.graph_pressure2s = []
self.previous_values = {}
# Initialize PressureReceiver
self.pressure_receiver = PressureReceiver()
self.pressure_thread = threading.Thread(target=self.pressure_receiver.run, daemon=True)
self.pressure_thread.start()
## clamp state
self.clamp_state = None
self.clamp_state = False # or True, depending on your system
# --------------------------
# input/output init
# --------------------------
self.valve1 = ValveController(supply_pins=[20], vent_pins=[27])
self.valve2 = ValveController(supply_pins=[12], vent_pins=[24])
self.i2c = busio.I2C(board.SCL, board.SDA)
self.lps = adafruit_lps2x.LPS22(self.i2c)
# self.lps.pressure
# self.lps.temperature
# --------------------------
# Top Navigation Bar Section
# --------------------------
self.nav_frame = ctk.CTkFrame(self, fg_color="transparent")
self.nav_frame.pack(fill="x", pady=5)
# Left frame for the logo
self.nav_left_frame = ctk.CTkFrame(self.nav_frame, fg_color="transparent")
self.nav_left_frame.pack(side="left")
# Right frame for nav buttons
self.nav_right_frame = ctk.CTkFrame(self.nav_frame, fg_color="transparent")
self.nav_right_frame.pack(side="right", padx=20)
self.data_recording = False
self.recorded_graph_times = []
self.recorded_input_pressures = []
self.recorded_pressure1s = []
self.recorded_pressure2s = []
# --- Logo on Left Side ---
# Create a white icon from the SVG file
icon_size = (20, 20)
# Create CTkImage for the first logo (lake logo)
logo_image = ctk.CTkImage(
light_image=Image.open("./img/lakelogo_dark.png"), # For light mode
dark_image=Image.open("./img/lakelogo.png"), # For dark mode
size=(60, 60)
)
# Create the first CTkButton with the lake logo
self.logo_button = ctk.CTkButton(
self.nav_left_frame,
image=logo_image,
text="",
fg_color="transparent",
hover_color="gray",
command=self.show_home
)
self.logo_button.pack(side="left", padx=1)
high_res_mesh_logo_dark = Image.open("./img/meshlogo_dark.png")
high_res_mesh_logo = Image.open("./img/meshlogo.png")
# Resize it to the target dimensions using a high-quality filter
high_res_mesh_logo_dark = high_res_mesh_logo_dark.resize((80, 60), Image.LANCZOS)
resized_mesh_logo = high_res_mesh_logo.resize((80, 60), Image.LANCZOS)
# Create CTkImage for the second logo (mesh logo)
mesh_logo_image = ctk.CTkImage(
light_image=high_res_mesh_logo_dark, # Use same image for both modes, or adjust if needed
dark_image=resized_mesh_logo,
size=(80, 60)
)
# Create a second CTkButton with the mesh logo
self.mesh_logo_button = ctk.CTkButton(
self.nav_left_frame,
image=mesh_logo_image,
text="",
hover_color="gray",
fg_color="transparent",
command=self.open_twitter # Updated command
)
self.mesh_logo_button.pack(side="left", padx=1)
# Load the PNG images
home_icon_image = Image.open("./img/fa-home.png")
protocol_icon_image = Image.open("./img/fa-tools.png")
calibrate_icon_image = Image.open("./img/fa-tachometer-alt.png")
settings_icon_image = Image.open("./img/fa-cog.png")
# Create CTkImage objects
home_icon = ctk.CTkImage(
light_image=Image.open("./img/fa-home_dark.png"),
dark_image=Image.open("./img/fa-home.png"),
size=(20, 20)
)
protocol_icon = ctk.CTkImage(
light_image=Image.open("./img/fa-tools_dark.png"),
dark_image=Image.open("./img/fa-tools.png"),
size=(20, 20)
)
calibrate_icon = ctk.CTkImage(
light_image=Image.open("./img/fa-tachometer-alt_dark.png"),
dark_image=Image.open("./img/fa-tachometer-alt.png"),
size=(20, 20)
)
settings_icon = ctk.CTkImage(
light_image=Image.open("./img/fa-cog_dark.png"),
dark_image=Image.open("./img/fa-cog.png"),
size=(20, 20)
)
# --- Navigation Buttons on Right Side ---
self.settings_button = ctk.CTkButton(
self.nav_right_frame,
text="Settings",
text_color="white",
image=settings_icon,
compound="left",
fg_color="transparent",
hover_color="gray",
command=self.show_settings
)
self.settings_button.pack(side="right", padx=20)
self.inspector_button = ctk.CTkButton(
self.nav_right_frame,
text="Calibrate",
text_color="white",
image=calibrate_icon,
compound="left",
fg_color="transparent",
hover_color="gray",
command=self.show_calibrate
)
self.inspector_button.pack(side="right", padx=20)
self.protocol_builder_button = ctk.CTkButton(
self.nav_right_frame,
text="Protocol Builder",
image=protocol_icon,
text_color="white",
compound="left",
fg_color="transparent",
hover_color="gray",
command=self.show_protocol_builder
)
self.protocol_builder_button.pack(side="right", padx=20)
self.home_button = ctk.CTkButton(
self.nav_right_frame,
text="Home",
image=home_icon,
text_color="white",
compound="left",
fg_color="transparent",
hover_color="gray",
command=self.show_home
)
self.home_button.pack(side="right", padx=20)
# --------------------------
# Main Content Frame
# --------------------------
self.content_frame = ctk.CTkFrame(self, fg_color="transparent")
self.content_frame.pack(expand=True, fill="both", pady=10)
self.home_frame = None
self.protocol_builder_frame = None
self.inspector_frame = None
self.settings_frame = None
# set up readvalues
self.sensor_data = []
self.calibrator = PressureCalibrator()
self.calibrator.models = load('calibrating_pressure_transducers/trained_pressure_calibrator_multioutput.joblib')
# Start the sensor reading in a separate daemon thread
self.update_queue = queue.Queue()
self.sensor_thread = threading.Thread(target=self.read_sensors, daemon=True)
self.sensor_thread.start()
self.process_queue()
## apperance defults
self.darkmodeToggle = False
if self.darkmodeToggle:
# Light/dark mode automatic toggle
current_hour = datetime.datetime.now().hour
default_mode = "Dark" if current_hour >= 18 or current_hour < 6 else "Light"
ctk.set_appearance_mode(default_mode)
else:
ctk.set_appearance_mode("Dark")
# clampmotor setup
try:
self.motor_controller = MotorController(port="/dev/ttyACM0", baudrate=9600)
except Exception as e:
print(f"Failed to initialize MotorController: {e}")
# Variables to track button hold state
self.motor_forward_pressed = False
self.motor_forward_active = False
self.motor_reverse_pressed = False
self.motor_reverse_active = False
import joblib, pathlib
base = pathlib.Path(__file__).parent
try:
self.inflation_model = joblib.load(base / "inflation_time_model.pkl")
print("Loaded inflation_time_model.pkl")
except Exception as e:
print("inflation model load failed:", e)
self.inflation_model = None
try:
self.deflation_model = joblib.load(base / "deflation_time_model.pkl")
print("Loaded deflation_time_model.pkl")
except Exception as e:
print("deflation model load failed:", e)
self.deflation_model = None
self.peak_pressure: float = 1.4 # psi
self.avg_IAP: float = 0.12 # psi
# Initialize the home display
self.show_home()
self.protocol_viewer.load_protocol(self.protocol_var.get())
def show_boot_animation(self):
# Remove title bar for splash screen effect
self.overrideredirect(True)
# Set the desired window size (720p video dimensions)
window_width = 854
window_height = 480
# Calculate the center of the screen
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
x_coordinate = (screen_width // 2) - (window_width // 2)
y_coordinate = (screen_height // 2) - (window_height // 2)
# Position the window at the center of the screen
self.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")
# Create a canvas for video and text overlay
canvas = Canvas(self, bg="black", highlightthickness=0)
canvas.pack(expand=True, fill="both")
# Variable for overlay text
setup_status = StringVar()
setup_status.set("")
# Function to play video
def play_video():
video_path = "./img/MeshAlyzer_.mp4"
video = cv2.VideoCapture(video_path)
setup_steps = [
("", 4),
("", 2),
("", 4),
("", 6),
]
current_step_index = 0
next_step_time = setup_steps[current_step_index][1]
start_time = time.time()
while video.isOpened():
ret, frame = video.read()
if not ret:
break
# Convert frame to ImageTk format
image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
image = ImageTk.PhotoImage(image)
# Display video frame on the canvas
canvas.create_image(0, 0, anchor="nw", image=image)
canvas.image = image # Keep a reference to avoid garbage collection
# Update overlay text based on time
elapsed_time = time.time() - start_time
if current_step_index < len(setup_steps) and elapsed_time >= next_step_time:
setup_status.set(setup_steps[current_step_index][0])
current_step_index += 1
if current_step_index < len(setup_steps):
next_step_time = elapsed_time + setup_steps[current_step_index][1]
# Overlay text on the canvas
canvas.delete("text")
canvas.create_text(
canvas.winfo_width() // 2,
(canvas.winfo_height() // 2) - 50,
text=setup_status.get(),
font=("Arial", 24),
fill="white",
tags="text",
)
self.update()
time.sleep(1 / video.get(cv2.CAP_PROP_FPS))
video.release()
canvas.destroy()
# Start the video playback
play_video()
self.overrideredirect(False)
def show_error_dialog(self, title, message):
"""Display a user-friendly error dialog."""
messagebox.showerror(title, message)
def update_splash_canvas(self, photo):
"""Update the splash canvas with the new video frame."""
self.splash_canvas.create_image(0, 0, anchor="nw", image=photo)
# Keep a reference to avoid garbage collection
self.splash_canvas.image = photo
def update_splash_image(self, pil_image):
"""
This method runs on the main thread.
It converts the PIL image to a PhotoImage and updates the canvas.
"""
try:
photo = ImageTk.PhotoImage(pil_image)
self.splash_canvas.create_image(0, 0, anchor="nw", image=photo)
# Keep a reference to avoid garbage collection.
self.splash_canvas.image = photo
except Exception as e:
self.show_error_dialog("Image Error", f"Failed to update image: {e}")
def play_video_thread(self):
"""Run video playback in a separate thread to keep the UI responsive."""
video_path = "./img/MeshAlyzer_.mp4"
if not os.path.exists(video_path):
self.after(0, lambda: self.show_error_dialog("Video Error", f"Video file not found:\n{video_path}"))
return
video = cv2.VideoCapture(video_path)
if not video.isOpened():
self.after(0, lambda: self.show_error_dialog("Video Error", "Unable to open video file."))
return
fps = video.get(cv2.CAP_PROP_FPS)
fps = fps if fps > 0 else 25 # Fallback if FPS is not available
delay = 1.0 / fps
while video.isOpened():
ret, frame = video.read()
if not ret:
break
# Convert the frame to RGB and then to a PIL Image.
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
pil_image = Image.fromarray(frame_rgb)
# Schedule the update of the canvas on the main thread.
self.after(0, self.update_splash_image, pil_image)
time.sleep(delay)
video.release()
# After video ends, schedule removal of the splash canvas.
self.after(0, self.splash_canvas.destroy)
def clear_content_frame(self):
for widget in self.content_frame.winfo_children():
widget.destroy()
def start_data_recording(self, duration=30):
"""
Start recording the data for a 30-second session.
"""
# Clear out any previously recorded data
self.recorded_graph_times = []
self.recorded_input_pressures = []
self.recorded_pressure1s = []
self.recorded_pressure2s = []
self.data_recording = True
self.show_overlay_notification("Data recording started")
# Schedule stop after 'duration' seconds
self.after(duration * 1000, self.stop_data_recording)
def stop_data_recording(self):
"""
Stop the recording and trigger saving the animation on a background thread.
"""
self.data_recording = False
self.show_overlay_notification("Data recording finished. Saving video...")
# Spawn a thread to avoid blocking the UI during animation rendering
threading.Thread(target=save_graph_animation,
args=(self.recorded_graph_times, self.recorded_input_pressures,
self.recorded_pressure1s, self.recorded_pressure2s, "graph_recording.mp4"),
daemon=True).start()
def open_twitter(self):
"""
Opens the MeshToTheMax Twitter page in Chromium.
"""
try:
subprocess.Popen(["chromium-browser", "https://x.com/MeshToTheMax"])
except Exception as e:
print("Failed to open Chromium browser:", e)
def update_pressure_values(self):
pressure0, pressure1, pressure2, pressure3 = PressureReceiver.getpressures()
self.pressure0 = pressure0
self.pressure1 = pressure1
self.pressure2 = pressure2
self.pressure3 = pressure3
def show_home(self):
self.clear_content_frame()
self.home_displayed = True
self.update_app_settings()
# Sidebar
self.sidebar_frame = ctk.CTkFrame(self.content_frame, width=300)
self.sidebar_frame.pack(side="left", fill="y", padx=15)
# Calibrate button
self.calibrate_button = ctk.CTkButton(self.sidebar_frame, text="Calibrate", command=self.show_calibrate)
self.calibrate_button.pack(pady=15, padx=15)
# Protocol selector
self.protocol_label = ctk.CTkLabel(self.sidebar_frame, text="Select a Protocol:")
self.protocol_label.pack(pady=15, padx=15)
self.protocol_folder = './protocols'
self.protocol_files = [f for f in os.listdir(self.protocol_folder) if
os.path.isfile(os.path.join(self.protocol_folder, f))]
self.protocol_var = ctk.StringVar(value=self.protocol_files[0])
self.protocol_dropdown = ctk.CTkComboBox(self.sidebar_frame, values=self.protocol_files,
variable=self.protocol_var)
self.protocol_dropdown.pack(pady=15)
self.run_button = ctk.CTkButton(self.sidebar_frame, text="Run Protocol", command=self.run_protocol)
self.run_button.pack(pady=15)
# Add Stop Protocol button to the sidebar
self.stop_protocol_button = ctk.CTkButton(
self.sidebar_frame,
text="Stop Protocol",
command=self.stop_protocol
)
self.stop_protocol_button.pack(pady=5)
# Motor buttons frame
motor_button_frame = ctk.CTkFrame(self.sidebar_frame, fg_color="transparent")
motor_button_frame.pack(pady=10)
# --- New: Segmented Button for Motor Control ---
self.motor_segmented_button = ctk.CTkSegmentedButton(
self.sidebar_frame,
values=["Left", "Both", "Right"],
command=self.set_motor_control
)
self.motor_segmented_button.set("Both") # Default to Both (middle option)
self.motor_segmented_button.pack(pady=5)
# --- New: Reset Buttons in Sidebar ---
self.reset_left_button_sidebar = ctk.CTkButton(
self.sidebar_frame, text="Reset Left Distance", command=self.reset_left_distance
)
self.reset_left_button_sidebar.pack(pady=5)
self.reset_right_button_sidebar = ctk.CTkButton(
self.sidebar_frame, text="Reset Right Distance", command=self.reset_right_distance
)
self.reset_right_button_sidebar.pack(pady=5)
self.motor_forward_button = ctk.CTkButton(motor_button_frame, text="Advance Motor", fg_color="transparent")
self.motor_forward_button.pack(side="left", padx=5)
self.motor_forward_button.bind("<ButtonPress-1>", self.start_motor_forward)
self.motor_forward_button.bind("<ButtonRelease-1>", self.stop_motor_forward)
self.motor_reverse_button = ctk.CTkButton(motor_button_frame, text="Reverse Motor", fg_color="transparent")
self.motor_reverse_button.pack(side="left", padx=5)
self.motor_reverse_button.bind("<ButtonPress-1>", self.start_motor_reverse)
self.motor_reverse_button.bind("<ButtonRelease-1>", self.stop_motor_reverse)
# Light/Dark mode toggle
self.mode_toggle = ctk.CTkSwitch(self.sidebar_frame, text="Dark/Light Mode", command=self.toggle_mode)
self.mode_toggle.pack(pady=15)
self.lps_info_label = ctk.CTkLabel(
self.sidebar_frame,
text="LPS: N/A | N/A",
text_color="darkgrey",
font=("Arial", 10)
)
self.lps_info_label.pack(side="bottom", pady=10, padx=10)
# add status lights below lps_info_label
# Container frame for status boxes
self.status_frame = ctk.CTkFrame(self.sidebar_frame, fg_color="transparent")
self.status_frame.pack(side="bottom", pady=10, padx=10)
# RPI Box – will check PressureReceiver status
self.rpi_box = ctk.CTkFrame(self.status_frame, width=80, height=40, corner_radius=10, fg_color="gray")
self.rpi_box.grid(row=0, column=0, padx=5)
self.rpi_label = ctk.CTkLabel(self.rpi_box, text="RPI", font=("Arial", 10, "bold"))
self.rpi_label.place(relx=0.5, rely=0.5, anchor="center")
# UNO Box – will check self.motor_controller status
self.uno_box = ctk.CTkFrame(self.status_frame, width=80, height=40, corner_radius=10, fg_color="gray")
self.uno_box.grid(row=0, column=1, padx=5)
self.uno_label = ctk.CTkLabel(self.uno_box, text="UNO", font=("Arial", 10, "bold"))
self.uno_label.place(relx=0.5, rely=0.5, anchor="center")
# BLK Box – dummy for now
self.blk_box = ctk.CTkFrame(self.status_frame, width=80, height=40, corner_radius=10, fg_color="gray")
self.blk_box.grid(row=0, column=2, padx=5)
self.blk_label = ctk.CTkLabel(self.blk_box, text="BLK", font=("Arial", 10, "bold"))
self.blk_label.place(relx=0.5, rely=0.5, anchor="center")
# Valve control dropdown
self.valve_control = ValveControlDropdown(
self.sidebar_frame,
get_pressures_func=lambda: {
"pressure0": self.pressure0_convert,
"pressure1": self.pressure1_convert,
"pressure2": self.pressure2_convert,
},
on_vent=lambda: (self.valve1.vent(), self.valve2.vent()),
on_neutral=lambda: (self.valve1.neutral(), self.valve2.neutral()),
on_supply=lambda: (self.valve1.supply(), self.valve2.supply())
)
self.valve_control.pack(pady=10)
# add a input box in the side frame that says sample ID and have that set to self.sampleID
self.sample_id_entry = ctk.CTkEntry(self.sidebar_frame, placeholder_text="Sample ID")
self.sample_id_entry.pack(pady=15, padx=15)
self.sample_id_entry.bind("<FocusOut>", self.update_sample_id)
# Main content area
self.main_frame = ctk.CTkFrame(self.content_frame, fg_color="transparent")
self.main_frame.pack(side="left", expand=True, fill="both", padx=10)
self.protocol_name_label = ctk.CTkLabel(self.main_frame, text="Current Protocol: None", anchor="w",
font=("Arial", 35, "bold"))
self.protocol_name_label.pack(pady=10, padx=20, anchor="w")
display_style = {
"width": 200,
"height": 100,
"corner_radius": 20,
"fg_color": "lightblue",
"text_color": "black",
"font": ("Arial", 45, "bold"),
}
# === Main Display Section ===
display_container = ctk.CTkFrame(self.main_frame, fg_color="transparent")
display_container.pack(pady=20)
# === Top Section: Sensor Metrics ===
sensor_section = ctk.CTkFrame(display_container, fg_color="transparent")
sensor_section.pack(pady=10)
# sensor_title = ctk.CTkLabel(sensor_section, text="Live Sensor Metrics", font=("Arial", 18, "bold"))
# sensor_title.grid(row=0, column=0, columnspan=4, pady=(0, 10))
self.time_display = ctk.CTkLabel(sensor_section, text="Time\n--:--.--", **display_style)
self.time_display.grid(row=1, column=0, padx=10, pady=5)
self.step_display = ctk.CTkLabel(sensor_section, text="Steps\nN/A", **display_style)
self.step_display.grid(row=1, column=1, padx=10, pady=5)
self.angle_display = ctk.CTkLabel(sensor_section, text="Angle\nN/A°", **display_style)
self.angle_display.grid(row=1, column=2, padx=10, pady=5)
self.force_display_frame = ctk.CTkLabel(sensor_section, text="Force\n-- | --", **display_style)
self.force_display_frame.grid(row=1, column=3, padx=10, pady=5)
# === Bottom Section: System Info ===
system_section = ctk.CTkFrame(display_container, fg_color="transparent")
system_section.pack(pady=10)
# system_title = ctk.CTkLabel(system_section, text="Protocol & System Info", font=("Arial", 18, "bold"))
# system_title.grid(row=0, column=0, columnspan=4, pady=(0, 10))
self.protocol_step_counter = ctk.CTkLabel(system_section, text="Protocol\nStep N/A", **display_style)
self.protocol_step_counter.grid(row=1, column=0, padx=10, pady=5)
self.valve_display = ctk.CTkLabel(system_section, text="Valves\nN/A", **display_style)
self.valve_display.grid(row=1, column=1, padx=10, pady=5)
self.left_distance_label = ctk.CTkLabel(system_section, text="Left\n0.00 mm", **display_style)
self.left_distance_label.grid(row=1, column=2, padx=10, pady=5)
self.right_distance_label = ctk.CTkLabel(system_section, text="Right\n0.00 mm", **display_style)
self.right_distance_label.grid(row=1, column=3, padx=10, pady=5)
# make transparent graph here
# === ADD TRANSPARENT GRAPH BELOW THE DISPLAYS ===
if self.graph_frame is not None and self.graph_frame.winfo_exists():
for widget in self.graph_frame.winfo_children():
widget.destroy()
self.graph_frame = ctk.CTkFrame(self.main_frame, fg_color="transparent")
self.graph_frame.pack(pady=10, padx=20, fill="both", expand=True)
self.fig, self.ax = plt.subplots(figsize=(6, 4)) # Adjust the figure size as needed
self.canvas = FigureCanvasTkAgg(self.fig, master=self.graph_frame)
self.canvas_widget = self.canvas.get_tk_widget()
self.canvas_widget.pack(expand=True, fill="both")
# === END GRAPH SETUP ===
# Add a "Clear Graph" button underneath the graph
self.clear_graph_button = ctk.CTkButton(
self.main_frame,
text="Clear Graph",
command=self.clear_graph_data
)
self.clear_graph_button.pack(pady=(0, 10))
# Initialize ProtocolViewer and start queue processing
self.initialize_protocol_viewer()
self.protocol_viewer.load_protocol(self.protocol_var.get())
self.process_queue()
self.record_data_button = ctk.CTkButton(
self.sidebar_frame,
text="Record 30-sec Data",
command=lambda: self.start_data_recording(30)
)
self.record_data_button.pack(pady=10)
def run_protocol(self):
if self.protocol_running:
print("Protocol is already running.")
return
protocol_name = self.protocol_var.get()
self.stop_flag = False # reset stop-flag
self.protocol_running = True
self.protocol_name_current = protocol_name
# Start the protocol in a separate thread
self.protocol_name_current = self.protocol_var.get()
threading.Thread(target=self.process_protocol,
args=(self.protocol_var.get(),),
daemon=True).start()
self.show_overlay_notification("Protocol started")
print(f"Running Protocol: {protocol_name}")
def update_sample_id(self, event):
self.sampleID = self.sample_id_entry.get()
def initialize_protocol_viewer(self):
# Initialize ProtocolViewer directly
self.protocol_viewer = ProtocolViewer(
self.main_frame,
protocol_folder=self.protocol_folder,
protocol_var=self.protocol_var,
app=self
)
self.protocol_viewer.pack(fill="both", expand=True, pady=10)
self.protocol_viewer.load_protocol(self.protocol_var.get())
# Trace for protocol_var to update ProtocolViewer when protocol changes
self.protocol_var.trace("w", self.update_protocol_viewer)
def update_protocol_viewer(self, *args):
# Update the protocol viewer synchronously when protocol_var changes
protocol_name = self.protocol_var.get()
protocol_path = os.path.join(self.protocol_folder, protocol_name)
if not protocol_name or not os.path.isfile(protocol_path):
return # ignore blanks or directories
self.protocol_viewer.load_protocol(protocol_name)
print(f"Updating ProtocolViewer with: {protocol_name}") # Debug print
self.protocol_viewer.load_protocol(self.protocol_var.get())
def show_protocol_builder(self):
self.home_displayed = False # Set to False to indicate home is not displayed
"""Display the protocol builder page with a sidebar and main content area."""