VisionDynamicAccuracyAnalyzerViewModel.cs 71 KB

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