VisionDynamicAccuracyAnalyzerViewModel.cs 71 KB

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