-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpump_control.py
2262 lines (2128 loc) · 98 KB
/
pump_control.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
# pyserial imports
import serial
import serial.tools.list_ports
# gui imports
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import pystray
from PIL import Image
# other library
import os, re
import time
import json
import logging
import pandas as pd
from queue import Queue
from datetime import datetime, timedelta
from tkinter_helpers import (
non_blocking_messagebox,
non_blocking_custom_messagebox,
non_blocking_checklist,
non_blocking_single_select,
non_blocking_input_dialog,
)
from helper_functions import (
check_lock_file,
remove_lock_file,
resource_path,
convert_minutes_to_ns,
convert_ns_to_timestr,
process_pump_actions,
)
pico_vid = 0x2E8A # Pi Pico vendor ID
global_pad_x = 2
global_pad_y = 2
global_pad_N = 3
global_pad_S = 3
global_pad_W = 3
global_pad_E = 3
NANOSECONDS_PER_SECOND = 1_000_000_000
NANOSECONDS_PER_MILLISECOND = 1_000_000
class PicoController:
def __init__(self, master) -> None:
self.master = master
self.master.title("Pump Control via Pi Pico")
self.main_loop_interval_ms = 20 # Main loop interval in milliseconds
# port refresh timer
self.port_refresh_interval_ns = (
5 * NANOSECONDS_PER_SECOND
) # Refresh rate for COM ports when not connected
self.last_port_refresh_ns = -1
self.timeout = 1 # Serial port timeout in seconds
# instance fields for the serial port and queue
# we have multiple controller, the key is the id, the value is the serial port object
self.pump_controllers = {}
self.pump_controllers_connected = {}
# format is "controller_id: bool"
self.pump_controllers_id_to_widget_map = {}
self.pump_controllers_send_queue = Queue() # format is "controller_id:command"
self.pump_controllers_rtc_time = {}
# instance field for the autosampler serial port
self.autosamplers = None
self.autosamplers_send_queue = Queue()
self.autosamplers_rtc_time = "Autosampler Time: --:--:--"
# Dictionary to store pump information
self.pumps = {}
# a mapping from pump id to the controller id
self.pump_ids_to_controller_ids = {}
self.controller_ids_to_pump_ids = {}
# define pumps per row in the manual control frame
self.pumps_per_row = 3
# Dataframe to store the recipe
self.recipe_df = pd.DataFrame()
self.recipe_rows = []
# time stamp for the start of the procedure
self.start_time_ns = -1
self.total_procedure_time_ns = -1
self.current_index = -1
self.pause_timepoint_ns = -1
self.pause_duration_ns = 0
self.scheduled_task = None
# time stamp for the RTC time query
self.last_time_query = time.monotonic_ns()
# define window behavior
self.image_red = Image.open(
resource_path(os.path.join("icons", "icons-red.ico"))
)
self.image_white = Image.open(
resource_path(os.path.join("icons", "icons-white.ico"))
)
self.first_close = True
# Set up logging
runtime = datetime.now().strftime("%Y%m%d_%H%M%S")
try:
os.mkdir("log")
except FileExistsError:
pass
log_filename = os.path.join("log", f"pump_control_run_{runtime}.log")
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s: %(message)s [%(funcName)s]",
handlers=[logging.FileHandler(log_filename), logging.StreamHandler()],
)
self.create_widgets()
self.master.after(self.main_loop_interval_ms, self.main_loop)
def create_widgets(self):
current_row = 0
# Port selection frame
self.port_select_frame = ttk.Labelframe(
self.master,
text="Select Port",
padding=(global_pad_N, global_pad_S, global_pad_W, global_pad_E),
)
self.port_select_frame.grid(
row=current_row,
column=0,
columnspan=8,
rowspan=3,
padx=global_pad_x,
pady=global_pad_y,
sticky="NSEW",
)
# first in the port_select_frame
# Create a row for each potential pump controller
for controller_id in range(1, 4): # Assume we can have up to 3 pump controllers
self.add_pump_controller_widgets(controller_id=controller_id)
current_row = self.port_select_frame.grid_size()[1]
# second in the port_select_frame
self.port_label_as = ttk.Label(self.port_select_frame, text="Autosampler:")
self.port_label_as.grid(
row=current_row, column=0, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.port_combobox_as = ttk.Combobox(
self.port_select_frame, state="readonly", width=30
)
self.port_combobox_as.grid(
row=current_row, column=1, padx=global_pad_x, pady=global_pad_y
)
self.connect_button_as = ttk.Button(
self.port_select_frame, text="Connect", command=self.connect_as
)
self.connect_button_as.grid(
row=current_row, column=2, padx=global_pad_x, pady=global_pad_y
)
self.disconnect_button_as = ttk.Button(
self.port_select_frame, text="Disconnect", command=self.disconnect_as
)
self.disconnect_button_as.grid(
row=current_row, column=3, padx=global_pad_x, pady=global_pad_y
)
self.disconnect_button_as.config(state=tk.DISABLED)
self.reset_button_as = ttk.Button(
self.port_select_frame, text="Reset", command=self.reset_as
)
self.reset_button_as.grid(
row=current_row, column=4, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.reset_button_as.config(state=tk.DISABLED)
self.status_label_as = ttk.Label(
self.port_select_frame, text="Status: Not connected"
)
self.status_label_as.grid(
row=current_row,
column=5,
padx=global_pad_x,
pady=global_pad_y,
sticky="W",
)
# update the current row
current_row = self.port_select_frame.grid_size()[1]
# Pump Manual Control frame
self.manual_control_frame = ttk.Labelframe(
self.master,
text="Pump Manual Control",
padding=(global_pad_N, global_pad_S, global_pad_W, global_pad_E),
)
self.manual_control_frame.grid(
row=current_row,
column=0,
columnspan=8,
padx=global_pad_x,
pady=global_pad_y,
sticky="NSEW",
)
# first row in the manual control frame, containing all the buttons
self.manual_control_frame_buttons = ttk.Frame(self.manual_control_frame)
self.manual_control_frame_buttons.grid(
row=0,
column=0,
columnspan=8,
padx=global_pad_x,
pady=global_pad_y,
sticky="NSEW",
)
self.add_pump_button = ttk.Button(
self.manual_control_frame_buttons, text="Add Pump", command=self.add_pump
)
self.add_pump_button.grid(
row=0, column=0, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.clear_pumps_button = ttk.Button(
self.manual_control_frame_buttons,
text="Clear All Pumps",
command=lambda: self.remove_pump(remove_all=True),
)
self.clear_pumps_button.grid(
row=0, column=1, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.save_pumps_button = ttk.Button(
self.manual_control_frame_buttons,
text="Save Config",
command=self.save_pump_config,
)
self.save_pumps_button.grid(
row=0, column=2, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.emergency_shutdown_button = ttk.Button(
self.manual_control_frame_buttons,
text="Shutdown All Pumps",
command=lambda: self.pumps_shutdown(confirmation=True),
)
self.emergency_shutdown_button.grid(
row=0, column=3, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
# second row in the manual control frame, containing the pumps widgets
self.pumps_frame = ttk.Frame(self.manual_control_frame)
self.pumps_frame.grid(
row=1,
column=0,
columnspan=8,
padx=global_pad_x,
pady=global_pad_y,
sticky="NSEW",
)
# update the current row
current_row += self.manual_control_frame.grid_size()[1]
# Autosampler Manual Control frame
self.manual_control_frame_as = ttk.Labelframe(
self.master,
text="Autosampler Manual Control",
padding=(global_pad_N, global_pad_S, global_pad_W, global_pad_E),
)
self.manual_control_frame_as.grid(
row=current_row,
column=0,
columnspan=8,
padx=global_pad_x,
pady=global_pad_y,
sticky="NSEW",
)
# Text Entry for Position
self.position_entry_as = ttk.Entry(self.manual_control_frame_as, width=15)
self.position_entry_as.grid(
row=0, column=1, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.goto_position_button_as = ttk.Button(
self.manual_control_frame_as,
text="Go to Position",
command=self.goto_position_as,
)
self.goto_position_button_as.grid(
row=0, column=2, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
# Dropdown and Button for Slots
self.slot_combobox_as = ttk.Combobox(
self.manual_control_frame_as, state="readonly", width=15
)
self.slot_combobox_as.grid(
row=0, column=3, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.goto_slot_button_as = ttk.Button(
self.manual_control_frame_as, text="Go to Slot", command=self.goto_slot_as
)
self.goto_slot_button_as.grid(
row=0, column=4, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
# update the current row
current_row += self.manual_control_frame_as.grid_size()[1]
# Recipe frame
self.recipe_frame = ttk.Labelframe(
self.master,
text="Recipe",
padding=(global_pad_N, global_pad_S, global_pad_W, global_pad_E),
)
self.recipe_frame.grid(
row=current_row,
column=0,
columnspan=8,
padx=global_pad_x,
pady=global_pad_y,
sticky="NSEW",
)
# first row in the recipe frame, containing the buttons
self.recipe_frame_buttons = ttk.Frame(self.recipe_frame)
self.recipe_frame_buttons.grid(
row=0,
column=0,
columnspan=8,
padx=global_pad_x,
pady=global_pad_y,
sticky="NSEW",
)
self.load_recipe_button = ttk.Button(
self.recipe_frame_buttons, text="Load Recipe", command=self.load_recipe
)
self.load_recipe_button.grid(
row=0, column=0, padx=global_pad_x, pady=global_pad_y
)
self.start_button = ttk.Button(
self.recipe_frame_buttons, text="Start", command=self.start_procedure
)
self.start_button.grid(row=0, column=1, padx=global_pad_x, pady=global_pad_y)
self.start_button.config(state=tk.DISABLED)
self.stop_button = ttk.Button(
self.recipe_frame_buttons,
text="Stop",
command=lambda: self.stop_procedure(True),
)
self.stop_button.grid(row=0, column=2, padx=global_pad_x, pady=global_pad_y)
self.stop_button.config(state=tk.DISABLED)
self.pause_button = ttk.Button(
self.recipe_frame_buttons, text="Pause", command=self.pause_procedure
)
self.pause_button.grid(row=0, column=3, padx=global_pad_x, pady=global_pad_y)
self.pause_button.config(state=tk.DISABLED)
self.continue_button = ttk.Button(
self.recipe_frame_buttons, text="Continue", command=self.continue_procedure
)
self.continue_button.grid(row=0, column=4, padx=global_pad_x, pady=global_pad_y)
self.continue_button.config(state=tk.DISABLED)
# second row in the recipe frame, containing the recipe table
self.recipe_table_frame = ttk.Frame(self.recipe_frame)
self.recipe_table_frame.grid(
row=1,
column=0,
columnspan=8,
padx=global_pad_x,
pady=global_pad_y,
sticky="NSEW",
)
self.recipe_table = ttk.Frame(self.recipe_table_frame)
self.recipe_table.grid(
row=0, column=0, padx=global_pad_x, pady=global_pad_y, sticky="NSEW"
)
self.scrollbar = ttk.Scrollbar()
# update the current row
current_row += self.recipe_frame.grid_size()[1]
# Progress frame
self.progress_frame = ttk.Labelframe(
self.master,
text="Progress",
padding=(global_pad_N, global_pad_S, global_pad_W, global_pad_E),
)
self.progress_frame.grid(
row=current_row,
column=0,
columnspan=8,
padx=global_pad_x,
pady=global_pad_y,
sticky="NSEW",
)
# first row in the progress frame, containing the progress bar
self.total_progress_label = ttk.Label(
self.progress_frame, text="Total Progress:"
)
self.total_progress_label.grid(
row=0, column=0, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.total_progress_bar = ttk.Progressbar(
self.progress_frame, length=250, mode="determinate"
)
self.total_progress_bar.grid(
row=0, column=1, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
# second row in the progress frame, containing the remaining time and Procedure end time
self.remaining_time_label = ttk.Label(
self.progress_frame, text="Remaining Time:"
)
self.remaining_time_label.grid(
row=1, column=0, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.remaining_time_value = ttk.Label(self.progress_frame, text="")
self.remaining_time_value.grid(
row=1, column=1, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.end_time_label = ttk.Label(self.progress_frame, text="End Time:")
self.end_time_label.grid(
row=1, column=2, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
self.end_time_value = ttk.Label(self.progress_frame, text="")
self.end_time_value.grid(
row=1, column=3, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
# update the current row
current_row += self.progress_frame.grid_size()[1]
# RTC time frame
self.rtc_time_frame = ttk.Frame(
self.master,
padding=(0, 0, 0, 0),
)
self.rtc_time_frame.grid(
row=current_row,
column=0,
columnspan=8,
padx=0,
pady=0,
sticky="NSE",
)
# first row in the rtc_time_frame, containing the current rtc time from the Pico
self.current_time_label = ttk.Label(
self.rtc_time_frame, text="Pump Controller Time: --:--:--"
)
self.current_time_label.grid(row=0, column=0, padx=0, pady=0, sticky="NSE")
self.current_time_label_as = ttk.Label(
self.rtc_time_frame, text=self.autosamplers_rtc_time
)
self.current_time_label_as.grid(row=0, column=1, padx=0, pady=0, sticky="NSE")
self.set_manual_control_buttons_state(tk.DISABLED)
self.set_autosampler_buttons_state(tk.DISABLED)
def add_pump_controller_widgets(self, controller_id):
# update the pump_controllers dictionary
self.pump_controllers[controller_id] = serial.Serial()
self.pump_controllers_connected[controller_id] = False
"""Adds the combobox and buttons for selecting and connecting a pump controller."""
row = controller_id - 1 # Zero-indexed for row position
port_label = ttk.Label(
self.port_select_frame, text=f"Pump controller {controller_id}:"
)
port_label.grid(
row=row, column=0, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
port_combobox = ttk.Combobox(self.port_select_frame, state="readonly", width=30)
port_combobox.grid(row=row, column=1, padx=global_pad_x, pady=global_pad_y)
connect_button = ttk.Button(
self.port_select_frame,
text="Connect",
command=lambda: self.connect(controller_id),
)
connect_button.grid(row=row, column=2, padx=global_pad_x, pady=global_pad_y)
disconnect_button = ttk.Button(
self.port_select_frame,
text="Disconnect",
command=lambda: self.disconnect(controller_id),
)
disconnect_button.grid(row=row, column=3, padx=global_pad_x, pady=global_pad_y)
disconnect_button.config(state=tk.DISABLED)
reset_button = ttk.Button(
self.port_select_frame,
text="Reset",
command=lambda: self.reset(controller_id),
)
reset_button.grid(
row=row, column=4, padx=global_pad_x, pady=global_pad_y, sticky="W"
)
reset_button.config(state=tk.DISABLED)
status_label = ttk.Label(
self.port_select_frame,
text=f"Status: Not connected",
)
status_label.grid(
row=row,
column=5,
padx=global_pad_x,
pady=global_pad_y,
columnspan=1,
sticky="W",
)
# Save references to widgets
self.pump_controllers_id_to_widget_map[controller_id] = {
"combobox": port_combobox,
"connect_button": connect_button,
"disconnect_button": disconnect_button,
"reset_button": reset_button,
"status_label": status_label,
}
def main_loop(self):
try:
self.refresh_ports()
self.read_serial()
self.read_serial_as()
self.send_command()
self.send_command_as()
self.update_progress()
self.query_rtc_time()
self.update_rtc_time_display()
self.master.after(self.main_loop_interval_ms, self.main_loop)
except Exception as e:
logging.error(f"Error in main loop: {e}")
non_blocking_messagebox(
parent=self.master,
title="Error",
message=f"An error occurred in the main loop: {e}",
)
def refresh_ports(self, instant=False):
# check if all serial objects in the self.pump_controllers dictionary are connected
pump_ctls_all_connected = all(
[
serial_port_obj and serial_port_obj.is_open
for serial_port_obj in self.pump_controllers.values()
]
)
if not pump_ctls_all_connected or not self.autosamplers:
if (
time.monotonic_ns() - self.last_port_refresh_ns
< self.port_refresh_interval_ns
and not instant
):
return
# filter by vendor id and ignore already connected ports
# get a list of connected ports name from the serial_port dictionary
connected_ports = [
port.name
for port in self.pump_controllers.values()
if port and port.is_open
]
if self.autosamplers:
connected_ports.append(self.autosamplers.name)
ports = [
port.device + " (SN:" + str(port.serial_number) + ")"
for port in serial.tools.list_ports.comports()
if port.vid == pico_vid and port.name.strip() not in connected_ports
]
ports_list = [
port
for port in serial.tools.list_ports.comports()
if port.vid == pico_vid and port.name.strip() not in connected_ports
]
# print detail information of the ports to the console
for port in ports_list:
try:
# put these into one line
logging.debug(
f"name: {port.name}, description: {port.description}, device: {port.device}, hwid: {port.hwid}, manufacturer: {port.manufacturer}, pid: {hex(port.pid)}, serial_number: {port.serial_number}, vid: {hex(port.vid)}"
)
except Exception as e:
logging.error(f"Error: {e}")
# go through the pump controllers dictionary and update the comboboxes in the corresponding frame
for id, widgets in self.pump_controllers_id_to_widget_map.items():
serial_port_obj = self.pump_controllers[id]
if (
serial_port_obj and not serial_port_obj.is_open
): # don't update the combobox if the port is already connected
widgets["combobox"]["values"] = ports
if widgets["combobox"].get() not in ports:
if len(ports) > 0:
widgets["combobox"].current(0)
else:
widgets["combobox"].set("")
if not self.autosamplers:
self.port_combobox_as["values"] = ports
# if current value is in the list, don't change it
if self.port_combobox_as.get() not in ports:
if len(ports) > 0:
self.port_combobox_as.current(0)
else:
self.port_combobox_as.set("")
self.last_port_refresh_ns = time.monotonic_ns()
def connect(self, controller_id):
selected_port = self.pump_controllers_id_to_widget_map[controller_id][
"combobox"
].get()
if selected_port:
parsed_port = selected_port.split("(")[0].strip()
if self.pump_controllers[controller_id].is_open:
if ( # if already connected, pop a confirmation message before disconnecting
messagebox.askyesno(
"Disconnect",
f"Disconnect from current port {parsed_port}?",
)
== tk.YES
):
# suppress the message for the disconnect
self.disconnect(controller_id=controller_id, show_message=False)
else:
return
try: # Attempt to connect to the selected port
serial_port_obj = self.pump_controllers[controller_id]
serial_port_widget = self.pump_controllers_id_to_widget_map[
controller_id
]
serial_port_obj.port = parsed_port
serial_port_obj.timeout = self.timeout
serial_port_obj.open()
serial_port_obj.write("0:ping\n".encode()) # identify Pico type
response = serial_port_obj.readline().decode("utf-8").strip()
if "Pico Pump Control Version" not in response:
self.disconnect(controller_id=controller_id, show_message=False)
non_blocking_messagebox(
parent=self.master,
title="Error",
message="Connected to the wrong device for pump control",
)
return
now = datetime.now() # synchronize the RTC with the PC time
sync_command = f"0:stime:{now.year}:{now.month}:{now.day}:{now.hour}:{now.minute}:{now.second}"
serial_port_obj.write(f"{sync_command}\n".encode())
response = serial_port_obj.readline().decode("utf-8").strip()
logging.info(f"Connected to {selected_port}")
self.refresh_ports(instant=True) # refresh the ports immediately
serial_port_widget["status_label"].config(
text=f"Status: Connected to {parsed_port}"
)
self.pump_controllers_connected[controller_id] = True
self.query_pump_info(controller_id=controller_id) # query the pump info
# enable the buttons
serial_port_widget["disconnect_button"].config(state=tk.NORMAL)
serial_port_widget["reset_button"].config(state=tk.NORMAL)
self.set_manual_control_buttons_state(tk.NORMAL)
except Exception as e:
serial_port_widget["status_label"].config(text="Status: Not connected")
self.pump_controllers_connected[controller_id] = False
logging.error(f"Error: {e}")
non_blocking_messagebox(
parent=self.master,
title="Error",
message=f"An error occurred in function connect: {e}",
)
def set_manual_control_buttons_state(self, state) -> None:
self.add_pump_button.config(state=state)
self.clear_pumps_button.config(state=state)
self.save_pumps_button.config(state=state)
self.emergency_shutdown_button.config(state=state)
def connect_as(self):
selected_port = self.port_combobox_as.get()
if selected_port:
parsed_port = selected_port.split("(")[0].strip()
if self.autosamplers:
if (
messagebox.askyesno(
"Disconnect",
f"Disconnect from current port {parsed_port}?",
)
== tk.YES
):
self.disconnect_as(show_message=False)
else:
return
try:
self.autosamplers = serial.Serial(parsed_port, timeout=self.timeout)
self.autosamplers.write("0:ping\n".encode()) # identify Pico type
response = self.autosamplers.readline().decode("utf-8").strip()
if "Pico Autosampler Control Version" not in response:
self.disconnect_as(show_message=False)
non_blocking_messagebox(
parent=self.master,
title="Error",
message="Connected to the wrong device for autosampler.",
)
return
now = datetime.now() # synchronize the RTC with the PC time
sync_command = f"0:stime:{now.year}:{now.month}:{now.day}:{now.hour}:{now.minute}:{now.second}"
self.autosamplers.write(f"{sync_command}\n".encode())
response = self.autosamplers.readline().decode("utf-8").strip()
self.status_label_as.config(text=f"Status: Connected to {parsed_port}")
logging.info(f"Connected to Autosampler at {selected_port}")
self.refresh_ports(instant=True)
self.set_autosampler_buttons_state(tk.NORMAL)
self.autosamplers_send_queue.put("config") # Populate the slots
except Exception as e:
self.status_label_as.config(text="Status: Not connected")
logging.error(f"Error: {e}")
non_blocking_messagebox(
parent=self.master,
title="Error",
message=f"An error occurred in function connect_as: {e}",
)
def set_autosampler_buttons_state(self, state) -> None:
self.disconnect_button_as.config(state=state)
self.reset_button_as.config(state=state)
self.position_entry_as.config(state=state)
self.goto_position_button_as.config(state=state)
self.slot_combobox_as.config(state=state)
self.goto_slot_button_as.config(state=state)
def query_rtc_time(self) -> None:
"""Send a request to the Pico to get the current RTC time every second."""
current_time = time.monotonic_ns()
if current_time - self.last_time_query >= NANOSECONDS_PER_SECOND:
# send the command to each controller
for id, connection_status in self.pump_controllers_connected.items():
if connection_status:
self.pump_controllers_send_queue.put(f"{id}:0:time")
if self.autosamplers:
self.autosamplers_send_queue.put("0:time")
self.last_time_query = current_time
def parse_rtc_time(self, controller_id, response, is_Autosampler=False) -> None:
try:
match = re.search(r"RTC Time: (\d+-\d+-\d+ \d+:\d+:\d+)", response)
if match and not is_Autosampler:
rtc_time = match.group(1)
# store the time in the dictionary
self.pump_controllers_rtc_time[controller_id] = (
f"{controller_id}:{rtc_time}"
)
if match and is_Autosampler:
rtc_time = match.group(1)
self.autosamplers_rtc_time = f"Autosampler Time: {rtc_time}"
except Exception as e:
logging.error(f"Error updating RTC time display: {e}")
def update_rtc_time_display(self) -> None:
try:
# assemble the time string
rtc_time_str = "Pump Controllers Time: "
# sort the keys of the dictionary by the pump id, join the values and update the label
rtc_time_str += " | ".join(
[
self.pump_controllers_rtc_time[key]
for key in sorted(self.pump_controllers_rtc_time.keys())
if self.pump_controllers_connected[key]
]
)
self.current_time_label.config(text=rtc_time_str)
self.current_time_label_as.config(text=self.autosamplers_rtc_time)
except Exception as e:
logging.error(f"Error updating RTC time display: {e}")
def disconnect(self, controller_id, show_message=True):
if self.pump_controllers[controller_id]:
serial_port_obj = self.pump_controllers[controller_id]
serial_port_widget = self.pump_controllers_id_to_widget_map[controller_id]
if serial_port_obj.is_open:
try:
serial_port_obj.close() # close the serial port connection
self.pump_controllers_connected[controller_id] = False
# update UI
serial_port_widget["status_label"].config(
text="Status: Not connected"
) # update the status label
serial_port_widget["disconnect_button"].config(state=tk.DISABLED)
serial_port_widget["reset_button"].config(state=tk.DISABLED)
self.remove_pumps_widgets(
remove_all=False, controller_id=controller_id
)
# only disable the manual control buttons if all controllers are disconnected
if all(
[not port.is_open for port in self.pump_controllers.values()]
):
self.set_manual_control_buttons_state(tk.DISABLED)
self.clear_recipe() # clear the recipe table
self.stop_procedure(False) # also stop any running procedure
# go into the queue and remove any command that is meant for the disconnected controller
temp_queue = Queue()
while not self.pump_controllers_send_queue.empty():
command = self.pump_controllers_send_queue.get()
if int(command.split(":")[0]) != controller_id:
temp_queue.put(command)
while not temp_queue.empty():
self.pump_controllers_send_queue.put(temp_queue.get())
self.refresh_ports(instant=True) # refresh the ports immediately
logging.info(f"Disconnected from Pico {controller_id}")
if show_message:
non_blocking_messagebox(
parent=self.master,
title="Connection Status",
message=f"Disconnected from pump controller {controller_id}",
)
except Exception as e:
logging.error(f"Error: {e}")
self.pump_controllers_connected[controller_id] = False
non_blocking_messagebox(
parent=self.master,
title="Error",
message=f"An error occurred in function disconnect: {e}",
)
def disconnect_as(self, show_message=True):
if self.autosamplers:
try:
self.autosamplers.close()
self.autosamplers = None
self.status_label_as.config(text="Status: Not connected")
self.set_autosampler_buttons_state(tk.DISABLED)
while not self.autosamplers_send_queue.empty(): # empty the queue
self.autosamplers_send_queue.get()
logging.info(f"Disconnected from Autosampler")
if show_message:
non_blocking_messagebox(
parent=self.master,
title="Error",
message="Disconnected from Autosampler",
)
except Exception as e:
logging.error(f"Error: {e}")
self.autosamplers = None
non_blocking_messagebox(
parent=self.master,
title="Error",
message=f"An error occurred: {e}",
)
def reset(self, controller_id):
try:
if self.pump_controllers[controller_id].is_open:
if messagebox.askyesno(
"Reset", "Are you sure you want to reset the Pico?"
):
self.pump_controllers_send_queue.put(f"{controller_id}:0:reset")
logging.info(f"Signal sent for controller {controller_id} reset.")
except Exception as e:
logging.error(f"Error: {e}")
non_blocking_messagebox(
parent=self.master,
title="Error",
message=f"An error occurred in function reset: {e}",
)
def reset_as(self):
if self.autosamplers:
try:
if messagebox.askyesno(
"Reset", "Are you sure you want to reset the Autosampler?"
):
self.autosamplers_send_queue.put("0:reset")
logging.info("Signal sent for Autosampler reset.")
except Exception as e:
logging.error(f"Error: {e}")
non_blocking_messagebox(
parent=self.master,
title="Error",
message=f"An error occurred in function reset_as: {e}",
)
def query_pump_info(self, controller_id):
serial_obj = self.pump_controllers.get(controller_id, None)
if serial_obj and serial_obj.is_open:
self.pump_controllers_send_queue.put(f"{controller_id}:0:info")
def update_status(self, controller_id):
serial_obj = self.pump_controllers.get(controller_id, None)
if serial_obj and serial_obj.is_open:
self.pump_controllers_send_queue.put(f"{controller_id}:0:st")
def toggle_power(self, pump_id, update_status=True):
controller_id = self.pump_ids_to_controller_ids.get(pump_id, None)
if controller_id:
if self.pump_controllers[controller_id].is_open:
self.pump_controllers_send_queue.put(f"{controller_id}:{pump_id}:pw")
if update_status:
self.update_status(controller_id=controller_id)
else:
logging.error(
f"Trying to toggle power for pump {pump_id} without a controller."
)
def toggle_direction(self, pump_id, update_status=True):
controller_id = self.pump_ids_to_controller_ids.get(pump_id, None)
if controller_id:
if self.pump_controllers[controller_id].is_open:
self.pump_controllers_send_queue.put(f"{controller_id}:{pump_id}:di")
if update_status:
self.update_status(controller_id=controller_id)
else:
logging.error(
f"Trying to toggle direction for pump {pump_id} without a controller."
)
def register_pump(
self,
controller_id,
pump_id,
power_pin,
direction_pin,
initial_power_pin_value,
initial_direction_pin_value,
initial_power_status,
initial_direction_status,
):
try:
serial_obj = self.pump_controllers.get(controller_id, None)
if serial_obj and serial_obj.is_open:
command = f"{pump_id}:reg:{power_pin}:{direction_pin}:{initial_power_pin_value}:{initial_direction_pin_value}:{initial_power_status}:{initial_direction_status}"
self.pump_controllers_send_queue.put(f"{controller_id}:{command}")
self.update_status(controller_id=controller_id)
except Exception as e:
logging.error(f"Error: {e}")
non_blocking_messagebox(
parent=self.master,
title="Error",
message=f"An error occurred in function register_pump: {e}",
)
def remove_pump(self, remove_all=False, pump_id=None):
try:
if remove_all:
if messagebox.askyesno("Clear Pumps", "Clear all pumps?") == tk.YES:
# query the pump info for all the controllers
for (
id,
connection_status,
) in self.pump_controllers_connected.items():
if connection_status:
self.remove_pumps_widgets(
remove_all=False, controller_id=id
)
self.pump_controllers_send_queue.put(f"{id}:0:clr")
self.query_pump_info(controller_id=id)
else:
if (
messagebox.askyesno("Clear Pump", f"Clear pump {pump_id}?")
== tk.YES
and pump_id
):
# find the controller id of the pump
controller_id = self.pump_ids_to_controller_ids.get(pump_id, None)
if controller_id:
self.remove_pumps_widgets(remove_all=False, pump_id=pump_id)
self.pump_controllers_send_queue.put(
f"{controller_id}:{pump_id}:clr"
)
self.query_pump_info(controller_id=controller_id)
except Exception as e:
logging.error(f"Error: {e}")
non_blocking_messagebox(
parent=self.master,
title="Error",
message=f"An error occurred in function remove_pump: {e}",
)
def save_pump_config(self):
if any(self.pump_controllers_connected.values()):
try:
# pop a checklist message box to let user choose which pump to save
pump_id_list = [
f"Controller {id}"
for id, connected in self.pump_controllers_connected.items()
if connected
]
if len(pump_id_list) > 1:
pump_id_list.insert(0, "All")
result_var = tk.StringVar()
result_var.set("") # Initialize as empty
non_blocking_checklist(
parent=self.master,
title="Select Controller to Save",
items=pump_id_list,
result_var=result_var,
) # Trigger non-blocking checklist
def on_selection(*args): # act once the user makes a selection
result = result_var.get()
if result == "": # check if empty
result_var.trace_remove("write", trace_id) # Untrace
return
selected_pumps = result.split(",")
if "All" in selected_pumps:
for id, connected in self.pump_controllers_connected.items():
if connected:
self.pump_controllers_send_queue.put(f"{id}:0:save")
logging.info(
f"Signal sent to save pump {id} configuration."
)
else:
for pump in selected_pumps:
pump_id = int(pump.split(" ")[1])
self.pump_controllers_send_queue.put(f"{pump_id}:0:save")
logging.info(