-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpHox_gui.py
2779 lines (2215 loc) · 108 KB
/
pHox_gui.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
#! /usr/bin/python
import os
import sys
from contextlib import asynccontextmanager
from pHox import *
from util import get_base_folderpath, box_id, config_name, rgb_lookup
try:
import warnings, time, RPi.GPIO
import RPi.GPIO as GPIO
except ModuleNotFoundError:
pass
from datetime import datetime, timedelta
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QLineEdit, QTabWidget, QWidget, QPushButton, QPlainTextEdit
from PyQt5.QtWidgets import (QGroupBox, QMessageBox, QLabel, QTableWidgetItem, QGridLayout, QProgressBar,
QTableWidget, QHeaderView, QComboBox, QCheckBox, QDialog,
QSlider, QInputDialog, QApplication, QMainWindow)
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QPixmap, QIcon
import numpy as np
import pyqtgraph as pg
import argparse
import pandas as pd
from util import config_file
import udp
from udp import Ferrybox as fbox
from precisions import precision as prec
from asyncqt import QEventLoop, asyncSlot
import asyncio
class AfterCuvetteCleaning(QDialog):
def __init__(self, Panel):
super(AfterCuvetteCleaning, self).__init__(Panel)
self.main_qt_panel = Panel
# Class functionality
# The Dialog will be opened when the user reach the step of cleaning the Cuvette.
# Button Update Plot: measure led intensity and plot it.
# So the user can understand if the cuvette was cleaned well or not
# Since during the calibration process the automatic real time updates of the plot
# Are turned off
# Other functionality : Ok and Cancel
# If clicked OK, the program will continue the calibration cycle
# If Cancel, the calibration will be stopped.
self.setWindowTitle("Calibration Step After cleaning the Cuvette")
self.btn_update_plots = QPushButton('Update Intensity Plots')
self.btn_update_plots.clicked.connect(self.button_clicked)
self.btn_update_plots.setCheckable(True)
layout = QtWidgets.QGridLayout()
pixmap = QPixmap(QPixmap('utils/figures_icons/pHox_idea.png')).scaledToHeight(100,
QtCore.Qt.SmoothTransformation)
self.image = QLabel("Hello")
self.image.setPixmap(pixmap)
self.setWindowIcon(QIcon('utils/figures_icons/pHox_logo.png'))
self.text = QLabel("<br>Please, clean the cuvette.\
<br>\
<br>Click <b>OK</b> When you are ready.\
<br>Click Cancel to stop calibration")
self.buttonBox = QtWidgets.QDialogButtonBox()
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
self.plotwidget = pg.PlotWidget()
self.plotSpc = self.plotwidget.plot()
self.plotwidget.setBackground("#19232D")
self.plotwidget.showGrid(x=True, y=True)
self.plotwidget.setYRange(1000, self.main_qt_panel.instrument.THR * 1.05)
layout.addWidget(self.image, 0, 0, 1, 1)
layout.addWidget(self.text, 0, 1, 1, 1)
layout.addWidget(self.plotwidget, 1, 1, 1, 1, )
layout.addWidget(self.btn_update_plots, 2, 1, 1, 1)
layout.addWidget(self.buttonBox, 3, 0, 1, 2)
self.setLayout(layout)
# cuvette_is_clean = self.valve_message(type='After cuvette cleaning')
# b = threading.Thread(target=self.button_clicked)
# b.start()
def button_clicked(self):
self.spectrum = self.main_qt_panel.instrument.spectrometer_cls.get_intensities_slow()
self.plotSpc.setData(self.main_qt_panel.wvls, self.spectrum)
self.btn_update_plots.setChecked(False)
return
class BatchNumber(QDialog):
def __init__(self, parent=None):
super(BatchNumber, self).__init__(parent)
self.setWindowTitle("Calibration solution Batch Number")
self.batch_number_widget = QtWidgets.QLineEdit()
self.batch_number = 1
self.batch_number_widget.setText(str(self.batch_number))
self.layout = QtWidgets.QGridLayout()
label_text = 'Please Enter the Calibration Solution Batch Number'
self.plus_one = QPushButton('+1')
self.plus_ten = QPushButton('+10')
self.minus_one = QPushButton('-1')
self.minus_ten = QPushButton('-10')
self.btns = {self.plus_one: 1,
self.minus_one: -1,
self.plus_ten: +10,
self.minus_ten: -10}
[btn.clicked.connect(self.button_clicked) for btn in self.btns.keys()]
self.layout.addWidget(QLabel(label_text), 0, 0, 1, 3)
self.layout.addWidget(self.batch_number_widget, 1, 0, 2, 1)
self.layout.addWidget(self.plus_one, 1, 1)
self.layout.addWidget(self.plus_ten, 1, 2)
self.layout.addWidget(self.minus_one, 2, 1)
self.layout.addWidget(self.minus_ten, 2, 2)
self.buttonBox = QtWidgets.QDialogButtonBox()
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
self.layout.addWidget(self.buttonBox, 3, 2, 1, 2)
self.setLayout(self.layout)
@pyqtSlot()
def button_clicked(self):
new_value = self.batch_number + self.btns[self.sender()]
if new_value > 0:
self.batch_number = new_value
self.batch_number_widget.setText(str(self.batch_number))
class CalibrationProgess(QDialog):
# Adapt dialog depending on the answer clean cuvette or not
def __init__(self, parent=None, with_cuvette_cleaning=True):
super(CalibrationProgess, self).__init__(parent)
self.setWindowTitle("Calibration check progress window")
# QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
progress_steps_style = """
QCheckBox::indicator::checked {
background-color: #32414B;}
"""
if with_cuvette_cleaning:
n_steps = 6
else:
n_steps = 3
self.progress_checkboxes = [QCheckBox('Calibration check {}'.format(n + 1)) for n in range(n_steps)]
self.result_checkboxes = [QCheckBox('result'.format(n + 1)) for n in range(n_steps)]
for n in self.progress_checkboxes:
n.setStyleSheet(progress_steps_style)
n.setEnabled(False)
for n in self.result_checkboxes:
n.setEnabled(False)
n.setTristate()
self.no_cleaning_groupbox = QGroupBox('Before Cuvette cleaning')
layout_1 = QtWidgets.QGridLayout()
for n in range(3):
layout_1.addWidget(self.progress_checkboxes[n], n, 0)
layout_1.addWidget(self.result_checkboxes[n], n, 1)
self.no_cleaning_groupbox.setLayout(layout_1)
self.layout = QtWidgets.QGridLayout()
self.layout.addWidget(self.no_cleaning_groupbox)
if with_cuvette_cleaning:
self.with_cleaning_groupbox = QGroupBox('After Cuvette cleaning')
layout_2 = QtWidgets.QGridLayout()
for n in range(3, 6):
layout_2.addWidget(self.progress_checkboxes[n], n - 3, 0)
layout_2.addWidget(self.result_checkboxes[n], n - 3, 1)
self.with_cleaning_groupbox.setLayout(layout_2)
self.layout.addWidget(self.with_cleaning_groupbox)
self.stop_calibr_btn = QPushButton('Stop Calibration')
self.stop_calibr_btn.setCheckable(True)
self.layout.addWidget(self.stop_calibr_btn)
self.setLayout(self.layout)
def closeEvent(self, event):
self.stop_calibr_btn.setChecked(True)
class TimerManager:
def __init__(self, input_timer):
self.input_timer = input_timer
# logging.debug('TimerManager init method called')
def __enter__(self):
self.input_timer.start(1000)
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.input_timer.stop()
# logging.debug('TimerManager method called')
class QTextEditLogger(logging.Handler):
def __init__(self, parent):
super().__init__()
self.widget = QPlainTextEdit(parent)
self.widget.setReadOnly(True)
def emit(self, record):
msg = self.format(record)
self.widget.appendPlainText(msg)
class TimeAxisItem(pg.AxisItem):
def tickStrings(self, values, scale, spacing):
return [datetime.fromtimestamp(value) for value in values]
class SimpleThread(QtCore.QThread):
finished = QtCore.pyqtSignal(object)
def __init__(self, slow_function, callback):
super(SimpleThread, self).__init__()
self.caller = slow_function
self.finished.connect(callback)
def run(self):
self.finished.emit(self.caller())
class AsyncThreadWrapper:
def __init__(self, slow_function):
self.callback_returned, self.result = False, None
self.thread = SimpleThread(slow_function, self.result_setter)
self.thread.start()
def result_setter(self, res):
self.result, self.callback_returned = res, True
async def result_returner(self):
while not self.callback_returned:
await asyncio.sleep(0.1)
self.thread.quit()
self.thread.wait()
return self.result
class Panel(QWidget):
def __init__(self, parent, panelargs):
super(QWidget, self).__init__(parent)
self.major_modes = set()
self.valid_modes = ["Measuring", "Adjusting", "Manual",
"Continuous", "Calibration", "Flowcheck",
"Paused"]
self.args = panelargs
self.starttime = datetime.now()
self.fformat = "%Y%m%d_%H%M%S"
self.init_instrument()
self.wvls = self.instrument.calc_wavelengths()
self.instrument.get_wvlPixels(self.wvls)
self.noWheelCombos = []
self.t_insitu_live = QLineEdit()
self.s_insitu_live = QLineEdit()
self.t_cuvette_live = QLineEdit()
self.voltage_live = QLineEdit()
self.btn_calibr = QPushButton()
self.init_ui()
self.create_timers()
self.updater = SensorStateUpdateManager(self)
self.infotimer_step = 15 # seconds
self.manual_limit = 4 # 3 minutes, time when we turn off manual mode if continuous is clicked
def init_ui(self):
self.tabs = QTabWidget()
self.tab_home = QWidget()
self.tab_manual = QWidget()
self.tab_status = QWidget()
self.tab_config = QWidget()
self.tab_log = QWidget()
self.plots = QWidget()
self.tabs.addTab(self.tab_home, "Home")
self.tabs.addTab(self.tab_manual, "Manual")
self.tabs.addTab(self.tab_config, "Config")
self.tabs.addTab(self.tab_status, "Status")
self.tabs.addTab(self.tab_log, "Log")
self.make_tab_log()
self.make_tab_home()
self.make_tab_manual()
self.make_tab_config()
self.make_plotwidgets()
l = QGridLayout()
l.addWidget(self.logTextBox.widget)
self.tab_log.setLayout(l)
# combine layout for plots and buttons
hboxPanel = QtWidgets.QHBoxLayout()
hboxPanel.addWidget(self.plotwdigets_groupbox)
hboxPanel.addWidget(self.tabs)
# Disable all manual buttons in the Automatic mode
self.manual_widgets_set_enabled(False)
self.setLayout(hboxPanel)
def refill_dye(self):
if self.dye_level < 2000:
if self.dye_level >= 1000:
self.dye_level = 2000
else:
self.dye_level = 1000
self.dye_level_bar.setValue(int(self.dye_level))
self.update_config('dye_level', 'pH', self.dye_level)
def empty_all_dye(self):
self.dye_level = 0
self.dye_level_bar.setValue(int(self.dye_level))
self.update_config('dye_level', 'pH', self.dye_level)
def update_dye_level_bar(self, nshots=1):
self.dye_level -= self.dye_step_1meas * nshots
self.dye_level_bar.setValue(int(self.dye_level))
self.update_config('dye_level', 'pH', self.dye_level)
def update_config(self, parameter, group, value):
with open(config_name, "r+") as json_file:
j = json.load(json_file)
j[group][parameter] = value
json_file.seek(0) # rewind
json.dump(j, json_file, indent=4)
json_file.truncate()
def make_tab_log(self):
self.tab_status.layout = QGridLayout()
self.logTextBox = QTextEditLogger(self)
dye_level_group = QGroupBox('Dye Level ')
l = QGridLayout()
self.dye_level_bar = QProgressBar()
self.dye_refill_btn = QPushButton('1 bag \nRefilled')
self.dye_empty_btn = QPushButton('Clear \nall')
l.addWidget(self.dye_empty_btn, 0, 0)
l.addWidget(self.dye_refill_btn, 0, 1)
l.addWidget(self.dye_level_bar, 0, 2)
dye_level_group.setLayout(l)
self.dye_level = config_file['Operational']['dye_level']
self.dye_level_bar.setMaximum(2000)
self.dye_level_bar.setValue(int(self.dye_level))
self.dye_step_1meas = (config_file['Operational']["ncycles"] * config_file['Operational']["DYE_V_INJ"] *
config_file['Operational']["dye_nshots"])
self.dye_refill_btn.clicked.connect(self.refill_dye)
self.dye_empty_btn.clicked.connect(self.empty_all_dye)
# self.dye_empty_btn.setToolTip("Selected Icon")
# Volume 1 shot 0.03 ml
# 1 measurement 1 shot * "dye_nshots" * "ncycles" = 0.03 ml * 1 * 4 = 0.12 ml
# You can format what is printed to text box
self.logTextBox.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logging.getLogger().addHandler(self.logTextBox)
if self.args.debug:
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.getLogger().setLevel(logging.INFO)
meas_qc_groupbox = QGroupBox('Last Measurement Quality Control')
l = QGridLayout()
self.flow_qc_chk = QCheckBox('Flow')
self.dye_qc_chk = QCheckBox('Dye')
self.biofouling_qc_chk = QCheckBox('Biofouling')
self.temp_alive_qc_chk = QCheckBox('Temp sensor')
qc_checks = [self.flow_qc_chk, self.dye_qc_chk,
self.biofouling_qc_chk, self.temp_alive_qc_chk]
for n in qc_checks:
n.setTristate()
n.setEnabled(False)
l.addWidget(self.flow_qc_chk, 0, 0)
l.addWidget(self.dye_qc_chk, 0, 1)
l.addWidget(self.biofouling_qc_chk, 1, 0)
l.addWidget(self.temp_alive_qc_chk, 1, 1)
meas_qc_groupbox.setLayout(l)
if self.args.localdev:
logging.info("Starting in local debug mode")
self.dye_level_bar.setToolTip("Dye level, 100% is two full bags of dye")
self.tab_status.layout.addWidget(dye_level_group, 0, 0)
self.tab_status.layout.addWidget(meas_qc_groupbox, 1, 0)
if not self.args.co3:
calibration_group = self.make_calibration_groupbox()
self.tab_status.layout.addWidget(calibration_group, 2, 0)
self.tab_status.setLayout(self.tab_status.layout)
def create_timers(self):
self.timer_contin_mode = QtCore.QTimer()
self.timer_contin_mode.timeout.connect(self.continuous_mode_timer_finished)
self.infotimer_contin_mode = QtCore.QTimer()
self.infotimer_contin_mode.timeout.connect(self.update_contin_mode_info)
self.timerSpectra_plot = QtCore.QTimer()
self.timerSpectra_plot.timeout.connect(self.update_spectra_plot)
self.timerTemp_info = QtCore.QTimer()
self.timerTemp_info.timeout.connect(self.update_sensors_info)
self.timerAuto = QtCore.QTimer()
self.timer2 = QtCore.QTimer()
self.timer2.timeout.connect(self.update_plot_no_request)
if self.args.pco2:
self.timerSave_pco2 = QtCore.QTimer()
self.timerSave_pco2.timeout.connect(self.update_pco2_data)
def btn_manual_mode_clicked(self):
if self.btn_manual_mode.isChecked():
self.set_major_mode("Manual")
else:
self.unset_major_mode("Manual")
def set_major_mode(self, mode_set):
"""Refer to Panel.valid_modes for a list of allowed modes"""
logging.debug(f"Current mode:{self.major_modes}")
if mode_set not in self.valid_modes:
logging.info(f"ERROR, '{mode_set}' is not a valid mode, valid modes: {self.valid_modes}")
return False
if mode_set in self.major_modes:
logging.info(f"ERROR, '{mode_set}' is already in major_modes: {self.major_modes}")
return False
# TODO Add more invalidating checks
if mode_set == "Manual":
self.manual_widgets_set_enabled(True)
self.btn_single_meas.setEnabled(False)
# if 'Continuous' in self.major_modes:
# self.btn_adjust_light_intensity.setEnabled(False)
# #self.btn_checkflow.setEnabled(False)
if mode_set == "Continuous":
self.until_next_sample = self.instrument.samplingInterval
self.timer_contin_mode.start(int(self.instrument.samplingInterval * 1000 * 60))
self.StatusBox.setText(f'Next sample in {self.until_next_sample} minutes ')
logging.debug('Start infotimer continous mode')
self.infotimer_contin_mode.start(self.infotimer_step * 1000)
self.btn_single_meas.setEnabled(False)
self.btn_calibr.setEnabled(False)
self.config_widgets_set_state(False)
self.manual_widgets_set_enabled(False)
if 'Manual' in self.major_modes:
self.btn_adjust_light_intensity.setEnabled(False)
# self.btn_checkflow.setEnabled(False)
if mode_set == 'Calibration':
self.btn_single_meas.setEnabled(False)
self.btn_calibr.setEnabled(False)
self.config_widgets_set_state(False)
self.btn_manual_mode.setEnabled(False)
if mode_set in ["Measuring", "Adjusting"]:
self.btn_manual_mode.setEnabled(False)
self.btn_single_meas.setEnabled(False)
self.btn_calibr.setEnabled(False)
if "Continuous" not in self.major_modes:
self.btn_cont_meas.setEnabled(False)
self.manual_widgets_set_enabled(False)
self.config_widgets_set_state(False)
if mode_set == 'Paused':
self.btn_manual_mode.setEnabled(True)
self.major_modes.add(mode_set)
logging.debug(f"New mode:{self.major_modes}")
return True
def unset_major_mode(self, mode_unset):
"""Refer to Panel.valid_modes for a list of allowed modes"""
logging.debug(f"Current mode:{self.major_modes}")
if mode_unset not in self.major_modes:
logging.info(f"ERROR, '{mode_unset}' is currently not in major_modes: '{self.major_modes}'")
return False
# TODO Add more invalidating checks
if mode_unset == "Manual":
if 'Continuous' in self.major_modes and self.until_next_sample <= self.manual_limit:
self.btn_manual_mode.setChecked(False)
self.btn_manual_mode.setEnabled(False)
if self.args.co3:
self.btn_drain.setChecked(False)
self.manual_widgets_set_enabled(False)
self.btn_single_meas.setEnabled(True)
if mode_unset == "Continuous":
print('unset mode continous')
self.infotimer_contin_mode.stop()
self.timer_contin_mode.stop()
self.StatusBox.clear()
self.btn_manual_mode.setEnabled(True)
if "Measuring" not in self.major_modes:
if self.args.co3:
self.btn_light.setChecked(False)
self.btn_light_clicked()
if 'Manual' not in self.major_modes:
self.btn_single_meas.setEnabled(True)
self.btn_calibr.setEnabled(True)
if 'Manual' in self.major_modes:
self.btn_adjust_light_intensity.setEnabled(True)
# self.btn_checkflow.setEnabled(True)
self.config_widgets_set_state(True)
print('finished unsetting continuous mode')
print('timer active', self.infotimer_contin_mode.isActive())
if mode_unset == "Calibration":
self.btn_single_meas.setEnabled(True)
self.btn_calibr.setEnabled(True)
self.config_widgets_set_state(True)
self.btn_manual_mode.setEnabled(True)
self.btn_cont_meas.setEnabled(True)
if mode_unset == "Measuring":
if "Calibration" not in self.major_modes:
if "Continuous" not in self.major_modes:
self.btn_single_meas.setEnabled(True)
self.btn_calibr.setEnabled(True)
self.config_widgets_set_state(True)
self.btn_manual_mode.setEnabled(True)
self.btn_cont_meas.setEnabled(True)
self.config_widgets_set_state(True)
if mode_unset == 'Adjusting' and "Measuring" not in self.major_modes:
logging.debug('unset mode adjusting')
if 'Manual' in self.major_modes:
self.btn_manual_mode.setEnabled(True)
self.manual_widgets_set_enabled(True)
self.config_widgets_set_state(True)
self.btn_calibr.setEnabled(True)
self.btn_single_meas.setEnabled(True)
self.btn_cont_meas.setEnabled(True)
if mode_unset == 'Paused':
logging.debug('unset paused mode')
if "Continuous" in self.major_modes:
self.until_next_sample = self.instrument.samplingInterval
self.timer_contin_mode.start(self.instrument.samplingInterval * 1000 * 60)
self.StatusBox.setText(f'Next sample in {self.until_next_sample} minutes ')
logging.debug('Restart infortimer',
'coninuous mode after pause')
self.infotimer_contin_mode.start(self.infotimer_step * 1000)
self.btn_single_meas.setEnabled(False)
self.btn_calibr.setEnabled(False)
self.config_widgets_set_state(False)
self.manual_widgets_set_enabled(False)
if 'Manual' in self.major_modes:
self.btn_adjust_light_intensity.setEnabled(False)
if mode_unset == 'Flowcheck':
if 'Manual' in self.major_modes:
self.manual_widgets_set_enabled(True)
self.btn_cont_meas.setEnabled(True)
self.btn_single_meas.setEnabled(True)
self.btn_calibr.setEnabled(True)
self.config_widgets_set_state(True)
self.btn_manual_mode.setEnabled(True)
self.major_modes.remove(mode_unset)
logging.debug(f"New mode:{self.major_modes}")
return True
def make_plotwidgets(self):
# create plotwidgets
self.plotwdigets_groupbox = QGroupBox()
pg.setConfigOptions(background="#19232D", crashWarning=True)
self.plotwidget1 = pg.PlotWidget()
self.plotwidget2 = pg.PlotWidget()
self.plotwidget1.setYRange(1000, self.instrument.THR * 1.05)
self.plotwidget1.showGrid(x=True, y=True)
self.plotwidget1.setTitle("Lightsource intensities")
self.plotwidget2.showGrid(x=True, y=True)
self.plotwidget2.setTitle("Last pH measurement")
vboxPlot = QtWidgets.QVBoxLayout()
vboxPlot.addWidget(self.plotwidget1)
vboxPlot.addWidget(self.plotwidget2)
self.plotSpc = self.plotwidget1.plot()
self.plot_calc_pH = self.plotwidget2.plot()
self.after_calc_pH = self.plotwidget2.plot()
self.lin_fit_pH = self.plotwidget2.plot()
self.plotwidget1.setMouseEnabled(x=False, y=False)
self.plotwidget2.setMouseEnabled(x=False, y=False)
self.plotwdigets_groupbox.setLayout(vboxPlot)
def make_steps_groupBox(self):
self.sample_steps_groupBox = QGroupBox("Measuring Progress")
# read the number of repetitions and adapt
self.sample_steps2 = [QCheckBox("Measurement {}".format(n)) for n in range(1, self.instrument.ncycles + 1)]
self.sample_steps = [QCheckBox("1. Adjusting Light"), QCheckBox("2 Dark and blank")] + self.sample_steps2
layout = QGridLayout()
[step.setEnabled(False) for step in self.sample_steps]
[layout.addWidget(step) for step in self.sample_steps]
self.sample_steps_groupBox.setLayout(layout)
def make_tab_home(self):
self.make_steps_groupBox()
self.make_last_measurement_table()
self.tab_home.layout = QGridLayout()
try:
self.StatusBox = QtWidgets.QTextEdit()
except:
self.StatusBox = QtWidgets.QTextEdit()
self.StatusBox.setReadOnly(True)
self.ferrypump_box = QCheckBox("Ferrybox pump is on")
self.ferrypump_box.setEnabled(False)
if fbox['pumping']:
self.ferrypump_box.setChecked(True)
self.table_grid = QGridLayout()
self.table_grid.addWidget(self.last_measurement_table)
self.live_updates_grid = QGridLayout()
live_widgets = [self.t_insitu_live, self.s_insitu_live, self.t_cuvette_live, self.voltage_live]
[n.setReadOnly(True) for n in live_widgets]
self.live_updates_grid.addWidget(QLabel('T insitu'), 0, 0)
self.live_updates_grid.addWidget(self.t_insitu_live, 0, 1)
self.live_updates_grid.addWidget(QLabel('S insitu'), 0, 2)
self.live_updates_grid.addWidget(self.s_insitu_live, 0, 3)
self.live_updates_grid.addWidget(QLabel('T cuvette'), 1, 0)
self.live_updates_grid.addWidget(self.t_cuvette_live, 1, 1)
self.live_updates_grid.addWidget(QLabel('Voltage'), 1, 2)
self.live_updates_grid.addWidget(self.voltage_live, 1, 3)
self.live_updates_grid.addWidget(self.ferrypump_box, 2, 2, 1, 2)
self.live_updates_grid.addWidget(self.StatusBox, 3, 0, 1, 4)
self.live_update_groupbox.setLayout(self.live_updates_grid)
self.last_measurement_table_groupbox.setLayout(self.table_grid)
self.btn_cont_meas = self.create_button("Continuous measurements", True)
self.btn_single_meas = self.create_button("Single measurement", True)
self.btn_single_meas.clicked.connect(self.btn_single_meas_clicked)
self.btn_cont_meas.clicked.connect(self.btn_cont_meas_clicked)
self.tab_home.layout.addWidget(self.btn_cont_meas, 0, 0, 1, 1)
self.tab_home.layout.addWidget(self.btn_single_meas, 0, 1)
self.tab_home.layout.addWidget(self.sample_steps_groupBox, 1, 0, 1, 1)
self.tab_home.layout.addWidget(self.last_measurement_table_groupbox, 1, 1, 1, 1)
self.tab_home.layout.addWidget(self.live_update_groupbox, 2, 0, 1, 2)
self.tab_home.setLayout(self.tab_home.layout)
def fill_table_measurement(self, x, y, item):
self.last_measurement_table.setItem(x, y, QTableWidgetItem(item))
def fill_live_updates_table(self, x, y, item):
self.live_updates_table.setItem(x, y, QTableWidgetItem(item))
def fill_table_config(self, x, y, item):
self.tableConfigWidget.setItem(x, y, QTableWidgetItem(item))
def eventFilter(self, source, event):
""" Filter all mouse scrolling for the defined comboboxes """
if (event.type() == QtCore.QEvent.Wheel and
source in self.noWheelCombos):
return True
return super(Panel, self).eventFilter(source, event)
def make_tab_config(self):
self.tab_config.layout = QGridLayout()
# Define widgets for config tab
self.btn_save_config = self.create_button("Save config", False)
self.btn_save_config.clicked.connect(self.btn_save_config_clicked)
self.btn_test_udp = self.create_button('Test UDP', True)
self.timer_test_udp = QtCore.QTimer()
#self.timer_udp = QtCore.QTimer()
self.timer_test_udp.timeout.connect(self.send_test_udp)
#self.timer_udp.timeout.connect(self.send_fb_udp)
self.btn_test_udp.clicked.connect(self.test_udp)
self.tableConfigWidget = QTableWidget()
self.tableConfigWidget.setEditTriggers(QTableWidget.NoEditTriggers)
self.tableConfigWidget.verticalHeader().hide()
self.tableConfigWidget.horizontalHeader().hide()
self.tableConfigWidget.setRowCount(9)
self.tableConfigWidget.setColumnCount(2)
self.tableConfigWidget.horizontalHeader().setResizeMode(QHeaderView.Stretch)
self.fill_table_config(0, 0, "DYE type")
self.config_dye_info()
self.fill_table_config(1, 0, "Autoadjust state")
self.autoadjState_combo = QComboBox()
self.combo_in_config(self.autoadjState_combo, "Autoadjust_state")
self.tableConfigWidget.setCellWidget(1, 1, self.autoadjState_combo)
self.fill_table_config(2, 0, 'Pumping time (seconds)')
self.fill_table_config(2, 1, str(self.instrument.pumpTime))
self.fill_table_config(3, 0, "Sampling interval (min)")
self.samplingInt_combo = QComboBox()
self.combo_in_config(self.samplingInt_combo, 'Sampling interval')
self.tableConfigWidget.setCellWidget(3, 1, self.samplingInt_combo)
self.fill_table_config(4, 0, "Spectro integration time")
self.specIntTime_combo = QComboBox()
self.combo_in_config(self.specIntTime_combo, "Spectro integration time")
self.tableConfigWidget.setCellWidget(4, 1, self.specIntTime_combo)
self.fill_table_config(5, 0, "Ship")
self.ship_code_combo = QComboBox()
self.combo_in_config(self.ship_code_combo, "Ship")
self.tableConfigWidget.setCellWidget(5, 1, self.ship_code_combo)
self.fill_table_config(6, 0, 'Temp probe id')
self.temp_id_combo = QComboBox()
self.combo_in_config(self.temp_id_combo, 'Temp probe id')
self.tableConfigWidget.setCellWidget(6, 1, self.temp_id_combo)
self.fill_table_config(7, 0, 'Temp probe is calibrated')
self.temp_id_is_calibr = QtWidgets.QCheckBox()
self.fill_table_config(8, 0, "Drain mode")
self.drain_mode_combo = QComboBox()
self.combo_in_config(self.drain_mode_combo, 'Drain_mode')
self.tableConfigWidget.setCellWidget(8, 1, self.drain_mode_combo)
if self.instrument.temp_iscalibrated:
self.temp_id_is_calibr.setChecked(True)
self.temp_id_is_calibr.setEnabled(False)
self.tableConfigWidget.setCellWidget(7, 1, self.temp_id_is_calibr)
self.create_manual_sal_group()
self.tab_config.layout.addWidget(self.btn_save_config, 0, 0, 1, 1)
self.tab_config.layout.addWidget(self.btn_test_udp, 0, 1, 1, 1)
self.tab_config.layout.addWidget(self.tableConfigWidget, 1, 0, 1, 3)
self.tab_config.layout.addWidget(self.manual_sal_group, 3, 0, 2, 3)
self.tab_config.setLayout(self.tab_config.layout)
def config_dye_info(self):
self.dye_combo = QComboBox()
self.combo_in_config(self.dye_combo, "DYE type pH")
self.tableConfigWidget.setCellWidget(0, 1, self.dye_combo)
def combo_in_config(self, combo, name):
combo_dict = {
"Ship": [
self.instrument.valid_ship_codes,
self.ship_code_changed,
self.instrument.ship_code],
'Temp probe id': [
["Probe_" + str(n) for n in range(1, 16)],
self.temp_id_combo_changed,
self.instrument.TempProbe_id],
'Sampling interval': [
self.instrument.valid_samplingIintervals,
self.sampling_int_chngd,
int(self.instrument.samplingInterval)],
"Autoadjust_state": [
['ON', 'OFF', 'ON_NORED'],
self.autoadj_opt_chgd,
self.instrument.autoadj_opt
],
"Drain_mode": [
['ON', 'OFF'],
self.drain_mode_chgd,
self.instrument.drain_mode
],
"Spectro integration time": [list(range(1, 20, 1)) + list(range(20, 100, 10)) + list(range(100, 5000, 100)),
self.specIntTime_combo_chngd,
self.instrument.specIntTime
],
"DYE type pH": [
["TB", "MCP"],
self.dye_combo_chngd,
self.instrument.dye
],
"DYE type CO3": [
['Pb_perchlor'],
self.dye_combo_chngd,
self.instrument.dye
]
}
self.noWheelCombos.append(combo)
combo.installEventFilter(self)
[combo.addItem(str(item)) for item in combo_dict[name][0]]
combo.currentIndexChanged.connect(combo_dict[name][1])
self.set_combo_index(combo, combo_dict[name], name)
def create_manual_sal_group(self):
self.manual_sal_group = QGroupBox('Salinity used for manual measurement')
l = QtWidgets.QHBoxLayout()
self.whole_sal = QComboBox()
self.first_decimal = QComboBox()
self.second_decimal = QComboBox()
self.third_decimal = QComboBox()
[self.whole_sal.addItem(str(n)) for n in np.arange(0, 40)]
self.whole_sal.setCurrentIndex(self.whole_sal.findText('35', QtCore.Qt.MatchFixedString))
for combo in [self.first_decimal, self.second_decimal, self.third_decimal]:
[combo.addItem(str(n)) for n in np.arange(0, 10)]
l.addWidget(self.whole_sal)
l.addWidget(QLabel('.'))
l.addWidget(self.first_decimal)
l.addWidget(self.second_decimal)
l.addWidget(self.third_decimal)
self.manual_sal_group.setLayout(l)
return self.manual_sal_group
def get_salinity_manual(self):
if 'Continuous' not in self.major_modes and 'Calibration' not in self.major_modes:
salinity_manual = (int(self.whole_sal.currentText()) + int(self.first_decimal.currentText()) / 10
+ int(self.second_decimal.currentText()) / 100 +
int(self.third_decimal.currentText()) / 1000)
elif 'Calibration' in self.major_modes:
salinity_manual = self.instrument.buffer_sal
else:
salinity_manual = None
return salinity_manual
def set_combo_index(self, combo, combo_info, combotype):
text = combo_info[2]
valid_intervals = combo_info[0]
index = combo.findText(str(text), QtCore.Qt.MatchFixedString)
if index >= 0:
combo.setCurrentIndex(index)
else:
if combotype in ("Spectro integration time", 'Sampling interval'):
diffs = np.abs(np.array(list(map(float, valid_intervals))) - float(text))
idx2 = np.argpartition(diffs, 2)[:2]
text_idx1 = float(valid_intervals[idx2[0]])
text_idx2 = float(valid_intervals[idx2[1]])
if text_idx1 < text_idx2:
idx = idx2[0]
text = text_idx1
else:
idx = idx2[1]
text = text_idx2
logging.error('Assigning a new value which is the closest from the list of valid values: {}'.
format(text))
combo.setCurrentIndex(idx)
else:
logging.error('was not able to set value from the config file,combo is {}, value is {}'.format(
combo, str(text)))
def sampling_int_chngd(self, ind):
self.instrument.samplingInterval = float(self.samplingInt_combo.currentText())
@asyncSlot()
async def specIntTime_combo_chngd(self):
new_int_time = float(self.specIntTime_combo.currentText())
await self.updater.set_specIntTime(new_int_time)
def ship_code_changed(self):
self.instrument.ship_code = self.ship_code_combo.currentText()
def drain_mode_chgd(self):
self.instrument.drain_mode = self.drain_mode_combo.currentText()
def autoadj_opt_chgd(self):
self.instrument.autoadj_opt = self.autoadjState_combo.currentText()
def temp_id_combo_changed(self):
self.instrument.TempProbe_id = self.temp_id_combo.currentText()
# self.instrument.temp_iscalibrated = config_file[self.TempProbe_id]["is_calibrated"]
self.instrument.update_temp_probe_coef()
logging.info('new temp sensor, calibrated:' + str(self.instrument.temp_iscalibrated))
# if self.instrument.temp_iscalibrated:
# self.temp_id_is_calibr.setChecked(True)
# self.temp_id_is_calibr.setChecked(False)
def config_widgets_set_state(self, state):
self.dye_combo.setEnabled(state)
self.specIntTime_combo.setEnabled(state)
self.samplingInt_combo.setEnabled(state)
self.btn_save_config.setEnabled(state)
self.ship_code_combo.setEnabled(state)
self.temp_id_combo.setEnabled(state)
def manual_widgets_set_enabled(self, state):
logging.debug(f"widgets_enabled_change, state is '{state}'")
buttons = [
self.btn_adjust_light_intensity,
self.btn_light,
self.btn_valve,
self.btn_stirr,
self.btn_dye_pmp,
self.btn_wpump,
]
if self.args.co3:
buttons = buttons + [self.btn_drain, self.btn_shutter]
for widget in [*buttons, *self.plus_btns, *self.minus_btns, *self.sliders, *self.spinboxes]:
widget.setEnabled(state)
def make_btngroupbox(self):
# Define widgets for main tab
# Create checkabple buttons
self.buttons_groupBox = QGroupBox("Manual Control")
btn_grid = QGridLayout()
self.btn_adjust_light_intensity = self.create_button("Adjust Light", True)
self.btn_light = self.create_button("Light", True)
self.btn_light.clicked.connect(self.btn_light_clicked)
self.btn_valve = self.create_button("Inlet valve", True)
self.btn_stirr = self.create_button("Stirrer", True)
self.btn_dye_pmp = self.create_button("Dye pump", True)
self.btn_wpump = self.create_button("Water pump", True)
if self.args.co3:
self.btn_drain = self.create_button("Drain", True)
self.btn_shutter = self.create_button('Shutter', True)
self.btn_shutter.clicked.connect(self.btn_shutter_clicked)
btn_grid.addWidget(self.btn_shutter, 3, 1)
btn_grid.addWidget(self.btn_drain, 3, 0)
btn_grid.addWidget(self.btn_dye_pmp, 0, 0)
btn_grid.addWidget(self.btn_wpump, 0, 1)
btn_grid.addWidget(self.btn_adjust_light_intensity, 1, 0)
btn_grid.addWidget(self.btn_light, 1, 1)
btn_grid.addWidget(self.btn_valve, 2, 0)
btn_grid.addWidget(self.btn_stirr, 2, 1)