forked from Cephla-Lab/Squid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserial_peripherals.py
1263 lines (1012 loc) · 41.9 KB
/
serial_peripherals.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
import serial
from serial.tools import list_ports
import time
from typing import Tuple, Optional
import struct
from control.microscope import LightSourceType, IntensityControlMode, ShutterControlMode
from control._def import *
from squid.abc import LightSource
import squid.logging
log = squid.logging.get_logger(__name__)
class SerialDevice:
"""
General wrapper for serial devices, with
automating device finding based on VID/PID
or serial number.
"""
def __init__(self, port=None, VID=None, PID=None, SN=None, baudrate=9600, read_timeout=0.1, **kwargs):
# Initialize the serial connection
self.port = port
self.VID = VID
self.PID = PID
self.SN = SN
self.baudrate = baudrate
self.read_timeout = read_timeout
self.serial_kwargs = kwargs
self.serial = None
if VID is not None and PID is not None:
for d in list_ports.comports():
if d.vid == VID and d.pid == PID:
self.port = d.device
break
if SN is not None:
for d in list_ports.comports():
if d.serial_number == SN:
self.port = d.device
break
if self.port is not None:
self.serial = serial.Serial(self.port, baudrate=baudrate, timeout=read_timeout, **kwargs)
def open_ser(self, SN=None, VID=None, PID=None, baudrate=None, read_timeout=None, **kwargs):
if self.serial is not None and not self.serial.is_open:
self.serial.open()
if SN is None:
SN = self.SN
if VID is None:
VID = self.VID
if PID is None:
PID = self.PID
if baudrate is None:
baudrate = self.baudrate
if read_timeout is None:
read_timeout = self.read_timeout
for k in self.serial_kwargs.keys():
if k not in kwargs:
kwargs[k] = self.serial_kwargs[k]
if self.serial is None:
if VID is not None and PID is not None:
for d in list_ports.comports():
if d.vid == VID and d.pid == PID:
self.port = d.device
break
if SN is not None:
for d in list_ports.comports():
if d.serial_number == SN:
self.port = d.device
break
if self.port is not None:
self.serial = serial.Serial(self.port, **kwargs)
def write_and_check(
self,
command,
expected_response,
read_delay=0.1,
max_attempts=5,
attempt_delay=1,
check_prefix=True,
print_response=False,
):
# Write a command and check the response
for attempt in range(max_attempts):
self.serial.write(command.encode())
time.sleep(read_delay) # Wait for the command to be sent/executed
response = self.serial.readline().decode().strip()
if print_response:
log.info(response)
# flush the input buffer
while self.serial.in_waiting:
if print_response:
log.info(self.serial.readline().decode().strip())
else:
self.serial.readline().decode().strip()
# check response
if response == expected_response:
return response
else:
log.warning(response)
# check prefix if the full response does not match
if check_prefix:
if response.startswith(expected_response):
return response
else:
time.sleep(attempt_delay) # Wait before retrying
raise RuntimeError("Max attempts reached without receiving expected response.")
def write_and_read(self, command, read_delay=0.1, max_attempts=3, attempt_delay=1):
self.serial.write(command.encode())
time.sleep(read_delay) # Wait for the command to be sent
response = self.serial.readline().decode().strip()
return response
def write(self, command):
self.serial.write(command.encode())
def close(self):
# Close the serial connection
self.serial.close()
class XLight_Simulation:
def __init__(self):
self.has_spinning_disk_motor = True
self.has_spinning_disk_slider = True
self.has_dichroic_filters_wheel = True
self.has_emission_filters_wheel = True
self.has_excitation_filters_wheel = True
self.has_illumination_iris_diaphragm = True
self.has_emission_iris_diaphragm = True
self.has_dichroic_filter_slider = True
self.has_ttl_control = True
self.emission_wheel_pos = 1
self.dichroic_wheel_pos = 1
self.disk_motor_state = False
self.spinning_disk_pos = 0
def set_emission_filter(self, position, extraction=False, validate=False):
self.emission_wheel_pos = position
return position
def get_emission_filter(self):
return self.emission_wheel_pos
def set_dichroic(self, position, extraction=False):
self.dichroic_wheel_pos = position
return position
def get_dichroic(self):
return self.dichroic_wheel_pos
def set_disk_position(self, position):
self.spinning_disk_pos = position
return position
def get_disk_position(self):
return self.spinning_disk_pos
def set_disk_motor_state(self, state):
self.disk_motor_state = state
return state
def get_disk_motor_state(self):
return self.disk_motor_state
def set_illumination_iris(self, value):
# value: 0 - 100
self.illumination_iris = value
return self.illumination_iris
def set_emission_iris(self, value):
# value: 0 - 100
self.emission_iris = value
return self.emission_iris
def set_filter_slider(self, position):
if str(position) not in ["0", "1", "2", "3"]:
raise ValueError("Invalid slider position!")
self.slider_position = position
return self.slider_position
# CrestOptics X-Light Port specs:
# 9600 baud
# 8 data bits
# 1 stop bit
# No parity
# no flow control
class XLight:
"""Wrapper for communicating with CrestOptics X-Light devices over serial"""
def __init__(self, SN, sleep_time_for_wheel=0.25, disable_emission_filter_wheel=True):
"""
Provide serial number (default is that of the device
cephla already has) for device-finding purposes. Otherwise, all
XLight devices should use the same serial protocol
"""
self.log = squid.logging.get_logger(self.__class__.__name__)
self.has_spinning_disk_motor = False
self.has_spinning_disk_slider = False
self.has_dichroic_filters_wheel = False
self.has_emission_filters_wheel = False
self.has_excitation_filters_wheel = False
self.has_illumination_iris_diaphragm = False
self.has_emission_iris_diaphragm = False
self.has_dichroic_filter_slider = False
self.has_ttl_control = False
self.sleep_time_for_wheel = sleep_time_for_wheel
self.disable_emission_filter_wheel = disable_emission_filter_wheel
self.serial_connection = SerialDevice(
SN=SN,
baudrate=115200,
bytesize=serial.EIGHTBITS,
stopbits=serial.STOPBITS_ONE,
parity=serial.PARITY_NONE,
xonxoff=False,
rtscts=False,
dsrdtr=False,
)
self.serial_connection.open_ser()
self.parse_idc_response(self.serial_connection.write_and_read("idc\r"))
self.print_config()
def parse_idc_response(self, response):
# Convert hexadecimal response to integer
config_value = int(response, 16)
# Check each bit and set the corresponding variable
self.has_spinning_disk_motor = bool(config_value & 0x00000001)
self.has_spinning_disk_slider = bool(config_value & 0x00000002)
self.has_dichroic_filters_wheel = bool(config_value & 0x00000004)
self.has_emission_filters_wheel = bool(config_value & 0x00000008)
self.has_excitation_filters_wheel = bool(config_value & 0x00000080)
self.has_illumination_iris_diaphragm = bool(config_value & 0x00000200)
self.has_emission_iris_diaphragm = bool(config_value & 0x00000400)
self.has_dichroic_filter_slider = bool(config_value & 0x00000800)
self.has_ttl_control = bool(config_value & 0x00001000)
def print_config(self):
self.log.info(
(
"Machine Configuration:\n" f" Spinning disk motor: {self.has_spinning_disk_motor}\n",
f" Spinning disk slider: {self.has_spinning_disk_slider}\n",
f" Dichroic filters wheel: {self.has_dichroic_filters_wheel}\n",
f" Emission filters wheel: {self.has_emission_filters_wheel}\n",
f" Excitation filters wheel: {self.has_excitation_filters_wheel}\n",
f" Illumination Iris diaphragm: {self.has_illumination_iris_diaphragm}\n",
f" Emission Iris diaphragm: {self.has_emission_iris_diaphragm}\n",
f" Dichroic filter slider: {self.has_dichroic_filter_slider}\n",
f" TTL control and combined commands subsystem: {self.has_ttl_control}",
)
)
def set_emission_filter(self, position, extraction=False, validate=True):
if self.disable_emission_filter_wheel:
print("emission filter wheel disabled")
return -1
if str(position) not in ["1", "2", "3", "4", "5", "6", "7", "8"]:
raise ValueError("Invalid emission filter wheel position!")
position_to_write = str(position)
position_to_read = str(position)
if extraction:
position_to_write += "m"
if validate:
current_pos = self.serial_connection.write_and_check(
"B" + position_to_write + "\r", "B" + position_to_read, read_delay=0.01
)
self.emission_wheel_pos = int(current_pos[1])
else:
self.serial_connection.write("B" + position_to_write + "\r")
time.sleep(self.sleep_time_for_wheel)
self.emission_wheel_pos = position
return self.emission_wheel_pos
def get_emission_filter(self):
current_pos = self.serial_connection.write_and_check("rB\r", "rB", read_delay=0.01)
self.emission_wheel_pos = int(current_pos[2])
return self.emission_wheel_pos
def set_dichroic(self, position, extraction=False):
if str(position) not in ["1", "2", "3", "4", "5"]:
raise ValueError("Invalid dichroic wheel position!")
position_to_write = str(position)
position_to_read = str(position)
if extraction:
position_to_write += "m"
current_pos = self.serial_connection.write_and_check(
"C" + position_to_write + "\r", "C" + position_to_read, read_delay=0.01
)
self.dichroic_wheel_pos = int(current_pos[1])
return self.dichroic_wheel_pos
def get_dichroic(self):
current_pos = self.serial_connection.write_and_check("rC\r", "rC", read_delay=0.01)
self.dichroic_wheel_pos = int(current_pos[2])
return self.dichroic_wheel_pos
def set_disk_position(self, position):
if str(position) not in ["0", "1", "2", "wide field", "confocal"]:
raise ValueError("Invalid disk position!")
if position == "wide field":
position = "0"
if position == "confocal":
position = "1'"
position_to_write = str(position)
position_to_read = str(position)
current_pos = self.serial_connection.write_and_check(
"D" + position_to_write + "\r", "D" + position_to_read, read_delay=5
)
self.spinning_disk_pos = int(current_pos[1])
return self.spinning_disk_pos
def set_illumination_iris(self, value):
# value: 0 - 100
self.illumination_iris = value
value = str(int(10 * value))
self.serial_connection.write_and_check("J" + value + "\r", "J" + value, read_delay=3)
return self.illumination_iris
def set_emission_iris(self, value):
# value: 0 - 100
self.emission_iris = value
value = str(int(10 * value))
self.serial_connection.write_and_check("V" + value + "\r", "V" + value, read_delay=3)
return self.emission_iris
def set_filter_slider(self, position):
if str(position) not in ["0", "1", "2", "3"]:
raise ValueError("Invalid slider position!")
self.slider_position = position
position_to_write = str(position)
position_to_read = str(position)
self.serial_connection.write_and_check("P" + position_to_write + "\r", "V" + position_to_read, read_delay=5)
return self.slider_position
def get_disk_position(self):
current_pos = self.serial_connection.write_and_check("rD\r", "rD", read_delay=0.01)
self.spinning_disk_pos = int(current_pos[2])
return self.spinning_disk_pos
def set_disk_motor_state(self, state):
"""Set True for ON, False for OFF"""
if state:
state_to_write = "1"
else:
state_to_write = "0"
current_pos = self.serial_connection.write_and_check(
"N" + state_to_write + "\r", "N" + state_to_write, read_delay=2.5
)
self.disk_motor_state = bool(int(current_pos[1]))
def get_disk_motor_state(self):
"""Return True for on, Off otherwise"""
current_pos = self.serial_connection.write_and_check("rN\r", "rN", read_delay=0.01)
self.disk_motor_state = bool(int(current_pos[2]))
return self.disk_motor_state
class LDI(LightSource):
"""Wrapper for communicating with LDI over serial"""
def __init__(self, SN="00000001"):
"""
Provide serial number
"""
self.log = squid.logging.get_logger(self.__class__.__name__)
self.serial_connection = SerialDevice(
SN=SN,
baudrate=9600,
bytesize=serial.EIGHTBITS,
stopbits=serial.STOPBITS_ONE,
parity=serial.PARITY_NONE,
xonxoff=False,
rtscts=False,
dsrdtr=False,
)
self.serial_connection.open_ser()
if LDI_INTENSITY_MODE == "PC":
self.intensity_mode = IntensityControlMode.Software
elif LDI_INTENSITY_MODE == "EXT":
self.intensity_mode = IntensityControlMode.SquidControllerDAC
if LDI_SHUTTER_MODE == "PC":
self.shutter_mode = ShutterControlMode.Software
elif LDI_SHUTTER_MODE == "EXT":
self.shutter_mode = ShutterControlMode.TTL
self.channel_mappings = {
405: 405,
470: 470,
488: 470,
545: 555,
550: 555,
555: 555,
561: 555,
638: 640,
640: 640,
730: 730,
735: 730,
750: 730,
}
self.active_channel = None
def initialize(self):
self.serial_connection.write_and_check("run!\r", "ok")
def set_shutter_control_mode(self, mode):
if mode == ShutterControlMode.TTL:
self.serial_connection.write_and_check("SH_MODE=EXT\r", "ok")
elif mode == ShutterControlMode.Software:
self.serial_connection.write_and_check("SH_MODE=PC\r", "ok")
self.shutter_mode = mode
def get_shutter_control_mode(self):
pass
def set_intensity_control_mode(self, mode):
if mode == IntensityControlMode.SquidControllerDAC:
self.serial_connection.write_and_check("INT_MODE=EXT\r", "ok")
elif mode == IntensityControlMode.Software:
self.serial_connection.write_and_check("INT_MODE=PC\r", "ok")
self.intensity_mode = mode
def get_intensity_control_mode(self):
pass
def set_intensity(self, channel, intensity):
channel = str(channel)
intensity = "{:.2f}".format(intensity)
self.log.debug("set:" + channel + "=" + intensity + "\r")
self.serial_connection.write_and_check("set:" + channel + "=" + intensity + "\r", "ok")
def get_intensity(self, channel):
try:
response = self.serial_connection.write_and_read("set?\r")
pairs = response.replace('SET:', '').split(',')
intensities = {}
for pair in pairs:
channel, value = pair.split('=')
intensities[int(channel)] = int(value)
return intensity[channel]
except:
return None
def set_shutter_state(self, channel, on):
channel = str(channel)
state = str(on)
if self.active_channel is not None and channel != self.active_channel:
self.set_active_channel_shutter(False)
self.serial_connection.write_and_check("shutter:" + channel + "=" + state + "\r", "ok")
if on:
self.active_channel = channel
def get_shutter_state(self, channel):
try:
response = self.serial_connection.write_and_read("shutter?" + channel + "\r")
state = response.split('=')[1]
return 1 if state == 'OPEN' else 0
except:
return None
def set_active_channel_shutter(self, state):
channel = str(self.active_channel)
state = str(state)
self.log.debug("shutter:" + channel + "=" + state + "\r")
self.serial_connection.write_and_check("shutter:" + channel + "=" + state + "\r", "ok")
def shut_down(self):
for ch in list(set(self.channel_mappings.values())):
self.set_intensity(ch, 0)
self.set_shutter_state(ch, False)
self.serial_connection.close()
class LDI_Simulation(LightSource):
"""Wrapper for communicating with LDI over serial"""
def __init__(self, SN="00000001"):
"""
Provide serial number
"""
self.log = squid.logging.get_logger(self.__class__.__name__)
self.intensity_mode = IntensityControlMode.Software
self.shutter_mode = ShutterControlMode.Software
self.channel_mappings = {
405: 405,
470: 470,
488: 470,
545: 555,
550: 555,
555: 555,
561: 555,
638: 640,
640: 640,
730: 730,
735: 730,
750: 730,
}
def initialize(self):
pass
def set_shutter_mode(self, mode):
if mode == ShutterControlMode.TTL:
self.serial_connection.write_and_check("SH_MODE=EXT\r", "ok")
elif mode == ShutterControlMode.Software:
self.serial_connection.write_and_check("SH_MODE=PC\r", "ok")
self.shutter_mode = mode
def set_intensity_mode(self, mode):
if mode == IntensityControlMode.SquidControllerDAC:
self.serial_connection.write_and_check("INT_MODE=EXT\r", "ok")
elif mode == IntensityControlMode.Software:
self.serial_connection.write_and_check("INT_MODE=PC\r", "ok")
self.intensity_mode = mode
def set_intensity(self, channel, intensity):
channel = str(channel)
intensity = "{:.2f}".format(intensity)
self.log.debug("set:" + channel + "=" + intensity + "\r")
self.log.debug("active channel: " + str(self.active_channel))
def get_intensity(self, channel):
return 0
def set_shutter_state(self, channel, on):
channel = str(channel)
state = str(on)
def get_shutter_state(self, channel):
return 0
def set_active_channel_shutter(self, state):
channel = str(self.active_channel)
state = str(state)
self.log.debug("shutter:" + channel + "=" + state + "\r")
def shut_down(self):
pass
class SciMicroscopyLEDArray:
"""Wrapper for communicating with SciMicroscopy over serial"""
def __init__(self, SN, array_distance=50, turn_on_delay=0.03):
"""
Provide serial number
"""
self.serial_connection = SerialDevice(
SN=SN,
baudrate=115200,
bytesize=serial.EIGHTBITS,
stopbits=serial.STOPBITS_ONE,
parity=serial.PARITY_NONE,
xonxoff=False,
rtscts=False,
dsrdtr=False,
)
self.serial_connection.open_ser()
self.check_about()
self.set_distance(array_distance)
self.set_brightness(1)
self.illumination = None
self.NA = 0.5
self.turn_on_delay = turn_on_delay
def write(self, command):
self.serial_connection.write_and_check(command + "\r", "", read_delay=0.01, print_response=True)
def check_about(self):
self.serial_connection.write_and_check("about" + "\r", "=", read_delay=0.01, print_response=True)
def set_distance(self, array_distance):
# array distance in mm
array_distance = str(int(array_distance))
self.serial_connection.write_and_check(
"sad." + array_distance + "\r",
"Current array distance from sample is " + array_distance + "mm",
read_delay=0.01,
print_response=False,
)
def set_NA(self, NA):
self.NA = NA
NA = str(int(NA * 100))
self.serial_connection.write_and_check(
"na." + NA + "\r", "Current NA is 0." + NA, read_delay=0.01, print_response=False
)
def set_color(self, color):
# (r,g,b), 0-1
r = int(255 * color[0])
g = int(255 * color[1])
b = int(255 * color[2])
self.serial_connection.write_and_check(
f"sc.{r}.{g}.{b}\r", f"Current color balance values are {r}.{g}.{b}", read_delay=0.01, print_response=False
)
def set_brightness(self, brightness):
# 0 to 100
brightness = str(int(255 * (brightness / 100.0)))
self.serial_connection.write_and_check(
f"sb.{brightness}\r", f"Current brightness value is {brightness}.", read_delay=0.01, print_response=False
)
def turn_on_bf(self):
self.serial_connection.write_and_check(f"bf\r", "-==-", read_delay=0.01, print_response=False)
def turn_on_dpc(self, quadrant):
self.serial_connection.write_and_check(f"dpc.{quadrant[0]}\r", "-==-", read_delay=0.01, print_response=False)
def turn_on_df(self):
self.serial_connection.write_and_check(f"df\r", "-==-", read_delay=0.01, print_response=False)
def set_illumination(self, illumination):
self.illumination = illumination
def clear(self):
self.serial_connection.write_and_check("x\r", "-==-", read_delay=0.01, print_response=False)
def turn_on_illumination(self):
if self.illumination is not None:
self.serial_connection.write_and_check(
f"{self.illumination}\r", "-==-", read_delay=0.01, print_response=False
)
time.sleep(self.turn_on_delay)
def turn_off_illumination(self):
self.clear()
class SciMicroscopyLEDArray_Simulation:
"""Wrapper for communicating with SciMicroscopy over serial"""
def __init__(self, SN, array_distance=50, turn_on_delay=0.03):
"""
Provide serial number
"""
self.serial_connection.open_ser()
self.check_about()
self.set_distance(array_distance)
self.set_brightness(1)
self.illumination = None
self.NA = 0.5
self.turn_on_delay = turn_on_delay
def write(self, command):
pass
def check_about(self):
pass
def set_distance(self, array_distance):
# array distance in mm
array_distance = str(int(array_distance))
def set_NA(self, NA):
self.NA = NA
NA = str(int(NA * 100))
def set_color(self, color):
# (r,g,b), 0-1
r = int(255 * color[0])
g = int(255 * color[1])
b = int(255 * color[2])
def set_brightness(self, brightness):
# 0 to 100
brightness = str(int(255 * (brightness / 100.0)))
def turn_on_bf(self):
pass
def turn_on_dpc(self, quadrant):
pass
def turn_on_df(self):
pass
def set_illumination(self, illumination):
pass
def clear(self):
pass
def turn_on_illumination(self):
pass
def turn_off_illumination(self):
pass
class CellX:
VALID_MODULATIONS = ["INT", "EXT Digital", "EXT Analog", "EXT Mixed"]
"""Wrapper for communicating with LDI over serial"""
def __init__(self, SN=""):
self.serial_connection = SerialDevice(
SN=SN,
baudrate=115200,
bytesize=serial.EIGHTBITS,
stopbits=serial.STOPBITS_ONE,
parity=serial.PARITY_NONE,
xonxoff=False,
rtscts=False,
dsrdtr=False,
)
self.serial_connection.open_ser()
self.power = {}
def turn_on(self, channel):
self.serial_connection.write_and_check(
"SOUR" + str(channel) + ":AM:STAT ON\r", "OK", read_delay=0.01, print_response=False
)
def turn_off(self, channel):
self.serial_connection.write_and_check(
"SOUR" + str(channel) + ":AM:STAT OFF\r", "OK", read_delay=0.01, print_response=False
)
def set_laser_power(self, channel, power):
if not (power >= 1 and power <= 100):
raise ValueError(f"Power={power} not in the range 1 to 100")
if channel not in self.power.keys() or power != self.power[channel]:
self.serial_connection.write_and_check(
"SOUR" + str(channel) + ":POW:LEV:IMM:AMPL " + str(power / 1000) + "\r",
"OK",
read_delay=0.01,
print_response=False,
)
self.power[channel] = power
else:
pass # power is the same
def set_modulation(self, channel, modulation):
if modulation not in CellX.VALID_MODULATIONS:
raise ValueError(f"Modulation '{modulation}' not in valid modulations: {CellX.VALID_MODULATIONS}")
self.serial_connection.write_and_check(
"SOUR" + str(channel) + ":AM:" + modulation + "\r", "OK", read_delay=0.01, print_response=False
)
def close(self):
self.serial_connection.close()
class CellX_Simulation:
"""Wrapper for communicating with LDI over serial"""
def __init__(self, SN=""):
self.serial_connection = SerialDevice(
SN=SN,
baudrate=115200,
bytesize=serial.EIGHTBITS,
stopbits=serial.STOPBITS_ONE,
parity=serial.PARITY_NONE,
xonxoff=False,
rtscts=False,
dsrdtr=False,
)
self.serial_connection.open_ser()
self.power = {}
def turn_on(self, channel):
pass
def turn_off(self, channel):
pass
def set_laser_power(self, channel, power):
if not (power >= 1 and power <= 100):
raise ValueError(f"Power={power} not in the range 1 to 100")
if channel not in self.power.keys() or power != self.power[channel]:
self.power[channel] = power
else:
pass # power is the same
def set_modulation(self, channel, modulation):
if modulation not in CellX.VALID_MODULATIONS:
raise ValueError(f"modulation '{modulation}' not in valid choices: {CellX.VALID_MODULATIONS}")
self.serial_connection.write_and_check(
"SOUR" + str(channel) + "AM:" + modulation + "\r", "OK", read_delay=0.01, print_response=False
)
def close(self):
pass
class FilterDeviceInfo:
"""
keep filter device information
"""
# default: 7.36
firmware_version = ""
# default: 250000
maxspeed = 0
# default: 900
accel = 0
class FilterController_Simulation:
"""
controller of filter device
"""
def __init__(self, _baudrate, _bytesize, _parity, _stopbits):
self.each_hole_microsteps = 4800
self.current_position = 0
self.current_index = 1
"""
the variable be used to keep current offset of wheel
it could be used by get the index of wheel position, the index could be '1', '2', '3' ...
"""
self.offset_position = 0
self.deviceinfo = FilterDeviceInfo()
def __del__(self):
pass
def do_homing(self):
self.current_position = 0
self.offset_position = 1100
def wait_homing_finish(self):
pass
def set_emission_filter(self, index):
self.current_index = index
pass
def get_emission_filter(self):
return 1
def start_homing(self):
pass
def complete_homing_sequence(self):
pass
def wait_for_homing_complete(self):
pass
class FilterControllerError(Exception):
"""Custom exception for FilterController errors."""
pass
class FilterController:
"""Controller for filter device."""
MICROSTEPS_PER_HOLE = 4800
OFFSET_POSITION = -8500
VALID_POSITIONS = set(range(1, 8))
MAX_RETRIES = 3
COMMAND_TIMEOUT = 1 # seconds
def __init__(self, serial_number: str, baudrate: int, bytesize: int, parity: str, stopbits: int):
self.log = squid.logging.get_logger(self.__class__.__name__)
self.current_position = 0
self.current_index = 1
self.serial = self._initialize_serial(serial_number, baudrate, bytesize, parity, stopbits)
self._configure_device()
def _initialize_serial(
self, serial_number: str, baudrate: int, bytesize: int, parity: str, stopbits: int
) -> serial.Serial:
ports = [p.device for p in list_ports.comports() if serial_number == p.serial_number]
if not ports:
raise ValueError(f"No device found with serial number: {serial_number}")
return serial.Serial(
ports[0],
baudrate=baudrate,
bytesize=bytesize,
parity=parity,
stopbits=stopbits,
timeout=self.COMMAND_TIMEOUT,
)
def _configure_device(self):
time.sleep(0.2)
self.firmware_version = self._get_device_info("/get version")
self._send_command_with_reply("/set maxspeed 250000")
self._send_command_with_reply("/set accel 900")
self.maxspeed = self._get_device_info("/get maxspeed")
self.accel = self._get_device_info("/get accel")
def __del__(self):
if hasattr(self, "serial") and self.serial.is_open:
self._send_command("/stop")
time.sleep(0.5)
self.serial.close()
def _send_command(self, cmd: str) -> Tuple[bool, str]:
"""
Send a command to the device and handle the response.
Args:
cmd (str): The command to send.
Returns:
Tuple[bool, str]: A tuple containing a success flag and the response message.
Raises:
FilterControllerError: If the command fails after maximum retries.
"""
if not self.serial.is_open:
raise RuntimeError("Serial port is not open")
for attempt in range(self.MAX_RETRIES):
try:
self.serial.write(f"{cmd}\n".encode("utf-8"))
response = self.serial.readline().decode("utf-8").strip()
success, message = self._parse_response(response)
if success:
return True, message
elif message.startswith("BUSY"):
time.sleep(0.1) # Wait a bit if the device is busy
continue
else:
# Log the error and retry
self.log.error(f"Command failed (attempt {attempt + 1}): {message}")
except serial.SerialTimeoutException:
self.log.error(f"Command timed out (attempt {attempt + 1})")
time.sleep(0.5) # Wait before retrying
raise FilterControllerError(f"Command '{cmd}' failed after {self.MAX_RETRIES} attempts")
def _parse_response(self, response: str) -> Tuple[bool, str]:
"""
Parse the response from the device.
Args:
response (str): The response string from the device.
Returns:
Tuple[bool, str]: A tuple containing a success flag and the parsed message.
"""
if not response:
return False, "No response received"
parts = response.split()
if len(parts) < 4:
return False, f"Invalid response format: {response}"
if parts[0].startswith("@"):
if parts[2] == "OK":
return True, " ".join(parts[3:])
else:
return False, " ".join(parts[2:])
elif parts[0].startswith("!"):
return False, f"Alert: {' '.join(parts[1:])}"
elif parts[0].startswith("#"):
return True, f"Info: {' '.join(parts[1:])}"
else:
return False, f"Unknown response format: {response}"