-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGUI.py
executable file
·423 lines (315 loc) · 16 KB
/
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QWidget, QGridLayout, QPushButton, QApplication,\
QTextEdit, QLabel, QFrame, QVBoxLayout, QHBoxLayout, QLineEdit, QCheckBox, QMessageBox
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.Qt import QRect
from PyQt5 import QtGui, Qt
from queue import Queue
import time
import threading
from UDPServer import PlayerArduinoPortConverter, ListeningThread, PeriodicSendingThread, SendingThread, SLEEP_TIME
import itertools
from collections import defaultdict
from datetime import datetime
import socket
import os
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
player_arduino_port_converter = PlayerArduinoPortConverter()
player_arduino2port = player_arduino_port_converter.get_player_arduino2port_converter()
port2player_arduino = player_arduino_port_converter.get_port2player_arduino_converter()
TIME_FORMAT4FILES = '%Y-%m-%d-%H-%M-%S'
class StatusWidget(QWidget):
STATUS_COLORS = {
'Idle': '#0000AA',
'Measuring': '#00AA00',
'NA': '#777777',
'File error': '#AA0000',
'Bad data': '#CC5500',
}
def __init__(self, square_size = 15, timeout=2):
super().__init__()
self.square = QFrame(self)
self.square.setStyleSheet("QWidget { background-color: %s }" % self.STATUS_COLORS['NA'])
self.square.setFixedSize(square_size, square_size)
# self.square.setMaximumHeight(25)
self.timeout = timeout
self.default_color = self.STATUS_COLORS['NA']
self.status = 'NA'
self.outdated = False
self.update_timestamp = datetime.now().timestamp()
self.status_color = self.STATUS_COLORS['NA']
self.label = QLabel(text=self.status, parent=self)
# self.label.setMaximumHeight(100)
# self.label.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
self.label.setMinimumSize(22, 22)
self.label.setAlignment(Qt.AlignTop)
# self.label.Preferred
self.layout = QHBoxLayout(self)
self.layout.addWidget(self.square, Qt.AlignLeft)
self.layout.addWidget(self.label, Qt.AlignLeft)
# self.layout.setSpacing(0)
self.setLayout(self.layout)
def updateStatus(self, new_status, update_timestamp=True):
if update_timestamp:
self.update_timestamp = datetime.now().timestamp()
self.outdated = False # It's not outdated anymore
if new_status == self.status:
return
# print(f"changing status from {self.status} to {new_status}")
statuses_splitted = new_status.split(',')
if (len(statuses_splitted) > 1) and (statuses_splitted[1] == 'Bad_data'):
status_class = 'Bad data'
else:
status_class = statuses_splitted[0]
new_status_color = self.STATUS_COLORS.get(status_class, self.default_color)
if new_status_color != self.status_color:
self.square.setStyleSheet("QWidget { background-color: %s }" % new_status_color)
self.status_color = new_status_color
self.status = new_status
self.label.setText(new_status)
def isOutdated(self, timeout=None, current_timestamp=None):
if self.outdated:
return self.outdated
# If it's not outdated we need to check if it's outdated now
if timeout is None:
timeout = self.timeout
if current_timestamp is None:
current_timestamp = datetime.now().timestamp()
self.outdated = (current_timestamp - self.update_timestamp > timeout)
# if self.outdated:
# print("OUTDATED")
return self.outdated
# def sizeHint(self):
# return QSize(20, 35)
class ControlCenter(QWidget):
# STATUS_COLORS = {
# 'Idle': '#0000AA',
# 'Measuring': '#00AA00',
# 'unknown': '#777777'
# } # TODO: make it default dict for unknown statuses?
def __init__(self, n_players=5, n_arduinos=3, address=('255.255.255.255', 3000)):
super().__init__()
self.input_queue = Queue(maxsize=1000)
self.n_players = n_players
self.n_arduinos = n_arduinos
self.status_widgets_dict = {}
self.listener_threads_dict = {}
self.ip = self.getIP()
self.enviromental_arduino_id = 3
self.enviromental_player_id = 9
self.players_arduinos_pairs = list(itertools.product(range(self.n_players), range(self.n_arduinos))) + \
[(self.enviromental_player_id, self.enviromental_arduino_id)] # Enviromental arduino
### Important warning: currently I'm using player_id == 9 for a general non player-specific sensors (such as enviroment)
for n_player, n_arduino in self.players_arduinos_pairs:
self.status_widgets_dict[(n_player, n_arduino)] = StatusWidget()
self.status_widgets_dict[(n_player, n_arduino)].setMaximumHeight(28)
# self.status_widgets_dict[(n_player, n_arduino)].label.update()
port = player_arduino2port(player_id=n_player, arduino_id=n_arduino)
self.listener_threads_dict[(n_player, n_arduino)] = ListeningThread(
queue=self.input_queue,
port=port,
# name=f'arduino_{n_player}_{n_arduino}',
verbose=False)
self.listener_threads_dict[(n_player, n_arduino)].start()
# for n_player, n_arduino in itertools.product([-1], [3]): # Enviromental arduino
# self.status_widgets_dict[(n_player, n_arduino)] = StatusWidget()
# self.status_widgets_dict[(n_player, n_arduino)].setMaximumHeight(28)
# # self.status_widgets_dict[(n_player, n_arduino)].label.update()
#
# port = player_arduino2port(player_id=n_player, arduino_id=n_arduino)
# self.listener_threads_dict[(n_player, n_arduino)] = ListeningThread(
# queue=self.input_queue,
# port=port,
# # name=f'arduino_{n_player}_{n_arduino}',
# verbose=False)
# self.listener_threads_dict[(n_player, n_arduino)].start()
self.periodic_sending_thread = PeriodicSendingThread(port=4000, address=address, msg='status;', period=1)
self.peridoc_send = True
self.periodic_sending_thread.start_periodic_send()
self.periodic_sending_thread.start()
self.sending_thread = SendingThread(port=4002, address=address)
self.sending_thread.start()
self.sendSetUdpIp(self.ip)
self.sendSetFtpIp(self.ip)
self.closed = False
self.initUI()
def initUI(self):
grid = QGridLayout()
grid.setVerticalSpacing(0)
# grid.setVerticalSpacing(0)
# grid.setHorizontalSpacing(0)
# grid.setSizeConstraint()
for n_arduino in range(self.n_arduinos):
arduino_label = QLabel(f'Arduino_{n_arduino}')
arduino_label.setContentsMargins(13, 0, 0, 0)
grid.addWidget(arduino_label, 0, 1 + n_arduino)# , alignment=Qt.AlignBottom)
for n_player in range(self.n_players):
player_label = QLabel(f'Player_{n_player}')
player_label.setContentsMargins(0, 0, 0, 0)
# print(type(player_label.layout()))
# .setContentsMargins(0, -10, 0, 0)
# player_label.setAlignment(Qt.AlignBottom)
grid.addWidget(player_label, 1 + n_player, 0, alignment=Qt.AlignBottom)
for n_arduino in range(self.n_arduinos):
for n_player in range(self.n_players):
grid.addWidget(self.status_widgets_dict[(n_player, n_arduino)], 1 + n_player, 1 + n_arduino)#, alignment=Qt.AlignLeft)
self.button_start = QPushButton('Start', self)
self.button_stop = QPushButton('Stop', self)
self.button_start.clicked.connect(self.sendStart)
self.button_stop.clicked.connect(self.sendStop)
self.button_time_sync = QPushButton('Time sync', self)
self.button_status = QPushButton('Status', self)
self.button_periodic_sending = QCheckBox('Periodic Sending', self)
self.button_periodic_sending.setChecked(True)
self.button_periodic_sending.stateChanged.connect(self.periodicSendingChange)
self.button_time_sync.clicked.connect(self.sendTimeSync)
self.button_status.clicked.connect(self.sendStatus)
self.button_set_udp = QPushButton('Set UDP IP', self)
self.button_set_ftp = QPushButton('Set FTP IP', self)
self.line_my_ip = QLineEdit(self)
self.line_my_ip.setText(self.ip)
self.button_set_udp.clicked.connect(lambda : self.sendSetUdpIp(self.line_my_ip.text()))
self.button_set_ftp.clicked.connect(lambda : self.sendSetFtpIp(self.line_my_ip.text()))
self.line_my_ip.setFixedWidth(120)
current_datetime = datetime.now().strftime(TIME_FORMAT4FILES)
# self.line_upload_date_min.setText(current_datetime)
self.text_ftpline_0 = QLabel("Upload data from ", self)
self.line_upload_date_min = QLineEdit(current_datetime, self)
self.text_ftpline_1 = QLabel(" to ", self)
self.line_upload_date_max = QLineEdit('2020-12-31-00-00-00', self)
self.button_upload_via_ftp = QPushButton('Upload', self)
self.line_upload_date_min.setFixedWidth(160)
self.line_upload_date_max.setFixedWidth(160)
self.button_upload_via_ftp.clicked.connect(lambda : self.sendUploadViaFTP(
self.line_upload_date_min.text(), self.line_upload_date_max.text()))
# layout_horizontal_enviromental = QHBoxLayout()
# layout_horizontal_enviromental.addWidget(self.button_start)
# layout_horizontal_enviromental.addWidget(self.button_stop)
grid_enviromental = QGridLayout()
grid_enviromental.setVerticalSpacing(0)
enviromental_label = QLabel('Enviromental arduino: ')
enviromental_label.setContentsMargins(0, 0, 0, 0)
grid_enviromental.addWidget(enviromental_label, 0, 0, alignment=Qt.AlignBottom)
grid_enviromental.addWidget(self.status_widgets_dict[(self.enviromental_player_id, self.enviromental_arduino_id)], 0, 1)
layout_horizontal_start_stop = QHBoxLayout()
layout_horizontal_start_stop.addWidget(self.button_start)
layout_horizontal_start_stop.addWidget(self.button_stop)
layout_horizontal_status_sync = QHBoxLayout()
layout_horizontal_status_sync.addWidget(self.button_time_sync)
layout_horizontal_status_sync.addWidget(self.button_status)
layout_horizontal_status_sync.addWidget(self.button_periodic_sending)
layout_horizontal_ip = QHBoxLayout()
layout_horizontal_ip.addWidget(self.line_my_ip)
layout_horizontal_ip.addWidget(self.button_set_udp)
layout_horizontal_ip.addWidget(self.button_set_ftp)
layout_horizontal_ftp = QHBoxLayout()
layout_horizontal_ftp.addWidget(self.text_ftpline_0)
layout_horizontal_ftp.addWidget(self.line_upload_date_min)
layout_horizontal_ftp.addWidget(self.text_ftpline_1)
layout_horizontal_ftp.addWidget(self.line_upload_date_max)
layout_horizontal_ftp.addWidget(self.button_upload_via_ftp)
layout_vertical = QVBoxLayout()
layout_vertical.addLayout(grid)
layout_vertical.addLayout(grid_enviromental)
layout_vertical.addLayout(layout_horizontal_start_stop)
layout_vertical.addLayout(layout_horizontal_status_sync)
layout_vertical.addLayout(layout_horizontal_ip)
layout_vertical.addLayout(layout_horizontal_ftp)
# layout_vertical.setSpacing(1)
self.setLayout(layout_vertical)
self.move(300, 150)
self.setWindowTitle('Control Panel')
self.input_queue_updater_thread = threading.Thread(target=self.input_queue_updater)
self.input_queue_updater_thread.start()
self.relevance_updater_thread = threading.Thread(target=self.relevance_updater)
self.relevance_updater_thread.start()
self.show()
def input_queue_updater(self):
while not self.closed:
if self.input_queue.empty():
time.sleep(SLEEP_TIME)
continue
item = self.input_queue.get(block=True)
if item['msg_type'] == 'status':
status = item['msg_content']
n_player, n_arduino = port2player_arduino(item['receiving_port'])
# if self.status_widgets_dict[(n_player, n_arduino)].status == status:
# continue # The same status, no need to update # Sorry, already implemented in the class
# print(f"updating n_arduino {n_arduino}")
self.status_widgets_dict[(n_player, n_arduino)].updateStatus(new_status=status, update_timestamp=True)
def relevance_updater(self, period=1, timeout=5):
while not self.closed:
current_timestamp = datetime.now().timestamp()
# for n_player, n_arduino in itertools.product(range(self.n_players), range(self.n_arduinos)):
for n_player, n_arduino in self.players_arduinos_pairs:
if self.status_widgets_dict[(n_player, n_arduino)].isOutdated(timeout=timeout, current_timestamp=current_timestamp):
# print("OUTDATED")
self.status_widgets_dict[(n_player, n_arduino)].updateStatus('NA', update_timestamp=False)
time.sleep(period)
def getIP(self):
# hostname = socket.gethostname()
# ip = socket.gethostbyname(hostname)
ip = socket.gethostbyname_ex(socket.gethostname())[-1][-1]
return ip
def sendMsg(self, msg):
self.sending_thread.send(msg)
def sendStart(self):
self.sendMsg('start;')
def sendStop(self):
self.sendMsg('end;')
def sendStatus(self):
self.sendMsg('status;')
def sendTimeSync(self):
self.sendMsg('time_sync;')
def sendSetUdpIp(self, udp_ip):
self.sendMsg(f'set udp {udp_ip};')
def sendSetFtpIp(self, ftp_ip):
self.sendMsg(f'set ftp {ftp_ip};')
def sendUploadViaFTP(self, datetime_start, datetime_end):
reply = QMessageBox.question(self, 'Are you sure?',
"Are you sure you want to upload the data from Arduino's to the FTP Server? "
"This may take some time, and you won't be able to start new measurements during upload",
QMessageBox.Yes |
QMessageBox.No,
QMessageBox.No)
if reply == QMessageBox.Yes:
self.sendMsg(f'upload {datetime_start} {datetime_end};')
def periodicSendingChange(self):
self.peridoc_send = not self.peridoc_send
if self.peridoc_send:
self.periodic_sending_thread.start_periodic_send()
else:
self.periodic_sending_thread.stop_periodic_send()
def closeEvent(self, event):
print("CLOSING")
self.closed = True
self.periodic_sending_thread.closed = True
self.periodic_sending_thread.join()
for listener_thread_name, listener_thread in self.listener_threads_dict.items():
listener_thread.closed = True
time.sleep(SLEEP_TIME * 2)
for listener_thread_name, listener_thread in self.listener_threads_dict.items():
listener_thread.socket.close()
listener_thread.join()
# print(listener_thread, 'closed')
# print('Joining sending threads...')
self.sending_thread.join()
self.periodic_sending_thread.join()
# print("Joining relevance_updater_thread")
self.relevance_updater_thread.join()
# print("Joining input_queue_updater_thread")
self.input_queue_updater_thread.join()
# print('Closing the main widget')
self.close()
# self.destroy()
if __name__ == '__main__':
app = QApplication(sys.argv)
path = os.path.join(os.path.dirname(sys.modules[__name__].__file__), 'Icons/Icon_0.ico')
app.setWindowIcon(QIcon(QPixmap(path)))
ex = ControlCenter()
print(ex.size())
sys.exit(app.exec_())