VisionDynamicAccuracyAnalyzerViewModel.cs 70 KB

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