VisionDynamicAccuracyAnalyzerViewModel.cs 82 KB

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