Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
2442 lines (2175 loc) · 112 KB
/
Copy pathmain.py
File metadata and controls
2442 lines (2175 loc) · 112 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
# -*- coding:utf-8 -*-
import re
import sys
import simplejson as json
import shelve
import sys
import time
from datetime import datetime
from decimal import Decimal
from functools import partial
from queue import Queue
from pubsub import pub
import common.settings as settings
from common.robot_module import Mirobot
from common.check_tools import check_robot_arm_connection, check_robot_arm_is_working, check_robot_arm_emergency_stop
from common.socket_client import ClientSocket, Worker
from common.work_threads import UpdateJointAnglesTask, AgnleDegreeWatchTask, CommandSenderTask, CommandReceiverTask
from componets.table_view_control import (JointOneDelegate, JointTwoDelegate, JointThreeDelegate,
JointFourDelegate, JointFiveDelegate, JointSixDelegate,
JointSpeedDelegate, JointDelayTimeDelegate, ToolControlDelegate)
# UI 相关模块
from PySide6.QtCore import Qt, QThreadPool, QTimer, Slot, QUrl, QRegularExpression
from PySide6.QtGui import QDesktopServices, QIcon, QRegularExpressionValidator
from PySide6.QtWidgets import (QApplication, QFrame, QMenu, QTableWidgetItem, QFileDialog)
from qfluentwidgets import (MSFluentWindow, CardWidget, ComboBox,
NavigationItemPosition, MessageBox, setThemeColor, InfoBar, InfoBarPosition, Dialog)
from qfluentwidgets import FluentIcon as FIF
# 导入子页面控件布局文件
from app.command_page import command_page_frame
from app.teach_page import teach_page_frame
from app.connect_page import connect_page_frame
# 正逆解相关模块
from math import degrees
from spatialmath import SE3
from spatialmath.base import rpy2tr
# 日志模块
from loguru import logger
logger.add(settings.LOG_FILE_PATH, level="DEBUG", rotation="50 MB", retention="7 days", compression="zip")
# 三方通讯模块
from serial.tools import list_ports
# 遇到异常退出时,解除注释下面的代码,查看异常信息
import faulthandler;faulthandler.enable()
class CommandPage(QFrame, command_page_frame):
"""命令控制页面"""
def __init__(self, page_name: str):
super().__init__()
self.setupUi(self)
self.setObjectName(page_name.replace(' ', '-'))
self.initButtonIcon()
self.robot_arm_is_connected = False
self.robot_arm_table_action_status = False
self.initGetRobotArmStatusTask()
self.CommandSendButton.clicked.connect(self.send_json_command)
def initButtonIcon(self):
"""初始化按钮图标"""
self.CommandSendButton.setIcon(FIF.SEND.icon(color="#ffffff"))
self.CommandSendButton.setText('发送')
def initGetRobotArmStatusTask(self):
"""初始化获取机械臂连接状态定时器"""
logger.warning("获取机械臂连接状态定时器,启动!")
self.get_robot_arm_status_timer = QTimer()
self.get_robot_arm_status_timer.timeout.connect(self._get_robot_arm_connect_status)
self.get_robot_arm_status_timer.start(100)
logger.warning("获取机械臂示教执行状态定时器,启动!")
self.get_robot_arm_table_action_status_timer = QTimer()
self.get_robot_arm_table_action_status_timer.timeout.connect(self._get_robot_arm_table_action_status)
self.get_robot_arm_table_action_status_timer.start(100)
@check_robot_arm_is_working
@check_robot_arm_connection
@Slot()
def send_json_command(self):
"""json数据发送按钮"""
try:
command_wait_for_send = self.CommandEditWindow.toPlainText().strip()
try:
json.loads(command_wait_for_send)
except json.JSONDecodeError:
raise ValueError("输入的内容不是有效的 JSON 字符串!")
if command_wait_for_send:
json_data = command_wait_for_send + '\r\n'
self.CommandSendWindow.appendPlainText(json_data.strip())
else:
raise ValueError("发送的数据为空!")
except ValueError as e:
logger.error(f"命令发送异常: {str(e)}")
InfoBar.error(
title='错误',
content=f"{str(e)}",
orient=Qt.Horizontal,
isClosable=True,
duration=3000,
position=InfoBarPosition.TOP,
parent=self
)
self.CommandResWindow.appendPlainText(f"error: {str(e)}")
else:
# 发送机械臂命令
robot_arm_client = self.get_robot_arm_connector()
with robot_arm_client as rac:
rac.send(json_data.encode('utf-8'))
try:
rs_data = json.loads(rac.recv(1024).decode('utf-8').strip())
except json.JSONDecodeError:
logger.error("接收到的数据不是有效的 JSON 字符串!")
InfoBar.error(
title='错误',
content="接收到的数据不是有效的 JSON 字符串!",
orient=Qt.Horizontal,
isClosable=True,
duration=3000,
position=InfoBarPosition.TOP,
parent=self
)
self.CommandResWindow.appendPlainText("error: 接收到的数据不是有效的 JSON 字符串!")
else:
self.CommandResWindow.appendPlainText(json.dumps(rs_data, use_decimal=True)) # 命令响应填入到响应窗口
def _get_robot_arm_connect_status(self):
"""获取机械臂连接状态"""
pub.subscribe(self._check_robot_arm_connect_status, 'robot_arm_connect_status')
def _check_robot_arm_connect_status(self, status: bool):
"""订阅机械臂连接状态"""
self.robot_arm_is_connected = status
def _get_robot_arm_table_action_status(self):
"""获取机械臂示教执行状态定时器方法"""
pub.subscribe(self._check_robot_arm_table_action_status, 'robot_arm_table_action_status')
def _check_robot_arm_table_action_status(self, status: bool):
"""订阅机械臂示教执行状态"""
self.robot_arm_table_action_status = status
@logger.catch
def get_robot_arm_connector(self):
"""获取与机械臂的连接对象"""
try:
socket_info = shelve.open(str(settings.IP_PORT_INFO_FILE_PATH))
host = socket_info['target_ip']
port = int(socket_info['target_port'])
if host and port:
robot_arm_client = ClientSocket(host, port)
else:
logger.error("IP 和 Port 信息为空!")
InfoBar.warning(
title='警告',
content="IP 和 Port 信息为空,请前往【连接配置】页面填写 !",
orient=Qt.Horizontal,
isClosable=True,
duration=3000,
position=InfoBarPosition.TOP,
parent=self
)
except Exception as e:
logger.error(str(e))
InfoBar.error(
title='错误',
content="没有读取到 ip 和 port 信息,请前往机械臂配置 !",
orient=Qt.Horizontal,
isClosable=True,
duration=3000,
position=InfoBarPosition.TOP,
parent=self
)
finally:
socket_info.close()
return robot_arm_client
class TeachPage(QFrame, teach_page_frame):
"""示教控制页面"""
def __init__(self, page_name: str, thread_pool: QThreadPool, command_queue: Queue, joints_angle_queue: Queue):
super().__init__()
self.setupUi(self)
self.setObjectName(page_name.replace(' ', '-'))
self.initButtonIcon()
self.initJointControlWidiget()
# 状态标志
self.move_status = False # 机械臂运动状态
self.thread_is_on = True # 线程工作标志位
self.table_action_thread_flag = True # 顺序执行示教动作线程标志位
self.robot_arm_table_action_status = False # 顺序执行示教动作任务进行标志位
self.robot_arm_is_connected = False # 机械臂连接状态
self.robot_arm_emergency_stop = False # 机械臂急停状态
self.init_button_clicks = 0 # 初始化按钮点击次数,用于机械臂急停按钮状态切换
self.command_model = "SEQ" # 用于示教执行命令时,判断机械臂的命令模式的标志位 SEQ(顺序指令), INT(实时指令)
# 线程与队列
self.thread_pool = thread_pool
self.command_queue = command_queue # 控制命令队列
self.joints_angle_queue = joints_angle_queue # 查询到的机械臂关节角度队列
self.robot_arm = Mirobot(settings.ROBOT_MODEL_CONFIG_FILE_PATH, param_type='MDH')
# 开启角度更新与末端工具位姿的更新线程
self.back_task_start()
# 设置输入框的过滤器
self.init_input_validator()
# 示教控制页面
self.tool_type = ["夹爪", "吸盘"]
self.ArmToolOptions = self.ArmToolComboBox.addItems(self.tool_type)
self.ArmToolComboBox.setCurrentText("吸盘")
# 机械臂工作模式下拉框
self.command_model_type = ["顺序执行", "立即执行"]
self.CommandModeComboBox.addItems(self.command_model_type)
self.CommandModeComboBox.setPlaceholderText("顺序执行")
self.CommandModeComboBox.setCurrentText(0)
# 示教控制操作按钮槽函数绑定
self.ActionImportButton.clicked.connect(self.import_data)
self.ActionOutputButton.clicked.connect(self.export_data)
self.CommandModeComboBox.currentIndexChanged.connect(self.change_command_mode)
self.ActionStepRunButton.clicked.connect(self.run_action_step)
self.ActionRunButton.clicked.connect(self.run_all_action)
self.ActionLoopRunButton.clicked.connect(self.run_action_loop)
self.ActionDeleteButton.clicked.connect(self.remove_item)
self.ActionAddButton.clicked.connect(self.add_item)
self.ActionUpdateRowButton.clicked.connect(self.update_row)
# 示教控制页面的按钮提示信息
self.ActionImportButton.setToolTip("导入动作文件")
self.ActionImportButton.setToolTipDuration(2000)
self.ActionOutputButton.setToolTip("导出动作文件")
self.ActionOutputButton.setToolTipDuration(2000)
self.ActionStepRunButton.setToolTip("单次执行选定的动作")
self.ActionStepRunButton.setToolTipDuration(2000)
self.ActionRunButton.setToolTip("顺序执行所有动作")
self.ActionRunButton.setToolTipDuration(2000)
self.ActionLoopRunButton.setToolTip("循环执行指定次数动作")
self.ActionLoopRunButton.setToolTipDuration(2000)
self.ActionDeleteButton.setToolTip("删除指定动作")
self.ActionDeleteButton.setToolTipDuration(2000)
self.ActionUpdateRowButton.setToolTip("更新指定行动作")
self.ActionUpdateRowButton.setToolTipDuration(2000)
self.ActionAddButton.setToolTip("添加一行动作")
self.ActionAddButton.setToolTipDuration(2000)
# 示教控制添加右键的上下文菜单
self.context_menu = QMenu(self)
self.copy_action = self.context_menu.addAction("复制")
self.paste_action = self.context_menu.addAction("粘贴") # 默认粘贴到最后一行
self.updata_action = self.context_menu.addAction("更新单元格")
self.insert_row_action = self.context_menu.addAction("插入一行") # 默认插入到最后一行,无法插入当前行的下一行
self.copy_action.triggered.connect(self.copy_selected_row)
self.paste_action.triggered.connect(self.paste_row)
self.updata_action.triggered.connect(self.update_cell)
self.insert_row_action.triggered.connect(self.insert_row)
self.ActionTableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.ActionTableWidget.customContextMenuRequested.connect(self.show_context_menu)
self.copied_row = None
# 实例化机械臂关节控制回调函数绑定
# TODO: 关节限位需要写到外部配置文件中去
self.JointOneAddButton.clicked.connect(partial(self.modify_joint_angle, 1, -130, 135, increase=True))
self.JointOneSubButton.clicked.connect(partial(self.modify_joint_angle, 1, -130, 135, increase=False))
self.JointTwoAddButton.clicked.connect(partial(self.modify_joint_angle, 2, -86, 96, increase=True))
self.JointTwoSubButton.clicked.connect(partial(self.modify_joint_angle, 2, -86, 96, increase=False))
self.JointThreeAddButton.clicked.connect(partial(self.modify_joint_angle, 3, -90, 46, increase=True))
self.JointThreeSubButton.clicked.connect(partial(self.modify_joint_angle, 3, -90, 46, increase=False))
self.JointFourAddButton.clicked.connect(partial(self.modify_joint_angle, 4, -143, 184, increase=True))
self.JointFourSubButton.clicked.connect(partial(self.modify_joint_angle, 4, -143, 184, increase=False))
self.JointFiveAddButton.clicked.connect(partial(self.modify_joint_angle, 5, -219, 36, increase=True))
self.JointFiveSubButton.clicked.connect(partial(self.modify_joint_angle, 5, -219, 36, increase=False))
self.JointSixAddButton.clicked.connect(partial(self.modify_joint_angle, 6, -360, 360, increase=True))
self.JointSixSubButton.clicked.connect(partial(self.modify_joint_angle, 6, -360, 360, increase=False))
self.JointStepAddButton.clicked.connect(partial(self.modify_joint_angle_step, increase=True))
self.JointStepSubButton.clicked.connect(partial(self.modify_joint_angle_step, increase=False))
self.JointSpeedUpButton.clicked.connect(partial(self.modify_joint_speed_percentage, increase=True))
self.JointSpeedDecButton.clicked.connect(partial(self.modify_joint_speed_percentage, increase=False))
self.JointDelayTimeAddButton.clicked.connect(partial(self.modify_joint_delay_time, increase=True))
self.JointDelayTimeSubButton.clicked.connect(partial(self.modify_joint_delay_time, increase=False))
# 复位和急停按钮绑定
self.RobotArmResetButton.clicked.connect(self.robot_arm_initialize)
self.RobotArmZeroButton.clicked.connect(self.reset_to_zero)
self.RobotArmStopButton.clicked.connect(self.stop_robot_arm_emergency)
# 末端工具控制组回调函数绑定
self.ArmToolSwitchButton.checkedChanged.connect(self.tool_switch_control)
self.GrapToolSlider.valueChanged.connect(self.tool_gripper_control)
self.SwitchButtonOne.checkedChanged.connect(partial(self.set_extend_io_status, 1))
self.SwitchButtonTwo.checkedChanged.connect(partial(self.set_extend_io_status, 2))
self.SwitchButtonThree.checkedChanged.connect(partial(self.set_extend_io_status, 3))
self.SwitchButtonFour.checkedChanged.connect(partial(self.set_extend_io_status, 4))
# 末端工具坐标增减回调函数绑定
self.XAxisAddButton.clicked.connect(partial(self.end_tool_coordinate_operate, axis='x', action="add"))
self.XAxisSubButton.clicked.connect(partial(self.end_tool_coordinate_operate, axis='x', action="sub"))
self.YAxisAddButton.clicked.connect(partial(self.end_tool_coordinate_operate, axis='y', action="add"))
self.YAxisSubButton.clicked.connect(partial(self.end_tool_coordinate_operate, axis='y', action="sub"))
self.ZAxisAddButton.clicked.connect(partial(self.end_tool_coordinate_operate, axis='z', action="add"))
self.ZAxisSubButton.clicked.connect(partial(self.end_tool_coordinate_operate, axis='z', action="sub"))
self.CoordinateAddButton.clicked.connect(partial(self.tool_coordinate_step_modify, action="add"))
self.CoordinateStepSubButton.clicked.connect(partial(self.tool_coordinate_step_modify, action="sub"))
# 末端工具姿态增减回调函数绑定
self.RxAxisAddButton.clicked.connect(partial(self.tool_rx_operate, action="add"))
self.RxAxisSubButton.clicked.connect(partial(self.tool_rx_operate, action="sub"))
self.RyAxisAddButton.clicked.connect(partial(self.tool_ry_operate, action="add"))
self.RyAxisSubButton.clicked.connect(partial(self.tool_ry_operate, action="sub"))
self.RzAxisAddButton.clicked.connect(partial(self.tool_rz_operate, action="add"))
self.RzAxisSubButton.clicked.connect(partial(self.tool_rz_operate, action="sub"))
self.ApStepAddButton.clicked.connect(partial(self.tool_pose_step_modify, action="add"))
self.ApStepSubButton.clicked.connect(partial(self.tool_pose_step_modify, action="sub"))
def back_task_start(self):
"""后台任务启动"""
logger.warning("获取机械臂连接状态定时器,启动!")
self.get_arm_connect_status_timer = QTimer()
self.get_arm_connect_status_timer.timeout.connect(self.get_robot_arm_connect_status_timer)
self.get_arm_connect_status_timer.start(100)
logger.warning("获取机械臂命令模式定时器,启动!")
self.update_connect_status_timer = QTimer()
self.update_connect_status_timer.timeout.connect(self.get_current_cmd_model)
self.update_connect_status_timer.start(1000)
logger.warning("更新机械臂的关节角度/末端位姿数据线程,启动!")
self.update_joint_angles_thread = UpdateJointAnglesTask(self.joints_angle_queue)
self.thread_pool.start(self.update_joint_angles_thread)
self.update_joint_angles_thread.singal_emitter.joint_angles_update_signal.connect(self.update_joint_degrees_text)
self.update_joint_angles_thread.singal_emitter.arm_endfactor_positions_update_signal.connect(self.update_arm_pose_text)
# 顶部工具栏
@check_robot_arm_connection
@check_robot_arm_is_working
@Slot()
def import_data(self):
"""导入动作"""
file_name, _ = QFileDialog.getOpenFileName(self, "导入动作文件", "",
"JSON Files (*.json);;All Files (*)")
try:
if file_name:
logger.info(f"开始导入 {file_name} 动作文件")
with open(file_name, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
self.ActionTableWidget.setRowCount(0) # 清空表格
for item in data:
angle_1 = item.get("J1/X", "")
angle_2 = item.get("J2/X", "")
angle_3 = item.get("J3/X", "")
angle_4 = item.get("J4/X", "")
angle_5 = item.get("J5/X", "")
angle_6 = item.get("J6/X", "")
speed_percentage = item.get("速度", 30) # 速度百分比默认为 30%
arm_tool_option = item.get("工具", "")
arm_tool_control = item.get("工具状态", "")
arm_action_delay_time = item.get("延时", "")
note = item.get("备注", "")
row_position = self.ActionTableWidget.rowCount()
self.ActionTableWidget.insertRow(row_position)
self.update_table_cell(row_position, 0, angle_1)
self.update_table_cell(row_position, 1, angle_2)
self.update_table_cell(row_position, 2, angle_3)
self.update_table_cell(row_position, 3, angle_4)
self.update_table_cell(row_position, 4, angle_5)
self.update_table_cell(row_position, 5, angle_6)
self.update_table_cell(row_position, 6, speed_percentage)
# 工具列
arm_tool_combobox = ComboBox()
arm_tool_combobox.addItems(["夹爪", "吸盘"])
arm_tool_combobox.setCurrentText(arm_tool_option)
self.update_table_cell_widget(row_position, 7, arm_tool_combobox)
# 工具状态列
if arm_tool_option == "吸盘":
arm_tool_control_combobox = ComboBox()
arm_tool_control_combobox.addItems(["关", "开"])
arm_tool_control_combobox.setCurrentText(arm_tool_control)
self.update_table_cell_widget(row_position, 8, arm_tool_control_combobox)
elif arm_tool_option == "夹爪":
self.update_table_cell(row_position, 8, arm_tool_control)
# 延时列
self.update_table_cell(row_position, 9, arm_action_delay_time)
# 备注列
self.update_table_cell(row_position, 10, note)
logger.info("完成导入动作文件!")
else:
logger.warning("取消导入动作文件!")
except Exception as e:
logger.error(f"导入动作文件失败: {e}")
InfoBar.error(
title="错误",
content="⬇️ 导入动作文件失败!",
isClosable=True,
orient=Qt.Horizontal,
duration=3000,
position=InfoBarPosition.TOP_LEFT,
parent=self
)
@check_robot_arm_connection
@check_robot_arm_is_working
@Slot()
def export_data(self):
"""导出动作"""
file_timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
file_name, _ = QFileDialog.getSaveFileName(self, "导出动作文件", f"robot_arm_action_{file_timestamp}.json", "JSON Files (*.json);;All Files (*)",
)
if file_name:
logger.info("开始导出动作文件")
logger.debug(f"导出的配置文件的路径 {file_name}")
data = []
for row in range(self.ActionTableWidget.rowCount()):
angle_1 = self.ActionTableWidget.item(row, 0).text()
angle_2 = self.ActionTableWidget.item(row, 1).text()
angle_3 = self.ActionTableWidget.item(row, 2).text()
angle_4 = self.ActionTableWidget.item(row, 3).text()
angle_5 = self.ActionTableWidget.item(row, 4).text()
angle_6 = self.ActionTableWidget.item(row, 5).text()
speed_percentage = self.ActionTableWidget.item(row, 6).text() # 速度列
arm_tool_widget = self.ActionTableWidget.cellWidget(row, 7) # 工具列
arm_action_delay_time = self.ActionTableWidget.item(row, 9).text() # 延时列
note = self.ActionTableWidget.item(row, 10).text() # 备注列
if arm_tool_widget is not None:
arm_tool_option = arm_tool_widget.currentText()
if arm_tool_option == "吸盘":
suction_cup_status_widget = self.ActionTableWidget.cellWidget(row, 8) # 工具状态列
if suction_cup_status_widget is not None:
tool_control_status = suction_cup_status_widget.currentText()
else:
tool_control_status = ""
elif arm_tool_option == "夹爪":
tool_control_status = self.ActionTableWidget.item(row, 8).text()
data.append({
"J1/X": angle_1,
"J2/X": angle_2,
"J3/X": angle_3,
"J4/X": angle_4,
"J5/X": angle_5,
"J6/X": angle_6,
"速度": speed_percentage,
"工具": arm_tool_option,
"工具状态": tool_control_status,
"延时": arm_action_delay_time,
"备注": note
})
with open(file_name, "w", encoding="utf-8") as json_file:
json.dump(data, json_file, indent=4, ensure_ascii=False)
logger.info("导出配置文件成功!")
@check_robot_arm_connection
@check_robot_arm_is_working
@Slot()
def change_command_mode(self, mode_index):
"""切换命令模式
:params mode_index: 0 顺序模式(SEQ), 1 实时模式(INT)
"""
logger.debug(f"命令模式当前索引: {mode_index}")
self.command_model = "SEQ" if mode_index == 0 else "INT"
logger.warning(f"命令模式切换: {self.command_model} !")
command_model_payload = {"command": "set_robot_mode", "data": [self.command_model]}
command_model_payload_str = json.dumps(command_model_payload).replace(' ', "") + '\r\n'
self.command_queue.put(command_model_payload_str.encode('utf-8'))
def tale_action_thread(self, total_action_row: int):
"""顺序执行示教动作线程"""
if total_action_row:
self.update_table_action_task_status(status_flag=True)
logger.debug(f"动作总数: {total_action_row}")
for each_row in range(total_action_row):
if self.table_action_thread_flag:
pub.subscribe(self._check_tale_action_thread_flag, 'tale_action_thread_flag')
if self.command_model == "SEQ":
logger.warning(f"【顺序执行】模式,机械臂正在发送第 {each_row + 1} 个动作")
else:
logger.warning(f"【立即执行】模式,机械臂正在执行第 {each_row + 1} 个动作")
# 更新任务执行的进度条
self.ProgressBar.setVal(100 * (each_row + 1) / total_action_row)
# 构造机械臂执行动作的数据
arm_payload_data, tool_type_data, delay_time = self.get_arm_action_payload(each_row)
# 订阅机械臂的角度信息,判断是否到达目标位置
logger.debug(f'运动状态: {self.move_status}')
# 发送机械臂执行动作的命令
json_command = {"command": "set_joint_angle_all_time", "data": arm_payload_data}
str_command = json.dumps(json_command, use_decimal=True).replace(' ', "") + '\r\n'
self.command_queue.put(str_command.encode())
# 控制末端工具动作的命令
if tool_type_data[0] == "吸盘" and tool_type_data[1] != "":
tool_status = 1 if tool_type_data[1] == "开" else 0
json_command = {"command":"set_end_tool", "data": [1, tool_status]}
str_command = json.dumps(json_command).replace(' ', "") + '\r\n'
self.command_queue.put(str_command.encode())
if tool_type_data[0] == "夹爪" and tool_type_data[1] != "":
grap_tool_status = tool_type_data[1] # 夹爪的开合大小
json_command = {"command":"set_end_tool", "data": [2, grap_tool_status]}
str_command = json.dumps(json_command).replace(' ', "") + '\r\n'
self.command_queue.put(str_command.encode())
# SEQ 顺序模式下,发送延时命令,INT 模式不发送延时命令
if self.command_model == 'SEQ' and delay_time != 0:
set_delay_time = int(delay_time * 1000)
if set_delay_time <= 30000:
json_command = {"command": "set_time_delay", "data": [set_delay_time]}
str_command = json.dumps(json_command).replace(' ', "") + '\r\n'
self.command_queue.put(str_command.encode())
else:
logger.error("延时时间超过 30s, 请重新设置!")
break
# 根据动作是否到位,以及线程是否工作判断是否执行
if self.command_model == "INT":
pub.subscribe(self._check_tale_action_thread_flag, 'tale_action_thread_flag')
delay_count = 0 # 动作超时计数器
while not self.move_status and self.table_action_thread_flag and self.thread_is_on:
time.sleep(0.1)
pub.subscribe(self._joints_move_status, 'joints/move_status') # 机械臂动作执行状态标识
pub.subscribe(self._check_flag, 'thread_work_flag') # 线程控制标识
pub.subscribe(self._check_tale_action_thread_flag, 'tale_action_thread_flag') # 示教线程运动标识
logger.warning("等待上一个动作完成")
delay_count += 1
logger.debug(f"等待次数: {delay_count}")
if delay_count >= 100:
logger.warning("等待时间过长,默认完成!")
self.move_status = True
# 完成所有动作后,退出循环
if each_row + 1 == total_action_row:
logger.debug("所有动作执行完成")
self.move_status = True
self.move_status = False # 单个动作执行完成后需要重置状态,否则无法进入 while 循环
self.ProgressBar.setVal(0) # 进度条清零
else:
logger.warning("急停, 线程退出!")
self.ProgressBar.setVal(0) # 重置进度条
self.update_table_action_task_status(status_flag=False)
break
self.update_table_action_task_status(status_flag=False)
else:
logger.warning("机械臂没有动作可以执行!")
def _check_flag(self, flag=True):
"""线程工作控制位"""
self.thread_is_on = flag
def _check_tale_action_thread_flag(self, flag=True):
"""示教线程工作控制位"""
self.table_action_thread_flag = flag
def _joints_move_status(self, move_status=False):
"""订阅机械臂的关节运动状态"""
self.move_status = move_status
@check_robot_arm_connection
@check_robot_arm_is_working
@check_robot_arm_emergency_stop
@Slot()
def run_all_action(self):
"""顺序执行示教动作"""
if (total_row_count := self.ActionTableWidget.rowCount()) > 0:
InfoBar.success(
title="成功",
content="【顺序执行】任务开始",
isClosable=True,
orient=Qt.Horizontal,
duration=3000,
position=InfoBarPosition.TOP_LEFT,
parent=self
)
run_all_action_thread = Worker(self.tale_action_thread, total_row_count)
self.thread_pool.start(run_all_action_thread)
else:
InfoBar.warning(
title="警告",
content="没有动作可以执行, 请添加动作!",
isClosable=True,
orient=Qt.Horizontal,
duration=3000,
position=InfoBarPosition.TOP_LEFT,
parent=self
)
def get_arm_action_payload(self, row):
"""获取机械臂示执行示教动作的角度数据
Args:
row (QTableWidget): 用户在示教界面,点击选中的行
Returns:
arm_payload_data (list): 机械臂的关节角度数据
tool_type_data (list): 末端工具的类型数据
delay_time (float): 执行动作需要的时间
"""
angle_1 = float(self.ActionTableWidget.item(row, 0).text())
angle_2 = float(self.ActionTableWidget.item(row, 1).text())
angle_3 = float(self.ActionTableWidget.item(row, 2).text())
angle_4 = float(self.ActionTableWidget.item(row, 3).text())
angle_5 = float(self.ActionTableWidget.item(row, 4).text())
angle_6 = float(self.ActionTableWidget.item(row, 5).text())
speed_percentage = float(self.ActionTableWidget.item(row, 6).text())
type_of_tool = self.ActionTableWidget.cellWidget(row, 7).currentText()
if type_of_tool == "吸盘":
tool_switch = self.ActionTableWidget.cellWidget(row, 8).currentText()
elif type_of_tool == "夹爪":
tool_switch = int(self.ActionTableWidget.item(row, 8).text())
delay_time = float(self.ActionTableWidget.item(row, 9).text()) # 执行动作需要的时间
# 机械臂执行命令
arm_payload = [speed_percentage, angle_1, angle_2, angle_3, angle_4, angle_5, angle_6]
tool_payload = [type_of_tool, tool_switch]
return arm_payload, tool_payload, delay_time
def robot_arm_step_action_thread(self, row):
"""机械臂单次执行示教动作线程"""
self.update_table_action_task_status(status_flag=True)
arm_payload_data, tool_type_data, _ = self.get_arm_action_payload(row)
json_command = {"command": "set_joint_angle_all_time", "data": arm_payload_data}
str_command = json.dumps(json_command, use_decimal=True).replace(' ', "") + '\r\n'
self.command_queue.put(str_command.encode())
# 末端工具动作
if tool_type_data[0] == "吸盘" and tool_type_data[1] != "":
tool_status = 1 if tool_type_data[1] == "开" else 0
json_command = {"command":"set_end_tool", "data": [1, tool_status]}
str_command = json.dumps(json_command).replace(' ', "") + '\r\n'
self.command_queue.put(str_command.encode())
if tool_type_data[0] == "夹爪" and tool_type_data[1] != "":
grap_tool_status = tool_type_data[1] # 夹爪的开合大小
json_command = {"command":"set_end_tool", "data": [2, grap_tool_status]}
str_command = json.dumps(json_command).replace(' ', "") + '\r\n'
self.command_queue.put(str_command.encode())
self.update_table_action_task_status(status_flag=False)
def update_table_action_task_status(self, status_flag=True):
"""发布并更新示教任务执行中的状态"""
if status_flag:
logger.warning("机械臂示教动作任务进行中! ")
else:
logger.warning("机械臂示教动作任务结束! ")
pub.sendMessage('robot_arm_table_action_status', status=status_flag)
self.robot_arm_table_action_status = status_flag
@check_robot_arm_connection
@check_robot_arm_is_working
@check_robot_arm_emergency_stop
@Slot()
def run_action_step(self):
"""单次执行选定的动作"""
# 获取到选定的动作
if (selected_row := self.ActionTableWidget.currentRow()) >= 0:
InfoBar.success(
title="成功",
content=f"【单次执行】正则执行第 {selected_row + 1} 个动作",
orient=Qt.Horizontal,
duration=3000,
isClosable=True,
position=InfoBarPosition.TOP_LEFT,
parent=self
)
# 启动机械臂动作执行线程
run_action_step_thread = Worker(self.robot_arm_step_action_thread, selected_row)
self.thread_pool.start(run_action_step_thread)
else:
InfoBar.warning(
title="警告",
content="请选择需要执行的动作!",
isClosable=True,
orient=Qt.Horizontal,
duration=3000,
position=InfoBarPosition.TOP_LEFT,
parent=self
)
def arm_action_loop_thread(self, loop_times):
"""机械臂循环执行指定次数的示教动作线程"""
# 获取循环动作循环执行的次数
if (action_count := self.ActionTableWidget.rowCount()) > 0:
for loop_time in range(loop_times):
logger.warning(f"机械臂正在执行第 {loop_time + 1} 次循环动作")
if self.table_action_thread_flag:
self.tale_action_thread(action_count)
time.sleep(1) # 循环组间的间隔时间
else:
logger.warning("急停, 循环执行任务退出!")
self.update_table_action_task_status(status_flag=False)
break
else:
logger.warning("机械臂没有动作可以执行!")
@check_robot_arm_connection
@check_robot_arm_is_working
@check_robot_arm_emergency_stop
@Slot()
def run_action_loop(self):
"""循环执行动作"""
if (row_count := self.ActionTableWidget.rowCount()) > 0:
if self.ActionLoopTimes.text().isdigit():
loop_times = int(self.ActionLoopTimes.text().strip())
# 顺序模式下,最多执行 400 条动作
# TODO: 需要优化,判断在顺序模式下,发送的一组任务是否完成,完成后再发送下一组任务
total_action_count = loop_times * row_count
if self.command_model == "SEQ":
if total_action_count <= 400:
InfoBar.success(
title="成功",
content="【循环执行】任务开始",
orient=Qt.Horizontal,
duration=3000,
isClosable=True,
position=InfoBarPosition.TOP_LEFT,
parent=self
)
loop_work_thread = Worker(self.arm_action_loop_thread, loop_times)
self.thread_pool.start(loop_work_thread)
else:
InfoBar.warning(
title="警告",
content=f"顺序模式下,最多执行 400 条动作\n当前 {total_action_count} 条,请减少循环次数!",
isClosable=True,
orient=Qt.Horizontal,
duration=-1,
position=InfoBarPosition.TOP,
parent=self
)
elif self.command_model == "INT":
loop_work_thread = Worker(self.arm_action_loop_thread, loop_times)
self.thread_pool.start(loop_work_thread)
InfoBar.success(
title="成功",
content="【循环执行】任务开始",
orient=Qt.Horizontal,
duration=3000,
isClosable=True,
position=InfoBarPosition.TOP_LEFT,
parent=self
)
else:
logger.error(f"未知命令模式: {self.command_model}")
else:
InfoBar.warning(
title="警告",
content="请输入动作循环次数[0-99]",
isClosable=True,
orient=Qt.Horizontal,
duration=3000,
position=InfoBarPosition.TOP_LEFT,
parent=self
)
else:
InfoBar.warning(
title="警告",
content="没有动作可以执行, 请添加动作!",
isClosable=True,
orient=Qt.Horizontal,
duration=3000,
position=InfoBarPosition.TOP_LEFT,
parent=self
)
@Slot()
def show_context_menu(self, pos):
"""右键复制粘贴菜单"""
self.context_menu.exec_(self.ActionTableWidget.mapToGlobal(pos))
@check_robot_arm_connection
@check_robot_arm_is_working
@check_robot_arm_emergency_stop
@Slot()
def add_item(self):
"""示教控制添加一行动作"""
speed_percentage = self.JointSpeedEdit.text() # 速度值,暂定百分比
type_of_tool = self.ArmToolComboBox.currentText() # 获取末端工具类型
row_position = self.ActionTableWidget.rowCount()
self.ActionTableWidget.insertRow(row_position)
# 定义列索引和对应的值
column_value_map = {
0: str(self.q1),
1: str(self.q2),
2: str(self.q3),
3: str(self.q4),
4: str(self.q5),
5: str(self.q6),
6: speed_percentage,
9: str(self.JointDelayTimeEdit.text()),
10: ""
}
# 设置普通单元格的值
for col, value in column_value_map.items():
self.ActionTableWidget.setItem(row_position, col, QTableWidgetItem(value))
# 工具列添加下拉选择框
arm_tool_combobox = ComboBox()
arm_tool_combobox.addItems(["夹爪", "吸盘"])
arm_tool_combobox.setCurrentText(type_of_tool)
# 监听表格中工具类型的变化,修改对应的工具状态
arm_tool_combobox.currentIndexChanged.connect(lambda: self.on_tool_control_change(row_position))
self.ActionTableWidget.setCellWidget(row_position, 7, arm_tool_combobox)
# 根据工具类型添加不同的控制方式
if type_of_tool == "吸盘":
arm_tool_control = ComboBox()
arm_tool_control.addItems(["关", "开"])
arm_tool_control.setCurrentText("开" if self.ArmToolSwitchButton.isChecked() else "关")
self.ActionTableWidget.setCellWidget(row_position, 8, arm_tool_control)
elif type_of_tool == "夹爪":
grap_value = self.GrapToolSlider.value()
self.ActionTableWidget.setItem(row_position, 8, QTableWidgetItem(str(grap_value)))
def on_tool_control_change(self, row):
"""根据工具类型的变化,修改表格中对应的工具状态"""
tool_type = self.ActionTableWidget.cellWidget(row, 7).currentText()
if tool_type == "吸盘":
arm_tool_control = ComboBox()
arm_tool_control.addItems(["关", "开"])
arm_tool_control.setCurrentText("开" if self.ArmToolSwitchButton.isChecked() else "关")
self.update_table_cell_widget(row, 8, arm_tool_control)
elif tool_type == "夹爪":
grap_value = self.GrapToolSlider.value()
self.update_table_cell(row, 8, grap_value)
@check_robot_arm_connection
@check_robot_arm_is_working
@check_robot_arm_emergency_stop
@Slot()
def remove_item(self):
"""示教控制删除一行动作"""
selected_rows = self.ActionTableWidget.selectionModel().selectedRows()
delete_confirm_window = Dialog("⚠️警告", "确定要删除选择的动作吗?删除动作不可恢复(不选择动作,默认从最后一行开始删除)")
if not selected_rows:
# 如果没有选中行,则删除最后一行
if delete_confirm_window.exec():
last_row = self.ActionTableWidget.rowCount() - 1
if last_row >= 0:
self.ActionTableWidget.removeRow(last_row)
else:
if delete_confirm_window.exec():
for row in reversed(selected_rows):
self.ActionTableWidget.removeRow(row.row())
@check_robot_arm_connection
@check_robot_arm_is_working
@check_robot_arm_emergency_stop
@Slot()
def update_row(self):
"""示教控制更新指定行的动作"""
selected_rows = self.ActionTableWidget.selectionModel().selectedRows()
if selected_rows:
for row in selected_rows:
row_index = row.row()
# 定义列索引和对应的值
column_value_map = {
0: self.q1,
1: self.q2,
2: self.q3,
3: self.q4,
4: self.q5,
5: self.q6,
6: self.JointSpeedEdit.text(),
9: self.JointDelayTimeEdit.text()
}
# 更新普通单元格的值
for col, value in column_value_map.items():
self.update_table_cell(row_index, col, value)
# 更新工具列和工具状态列
arm_tool_combobox = ComboBox()
arm_tool_combobox.addItems(["", "夹爪", "吸盘"])
arm_current_tool_type = self.ArmToolComboBox.currentText()
arm_tool_combobox.setCurrentText(arm_current_tool_type)
self.update_table_cell_widget(row_index, 7, arm_tool_combobox)
# 根据工具类型,更新工具的状态
if arm_current_tool_type == "夹爪":
self.update_table_cell(row_index, 8, self.GrapToolSlider.value())
elif arm_current_tool_type == "吸盘":
arm_tool_control = ComboBox()
arm_tool_control.addItems(["", "关", "开"])
arm_tool_control.setCurrentText("开" if self.ArmToolSwitchButton.isChecked() else "关")
self.update_table_cell_widget(row_index, 8, arm_tool_control)
else:
InfoBar.warning(
title="警告",
content="请选择需要更新的行! \n点击表格左侧行号即可选中行",
isClosable=True,
orient=Qt.Horizontal,
duration=3000,
parent=self
)
@check_robot_arm_connection
@check_robot_arm_is_working
@check_robot_arm_emergency_stop
@Slot()
def update_column(self):
"""更新选中的列"""
selected_columns = self.ActionTableWidget.selectionModel().selectedColumns()
if selected_columns:
# 定义列索引和对应的值
column_value_map = {
0: self.q1,
1: self.q2,
2: self.q3,
3: self.q4,
4: self.q5,
5: self.q6,
6: self.JointSpeedEdit.text(),
9: self.JointDelayTimeEdit.text()
}
for col in selected_columns:
column_number = col.column()
for row in range(self.ActionTableWidget.rowCount()):
if column_number in column_value_map:
self.update_table_cell(row, column_number, column_value_map[column_number])
elif column_number == 7:
arm_tool_combobox = ComboBox()
arm_tool_combobox.addItems(["", "夹爪", "吸盘"])
arm_tool_combobox.setCurrentText(self.ArmToolComboBox.currentText())
self.update_table_cell_widget(row, column_number, arm_tool_combobox)
elif column_number == 8:
arm_tool_control = ComboBox()
arm_tool_control.addItems(["", "关", "开"])
self.update_table_cell_widget(row, column_number, arm_tool_control)
else:
InfoBar.warning(
title="警告",
content="请选择需要更新的列! \n点击表格上方列名即可选中列",
isClosable=True,
orient=Qt.Horizontal,
duration=3000,
parent=self
)
# 表格的右键菜单功能
@Slot()
def show_context_menu(self, pos):
"""右键菜单"""
self.context_menu.exec(self.ActionTableWidget.mapToGlobal(pos))
@Slot()
def copy_selected_row(self):
"""复制选择行"""
selected_row = self.ActionTableWidget.currentRow()
if selected_row >= 0:
self.copied_row = []
for col in range(self.ActionTableWidget.columnCount()):
# 工具列、开关列,需要获取下拉框中的文本
if col in (7, 8):
item_widget = self.ActionTableWidget.cellWidget(selected_row, col)
if item_widget is not None:
self.copied_row.append(item_widget.currentText())
else:
item = self.ActionTableWidget.item(selected_row, col)
if item is not None: