-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDPSManagerApp_PyQt5.py
More file actions
2492 lines (2190 loc) · 107 KB
/
PDPSManagerApp_PyQt5.py
File metadata and controls
2492 lines (2190 loc) · 107 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 -*-
"""
PDPSManagerApp - PyQt5 GUI 重写版
将原 tkinter GUI 全部替换为 PyQt5,业务逻辑类保持不变。
"""
import os
import sys
import subprocess
import threading
import queue
import traceback
import json
import math
import zipfile
from datetime import datetime
from typing import List, Dict, Optional, Tuple
import pandas as pd
import numpy as np
import winreg
import re
import ctypes
import threading
import queue
import traceback
from PyQt5.QtWidgets import (QMessageBox, QInputDialog, QLineEdit, QDialog,
QVBoxLayout, QLabel, QProgressBar, QPushButton, QApplication)
from PyQt5.QtCore import QTimer, Qt
from PyQt5.QtGui import QFont
from PIL import Image
# ── PyQt5 ──────────────────────────────────────────────────────────────────
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QTabWidget, QFrame, QSplitter,
QVBoxLayout, QHBoxLayout, QGridLayout, QFormLayout,
QLabel, QPushButton, QLineEdit, QTextEdit, QPlainTextEdit,
QComboBox, QCheckBox, QRadioButton, QButtonGroup,
QTreeWidget, QTreeWidgetItem, QHeaderView,
QTableWidget, QTableWidgetItem, QAbstractItemView,
QProgressBar, QScrollArea, QGroupBox,
QMenu, QAction, QMessageBox, QFileDialog, QDialog,
QStatusBar, QSizePolicy, QDoubleSpinBox, QSpinBox,
QStyleFactory
)
from PyQt5.QtGui import (
QFont, QColor, QPixmap, QIcon, QPalette, QImage,
QStandardItemModel, QStandardItem
)
from PyQt5.QtCore import (
Qt, QThread, pyqtSignal, QTimer, QSize, QMimeData, QModelIndex
)
# ── 全局常量 ────────────────────────────────────────────────────────────────
CONFIG_FILE = "pdps_master_config_v13.xlsx"
REG_PATH = r"Software\TECNOMATIX\TUNE\NewAssembler\Options\EMS"
# ── pycatia 可选导入 ────────────────────────────────────────────────────────
try:
from pycatia import catia as pycatia_catia
from pycatia.mec_mod_interfaces.part_document import PartDocument
PYCATIA_AVAILABLE = True
except Exception:
PYCATIA_AVAILABLE = False
# ============================================================================
# 业务逻辑类(直接从原文件保留,不做任何修改)
# ============================================================================
# ── CATIAWeldPointExtractor ──────────────────────────────────────────────────
class CATIAWeldPointExtractor:
"""CATIA 焊点提取工具类(兼容 win32com 和 pycatia)"""
def __init__(self, catia_app=None):
self.catia_app = catia_app
self.weld_points_data: List[Dict] = []
self.status_message = "就绪"
self.connection_type = None
def connect_catia(self, use_pycatia=False) -> bool:
try:
if use_pycatia:
if not PYCATIA_AVAILABLE:
return False
self.catia_app = pycatia_catia()
self.connection_type = 'pycatia'
self.status_message = "已连接 | CATIA (pycatia)"
return True
else:
import win32com.client
try:
self.catia_app = win32com.client.GetActiveObject("CATIA.Application")
except Exception:
self.catia_app = win32com.client.Dispatch("CATIA.Application")
self.connection_type = 'win32com'
self.status_message = "已连接 | CATIA (win32com)"
return True
except Exception as e:
self.status_message = "连接 CATIA 失败"
return False
def set_catia_app(self, catia_app, connection_type='win32com'):
self.catia_app = catia_app
self.connection_type = connection_type
self.status_message = f"CATIA 应用已设置 ({connection_type})"
def get_status(self):
return self.status_message
def extract_weld_points(self, auto_rename: bool = False) -> List[Dict]:
if not self.catia_app:
self.status_message = "请先连接 CATIA"
return []
self.weld_points_data = []
try:
if self.connection_type == 'pycatia':
doc = self.catia_app.active_document
if not doc or not hasattr(doc, 'part'):
self.status_message = "当前文档不是 Part 文档"
return []
part = doc.part
selection = doc.selection
part_full_name = doc.name
else:
doc = self.catia_app.ActiveDocument
if not doc:
return []
try:
part = doc.Part
except:
self.status_message = "当前文档不是 Part 文档"
return []
selection = doc.Selection
part_full_name = doc.Name
spa_workbench = None
try:
if self.connection_type == 'pycatia':
spa_workbench = doc.spa_workbench()
else:
spa_workbench = doc.GetWorkbench("SPAWorkbench")
except:
pass
if self.connection_type == 'pycatia':
selection.clear()
selection.search("CATGmoSearch.Point,all")
count = selection.count
else:
selection.Clear()
selection.Search("CATGmoSearch.Point,all")
count = selection.Count
# ── 预扫描:构建 {点名称 → 直接父图形集名称} 映射表 ────────────
# 比逐点调用 .Parent 更可靠,避免 win32com/pycatia 的 Parent 属性失效问题
point_parent_map = self._build_point_parent_map(part)
for i in range(1, count + 1):
try:
if self.connection_type == 'pycatia':
item = selection.item(i)
point_obj = item.value
name = getattr(point_obj, 'name', f"Point_{i}")
else:
item = selection.Item(i)
point_obj = item.Value
name = getattr(point_obj, 'Name', f"Point_{i}")
# ── 从映射表获取父图形集名 ──────────────────────────────
# 优先用精确名查询,再去掉 GSMPoint 后缀的基本名匹配
geo_set_name = point_parent_map.get(name, "")
if not geo_set_name:
# 点名可能含 ".N" 后缀,尝试去掉后缀再匹配
base_name = re.sub(r'\.GSMPoint\.\d+$', '', name, flags=re.IGNORECASE)
base_name = re.sub(r'-GSMPoint\.\d+$', '', base_name, flags=re.IGNORECASE)
geo_set_name = point_parent_map.get(base_name, "")
# ── 获取坐标 ────────────────────────────────────────────
x, y, z = 0, 0, 0
try:
if spa_workbench:
if self.connection_type == 'pycatia':
ref = part.create_reference_from_object(point_obj)
m = spa_workbench.get_measurable(ref)
coords = m.get_point()
else:
ref = part.CreateReferenceFromObject(point_obj)
m = spa_workbench.GetMeasurable(ref)
coords = [0, 0, 0]
m.GetPoint(coords)
x, y, z = coords[0], coords[1], coords[2]
except:
pass
# ── 自动重命名 ───────────────────────────────────────────
# geo_set_name 即为图形集名(如 DPUB-501000588-XAX&DPUB-501000592-XAX&...)
# 直接用它提取零件号,无需再向上遍历父节点
std_name = name
if auto_rename:
std_name = self._generate_standard_name(name, geo_set_name)
# ── 根据图形集名称中 & 数量推断焊接层数类型 ────────────
weld_type = self._weld_type_from_location(geo_set_name)
location_str = f"{x:.3f},{y:.3f},{z:.3f}"
self.weld_points_data.append({
"Class": "PmWeldPoint",
"ExternalId": std_name,
"Name": std_name,
"Location": location_str,
"X": round(x, 3),
"Y": round(y, 3),
"Z": round(z, 3),
"Type": weld_type
})
except:
pass
self.status_message = f"已提取 {len(self.weld_points_data)} 个焊点"
except Exception as e:
self.status_message = f"提取失败: {e}"
return self.weld_points_data
def _generate_standard_name(self, original_name: str, geo_set_name: str) -> str:
"""
生成标准命名:{前缀}_{零件数字段}_{焊点数字段}
焊点名示例: T1E-0000010296-RSW-GSMPoint.2
→ 前缀 = T1E,焊点 ID = 10296
图形集名示例:DPUB-501000588-XAX&DPUB-501000592-XAX&DPUB-501001638-XAX
→ 取第一段 DPUB-501000588-XAX,零件 ID = 501000588(首个纯数字段)
结果示例:T1E_501000588_10296
"""
try:
# ── 1. 提取前缀(焊点名第一个"-"之前)──────────────────────────
orig_segs = original_name.split('-')
prefix = orig_segs[0].strip() if orig_segs else "UNK"
# ── 2. 提取零件 ID(从图形集名第一个 & 段中找首个纯数字段)──────
part_id = ""
if geo_set_name:
# 取 & 之前的第一个零件名段,如 "DPUB-501000588-XAX"
first_part_seg = geo_set_name.split('&')[0].strip()
for seg in first_part_seg.split('-'):
seg_clean = seg.split('_')[0] # 去掉下划线后缀,如 "XWS_00" → "XWS"
if seg_clean.isdigit():
part_id = seg_clean
break
if not part_id:
# 降级:取第二段(不要求纯数字)
p_segs = first_part_seg.split('-')
part_id = p_segs[1].split('_')[0] if len(p_segs) > 1 else p_segs[0]
if not part_id:
part_id = re.sub(r'[^A-Za-z0-9]', '', geo_set_name)[:12] or "PART"
# ── 3. 提取焊点数字(第二段去前导零)──────────────────────────
weld_id = "0"
if len(orig_segs) > 1:
raw = orig_segs[1].strip()
weld_id = raw.lstrip('0') or "0"
return f"{prefix}_{part_id}_{weld_id}"
except Exception:
return original_name
@staticmethod
def _weld_type_from_location(location_name: str) -> str:
"""
根据图形集名称中 '&' 的数量推断焊接层数类型:
无 & 或 1 个 & → 双层板 → "2T"
2 个 & → 三层板 → "3T"
N 个 & → (N+1) 层板 → "{N+1}T"
规则:N 个 & 连接 (N+1) 个零件,即 (N+1) 层板。
无 & 时认为只有1个零件段,默认双层板(实际为单零件贴合场景取2T)。
"""
count = location_name.count('&')
layers = max(2, count + 1) # 0 个 & → 1 个零件 → 默认 2T; 2 个 & → 3 个零件 → 3T
return f"{layers}T"
def _build_point_parent_map(self, part) -> Dict[str, str]:
"""
预扫描零件的全部 HybridBodies(图形集)层级,
构建 {点名称: 直接父图形集名称} 映射表。
支持 win32com 和 pycatia 两种连接方式。
"""
point_parent_map: Dict[str, str] = {}
def _scan_body(hb, conn_type: str):
"""递归扫描一个 HybridBody 内的所有点和子图形集。"""
try:
if conn_type == 'pycatia':
hb_name = hb.name
shapes = hb.hybrid_shapes
shape_count = shapes.count
sub_bodies = hb.hybrid_bodies
sub_count = sub_bodies.count
def get_shape(j): return shapes.item(j)
def get_shape_name(s): return s.name
def get_sub(j): return sub_bodies.item(j)
else:
hb_name = hb.Name
shapes = hb.HybridShapes
shape_count = shapes.Count
sub_bodies = hb.HybridBodies
sub_count = sub_bodies.Count
def get_shape(j): return shapes.Item(j)
def get_shape_name(s): return s.Name
def get_sub(j): return sub_bodies.Item(j)
# 登记本 HybridBody 内直属的所有形状
for j in range(1, shape_count + 1):
try:
shape = get_shape(j)
sname = get_shape_name(shape)
if sname:
point_parent_map[sname] = hb_name
except Exception:
pass
# 递归处理子图形集(但子图形集内的点归属子图形集,不覆盖父级)
for j in range(1, sub_count + 1):
try:
_scan_body(get_sub(j), conn_type)
except Exception:
pass
except Exception as e:
print(f"_scan_body error: {e}")
try:
if self.connection_type == 'pycatia':
root_bodies = part.hybrid_bodies
for i in range(1, root_bodies.count + 1):
_scan_body(root_bodies.item(i), 'pycatia')
else:
root_bodies = part.HybridBodies
for i in range(1, root_bodies.Count + 1):
_scan_body(root_bodies.Item(i), 'win32com')
except Exception as e:
print(f"_build_point_parent_map error: {e}")
return point_parent_map
# ---------------------------
# 生成球体(完整实现 - PyQt5版)
# ---------------------------
def generate_spheres_from_points(self, parent_qt=None):
"""
从焊点生成球体(win32com 版本为主)
parent_qt: 可选,传入 QWidget (如 QMainWindow) 用于设置父窗口及更新 status_label
"""
# 入口判断
weld_points_data = self.get_data() if hasattr(self, "get_data") else self.weld_points_data
if not weld_points_data:
QMessageBox.warning(parent_qt, "警告", "没有焊点数据可生成球体")
return
# 参数对话框
radius_str, ok = QInputDialog.getText(parent_qt, "球体半径", "请输入球体半径(mm):", QLineEdit.Normal, "10")
if not ok or not radius_str:
return
try:
radius = float(radius_str)
except ValueError:
QMessageBox.critical(parent_qt, "参数错误", "请输入有效的半径数值")
return
name_prefix, ok = QInputDialog.getText(parent_qt, "名称前缀", "球体名称前缀:", QLineEdit.Normal, "SPHERE")
if not ok:
return
name_prefix = name_prefix or "SPHERE"
geom_set_name, ok = QInputDialog.getText(parent_qt, "几何集名称", "几何集名称:", QLineEdit.Normal,
"Geometry_Spheres")
if not ok:
return
geom_set_name = geom_set_name or "Geometry_Spheres"
# 创建进度对话框
progress_dialog = QDialog(parent_qt)
progress_dialog.setWindowTitle("生成球体")
progress_dialog.resize(420, 160)
progress_dialog.setWindowModality(Qt.WindowModal) # 模态窗口,阻塞父窗口交互
layout = QVBoxLayout(progress_dialog)
# 标题 Label
title_lbl = QLabel(f"将生成 {len(weld_points_data)} 个球体")
title_lbl.setFont(QFont("Microsoft YaHei", 10))
layout.addWidget(title_lbl, alignment=Qt.AlignHCenter)
# 进度条
progress_bar = QProgressBar()
progress_bar.setRange(0, 100)
progress_bar.setValue(0)
layout.addWidget(progress_bar)
# 状态 Label
status_lbl = QLabel("准备中...")
status_lbl.setStyleSheet("color: gray;")
layout.addWidget(status_lbl, alignment=Qt.AlignHCenter)
# 取消按钮
cancel_btn = QPushButton("取消")
cancel_btn.setFixedSize(100, 30)
cancel_btn.setStyleSheet("background-color: #7f8c8d; color: white; border-radius: 4px;")
layout.addWidget(cancel_btn, alignment=Qt.AlignHCenter)
cancel_event = threading.Event()
progress_q = queue.Queue()
def worker():
"""在后台线程中执行 CATIA 操作"""
try:
import pythoncom
pythoncom.CoInitialize()
try:
import win32com.client
try:
catia = win32com.client.GetActiveObject("CATIA.Application")
except Exception:
catia = win32com.client.Dispatch("CATIA.Application")
# 获取文档与 Part
doc = getattr(catia, "ActiveDocument", None)
if doc is None:
progress_q.put(("error", "没有活动的 CATIA 文档"))
return
part = getattr(doc, "Part", None)
if part is None:
progress_q.put(("error", "当前文档不是 Part 类型"))
return
hsf = part.HybridShapeFactory
hybrid_bodies = part.HybridBodies
# 尝试切换工作台(可选)
try:
catia.StartWorkbench("PartDesign")
except:
pass
# 获取或创建几何集
target_body = None
try:
for i in range(1, hybrid_bodies.Count + 1):
body = hybrid_bodies.Item(i)
if body.Name == geom_set_name:
target_body = body
break
if target_body is None:
target_body = hybrid_bodies.Add()
target_body.Name = geom_set_name
except Exception as e:
progress_q.put(("error", f"无法获取或创建几何集: {str(e)}"))
return
# 尝试设置 InWorkObject
try:
part.InWorkObject = target_body
except:
pass
total = len(weld_points_data)
created_points = []
# 1) 批量创建点并 append 到几何集(不频繁 Update)
for idx, weld in enumerate(weld_points_data):
if cancel_event.is_set():
progress_q.put(("info", f"已取消,已创建 {len(created_points)} 个点"))
return
try:
x = float(weld.get("X", 0))
y = float(weld.get("Y", 0))
z = float(weld.get("Z", 0))
except Exception:
progress_q.put(("warn", f"第 {idx + 1} 个坐标解析失败,跳过"))
continue
try:
pt = hsf.AddNewPointCoord(x, y, z)
if pt is None:
progress_q.put(("warn", f"第 {idx + 1} 个点创建失败"))
continue
target_body.AppendHybridShape(pt)
created_points.append(pt)
except Exception as e:
progress_q.put(("warn", f"第 {idx + 1} 个点创建异常: {str(e)}"))
continue
# 每创建 10 个点更新一次进度
if (idx + 1) % 10 == 0 or (idx + 1) == total:
progress_q.put(("progress", (idx + 1, total)))
# 一次性 Update 以生成引用
try:
part.Update()
except:
pass
# 2) 为每个点创建球体
success = 0
fail = 0
created_count = len(created_points)
for i, pt in enumerate(created_points):
if cancel_event.is_set():
progress_q.put(("info", f"已取消,已创建 {success} 个球体"))
return
try:
pt_ref = part.CreateReferenceFromObject(pt)
try:
sphere = hsf.AddNewSphere(pt_ref, None, radius, -90.0, 90.0, 0.0, 360.0)
except Exception:
sphere = hsf.AddNewSphere(pt_ref, None, radius)
if sphere is None:
fail += 1
continue
try:
target_body.AppendHybridShape(sphere)
except:
pass
try:
sphere.Name = f"{name_prefix}_{i + 1}"
except:
pass
success += 1
# 每 10 个刷新一次窗口
if i % 10 == 0:
try:
doc.Windows.Item(1).Refresh()
except:
pass
progress_q.put(("progress", (created_count + i + 1, created_count * 2)))
except Exception:
fail += 1
continue
# 最终 Update
try:
part.Update()
doc.Windows.Item(1).Refresh()
except:
pass
progress_q.put(("done", (success, fail)))
finally:
pythoncom.CoUninitialize()
except Exception:
progress_q.put(("error", traceback.format_exc()))
# 启动后台线程
t = threading.Thread(target=worker, daemon=True)
t.start()
# 声明 QTimer 用于主线程轮询队列更新UI
poll_timer = QTimer()
def poll():
try:
while not progress_q.empty():
typ, val = progress_q.get_nowait()
if typ == "progress":
cur, tot = val
pct = int(min(100.0, (cur / max(1, tot)) * 100.0))
progress_bar.setValue(pct)
status_lbl.setText(f"处理中: {cur}/{tot}")
if parent_qt and hasattr(parent_qt, "status_label"):
parent_qt.status_label.setText(f"生成中: {cur}/{tot}")
elif typ == "warn":
print("WARN:", val)
elif typ == "info":
QMessageBox.information(progress_dialog, "信息", val)
if parent_qt and hasattr(parent_qt, "status_label"):
parent_qt.status_label.setText(val)
progress_dialog.accept() # 关闭窗口
elif typ == "error":
QMessageBox.critical(progress_dialog, "生成球体失败", val)
status_lbl.setText("生成失败")
if parent_qt and hasattr(parent_qt, "status_label"):
parent_qt.status_label.setText("生成失败")
progress_dialog.accept()
elif typ == "done":
success, fail = val
QMessageBox.information(progress_dialog, "完成", f"已生成 {success} 个球体,失败 {fail} 个")
status_lbl.setText(f"完成: 成功 {success},失败 {fail}")
if parent_qt and hasattr(parent_qt, "status_label"):
parent_qt.status_label.setText(f"完成: 成功 {success},失败 {fail}")
progress_dialog.accept()
except Exception:
pass
# 如果线程已经结束,停止定时器
if not t.is_alive():
poll_timer.stop()
def on_cancel():
reply = QMessageBox.question(progress_dialog, "取消", "确定要取消生成吗?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
cancel_event.set()
status_lbl.setText("正在取消...")
cancel_btn.setEnabled(False) # 防重复点击
cancel_btn.clicked.connect(on_cancel)
# 启动轮询并阻塞显示对话框
poll_timer.timeout.connect(poll)
poll_timer.start(200)
progress_dialog.exec_()
def log_error(self, context, error):
print(f"Error in {context}: {error}")
traceback.print_exc()
self.status_message = f"错误: {context}"
# ── CATIASphereScanner ──────────────────────────────────────────────────────
class CATIASphereScanner:
def __init__(self, catia_app=None):
self.catia_app = catia_app
self.sphere_data = []
def set_catia_app(self, catia_app):
self.catia_app = catia_app
def scan_selected_objects(self) -> List[Dict]:
if not self.catia_app:
raise Exception("CATIA 未连接")
try:
document = self.catia_app.active_document
part_doc = PartDocument(document.com_object)
part = part_doc.part
selection = document.selection
spa_workbench = part_doc.spa_workbench()
count = selection.count
if count == 0:
return []
self.sphere_data = []
for i in range(1, count + 1):
try:
selected_obj = selection.item(i).value
obj_name = getattr(selected_obj, 'name', f"Object_{i}")
reference = part.create_reference_from_object(selected_obj)
measurable = spa_workbench.get_measurable(reference)
cog = measurable.get_cog()
try:
volume = measurable.volume
except:
volume = 0
radius = (volume * 3 / (4 * 3.14159265359)) ** (1 / 3) if volume > 0 else 0
self.sphere_data.append({
"Name": obj_name,
"X": f"{cog[0]:.2f}",
"Y": f"{cog[1]:.2f}",
"Z": f"{cog[2]:.2f}",
"Radius": f"{radius:.2f}",
"Volume": round(volume, 3),
"Type": "实体" if volume > 0 else "几何图形",
"_coords": cog
})
except Exception as e:
print(f"无法测量对象 {i}: {e}")
return self.sphere_data
except Exception as e:
traceback.print_exc()
return []
def scan_all_bodies(self, search_keywords=None):
if not self.catia_app:
raise Exception("CATIA 未连接")
try:
document = self.catia_app.active_document
part_doc = PartDocument(document.com_object)
part = part_doc.part
spa_workbench = part_doc.spa_workbench()
self.sphere_data = []
bodies = part.bodies
for i in range(1, bodies.count + 1):
body = bodies.item(i)
if search_keywords:
if not any(kw.lower() in body.name.lower() for kw in search_keywords):
continue
try:
reference = part.create_reference_from_object(body)
measurable = spa_workbench.get_measurable(reference)
cog = measurable.get_cog()
volume = measurable.volume
self.sphere_data.append({
"Name": body.name,
"X": f"{cog[0]:.2f}",
"Y": f"{cog[1]:.2f}",
"Z": f"{cog[2]:.2f}",
"Radius": f"{(volume * 3 / (4 * 3.14)) ** (1 / 3):.2f}" if volume > 0 else "0",
"Volume": round(volume, 3),
"Type": "Body",
"_coords": cog
})
except:
continue
return self.sphere_data
except Exception as e:
traceback.print_exc()
return []
def generate_points_at_centers(self, geometrical_set_name="Geometry_COG_Points") -> int:
if not self.sphere_data:
return 0
try:
part_doc = PartDocument(self.catia_app.active_document.com_object)
part = part_doc.part
hs_factory = part.hybrid_shape_factory
hybrid_bodies = part.hybrid_bodies
try:
target_hb = hybrid_bodies.item(geometrical_set_name)
except:
target_hb = hybrid_bodies.add()
target_hb.name = geometrical_set_name
for data in self.sphere_data:
x, y, z = data["_coords"]
new_point = hs_factory.add_new_point_coord(x, y, z)
new_point.name = f"COG_{data['Name']}"
target_hb.append_hybrid_shape(new_point)
part.update()
return len(self.sphere_data)
except Exception as e:
print(f"生成点失败: {e}")
return 0
def get_data(self):
return self.sphere_data
# ── CatiaGunPlacer ──────────────────────────────────────────────────────────
class CatiaGunPlacer:
def __init__(self, catia_app=None):
self.catia_app = catia_app
self.connection_type = None
self.status_message = "就绪"
self.gun_template_path = ""
self.rotation_order = 'kuka'
def set_rotation_order(self, order: str):
valid_orders = ['kuka', 'catia_zyx', 'catia_xyz']
if order in valid_orders:
self.rotation_order = order
def set_catia_app(self, catia_app, connection_type='win32com'):
self.catia_app = catia_app
self.connection_type = connection_type
self.status_message = f"CATIA 已连接 ({connection_type})"
def is_catia_connected(self) -> bool:
if not self.catia_app:
return False
try:
if self.connection_type == 'pycatia':
_ = self.catia_app.documents.count
else:
_ = self.catia_app.Documents.Count
return True
except:
return False
def has_active_product(self) -> bool:
if not self.is_catia_connected():
return False
try:
if self.connection_type == 'pycatia':
doc = self.catia_app.active_document
return hasattr(doc, 'product')
else:
doc = self.catia_app.ActiveDocument
try:
_ = doc.Product
return True
except:
return False
except:
return False
def euler_to_rotation_matrix(self, rx, ry, rz, order=None):
if order is None:
order = self.rotation_order
rx_r, ry_r, rz_r = math.radians(rx), math.radians(ry), math.radians(rz)
Rx = np.array([[1,0,0],[0,math.cos(rx_r),-math.sin(rx_r)],[0,math.sin(rx_r),math.cos(rx_r)]])
Ry = np.array([[math.cos(ry_r),0,math.sin(ry_r)],[0,1,0],[-math.sin(ry_r),0,math.cos(ry_r)]])
Rz = np.array([[math.cos(rz_r),-math.sin(rz_r),0],[math.sin(rz_r),math.cos(rz_r),0],[0,0,1]])
if order in ('kuka', 'catia_zyx'):
return Rz @ Ry @ Rx
else:
return Rx @ Ry @ Rz
def euler_to_catia_components(self, x, y, z, rx, ry, rz):
R = self.euler_to_rotation_matrix(rx, ry, rz)
return [R[0,0],R[1,0],R[2,0], R[0,1],R[1,1],R[2,1], R[0,2],R[1,2],R[2,2], x, y, z]
def pose_to_matrix(self, x, y, z, rx, ry, rz, order=None):
"""
辅助方法:将 6D 位姿(XYZ + 欧拉角)转换为 4x4 齐次变换矩阵
"""
R = self.euler_to_rotation_matrix(rx, ry, rz, order)
M = np.eye(4)
M[:3, :3] = R
M[0, 3] = x
M[1, 3] = y
M[2, 3] = z
return M
def get_kuka_correction_matrix(self, kuka_data):
"""
[新增方法] 将库卡控制柜 TCP (X, Y, Z, A, B, C) 映射为 CATIA 修正矩阵
"""
try:
kx = float(kuka_data.get('X', 0))
ky = float(kuka_data.get('Y', 0))
kz = float(kuka_data.get('Z', 0))
ka = float(kuka_data.get('A', 0))
kb = float(kuka_data.get('B', 0))
kc = float(kuka_data.get('C', 0))
# 根据实测数据的映射规律 (补偿模板的建模朝向)
cx = -kz
cy = -ky
cz = kx
crx = kc
cry = -kb
crz = ka
return self.pose_to_matrix(cx, cy, cz, crx, cry, crz)
except Exception as e:
print(f"TCP 转换失败: {e}")
return np.eye(4)
def place_guns_batch(self, gun_template, gun_data, progress_callback=None,
correction_values=None, rotation_order=None, kuka_tcp_input=None):
"""
[完全替换原方法] 批量放置焊枪,支持库卡 TCP 矩阵变换与普通坐标偏移
"""
if not self.is_catia_connected():
return 0, 0, ["✗ CATIA 未连接"]
if not self.has_active_product():
return 0, 0, ["✗ 请先打开一个 Product 文档"]
if rotation_order:
self.set_rotation_order(rotation_order)
gun_template_normalized = os.path.normpath(gun_template).replace('/', '\\')
success_count, failed_count = 0, 0
status_list = []
# 1. 预计算修正矩阵
import numpy as np
M_corr = np.eye(4)
if kuka_tcp_input:
# 如果是 TCP 模式,生成库卡修正矩阵
M_corr = self.get_kuka_correction_matrix(kuka_tcp_input)
try:
# 2. CATIA 环境与容器准备
if self.connection_type == 'pycatia':
doc = self.catia_app.active_document
product = doc.product
com_products = product.products.com_object
else:
doc = self.catia_app.ActiveDocument
product = doc.Product
com_products = product.Products
from datetime import datetime as dt
container_name = f"{product.Name if hasattr(product, 'Name') else 'Product'}-GUN-{dt.now().strftime('%Y%m%d_%H%M%S')}"
try:
container = com_products.AddNewComponent("Product", container_name)
container_products = container.Products
except Exception as e:
print(f"创建容器失败: {e},将直接在根节点下插入")
container_products = com_products
# 3. 循环插入焊枪并应用变换
total = len(gun_data)
for idx, gun in enumerate(gun_data):
try:
# 获取当前焊枪的原始位姿
x = float(gun.get('X', 0))
y = float(gun.get('Y', 0))
z = float(gun.get('Z', 0))
rx = float(gun.get('Rx', 0))
ry = float(gun.get('Ry', 0))
rz = float(gun.get('Rz', 0))
# 如果没有勾选 TCP 且存在普通偏移,直接加到基础坐标上
if correction_values and not kuka_tcp_input:
x += float(correction_values.get('X', 0))
y += float(correction_values.get('Y', 0))
z += float(correction_values.get('Z', 0))
rx += float(correction_values.get('Rx', 0))
ry += float(correction_values.get('Ry', 0))
rz += float(correction_values.get('Rz', 0))
# 基础位姿矩阵
M_pose = self.pose_to_matrix(x, y, z, rx, ry, rz)
# 核心修正:矩阵乘法 M_final = M_pose * M_corr
M_final = M_pose @ M_corr
# 插入模型文件
file_array = (gun_template_normalized,)
container_products.AddComponentsFromFiles(file_array, "All")
import time
time.sleep(0.3)
# 获取刚刚插入的对象并重命名
count = container_products.Count
new_product = container_products.Item(count)
new_product.Name = gun.get('Name', f'Gun_{idx + 1}')
# 提取 CATIA 需要的 12 个分量
components = [
M_final[0, 0], M_final[1, 0], M_final[2, 0],
M_final[0, 1], M_final[1, 1], M_final[2, 1],
M_final[0, 2], M_final[1, 2], M_final[2, 2],
M_final[0, 3], M_final[1, 3], M_final[2, 3]
]
# 设置最终位姿
new_product.Position.SetComponents(components)
success_count += 1
status_list.append("✓ 成功")
if progress_callback:
progress_callback(idx + 1, total, f"插入: {new_product.Name}")
except Exception as e:
failed_count += 1
status_list.append(f"✗ {str(e)[:30]}")
print(f"插入第{idx + 1}个失败: {e}")
# 4. 更新文档
try:
if self.connection_type == 'pycatia':
doc.product.update()
else:
doc.Product.Update()
except:
pass
self.status_message = f"完成 | 成功: {success_count} | 失败: {failed_count}"
return success_count, failed_count, status_list
except Exception as e:
return success_count, failed_count, [f"✗ 致命错误: {str(e)}"]
# ============================================================================
# 样式助手
# ============================================================================
def _lighten(hex_color: str, factor: float = 1.18) -> str:
"""将 HEX 颜色调亮,用于 hover 状态。"""
h = hex_color.lstrip('#')
r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
return "#{:02x}{:02x}{:02x}".format(min(255, int(r*factor)),
min(255, int(g*factor)),
min(255, int(b*factor)))
def _darken(hex_color: str, factor: float = 0.78) -> str:
"""将 HEX 颜色调暗,用于 pressed 状态。"""
h = hex_color.lstrip('#')
r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
return "#{:02x}{:02x}{:02x}".format(int(r*factor), int(g*factor), int(b*factor))
def make_btn(text, color, callback=None, width=None, height=None):
"""创建带悬停/按下变色特效的按钮。"""
btn = QPushButton(text)
hov = _lighten(color) # 悬停时变亮
prs = _darken(color) # 按下时变暗
btn.setStyleSheet(
f"QPushButton {{"
f" background-color: {color}; color: white;"
f" border: none; border-radius: 4px;"
f" padding: 5px 12px; font-size: 13px;"
f"}}"
f"QPushButton:hover {{"
f" background-color: {hov};"
f" border-bottom: 2px solid {prs};"
f"}}"
f"QPushButton:pressed {{"
f" background-color: {prs};"