VisionDynamicAccuracyAnalyzerViewModel.cs 72 KB

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