-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathintegration.py
More file actions
executable file
·2122 lines (1796 loc) · 95.3 KB
/
Copy pathintegration.py
File metadata and controls
executable file
·2122 lines (1796 loc) · 95.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
#!/usr/bin/env python3
import threading
import ui.integration_gui as integration_gui
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QVBoxLayout, QWidget,
QLineEdit, QLabel, QFormLayout, QTreeWidgetItem,
QTreeWidget, QMessageBox, QPushButton, QInputDialog, QHBoxLayout, QSpacerItem, QSizePolicy, QComboBox
)
from PyQt5.QtGui import QPen
from PyQt5.QtCore import Qt, QTimer, pyqtSignal, QObject, QThread, QSize, QUrl
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView
from PyQt5.QtWebEngineWidgets import QWebEngineView
from math import *
import requests
import subprocess
import yaml
import os
import paho.mqtt.client as mqtt
import struct
import numpy as np
from caen.caenGUI import CAENControl
import json
# Set matplotlib backend before importing pyplot
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from mpl_toolkits.axes_grid1 import make_axes_locatable
import struct
import numpy as np
import webbrowser
import os.path
import re
from datetime import datetime
from db.module_db import ModuleDB
from db.utils import get_module_fuse_id
# Add this class near the top of the file
class LogEmitter(QObject):
"""Helper class to emit log messages from any thread"""
log_message = pyqtSignal(str)
# Add new CommandWorker class
class CommandWorker(QThread):
finished = pyqtSignal(bool, str, str) # success, stdout, stderr
def __init__(self, command):
super().__init__()
self.command = command
def run(self):
try:
expanded_command = self.command
#open spinning wheel dialog
result = subprocess.run(expanded_command, shell=True,
capture_output=True, text=True)
self.finished.emit(result.returncode == 0, result.stdout, result.stderr)
#create a waiting dialog
# Create a waiting dialog
except Exception as e:
self.finished.emit(False, "", str(e))
class MainApp(integration_gui.Ui_MainWindow):
def __init__(self, window):
# First call setupUi to create all UI elements from the .ui file
self.setupUi(window)
# Add Ph2ACF topic to API settings layout programmatically
# Need to do this before load_settings
self.ph2acfTopicLabel = QLabel("Ph2ACF Topic:")
self.ph2acfTopicLE = QLineEdit()
self.ph2acfTopicLE.setObjectName("ph2acfTopicLE")
self.formLayout_2.addRow(self.ph2acfTopicLabel, self.ph2acfTopicLE)
# Load settings before setting up connections
self.load_settings()
# Connect settings change
self.ph2acfTopicLE.textChanged.connect(self.save_settings)
# Create ModuleDB instance
self.module_db = ModuleDB()
# Replace inventory and details tabs with ModuleDB tabs
self.tabWidget.insertTab(1,self.module_db.ui.tab_2, "Module Inventory")
self.tabWidget.insertTab(2,self.module_db.ui.moduleDetailsTab, "Module Details")
# Connect module selection signal
self.module_db.module_selected.connect(self.on_module_selected)
self.module_db.ui.viewDetailsPB.clicked.connect(self.view_module_details)
# Set stretch factors for the main grid layout to make left side expand more
# grid_layout = self.tab.layout()
# grid_layout.setColumnStretch(0, 2) # Left column gets 2 parts
# grid_layout.setColumnStretch(1, 1) # Right column gets 1 part
# Set up square aspect ratio for graphics view
self.graphicsView.setMinimumSize(300, 300)
self.graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
# Create a custom resize event for the graphics view
# def resizeEvent(event):
# # Get the smaller of width or height
# size = min(event.size().width(), event.size().height())
# # Create a square size
# square_size = QSize(size, size)
# # Resize to square
# self.graphicsView.resize(square_size)
# # Call parent resize event
# QGraphicsView.resizeEvent(self.graphicsView, event)
# # Attach the custom resize event
# self.graphicsView.resizeEvent = resizeEvent
# Initialize log emitter
self.log_emitter = LogEmitter()
self.log_emitter.log_message.connect(self.append_log)
# Fix text format setting
self.placeholdersHelpLabel.setTextFormat(Qt.PlainText)
# Initialize MQTT client to None
self.client = None
# Initialize air state
self.air_state = False
# Store the full module list for filtering - initialize before using
self.all_modules = []
# # Add search box - move this before connecting signals
# searchLayout = QHBoxLayout()
# searchLabel = QLabel("Search:")
# self.searchBox = QLineEdit()
# self.searchBox.setPlaceholderText("Search modules...")
# searchLayout.addWidget(searchLabel)
# searchLayout.addWidget(self.searchBox)
# searchLayout.addStretch()
# # Insert search layout before the tree widget
# layout = self.tab_2.layout()
# layout.insertLayout(1, searchLayout)
# Enable sorting
# self.treeWidget.setSortingEnabled(True)
# Enable sorting
# self.treeWidget.setSortingEnabled(True)
# Initialize lists for Ph2ACF temperatures
self.ph2acf_time = []
self.ssa_mean_values = []
self.ssa_max_values = []
self.mpa_mean_values = []
self.mpa_max_values = []
self.current_fuse_id = None
# Setup module details tab
# self.setup_module_details_tab()
# Now connect signals after UI elements exist
# self.searchBox.textChanged.connect(self.filter_modules)
self.ringLE.returnPressed.connect(self.split_ring_and_position)
self.positionLE.returnPressed.connect(self.draw_ring)
self.mountPB.clicked.connect(self.mount_module)
self.unmountPB.clicked.connect(self.unmount_module)
# Initialize mounted modules dict
self.mounted_modules = {}
self.analysisURL=""
fibers=["SfibA","SfibB"]
fibers+=[f"E3;{x}" for x in range(1,6)]
powers=["BINT1"]
powers+=[f"R01;M1.{x}" for x in range(1,13)]
powers+=[f"R01;M2.{x}" for x in range(1,13)]
powers+=[f"R01;M3.{x}" for x in range(1,13)]
self.layers_to_filters = {
"L1_47": {
"spacer": "2.6mm",
"speed": "10G",
},
"L1_60": {
"spacer": "4.0mm",
"speed": "10G",
},
"L1_72": {
"spacer": "4.0mm",
"speed": "10G",
},
#40,55,68
"L2_40": {
"spacer": "2.6mm",
"speed": "10G",
},
"L2_55": {
"spacer": "2.6mm",
"speed": "10G",
},
"L2_68": {
"spacer": "4.0mm",
"speed": "10G",
},
"L3": {
"spacer": "2.6mm",
"speed": "5G",
},
}
self.fiberCB.addItems(fibers)
self.powerCB.addItems(powers)
self.number_of_modules=18
# config_dir = os.path.expanduser("~/.config/integration_ui")
#load last session from ~/.config/integration_ui/lastsession.txt
# Setup thermal camera plotting
self.setup_thermal_plot()
# Setup CAEN control
self.caen = CAENControl(self)
# Connect button signals
self.checkIDPB.clicked.connect(self.run_check_id)
self.hvOFFTestPB.clicked.connect(self.run_light_on_test)
self.hvONTestPB.clicked.connect(self.run_dark_test)
self.connectPowerPB.clicked.connect(self.connect_power)
self.connectFiberPB.clicked.connect(self.connect_fiber)
# Connect settings-related signals
self.checkIDCommandLE.textChanged.connect(self.save_settings)
self.lightOnCommandLE.textChanged.connect(self.save_settings)
self.darkTestCommandLE.textChanged.connect(self.save_settings)
self.dbEndpointLE.textChanged.connect(self.save_settings)
self.mqttServerLE.textChanged.connect(self.save_settings)
self.mqttTopicLE.textChanged.connect(self.save_settings)
self.airCommandLE.textChanged.connect(self.save_settings)
self.resultsUrlLE.textChanged.connect(self.save_settings)
# Connect Apply button
self.applySettingsPB.clicked.connect(self.apply_settings)
# Initial MQTT setup
self.setup_mqtt()
# # Connect filter signals
# self.speedCB.currentTextChanged.connect(self.update_module_list)
# self.spacerCB.currentTextChanged.connect(self.update_module_list)
# self.spacerCB_2.currentTextChanged.connect(self.update_module_list)
# self.spacerCB_3.currentTextChanged.connect(self.update_module_list)
# # Initial module list load
self.update_module_list()
# # Connect select module button
# self.selectModulePB.clicked.connect(self.select_module)
# # Enable selection mode for tree widget
# self.treeWidget.setSelectionMode(QTreeWidget.SingleSelection)
# Connect selection changes
self.moduleLE.textChanged.connect(self.module_changed)
self.powerCB.currentTextChanged.connect(self.update_connection_status)
self.fiberCB.currentTextChanged.connect(self.update_connection_status)
self.fiber_endpoint=""
# Initial connection status check
QTimer.singleShot(100, self.update_connection_status) # Small delay to ensure UI is ready
# Connect module details buttons
# self.editDetailsButton.clicked.connect(self.edit_selected_detail)
# self.saveDetailsButton.clicked.connect(self.save_module_details)
# Setup inventory buttons
# self.setup_inventory_buttons()
# Initialize current module tracking
self.current_module_id = None
# Initialize test states
self.checkIDLED.setStyleSheet("background-color: rgb(255, 255, 0);") # Yellow
self.hvOFFTestLED.setStyleSheet("background-color: rgb(255, 255, 0);")
self.hvONTestLED.setStyleSheet("background-color: rgb(255, 255, 0);")
# Disable tests 2 and 3 initially
# self.hvOFFTestPB.setEnabled(False)
# self.hvONTestPB.setEnabled(False)
# Track command workers
self.current_worker = None
# Connect module ID changes to reset test states
self.moduleLE.textChanged.connect(self.reset_test_states)
# Connect module selection to reset test states
self.module_db.ui.selectModulePB.clicked.connect(self.reset_test_states)
self.logsPB.clicked.connect(self.open_ph2acf_log)
# Connect module ID changes to load details
# self.moduleLE.textChanged.connect(self.load_module_details)
# Populate layer type combo box
# self.ui.layertypeCB.clear()
# self.ui.layertypeCB.addItem("any")
# self.ui.layertypeCB.addItems(sorted(self.layers_to_filters.keys()))
# Connect signals
#self.ui.layertypeCB.currentTextChanged.connect(self.update_filters_from_layer)
self.ringLE.textChanged.connect(self.update_layer_from_ring)
# Connect module ID changes to check mounting status
self.moduleLE.textChanged.connect(self.check_module_mounting_status)
session_file = os.path.join(os.path.expanduser("~/.config/integration_ui"), "lastsession.txt")
if os.path.exists(session_file):
with open(session_file, "r") as f:
session = f.read().strip()
self.ringLE.setText(session)
self.split_ring_and_position()
else:
self.ringLE.setText("L1")
self.split_ring_and_position()
self.draw_ring()
# Connect air control buttons
self.airONPB.clicked.connect(lambda: self.control_air(True))
self.airOFFPB.clicked.connect(lambda: self.control_air(False))
# Connect test results button
self.showPB.clicked.connect(self.show_test_results)
# Store max temperature
self.max_temperature = 0.0
# Connect open in browser button
self.openInBrowserPB.clicked.connect(self.open_results_in_browser)
self.current_module_data = {}
self.current_session = None
self.current_session_operator = None
self.current_session_comments = None
self.current_module_id = None
self.pbstatus={}
self.airLed.setStyleSheet("background-color: yellow;")
#define test session for DB
# session = {
# "operator": self.BI_Operator_line.text(),
# "timestamp": datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
# "description": self.SeshDescription_db.text(),
# "temperatures": {
# "low": self.BI_LowTemp_dsb.value(),
# "high": self.BI_HighTemp_dsb.value(),
# },
# "nCycles": self.BI_NCycles_sb.value(),
# # "status": "Open" #to be implemented
# "modulesList": [],
# }
def disable_test_pbs_enable_cancel(self):
self.pbstatus ={
self.checkIDPB: self.checkIDPB.isEnabled(),
self.hvOFFTestPB: self.hvOFFTestPB.isEnabled(),
self.hvONTestPB: self.hvONTestPB.isEnabled(),
}
self.checkIDPB.setEnabled(False)
self.hvOFFTestPB.setEnabled(False)
self.hvONTestPB.setEnabled(False)
self.cancelPB.setEnabled(True)
def reset_test_pbs(self):
print("Resetting test PBs")
print(self.pbstatus)
for pb, status in self.pbstatus.items():
pb.setEnabled(status)
self.cancelPB.setEnabled(False)
def new_session(self):
session={
"operator": self.operatorLE.text(),
"description": "INTEGRATION: "+self.commentsLE.text(),
"timestamp": datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
"modulesList": [ self.moduleLE.text() ],
}
#create new session in DB
success, result = self.make_api_request("sessions", "POST", session)
self.current_session = result["sessionName"]
self.current_module_id = self.moduleLE.text()
self.current_session_operator = self.operatorLE.text()
self.current_session_comments = self.commentsLE.text()
print(self.current_session)
return self.current_session
def get_session(self):
if self.current_session is None:
return self.new_session()
if self.current_session_operator != self.operatorLE.text() or self.current_session_comments != self.commentsLE.text():
return self.new_session()
if self.moduleLE.text() != self.current_module_id:
return self.new_session()
return self.current_session
def setup_thermal_plot(self):
self.fig, (self.ax1, self.ax2) = plt.subplots(2, 1, figsize=(8, 6))
# First plot: Image
self.im = self.ax1.imshow(np.random.rand(24, 32) * 30 + 10, cmap="plasma")
divider1 = make_axes_locatable(self.ax1)
self.cax1 = divider1.append_axes("right", size="5%", pad=0.05)
plt.colorbar(self.im, cax=self.cax1)
# Second plot: Trend
self.time = []
self.min_values = []
self.max_values = []
self.avg_values = []
self.line_min, = self.ax2.plot(self.time, self.min_values, label='Min')
self.line_max, = self.ax2.plot(self.time, self.max_values, label='Max')
self.line_avg, = self.ax2.plot(self.time, self.avg_values, label='Avg')
# SSA/MPA trend lines
self.line_ssa_mean, = self.ax2.plot([], [], label='SSA Mean', linestyle='-', marker='s', markersize=3)
self.line_ssa_max, = self.ax2.plot([], [], label='SSA Max', linestyle='-', marker='^', markersize=3)
self.line_mpa_mean, = self.ax2.plot([], [], label='MPA Mean', linestyle='-', marker='o', markersize=3)
self.line_mpa_max, = self.ax2.plot([], [], label='MPA Max', linestyle='-', marker='v', markersize=3)
self.ax2.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
self.ax2.legend(fontsize='xx-small', loc='upper left', ncol=2)
# Create canvas and add to layout
self.canvas = FigureCanvas(self.fig)
layout = QVBoxLayout(self.plotWidget)
layout.addWidget(self.canvas)
def get_settings_file(self):
"""Get the settings file path"""
config_file = os.path.join(os.path.expanduser("~/.config/integration_ui"), 'settings.yaml')
bundled_file = os.path.join(os.path.dirname(__file__), 'settings_integration.yaml')
if os.path.exists(config_file):
return config_file
elif os.path.exists(bundled_file):
return bundled_file
else:
return config_file
def load_settings(self):
"""Load settings from YAML file"""
try:
with open(self.get_settings_file(), 'r') as f:
settings = yaml.safe_load(f)
if settings:
print(settings)
print(self.get_settings_file())
# Load database URL
self.dbEndpointLE.setText(settings.get('db_url', 'http://localhost:5000'))
# Load MQTT settings
self.mqttServerLE.setText(settings.get('mqtt_server', 'test.mosquitto.org'))
self.mqttTopicLE.setText(settings.get('mqtt_topic', '/ar/thermal/image'))
# Load command settings
self.checkIDCommandLE.setText(settings.get('check_id_command', ''))
self.lightOnCommandLE.setText(settings.get('light_on_command', ''))
self.darkTestCommandLE.setText(settings.get('dark_test_command', ''))
self.airCommandLE.setText(settings.get('air_command', 'air.sh {airOn}'))
self.ph2acfTopicLE.setText(settings.get('ph2acf_topic', '/ph2acf/data'))
self.resultsUrlLE.setText(settings.get('results_url', 'file:Results/html/latest/index.html'))
except FileNotFoundError:
# Use defaults if no settings file exists
self.save_settings()
def get_api_url(self, endpoint=''):
"""Get full API URL with endpoint"""
base_url = self.dbEndpointLE.text().rstrip('/')
return f"{base_url}/{endpoint.lstrip('/')}" if endpoint else base_url
def save_settings(self):
"""Save settings to YAML file"""
settings = {
'db_url': self.dbEndpointLE.text(),
'mqtt_server': self.mqttServerLE.text(),
'mqtt_topic': self.mqttTopicLE.text(),
# Add command settings
'check_id_command': self.checkIDCommandLE.text(),
'light_on_command': self.lightOnCommandLE.text(),
'dark_test_command': self.darkTestCommandLE.text(),
'air_command': self.airCommandLE.text(),
'ph2acf_topic': self.ph2acfTopicLE.text(),
'results_url': self.resultsUrlLE.text(),
}
try:
# Ensure config directory exists
config_dir = os.path.dirname(self.get_settings_file())
os.makedirs(config_dir, exist_ok=True)
with open(self.get_settings_file(), 'w') as f:
yaml.dump(settings, f, default_flow_style=False)
except Exception as e:
self.log_output(f"Error saving settings: {e}")
def setup_mqtt(self):
"""Setup MQTT client with error handling"""
try:
# Disconnect existing client if any
if self.client:
try:
self.client.disconnect()
self.client.loop_stop()
except:
pass
self.client = mqtt.Client()
self.client.on_connect = self.on_mqtt_connect
self.client.on_message = self.on_mqtt_message
self.client.on_disconnect = self.on_mqtt_disconnect
# Use settings from UI
mqtt_server = self.mqttServerLE.text()
# Connect with timeout
self.log_output(f"Connecting to MQTT server: {mqtt_server}")
self.client.connect_async(mqtt_server, 1883, 60)
self.client.loop_start()
except Exception as e:
self.log_output(f"MQTT Setup Error: {str(e)}")
# Don't let MQTT errors crash the UI
return False
return True
def on_mqtt_connect(self, client, userdata, flags, rc):
"""Handle MQTT connection"""
try:
if rc == 0:
self.log_output("Connected to MQTT server")
mqtt_topic = self.mqttTopicLE.text()
ph2acf_topic = self.ph2acfTopicLE.text()
self.log_output(f"Subscribing to topics: {mqtt_topic}, {ph2acf_topic}")
client.subscribe([
("/air/status", 0),
(mqtt_topic, 0),
(ph2acf_topic, 0),
("shellies/ventola/status/switch:0", 0)
])
else:
self.log_output(f"MQTT Connection failed with code {rc}")
except Exception as e:
self.log_output(f"MQTT Connect Error: {str(e)}")
def on_mqtt_disconnect(self, client, userdata, rc):
"""Handle MQTT disconnection"""
try:
self.log_output("Disconnected from MQTT server")
if rc != 0:
self.log_output("Unexpected disconnection. Will attempt to reconnect...")
except Exception as e:
self.log_output(f"MQTT Disconnect Error: {str(e)}")
def on_mqtt_message(self, client, userdata, msg):
"""Handle MQTT messages with error protection"""
# print(msg.topic)
if msg.topic == "shellies/ventola/status/switch:0" :
j=json.loads(msg.payload)
print(j)
if j.get("apower",0) > 0.1 :
self.airLed.setStyleSheet("background-color: green;")
else:
self.airLed.setStyleSheet("background-color: red;")
elif msg.topic == "/air/status":
# print(msg.payload)
if int(msg.payload)==1:
self.airLed.setStyleSheet("background-color: green;")
else:
self.airLed.setStyleSheet("background-color: red;")
elif msg.topic == self.ph2acfTopicLE.text():
try:
data = json.loads(msg.payload)
# Only process if fuseId matches (and is not None)
fuse_id_msg = data.get("LpGBT_OG0_fuseId")
if self.current_fuse_id is not None and fuse_id_msg is not None and int(fuse_id_msg) == int(self.current_fuse_id):
# We have matching data, extract temperatures
ssa_temps = []
mpa_temps = []
missing_any_offset = False
offsets = {}
if self.current_module_data:
if "temperature_offset" in self.current_module_data:
offsets = self.current_module_data["temperature_offset"]
else:
# Look for alternative keys starting with 'temperature_offset'
variants = sorted([k for k in self.current_module_data.keys() if k.startswith("temperature_offset")])
if variants:
offsets = self.current_module_data[variants[0]]
if not isinstance(offsets, dict):
offsets = {}
print(offsets)
for key, value in data.items():
if key.endswith("_temp"):
# Extract hybrid and chip from key like SSA_H0_C0_temp
print(key,value)
parts = key.split('_')
if len(parts) >= 3:
ctype = parts[0] # SSA or MPA (though MPA often encoded as SSA in some Ph2_ACF versions)
hybrid = parts[1] # H0 or H1
chip = parts[2] # C0, C1, ...
# Clean up indices
h_idx = hybrid[1:] if hybrid.startswith('H') else hybrid
c_idx = chip[1:] if chip.startswith('C') else chip
# Construct offset key like SSA_H0_0
# Note: The mapping provided in prompt says SSA_H0_0, MPA_H0_8 etc.
# We need to determine if it's SSA or MPA based on the chip index or key name.
# User said "SSA/MPA mean and max".
# Let's use the provided mapping logic: keys like SSA_H0_0
offset_key = f"{ctype}_{hybrid}_{c_idx}"
temp = float(value)
if offset_key in offsets:
temp += float(offsets[offset_key])
else:
missing_any_offset = True
if ctype == "SSA":
ssa_temps.append(temp)
elif ctype == "MPA":
mpa_temps.append(temp)
else:
# Fallback/Mixed
ssa_temps.append(temp)
now = datetime.now()
# Update trend
self.ph2acf_time.append(now)
# Keep maximum 600 values for Ph2ACF data
if len(self.ph2acf_time) > 600:
self.ph2acf_time.pop(0)
self.ssa_mean_values.pop(0)
self.ssa_max_values.pop(0)
self.mpa_mean_values.pop(0)
self.mpa_max_values.pop(0)
# SSA Stats
if ssa_temps:
self.ssa_mean_values.append(np.mean(ssa_temps))
self.ssa_max_values.append(np.max(ssa_temps))
else:
self.ssa_mean_values.append(np.nan)
self.ssa_max_values.append(np.nan)
# MPA Stats
if mpa_temps:
self.mpa_mean_values.append(np.mean(mpa_temps))
self.mpa_max_values.append(np.max(mpa_temps))
else:
self.mpa_mean_values.append(np.nan)
self.mpa_max_values.append(np.nan)
print(f"DEBUG: SSA Mean: {self.ssa_mean_values[-1] if ssa_temps else 'N/A'}")
# Update plot lines
# Set line style based on offset presence
ls = '--' if missing_any_offset else '-'
self.line_ssa_mean.set_data(self.ph2acf_time, self.ssa_mean_values)
self.line_ssa_mean.set_linestyle(ls)
self.line_ssa_max.set_data(self.ph2acf_time, self.ssa_max_values)
self.line_ssa_max.set_linestyle(ls)
self.line_mpa_mean.set_data(self.ph2acf_time, self.mpa_mean_values)
self.line_mpa_mean.set_linestyle(ls)
self.line_mpa_max.set_data(self.ph2acf_time, self.mpa_max_values)
self.line_mpa_max.set_linestyle(ls)
self.ax2.relim()
self.ax2.autoscale_view()
self.canvas.draw()
except Exception as e:
self.log_output(f"Ph2ACF Message Error: {str(e)}")
elif msg.topic == self.mqttTopicLE.text():
try:
flo_arr = [
struct.unpack("f", msg.payload[i : i + 4])[0]
for i in range(0, len(msg.payload), 4)
]
# Update image plot
self.im.set_data(np.array(flo_arr).reshape(24, 32))
self.im.set_clim(18, 35)
# Update trend plot
now = datetime.now()
self.time.append(now)
self.min_values.append(min(flo_arr))
self.max_values.append(max(flo_arr))
self.avg_values.append(np.mean(flo_arr))
data={ "min": min(flo_arr), "max": max(flo_arr), "avg":np.mean(flo_arr) }
ret=client.publish("/integration/thermalcamera",json.dumps(data))
# Update max temperature display
self.max_temperature = max(flo_arr)
self.tMaxLabel.setText(f"Tmax: {self.max_temperature:.1f}")
if self.max_temperature > 45 :
self.caenGUI.safe_lv_off()
if self.max_temperature > 50 :
self.caenGUI.off(self.caenGUI.channels["HV"])
self.caenGUI.off(self.caenGUI.channels["LV"])
# Keep maximum 600 values
if len(self.time) > 600:
self.time.pop(0)
self.min_values.pop(0)
self.max_values.pop(0)
self.avg_values.pop(0)
self.line_min.set_data(self.time, self.min_values)
self.line_max.set_data(self.time, self.max_values)
self.line_avg.set_data(self.time, self.avg_values)
self.ax2.relim()
self.ax2.autoscale_view()
self.canvas.draw()
except Exception as e:
self.log_output(f"MQTT Message Error: {str(e)}")
else:
# Handle other topics if any (already handled for air and fan)
pass
def split_ring_and_position(self):
ring_position = self.ringLE.text()
config_dir = os.path.expanduser("~/.config/integration_ui")
os.makedirs(config_dir, exist_ok=True)
session_file = os.path.join(config_dir, "lastsession.txt")
with open(session_file, "w") as f:
f.write(self.ringLE.text())
ring=ring_position
position="0"
if ';' in ring_position:
ring, position = ring_position.split(';')
self.ringLE.setText(ring)
self.positionLE.setText(position)
if ring[:2] == "L1":
self.number_of_modules=18
if ring[:2] == "L2":
self.number_of_modules=26
if ring[:2] == "L3":
self.number_of_modules=36
self.draw_ring()
def draw_ring(self):
#draw a ring with number_of_modules modules, each is draw as a rectangle
# even and odd modules are drawn at different radii
# draw in graphics view
self.update_module_list()
scene = QGraphicsScene()
self.graphicsView.setScene(scene)
# Store module coordinates for click detection
self.module_coordinates = []
pen = QPen()
pen.setWidth(2)
pen.setColor(Qt.black)
#dashed style
pen.setStyle(Qt.DashLine)
radius=min(self.graphicsView.width(),self.graphicsView.height())/2.5
scene.addEllipse(0, 0, radius*2, radius*2, pen)
deltaphi=360/self.number_of_modules*2
#solid
pen.setStyle(Qt.SolidLine)
#draw two circles in the middle-top
scene.addEllipse(radius-7, -20, 6, 6, pen)
scene.addEllipse(radius+7, -20, 6, 6, pen)
scene.addEllipse(radius-4, -17, 1, 1, pen)
scene.addEllipse(radius+10, -17, 1, 1, pen)
ring_id = self.ringLE.text()
for i in range(1,self.number_of_modules+1):
phi=-(i)*deltaphi+deltaphi/2
phi-=90
if i> self.number_of_modules/2:
phi+=deltaphi/2
# Check if this position has a mounted module
position_key = f"{ring_id};{i}"
is_mounted = position_key in self.mounted_modules
if self.positionLE.text()==str(i):
pen.setColor(Qt.red)
elif is_mounted:
pen.setColor(Qt.blue) # Use blue for mounted positions
else:
pen.setColor(Qt.black)
# Calculate module coordinates
if i<= self.number_of_modules/2:
x1=(radius*0.95)*cos((phi+deltaphi/4)/180*pi)+radius
y1=(radius*0.95)*sin((phi+deltaphi/4)/180*pi)+radius
x2=(radius*0.95)*cos((phi-deltaphi/4)/180*pi)+radius
y2=(radius*0.95)*sin((phi-deltaphi/4)/180*pi)+radius
x3=(radius*1.1)*cos((phi+deltaphi/4)/180*pi)+radius
y3=(radius*1.1)*sin((phi+deltaphi/4)/180*pi)+radius
x4=(radius*1.1)*cos((phi-deltaphi/4)/180*pi)+radius
y4=(radius*1.1)*sin((phi-deltaphi/4)/180*pi)+radius
else:
x1=(radius*0.9)*cos((phi+deltaphi/4)/180*pi)+radius
y1=(radius*0.9)*sin((phi+deltaphi/4)/180*pi)+radius
x2=(radius*0.9)*cos((phi-deltaphi/4)/180*pi)+radius
y2=(radius*0.9)*sin((phi-deltaphi/4)/180*pi)+radius
x3=(radius*1.05)*cos((phi+deltaphi/4)/180*pi)+radius
y3=(radius*1.05)*sin((phi+deltaphi/4)/180*pi)+radius
x4=(radius*1.05)*cos((phi-deltaphi/4)/180*pi)+radius
y4=(radius*1.05)*sin((phi-deltaphi/4)/180*pi)+radius
# Store module coordinates and position number
self.module_coordinates.append({
'position': i,
'coords': [(x1,y1), (x2,y2), (x3,y3), (x4,y4)]
})
scene.addLine(x1, y1, x2, y2, pen)
scene.addLine(x2, y2, x4, y4, pen)
scene.addLine(x4, y4, x3, y3, pen)
scene.addLine(x3, y3, x1, y1, pen)
# Add module ID text for mounted modules
if is_mounted:
text = self.mounted_modules[position_key]
else:
text= str(i)
# Calculate center point of the module
center_x = (x1 + x3) / 2
center_y = (y1 + y3) / 2
# Calculate angle for radial text (in degrees)
angle = atan2(center_y - radius, center_x - radius) * 180 / pi
# Add 90 degrees to make text perpendicular to radius
angle += 180-deltaphi/4
text_item = scene.addText(text)
# Center the text around its position
text_bounds = text_item.boundingRect()
text_item.setPos((radius*0.5)*cos(phi/180*pi)+radius - text_bounds.width()/2,
(radius*0.5)*sin(phi/180*pi)+radius - text_bounds.height()/2)
# Set the rotation around the center of the text
text_item.setTransformOriginPoint(text_bounds.center())
text_item.setRotation(angle)
# Enable mouse tracking
self.graphicsView.setMouseTracking(True)
self.graphicsView.mousePressEvent = self.handle_ring_click
self.graphicsView.show()
def handle_ring_click(self, event):
"""Handle clicks on the ring diagram"""
# Convert click coordinates to scene coordinates
scene_pos = self.graphicsView.mapToScene(event.pos())
x, y = scene_pos.x(), scene_pos.y()
# Check if click is inside any module
for module in self.module_coordinates:
coords = module['coords']
# Create polygon from module coordinates
polygon = [(x_, y_) for x_, y_ in coords]
# Calculate bounding box for quick check
min_x = min(x for x, _ in polygon)
max_x = max(x for x, _ in polygon)
min_y = min(y for _, y in polygon)
max_y = max(y for _, y in polygon)
# First do a bounding box check
if (min_x <= x <= max_x and min_y <= y <= max_y):
# If in bounding box, do detailed polygon check
if self.point_in_polygon(x, y, polygon):
new_position = str(module['position'])
# Only proceed if position actually changed
if new_position != self.positionLE.text():
self.log_output(f"Found match in module {new_position}")
# Update position LE
self.positionLE.setText(new_position)
# Check if a module is mounted at this position
ring_id = self.ringLE.text()
position_key = f"{ring_id};{new_position}"
if position_key in self.mounted_modules:
# Update module ID with the mounted module's ID
mounted_module_id = self.mounted_modules[position_key]
self.moduleLE.setText(mounted_module_id)
# Reset test states since we have a new module
self.reset_test_states()
# Redraw ring to update highlighting
self.draw_ring()
break
def point_in_polygon(self, x, y, polygon):
"""Check if point (x,y) is inside polygon using cross product method"""
def sign(p1, p2, p3):
return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1])
def is_point_in_triangle(pt, v1, v2, v3):
d1 = sign(pt, v1, v2)
d2 = sign(pt, v2, v3)
d3 = sign(pt, v3, v1)
has_neg = (d1 < 0) or (d2 < 0) or (d3 < 0)
has_pos = (d1 > 0) or (d2 > 0) or (d3 > 0)
return not (has_neg and has_pos)
# For quadrilateral, split into two triangles and check both
point = (x, y)
return (is_point_in_triangle(point, polygon[0], polygon[1], polygon[2]) or
is_point_in_triangle(point, polygon[2], polygon[3], polygon[0]))
def get_placeholder_values(self):
"""Get current values for all placeholders"""
return {
'ring_id': self.ringLE.text(),
'position': self.positionLE.text(),
'module_id': self.moduleLE.text(),
'fiber': self.fiberCB.currentText(),
'power': self.powerCB.currentText(),
'fiber_endpoint': self.fiber_endpoint,
'session': self.get_session(),
}
def expand_placeholders(self, text):
"""Replace placeholders in text with their current values"""
values = self.get_placeholder_values()
try:
return text.format(**values)
except KeyError as e:
self.log_output(f"Warning: Unknown placeholder {e}")
return text
except ValueError as e:
self.log_output(f"Warning: Invalid placeholder format - {e}")
return text
def run_command(self, command):
"""Run a shell command asynchronously"""
if self.current_worker is not None:
self.current_worker.finished.disconnect()
self.current_worker.terminate()
self.current_worker.wait()
expanded_command = self.expand_placeholders(command)
self.log_output(f"Running command: {expanded_command}")
self.log_output(f"Using placeholders: {self.get_placeholder_values()}")
self.current_worker = CommandWorker(expanded_command)
self.current_worker.finished.connect(self.handle_command_finished)
self.current_worker.start()
def handle_command_finished(self, success, stdout, stderr):
"""Handle command completion"""
if stdout:
self.log_output(f"Output:\n{stdout}")
if stderr:
self.log_output(f"Error:\n{stderr}")
# Clean up worker
if self.current_worker:
self.current_worker.finished.disconnect()
self.current_worker = None
def show_error_dialog(self, message):
"""Show error dialog with the given message"""
msg = QMessageBox()