VisionDynamicAccuracyAnalyzerViewModel.cs 71 KB

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