CalibrationAutoViewModel.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. using MathNet.Numerics.LinearAlgebra;
  2. using NPOI.SS.Formula.Functions;
  3. using OpenCvSharp;
  4. using Prism.Commands;
  5. using Prism.Events;
  6. using Prism.Ioc;
  7. using Prism.Mvvm;
  8. using Prism.Regions;
  9. using Prism.Services.Dialogs;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Threading.Tasks;
  14. using System.Windows;
  15. using Team.FFFeederService.Interfaces;
  16. using TeamAAS_VP.Events;
  17. using TeamAAS_VP.Core;
  18. using TeamAAS_VP.Interfaces;
  19. using TeamAAS_VP.Models;
  20. using static NPOI.POIFS.Crypt.CryptoFunctions;
  21. using TeamAAS_VP;
  22. using Cognex.VisionPro;
  23. using System.Drawing;
  24. using Cognex.VisionPro.ToolBlock;
  25. using TeamAAS_VP.Resources.Languages;
  26. using TeamAAS_VP.Models.Calibration;
  27. using TeamAAS_VP.Models.Robot;
  28. using TeamAAS_VP.Services;
  29. using System.Threading;
  30. namespace TeamAAS_VP.ViewModels.Calibration
  31. {
  32. public class CalibrationAutoViewModel : BindableBase, IConfirmNavigationRequest
  33. {
  34. IRegionManager _regionManager;
  35. IRegionNavigationService _regionNavigationService;
  36. IContainerProvider _container;
  37. IDialogService _dialogService;
  38. IEventAggregator _eventAggregator;
  39. IRobotService _robotService;
  40. IFeederService _feederService;
  41. ICameraService _cameraService;
  42. ISystemDatabaseService _systemDatabaseService;
  43. ICameraCalibrationService _cameraCalibrationService;
  44. private CancellationTokenSource _cts;
  45. #region 属性
  46. private ICogImage _Image;
  47. public ICogImage Image
  48. {
  49. get { return _Image; }
  50. set { SetProperty(ref _Image, value); }
  51. }
  52. private Cognex.VisionPro.CogGraphicCollection _Graphic;
  53. public Cognex.VisionPro.CogGraphicCollection Graphic
  54. {
  55. get { return _Graphic; }
  56. set { SetProperty(ref _Graphic, value); }
  57. }
  58. private CalibrationInfo _SelectCalibration;
  59. public CalibrationInfo SelectCalibration
  60. {
  61. get { return _SelectCalibration; }
  62. set { SetProperty(ref _SelectCalibration, value); }
  63. }
  64. public Management management { get; set; }
  65. public IRobot Robot { get; set; }
  66. public IVoiceCoilMotorFeeder Feeder { get; set; }
  67. private bool _IsRunning = true;
  68. public bool IsRunning
  69. {
  70. get { return _IsRunning; }
  71. set { SetProperty(ref _IsRunning, value); }
  72. }
  73. private ICamera _Camera;
  74. public ICamera Camera
  75. {
  76. get { return _Camera; }
  77. set { SetProperty(ref _Camera, value); }
  78. }
  79. #endregion
  80. #region 命令
  81. private DelegateCommand _LoadedCommand;
  82. public DelegateCommand LoadedCommand =>
  83. _LoadedCommand ?? (_LoadedCommand = new DelegateCommand(ExecuteLoadedCommand));
  84. private DelegateCommand _NextCommand;
  85. public DelegateCommand NextCommand =>
  86. _NextCommand ?? (_NextCommand = new DelegateCommand(ExecuteNextCommand).ObservesCanExecute(() => IsRunning));
  87. private DelegateCommand _BackCommand;
  88. public DelegateCommand BackCommand =>
  89. _BackCommand ?? (_BackCommand = new DelegateCommand(ExecuteBackCommand).ObservesCanExecute(() => IsRunning));
  90. private DelegateCommand _StartCalibCommand;
  91. public DelegateCommand StartCalibCommand =>
  92. _StartCalibCommand ?? (_StartCalibCommand = new DelegateCommand(ExecuteStartCalibCommand).ObservesCanExecute(() => IsRunning));
  93. #endregion
  94. #region 事件
  95. #endregion
  96. public CalibrationAutoViewModel(IRegionManager regionManager, IEventAggregator ea, IRegionNavigationService regionNavigationService, IContainerProvider container, IDialogService dialogService,
  97. IRobotService robotService, IFeederService feederService,ICameraService cameraService,ISystemDatabaseService systemDatabaseService, ICameraCalibrationService cameraCalibrationService)
  98. {
  99. _regionManager = regionManager;
  100. _regionNavigationService = regionNavigationService;
  101. _container = container;
  102. _dialogService = dialogService;
  103. _robotService = robotService;
  104. _eventAggregator = ea;
  105. _feederService = feederService;
  106. _cameraService = cameraService;
  107. _systemDatabaseService = systemDatabaseService;
  108. _cameraCalibrationService = cameraCalibrationService;
  109. }
  110. #region 方法
  111. void ExecuteLoadedCommand()
  112. {
  113. try
  114. {
  115. if (_systemDatabaseService.GetCurrentUser().userPart == Enums.UserPart.Operator)
  116. {
  117. IsAllowEdit = false;
  118. }
  119. else
  120. {
  121. IsAllowEdit = true;
  122. }
  123. }
  124. catch (Exception ex)
  125. {
  126. LogHelper.WriteLogError("9点校准界面加载时出错!", ex);
  127. MessageBox.Show(ex.ToString());
  128. }
  129. }
  130. async void ExecuteStartCalibCommand()
  131. {
  132. try
  133. {
  134. if (MessageBox.Show(Lang.是否开始自动校准, $"{Lang.自动校准}", MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK) return;
  135. IsRunning = false;
  136. _cts=new CancellationTokenSource();
  137. (bool IsSuccess, Matrix<double> AffineTransformationMaterial, RobotPixelPoint[] NinePoint, CalibrationResult Result) = await _cameraCalibrationService.AutoNinePointCalibration(SelectCalibration, Robot, _cts.Token);
  138. if (!IsSuccess)
  139. {
  140. MessageBox.Show("相机校准失败", $"{Lang.自动校准}", MessageBoxButton.OK, MessageBoxImage.Warning);
  141. return;
  142. }
  143. SelectCalibration.AffineTransformationMaterial = AffineTransformationMaterial.ToArray();
  144. SelectCalibration.CalibPoints = new System.Collections.ObjectModel.ObservableCollection<RobotPixelPoint>(NinePoint);
  145. SelectCalibration.CalibrationResult = Result;
  146. DialogParameters parameters = new DialogParameters();
  147. parameters.Add("Result", Result);
  148. _dialogService.Show("ShowCalibrationResult", parameters, rst =>
  149. {
  150. //对话框关闭之后的回调函数,可以在这解析结果。
  151. ButtonResult result1 = rst.Result;
  152. if (result1 == ButtonResult.OK)
  153. {
  154. NavigationParameters param = new NavigationParameters();
  155. param.Add("SelectCalibration", SelectCalibration);
  156. _regionManager.RequestNavigate("CalibrationRegionContext", "CalibrationVerification",param);
  157. }
  158. });
  159. }
  160. catch (Exception ex)
  161. {
  162. LogHelper.WriteLogError("9点校准时出错!", ex);
  163. MessageBox.Show(ex.Message);
  164. }
  165. finally
  166. {
  167. try
  168. {
  169. if (_cts != null && !_cts.IsCancellationRequested)
  170. _cts.Cancel();
  171. _cts?.Dispose();
  172. _cts = null;
  173. }
  174. catch (Exception)
  175. {
  176. }
  177. IsRunning = true;
  178. }
  179. }
  180. /// <summary>
  181. /// 下一步
  182. /// </summary>
  183. void ExecuteNextCommand()
  184. {
  185. NavigationParameters param = new NavigationParameters();
  186. param.Add("SelectCalibration", SelectCalibration);
  187. _regionManager.RequestNavigate("CalibrationRegionContext", "CalibrationVerification", param);
  188. }
  189. /// <summary>
  190. /// 上一步
  191. /// </summary>
  192. void ExecuteBackCommand()
  193. {
  194. NavigationParameters param = new NavigationParameters();
  195. param.Add("SelectCalibration", SelectCalibration);
  196. if (SelectCalibration.CameraMount == Enums.CameraMount.MobileDown_XYPlatform)
  197. {
  198. if (SelectCalibration.CalibTechP0Mode == Enums.CalibTechP0Mode.CameraFindP0)
  199. {
  200. _regionManager.RequestNavigate("CalibrationRegionContext", "FixedUpCameraFindP0", param);
  201. return;
  202. }
  203. else
  204. {
  205. _regionManager.RequestNavigate("CalibrationRegionContext", "CalibrationTeachCenterPoint", param);
  206. }
  207. }
  208. //else if (Robot.Brand == Enums.RobotBrand.XYZ_Platform)
  209. //{
  210. // _regionManager.RequestNavigate("CalibrationRegionContext", "CalibrationTeachCenterPoint", param);
  211. //}
  212. else
  213. {
  214. _regionManager.RequestNavigate("CalibrationRegionContext", "CalibrationSelectTool", param);
  215. }
  216. }
  217. /// <summary>
  218. /// 相机拍照
  219. /// </summary>
  220. /// <returns></returns>
  221. private async Task<(bool IsSuccess, double X, double Y, double U, int ImageWidth, int ImageHeight)> CaptureAndProcess()
  222. {
  223. if (Feeder != null)
  224. {
  225. Feeder.OpenLight();
  226. Feeder.SetLightTimeOut((ushort)SelectCalibration.Brightness);
  227. }
  228. await Task.Delay(200);
  229. //采集图像
  230. if (Camera != null)
  231. {
  232. SelectCalibration.ToolBlock.Inputs["InputImage"].Value = Camera.Grab();
  233. }
  234. App.Current.Dispatcher.Invoke(() =>
  235. {
  236. Graphic = null;
  237. Image = (ICogImage)SelectCalibration.ToolBlock.Inputs["InputImage"].Value;
  238. });
  239. SelectCalibration.ToolBlock.Run();
  240. CogToolBlockTerminalCollection outputCollection = SelectCalibration.ToolBlock.Outputs;
  241. App.Current.Dispatcher.Invoke(() =>
  242. {
  243. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection;
  244. });
  245. bool Found = (bool)(outputCollection["Found"].Value);
  246. if (Found)
  247. {
  248. var strpoints = outputCollection["Point"].Value.ToString();
  249. string[] items = strpoints.Split(',');
  250. double x = double.Parse(items[0]);
  251. double y = double.Parse(items[1]);
  252. return (true, x, y, 0, Image.Width, Image.Height);
  253. }
  254. else
  255. {
  256. return (false, 0, 0, 0, Image.Width, Image.Height);
  257. }
  258. }
  259. #endregion
  260. #region 继承
  261. /// <summary>
  262. /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。
  263. /// </summary>
  264. /// <param name="navigationContext"></param>
  265. /// <param name="continuationCallback"></param>
  266. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  267. {
  268. continuationCallback(true);
  269. }
  270. /// <summary>
  271. /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。
  272. /// </summary>
  273. /// <param name="navigationContext"></param>
  274. /// <exception cref="NotImplementedException"></exception>
  275. public async void OnNavigatedTo(NavigationContext navigationContext)
  276. {
  277. SelectCalibration = navigationContext.Parameters.GetValue<CalibrationInfo>("SelectCalibration");
  278. if (SelectCalibration != null)
  279. {
  280. Robot = _robotService.GetRobot(SelectCalibration.RobotId);
  281. if (SelectCalibration.FeederId != Guid.Empty)
  282. {
  283. Feeder = _feederService.GetFeeder(SelectCalibration.FeederId);
  284. }
  285. }
  286. Camera = _cameraService.GetCamera(SelectCalibration.CameraID);
  287. _cameraCalibrationService.CaptureAndProcessCallback = null;
  288. _cameraCalibrationService.CaptureAndProcessCallback= CaptureAndProcess;
  289. }
  290. /// <summary>
  291. /// 是否允许导航到此视图模型。
  292. /// </summary>
  293. /// <param name="navigationContext"></param>
  294. /// <returns></returns>
  295. public bool IsNavigationTarget(NavigationContext navigationContext)
  296. {
  297. return true;
  298. }
  299. /// <summary>
  300. /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。
  301. /// </summary>
  302. /// <param name="navigationContext"></param>
  303. public void OnNavigatedFrom(NavigationContext navigationContext)
  304. {
  305. _cameraCalibrationService.CaptureAndProcessCallback = null;
  306. }
  307. #endregion
  308. private bool _IsAllowEdit = false;
  309. public bool IsAllowEdit
  310. {
  311. get { return _IsAllowEdit; }
  312. set { SetProperty(ref _IsAllowEdit, value); }
  313. }
  314. private void LoginChange(Models.User user)
  315. {
  316. if (user.userPart == Enums.UserPart.Operator)
  317. {
  318. IsAllowEdit = false;
  319. }
  320. else
  321. {
  322. IsAllowEdit = true;
  323. }
  324. }
  325. }
  326. }