/
MainWindow.py
555 lines (493 loc) · 18.1 KB
/
MainWindow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
import os
import re
from functools import partial
from threading import Timer
import playsound
from PySide2.QtCore import QModelIndex, Slot, QObject
from PySide2.QtWidgets import QSplitter, QApplication, QAction, QHeaderView
from PySide2.QtUiTools import QUiLoader
from PySide2.QtGui import Qt, QColor, QTextCursor, QIcon
import util
from Helper import Helper
from InfoDialog import InfoDialog
from LoginDialog import LoginDialog
from ModifyDialog import ModifyDialog
from WindowSignal import message
from SerialWorker import SerialWorker
from CheckWorker import CheckWorker
class MainWindow(QObject):
"""
控制系统的主窗口
"""
def __init__(self):
"""
初始化界面
"""
#
# 成员变量
#
super().__init__()
self.isPolling = False # 是否在轮询中
self.helper = Helper() # 控制器
self.polling_timer = None # 轮询定时器,设成成员变量是为了能够取消定时器
self.play_sound = True # 默认允许播放蜂鸣声
#
# 初始化界面
#
self.ui = QUiLoader().load('./QtDesigner/main_window.ui') # 加载 UI 文件,self.ui 就是应用中 MainWindow 这个对象
self.init_window() # 初始化主窗口
self.init_interval_combobox() # 初始化轮询时间下拉框
self.init_splitter() # 初始化分离器
self.init_table() # 初始化表格
self.init_output_edit() # 初始化输出信息的窗口
self.init_menu_bar() # 初始化菜单
self.ui.btn_submit.clicked.connect(self.start_polling) # 绑定点击事件
def init_window(self):
"""
初始化主窗口
:return: 无
"""
self.ui.setWindowTitle("光伏集群现场监控") # 窗口标题
#
# 左上角图标,任务栏图标
#
app_icon = QIcon("./other/logo.ico")
self.ui.setWindowIcon(app_icon)
#
# 读取配置文件
#
baudrate, address = self.helper.read_config()
if baudrate != "" and address != "":
self.ui.edit_baudrate.setText(baudrate)
self.ui.edit_addr.setText(address)
def init_menu_bar(self):
"""
初始化菜单栏
:return: 无
"""
self.ui.restart.triggered.connect(partial(self.one_key, self.ui.restart.text()))
self.ui.lock.triggered.connect(partial(self.one_key, self.ui.lock.text()))
self.ui.unlock1.triggered.connect(partial(self.one_key, self.ui.unlock1.text()))
self.ui.wind_bread.triggered.connect(partial(self.one_key, self.ui.wind_bread.text()))
self.ui.planish.triggered.connect(partial(self.one_key, self.ui.planish.text()))
self.ui.snow_removal.triggered.connect(partial(self.one_key, self.ui.snow_removal.text()))
self.ui.clean_board.triggered.connect(partial(self.one_key, self.ui.clean_board.text()))
self.ui.sub_angle.triggered.connect(partial(self.one_key, self.ui.sub_angle.text()))
self.ui.add_angle.triggered.connect(partial(self.one_key, self.ui.add_angle.text()))
self.ui.advance.triggered.connect(self.show_advance_dialog)
#
# 日志
#
self.ui.wind_log.triggered.connect(partial(self.show_window, "wind"))
self.ui.error_log.triggered.connect(partial(self.show_window, "error"))
#
# 帮助
#
self.ui.about.triggered.connect(self.show_about)
self.ui.open_book.triggered.connect(partial(self.show_window, "book"))
#
# 蜂鸣报警声
#
self.ui.close_beep.triggered.connect(self.set_play_sound)
def init_interval_combobox(self):
"""
初始化轮询时间下拉列表框
:return: 无
"""
interval_list = ['5 s', '10 s', '15 s', '30 s', '60 s']
self.ui.combobox_interval.addItems(interval_list)
def init_splitter(self):
"""
初始化分离器控件
:return: 无
"""
self.main_splitter = QSplitter(Qt.Vertical) # 新建一个分离器,垂直分离
#
# 分离器添加控件
#
self.main_splitter.addWidget(self.ui.tableView)
self.main_splitter.addWidget(self.ui.output_edit)
#
# 设置窗口比例
#
self.main_splitter.setStretchFactor(0, 8)
self.main_splitter.setStretchFactor(1, 2)
self.ui.data_layout.addWidget(self.main_splitter) # 把这个 splitter 放在一个布局里才能显示出来
def init_output_edit(self):
"""
初始化输出框
:return: 无
"""
self.ui.output_edit.setReadOnly(True) # 禁止编辑
#
# 添加右键菜单
#
self.ui.output_edit.setContextMenuPolicy(Qt.ActionsContextMenu) # 允许右键菜单
send_option = QAction(self.ui.output_edit) # 具体菜单项
send_option.setText("清除内容")
send_option.triggered.connect(self.ui.output_edit.clear) # 点击菜单中的具体选项执行的函数
self.ui.output_edit.addAction(send_option)
def init_table(self):
"""
初始化表格样式
:return:无
"""
self.ui.tableView.verticalHeader().setVisible(False) # 隐藏垂直表头
self.ui.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) # 设置每列宽度:根据表头调整表格宽度
self.ui.tableView.resizeColumnsToContents() # 根据内容调整列宽
self.ui.tableView.clicked.connect(self.handle_table_click) # 鼠标左键点击事件
def show_window(self, name: str):
"""
显示 Windows 资源管理器
:param url: 路径
:return: 无
"""
path = None
if name == "wind":
path = os.getcwd() + r"\log\wind_speed"
elif name == "error":
path = os.getcwd() + r"\log\error_log"
elif name == "book":
path = os.getcwd() + r"\other\光伏集群现场监控使用说明书.pdf"
if os.path.exists(path):
os.system("explorer.exe %s" % path)
else:
dail = InfoDialog("提示", "目前还没有日志!")
dail.exec_()
def show_about(self):
"""
显示关于信息
:return: 无
"""
dial = InfoDialog("关于", "四川近日点新能源科技有限公司\n联系电话:15108303256")
dial.exec_() # 进入事件循环,不关闭不会退出循环
def set_play_sound(self):
"""
设置蜂鸣声
:return:
"""
if self.play_sound is False:
self.play_sound = True
self.append_info("已打开蜂鸣报警声")
self.ui.close_beep.setText("关闭蜂鸣报警声")
else:
self.play_sound = False
self.append_info("已关闭蜂鸣报警声")
self.ui.close_beep.setText("打开蜂鸣报警声")
def get_serial_info(self):
com_port = self.ui.box_com_port.currentText() # 端口号
collector_addr = self.ui.edit_addr.text() # 数采地址
baud_rate = self.ui.edit_baudrate.text() # 波特率
return com_port, collector_addr, baud_rate
def one_key(self, option: str):
"""
一键命令
:param option:命令
:return:无
"""
# self.update_serial()
if self.isPolling is False:
self.append_info("请先开始轮询,然后再开始一键操作!", 'red')
else:
message.append({'cmd': 'one_key', 'option': "%s" % option})
@Slot(int)
def update_member(self, member: int):
"""
更新成员数
:param member:成员数
:return:无
"""
self.ui.label_member.setText(str(member))
@Slot(str)
def update_port(self, port_name_list: str):
"""
初始化下拉列表框
:return:无
"""
port_name_list = eval(port_name_list)
self.ui.box_com_port.clear()
self.ui.box_com_port.addItems(port_name_list)
if len(port_name_list) > 0:
self.append_info("共扫描到 %d 个串口设备:%s" % (len(port_name_list), port_name_list))
self.ui.btn_submit.setEnabled(True) # 可以轮询
else:
self.append_info('未检测到任何串口设备,请检查连接是否正常', 'red')
#
# 加个 if 是为了判断是不是正在轮询中,
# 有可能是正在轮询,突然没有一个串口设备了
#
self.ui.btn_submit.setEnabled(False) # 禁止轮询
@Slot(str, str)
def append_info(self, text: str, color: str = 'black'):
"""
追加信息到输出狂
:param info:信息,字典字符串
:return:
"""
black = QColor(0, 0, 0)
if color == 'red':
c = QColor(255, 0, 0)
elif color == 'green':
c = QColor(0, 128, 0)
else:
c = black
#
# 使用指定颜色追加文本,然后恢复为黑色
#
self.ui.output_edit.setTextColor(c)
self.ui.output_edit.append(util.get_time() + " " + text) # 显示文本
self.ui.output_edit.setTextColor(black)
self.ui.output_edit.moveCursor(QTextCursor.End) # 输出信息后滚动到最后
def handle_table_click(self, item: QModelIndex):
"""
处理表格左键点击事件
:param item:点击的单元格
:return:无
"""
#
# 首先获取点击的行、列号
# 判断点击的单元格是否可点击,如果可以,
# 就弹出编辑对话框
#
i = item.row()
j = item.column()
if self.is_editable(i, j):
#
# 如果在轮询的话,立即停止,并标记需要恢复
#
# recover = False
#
# if self.isPolling:
# self.stop_polling()
# recover = True
#
# 根据行号、列号计算出机器编号,然后显示修改窗口
#
machine_number = self.helper.get_machine_number(i, j)
if self.isPolling is False:
self.append_info("请先开始轮询,再发送控制代码!", 'red')
else:
self.show_modify_dialog(machine_number)
# if recover is True:
# self.start_polling()
def is_editable(self, i, j) -> bool:
"""
判断该单元格是否可编辑
:param i:行,从 0 开始
:param j:列,从 0 开始
:return:是否可编辑
"""
#
# i % 4 == 1 表示 i 在控制代码行
# j % 2 == 1 表示 j 在控制代码列
#
if i % 4 == 1 and j % 2 == 1:
return True
return False
def set_enable(self, enable: bool):
"""
是否允许编辑串口参数相关
:param enable: 是否允许
:return: 无
"""
self.ui.box_com_port.setEnabled(enable) # 端口下拉框
self.ui.edit_baudrate.setEnabled(enable) # 波特率
self.ui.edit_addr.setEnabled(enable) # 地址
self.ui.combobox_interval.setEnabled(enable) # 轮询时间
def start_polling(self):
"""
开始轮询按钮响应函数
提交轮询 or 停止轮询
:return:无
"""
if not self.isPolling:
self.isPolling = True
self.ui.btn_submit.setText("停止轮询")
self.set_enable(False) # 禁止编辑
self.update_serial()
self.append_info("开始轮询")
self.polling()
else:
self.stop_polling()
def update_serial(self):
com_port, collector_addr, baud_rate = self.get_serial_info()
message.append({'cmd': 'update_serial', 'com_port': com_port, 'collector_addr': collector_addr,
'baud_rate': baud_rate})
def polling(self):
"""
轮询查询
:return:无
"""
#
# 更新界面
#
message.append({'cmd': 'member'})
message.append({'cmd': 'table'})
message.append({'cmd': 'wind_speed'})
self.next_polling() # 准备下一次轮询
@Slot()
def stop_polling(self):
"""
立即停止轮询
:return:无
"""
#
# 如果正在轮询,就停止轮询
# 点击“停止轮询”,则按钮立即显示“开始轮询”
#
if self.isPolling:
self.ui.btn_submit.setText("开始轮询")
self.set_enable(True) # 恢复允许编辑
self.isPolling = False
self.append_info("结束轮询") # 信息台输出结束信息
self.close_serial()
#
# 强制停止子线程
#
if self.polling_timer is not None and self.polling_timer.is_alive():
util.stop_thread(self.polling_timer)
def close_serial(self):
"""
发命令关闭串口
:return:
"""
msg = {"cmd": 'close_serial'}
message.append(msg)
def next_polling(self):
"""
设置一个定时器,到了一定时间后就启动轮询
:return:无
"""
interval = int(self.ui.combobox_interval.currentText()[:-2]) # 获取间隔时间下拉框的值
self.polling_timer = Timer(interval, self.polling)
self.polling_timer.setName("polling_timer")
self.polling_timer.setDaemon(True)
self.polling_timer.start()
@Slot(str)
def update_wind_speed(self, wind_speed: str):
"""
更新风速
:param wind_speed:风速值
:return: 无
"""
self.ui.label_wind_speed.setText(wind_speed + " m/s")
collector_addr = self.ui.edit_addr.text() # 数采地址
self.helper.write_wind_speed(float(wind_speed), collector_addr)
@Slot(str)
def update_table(self, table_data: str):
"""
更新表格数据
:param table_data:表格数据
:return:无
"""
table_model, error_number = self.helper.get_table_model(table_data)
if error_number != "":
self.append_info("有异常机器编号:" + error_number)
self.play_error_sound()
collector_addr = self.ui.edit_addr.text() # 数采地址
self.helper.write_error(error_number, collector_addr)
self.ui.tableView.setModel(table_model)
def play_error_sound(self):
"""
播放警报
:return:
"""
if self.play_sound:
playsound.playsound("./other/bee.mp3")
def show_modify_dialog(self, machine_number: int):
"""
显示发送控制代码的对话框
:return: 无
"""
input_dial = ModifyDialog("发送控制代码", "%d 号控制器:" % machine_number)
if input_dial.exec_():
try:
value = input_dial.textValue()
#
# 检查输入
#
obj = re.match(r"^[0-9]{1,2}$", "12")
if obj is None:
raise ValueError
else:
code = int(value)
if 1 <= code <= 99:
code = int(input_dial.textValue())
self.send_control_code(machine_number, code)
else:
raise ValueError
except ValueError:
#
# 提示输入有误
#
info = "输入的控制代码有误!控制代码只能是:1~99"
dial = InfoDialog("提示", info)
dial.exec_() # 进入事件循环
def show_advance_dialog(self):
"""
显示高级对话框,留着预防以后加什么新命令,可以通过这个对话框进行发送
:return:
"""
input_dial = ModifyDialog("发送控制代码", "对所有控制器发送:" )
if input_dial.exec_():
try:
value = input_dial.textValue()
#
# 判断输入字符的长度,大于 2 就不是 1<= x <= 99
#
obj = re.match(r"^[0-9]{1,2}$", "12")
if obj is None:
raise ValueError
else:
code = int(value)
if 1 <= code <= 99:
code = int(input_dial.textValue())
self.one_key(code)
else:
raise ValueError
except ValueError:
#
# 提示输入有误
#
info = "输入的控制代码有误!控制代码只能是 1~99!"
dial = InfoDialog("提示", info)
dial.exec_() # 进入事件循环
def send_control_code(self, machine_number: int, code: int) -> None:
"""
发送控制代码
:param machine_number:机器编号
:param code:控制代码
:return:无
"""
msg = {}
msg["cmd"] = 'send_control_code'
code = '{:04X}'.format(code) # 十进制控制代码转十六进制
msg['machine_number'] = "%d" % machine_number
msg['code'] = "%s" % code
message.append(msg)
if __name__ == '__main__':
app = QApplication([]) # 初始化应用
#
# 检查是否需要验证产品密钥
#
login_dial = LoginDialog()
if login_dial.check() or login_dial.exec_():
#
# 显示界面
#
main_window = MainWindow() # 创建主窗口
# main_window.ui.show() # 按实际大小显示窗口
main_window.ui.showMaximized() # 全屏显示窗口,必须要用,不然不显示界面
#
# 子线程启动
#
serial_worker = SerialWorker(main_window)
serial_worker.start()
check_worker = CheckWorker(main_window)
check_worker.start()
#
# 关闭界面了,强制关闭子线程
#
if app.exec_() == 0:
serial_worker.terminate()
check_worker.terminate()