-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
3646 lines (3226 loc) · 186 KB
/
functions.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
# -*- coding: utf-8 -*-
import datetime
import os
import sys
import time
from decimal import Decimal
import qdarktheme
import serial.tools.list_ports
from PyQt6 import QtCore, QtGui, QtWidgets
from serial.tools.list_ports import comports
import math
import numpy as np
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT
from matplotlib.figure import Figure
from matplotlib.collections import LineCollection
import matplotlib.font_manager as font_manager
import logging.config
from settings import settings_log
import json
import global_hotkeys as hotkey
import resources_rc
icon_dict = {
"const_icon.png": "Constant",
"ramp_icon.png": "Ramp",
"stepped_icon.png": "Stepped",
"pulse_icon.png": "Pulse",
"bolus_icon.png": "Bolus",
"concentration_icon.png": "Concentration",
"gradient_icon.png": "Gradient",
"autofill_icon.png": "Autofill",
}
label_path_StepGuide_dict = {
"Constant": ["Format: INF|WD, rate, units, target(t/v)", "const_param.png"],
"Ramp": ["Format: INF|WD, rate r<sub>start</sub>, rate r<sub>end</sub>, target t", "ramp_param.png"],
"Stepped": ["Format: INF|WD, rate [r<sub>1</sub>, r<sub>2</sub>], target [t, steps]", "stepped_param.png"],
"Pulse": ["Format: INF|WD, rate [r<sub>1</sub>, r<sub>2</sub>], [v<sub>1</sub>, v<sub>2</sub>]| ["
"t<sub>1</sub>, t<sub>2</sub>], pulses", "pulse_param.png"],
"Bolus": ["Format: target t, target v", "bolus_param.png"],
"Concentration": ["Format: weight, rate, concentration[%], Dose|time lag", "concentration_param.png"],
"Gradient": ["Format: total rate, [addr.1-[%], addr.2-[%]...] , time|steps", "gradient_param.png"],
"Autofill": ["Format: INF/WD| WD/INF, [r<sub>1</sub>, r<sub>2</sub>], v per Cyc, total v/ Cyc",
"autofill_param.png"],
}
# stepGuide_ReMatch = {
# "Constant": "^(INF|WD)[,;]\s*(\d+)[,;]\s*(nl\/s|nl\/min|pl\/s|pl\/min|u\/s|u\/min|ml\/s|ml\/min)?$",
# "Ramp":,
# "Stepped":,
# "Pulse":,
# "Bolus":,
# "Concentration",
# "Gradient":,
# "Autofill":
# }
label_stepGuide_dict = {
"Constant": "Format: INF|WD, rate, units",
"Ramp": "Format: INF|WD, rate [r<sub>1</sub>, r<sub>2</sub>], target t",
"Stepped": "Format: INF|WD, rate [r<sub>1</sub>, r<sub>2</sub>], target [t, steps]",
"Pulse": "Format: INF|WD, rate [r<sub>1</sub>, r<sub>2</sub>], [v<sub>1</sub>, v<sub>2</sub>]| ["
"t<sub>1</sub>, t<sub>2</sub>], pulses",
"Bolus": "Format: target t, target v",
"Concentration": "Format: weight, rate, concentration[%], Dose|time lag",
"Gradient": "Format: total rate, [addr.1-[%], addr.2-[%]...] , time|steps",
"Autofill": "Format: INF/WD| WD/INF, [r<sub>1</sub>, r<sub>2</sub>], v per Cyc, total v/ Cyc",
}
import_dict_rename = {
"Constant": "Constant rate",
"Ramp": "Ramp rate",
"Stepped": "Stepped rate",
"Pulse": "Pulse flow",
"Bolus": "Bolus delivery",
"Concentration": "Concentration delivery",
"Gradient": "Gradient",
"Autofill": "Autofill",
}
# Configuration logging functionality
logging.config.dictConfig(settings_log.LOGGING_DIC)
logger_debug_console = logging.getLogger('logger1') # Console print
logger_info_console_file = logging.getLogger('logger2') # Console & file recording
logger_info_file = logging.getLogger('logger3')
# Logging module after packaging as an executable application
# 获取当前目录下的日志文件路径
# Set global warning filter for pyqtSignal, it still works though
# warnings.filterwarnings("ignore", category=UserWarning, message="Cannot find reference 'connect' in 'pyqtSignal | pyqtSignal'")
"""Class to be called in MainWindow to set up the port connection"""
# Bug to be solved: switch connection from a normally running port to a occupied port
class CheckSerialThread(QtCore.QThread):
CONNECTION_STATUS_CHANGED = QtCore.pyqtSignal(str)
SERIAL_OPENED = QtCore.pyqtSignal(bool)
PORT_PARAM_DICT = {}
PORT_PARAM_DICT_PREVIOUS = {}
TIMEOUT_COUNT = 0
MAX_TIMEOUT = 20
def __init__(self, ui, parent):
super().__init__(parent)
self.read_send_thread = None
self.send_thread = None
self.read_thread = None
self.port_param_dict_func = {}
self.ser = None
self.ui = ui
self.parent = parent
self.connected = False
self.auto_reconnect = True
self._pause_thread = False # 用于暂停串口检测线程的标志
self.wait_condition = QtCore.QWaitCondition()
self.mutex = QtCore.QMutex()
self.mutex_sub = QtCore.QMutex()
self.auto_reconnect_str = None
self.flag_auto_reconnect = True
def run(self):
self.mutex.lock()
try:
if self._pause_thread and not self.auto_reconnect:
self.wait_condition.wait(self.mutex)
else:
# Get serial parameters from the dialog
self.port_param_dict_func = CheckSerialThread.PORT_PARAM_DICT
# print(f'dict from run: {self.port_param_dict_func}\n') # 有输出
if self.port_param_dict_func['port'] != '' and not self.connected:
self.CONNECTION_STATUS_CHANGED.emit(f"Opening port {self.port_param_dict_func['port']}.")
try:
self.ser = serial.Serial(**self.port_param_dict_func)
# Config buffer zone for port read and write, to avoid crashing of program
self.ser.set_buffer_size(rx_size=4096, tx_size=4096)
# self.start_read_thread()
self.start_read_send_thread()
# self.start_send_thread()
self.ser.flushInput()
self.ser.flushOutput()
# print('连接成功的参数:', self.port_param_dict_func)
# 连接成功后清空类变量中的参数字典
CheckSerialThread.PORT_PARAM_DICT = {}
self.connected = True # 设置连接成功的标志
# print(f'dict from run: {self.port_param_dict_func}\n')
self.CONNECTION_STATUS_CHANGED.emit(
f"Port {self.ser.port} successfully opened. [{self.ser.baudrate}, {self.ser.bytesize}, {self.ser.parity}, {self.ser.stopbits}]")
self.SERIAL_OPENED.emit(True)
# CheckSerialThread.return_ser_status(self)
except serial.SerialException as e:
if 'PermissionError' in str(e):
self.CONNECTION_STATUS_CHANGED.emit(
f"Unable to open the port {self.port_param_dict_func['port']}. Please ensure the port is available. {str(e)}")
# Try to open again if the port is released within 10 seconds
self.connected = False
self.SERIAL_OPENED.emit(False)
# self.timer_reconnect = QtCore.QTimer()
# self.timer_reconnect.timeout.connect(self.auto_reconnect_from_failure)
# self.timer_reconnect.moveToThread(self)
# self.timer_reconnect.timeout.connect(self.auto_reconnect_from_failure)
# self.timer_reconnect.start(1000)
# self.exec()
# QtCore.QThread.exec(self)
# timer_reconnect_thread.start()
# self.timer_resume_start(e)
# self.timer_reconnect.start(1000)
# self.pause_thread()
# print('self.isRunning()', self.isRunning())
self.auto_reconnect_from_failure(e, self.port_param_dict_func)
else:
# print(e.args[0].split(":")[1])
self.CONNECTION_STATUS_CHANGED.emit(
f"Unable to configure the port {self.port_param_dict_func['port']}. {e.args[0].split(':')[1]}")
self.connected = False
self.SERIAL_OPENED.emit(False)
self._pause_thread = False
self.auto_reconnect = True
# self.auto_reconnect_from_failure()
elif self.port_param_dict_func['port'] == '':
self.CONNECTION_STATUS_CHANGED.emit('Fatal Error!')
self.SERIAL_OPENED.emit(False)
# time.sleep(0.5)
finally:
self.mutex.unlock()
def set_port_params(self, dict_port):
if CheckSerialThread.PORT_PARAM_DICT != dict_port: # 从更新参数后恢复
self.resume_thread()
self._pause_thread = False
self.auto_reconnect = True
self.disconnect_from_port(auto_reconnect=True, _pause_thread=False)
CheckSerialThread.PORT_PARAM_DICT = dict_port
self.start(auto_reconnect=True, _pause_thread=False)
if self._pause_thread and not self.auto_reconnect: # 从stop恢复
self.resume_thread()
CheckSerialThread.PORT_PARAM_DICT = dict_port
self.start(auto_reconnect=True, _pause_thread=False)
elif not self._pause_thread and self.auto_reconnect: # 从重连超时恢复
self.resume_thread()
CheckSerialThread.PORT_PARAM_DICT = dict_port
self.start(auto_reconnect=True, _pause_thread=False)
else:
pass
def start(self, auto_reconnect=True, _pause_thread=False):
self.auto_reconnect = auto_reconnect
self._pause_thread = _pause_thread
# print('start!!', self.auto_reconnect, self._pause_thread)
super().start()
def disconnect_from_port(self, auto_reconnect=None, _pause_thread=None):
try:
if self.connected and self.ser is not None and self.ser.is_open:
self.CONNECTION_STATUS_CHANGED.emit(f"Port {self.ser.port} closed.")
self.ser.close()
self.stop_read_send_thread()
self.ser = None
self.connected = False
self.SERIAL_OPENED.emit(False)
# 自动重连接√,线程休眠x : 由方法调用
if auto_reconnect and not _pause_thread:
self.auto_reconnect = True
self._pause_thread = False
# 自动重连x,线程休眠√ : 由按钮断开
elif not auto_reconnect and _pause_thread:
self.auto_reconnect = False
self._pause_thread = True
self.SERIAL_OPENED.emit(False)
CheckSerialThread.PORT_PARAM_DICT = {}
CheckSerialThread.PORT_PARAM_DICT_PREVIOUS = {}
else:
# self.ser is None时:通过stop按钮停止失败自动重连
CheckSerialThread.TIMEOUT_COUNT = CheckSerialThread.MAX_TIMEOUT
except Exception as e:
# logger_info_console_file.info(str(e))
logger_info_console_file.info(e)
self.CONNECTION_STATUS_CHANGED.emit(f"Failed to close port {self.ser.port}: " + str(e))
self.connected = False
self.ser = None
self.SERIAL_OPENED.emit(False)
def pause_thread(self):
self._pause_thread = True
def resume_thread(self):
self.auto_reconnect = True
self._pause_thread = False
self.wait_condition.wakeAll()
def timer_resume_start(self, error_port):
# print('timer_resume_start called!')
if error_port:
# print(error_port)
# self.timer_reconnect.timeout.disconnect()
# self.timer_reconnect.timeout.connect(self.auto_reconnect_from_failure)
# self.timer_reconnect.start(1000)
# print(self.timer_reconnect.timerId())
pass
# def auto_reconnect_from_failure(self):
# # Using QTimer to substitute time.sleep(), deprecated due to compatibility problem of QTimer in QThread
# print('auto_reconnect_from_failure called!')
# dict_port = CheckSerialThread.PORT_PARAM_DICT
# print(self.count)
# if self.count < 10:
# if self.ser is None and not self.connected:
# self.CONNECTION_STATUS_CHANGED.emit(
# f"Try to reconnect port {self.port_param_dict_func['port']}, timeout : {int(10 - self.count)}s.")
# try:
# self.ser = serial.Serial(**dict_port)
# except Exception as e:
# logger_info_console_file.info(f"1111111 {str(e)}")
# finally:
# self.count += 1
# # self.timer_reconnect.start(500)
# self.timer_reconnect.singleShot(500, self.auto_reconnect_from_failure)
# print(self.count)
# else:
# self.connected = True
# self.ser.set_buffer_size(rx_size=4096, tx_size=4096)
# self.start_read_send_thread()
# self.ser.flushInput()
# self.ser.flushOutput()
# self.CONNECTION_STATUS_CHANGED.emit(f"Successfully reconnected to port {self.ser.port}.")
# self.SERIAL_OPENED.emit(True)
# CheckSerialThread.PORT_PARAM_DICT = {}
# return
# else:
# self.timer_reconnect.stop()
# self.count = 0
# self.CONNECTION_STATUS_CHANGED.emit(f"Reconnection to port {dict_port['port']} failed, please check "
# f"the port usage.")
# self.SERIAL_OPENED.emit(False)
# self.ser = None
# self._pause_thread = True
# self.auto_reconnect = False
# # break
# # except Exception as e:
# # count = 0
# # print(count)
# #
# # print(self.count)
# # # finally:
# # self.count += 1
#
# # time.sleep(0.5)
# # continue
# # self.auto_reconnect_from_failure(failure_str=failure_str, dict_port=dict_port)
# # else:
# # self.count = 0
# # self.CONNECTION_STATUS_CHANGED.emit(f"Reconnection to port {dict_port['port']} failed, please check "
# # f"the port usage.")
# # self.SERIAL_OPENED.emit(False)
# # self.ser = None
# # self._pause_thread = False
# # self.auto_reconnect = True
#
def auto_reconnect_from_failure(self, failure_str, dict_port):
# 通过已连接的串口向被占用串口切换的时候,要停止当前的线程,否则会造成time.sleep()抢占线程资源,导致无法自动连接
self._pause_thread = True
self.auto_reconnect = False
if failure_str:
# print(str(failure_str).split(':')[1])
self.mutex_sub.lock()
CheckSerialThread.TIMEOUT_COUNT = 0
while (
self.ser is None or not self.connected) and CheckSerialThread.TIMEOUT_COUNT < CheckSerialThread.MAX_TIMEOUT:
self.CONNECTION_STATUS_CHANGED.emit(
f"Attempting to reopen port {self.port_param_dict_func['port']}, {str(failure_str).split(':')[1]}, timeout : {int(CheckSerialThread.MAX_TIMEOUT / 2 - CheckSerialThread.TIMEOUT_COUNT * 0.5)}s.")
try:
self.ser = serial.Serial(**dict_port)
self.ser.set_buffer_size(rx_size=4096, tx_size=4096)
self.connected = True
self.start_read_send_thread()
self.ser.flushInput()
self.ser.flushOutput()
self.CONNECTION_STATUS_CHANGED.emit(
f"Port {self.ser.port} successfully opened. [{self.ser.baudrate}, {self.ser.bytesize}, {self.ser.parity}, {self.ser.stopbits}]")
self.SERIAL_OPENED.emit(True)
CheckSerialThread.PORT_PARAM_DICT = {}
break
except Exception as e:
# logger_info_console_file.info(f"{str(e)}")
logger_info_console_file.info(f"{str(e)}")
CheckSerialThread.TIMEOUT_COUNT += 1
time.sleep(0.5)
else:
CheckSerialThread.TIMEOUT_COUNT = 0
self.CONNECTION_STATUS_CHANGED.emit(f"Reopen port {dict_port['port']} failed, please check "
f"the port usage.")
self.SERIAL_OPENED.emit(False)
self.ser = None
self.connected = False
self._pause_thread = False
self.auto_reconnect = True
self.mutex_sub.unlock()
# @staticmethod
def get_ser(self):
return self.ser
def start_read_thread(self):
pass
# self.read_thread = ReadDataFromPort(ser=self.ser, ui_main=self.ui)
# self.read_thread.start()
# if self.read_thread.isRunning():
# print('read_thread running', self.read_thread.ser)
def stop_read_thread(self):
pass
# if self.read_thread:
# self.read_thread.terminate()
def start_send_thread(self):
# self.send_thread = SendDataToPort(check_serial_thread=None, read_data_from_port=None, ser=self.ser,
# ui_main=self.ui)
# self.send_thread.start()
# if self.send_thread.isRunning():
# print('send_thread running!', self.send_thread.ser)
pass
def stop_send_thread(self):
pass
# if self.send_thread:
# self.send_thread.terminate()
def start_read_send_thread(self):
self.read_send_thread = ReadSendPort(ser=self.ser, ui_main=self.ui, parent=None)
self.read_send_thread.start()
def stop_read_send_thread(self):
if self.read_send_thread:
# self.read_send_thread.terminate()
self.read_send_thread.stop()
self.read_send_thread.wait()
# Check port usage: deprecated
@staticmethod
def port_is_in_use(port: str) -> bool:
for info in serial.tools.list_ports.comports():
# logger_debug_console.info(info.device)
if info.device == port:
return True
return False
# 为避免与串口检测线程冲突造成阻塞,另起两个线程,分别负责串口数据的发送和接收
# class SendDataToPort(QtCore.QThread):
# ENCODE_TYPE = 'utf-8'
#
# def __init__(self, parent, check_serial_thread, receive_status=None, ser=None, ui_main=None):
# super().__init__(parent)
# self.force_level = None
# self.run_commands_set_ButtonClear = {}
# self.mutex = QtCore.QMutex()
# self.mutex_sub = QtCore.QMutex()
# self.check_serial_thread = check_serial_thread
# # self.read_data_from_port = read_data_from_port
# self.ser = ser
# # self.read_data_from_port = read_data_from_port
# # self.read_data_from_port = ReadDataFromPort(self.check_serial_thread.ser)
# self.ui = ui_main
# self.receive_status = receive_status
# self.run_commands_set = {}
# self.run_commands_set_Syrm = {}
# self.run_commands_set_INF = {}
# self.run_commands_set_WD = {}
# self.run_commands_set_GetResponse_INF = {}
# self.run_commands_set_GetResponse_WD = {}
# self.run_commands_set_ClearTarget = {}
# self.run_commands_set_Clear_INF = {}
# self.run_commands_set_Clear_WD = {}
# self.run_commands_set_Ramp = {}
# self.status_str = None
# self.args_list = None
# self.timer_run = QtCore.QTimer()
# self.running_flag = True
# # self.timer_run.timeout.connect(lambda: self.ser_quick_mode_command_set(ui, setups_dict_quick_mode))
#
# # self.read_data_from_port.receive_status.connect(lambda status: self.send_thread_start(status))
#
# def run(self):
# print('Send thread running: ', self.isRunning())
# print(self.ser)
# print(self.receive_status)
# if self.ser is None:
# # self.quit()
# # return
# pass
# while True:
# # self.mutex.lock()
# try:
# pass
# # print('self.receive_status from send class!', self.receive_status)
# # self.read_data_from_port.receive_status.connect(self.handle_receive_status)
# # else:
# # pass
# # self.read_data_from_port.receive_status.connect(self.handle_receive_status)
# # print(self.status_str)
# except Exception as e:
# logger_debug_console.info(e)
#
# def ser_command_catalog(self):
# # print('ser_command_catalog called!')
# # print('From send thread: ', self.ser)
# # print(self.check_serial_thread.ser, type(self.check_serial_thread.ser))
# # print(self.check_serial_thread, self.read_data_from_port)
# # self.status_str = self.read_data_from_port.receive_status()
# print(self.ser)
# self.mutex_sub.lock()
# self.running_flag = False
# if isinstance(self.ser, serial.Serial):
# # self.start()
# self.ser.write('@cat\r\n'.encode(SendDataToPort.ENCODE_TYPE))
# # print(SendDataToPort.ENCODE_TYPE)
# else:
# pass
# self.mutex_sub.unlock()
#
# def ser_command_tilt(self):
# self.mutex_sub.lock()
# if isinstance(self.check_serial_thread.ser, serial.Serial):
# self.check_serial_thread.ser.write('@tilt\r\n'.encode(SendDataToPort.ENCODE_TYPE))
# else:
# logger_info_console_file.warning(
# f"self.ser is not a serial.Serial object, it's {type(self.check_serial_thread.ser)}")
# self.mutex_sub.unlock()
#
# def get_set_address(self, ui):
# self.mutex_sub.lock()
# if isinstance(self.check_serial_thread.ser, serial.Serial):
# if ui.address_input.text() and ui.address_input.text() != '':
# # print('addr.', ui.address_input.text())
# self.check_serial_thread.ser.write(
# ('@addr. ' + str(ui.address_input.text()) + '\r\n').encode(SendDataToPort.ENCODE_TYPE))
# else:
# self.check_serial_thread.ser.write(('@addr. ' + '\r\n').encode(SendDataToPort.ENCODE_TYPE))
# else:
# pass
# self.mutex_sub.unlock()
#
# def send_command_manual(self, ui):
# # print('send_command_manual called!')
# self.mutex_sub.lock()
# if self.check_serial_thread.ser and isinstance(self.check_serial_thread.ser, serial.Serial):
# if ui.lineEdit_send_toPump.currentText() and ui.lineEdit_send_toPump.currentText() != '':
# current_time = QtCore.QDateTime.currentDateTime().toString("[hh:mm:ss]")
# str_to_send = '@' + ui.lineEdit_send_toPump.currentText() + '\r\n'
# try:
# self.check_serial_thread.ser.write(str_to_send.encode(SendDataToPort.ENCODE_TYPE))
# ui.commands_sent.moveCursor(QtGui.QTextCursor.MoveOperation.End)
# # ui.commands_sent.insertHtml(f"<b>{current_time} >></b>\r\n{str_to_send}")
# ui.commands_sent.append(f"{current_time} >>\r\n{str_to_send}")
# except Exception as e:
# logger_info_console_file.warning(e)
# # 如果数据未能成功写入,并且超过了缓冲区最大限制,则重置buffer
# if len(self.check_serial_thread.ser.out_waiting) > 4096:
# self.check_serial_thread.ser.reset_output_buffer()
# ui.commands_sent.append(f"{current_time} >>\r\nBuffer overflow, clearing buffer...")
# self.check_serial_thread.ser.write(str_to_send.encode(SendDataToPort.ENCODE_TYPE))
# ui.commands_sent.moveCursor(QtGui.QTextCursor.MoveOperation.End)
# ui.commands_sent.append(f"{current_time} >>\r\n{str_to_send}")
# # 将输入唯一保存在下拉列表中
# if ui.lineEdit_send_toPump.currentText() not in [ui.lineEdit_send_toPump.itemText(i) for i in
# range(ui.lineEdit_send_toPump.count())]:
# ui.lineEdit_send_toPump.addItem(ui.lineEdit_send_toPump.currentText())
# else:
# pass
# else:
# pass
# else:
# pass
# self.mutex_sub.unlock()
#
# def ser_bgl_level(self, ui):
# value = ui.bgLight_Slider.value()
# self.mutex_sub.lock()
# current_time = QtCore.QDateTime.currentDateTime().toString("[hh:mm:ss]")
# if isinstance(self.check_serial_thread.ser, serial.Serial):
# self.check_serial_thread.ser.write(('@dim ' + str(value) + '\r\n').encode(SendDataToPort.ENCODE_TYPE))
# ui.commands_sent.moveCursor(QtGui.QTextCursor.MoveOperation.End)
# # ui.commands_sent.insertHtml(f"<b>{current_time} >></b>\r\n{str_to_send}")
# ui.commands_sent.append(f"{current_time} >>\r\nBackground light set to: {str(value)} %")
# else:
# logger_info_console_file.warning(
# f"self.ser is not a serial.Serial object, it's {type(self.check_serial_thread.ser)}")
# pass
# self.mutex_sub.unlock()
#
# def ser_force_limit(self, ui):
# value = ui.forceLimit_Slider.value()
# self.mutex_sub.lock()
# current_time = QtCore.QDateTime.currentDateTime().toString("[hh:mm:ss]")
# if isinstance(self.check_serial_thread.ser, serial.Serial):
# self.check_serial_thread.ser.write(('@force ' + str(value) + '\r\n').encode(SendDataToPort.ENCODE_TYPE))
# ui.commands_sent.moveCursor(QtGui.QTextCursor.MoveOperation.End)
# ui.commands_sent.append(f"{current_time} >>\r\nForce limit set to: {str(value)} %")
# else:
# logger_info_console_file.warning(
# f"self.ser is not a serial.Serial object, it's {type(self.check_serial_thread.ser)}")
# pass
# self.mutex_sub.unlock()
#
# @staticmethod
# def ser_bgl_label_show(ui):
# value = ui.bgLight_Slider.value()
# ui.bgLight_Label.setText("BG-Light: " + str(value) + "[%]")
#
# @staticmethod
# def ser_force_label_show(ui):
# value = ui.forceLimit_Slider.value()
# ui.forceLimit_Label.setText("Force Limit: " + str(value) + "[%]")
#
# def fast_forward_btn(self):
# if isinstance(self.check_serial_thread.ser, serial.Serial):
# self.check_serial_thread.ser.write('@run\r\n'.encode(SendDataToPort.ENCODE_TYPE))
# else:
# pass
#
# def rewind_btn(self):
# if isinstance(self.check_serial_thread.ser, serial.Serial):
# self.check_serial_thread.ser.write('@rrun\r\n'.encode(SendDataToPort.ENCODE_TYPE))
# else:
# pass
#
# def release_to_stop(self):
# if isinstance(self.check_serial_thread.ser, serial.Serial):
# self.check_serial_thread.ser.write('@stop\r\n'.encode(SendDataToPort.ENCODE_TYPE))
# else:
# pass
#
# def ser_quick_mode_command_set(self, ui, setups_dict_quick_mode):
# self.mutex.lock()
# update_combox_syr_enabled(ui, setups_dict_quick_mode)
# self.force_level = force_level_recommendation(self.ui)
# self.run_commands_set = {}
# self.run_commands_set_Syrm = {}
# self.run_commands_set_INF = {}
# self.run_commands_set_WD = {}
# self.run_commands_set_GetResponse_INF = {"Infused volume": "@ivolume\r\n",
# "Infused time": "@itime\r\n",
# "Motor rate": "@crate\r\n",
# "Infusing rate": "@irate\r\n"}
# self.run_commands_set_GetResponse_WD = {"Withdrawn volume": "@wvolume\r\n",
# "Withdrawn time": "@wtime\r\n",
# "Motor rate": "@crate\r\n",
# "Withdraw rate": "@wrate\r\n"}
# self.run_commands_set_ClearTarget = {"Clear target t:": "@cttime\r\n",
# "Clear target V:": "@ctvolume\r\n",
# "Writes to memory: OFF:": "@NVRAM\r\n",
# "Default force level": f"@force {self.force_level}\r\n"}
# if all(value is not None and value != '' for key, value in setups_dict_quick_mode.items() if
# key in ['Run Mode', 'Syringe Info', 'Flow Parameter']):
# # 注射器选择指令
# self.run_commands_set_Syrm['Syringe Type'] = {
# 'prompt': ' >>Syringe selected: ' + setups_dict_quick_mode['Syringe Info']['Selected Syringe'],
# 'command': '@syrm' + ' ' + setups_dict_quick_mode['Syringe Info']['Selected Syringe'] + '\r\n'}
#
# if setups_dict_quick_mode['Run Mode'] == 'INF':
# self.run_commands_set_INF['Rate INF'] = {
# 'prompt': ' >>Infusion rate: ' + setups_dict_quick_mode['Flow Parameter']['Frate INF'],
# 'command': '@irate' + ' ' + setups_dict_quick_mode['Flow Parameter']['Frate INF'] + '\r\n'}
# if 'l' in setups_dict_quick_mode['Flow Parameter']['Target INF']:
# self.run_commands_set_INF['Target INF'] = {
# "prompt": " >>Target Volume: " + setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'],
# "command": '@tvolume' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'] + '\r\n'}
# else:
# self.run_commands_set_INF['Target INF'] = {
# "prompt": ' >>Target Time: ' + setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'],
# "command": '@ttime' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'] + '\r\n'}
# self.run_commands_set_INF['Run Code INF'] = {"prompt": ' >>Infusion running:', "command": "@irun\r\n"}
# # self.run_commands_set_INF['Motor rate INF'] = 'crate\r\n'
# # self.run_commands_set_INF['Volume INF'] = 'ivolume\r\n'
# elif setups_dict_quick_mode['Run Mode'] == 'WD':
# self.run_commands_set_WD['Rate WD'] = {
# 'prompt': ' >>Withdraw rate: ' + setups_dict_quick_mode['Flow Parameter']['Frate WD'],
# 'command': '@wrate' + ' ' + setups_dict_quick_mode['Flow Parameter']['Frate WD'] + '\r\n'}
# if 'l' in setups_dict_quick_mode['Flow Parameter']['Target WD']:
# self.run_commands_set_WD['Target WD'] = {
# "prompt": " >>Target Volume: " + setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'],
# "command": '@tvolume' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'] + '\r\n'}
# else:
# self.run_commands_set_WD['Target WD'] = {
# "prompt": ' >>Target Time: ' + setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'],
# "command": '@ttime' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'] + '\r\n'}
# self.run_commands_set_WD['Run Code WD'] = {"prompt": ' >>Withdraw running:', "command": "@wrun\r\n"}
# # self.run_commands_set_WD['Motor rate WD'] = 'crate\r\n'
# # self.run_commands_set_WD['Volume WD'] = 'wvolume\r\n'
# # print('输出命令:', run_commands_set)
# elif setups_dict_quick_mode['Run Mode'] == 'INF/ WD':
# self.run_commands_set_INF['Rate INF'] = {
# 'prompt': ' >>Infusion rate: ' + setups_dict_quick_mode['Flow Parameter']['Frate INF'],
# 'command': '@irate' + ' ' + setups_dict_quick_mode['Flow Parameter']['Frate INF'] + '\r\n'}
# if 'l' in setups_dict_quick_mode['Flow Parameter']['Target INF']:
# self.run_commands_set_INF['Target INF'] = {
# "prompt": " >>Target Volume: " + setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'],
# "command": '@tvolume' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'] + '\r\n'}
# else:
# self.run_commands_set_INF['Target INF'] = {
# "prompt": ' >>Target Time: ' + setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'],
# "command": '@ttime' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'] + '\r\n'}
# self.run_commands_set_INF['Run Code INF'] = {"prompt": ' >>Infusion running:', "command": "@irun\r\n"}
# # self.run_commands_set_INF['Motor rate INF'] = 'crate\r\n'
# # self.run_commands_set_INF['Volume INF'] = 'ivolume\r\n'
# # WD
# self.run_commands_set_WD['Rate WD'] = {
# 'prompt': ' >>Withdraw rate: ' + setups_dict_quick_mode['Flow Parameter']['Frate WD'],
# 'command': '@wrate' + ' ' + setups_dict_quick_mode['Flow Parameter']['Frate WD'] + '\r\n'}
# if 'l' in setups_dict_quick_mode['Flow Parameter']['Target WD']:
# self.run_commands_set_WD['Target WD'] = {
# "prompt": " >>Target Volume: " + setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'],
# "command": '@tvolume' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'] + '\r\n'}
# else:
# self.run_commands_set_WD['Target WD'] = {
# "prompt": ' >>Target Time: ' + setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'],
# "command": '@ttime' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'] + '\r\n'}
# self.run_commands_set_WD['Run Code WD'] = {"prompt": ' >>Withdraw running:', "command": "@wrun\r\n"}
# # self.run_commands_set_WD['Motor rate WD'] = 'crate\r\n'
# # self.run_commands_set_WD['Volume WD'] = 'wvolume\r\n'
# elif setups_dict_quick_mode['Run Mode'] == 'WD/ INF':
# self.run_commands_set_WD['Rate WD'] = {
# 'prompt': ' >>Withdraw rate: ' + setups_dict_quick_mode['Flow Parameter']['Frate WD'],
# 'command': '@wrate' + ' ' + setups_dict_quick_mode['Flow Parameter']['Frate WD'] + '\r\n'}
# if 'l' in setups_dict_quick_mode['Flow Parameter']['Target WD']:
# self.run_commands_set_WD['Target WD'] = {
# "prompt": " >>Target Volume: " + setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'],
# "command": '@tvolume' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'] + '\r\n'}
# else:
# self.run_commands_set_WD['Target WD'] = {
# "prompt": ' >>Target Time: ' + setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'],
# "command": '@ttime' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target WD'] + '\r\n'}
# self.run_commands_set_WD['Run Code WD'] = {"prompt": ' >>Withdraw running:', "command": "@wrun\r\n"}
# # self.run_commands_set_WD['Motor rate WD'] = 'crate\r\n'
# # self.run_commands_set_WD['Volume WD'] = 'wvolume\r\n'
# # INF
# self.run_commands_set_INF['Rate INF'] = {
# 'prompt': ' >>Infusion rate: ' + setups_dict_quick_mode['Flow Parameter']['Frate INF'],
# 'command': '@irate' + ' ' + setups_dict_quick_mode['Flow Parameter']['Frate INF'] + '\r\n'}
# if 'l' in setups_dict_quick_mode['Flow Parameter']['Target INF']:
# self.run_commands_set_INF['Target INF'] = {
# "prompt": " >>Target Volume: " + setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'],
# "command": '@tvolume' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'] + '\r\n'}
# else:
# self.run_commands_set_INF['Target INF'] = {
# "prompt": ' >>Target Time: ' + setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'],
# "command": '@ttime' + ' ' +
# setups_dict_quick_mode['Flow Parameter'][
# 'Target INF'] + '\r\n'}
# self.run_commands_set_INF['Run Code INF'] = {"prompt": ' >>Infusion running:', "command": "@irun\r\n"}
# # self.run_commands_set_INF['Motor rate INF'] = 'crate\r\n'
# # self.run_commands_set_INF['Volume INF'] = 'ivolume\r\n'
# else:
# pass
#
# if not isinstance(self.check_serial_thread.ser, serial.Serial):
# QtWidgets.QMessageBox.information(ui.Run_button_quick, 'Port not connected.',
# 'Please check the port connection.')
# else:
# if setups_dict_quick_mode['Run Mode'] == 'INF':
# self.args_list = (self.ui, self.status_str, 0.8, 0.1, self.run_commands_set_ClearTarget,
# self.run_commands_set_Syrm, self.run_commands_set_INF,
# self.run_commands_set_GetResponse_INF)
# self.send_run_commands(*self.args_list)
# self.timer_run.timeout.connect(functools.partial(self.send_run_commands, *self.args_list))
# elif setups_dict_quick_mode['Run Mode'] == 'WD':
# self.args_list = (self.ui, self.status_str, 0.8, 0.1, self.run_commands_set_ClearTarget,
# self.run_commands_set_Syrm, self.run_commands_set_WD,
# self.run_commands_set_GetResponse_WD)
# self.send_run_commands(*self.args_list)
# self.timer_run.timeout.connect(functools.partial(self.send_run_commands, *self.args_list))
# elif setups_dict_quick_mode['Run Mode'] == 'INF/ WD':
# self.args_list = (self.ui, self.status_str, 0.8, 0.1, self.run_commands_set_ClearTarget,
# self.run_commands_set_Syrm, self.run_commands_set_INF,
# self.run_commands_set_GetResponse_INF, self.run_commands_set_ClearTarget,
# self.run_commands_set_WD, self.run_commands_set_GetResponse_WD)
# self.send_run_commands(*self.args_list)
# self.timer_run.timeout.connect(functools.partial(self.send_run_commands, *self.args_list))
# elif setups_dict_quick_mode['Run Mode'] == 'WD/ INF':
# self.args_list = (self.ui, self.status_str, 0.8, 0.1, self.run_commands_set_ClearTarget,
# self.run_commands_set_Syrm, self.run_commands_set_WD,
# self.run_commands_set_GetResponse_WD, self.run_commands_set_ClearTarget,
# self.run_commands_set_INF, self.run_commands_set_GetResponse_INF)
# self.send_run_commands(*self.args_list)
# self.timer_run.timeout.connect(functools.partial(self.send_run_commands, *self.args_list))
# else:
# pass
#
# self.mutex.unlock()
#
# def send_run_commands(self, ui, status_str, time_run, time_response, *run_dict):
# self.timer_run.start()
# current_time = QtCore.QDateTime.currentDateTime().toString("[hh:mm:ss]")
# for dict_run in run_dict:
# if status_str in (None, 'Continue'):
# if not isinstance(list(dict_run.values())[0], dict): # clear
# for key, value in dict_run.items():
# ui.commands_sent.append(f"{current_time} >>{key}:")
# # print(f"{current_time} >>{value}:")
# self.check_serial_thread.ser.write(value.encode(SendDataToPort.ENCODE_TYPE))
# # QtCore.QCoreApplication.instance().processEvents()
# # time.sleep(time_run)
# # 用QTimer 代替原来的time.sleep()
# self.timer_run.singleShot(time_run, QtCore.QCoreApplication.processEvents)
# logger_debug_console.debug(status_str)
# else:
# for value in dict_run.values():
# ui.commands_sent.append(f"{current_time}{value['prompt']}")
# # print(f"{current_time}{value['prompt']}")
# self.check_serial_thread.ser.write(value['command'].encode(SendDataToPort.ENCODE_TYPE))
# # QtCore.QCoreApplication.instance().processEvents()
# # time.sleep(time_run)
# self.timer_run.singleShot(time_run, QtCore.QCoreApplication.processEvents)
# # 运行到commands_set_INF/WD的'irun/wrun'时,响应会变为:'>'或者'<' || 'INF running', 'WD running'
# logger_debug_console.debug(status_str)
# elif status_str in ('INF running', 'WD running'): # 每0.1s向pump发送获取四个参数的命令
# if isinstance(list(dict_run.values())[0], str):
# while True:
# commands = ''.join(dict_run.values())
# # print('commands', commands)
# logger_debug_console.info(f"commands: {commands}")
# self.check_serial_thread.ser.write(commands.encode(SendDataToPort.ENCODE_TYPE))
# # QtCore.QCoreApplication.instance().processEvents()
# # time.sleep(time_response)
# self.timer_run.singleShot(time_response, QtCore.QCoreApplication.processEvents)
# logger_debug_console.debug(status_str)
# elif status_str == 'Target reached':
# logger_debug_console.debug(status_str)
# continue
# elif status_str == 'STOP':
# self.timer_run.stop()
# logger_debug_console.debug(status_str)
# break
#
# def clear_from_button(self, ui):
# self.run_commands_set_Clear_INF = {"Clear infused time": "@citime\r\n",
# "Clear infused volume": "@civolume\r\n"}
# self.run_commands_set_Clear_WD = {"Clear withdrawn time": "@cwtime\r\n",
# "Clear withdrawn volume": "@cwvolume\r\n"}
# self.run_commands_set_ButtonClear = {"Clear target t:": "@cttime\r\n",
# "Clear target V:": "@ctvolume\r\n"}
# current_time = QtCore.QDateTime.currentDateTime().toString("[hh:mm:ss]")
# for key, value in self.run_commands_set_ButtonClear.items():
# # print(f"{current_time} >>{key}\r\n")
# if isinstance(self.check_serial_thread.ser, serial.Serial):
# # ui.commands_sent.append(f"{current_time} >>{key}")
# self.check_serial_thread.ser.write(value.encode(SendDataToPort.ENCODE_TYPE))
# QtCore.QCoreApplication.instance().processEvents()
# time.sleep(0.1)
# else:
# pass
#
# @staticmethod
# def set_encode_format(ui, encode_sender):
# if encode_sender == ui.actionUTF_8:
# SendDataToPort.ENCODE_TYPE = 'utf-8'
# elif encode_sender == ui.actionASCII:
# SendDataToPort.ENCODE_TYPE = 'ascii'
# return SendDataToPort.ENCODE_TYPE
#
# def send_thread_start(self, status):
# if status and status != '':
# self.return_status(status)
# self.start()
# super().start()
#
# def return_status(self, status):
# self.receive_status = status
# return status
#
#
# class ReadDataFromPort(QtCore.QThread):
# receive_status = QtCore.pyqtSignal(str)
# # read_running = QtCore.pyqtSignal(bool)
# # Enable selection of encoding/ decoding format
# DECODE_STYLE = 'NoLF' # 默认结尾标识:无换行符
# __LINE_FEED_TYPE = (b':', b'<', b'>', b'*', b'T*') # Default no line feed following end identifier
# DECODE_TYPE = 'utf-8'
#
# def __init__(self, ser, ui_main=None, parent=None):
# super().__init__(parent)
# self.mutex = QtCore.QMutex()
# self.mutex_sub = QtCore.QMutex()
# self.ui = ui_main
# self.ser = ser
# self.__response = None
# self.__RECEIVE_STATUS = None
# self.send_thread = None
# # self.receive_status.connect(self.print_receive_status)
# # self.read_running.connect(self.call_send_thread)
#
# @staticmethod
# def set_line_feed_style(ui, sender_check):
# if sender_check == ui.actionNo_line_feed:
# ReadDataFromPort.__LINE_FEED_TYPE = (b':', b'<', b'>', b'*', b'T*')
# ReadDataFromPort.DECODE_STYLE = 'NoLF'
# elif sender_check == ui.action_carrige_return:
# ReadDataFromPort.__LINE_FEED_TYPE = (b':\r', b'<\r', b'>\r', b'*\r', b'T*\r')
# ReadDataFromPort.DECODE_STYLE = 'CR'
# elif sender_check == ui.action_line_feed:
# ReadDataFromPort.__LINE_FEED_TYPE = (b':\n', b'<\n', b'>\n', b'*\n', b'T*\n')
# ReadDataFromPort.DECODE_STYLE = 'LF'
# elif sender_check == ui.action_CR_LF:
# ReadDataFromPort.__LINE_FEED_TYPE = (b':\r\n', b'<\r\n', b'>\r\n', b'*\r\n', b'T*\r\n')
# ReadDataFromPort.DECODE_STYLE = 'CR&LF'
# logger_debug_console.info(
# f"set_line_feed_style called! Current decoding format: {ReadDataFromPort.DECODE_STYLE}")
# logger_debug_console.info(f"当前结尾标识符: {ReadDataFromPort.__LINE_FEED_TYPE}")
# return ReadDataFromPort.__LINE_FEED_TYPE, ReadDataFromPort.DECODE_STYLE
#
# @staticmethod
# def decode_according_to_identifier(DECODE_STYLE, response):
# if not DECODE_STYLE or DECODE_STYLE == 'NoLF':
# return response.decode(ReadDataFromPort.DECODE_TYPE, 'replace')
# elif DECODE_STYLE == 'CR':
# return response.replace(b'\r', b'\r\n').decode(ReadDataFromPort.DECODE_TYPE).strip()
# elif DECODE_STYLE == 'LF' or DECODE_STYLE == 'CR&LF':
# return response.decode(ReadDataFromPort.DECODE_TYPE, 'replace').strip()
#
# def run(self):
# # print(self.ui)
# # print(self.ser)
# # print('ReadDataFromPort called!')
# # print('Run:', self.ser is None, self.connect_status)
# if self.ser is None:
# self.quit()
# return
# else:
# self.call_send_thread()
# pass
# # self.start_send_thread()
#
# while self.ser:
# self.mutex.lock()
# print('Read running: ', self.isRunning())
# current_time = QtCore.QDateTime.currentDateTime().toString("[hh:mm:ss]")
# response = self.read_single_line()
# # response = self.response
# # if response and response != b'':
# # print('response from run multi:', response)
# """不以(':', '>', '<', '*', 'T*')结尾的读取数据用来绘图"""
# if response and response != b'':
# # response_dec = response.decode('utf-8', 'replace') # Pump
# # response_dec = response.decode('utf-8', 'replace').strip() # 末尾包含\r或者\r\n
# # response_dec_rep = response.replace(b'\r', b'\r\n').decode('utf-8').strip() # 保证解码之后能够通过print()打印,然后解析
# # print('response_dec_rep', response_dec_rep)
# # print('response_dec from run multi:', response_dec)
# response_dec = self.decode_according_to_identifier(DECODE_STYLE=ReadDataFromPort.DECODE_STYLE,
# response=response)
# if response_dec.endswith(':'):
# self.receive_status.emit('Continue')
# # print(self.receive_status.signal)
# self.__RECEIVE_STATUS = 'Continue'
# print('self.receive_status_instance: ', self.__RECEIVE_STATUS)
# self.ui.Response_from_pump.append(f"{current_time} >>\n{response_dec}\n")
# # print(f"{current_time} >>\n{response_dec}\n")
# self.ui.Response_from_pump.moveCursor(QtGui.QTextCursor.MoveOperation.End)
# QtCore.QCoreApplication.instance().processEvents()
# elif response_dec.endswith('>'):
# self.receive_status.emit('INF running')
# # print('>>>>>>>>>>>>>', response_dec)
# self.ui.Response_from_pump.append(f"{current_time} >>\n{response_dec}\n")
# self.ui.Response_from_pump.moveCursor(QtGui.QTextCursor.MoveOperation.End)
# QtCore.QCoreApplication.instance().processEvents()
# elif response_dec.endswith('<'):
# self.receive_status.emit('WD running')
# # print('<<<<<<<<<<<<<<', response_dec)
# self.ui.Response_from_pump.append(f"{current_time} >>\n{response_dec}\n")
# self.ui.Response_from_pump.moveCursor(QtGui.QTextCursor.MoveOperation.End)
# QtCore.QCoreApplication.instance().processEvents()
# elif response_dec.endswith('*'):
# if response_dec[-2:] == 'T*':
# self.receive_status.emit('Target reached')
# self.ui.Response_from_pump.append(f"{current_time} >>\n{response_dec}\n")
# self.ui.Response_from_pump.moveCursor(QtGui.QTextCursor.MoveOperation.End)
# QtCore.QCoreApplication.instance().processEvents()
# else:
# self.receive_status.emit('STOP')
# self.ui.Response_from_pump.append(f"{current_time} >>\n{response_dec}\n")
# self.ui.Response_from_pump.moveCursor(QtGui.QTextCursor.MoveOperation.End)
# QtCore.QCoreApplication.instance().processEvents()
# else:
# # self.ui.Response_from_pump.append(f"{current_time} >>{response_dec}")
# # self.ui.Response_from_pump.moveCursor(QtGui.QTextCursor.MoveOperation.End)
# pass
# else:
# pass
# # 释放锁,避免阻塞其他线程的执行
# self.mutex.unlock()