VisionDynamicAccuracyAnalyzerViewModel.cs 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  1. using Cognex.VisionPro;
  2. using Cognex.VisionPro.ToolBlock;
  3. using MaterialDesignThemes.Wpf;
  4. using OxyPlot;
  5. using Prism.Commands;
  6. using Prism.Events;
  7. using Prism.Ioc;
  8. using Prism.Mvvm;
  9. using Prism.Regions;
  10. using Prism.Services.Dialogs;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Collections.ObjectModel;
  14. using System.Data;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using Team.FFFeederService.Interfaces;
  20. using TeamAAS_VP.Core;
  21. using TeamAAS_VP.Enums;
  22. using TeamAAS_VP.Interfaces;
  23. using TeamAAS_VP.Models;
  24. using TeamAAS_VP.Resources.Languages;
  25. using static TeamAAS_VP.Core.StabilityAnalyzer;
  26. namespace TeamAAS_VP.ViewModels.Product
  27. {
  28. public class VisionDynamicAccuracyAnalyzerViewModel : BindableBase, IDialogAware
  29. {
  30. IRegionManager _regionManager;
  31. IEventAggregator _eventAggregator;
  32. IContainerProvider _container;
  33. IDialogService _dialogService;
  34. IFeederService _feederService;
  35. IRobotService _robotService;
  36. ICameraService _cameraService;
  37. ISystemDatabaseService _systemDatabaseService;
  38. ICalibrationService _calibrationService;
  39. //测试过程中控制取消的CTS
  40. CancellationTokenSource _cts;
  41. #region 属性
  42. private ProductModel _SelectProduct;
  43. public ProductModel SelectProduct
  44. {
  45. get { return _SelectProduct; }
  46. set { SetProperty(ref _SelectProduct, value); }
  47. }
  48. private ICogImage _Image;
  49. public ICogImage Image
  50. {
  51. get { return _Image; }
  52. set { SetProperty(ref _Image, value); }
  53. }
  54. private Cognex.VisionPro.CogGraphicCollection _Graphic;
  55. public Cognex.VisionPro.CogGraphicCollection Graphic
  56. {
  57. get { return _Graphic; }
  58. set { SetProperty(ref _Graphic, value); }
  59. }
  60. private ProcedureModel _SelectProcedure;
  61. /// <summary>
  62. /// 选中的流程
  63. /// </summary>
  64. public ProcedureModel SelectProcedure
  65. {
  66. get { return _SelectProcedure; }
  67. set
  68. {
  69. SetProperty(ref _SelectProcedure, value);
  70. }
  71. }
  72. private ICamera _Camera;
  73. public ICamera Camera
  74. {
  75. get { return _Camera; }
  76. set { SetProperty(ref _Camera, value); }
  77. }
  78. private IRobot _Robot;
  79. public IRobot Robot
  80. {
  81. get { return _Robot; }
  82. set { SetProperty(ref _Robot, value); }
  83. }
  84. private string _Message = "等待开始...";
  85. public string Message
  86. {
  87. get { return _Message; }
  88. set { SetProperty(ref _Message, value); }
  89. }
  90. private bool _IsRunning;
  91. public bool IsRunning
  92. {
  93. get { return _IsRunning; }
  94. set { SetProperty(ref _IsRunning, value); }
  95. }
  96. private CogToolBlock _VisionTool;
  97. public CogToolBlock VisionTool
  98. {
  99. get { return _VisionTool; }
  100. set { SetProperty(ref _VisionTool, value); }
  101. }
  102. private int _RepeatCount = 10;
  103. /// <summary>
  104. /// 重复次数
  105. /// </summary>
  106. public int RepeatCount
  107. {
  108. get { return _RepeatCount; }
  109. set { SetProperty(ref _RepeatCount, value); }
  110. }
  111. private int _CurrentProgress;
  112. /// <summary>
  113. /// 当前进度
  114. /// </summary>
  115. public int CurrentProgress
  116. {
  117. get { return _CurrentProgress; }
  118. set { SetProperty(ref _CurrentProgress, value); }
  119. }
  120. private int _SuccessCount;
  121. /// <summary>
  122. /// 成功次数
  123. /// </summary>
  124. public int SuccessCount
  125. {
  126. get { return _SuccessCount; }
  127. set { SetProperty(ref _SuccessCount, value); }
  128. }
  129. private int _FailCount;
  130. /// <summary>
  131. /// 失败次数
  132. /// </summary>
  133. public int FailCount
  134. {
  135. get { return _FailCount; }
  136. set { SetProperty(ref _FailCount, value); }
  137. }
  138. private double _SuccessRate;
  139. /// <summary>
  140. /// 成功率
  141. /// </summary>
  142. public double SuccessRate
  143. {
  144. get { return _SuccessRate; }
  145. set { SetProperty(ref _SuccessRate, value); }
  146. }
  147. private ObservableCollection<DynamicTestResult> _TestResults;
  148. /// <summary>
  149. /// 测试结果列表
  150. /// </summary>
  151. public ObservableCollection<DynamicTestResult> TestResults
  152. {
  153. get { return _TestResults; }
  154. set { SetProperty(ref _TestResults, value); }
  155. }
  156. private SnackbarMessageQueue _MessageQueue;
  157. public SnackbarMessageQueue MessageQueue
  158. {
  159. get { return _MessageQueue; }
  160. set { SetProperty(ref _MessageQueue, value); }
  161. }
  162. private RPoint _PointA;
  163. public RPoint PointA
  164. {
  165. get { return _PointA; }
  166. set { SetProperty(ref _PointA, value); }
  167. }
  168. private RPoint _PointB;
  169. public RPoint PointB
  170. {
  171. get { return _PointB; }
  172. set { SetProperty(ref _PointB, value); }
  173. }
  174. private ObservableCollection<ProcedureModel> _ProcedureModels;
  175. /// <summary>
  176. /// 流程集合
  177. /// </summary>
  178. public ObservableCollection<ProcedureModel> ProcedureModels
  179. {
  180. get { return _ProcedureModels; }
  181. set { SetProperty(ref _ProcedureModels, value); }
  182. }
  183. private int _MoveSpeed;
  184. /// <summary>
  185. /// 移动速度
  186. /// </summary>
  187. public int MoveSpeed
  188. {
  189. get { return _MoveSpeed; }
  190. set { SetProperty(ref _MoveSpeed, value); }
  191. }
  192. private double _CycleTime;
  193. /// <summary>
  194. /// 单次的时长
  195. /// </summary>
  196. public double CycleTime
  197. {
  198. get { return _CycleTime; }
  199. set { SetProperty(ref _CycleTime, value); }
  200. }
  201. private PrecisionAnalysisResult _precisionResult = new PrecisionAnalysisResult();
  202. /// <summary>
  203. /// 精度分析结果
  204. /// </summary>
  205. public PrecisionAnalysisResult PrecisionResult
  206. {
  207. get { return _precisionResult; }
  208. set { SetProperty(ref _precisionResult, value); }
  209. }
  210. #endregion
  211. #region 命令
  212. private DelegateCommand _ConfirmCommand;
  213. public DelegateCommand ConfirmCommand =>
  214. _ConfirmCommand ?? (_ConfirmCommand = new DelegateCommand(ExecuteConfirmCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
  215. private DelegateCommand _CancelCommand;
  216. public DelegateCommand CancelCommand =>
  217. _CancelCommand ?? (_CancelCommand = new DelegateCommand(ExecuteCancelCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
  218. private DelegateCommand _StartTestCommand;
  219. public DelegateCommand StartTestCommand =>
  220. _StartTestCommand ?? (_StartTestCommand = new DelegateCommand(ExecuteStartTestCommand, CanExecuteStartTestCommand).ObservesProperty(() => IsRunning).ObservesProperty(() => SelectProcedure).ObservesProperty(() => PointA).ObservesProperty(() => PointB));
  221. private DelegateCommand _StopTestCommand;
  222. public DelegateCommand StopTestCommand =>
  223. _StopTestCommand ?? (_StopTestCommand = new DelegateCommand(() => { _cts?.Cancel(); }, () => IsRunning).ObservesProperty(() => IsRunning));
  224. //暂停测试命令
  225. private DelegateCommand _PauseTestCommand;
  226. public DelegateCommand PauseTestCommand =>
  227. _PauseTestCommand ?? (_PauseTestCommand = new DelegateCommand(() => { _cts?.Cancel(); }, () => IsRunning).ObservesProperty(() => IsRunning));
  228. private DelegateCommand _ExportCSVCommand;
  229. public DelegateCommand ExportCSVCommand =>
  230. _ExportCSVCommand ?? (_ExportCSVCommand = new DelegateCommand(ExecuteExportCSVCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
  231. private DelegateCommand _ExportReportCommand;
  232. public DelegateCommand ExportReportCommand =>
  233. _ExportReportCommand ?? (_ExportReportCommand = new DelegateCommand(ExecuteExportReportCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
  234. private DelegateCommand _ClearDataCommand;
  235. public DelegateCommand ClearDataCommand =>
  236. _ClearDataCommand ?? (_ClearDataCommand = new DelegateCommand(ExecuteClearDataCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
  237. private DelegateCommand _TeachPointACommand;
  238. public DelegateCommand TeachPointACommand =>
  239. _TeachPointACommand ?? (_TeachPointACommand = new DelegateCommand(ExecuteTeachPointACommand, () => !IsRunning).ObservesProperty(() => IsRunning));
  240. private DelegateCommand _TeachPointBCommand;
  241. public DelegateCommand TeachPointBCommand =>
  242. _TeachPointBCommand ?? (_TeachPointBCommand = new DelegateCommand(ExecuteTeachPointBCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
  243. private DelegateCommand _ProcedureSelectionChangedCommand;
  244. public DelegateCommand ProcedureSelectionChangedCommand =>
  245. _ProcedureSelectionChangedCommand ?? (_ProcedureSelectionChangedCommand = new DelegateCommand(ExecuteProcedureSelectionChangedCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
  246. private DelegateCommand _SingleTestCommand;
  247. public DelegateCommand SingleTestCommand =>
  248. _SingleTestCommand ?? (_SingleTestCommand = new DelegateCommand(ExecuteSingleTestCommand, () => !IsRunning && SelectProcedure != null && PointA != null && PointB != null).ObservesProperty(() => IsRunning).ObservesProperty(() => SelectProcedure).ObservesProperty(() => PointA).ObservesProperty(() => PointB));
  249. private DelegateCommand _ShowTrendChartCommand;
  250. public DelegateCommand ShowTrendChartCommand =>
  251. _ShowTrendChartCommand ?? (_ShowTrendChartCommand = new DelegateCommand(ExecuteShowTrendChartCommand));
  252. #endregion
  253. #region 事件
  254. #endregion
  255. public VisionDynamicAccuracyAnalyzerViewModel(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IDialogService dialogService,
  256. IFeederService feederService, IRobotService robotService, ICameraService cameraService, ISystemDatabaseService systemDatabaseService, ICalibrationService calibrationService)
  257. {
  258. _regionManager = regionManager;
  259. _eventAggregator = ea;
  260. _container = container;
  261. _dialogService = dialogService;
  262. _feederService = feederService;
  263. _robotService = robotService;
  264. _cameraService = cameraService;
  265. _systemDatabaseService = systemDatabaseService;
  266. MessageQueue = new SnackbarMessageQueue(TimeSpan.FromSeconds(1));
  267. _calibrationService = calibrationService;
  268. }
  269. #region 方法
  270. /// <summary>
  271. /// 确定
  272. /// </summary>
  273. void ExecuteConfirmCommand()
  274. {
  275. _cts?.Cancel();
  276. IDialogParameters parameters = new DialogParameters();
  277. //parameters.Add("Tool", Tool);
  278. //parameters.Add("RobotCameraRotationMatrix", RobotCameraRotationMatrix);
  279. //parameters.Add("Angle", Angle);
  280. RequestClose?.Invoke(new DialogResult(ButtonResult.OK, parameters));
  281. }
  282. /// <summary>
  283. /// 取消
  284. /// </summary>
  285. void ExecuteCancelCommand()
  286. {
  287. _cts?.Cancel();
  288. IDialogParameters parameters = new DialogParameters();
  289. //parameters.Add("Tool", Tool);
  290. RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel, parameters));
  291. }
  292. /// <summary>
  293. /// 单次测试
  294. /// </summary>
  295. async void ExecuteSingleTestCommand()
  296. {
  297. if (Robot == null || !Robot.IsConnected)
  298. {
  299. SendTaskMessage("机器人未连接,无法示教!");
  300. return;
  301. }
  302. if (Camera == null || !Camera.IsConnected)
  303. {
  304. SendTaskMessage("相机未连接,无法示教!");
  305. return;
  306. }
  307. //弹窗提示是否进行单次测试
  308. var result = System.Windows.MessageBox.Show("确定进行单次测试吗?", "提示", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question);
  309. if (result != System.Windows.MessageBoxResult.Yes)
  310. {
  311. return;
  312. }
  313. IsRunning = true;
  314. try
  315. {
  316. DateTime startTime = DateTime.Now;
  317. //为机器人设置移动速度
  318. await Robot.SpeedAsync(MoveSpeed);
  319. //移动机器人至A点
  320. bool isSuccess1 = await Robot.CalibMotionAsync(PointA, null);
  321. if (!isSuccess1)
  322. {
  323. SendTaskMessage("机器人移动到A点失败!");
  324. return;
  325. }
  326. await Task.Delay(200);
  327. //移动机器人至B点
  328. isSuccess1 = await Robot.CalibMotionAsync(PointB, null);
  329. if (!isSuccess1)
  330. {
  331. SendTaskMessage("机器人移动到B点失败!");
  332. return;
  333. }
  334. await Task.Delay(300);
  335. //相机拍照并处理
  336. (bool isSuccess, double pixelX, double pixelY, double angleU, double transformX, double transformY) = await ExecutePhotoEx(CurrentProgress);
  337. CycleTime = DateTime.Now.Subtract(startTime).TotalSeconds;
  338. }
  339. catch (Exception ex)
  340. {
  341. LogHelper.WriteLogError("机器人移动到A点失败!", ex);
  342. SendTaskMessage("机器人移动到A点失败!");
  343. }
  344. finally
  345. {
  346. IsRunning = false;
  347. }
  348. }
  349. /// <summary>
  350. /// 连续测试
  351. /// </summary>
  352. async void ExecuteStartTestCommand()
  353. {
  354. IsRunning = true;
  355. _cts = new CancellationTokenSource();
  356. CurrentProgress = 0;
  357. SuccessCount = 0;
  358. SuccessRate = 0;
  359. FailCount = 0;
  360. Message = "测试进行中...";
  361. TestResults = new ObservableCollection<DynamicTestResult>();
  362. try
  363. {
  364. //弹窗提示是否进行连续测试
  365. var result = System.Windows.MessageBox.Show("确定进行连续测试吗?", "提示", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question);
  366. if (result != System.Windows.MessageBoxResult.Yes)
  367. {
  368. return;
  369. }
  370. //为机器人设置移动速度
  371. await Robot.SpeedAsync(MoveSpeed);
  372. while (CurrentProgress < RepeatCount)
  373. {
  374. if (_cts.Token.IsCancellationRequested)
  375. {
  376. Message = "测试已取消!";
  377. break;
  378. }
  379. DateTime startTime = DateTime.Now;
  380. //移动机器人至A点
  381. bool isSuccess1 = await Robot.CalibMotionAsync(PointA, null);
  382. if (!isSuccess1)
  383. {
  384. SendTaskMessage("机器人移动到A点失败!");
  385. return;
  386. }
  387. await Task.Delay(200);
  388. if (_cts.Token.IsCancellationRequested)
  389. {
  390. Message = "测试已取消!";
  391. break;
  392. }
  393. //移动机器人至B点
  394. isSuccess1 = await Robot.CalibMotionAsync(PointB, null);
  395. if (!isSuccess1)
  396. {
  397. SendTaskMessage("机器人移动到B点失败!");
  398. return;
  399. }
  400. await Task.Delay(300);
  401. if (_cts.Token.IsCancellationRequested)
  402. {
  403. Message = "测试已取消!";
  404. break;
  405. }
  406. //相机拍照并处理
  407. (bool isSuccess, double pixelX, double pixelY, double angleU, double transformX, double transformY) = await ExecutePhotoEx(CurrentProgress);
  408. CycleTime = DateTime.Now.Subtract(startTime).TotalSeconds;
  409. if (isSuccess)
  410. {
  411. SuccessCount++;
  412. }
  413. else
  414. {
  415. FailCount++;
  416. }
  417. TestResults.Add(new DynamicTestResult(CurrentProgress,isSuccess,PointB,CycleTime,pixelX,pixelY,angleU,transformX,transformY));
  418. OnTestResultAdded();
  419. CurrentProgress++;
  420. SuccessRate = (double)SuccessCount / CurrentProgress * 100;
  421. SendTaskMessage($"测试进行中... {CurrentProgress}/{RepeatCount}");
  422. }
  423. if (CurrentProgress >= RepeatCount)
  424. {
  425. Message = "测试完成!";
  426. }
  427. }
  428. catch (Exception ex)
  429. {
  430. LogHelper.WriteLogError("视觉静态重复测试时出错!", ex);
  431. }
  432. finally
  433. {
  434. IsRunning = false;
  435. }
  436. }
  437. bool CanExecuteStartTestCommand()
  438. {
  439. return !IsRunning && SelectProcedure != null && PointA != null && PointB != null;
  440. }
  441. /// <summary>
  442. /// 清除数据
  443. /// </summary>
  444. void ExecuteClearDataCommand()
  445. {
  446. if (TestResults != null)
  447. {
  448. TestResults.Clear();
  449. }
  450. }
  451. /// <summary>
  452. /// 导出测试报告
  453. /// 使用 iTextSharp 生成 PDF,包含:标题、测试摘要、数据表格、每列稳定性分析结果
  454. /// 详细伪代码:
  455. /// 1. 校验 TestResults 是否存在且有数据,若无则提示并返回。
  456. /// 2. 弹出保存对话框,获取 PDF 保存路径,若取消则返回。
  457. /// 3. 使用 iTextSharp 创建 Document 和 PdfWriter,打开文档流。
  458. /// 4. 尝试从系统字体目录加载中文字体(多候选),若加载失败使用回退字体。
  459. /// 5. 写入标题(居中大号字体)和测试摘要信息(表格格式:导出时间、目标次数、当前进度、成功/失败次数、成功率)。
  460. /// 6. 创建一个 PdfPTable,列为固定的测试结果字段(Index, Timestamp, IsPhotoSuccess, PointB.X/Y/Z, CycleTime, PixelX, PixelY, AngleU, TransformX, TransformY)。
  461. /// - 写入表头(加粗)
  462. /// - 遍历 TestResults,每行按列顺序写入值(数值按 InvariantCulture 格式化,空值写空字符串)
  463. /// 7. 新页,写入“分析结果”标题。
  464. /// 8. 对于需要分析的维度(TransformX, TransformY, AngleU):
  465. /// - 从 TestResults 过滤出 IsPhotoSuccess 为 true 的样本并收集对应维度值(double)
  466. /// - 若样本数为0,写明无法计算;否则调用 StabilityAnalyzer.AnalyzeStability(values) 获取 StabilityMetrics
  467. /// - 将 StabilityMetrics 的公开属性写成两列表(属性名 / 值)写入 PDF
  468. /// 9. 关闭并释放文档、writer、流,提示导出成功;捕获异常记录日志并提示失败。
  469. /// 10. 使用 SendTaskMessage 在 UI 上通知结果。
  470. /// </summary>
  471. void ExecuteExportReportCommand()
  472. {
  473. try
  474. {
  475. if (TestResults == null || TestResults.Count == 0)
  476. {
  477. SendTaskMessage("无测试数据,无法导出报告。");
  478. return;
  479. }
  480. var dlg = new Microsoft.Win32.SaveFileDialog
  481. {
  482. DefaultExt = "pdf",
  483. Filter = "PDF 文件 (*.pdf)|*.pdf|所有文件 (*.*)|*.*",
  484. FileName = "TestReport.pdf",
  485. Title = "保存测试报告为 PDF"
  486. };
  487. bool? dlgResult = dlg.ShowDialog();
  488. if (dlgResult != true)
  489. return;
  490. string path = dlg.FileName;
  491. // 创建文档(A4, 边距)
  492. var doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 36, 36, 54, 54);
  493. using (var fs = System.IO.File.Create(path))
  494. {
  495. var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, fs);
  496. doc.Open();
  497. // 字体加载,优先中文系统字体
  498. iTextSharp.text.Font titleFont;
  499. iTextSharp.text.Font headerFont;
  500. iTextSharp.text.Font normalFont;
  501. iTextSharp.text.pdf.BaseFont baseFont = null;
  502. try
  503. {
  504. var fontsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
  505. var candidates = new[]
  506. {
  507. "msyh.ttf",
  508. "msyhbd.ttf",
  509. "simsun.ttc,0",
  510. "simsun.ttc,1",
  511. "Microsoft YaHei.ttf",
  512. "msyh.ttc,0",
  513. "msyh.ttc,1",
  514. "simhei.ttf"
  515. };
  516. foreach (var f in candidates)
  517. {
  518. var path1 = Path.Combine(fontsFolder, f);
  519. try
  520. {
  521. baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(
  522. path1,
  523. iTextSharp.text.pdf.BaseFont.IDENTITY_H,
  524. iTextSharp.text.pdf.BaseFont.EMBEDDED
  525. );
  526. if (baseFont != null)
  527. break;
  528. }
  529. catch
  530. {
  531. continue;
  532. }
  533. }
  534. }
  535. catch
  536. {
  537. baseFont = null;
  538. }
  539. if (baseFont != null)
  540. {
  541. titleFont = new iTextSharp.text.Font(baseFont, 16, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
  542. headerFont = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
  543. normalFont = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
  544. }
  545. else
  546. {
  547. titleFont = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 16, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
  548. headerFont = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
  549. normalFont = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
  550. }
  551. // 标题
  552. var title = new iTextSharp.text.Paragraph("视觉动态精度测试报告", titleFont)
  553. {
  554. Alignment = iTextSharp.text.Element.ALIGN_CENTER,
  555. SpacingAfter = 12f
  556. };
  557. doc.Add(title);
  558. // 测试摘要
  559. var metaTable = new iTextSharp.text.pdf.PdfPTable(2) { WidthPercentage = 100f };
  560. metaTable.SetWidths(new float[] { 1f, 2f });
  561. void AddMeta(string name, string value)
  562. {
  563. var cellName = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(name, headerFont)) { Border = 0, PaddingBottom = 6f };
  564. var cellVal = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(value, normalFont)) { Border = 0, PaddingBottom = 6f };
  565. metaTable.AddCell(cellName);
  566. metaTable.AddCell(cellVal);
  567. }
  568. AddMeta("导出时间", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  569. AddMeta("测试次数(目标)", RepeatCount.ToString(System.Globalization.CultureInfo.InvariantCulture));
  570. AddMeta("当前进度", $"{CurrentProgress} / {RepeatCount}");
  571. AddMeta("成功次数", SuccessCount.ToString(System.Globalization.CultureInfo.InvariantCulture));
  572. AddMeta("失败次数", FailCount.ToString(System.Globalization.CultureInfo.InvariantCulture));
  573. AddMeta("成功率(%)", SuccessRate.ToString("F2", System.Globalization.CultureInfo.InvariantCulture));
  574. doc.Add(metaTable);
  575. doc.Add(new iTextSharp.text.Paragraph(" ")); // 空行
  576. // 数据表格列定义
  577. var headers = new[]
  578. {
  579. "Index",
  580. "Timestamp",
  581. "IsPhotoSuccess",
  582. "PointB.X",
  583. "PointB.Y",
  584. "PointB.Z",
  585. "CycleTime(s)",
  586. "PixelX",
  587. "PixelY",
  588. "AngleU",
  589. "TransformX",
  590. "TransformY"
  591. };
  592. var table = new iTextSharp.text.pdf.PdfPTable(headers.Length) { WidthPercentage = 100f };
  593. foreach (var h in headers)
  594. {
  595. var cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(h, headerFont))
  596. {
  597. HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER,
  598. BackgroundColor = new iTextSharp.text.BaseColor(230, 230, 230),
  599. Padding = 4f
  600. };
  601. table.AddCell(cell);
  602. }
  603. // 写入每一行数据
  604. foreach (var r in TestResults)
  605. {
  606. string sIndex = r.Index.ToString(System.Globalization.CultureInfo.InvariantCulture);
  607. string sTime = r.Timestamp.ToString("o", System.Globalization.CultureInfo.InvariantCulture);
  608. string sSucc = r.IsPhotoSuccess ? "True" : "False";
  609. string sPx = "";
  610. string sPy = "";
  611. string sPz = "";
  612. if (r.PointB != null)
  613. {
  614. sPx = Convert.ToString(r.PointB.X, System.Globalization.CultureInfo.InvariantCulture);
  615. sPy = Convert.ToString(r.PointB.Y, System.Globalization.CultureInfo.InvariantCulture);
  616. sPz = Convert.ToString(r.PointB.Z, System.Globalization.CultureInfo.InvariantCulture);
  617. }
  618. string sCycle = Convert.ToString(r.CycleTime, System.Globalization.CultureInfo.InvariantCulture);
  619. string sPixelX = Convert.ToString(r.PixelX, System.Globalization.CultureInfo.InvariantCulture);
  620. string sPixelY = Convert.ToString(r.PixelY, System.Globalization.CultureInfo.InvariantCulture);
  621. string sAngle = Convert.ToString(r.AngleU, System.Globalization.CultureInfo.InvariantCulture);
  622. string sTx = Convert.ToString(r.TransformX, System.Globalization.CultureInfo.InvariantCulture);
  623. string sTy = Convert.ToString(r.TransformY, System.Globalization.CultureInfo.InvariantCulture);
  624. var rowVals = new[] { sIndex, sTime, sSucc, sPx, sPy, sPz, sCycle, sPixelX, sPixelY, sAngle, sTx, sTy };
  625. foreach (var v in rowVals)
  626. {
  627. var cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(v ?? "", normalFont)) { Padding = 4f };
  628. table.AddCell(cell);
  629. }
  630. }
  631. doc.Add(table);
  632. // 新页,写入分析结果
  633. doc.NewPage();
  634. var analysisTitle = new iTextSharp.text.Paragraph("分析结果", titleFont) { SpacingAfter = 8f };
  635. doc.Add(analysisTitle);
  636. var dims = new[]
  637. {
  638. new { Name = "TransformX", Values = TestResults.Where(t => t.IsPhotoSuccess).Select(t => t.TransformX).ToArray() },
  639. new { Name = "TransformY", Values = TestResults.Where(t => t.IsPhotoSuccess).Select(t => t.TransformY).ToArray() },
  640. new { Name = "AngleU", Values = TestResults.Where(t => t.IsPhotoSuccess).Select(t => t.AngleU).ToArray() }
  641. };
  642. foreach (var dim in dims)
  643. {
  644. try
  645. {
  646. var header = new iTextSharp.text.Paragraph(dim.Name, headerFont) { SpacingBefore = 6f, SpacingAfter = 4f };
  647. doc.Add(header);
  648. if (dim.Values == null || dim.Values.Length == 0)
  649. {
  650. doc.Add(new iTextSharp.text.Paragraph("样本数为 0,无法计算。", normalFont));
  651. continue;
  652. }
  653. StabilityMetrics metrics = StabilityAnalyzer.AnalyzeStability(dim.Values);
  654. var metricsTable = new iTextSharp.text.pdf.PdfPTable(2) { WidthPercentage = 60f, SpacingAfter = 6f };
  655. metricsTable.SetWidths(new float[] { 1f, 1f });
  656. var props = metrics.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
  657. foreach (var p in props)
  658. {
  659. object pv = p.GetValue(metrics);
  660. string pvStr;
  661. if (pv == null) pvStr = "";
  662. else if (pv is double) pvStr = ((double)pv).ToString("G", System.Globalization.CultureInfo.InvariantCulture);
  663. else pvStr = pv.ToString();
  664. var pc = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(p.Name, normalFont)) { Padding = 4f };
  665. var vc = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(pvStr, normalFont)) { Padding = 4f };
  666. metricsTable.AddCell(pc);
  667. metricsTable.AddCell(vc);
  668. }
  669. doc.Add(metricsTable);
  670. }
  671. catch (Exception exCol)
  672. {
  673. LogHelper.WriteLogError($"导出报告时处理维度[{dim.Name}]出错", exCol);
  674. doc.Add(new iTextSharp.text.Paragraph($"处理维度 {dim.Name} 时出错: {exCol.Message}", normalFont));
  675. }
  676. }
  677. doc.Close();
  678. writer.Close();
  679. }
  680. SendTaskMessage($"已导出测试报告到:{path}");
  681. }
  682. catch (Exception ex)
  683. {
  684. LogHelper.WriteLogError("导出测试报告时出错", ex);
  685. SendTaskMessage($"导出测试报告失败:{ex.Message}");
  686. }
  687. }
  688. /// <summary>
  689. /// 导出测试数据为CSV文件
  690. /// </summary>
  691. void ExecuteExportCSVCommand()
  692. {
  693. try
  694. {
  695. if (TestResults == null || TestResults.Count == 0)
  696. {
  697. SendTaskMessage("无测试数据,无法导出。");
  698. return;
  699. }
  700. var dlg = new Microsoft.Win32.SaveFileDialog
  701. {
  702. DefaultExt = "csv",
  703. Filter = "CSV 文件 (*.csv)|*.csv|所有文件 (*.*)|*.*",
  704. FileName = "TestResults.csv",
  705. Title = "保存测试结果为 CSV"
  706. };
  707. bool? dlgResult = dlg.ShowDialog();
  708. if (dlgResult != true)
  709. return;
  710. string path = dlg.FileName;
  711. var sb = new System.Text.StringBuilder();
  712. // CSV 字段转义
  713. Func<string, string> EscapeCsv = (s) =>
  714. {
  715. if (s == null) return "";
  716. bool mustQuote = s.Contains(",") || s.Contains("\"") || s.Contains("\r") || s.Contains("\n");
  717. string esc = s.Replace("\"", "\"\"");
  718. return mustQuote ? $"\"{esc}\"" : esc;
  719. };
  720. // 写入表头
  721. var headers = new[]
  722. {
  723. "Index",
  724. "Timestamp",
  725. "IsPhotoSuccess",
  726. "PointB.X",
  727. "PointB.Y",
  728. "PointB.Z",
  729. "CycleTime",
  730. "PixelX",
  731. "PixelY",
  732. "AngleU",
  733. "TransformX",
  734. "TransformY"
  735. };
  736. sb.AppendLine(string.Join(",", headers.Select(h => EscapeCsv(h))));
  737. // 写入数据行
  738. foreach (var r in TestResults)
  739. {
  740. var cols = new List<string>();
  741. cols.Add(EscapeCsv(r.Index.ToString()));
  742. cols.Add(EscapeCsv(r.Timestamp.ToString("o"))); // ISO 8601 格式
  743. cols.Add(EscapeCsv(r.IsPhotoSuccess ? "True" : "False"));
  744. if (r.PointB != null)
  745. {
  746. // 假设 RPoint 有 X,Y,Z 属性(若命名不同需调整)
  747. cols.Add(EscapeCsv(Convert.ToString(r.PointB.X, System.Globalization.CultureInfo.InvariantCulture)));
  748. cols.Add(EscapeCsv(Convert.ToString(r.PointB.Y, System.Globalization.CultureInfo.InvariantCulture)));
  749. cols.Add(EscapeCsv(Convert.ToString(r.PointB.Z, System.Globalization.CultureInfo.InvariantCulture)));
  750. }
  751. else
  752. {
  753. cols.Add("");
  754. cols.Add("");
  755. cols.Add("");
  756. }
  757. cols.Add(EscapeCsv(Convert.ToString(r.CycleTime, System.Globalization.CultureInfo.InvariantCulture)));
  758. cols.Add(EscapeCsv(Convert.ToString(r.PixelX, System.Globalization.CultureInfo.InvariantCulture)));
  759. cols.Add(EscapeCsv(Convert.ToString(r.PixelY, System.Globalization.CultureInfo.InvariantCulture)));
  760. cols.Add(EscapeCsv(Convert.ToString(r.AngleU, System.Globalization.CultureInfo.InvariantCulture)));
  761. cols.Add(EscapeCsv(Convert.ToString(r.TransformX, System.Globalization.CultureInfo.InvariantCulture)));
  762. cols.Add(EscapeCsv(Convert.ToString(r.TransformY, System.Globalization.CultureInfo.InvariantCulture)));
  763. sb.AppendLine(string.Join(",", cols));
  764. }
  765. // 在末尾追加分析结果
  766. sb.AppendLine();
  767. sb.AppendLine("分析结果");
  768. sb.AppendLine("维度,指标,值");
  769. // 要分析的维度:TransformX, TransformY, AngleU
  770. var dims = new[]
  771. {
  772. new { Name = "TransformX", Values = TestResults.Where(t => t.IsPhotoSuccess).Select(t => t.TransformX).ToArray() },
  773. new { Name = "TransformY", Values = TestResults.Where(t => t.IsPhotoSuccess).Select(t => t.TransformY).ToArray() },
  774. new { Name = "AngleU", Values = TestResults.Where(t => t.IsPhotoSuccess).Select(t => t.AngleU).ToArray() }
  775. };
  776. foreach (var dim in dims)
  777. {
  778. try
  779. {
  780. if (dim.Values == null || dim.Values.Length == 0)
  781. {
  782. sb.AppendLine($"{EscapeCsv(dim.Name)},{EscapeCsv("样本数")},{EscapeCsv("0")}");
  783. continue;
  784. }
  785. // 调用稳定性分析
  786. StabilityMetrics metrics = StabilityAnalyzer.AnalyzeStability(dim.Values);
  787. // 反射写入公开属性
  788. var props = metrics.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
  789. foreach (var p in props)
  790. {
  791. object pv = p.GetValue(metrics);
  792. string pvStr;
  793. if (pv == null) pvStr = "";
  794. else if (pv is double) pvStr = Convert.ToString((double)pv, System.Globalization.CultureInfo.InvariantCulture);
  795. else pvStr = pv.ToString();
  796. sb.AppendLine($"{EscapeCsv(dim.Name)},{EscapeCsv(p.Name)},{EscapeCsv(pvStr)}");
  797. }
  798. }
  799. catch (Exception exCol)
  800. {
  801. LogHelper.WriteLogError($"导出分析结果时处理维度[{dim.Name}]出错", exCol);
  802. sb.AppendLine($"{EscapeCsv(dim.Name)},{EscapeCsv("Error")},{EscapeCsv(exCol.Message)}");
  803. }
  804. }
  805. // 写入文件(UTF8,无 BOM)
  806. System.IO.File.WriteAllText(path, sb.ToString(), System.Text.Encoding.UTF8);
  807. SendTaskMessage($"已导出测试结果到:{path}");
  808. }
  809. catch (Exception ex)
  810. {
  811. LogHelper.WriteLogError("导出CSV时出错", ex);
  812. SendTaskMessage($"导出CSV失败:{ex.Message}");
  813. }
  814. }
  815. /// <summary>
  816. /// 选中视觉流程改变时
  817. /// </summary>
  818. void ExecuteProcedureSelectionChangedCommand()
  819. {
  820. if (SelectProcedure == null)
  821. {
  822. return;
  823. }
  824. //获取相机
  825. Camera = _cameraService.GetCamera(SelectProcedure.CameraId);
  826. VisionTool = SelectProcedure.ToolBlock;
  827. }
  828. /// <summary>
  829. /// 示教点B
  830. /// </summary>
  831. void ExecuteTeachPointBCommand()
  832. {
  833. if (Robot == null || !Robot.IsConnected)
  834. {
  835. SendTaskMessage("机器人未连接,无法示教!");
  836. return;
  837. }
  838. try
  839. {
  840. var position = Robot.GetRobotPos();
  841. if (position != null)
  842. {
  843. PointB = position.Clone();
  844. SendTaskMessage($"已示教点B:X={PointB.X:F2} Y={PointB.Y:F2} Z={PointB.Z:F2}");
  845. }
  846. else
  847. {
  848. SendTaskMessage("获取机器人当前位置失败,无法示教点B!");
  849. }
  850. }
  851. catch (Exception ex)
  852. {
  853. LogHelper.WriteLogError("示教点B时出错!", ex);
  854. SendTaskMessage($"示教点B时出错:{ex.Message}");
  855. }
  856. }
  857. /// <summary>
  858. /// 示教点A
  859. /// </summary>
  860. void ExecuteTeachPointACommand()
  861. {
  862. if (Robot == null || !Robot.IsConnected)
  863. {
  864. SendTaskMessage("机器人未连接,无法示教!");
  865. return;
  866. }
  867. try
  868. {
  869. var position = Robot.GetRobotPos();
  870. if (position != null)
  871. {
  872. PointA = position.Clone();
  873. SendTaskMessage($"已示教点A:X={PointA.X:F2} Y={PointA.Y:F2} Z={PointA.Z:F2}");
  874. }
  875. else
  876. {
  877. SendTaskMessage("获取机器人当前位置失败,无法示教点A!");
  878. }
  879. }
  880. catch (Exception ex)
  881. {
  882. LogHelper.WriteLogError("示教点A时出错!", ex);
  883. SendTaskMessage($"示教点A时出错:{ex.Message}");
  884. }
  885. }
  886. /// <summary>
  887. /// 显示趋势图
  888. /// </summary>
  889. void ExecuteShowTrendChartCommand()
  890. {
  891. }
  892. /// <summary>
  893. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs、图像和图形集合。
  894. /// </summary>
  895. /// <param name="index"></param>
  896. /// <returns></returns>
  897. public Task<(bool isSuccess, double pixelX, double pixelY, double angleU, double transformX, double transformY)> ExecutePhotoEx(int index)
  898. {
  899. return Task.Run(() =>
  900. {
  901. CogToolBlockTerminalCollection outputCollection;
  902. List<object> result = new List<object>();
  903. result.Add(index);
  904. try
  905. {
  906. // 1. 采集图像
  907. //bool succed = Camera.SetExposureTime(SelectProcedure.ExposureTime);
  908. //if (!succed)
  909. //{
  910. // SendTaskMessage(Lang.相机曝光设置失败);
  911. //}
  912. //succed = Camera.SetGain(SelectProcedure.Gain);
  913. //if (!succed)
  914. //{
  915. // SendTaskMessage(Lang.相机增益设置失败);
  916. //}
  917. //DateTime nowtime = DateTime.Now;
  918. //LogHelper.WriteLogInfo(Lang.开始采集图像);
  919. //var image = Camera.Grab();
  920. //if (image == null)
  921. //{
  922. // SendTaskMessage(Lang.图像采集失败);
  923. // outputCollection = null;
  924. // return (false, result.ToArray());
  925. //}
  926. //Image = image;
  927. //VisionTool.Inputs["InputImage"].Value = image;
  928. //LogHelper.WriteLogInfo(string.Format(Lang.采集图像完成用时0ms, (DateTime.Now - nowtime).Milliseconds));
  929. // 2. 为ToolBlock传入其他输入终端
  930. //if (InputTerminal != null)
  931. //{
  932. // LogHelper.WriteLogInfo(Lang.为ToolBlock传入输入终端);
  933. // foreach (var item in InputTerminal)
  934. // {
  935. // if (VisionTool.Inputs.Contains(item.Key))
  936. // {
  937. // LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  938. // VisionTool.Inputs[item.Key].Value = item.Value;
  939. // }
  940. // else
  941. // {
  942. // LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  943. // VisionTool.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  944. // }
  945. // }
  946. //}
  947. Image = VisionTool.Inputs["InputImage"].Value as ICogImage;
  948. // 3. 运行视觉工具
  949. LogHelper.WriteLogInfo(Lang.开始运行视觉工具);
  950. VisionTool.Run(); //运行ToolBlock
  951. if (VisionTool.RunStatus.Result == CogToolResultConstants.Accept)
  952. {
  953. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", SelectProcedure.Name).Replace("{1}", $"{VisionTool.RunStatus.ProcessingTime:F1}"));
  954. outputCollection = VisionTool.Outputs; //获取输出终端集合
  955. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection;
  956. if (!outputCollection.Contains("Found"))
  957. {
  958. SendTaskMessage(Lang.未找到视觉输出结果);
  959. return (false, 0d, 0d, 0d, 0d, 0d);
  960. }
  961. // 2. 获取视觉输出结果
  962. bool Found = (bool)(outputCollection["Found"].Value);
  963. if (!Found)
  964. {
  965. SendTaskMessage(Lang.拍照NG);
  966. return (false, 0d, 0d, 0d, 0d, 0d);
  967. }
  968. //SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  969. // 3. 获取视觉输出结果
  970. //获取相机校准
  971. var calib = _calibrationService.GetCalibration(SelectProcedure.CalibrationId);
  972. string points = (string)(outputCollection["Point"].Value);
  973. string[] strpoints = points.Split(';');
  974. //先将pos按照逗号进行分隔,拿到数组
  975. var posParts = strpoints[0].Split(',');
  976. double _pixel_x = double.Parse(posParts[0]);
  977. double _pixel_y = double.Parse(posParts[1]);
  978. double _pixel_u = double.Parse(posParts[2]);
  979. //获取机器人当前坐标系
  980. RPoint rPoint = Robot.GetRobotPos();
  981. double[] point = new double[2];
  982. point[0] = rPoint.X;
  983. point[1] = rPoint.Y;
  984. point[2] = rPoint.U;
  985. if (calib.CameraMount == CameraMount.FixedUp || calib.CameraMount == CameraMount.FixedDown)
  986. {
  987. point = null;
  988. }
  989. //转换点位-像素转换成机器人绝对坐标
  990. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), point, calib, RobotBrand.XYZ_Platform);
  991. if (!calibResult.IsSucceed)
  992. {
  993. return (false, _pixel_x, _pixel_y, _pixel_u, 0d, 0d);
  994. }
  995. return (true, _pixel_x, _pixel_y, _pixel_u, calibResult.X, calibResult.Y); ;
  996. }
  997. else
  998. {
  999. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", SelectProcedure.Name).Replace("{1}", $"{VisionTool.RunStatus.ProcessingTime:F1}"));
  1000. SendTaskMessage(VisionTool.RunStatus.Message);
  1001. outputCollection = null;
  1002. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection;
  1003. return (false, 0d, 0d, 0d, 0d, 0d);
  1004. }
  1005. }
  1006. catch (Exception ex)
  1007. {
  1008. SendTaskMessage(ex.Message);
  1009. LogHelper.WriteLogError(Lang.执行相机取图并执行视觉工具组时出错, ex);
  1010. outputCollection = null;
  1011. return (false, 0d, 0d, 0d, 0d, 0d);
  1012. }
  1013. });
  1014. }
  1015. public void SendTaskMessage(string msg)
  1016. {
  1017. App.Current.Dispatcher.Invoke(() =>
  1018. {
  1019. MessageQueue.Clear();
  1020. MessageQueue.Enqueue(msg);
  1021. });
  1022. }
  1023. // 规格限制(根据实际情况设置)
  1024. private double _xLSL = -0.02; // X下规格限
  1025. private double _xUSL = 0.02; // X上规格限
  1026. private double _yLSL = -0.02; // Y下规格限
  1027. private double _yUSL = 0.02; // Y上规格限
  1028. private double _angleLSL = -1.0; // 角度下规格限
  1029. private double _angleUSL = 1.0; // 角度上规格限
  1030. /// <summary>
  1031. /// 计算所有精度指标
  1032. /// </summary>
  1033. public void CalculatePrecisionMetrics()
  1034. {
  1035. if (TestResults == null || TestResults.Count < 2)
  1036. return;
  1037. // 过滤成功的测试结果
  1038. var successResults = TestResults.Where(r => r.IsPhotoSuccess).ToList();
  1039. if (successResults.Count < 2)
  1040. return;
  1041. // 提取数据
  1042. var transformXs = successResults.Select(r => r.TransformX).ToList();
  1043. var transformYs = successResults.Select(r => r.TransformY).ToList();
  1044. var angleUs = successResults.Select(r => r.AngleU).ToList();
  1045. // 计算X方向指标
  1046. var xMetrics = CalculateMetrics(transformXs, _xLSL, _xUSL);
  1047. PrecisionResult.XMean = xMetrics.Mean;
  1048. PrecisionResult.XPrecision = xMetrics.StdDeviation;
  1049. PrecisionResult.XThreeSigmaRange = xMetrics.ThreeSigmaRange;
  1050. PrecisionResult.XRange = xMetrics.Range;
  1051. PrecisionResult.XKurtosis = xMetrics.Kurtosis;
  1052. PrecisionResult.XCpk = xMetrics.Cpk;
  1053. // 计算Y方向指标
  1054. var yMetrics = CalculateMetrics(transformYs, _yLSL, _yUSL);
  1055. PrecisionResult.YMean = yMetrics.Mean;
  1056. PrecisionResult.YPrecision = yMetrics.StdDeviation;
  1057. PrecisionResult.YThreeSigmaRange = yMetrics.ThreeSigmaRange;
  1058. PrecisionResult.YRange = yMetrics.Range;
  1059. PrecisionResult.YKurtosis = yMetrics.Kurtosis;
  1060. PrecisionResult.YCpk = yMetrics.Cpk;
  1061. // 计算角度指标
  1062. var angleMetrics = CalculateMetrics(angleUs, _angleLSL, _angleUSL);
  1063. PrecisionResult.AngleMean = angleMetrics.Mean;
  1064. PrecisionResult.AnglePrecision = angleMetrics.StdDeviation;
  1065. PrecisionResult.AngleThreeSigmaRange = angleMetrics.ThreeSigmaRange;
  1066. PrecisionResult.AngleRange = angleMetrics.Range;
  1067. PrecisionResult.AngleCpk = angleMetrics.Cpk;
  1068. // 计算综合精度
  1069. PrecisionResult.OverallPrecision = Math.Sqrt(
  1070. Math.Pow(PrecisionResult.XPrecision, 2) +
  1071. Math.Pow(PrecisionResult.YPrecision, 2));
  1072. PrecisionResult.OverallThreeSigmaRange = PrecisionResult.OverallPrecision * 3;
  1073. // 使用最差的CPK作为整体评级
  1074. var minCpk = Math.Min(Math.Min(PrecisionResult.XCpk, PrecisionResult.YCpk), PrecisionResult.AngleCpk);
  1075. PrecisionResult.ProcessRating = PrecisionResult.GetCpkRating(minCpk);
  1076. }
  1077. /// <summary>
  1078. /// 计算单个维度的所有指标
  1079. /// </summary>
  1080. private DimensionMetrics CalculateMetrics(List<double> values, double lsl, double usl)
  1081. {
  1082. if (values == null || values.Count < 2)
  1083. return new DimensionMetrics();
  1084. var metrics = new DimensionMetrics
  1085. {
  1086. Mean = values.Average(),
  1087. StdDeviation = CalculateStandardDeviation(values),
  1088. Range = values.Max() - values.Min(),
  1089. Kurtosis = CalculateKurtosis(values)
  1090. };
  1091. metrics.ThreeSigmaRange = metrics.StdDeviation * 3;
  1092. metrics.Cpk = CalculateCpk(values, lsl, usl);
  1093. return metrics;
  1094. }
  1095. /// <summary>
  1096. /// 计算标准差
  1097. /// </summary>
  1098. private double CalculateStandardDeviation(List<double> values)
  1099. {
  1100. if (values.Count < 2)
  1101. return 0;
  1102. var mean = values.Average();
  1103. var sumSq = values.Sum(v => Math.Pow(v - mean, 2));
  1104. return Math.Sqrt(sumSq / (values.Count - 1));
  1105. }
  1106. /// <summary>
  1107. /// 计算峰度
  1108. /// </summary>
  1109. private double CalculateKurtosis(List<double> values)
  1110. {
  1111. if (values.Count < 4)
  1112. return 0;
  1113. var mean = values.Average();
  1114. var n = values.Count;
  1115. var sum4 = values.Sum(v => Math.Pow(v - mean, 4));
  1116. var sum2 = values.Sum(v => Math.Pow(v - mean, 2));
  1117. if (sum2 == 0)
  1118. return 0;
  1119. return (n * sum4) / Math.Pow(sum2, 2) - 3;
  1120. }
  1121. /// <summary>
  1122. /// 计算CPK
  1123. /// </summary>
  1124. private double CalculateCpk(List<double> values, double lsl, double usl)
  1125. {
  1126. if (values.Count < 2 || usl <= lsl)
  1127. return 0;
  1128. var stdDev = CalculateStandardDeviation(values);
  1129. if (stdDev == 0)
  1130. return double.MaxValue;
  1131. var mean = values.Average();
  1132. var cpu = (usl - mean) / (3 * stdDev);
  1133. var cpl = (mean - lsl) / (3 * stdDev);
  1134. return Math.Min(cpu, cpl);
  1135. }
  1136. /// <summary>
  1137. /// 单个维度的指标
  1138. /// </summary>
  1139. private class DimensionMetrics
  1140. {
  1141. public double Mean { get; set; }
  1142. public double StdDeviation { get; set; }
  1143. public double ThreeSigmaRange { get; set; }
  1144. public double Range { get; set; }
  1145. public double Kurtosis { get; set; }
  1146. public double Cpk { get; set; }
  1147. }
  1148. /// <summary>
  1149. /// 在添加测试结果后自动更新精度分析
  1150. /// </summary>
  1151. private void OnTestResultAdded()
  1152. {
  1153. CalculatePrecisionMetrics();
  1154. RaisePropertyChanged(nameof(PrecisionResult));
  1155. }
  1156. /// <summary>
  1157. /// 设置规格限制
  1158. /// </summary>
  1159. public void SetSpecificationLimits(double xLSL, double xUSL, double yLSL, double yUSL, double angleLSL, double angleUSL)
  1160. {
  1161. _xLSL = xLSL;
  1162. _xUSL = xUSL;
  1163. _yLSL = yLSL;
  1164. _yUSL = yUSL;
  1165. _angleLSL = angleLSL;
  1166. _angleUSL = angleUSL;
  1167. // 重新计算精度指标
  1168. CalculatePrecisionMetrics();
  1169. }
  1170. /// <summary>
  1171. /// 基于3σ自动设置规格限制
  1172. /// </summary>
  1173. public void AutoSetSpecificationLimits()
  1174. {
  1175. if (TestResults == null || TestResults.Count < 2)
  1176. return;
  1177. var successResults = TestResults.Where(r => r.IsPhotoSuccess).ToList();
  1178. if (successResults.Count < 2)
  1179. return;
  1180. var transformXs = successResults.Select(r => r.TransformX).ToList();
  1181. var transformYs = successResults.Select(r => r.TransformY).ToList();
  1182. var angleUs = successResults.Select(r => r.AngleU).ToList();
  1183. var xStd = CalculateStandardDeviation(transformXs);
  1184. var yStd = CalculateStandardDeviation(transformYs);
  1185. var angleStd = CalculateStandardDeviation(angleUs);
  1186. var xMean = transformXs.Average();
  1187. var yMean = transformYs.Average();
  1188. var angleMean = angleUs.Average();
  1189. // 使用平均值±3σ作为自动规格限
  1190. SetSpecificationLimits(
  1191. xLSL: xMean - 3 * xStd,
  1192. xUSL: xMean + 3 * xStd,
  1193. yLSL: yMean - 3 * yStd,
  1194. yUSL: yMean + 3 * yStd,
  1195. angleLSL: angleMean - 3 * angleStd,
  1196. angleUSL: angleMean + 3 * angleStd
  1197. );
  1198. }
  1199. #endregion
  1200. #region 继承
  1201. public string Title { get; set; } = "视觉静态精度分析仪";
  1202. public event Action<IDialogResult> RequestClose;
  1203. public bool CanCloseDialog()
  1204. {
  1205. return true;
  1206. }
  1207. public void OnDialogClosed()
  1208. {
  1209. _cts?.Cancel();
  1210. }
  1211. public void OnDialogOpened(IDialogParameters parameters)
  1212. {
  1213. SelectProduct = parameters.GetValue<ProductModel>("SelectProduct");
  1214. Robot = parameters.GetValue<IRobot>("Robot");
  1215. //Camera = _cameraService.GetCamera(SelectProcedure.CameraId);
  1216. //VisionTool = parameters.GetValue<CogToolBlock>("ToolBlock");
  1217. ProcedureModels = new ObservableCollection<ProcedureModel>();
  1218. foreach (var item in SelectProduct.CameraProcedures)
  1219. {
  1220. foreach (var item1 in item.ProcedureModels)
  1221. {
  1222. ProcedureModels.Add(item1);
  1223. }
  1224. }
  1225. //VisionTool.Run();
  1226. //TestResult = CreateResultDataTable(VisionTool.Outputs);
  1227. }
  1228. #endregion
  1229. }
  1230. public class DynamicTestResult : BindableBase
  1231. {
  1232. private int _Index;
  1233. /// <summary>
  1234. /// 序号
  1235. /// </summary>
  1236. public int Index
  1237. {
  1238. get { return _Index; }
  1239. set { SetProperty(ref _Index, value); }
  1240. }
  1241. private DateTime _Timestamp;
  1242. /// <summary>
  1243. /// 时间戳
  1244. /// </summary>
  1245. public DateTime Timestamp
  1246. {
  1247. get { return _Timestamp; }
  1248. set { SetProperty(ref _Timestamp, value); }
  1249. }
  1250. private bool _isPhotoSuccess;
  1251. /// <summary>
  1252. /// 拍照结果
  1253. /// </summary>
  1254. public bool IsPhotoSuccess
  1255. {
  1256. get { return _isPhotoSuccess; }
  1257. set { SetProperty(ref _isPhotoSuccess, value); }
  1258. }
  1259. private RPoint _PointB;
  1260. /// <summary>
  1261. /// 机器人拍照的坐标
  1262. /// </summary>
  1263. public RPoint PointB
  1264. {
  1265. get { return _PointB; }
  1266. set { SetProperty(ref _PointB, value); }
  1267. }
  1268. private double _CycleTime;
  1269. /// <summary>
  1270. /// 单次节拍
  1271. /// </summary>
  1272. public double CycleTime
  1273. {
  1274. get { return _CycleTime; }
  1275. set { SetProperty(ref _CycleTime, value); }
  1276. }
  1277. private double _PixelX;
  1278. /// <summary>
  1279. /// 像素X
  1280. /// </summary>
  1281. public double PixelX
  1282. {
  1283. get { return _PixelX; }
  1284. set { SetProperty(ref _PixelX, value); }
  1285. }
  1286. private double _PixelY;
  1287. /// <summary>
  1288. /// 像素Y
  1289. /// </summary>
  1290. public double PixelY
  1291. {
  1292. get { return _PixelY; }
  1293. set { SetProperty(ref _PixelY, value); }
  1294. }
  1295. private double _AngleU;
  1296. /// <summary>
  1297. /// 像素U
  1298. /// </summary>
  1299. public double AngleU
  1300. {
  1301. get { return _AngleU; }
  1302. set { SetProperty(ref _AngleU, value); }
  1303. }
  1304. private double _TransformX;
  1305. /// <summary>
  1306. /// 转换后的机器人坐标X
  1307. /// </summary>
  1308. public double TransformX
  1309. {
  1310. get { return _TransformX; }
  1311. set { SetProperty(ref _TransformX, value); }
  1312. }
  1313. private double _TransformY;
  1314. /// <summary>
  1315. /// 转换后的机器人坐标Y
  1316. /// </summary>
  1317. public double TransformY
  1318. {
  1319. get { return _TransformY; }
  1320. set { SetProperty(ref _TransformY, value); }
  1321. }
  1322. public DynamicTestResult()
  1323. { }
  1324. public DynamicTestResult(int index, bool isPhotoSuccess, RPoint pointB, double cycleTime, double pixelX, double pixelY, double angleU, double transformX, double transformY)
  1325. {
  1326. Index = index;
  1327. Timestamp = DateTime.Now;
  1328. IsPhotoSuccess = isPhotoSuccess;
  1329. PointB = pointB;
  1330. CycleTime = cycleTime;
  1331. PixelX = pixelX;
  1332. PixelY = pixelY;
  1333. AngleU = angleU;
  1334. TransformX = transformX;
  1335. TransformY = transformY;
  1336. }
  1337. }
  1338. /// <summary>
  1339. /// 精度分析结果
  1340. /// </summary>
  1341. public class PrecisionAnalysisResult : BindableBase
  1342. {
  1343. private double _xPrecision;
  1344. /// <summary>
  1345. /// X方向精度(标准差)
  1346. /// </summary>
  1347. public double XPrecision
  1348. {
  1349. get { return _xPrecision; }
  1350. set { SetProperty(ref _xPrecision, value); }
  1351. }
  1352. private double _yPrecision;
  1353. /// <summary>
  1354. /// Y方向精度(标准差)
  1355. /// </summary>
  1356. public double YPrecision
  1357. {
  1358. get { return _yPrecision; }
  1359. set { SetProperty(ref _yPrecision, value); }
  1360. }
  1361. private double _anglePrecision;
  1362. /// <summary>
  1363. /// 角度精度(标准差)
  1364. /// </summary>
  1365. public double AnglePrecision
  1366. {
  1367. get { return _anglePrecision; }
  1368. set { SetProperty(ref _anglePrecision, value); }
  1369. }
  1370. private double _xThreeSigmaRange;
  1371. /// <summary>
  1372. /// X方向3σ范围
  1373. /// </summary>
  1374. public double XThreeSigmaRange
  1375. {
  1376. get { return _xThreeSigmaRange; }
  1377. set { SetProperty(ref _xThreeSigmaRange, value); }
  1378. }
  1379. private double _yThreeSigmaRange;
  1380. /// <summary>
  1381. /// Y方向3σ范围
  1382. /// </summary>
  1383. public double YThreeSigmaRange
  1384. {
  1385. get { return _yThreeSigmaRange; }
  1386. set { SetProperty(ref _yThreeSigmaRange, value); }
  1387. }
  1388. private double _angleThreeSigmaRange;
  1389. /// <summary>
  1390. /// 角度3σ范围
  1391. /// </summary>
  1392. public double AngleThreeSigmaRange
  1393. {
  1394. get { return _angleThreeSigmaRange; }
  1395. set { SetProperty(ref _angleThreeSigmaRange, value); }
  1396. }
  1397. private double _xMean;
  1398. /// <summary>
  1399. /// X方向平均值
  1400. /// </summary>
  1401. public double XMean
  1402. {
  1403. get { return _xMean; }
  1404. set { SetProperty(ref _xMean, value); }
  1405. }
  1406. private double _yMean;
  1407. /// <summary>
  1408. /// Y方向平均值
  1409. /// </summary>
  1410. public double YMean
  1411. {
  1412. get { return _yMean; }
  1413. set { SetProperty(ref _yMean, value); }
  1414. }
  1415. private double _angleMean;
  1416. /// <summary>
  1417. /// 角度平均值
  1418. /// </summary>
  1419. public double AngleMean
  1420. {
  1421. get { return _angleMean; }
  1422. set { SetProperty(ref _angleMean, value); }
  1423. }
  1424. private double _xRange;
  1425. /// <summary>
  1426. /// X方向极差
  1427. /// </summary>
  1428. public double XRange
  1429. {
  1430. get { return _xRange; }
  1431. set { SetProperty(ref _xRange, value); }
  1432. }
  1433. private double _yRange;
  1434. /// <summary>
  1435. /// Y方向极差
  1436. /// </summary>
  1437. public double YRange
  1438. {
  1439. get { return _yRange; }
  1440. set { SetProperty(ref _yRange, value); }
  1441. }
  1442. private double _angleRange;
  1443. /// <summary>
  1444. /// 角度极差
  1445. /// </summary>
  1446. public double AngleRange
  1447. {
  1448. get { return _angleRange; }
  1449. set { SetProperty(ref _angleRange, value); }
  1450. }
  1451. private double _xKurtosis;
  1452. /// <summary>
  1453. /// X方向峰度
  1454. /// </summary>
  1455. public double XKurtosis
  1456. {
  1457. get { return _xKurtosis; }
  1458. set { SetProperty(ref _xKurtosis, value); }
  1459. }
  1460. private double _yKurtosis;
  1461. /// <summary>
  1462. /// Y方向峰度
  1463. /// </summary>
  1464. public double YKurtosis
  1465. {
  1466. get { return _yKurtosis; }
  1467. set { SetProperty(ref _yKurtosis, value); }
  1468. }
  1469. private double _xCpk;
  1470. /// <summary>
  1471. /// X方向CPK
  1472. /// </summary>
  1473. public double XCpk
  1474. {
  1475. get { return _xCpk; }
  1476. set { SetProperty(ref _xCpk, value); }
  1477. }
  1478. private double _yCpk;
  1479. /// <summary>
  1480. /// Y方向CPK
  1481. /// </summary>
  1482. public double YCpk
  1483. {
  1484. get { return _yCpk; }
  1485. set { SetProperty(ref _yCpk, value); }
  1486. }
  1487. private double _angleCpk;
  1488. /// <summary>
  1489. /// 角度CPK
  1490. /// </summary>
  1491. public double AngleCpk
  1492. {
  1493. get { return _angleCpk; }
  1494. set { SetProperty(ref _angleCpk, value); }
  1495. }
  1496. private double _overallPrecision;
  1497. /// <summary>
  1498. /// 综合精度(XY合成标准差)
  1499. /// </summary>
  1500. public double OverallPrecision
  1501. {
  1502. get { return _overallPrecision; }
  1503. set { SetProperty(ref _overallPrecision, value); }
  1504. }
  1505. private double _overallThreeSigmaRange;
  1506. /// <summary>
  1507. /// 综合3σ范围
  1508. /// </summary>
  1509. public double OverallThreeSigmaRange
  1510. {
  1511. get { return _overallThreeSigmaRange; }
  1512. set { SetProperty(ref _overallThreeSigmaRange, value); }
  1513. }
  1514. private string _processRating;
  1515. /// <summary>
  1516. /// 过程能力评级
  1517. /// </summary>
  1518. public string ProcessRating
  1519. {
  1520. get { return _processRating; }
  1521. set { SetProperty(ref _processRating, value); }
  1522. }
  1523. /// <summary>
  1524. /// 获取CPK评级描述
  1525. /// </summary>
  1526. public string GetCpkRating(double cpk)
  1527. {
  1528. if (cpk >= 1.67)
  1529. return "卓越";
  1530. else if (cpk >= 1.33)
  1531. return "良好";
  1532. else if (cpk >= 1.00)
  1533. return "可接受";
  1534. else if (cpk >= 0.67)
  1535. return "不足";
  1536. else
  1537. return "严重不足";
  1538. }
  1539. }
  1540. }