-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff.py
executable file
·279 lines (205 loc) · 8.54 KB
/
diff.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
#!/home/p212user/miniforge3/envs/loadframe/bin/python
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 24 09:45:55 2023
@author: hegedues
"""
VERSION = {'major': 0, 'minor': 1, 'patch': 0}
import sys
import os
import psutil
import time
import datetime
import logging
logFormatter = logging.Formatter("%(asctime)-25.25s %(threadName)-12.12s %(name)-25.24s %(levelname)-10.10s %(message)s")
rootLogger = logging.getLogger()
rootLogger.setLevel(logging.INFO)
#logging.getLogger().setLevel(logging.DEBUG)
fileHandler = logging.FileHandler(os.path.join(os.getcwd(), 'log.log'))
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
import glob
import multiprocessing
from multiprocessing import Event, Process, Queue, Pool
from threading import Thread
import queue
from pathlib import Path
from PyQt5 import QtWidgets, uic, QtGui
from PyQt5.QtCore import QRunnable, Qt, QThreadPool, pyqtSignal, QThread, QObject, pyqtSlot, QTimer
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (
QMainWindow,
QLabel,
QGridLayout,
QWidget,
QPushButton,
QProgressBar,
QFileDialog,
QSizePolicy,
)
try:
import PyTango as PT
TANGO = True
except ImportError as e:
logging.warning(f"{e}")
# resource:
# https://doc.qt.io/qt-5/stylesheet-examples.html
_coolBlue = '#0d6efd'
_TangoStateColors = {'ON': '#42f545',
'OFF': '#f4f7f2',
'MOVING': '#427ef5',
'STANDBY': '#f5f253',
'FAULT': '#cc2b2b',
'INIT': '#daa06d',
'ALARM': '#eb962f',
'DISABLE': '#f037fa',
'UNKNOWN': '#808080'}
mots = {'idtz2': 'p21/motor/eh3_u1.06',
'idty2': 'p21/motor/eh3_u1.05',
'idtx2': 'p21/motor/eh3_u1.10',
'idry2': 'p21/motor/eh3_u1.04',
'idrx2': 'p21/motor/eh3_u1.09',
'idrz1': 'p21/motor/eh3_u2.05',
'idty1': 'p21/motor/eh3_u1.14',
'idry1': 'p21/motor/eh3_u1.13'}
FASTTIMER = 0.1
SLOWTIMER = 1
PROGRESS = '|/-\\'
class myQLabel(QLabel):
'''
This class is supposed to resize the label on size change, but does not yet work properly
https://stackoverflow.com/questions/29852498/syncing-label-fontsize-with-layout-in-pyqt
'''
def __init__(self, *args, **kargs):
super(myQLabel, self).__init__(*args, **kargs)
self.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored))
self.setMinSize(14)
def setMinSize(self, minfs):
f = self.font()
f.setPixelSize(minfs)
br = QtGui.QFontMetrics(f).boundingRect(self.text())
self.setMinimumSize(br.width(), br.height())
def resizeEvent(self, event):
super(myQLabel, self).resizeEvent(event)
if not self.text():
return
# --- fetch current parameters ----
f = self.font()
cr = self.contentsRect()
# --- iterate to find the font size that fits the contentsRect ---
dw = event.size().width() - event.oldSize().width() # width change
dh = event.size().height() - event.oldSize().height() # height change
print(f'resize: {dw} {dh}')
fs = max(f.pixelSize(), 1)
while True:
f.setPixelSize(fs)
br = QtGui.QFontMetrics(f).boundingRect(self.text())
if dw >= 0 and dh >= 0: # label is expanding
if br.height() <= cr.height() and br.width() <= cr.width():
fs += 1
else:
f.setPixelSize(max(fs - 1, 1)) # backtrack
break
else: # label is shrinking
if br.height() > cr.height() or br.width() > cr.width():
fs -= 1
else:
break
if fs < 1:
break
# --- update font size ---
self.setFont(f)
class MainWidget(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
super(MainWidget, self).__init__(*args, **kwargs)
uic.loadUi('diffractometerGUI.ui', self)
self.t0 = time.time()
self.mot = {}
font = self.frame.font()
font.setPointSize(50)
grid = QGridLayout()
for i,(k,v) in enumerate(mots.items()):
self.mot[k] = {}
# name labels
self.mot[k]['label'] = QLabel(k)
self.mot[k]['label'].setStyleSheet('''QLabel {
font-size: 30px;
font-weight: 600;
}''')
# position labels
self.mot[k]['value'] = QLabel('position')
self.mot[k]['value'].setStyleSheet('''QLabel {
color: #0d6efd;
font-size: 30px;
font=weight: 600;
border-radius: 5px;
border: 2px solid #0d6efd;
}''')
self.mot[k]['state'] = QPushButton('state')
self.mot[k]['state'].setStyleSheet('''QPushButton {
color: #fff;
font-weight: 600;
border-radius: 5px;
border: 1px solid #0d6efd;
padding: 5px 15px;
outline: 0px;
font-size: 30px;
}''')
self.mot[k]['state'].setStyleSheet("QPushButton {background-color: %s}" % _TangoStateColors['UNKNOWN'])
grid.addWidget(self.mot[k]['label'], i, 0)
grid.addWidget(self.mot[k]['value'], i, 1)
grid.addWidget(self.mot[k]['state'], i, 2)
try:
self.mot[k]['DeviceProxy'] = PT.DeviceProxy('tango://hasep21eh3:10000/%s' % v)
logging.info(f"{k} connected")
except:
self.mot[k]['DeviceProxy'] = None
logging.error(f"Failed to connect to {k}")
self.frame_2.setLayout(grid)
self.label_pixmap.setPixmap(QPixmap('./drawing.png'))
self.label_pixmap.setScaledContents(True)
self.timerSlow = QTimer()
self.timerSlow.start(int(1000*SLOWTIMER))
self.timerFast = QTimer()
self.timerFast.start(int(1000*FASTTIMER))
self.timerFast.timeout.connect(self.update_states_pos)
def _upd(self, *args):
key = args[0]
position = self.mot[key]['DeviceProxy'].position
self.mot[key]['value'].setText(f"{position:.4f}")
state = str(self.mot[key]['DeviceProxy'].state())
self.mot[key]['state'].setStyleSheet('QPushButton {background-color: %s}' % _TangoStateColors[state])
self.mot[key]['state'].setText(state)
def update_states_pos(self):
threads = []
for i, k in enumerate(self.mot.keys()):
thread = Thread(target=self._upd, args=(k,))
threads.append(thread)
for t in threads:
t.start()
time.sleep(FASTTIMER)
self.label.setText(PROGRESS[int((time.time()-self.t0) % len(PROGRESS))])
#imgidx = int((time.time()-self.t0) % 8)
#self.label.setPixmap(QPixmap('./progress/%d.png' % imgidx))
for t in threads:
t.join()
#with Pool(len(self.mot.keys())) as p:
#DPs = [self.mot[k]['DeviceProxy'] for k in self.mot.keys()] # this is not picklable
#labels = [self.mot[k]['value'] for k in self.mot.keys()]
#btns = [self.mot[k]['state'] for k in self.mot.keys()]
#p.map(self._upd, [(self, k) for k in self.mot.keys()])
def exitHandler():
print('BYE')
def mainGUI():
print('Version: %d.%d.%d' % (VERSION['major'], VERSION['minor'], VERSION['patch']))
app = QtWidgets.QApplication(sys.argv)
app.aboutToQuit.connect(exitHandler)
#app.setStyleSheet(Path('style.qss').read_text())
main = MainWidget()
main.show()
sys.exit(app.exec_())
if __name__ == "__main__":
mainGUI()