VisionDynamicAccuracyAnalyzerViewModel.cs 70 KB

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