VisionDynamicAccuracyAnalyzerViewModel.cs 73 KB

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