-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcold.py
More file actions
executable file
·1624 lines (1421 loc) · 77.3 KB
/
Copy pathcold.py
File metadata and controls
executable file
·1624 lines (1421 loc) · 77.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/env python3
import sys
import os
import yaml
import argparse
import logging
import time
from PyQt5 import QtWidgets, uic, QtGui
from PyQt5.QtCore import Qt, QTimer
from coldroom.system import System
from coldroom.thermal_camera_gui import ThermalCameraTab
from coldroom.modules_list_gui import ModulesListTab
from coldroom.module_temperatures_gui import ModuleTemperaturesTAB
from coldroom.safety import (
check_door_safe_to_open,
check_dew_point,
# check_hv_safe,
check_light_status,
check_door_status,
check_light_safe_to_turn_on,
check_marta_safe,
)
from caen.caenGUIall import caenGUIall
from Inner_tracker_GUI.caenGUIall_v2 import caenGUI8LV
from db.module_db import ModuleDB
from db.utils import *
# Configure logging
logger = logging.getLogger("integration")
class MainApp(QtWidgets.QMainWindow):
def __init__(self):
super(MainApp, self).__init__()
# Create system instance to hold references to all components
self.system = System()
self.mounted_modules = None
self.number_of_modules = 0 # Add this line
# Set up the main UI
self.setup_ui()
# Connect signals and slots
self.connect_signals()
# Setup update timer
self.update_timer = QTimer()
self.update_timer.timeout.connect(self.update_ui)
self.update_timer.start(1000) # Update every second
# Connect to MQTT broker at startup
self.connect_mqtt()
def closeEvent(self, event):
"""Handle application close event"""
try:
logger.info("Application closing, cleaning up resources...")
# Stop the update timer
if hasattr(self, "update_timer"):
self.update_timer.stop()
logger.debug("Stopped update timer")
# Cleanup Thermal Camera tab if it exists
if hasattr(self, "thermal_camera_tab"):
self.thermal_camera_tab.cleanup()
logger.debug("Cleaned up Thermal Camera tab")
# Cleanup MQTT connection
if hasattr(self, "system") and hasattr(self.system, "mqtt_client"):
self.system.mqtt_client.disconnect()
self.system.mqtt_client.loop_stop()
logger.debug("Disconnected MQTT client")
# Cleanup MARTA Cold Room client
if hasattr(self, "system") and hasattr(self.system, "_martacoldroom"):
self.system._martacoldroom.disconnect()
logger.debug("Disconnected MARTA Cold Room client")
# Cleanup system resources
if hasattr(self, "system"):
self.system.cleanup()
logger.debug("Cleaned up system resources")
# Close all tabs
if hasattr(self, "tab_widget"):
for i in range(self.tab_widget.count()):
widget = self.tab_widget.widget(i)
if hasattr(widget, "cleanup"):
widget.cleanup()
logger.debug("Cleaned up all tabs")
logger.info("All resources cleaned up successfully")
except Exception as e:
logger.error(f"Error during cleanup: {str(e)}")
# Still accept the close event even if cleanup fails
event.accept()
return
# Accept the close event
event.accept()
def setup_ui(self):
# Create main window with tab widget
self.setWindowTitle("Integration MQTT GUI")
self.resize(1200, 800)
self.message_box = QtWidgets.QMessageBox(self)
self.message_box.setWindowTitle("Safety Warning")
self.message_box.setIcon(QtWidgets.QMessageBox.Information)
self.message_box.setStandardButtons(QtWidgets.QMessageBox.Ok)
self.message_box.setDefaultButton(QtWidgets.QMessageBox.Ok)
# Create central widget and layout
self.central_widget = QtWidgets.QWidget()
self.setCentralWidget(self.central_widget)
self.main_layout = QtWidgets.QVBoxLayout(self.central_widget)
# Create tab widget
self.tab_widget = QtWidgets.QTabWidget()
self.main_layout.addWidget(self.tab_widget)
# Load the MARTA Cold Room tab from UI file
# Create a temporary QMainWindow to load the UI
temp_window = QtWidgets.QMainWindow()
marta_ui_file = os.path.join(os.path.dirname(__file__), "coldroom", "marta_coldroom.ui")
uic.loadUi(marta_ui_file, temp_window)
# Create a QWidget for our tab and get the central widget from temp_window
self.marta_coldroom_tab = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(self.marta_coldroom_tab)
layout.setContentsMargins(0, 0, 0, 0)
# Move the central widget from temp_window to our tab
central_widget = temp_window.centralWidget()
central_widget.setParent(self.marta_coldroom_tab)
layout.addWidget(central_widget)
# Add the tab to the tab widget
self.tab_widget.addTab(self.marta_coldroom_tab, "MARTA Cold Room")
self.modules_list_tab = ModulesListTab()
self.tab_widget.addTab(self.modules_list_tab, "Modules List")
# Add Thermal Camera tab
self.thermal_camera_tab = ThermalCameraTab(self.system)
self.tab_widget.addTab(self.thermal_camera_tab, "Thermal Camera")
self.module_temperatures_tab = ModuleTemperaturesTAB(self.system)
self.tab_widget.addTab(self.module_temperatures_tab, "Module Temperatures")
# Add OT_CAEN tab
self.caen_tab = caenGUIall()
self.tab_widget.addTab(self.caen_tab, "CAEN")
# Add Module DB tab
self.module_db = ModuleDB()
self.tab_widget.addTab(self.module_db.ui.tab_2, "Module Inventory")
self.tab_widget.addTab(self.module_db.ui.moduleDetailsTab, "Module Details")
self.module_db.ui.viewDetailsPB.clicked.connect(
lambda: self.tab_widget.setCurrentIndex(self.tab_widget.indexOf(self.module_db.ui.moduleDetailsTab))
)
self.module_db.ui.selectModulePB.setEnabled(False)
self.modules_list_tab.db_url = self.module_db.db_url
# Load settings tab from UI file
self.settings_tab = QtWidgets.QWidget()
settings_ui_file = os.path.join(os.path.dirname(__file__), "coldroom", "settings_coldroom.ui")
uic.loadUi(settings_ui_file, self.settings_tab)
self.tab_widget.addTab(self.settings_tab, "Settings")
# Add IT_CAEN tab
self.IT_caen_tab = caenGUI8LV()
self.tab_widget.addTab(self.IT_caen_tab, "IT CAEN")
# Pre-fill settings with values from system
self.load_settings_to_ui()
self.get_ring_id()
self.thermal_camera_tab.mounted_modules = self.mounted_modules
self.module_temperatures_tab.mounted_modules = self.mounted_modules
self.module_temperatures_tab.number_of_modules = self.number_of_modules
self.module_temperatures_tab.setup_module_temperature_table()
self.module_temperatures_tab.start_temperature_monitoring()
# Setup status bar
self.statusBar().showMessage("Ready")
logger.info("UI setup completed")
def get_ring_id(self):
self.number_of_modules = 0 # Add default at the start
self.ring_id=get_ring_from_cable("I1") #hardcode the single harting cable I1
if self.ring_id == None:
ring_history_file = os.path.join(os.path.dirname(__file__), "ring_history.txt")
if os.path.exists(ring_history_file):
with open(ring_history_file, "r") as f:
lines = f.readlines()
if lines:
self.ring_id = lines[-1].strip()
else:
self.ring_id = None
#TODO: move this to the right place so it works also when ring ID LineEdit is updated
if self.ring_id != None:
self.modules_list_tab.ring_id_LE.setText(self.ring_id)
logger.info(f"Loaded ring ID from history: {self.ring_id}")
self.get_mounted_modules()
if self.ring_id.startswith("L1_"):
self.number_of_modules = 18
elif self.ring_id.startswith("L2_"):
self.number_of_modules = 26
elif self.ring_id.startswith("L3_"):
self.number_of_modules = 36
self.modules_list_tab.populate_from_config(
self.caen_tab, self.mounted_modules, self.number_of_modules, self.thermal_camera_tab
)
return self.ring_id
def setup_ring_id(self):
self.ring_id = self.modules_list_tab.ring_id_LE.text().strip()
if not self.ring_id:
self.message_box.setText("Please enter a valid ring ID.")
self.message_box.exec_()
return
self.get_mounted_modules()
if self.ring_id.startswith("L1_"):
self.number_of_modules = 18
elif self.ring_id.startswith("L2_"):
self.number_of_modules = 26
elif self.ring_id.startswith("L3_"):
self.number_of_modules = 36
else:
self.message_box.setText("Invalid ring ID format. Must start with L1_, L2_, or L3_.")
self.message_box.exec_()
self.modules_list_tab.populate_from_config(self.caen_tab, self.mounted_modules, self.number_of_modules)
def save_ring_id(self):
ring_history_file = os.path.join(os.path.dirname(__file__), "ring_history.txt")
with open(ring_history_file, "a") as f:
f.write(f"{self.ring_id}\n")
logger.info(f"Ring ID {self.ring_id} saved successfully.")
def get_mounted_modules(self):
self.mounted_modules = get_modules_on_ring(self.ring_id, db_url=self.module_db.db_url)
for module_name in self.mounted_modules:
self.mounted_modules[module_name].update(get_module_endpoints(module_name, db_url=self.module_db.db_url))
self.mounted_modules[module_name].update(
{"speed": get_module_speed(module_name, db_url=self.module_db.db_url)}
)
self.mounted_modules[module_name].update(
{"fuseId": get_module_fuse_id(module_name, db_url=self.module_db.db_url)}
)
self.mounted_modules[module_name].update(
{
"temperature_offsets": get_module(module_name, db_url=self.module_db.db_url).get(
"temperature_offsets", {}
)
}
)
logger.debug(f"Mounted modules for ring {self.ring_id}: {self.mounted_modules}")
return self.mounted_modules
def load_settings_to_ui(self):
# Fill settings UI with current values
self.settings_tab.brokerLineEdit.setText(self.system.settings["mqtt"]["broker"])
self.settings_tab.portSpinBox.setValue(self.system.settings["mqtt"]["port"])
self.settings_tab.martaTopicLineEdit.setText(self.system.settings["MARTA"]["mqtt_topic"])
self.settings_tab.coldroomTopicLineEdit.setText(self.system.settings["Coldroom"]["mqtt_topic"])
self.settings_tab.co2SensorTopicLineEdit.setText(self.system.settings["Coldroom"]["co2_sensor_topic"])
self.settings_tab.thermalCameraTopicLineEdit.setText(self.system.settings["ThermalCamera"]["mqtt_topic"])
self.settings_tab.cleanroomTopicLineEdit.setText(self.system.settings["Cleanroom"]["mqtt_topic"])
def connect_signals(self):
# Module list
self.modules_list_tab.enter_ring_id_button.clicked.connect(self.setup_ring_id)
self.modules_list_tab.save_ring_id_button.clicked.connect(self.save_ring_id)
# Connect settings tab
self.settings_tab.saveButton.clicked.connect(self.save_settings)
def configure_line_edit(field_name, placeholder):
le = self.marta_coldroom_tab.findChild(QtWidgets.QLineEdit, field_name)
if le:
le.setPlaceholderText(placeholder)
le.setStyleSheet("QLineEdit { color: grey; }")
# Connect signals
le.textChanged.connect(lambda: le.setStyleSheet("QLineEdit { color: black; }"))
le.editingFinished.connect(lambda: le.setPlaceholderText(placeholder) if le.text() == "" else None)
# Light controls
self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_light_on_PB").clicked.connect(
self.coldroom_light_on
)
self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_light_off_PB").clicked.connect(
self.coldroom_light_off
)
# Dry air controls
self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_dry_air_on_PB").clicked.connect(
self.coldroom_dry_air_on
)
self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_dry_air_off_PB").clicked.connect(
self.coldroom_dry_air_off
)
# Dry air bypass controls
self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_dry_air_bypass_on_PB").clicked.connect(
self.coldroom_dry_air_bypass_on
)
self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_dry_air_bypass_off_PB").clicked.connect(
self.coldroom_dry_air_bypass_off
)
# Door controls
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_door_toggle_PB")
if button:
button.clicked.connect(self.toggle_coldroom_door)
# Temperature controls
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_temp_ctrl_PB")
if button:
button.clicked.connect(self.toggle_coldroom_temp_control)
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_run_start")
if button:
button.clicked.connect(self.system._martacoldroom.run)
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_run_stop")
if button:
button.clicked.connect(self.system._martacoldroom.stop)
configure_line_edit("coldroom_temp_LE", "-30°C to 30°C")
configure_line_edit("coldroom_humidity_LE", "0% to 50%")
# Temperature setpoint label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "coldroom_temp_set_point_label")
if label:
logger.debug("Connected temperature set point label")
# Humidity setpoint label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "coldroom_humidity_set_point_label")
if label:
logger.debug("Connected humidity set point label")
# Temperature control LED
ctrl_temp_led = self.marta_coldroom_tab.findChild(QtWidgets.QFrame, "ctrl_temp_LED")
if ctrl_temp_led:
logger.debug("Connected temperature control LED")
# Humidity control LED
ctrl_humidity_led = self.marta_coldroom_tab.findChild(QtWidgets.QFrame, "ctrl_humidity_LED")
if ctrl_humidity_led:
logger.debug("Connected humidity control LED")
# Light control LED
light_led = self.marta_coldroom_tab.findChild(QtWidgets.QFrame, "light_LED")
if light_led:
logger.debug("Connected light control LED")
# Dry air control LED
dry_air_led = self.marta_coldroom_tab.findChild(QtWidgets.QFrame, "dryair_LED")
if dry_air_led:
logger.debug("Connected dry air control LED")
# Safe to open LED
safe_to_open_led = self.marta_coldroom_tab.findChild(QtWidgets.QFrame, "safe_to_open_LED")
if safe_to_open_led:
logger.debug("Connected safe to open LED")
# Door state label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "coldroom_door_state_label")
if label:
logger.debug("Connected door state label")
# Temperature setpoint controls
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_temp_set_PB")
if button:
button.clicked.connect(self.set_coldroom_temperature)
# Humidity controls
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_humidity_ctrl_PB")
if button:
button.clicked.connect(self.toggle_coldroom_humidity_control)
# Humidity setpoint controls
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_humidity_set_PB")
if button:
button.clicked.connect(self.set_coldroom_humidity)
# Run controls
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_run_toggle_PB")
if button:
button.clicked.connect(self.toggle_coldroom_run)
# Reset alarms
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "coldroom_reset_alarms_PB")
if button:
button.clicked.connect(self.reset_coldroom_alarms)
# MARTA CO2 Plant controls
# Temperature controls
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "marta_temp_set_PB")
if button:
button.clicked.connect(self.set_marta_temperature)
configure_line_edit("marta_temp_LE", "-30°C to 18°C") # Placeholder for temperature input
# Speed controls
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "marta_speed_set_PB")
if button:
button.clicked.connect(self.set_marta_speed)
configure_line_edit("marta_speed_LE", "5000 to 6000 RPM") # Placeholder for speed input
# Flow controls
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "marta_flow_set_PB")
if button:
button.clicked.connect(self.set_marta_flow)
configure_line_edit("marta_flow_LE", "0 to 5 L/min") # Placeholder for flow input
# Supply temperature label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "marta_temp_supply_value_label")
if label:
logger.debug("Connected supply temperature label")
# Return temperature label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "marta_temp_return_value_label")
if label:
logger.debug("Connected return temperature label")
# Supply pressure label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "marta_pressure_supply_value_label")
if label:
logger.debug("Connected supply pressure label")
# Return pressure label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "marta_pressure_return_value_label")
if label:
logger.debug("Connected return pressure label")
# Speed label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "marta_speed_value_label")
if label:
logger.debug("Connected speed label")
# Temperature Set Point Label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "marta_temp_set_point_label")
if label:
logger.debug("Connected temperature set point label")
# Speed Set Point Label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "marta_speed_set_point_label")
if label:
logger.debug("Connected speed set point label")
# Flow Set Point Label
label = self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "marta_flow_set_point_label")
if label:
logger.debug("Connected flow set point label")
# Other MARTA controls
# Start chiller button
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "marta_chiller_start_PB")
if button:
button.clicked.connect(self.start_marta_chiller)
# Start CO2 button
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "marta_co2_start_PB")
if button:
button.clicked.connect(self.start_marta_co2)
# Stop CO2 button
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "marta_co2_stop_PB")
if button:
button.clicked.connect(self.stop_marta_co2)
# Stop chiller button
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "marta_chiller_stop_PB")
if button:
button.clicked.connect(self.stop_marta_chiller)
# Clear alarms button
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "marta_alarms_clear_PB")
if button:
button.clicked.connect(self.clear_marta_alarms)
# Reconnect button
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "marta_reconnect_PB")
if button:
button.clicked.connect(self.reconnect_marta)
# Refresh button
button = self.marta_coldroom_tab.findChild(QtWidgets.QPushButton, "marta_refresh_PB")
if button:
button.clicked.connect(self.refresh_marta)
# Flow active checkbox
checkbox = self.marta_coldroom_tab.findChild(QtWidgets.QCheckBox, "marta_flow_active_CB")
if checkbox:
checkbox.clicked.connect(self.toggle_marta_flow_active)
# Add debug logging for all connections
# Log all connections
logger.debug("Signal connections:")
for button in self.marta_coldroom_tab.findChildren(QtWidgets.QPushButton):
logger.debug(f"Found button: {button.objectName()}")
for checkbox in self.marta_coldroom_tab.findChildren(QtWidgets.QCheckBox):
logger.debug(f"Found checkbox: {checkbox.objectName()}")
# Update validators to match placeholder ranges
temp_lineedit_coldroom = self.marta_coldroom_tab.findChild(QtWidgets.QLineEdit, "coldroom_temp_LE")
if temp_lineedit_coldroom:
temp_lineedit_coldroom.setValidator(QtGui.QDoubleValidator(-30, 30, 2)) # Matches placeholder
humid_lineedit_coldroom = self.marta_coldroom_tab.findChild(QtWidgets.QLineEdit, "coldroom_humidity_LE")
if humid_lineedit_coldroom:
humid_lineedit_coldroom.setValidator(QtGui.QDoubleValidator(0, 50, 2))
# Add input validation for numeric fields
temp_lineedit = self.marta_coldroom_tab.findChild(QtWidgets.QLineEdit, "marta_temp_LE")
if temp_lineedit:
validator = QtGui.QDoubleValidator(-30, 18, 2) # min, max, decimals
temp_lineedit.setValidator(validator)
# Add input validation for numeric fields
speed_lineedit = self.marta_coldroom_tab.findChild(QtWidgets.QLineEdit, "marta_speed_LE")
if speed_lineedit:
validator = QtGui.QDoubleValidator(5000, 6000, 0) # min, max, decimals
speed_lineedit.setValidator(validator)
# Add input validation for numeric fields
flow_lineedit = self.marta_coldroom_tab.findChild(QtWidgets.QLineEdit, "marta_flow_LE")
if flow_lineedit:
validator = QtGui.QDoubleValidator(0, 5, 2) # min, max, decimals
flow_lineedit.setValidator(validator)
def connect_mqtt(self):
"""Connect to MQTT broker using settings"""
try:
# Get broker settings from system
server = self.system.settings["mqtt"]["broker"]
port = self.system.settings["mqtt"]["port"]
# Update system broker and port (in case they were changed)
self.system.BROKER = server
self.system.PORT = port
# Start MQTT thread
self.system.start_mqtt_thread()
# Update status
status_msg = f"Connected to MQTT broker at {server}:{port}"
self.statusBar().showMessage(status_msg)
logger.info(status_msg)
except Exception as e:
error_msg = f"Failed to connect to MQTT broker: {str(e)}"
self.statusBar().showMessage(error_msg)
logger.error(error_msg)
def update_ui(self):
"""Update UI with current system status"""
try:
self.system._martacoldroom._cleanroom_last_update_elapsed_time = (
time.time() - self.system._martacoldroom._cleanroom_last_update_timer
)
self.system.status["cleanroom"][
"elapsed_time"
] = self.system._martacoldroom._cleanroom_last_update_elapsed_time
self.modules_list_tab.light_on = check_light_status(self.system.status)
# Get the central widget
central = self.marta_coldroom_tab
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# =========================================================================================== CLEANROOM ===========================================================================================
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# Update Cleanroom values from system status
if "cleanroom" in self.system.status:
cleanroom = self.system.status["cleanroom"]
logger.debug(f"Updating Cleanroom UI with status: {cleanroom}")
# Temperature
label = central.findChild(QtWidgets.QLabel, "cleanroom_temp_value_label")
if label and "temperature" in cleanroom and cleanroom["temperature"] is not None:
temp_value = cleanroom["temperature"]
label.setText(f"{temp_value:.1f}")
logger.debug(f"Updated Cleanroom temperature: {temp_value}")
# Humidity
label = central.findChild(QtWidgets.QLabel, "cleanroom_humidity_value_label")
if label and "humidity" in cleanroom and cleanroom["humidity"] is not None:
humid_value = cleanroom["humidity"]
label.setText(f"{humid_value:.1f}")
logger.debug(f"Updated Cleanroom humidity: {humid_value}")
# Dewpoint
label = central.findChild(QtWidgets.QLabel, "cleanroom_dewpoint_value_label")
if label and "dewpoint" in cleanroom and cleanroom["dewpoint"] is not None:
dewpoint = cleanroom["dewpoint"]
label.setText(f"{dewpoint:.1f}")
logger.debug(f"Updated Cleanroom dewpoint: {dewpoint}")
# Pressure
label = central.findChild(QtWidgets.QLabel, "cleanroom_pressure_value_label")
if label and "pressure" in cleanroom and cleanroom["pressure"] is not None:
pressure = cleanroom["pressure"]
label.setText(f"{pressure:.1f}")
logger.debug(f"Updated Cleanroom pressure: {pressure}")
label = central.findChild(QtWidgets.QLabel, "cleanroom_last_update_value_label")
if label and "last_update" in cleanroom and cleanroom["last_update"] is not None:
last_update = cleanroom["last_update"]
label.setText(f"{last_update}")
logger.debug(f"Updated Cleanroom last update: {last_update}")
label = central.findChild(QtWidgets.QLabel, "cleanroom_last_update_value_label_2")
if label:
delta_t_update = self.system._martacoldroom._cleanroom_last_update_elapsed_time
delta_t_update = time.strftime("%H:%M:%S", time.gmtime(delta_t_update))
label.setText(delta_t_update)
logger.debug(f"Updated Cleanroom delta t update: {delta_t_update}")
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# =========================================================================================== COLDROOM ===========================================================================================
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# Update Cold Room values from system status
if "coldroom" in self.system.status:
coldroom = self.system.status["coldroom"]
logger.debug(f"Updating Coldroom UI with status: {coldroom}")
temp_control_active = coldroom.get("ch_temperature", {}).get("status", False)
hum_control_active = coldroom.get("ch_humidity", {}).get("status", False)
# =========================================================================================== COLDROOM TEMPERATURE PROCESS ===========================================================================================
# Temperature Current Value
if "ch_temperature" in coldroom:
# Current temperature
label = central.findChild(QtWidgets.QLabel, "coldroom_temp_value_label")
if label:
temp_value = coldroom["ch_temperature"].get("value", "?")
label.setText(f"{temp_value:.1f}")
logger.debug(f"Updated temperature: {temp_value}")
# Temperature control LED
if "ch_temperature" in coldroom:
if "status" in coldroom["ch_temperature"]:
# Update Temperature control LED
ctrl_temp_led = central.findChild(QtWidgets.QFrame, "ctrl_temp_LED")
if ctrl_temp_led:
ctrl_temp_led.setStyleSheet(
"background-color: green;"
if coldroom["ch_temperature"]["status"]
else "background-color: black;"
) # LED is green when ON
logger.debug(
f"Updated temp control LED: {'green' if coldroom['ch_temperature']['status'] else 'black'}"
)
# Temperature setpoint lineedit
lineedit = central.findChild(QtWidgets.QLineEdit, "coldroom_temp_LE")
if lineedit:
user_has_entered_value = bool(lineedit.text().strip())
# Case 1: User is actively typing - preserve their input
if lineedit.hasFocus():
pass
# Case 2: User has entered a value - use that value
elif temp_control_active and user_has_entered_value:
coldroom_temp_lE_active_flag = True
setpoint = lineedit.text()
lineedit.setText(str(setpoint))
logger.debug(f"Updated temperature setpoint: {setpoint}")
else:
coldroom_temp_lE_active_flag = False
lineedit.clear()
logger.debug("Cleared temperature setpoint")
# Temperature setpoint label
if "ch_temperature" in coldroom:
if "setpoint" in coldroom["ch_temperature"]:
label = central.findChild(QtWidgets.QLabel, "coldroom_temp_set_point_label")
if label:
temp_setpoint = coldroom["ch_temperature"]["setpoint"]
label.setText(f"{temp_setpoint:.1f}")
logger.debug(f"Updated temperature setpoint: {temp_setpoint}")
# =========================================================================================== COLDROOM HUMIDITY PROCESS ===========================================================================================
# Humidity Current Value
if "ch_humidity" in coldroom:
# Current humidity
label = central.findChild(QtWidgets.QLabel, "coldroom_humidity_value_label")
if label:
humid_value = coldroom["ch_humidity"].get("value", "?")
label.setText(f"{humid_value:.1f}")
logger.debug(f"Updated humidity: {humid_value}")
# Humidity control LED
if "ch_humidity" in coldroom:
if "status" in coldroom["ch_humidity"]:
# Update Humidity control LED
ctrl_humidity_led = central.findChild(QtWidgets.QFrame, "ctrl_humidity_LED")
if ctrl_humidity_led:
ctrl_humidity_led.setStyleSheet(
"background-color: green;"
if coldroom["ch_humidity"]["status"]
else "background-color: black;"
) # LED is green when ON
logger.debug(
f"Updated humidity control LED: {'green' if coldroom['ch_humidity']['status'] else 'black'}"
)
# Humidity setpoint lineedit
lineedit = central.findChild(QtWidgets.QLineEdit, "coldroom_humidity_LE")
if lineedit:
user_has_entered_value = bool(lineedit.text().strip())
# Case 1: User is actively typing - preserve their input
if lineedit.hasFocus():
pass
# Case 2: User has entered a value - use that value
elif hum_control_active and user_has_entered_value:
coldroom_humidity_lE_active_flag = True
setpoint = lineedit.text()
lineedit.setText(str(setpoint))
logger.debug(f"Updated humidity setpoint: {setpoint}")
else:
coldroom_humidity_lE_active_flag = False
lineedit.clear()
logger.debug("Cleared humidity setpoint")
# Humidity setpoint label
if "ch_humidity" in coldroom:
if "setpoint" in coldroom["ch_humidity"]:
label = central.findChild(QtWidgets.QLabel, "coldroom_humidity_set_point_label")
if label:
humid_setpoint = coldroom["ch_humidity"]["setpoint"]
label.setText(f"{humid_setpoint:.1f}")
logger.debug(f"Updated humidity setpoint: {humid_setpoint}")
# =========================================================================================== COLDROOM DEWPOINT PROCESS ===========================================================================================
# Dewpoint (from coldroom data)
label = central.findChild(QtWidgets.QLabel, "coldroom_dewpoint_value_label")
if label and "dew_point_c" in coldroom:
dewpoint = coldroom["dew_point_c"]
label.setText(f"{dewpoint:.1f}")
logger.debug(f"Updated dewpoint: {dewpoint}")
# =========================================================================================== COLDROOM LIGHT PROCESS ===========================================================================================
# Light status and LED
if "light" in coldroom:
# Update light LED
light_led = central.findChild(QtWidgets.QFrame, "light_LED")
if light_led:
light_led.setStyleSheet(
"background-color: yellow;" if coldroom["light"] else "background-color: black;"
) # LED is yellow when ON
logger.debug(f"Updated light LED: {'yellow' if coldroom['light'] else 'black'}")
if bool(coldroom["light"]) is False:
logger.debug("Light off, check if it is safe")
used_caen_channels = self.modules_list_tab.get_used_channels()
is_safe = check_light_safe_to_turn_on(
self.system.status, self.caen_tab.last_response, used_caen_channels
)
button = central.findChild(QtWidgets.QPushButton, "coldroom_light_on_PB")
if not is_safe:
logger.debug("not safe")
if button:
button.setEnabled(False)
logger.debug("Disabled light button due to safety check")
else:
if button:
button.setEnabled(True)
logger.debug("Enabled light button after safety check")
# Dry air bypass
dryair_bypass_led = central.findChild(QtWidgets.QFrame, "dryair_bypass_LED")
coldroom_air = self.system.status.get("coldroomair", {})
if dryair_bypass_led:
if "air_bypass_status" in coldroom_air:
dryair_bypass_led.setStyleSheet(
"background-color: green;" if coldroom_air["air_bypass_status"] else "background-color: red;"
)
logger.debug(
f"Updated dry air bypass LED: {'green' if coldroom_air['air_bypass_status'] else 'red'}"
)
else:
dryair_bypass_led.setStyleSheet("background-color: yellow;")
logger.debug("Set dry air bypass LED to grey (unknown status)")
# =========================================================================================== COLDROOM DOOR PROCESS ===========================================================================================
# Door status and LED
if "CmdDoorUnlock_Reff" in coldroom:
door_status = "OPEN" if coldroom["CmdDoorUnlock_Reff"] else "CLOSED"
label = central.findChild(QtWidgets.QLabel, "coldroom_door_state_label")
if label:
label.setText(door_status)
logger.debug(f"Updated door status: {door_status}")
# =========================================================================================== COLDROOM RUN PROCESS ===========================================================================================
# Update safe to open LED based on door safety check
safe_to_open_led = central.findChild(QtWidgets.QFrame, "safe_to_open_LED")
if safe_to_open_led:
used_caen_channels = self.modules_list_tab.get_used_channels()
is_safe, door_msg = check_door_safe_to_open(
self.system.status, self.caen_tab.last_response, used_caen_channels
)
# Check co2 values
if "co2_sensor" in self.system.status:
co2_data = self.system.status["co2_sensor"]
if "CO2" in co2_data:
if co2_data["CO2"] > 800:
is_safe = False
door_msg += "CO2 levels safe: False"
else:
door_msg += "CO2 levels safe: True"
safe_to_open_led.setStyleSheet("background-color: green;" if is_safe else "background-color: red;")
logger.debug(f"Updated safe to open LED: {'green' if is_safe else 'red'} (is_safe={is_safe})")
self.system._martacoldroom.publish_door_safety_status(is_safe)
self.marta_coldroom_tab.findChild(QtWidgets.QLabel, "door_safety_msg").setText(door_msg)
# =========================================================================================== COLDROOM RUN PROCESS ===========================================================================================
# Run status
if "running" in coldroom:
label = central.findChild(QtWidgets.QLabel, "coldroom_run_state_label")
if label:
run_text = "Running" if coldroom["running"] else "Stopped"
label.setText(run_text)
logger.debug(f"Updated run state label: {run_text}")
# =========================================================================================== COLDROOM DRY AIR PROCESS ===========================================================================================
# External dry air status
if "dry_air_status" in coldroom:
# Update dry air LED
dry_air_led = central.findChild(QtWidgets.QFrame, "dryair_LED")
if dry_air_led:
dry_air_led.setStyleSheet(
"background-color: green;" if coldroom["dry_air_status"] else "background-color: red;"
)
logger.debug(f"Updated dry air LED: {'green' if coldroom['dry_air_status'] else 'red'}")
# Update CO2 sensor data
if "co2_sensor" in self.system.status:
co2_data = self.system.status["co2_sensor"]
logger.debug(f"Updating CO2 sensor data: {co2_data}")
# # Update CO2 level
# label = central.findChild(QtWidgets.QLabel, "coldroom_co2_value_label")
# if label and "CO2" in co2_data:
# co2_value = co2_data["CO2"]
# label.setText(f"{co2_value:.1f}")
# logger.debug(f"Updated CO2 level: {co2_value}")
# if co2_value > 800 and co2_value <= 1000:
# label.setStyleSheet("color: pink;")
# elif co2_value > 1000 and co2_value <= 2500:
# label.setStyleSheet("color: orange;")
# elif co2_value > 2500:
# label.setStyleSheet("color: red;")
# Update CO2 level
label = central.findChild(QtWidgets.QLabel, "coldroom_co2_value_label")
if label and "CO2" in co2_data:
co2_value = co2_data["CO2"]
label.setText(f"{co2_value:.1f}")
logger.debug(f"Updated CO2 level: {co2_value}")
# Optional: common styling for visibility
base_style = """
QLabel {
font-weight: bold;
padding: 2px 6px;
border-radius: 4px;
}
"""
if 800 < co2_value <= 1000:
label.setStyleSheet(base_style + """
QLabel {
color: #ffb6c1;
background-color: #4a1f2a;
}
""")
elif 1000 < co2_value <= 2500:
label.setStyleSheet(base_style + """
QLabel {
color: #ffa500;
background-color: #3a2600;
}
""")
elif co2_value > 2500:
label.setStyleSheet(base_style + """
QLabel {
color: #ff4d4d;
background-color: #3a0000;
}
""")
else:
label.setStyleSheet(base_style + """
QLabel {
color: black;
background-color: transparent;
}
""")
# check alarms
if "alarm" in self.system.status:
label = central.findChild(QtWidgets.QLabel, "alarm_value")
if label:
alarm_value = self.system.status.get("alarm", "None")
label.setText(f"{alarm_value}")
logger.debug(f"Updated alarm value: {alarm_value}")
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# =========================================================================================== MARTA ===========================================================================================
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
self.modules_list_tab.marta_safe, self.modules_list_tab.marta_log_msg = check_marta_safe(self.system.status)
# Update MARTA CO2 Plant values
if "marta" in self.system.status:
marta = self.system.status["marta"]
logger.debug(f"Updating MARTA UI with status: {marta}")
# =========================================================================================== MARTA FSM STATE PROCESS ===========================================================================================
# Update FSM state
if "fsm_state" in marta:
state_label = central.findChild(QtWidgets.QLabel, "marta_state_label")
if state_label:
state_label.setText(marta["fsm_state"])
logger.debug(f"Updated MARTA state: {marta['fsm_state']}")
# Update state-specific UI elements
if marta["fsm_state"] == "ALARM":
# Highlight alarm state
alarm_frame = central.findChild(QtWidgets.QFrame, "marta_alarm_frame")
if alarm_frame:
alarm_frame.setStyleSheet("background-color: red;")
# Show alarm message
alarm_msg = central.findChild(QtWidgets.QLabel, "marta_alarm_msg_label")
if alarm_msg and "alarm_message" in marta:
alarm_msg.setText(marta["alarm_message"])
else:
# Clear alarm highlighting
alarm_frame = central.findChild(QtWidgets.QFrame, "marta_alarm_frame")
if alarm_frame:
alarm_frame.setStyleSheet("")
# =========================================================================================== MARTA TEMPERATURE PROCESS ===========================================================================================
# Temperature from TT05_CO2 (Supply)
if "TT05_CO2" in marta:
label = central.findChild(QtWidgets.QLabel, "marta_temp_supply_value_label")
if label:
temp_value = marta["TT05_CO2"]
label.setText(f"{temp_value:.1f}")
logger.debug(f"Updated MARTA supply temperature: {temp_value}")
# Temperature from TT06_CO2 (Return)
if "TT06_CO2" in marta:
label = central.findChild(QtWidgets.QLabel, "marta_temp_return_value_label")
if label:
temp_value = marta["TT06_CO2"]
label.setText(f"{temp_value:.1f}")
logger.debug(f"Updated MARTA return temperature: {temp_value}")
# Temperature setpoint
lineedit = central.findChild(QtWidgets.QLineEdit, "marta_temp_LE")
if lineedit:
user_has_entered_value = bool(lineedit.text().strip())
# Case 1: User is actively typing - preserve their input
if lineedit.hasFocus():
pass
# Case 2: User has entered a value - use that value
elif temp_control_active and user_has_entered_value:
marta_temp_lE_active_flag = True
temp_setpoint = lineedit.text()
lineedit.setText(str(temp_setpoint))
logger.debug(f"Updated MARTA temperature setpoint: {temp_setpoint}")
else:
marta_temp_lE_active_flag = False
lineedit.clear()
logger.debug("Cleared MARTA temperature setpoint")
# Temperature setpoint label
if "temperature_setpoint" in marta:
label = central.findChild(QtWidgets.QLabel, "marta_temp_set_point_label")
if label:
temp_setpoint = marta["temperature_setpoint"]
label.setText(f"{temp_setpoint:.1f}")
logger.debug(f"Updated MARTA temperature setpoint: {temp_setpoint}")
# =========================================================================================== MARTA PRESSURE PROCESS ===========================================================================================
# Pressure from PT05_CO2 (Supply)
if "PT05_CO2" in marta:
label = central.findChild(QtWidgets.QLabel, "marta_pressure_supply_value_label")
if label:
pressure_value = marta["PT05_CO2"]
label.setText(f"{pressure_value:.3f}")
logger.debug(f"Updated MARTA supply pressure: {pressure_value}")
# Pressure from PT06_CO2 (Return)
if "PT06_CO2" in marta:
label = central.findChild(QtWidgets.QLabel, "marta_pressure_return_value_label")
if label:
pressure_value = marta["PT06_CO2"]
label.setText(f"{pressure_value:.3f}")
logger.debug(f"Updated MARTA return pressure: {pressure_value}")
# =========================================================================================== MARTA SPEED PROCESS ===========================================================================================
# Speed
if "LP_speed" in marta:
label = central.findChild(QtWidgets.QLabel, "marta_speed_value_label")