VisionDynamicAccuracyAnalyzerViewModel.cs 68 KB

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