VisionDynamicAccuracyAnalyzerViewModel.cs 70 KB

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