VisionDynamicAccuracyAnalyzerViewModel.cs 73 KB

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