VisionDynamicAccuracyAnalyzerViewModel.cs 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  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, 0d, 0d, 0d, 0d, 0d);
  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. string points = (string)(outputCollection["Point"].Value);
  971. string[] strpoints = points.Split(';');
  972. //先将pos按照逗号进行分隔,拿到数组
  973. var posParts = strpoints[0].Split(',');
  974. double _pixel_x = double.Parse(posParts[0]);
  975. double _pixel_y = double.Parse(posParts[1]);
  976. double _pixel_u = double.Parse(posParts[2]);
  977. //获取相机校准
  978. var calib = _calibrationService.GetCalibration(SelectProcedure.CalibrationId);
  979. if (calib == null)
  980. {
  981. return (true, _pixel_x, _pixel_y, _pixel_u, 0, 0); ;
  982. }
  983. //获取机器人当前坐标系
  984. RPoint rPoint = Robot.GetRobotPos();
  985. double[] point = new double[2];
  986. point[0] = rPoint.X;
  987. point[1] = rPoint.Y;
  988. point[2] = rPoint.U;
  989. if (calib.CameraMount == CameraMount.FixedUp || calib.CameraMount == CameraMount.FixedDown)
  990. {
  991. point = null;
  992. }
  993. //转换点位-像素转换成机器人绝对坐标
  994. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), point, calib, RobotBrand.XYZ_Platform);
  995. if (!calibResult.IsSucceed)
  996. {
  997. return (false, _pixel_x, _pixel_y, _pixel_u, 0d, 0d);
  998. }
  999. return (true, _pixel_x, _pixel_y, _pixel_u, calibResult.X, calibResult.Y); ;
  1000. }
  1001. else
  1002. {
  1003. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", SelectProcedure.Name).Replace("{1}", $"{VisionTool.RunStatus.ProcessingTime:F1}"));
  1004. SendTaskMessage(VisionTool.RunStatus.Message);
  1005. outputCollection = null;
  1006. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection;
  1007. return (false, 0d, 0d, 0d, 0d, 0d);
  1008. }
  1009. }
  1010. catch (Exception ex)
  1011. {
  1012. SendTaskMessage(ex.Message);
  1013. LogHelper.WriteLogError(Lang.执行相机取图并执行视觉工具组时出错, ex);
  1014. outputCollection = null;
  1015. return (false, 0d, 0d, 0d, 0d, 0d);
  1016. }
  1017. });
  1018. }
  1019. public void SendTaskMessage(string msg)
  1020. {
  1021. App.Current.Dispatcher.Invoke(() =>
  1022. {
  1023. MessageQueue.Clear();
  1024. MessageQueue.Enqueue(msg);
  1025. });
  1026. }
  1027. // 规格限制(根据实际情况设置)
  1028. private double _xLSL = -0.02; // X下规格限
  1029. private double _xUSL = 0.02; // X上规格限
  1030. private double _yLSL = -0.02; // Y下规格限
  1031. private double _yUSL = 0.02; // Y上规格限
  1032. private double _angleLSL = -1.0; // 角度下规格限
  1033. private double _angleUSL = 1.0; // 角度上规格限
  1034. /// <summary>
  1035. /// 计算所有精度指标
  1036. /// </summary>
  1037. public void CalculatePrecisionMetrics()
  1038. {
  1039. if (TestResults == null || TestResults.Count < 2)
  1040. return;
  1041. // 过滤成功的测试结果
  1042. var successResults = TestResults.Where(r => r.IsPhotoSuccess).ToList();
  1043. if (successResults.Count < 2)
  1044. return;
  1045. // 提取数据
  1046. var transformXs = successResults.Select(r => r.TransformX).ToList();
  1047. var transformYs = successResults.Select(r => r.TransformY).ToList();
  1048. var angleUs = successResults.Select(r => r.AngleU).ToList();
  1049. // 计算X方向指标
  1050. var xMetrics = CalculateMetrics(transformXs, _xLSL, _xUSL);
  1051. PrecisionResult.XMean = xMetrics.Mean;
  1052. PrecisionResult.XPrecision = xMetrics.StdDeviation;
  1053. PrecisionResult.XThreeSigmaRange = xMetrics.ThreeSigmaRange;
  1054. PrecisionResult.XRange = xMetrics.Range;
  1055. PrecisionResult.XKurtosis = xMetrics.Kurtosis;
  1056. PrecisionResult.XCpk = xMetrics.Cpk;
  1057. // 计算Y方向指标
  1058. var yMetrics = CalculateMetrics(transformYs, _yLSL, _yUSL);
  1059. PrecisionResult.YMean = yMetrics.Mean;
  1060. PrecisionResult.YPrecision = yMetrics.StdDeviation;
  1061. PrecisionResult.YThreeSigmaRange = yMetrics.ThreeSigmaRange;
  1062. PrecisionResult.YRange = yMetrics.Range;
  1063. PrecisionResult.YKurtosis = yMetrics.Kurtosis;
  1064. PrecisionResult.YCpk = yMetrics.Cpk;
  1065. // 计算角度指标
  1066. var angleMetrics = CalculateMetrics(angleUs, _angleLSL, _angleUSL);
  1067. PrecisionResult.AngleMean = angleMetrics.Mean;
  1068. PrecisionResult.AnglePrecision = angleMetrics.StdDeviation;
  1069. PrecisionResult.AngleThreeSigmaRange = angleMetrics.ThreeSigmaRange;
  1070. PrecisionResult.AngleRange = angleMetrics.Range;
  1071. PrecisionResult.AngleCpk = angleMetrics.Cpk;
  1072. // 计算综合精度
  1073. PrecisionResult.OverallPrecision = Math.Sqrt(
  1074. Math.Pow(PrecisionResult.XPrecision, 2) +
  1075. Math.Pow(PrecisionResult.YPrecision, 2));
  1076. PrecisionResult.OverallThreeSigmaRange = PrecisionResult.OverallPrecision * 3;
  1077. // 使用最差的CPK作为整体评级
  1078. var minCpk = Math.Min(Math.Min(PrecisionResult.XCpk, PrecisionResult.YCpk), PrecisionResult.AngleCpk);
  1079. PrecisionResult.ProcessRating = PrecisionResult.GetCpkRating(minCpk);
  1080. }
  1081. /// <summary>
  1082. /// 计算单个维度的所有指标
  1083. /// </summary>
  1084. private DimensionMetrics CalculateMetrics(List<double> values, double lsl, double usl)
  1085. {
  1086. if (values == null || values.Count < 2)
  1087. return new DimensionMetrics();
  1088. var metrics = new DimensionMetrics
  1089. {
  1090. Mean = values.Average(),
  1091. StdDeviation = CalculateStandardDeviation(values),
  1092. Range = values.Max() - values.Min(),
  1093. Kurtosis = CalculateKurtosis(values)
  1094. };
  1095. metrics.ThreeSigmaRange = metrics.StdDeviation * 3;
  1096. metrics.Cpk = CalculateCpk(values, lsl, usl);
  1097. return metrics;
  1098. }
  1099. /// <summary>
  1100. /// 计算标准差
  1101. /// </summary>
  1102. private double CalculateStandardDeviation(List<double> values)
  1103. {
  1104. if (values.Count < 2)
  1105. return 0;
  1106. var mean = values.Average();
  1107. var sumSq = values.Sum(v => Math.Pow(v - mean, 2));
  1108. return Math.Sqrt(sumSq / (values.Count - 1));
  1109. }
  1110. /// <summary>
  1111. /// 计算峰度
  1112. /// </summary>
  1113. private double CalculateKurtosis(List<double> values)
  1114. {
  1115. if (values.Count < 4)
  1116. return 0;
  1117. var mean = values.Average();
  1118. var n = values.Count;
  1119. var sum4 = values.Sum(v => Math.Pow(v - mean, 4));
  1120. var sum2 = values.Sum(v => Math.Pow(v - mean, 2));
  1121. if (sum2 == 0)
  1122. return 0;
  1123. return (n * sum4) / Math.Pow(sum2, 2) - 3;
  1124. }
  1125. /// <summary>
  1126. /// 计算CPK
  1127. /// </summary>
  1128. private double CalculateCpk(List<double> values, double lsl, double usl)
  1129. {
  1130. if (values.Count < 2 || usl <= lsl)
  1131. return 0;
  1132. var stdDev = CalculateStandardDeviation(values);
  1133. if (stdDev == 0)
  1134. return double.MaxValue;
  1135. var mean = values.Average();
  1136. var cpu = (usl - mean) / (3 * stdDev);
  1137. var cpl = (mean - lsl) / (3 * stdDev);
  1138. return Math.Min(cpu, cpl);
  1139. }
  1140. /// <summary>
  1141. /// 单个维度的指标
  1142. /// </summary>
  1143. private class DimensionMetrics
  1144. {
  1145. public double Mean { get; set; }
  1146. public double StdDeviation { get; set; }
  1147. public double ThreeSigmaRange { get; set; }
  1148. public double Range { get; set; }
  1149. public double Kurtosis { get; set; }
  1150. public double Cpk { get; set; }
  1151. }
  1152. /// <summary>
  1153. /// 在添加测试结果后自动更新精度分析
  1154. /// </summary>
  1155. private void OnTestResultAdded()
  1156. {
  1157. CalculatePrecisionMetrics();
  1158. RaisePropertyChanged(nameof(PrecisionResult));
  1159. }
  1160. /// <summary>
  1161. /// 设置规格限制
  1162. /// </summary>
  1163. public void SetSpecificationLimits(double xLSL, double xUSL, double yLSL, double yUSL, double angleLSL, double angleUSL)
  1164. {
  1165. _xLSL = xLSL;
  1166. _xUSL = xUSL;
  1167. _yLSL = yLSL;
  1168. _yUSL = yUSL;
  1169. _angleLSL = angleLSL;
  1170. _angleUSL = angleUSL;
  1171. // 重新计算精度指标
  1172. CalculatePrecisionMetrics();
  1173. }
  1174. /// <summary>
  1175. /// 基于3σ自动设置规格限制
  1176. /// </summary>
  1177. public void AutoSetSpecificationLimits()
  1178. {
  1179. if (TestResults == null || TestResults.Count < 2)
  1180. return;
  1181. var successResults = TestResults.Where(r => r.IsPhotoSuccess).ToList();
  1182. if (successResults.Count < 2)
  1183. return;
  1184. var transformXs = successResults.Select(r => r.TransformX).ToList();
  1185. var transformYs = successResults.Select(r => r.TransformY).ToList();
  1186. var angleUs = successResults.Select(r => r.AngleU).ToList();
  1187. var xStd = CalculateStandardDeviation(transformXs);
  1188. var yStd = CalculateStandardDeviation(transformYs);
  1189. var angleStd = CalculateStandardDeviation(angleUs);
  1190. var xMean = transformXs.Average();
  1191. var yMean = transformYs.Average();
  1192. var angleMean = angleUs.Average();
  1193. // 使用平均值±3σ作为自动规格限
  1194. SetSpecificationLimits(
  1195. xLSL: xMean - 3 * xStd,
  1196. xUSL: xMean + 3 * xStd,
  1197. yLSL: yMean - 3 * yStd,
  1198. yUSL: yMean + 3 * yStd,
  1199. angleLSL: angleMean - 3 * angleStd,
  1200. angleUSL: angleMean + 3 * angleStd
  1201. );
  1202. }
  1203. #endregion
  1204. #region 继承
  1205. public string Title { get; set; } = "视觉静态精度分析仪";
  1206. public event Action<IDialogResult> RequestClose;
  1207. public bool CanCloseDialog()
  1208. {
  1209. return true;
  1210. }
  1211. public void OnDialogClosed()
  1212. {
  1213. _cts?.Cancel();
  1214. }
  1215. public void OnDialogOpened(IDialogParameters parameters)
  1216. {
  1217. SelectProduct = parameters.GetValue<ProductModel>("SelectProduct");
  1218. Robot = parameters.GetValue<IRobot>("Robot");
  1219. //Camera = _cameraService.GetCamera(SelectProcedure.CameraId);
  1220. //VisionTool = parameters.GetValue<CogToolBlock>("ToolBlock");
  1221. ProcedureModels = new ObservableCollection<ProcedureModel>();
  1222. foreach (var item in SelectProduct.CameraProcedures)
  1223. {
  1224. foreach (var item1 in item.ProcedureModels)
  1225. {
  1226. ProcedureModels.Add(item1);
  1227. }
  1228. }
  1229. //VisionTool.Run();
  1230. //TestResult = CreateResultDataTable(VisionTool.Outputs);
  1231. }
  1232. #endregion
  1233. }
  1234. public class DynamicTestResult : BindableBase
  1235. {
  1236. private int _Index;
  1237. /// <summary>
  1238. /// 序号
  1239. /// </summary>
  1240. public int Index
  1241. {
  1242. get { return _Index; }
  1243. set { SetProperty(ref _Index, value); }
  1244. }
  1245. private DateTime _Timestamp;
  1246. /// <summary>
  1247. /// 时间戳
  1248. /// </summary>
  1249. public DateTime Timestamp
  1250. {
  1251. get { return _Timestamp; }
  1252. set { SetProperty(ref _Timestamp, value); }
  1253. }
  1254. private bool _isPhotoSuccess;
  1255. /// <summary>
  1256. /// 拍照结果
  1257. /// </summary>
  1258. public bool IsPhotoSuccess
  1259. {
  1260. get { return _isPhotoSuccess; }
  1261. set { SetProperty(ref _isPhotoSuccess, value); }
  1262. }
  1263. private RPoint _PointB;
  1264. /// <summary>
  1265. /// 机器人拍照的坐标
  1266. /// </summary>
  1267. public RPoint PointB
  1268. {
  1269. get { return _PointB; }
  1270. set { SetProperty(ref _PointB, value); }
  1271. }
  1272. private double _CycleTime;
  1273. /// <summary>
  1274. /// 单次节拍
  1275. /// </summary>
  1276. public double CycleTime
  1277. {
  1278. get { return _CycleTime; }
  1279. set { SetProperty(ref _CycleTime, value); }
  1280. }
  1281. private double _PixelX;
  1282. /// <summary>
  1283. /// 像素X
  1284. /// </summary>
  1285. public double PixelX
  1286. {
  1287. get { return _PixelX; }
  1288. set { SetProperty(ref _PixelX, value); }
  1289. }
  1290. private double _PixelY;
  1291. /// <summary>
  1292. /// 像素Y
  1293. /// </summary>
  1294. public double PixelY
  1295. {
  1296. get { return _PixelY; }
  1297. set { SetProperty(ref _PixelY, value); }
  1298. }
  1299. private double _AngleU;
  1300. /// <summary>
  1301. /// 像素U
  1302. /// </summary>
  1303. public double AngleU
  1304. {
  1305. get { return _AngleU; }
  1306. set { SetProperty(ref _AngleU, value); }
  1307. }
  1308. private double _TransformX;
  1309. /// <summary>
  1310. /// 转换后的机器人坐标X
  1311. /// </summary>
  1312. public double TransformX
  1313. {
  1314. get { return _TransformX; }
  1315. set { SetProperty(ref _TransformX, value); }
  1316. }
  1317. private double _TransformY;
  1318. /// <summary>
  1319. /// 转换后的机器人坐标Y
  1320. /// </summary>
  1321. public double TransformY
  1322. {
  1323. get { return _TransformY; }
  1324. set { SetProperty(ref _TransformY, value); }
  1325. }
  1326. public DynamicTestResult()
  1327. { }
  1328. public DynamicTestResult(int index, bool isPhotoSuccess, RPoint pointB, double cycleTime, double pixelX, double pixelY, double angleU, double transformX, double transformY)
  1329. {
  1330. Index = index;
  1331. Timestamp = DateTime.Now;
  1332. IsPhotoSuccess = isPhotoSuccess;
  1333. PointB = pointB;
  1334. CycleTime = cycleTime;
  1335. PixelX = pixelX;
  1336. PixelY = pixelY;
  1337. AngleU = angleU;
  1338. TransformX = transformX;
  1339. TransformY = transformY;
  1340. }
  1341. }
  1342. /// <summary>
  1343. /// 精度分析结果
  1344. /// </summary>
  1345. public class PrecisionAnalysisResult : BindableBase
  1346. {
  1347. private double _xPrecision;
  1348. /// <summary>
  1349. /// X方向精度(标准差)
  1350. /// </summary>
  1351. public double XPrecision
  1352. {
  1353. get { return _xPrecision; }
  1354. set { SetProperty(ref _xPrecision, value); }
  1355. }
  1356. private double _yPrecision;
  1357. /// <summary>
  1358. /// Y方向精度(标准差)
  1359. /// </summary>
  1360. public double YPrecision
  1361. {
  1362. get { return _yPrecision; }
  1363. set { SetProperty(ref _yPrecision, value); }
  1364. }
  1365. private double _anglePrecision;
  1366. /// <summary>
  1367. /// 角度精度(标准差)
  1368. /// </summary>
  1369. public double AnglePrecision
  1370. {
  1371. get { return _anglePrecision; }
  1372. set { SetProperty(ref _anglePrecision, value); }
  1373. }
  1374. private double _xThreeSigmaRange;
  1375. /// <summary>
  1376. /// X方向3σ范围
  1377. /// </summary>
  1378. public double XThreeSigmaRange
  1379. {
  1380. get { return _xThreeSigmaRange; }
  1381. set { SetProperty(ref _xThreeSigmaRange, value); }
  1382. }
  1383. private double _yThreeSigmaRange;
  1384. /// <summary>
  1385. /// Y方向3σ范围
  1386. /// </summary>
  1387. public double YThreeSigmaRange
  1388. {
  1389. get { return _yThreeSigmaRange; }
  1390. set { SetProperty(ref _yThreeSigmaRange, value); }
  1391. }
  1392. private double _angleThreeSigmaRange;
  1393. /// <summary>
  1394. /// 角度3σ范围
  1395. /// </summary>
  1396. public double AngleThreeSigmaRange
  1397. {
  1398. get { return _angleThreeSigmaRange; }
  1399. set { SetProperty(ref _angleThreeSigmaRange, value); }
  1400. }
  1401. private double _xMean;
  1402. /// <summary>
  1403. /// X方向平均值
  1404. /// </summary>
  1405. public double XMean
  1406. {
  1407. get { return _xMean; }
  1408. set { SetProperty(ref _xMean, value); }
  1409. }
  1410. private double _yMean;
  1411. /// <summary>
  1412. /// Y方向平均值
  1413. /// </summary>
  1414. public double YMean
  1415. {
  1416. get { return _yMean; }
  1417. set { SetProperty(ref _yMean, value); }
  1418. }
  1419. private double _angleMean;
  1420. /// <summary>
  1421. /// 角度平均值
  1422. /// </summary>
  1423. public double AngleMean
  1424. {
  1425. get { return _angleMean; }
  1426. set { SetProperty(ref _angleMean, value); }
  1427. }
  1428. private double _xRange;
  1429. /// <summary>
  1430. /// X方向极差
  1431. /// </summary>
  1432. public double XRange
  1433. {
  1434. get { return _xRange; }
  1435. set { SetProperty(ref _xRange, value); }
  1436. }
  1437. private double _yRange;
  1438. /// <summary>
  1439. /// Y方向极差
  1440. /// </summary>
  1441. public double YRange
  1442. {
  1443. get { return _yRange; }
  1444. set { SetProperty(ref _yRange, value); }
  1445. }
  1446. private double _angleRange;
  1447. /// <summary>
  1448. /// 角度极差
  1449. /// </summary>
  1450. public double AngleRange
  1451. {
  1452. get { return _angleRange; }
  1453. set { SetProperty(ref _angleRange, value); }
  1454. }
  1455. private double _xKurtosis;
  1456. /// <summary>
  1457. /// X方向峰度
  1458. /// </summary>
  1459. public double XKurtosis
  1460. {
  1461. get { return _xKurtosis; }
  1462. set { SetProperty(ref _xKurtosis, value); }
  1463. }
  1464. private double _yKurtosis;
  1465. /// <summary>
  1466. /// Y方向峰度
  1467. /// </summary>
  1468. public double YKurtosis
  1469. {
  1470. get { return _yKurtosis; }
  1471. set { SetProperty(ref _yKurtosis, value); }
  1472. }
  1473. private double _xCpk;
  1474. /// <summary>
  1475. /// X方向CPK
  1476. /// </summary>
  1477. public double XCpk
  1478. {
  1479. get { return _xCpk; }
  1480. set { SetProperty(ref _xCpk, value); }
  1481. }
  1482. private double _yCpk;
  1483. /// <summary>
  1484. /// Y方向CPK
  1485. /// </summary>
  1486. public double YCpk
  1487. {
  1488. get { return _yCpk; }
  1489. set { SetProperty(ref _yCpk, value); }
  1490. }
  1491. private double _angleCpk;
  1492. /// <summary>
  1493. /// 角度CPK
  1494. /// </summary>
  1495. public double AngleCpk
  1496. {
  1497. get { return _angleCpk; }
  1498. set { SetProperty(ref _angleCpk, value); }
  1499. }
  1500. private double _overallPrecision;
  1501. /// <summary>
  1502. /// 综合精度(XY合成标准差)
  1503. /// </summary>
  1504. public double OverallPrecision
  1505. {
  1506. get { return _overallPrecision; }
  1507. set { SetProperty(ref _overallPrecision, value); }
  1508. }
  1509. private double _overallThreeSigmaRange;
  1510. /// <summary>
  1511. /// 综合3σ范围
  1512. /// </summary>
  1513. public double OverallThreeSigmaRange
  1514. {
  1515. get { return _overallThreeSigmaRange; }
  1516. set { SetProperty(ref _overallThreeSigmaRange, value); }
  1517. }
  1518. private string _processRating;
  1519. /// <summary>
  1520. /// 过程能力评级
  1521. /// </summary>
  1522. public string ProcessRating
  1523. {
  1524. get { return _processRating; }
  1525. set { SetProperty(ref _processRating, value); }
  1526. }
  1527. /// <summary>
  1528. /// 获取CPK评级描述
  1529. /// </summary>
  1530. public string GetCpkRating(double cpk)
  1531. {
  1532. if (cpk >= 1.67)
  1533. return "卓越";
  1534. else if (cpk >= 1.33)
  1535. return "良好";
  1536. else if (cpk >= 1.00)
  1537. return "可接受";
  1538. else if (cpk >= 0.67)
  1539. return "不足";
  1540. else
  1541. return "严重不足";
  1542. }
  1543. }
  1544. }