CalibToolViewModel.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. using Cognex.VisionPro;
  2. using Cognex.VisionPro.ToolBlock;
  3. using MaterialDesignThemes.Wpf;
  4. using MathNet.Numerics;
  5. using MathNet.Numerics.LinearAlgebra;
  6. using NPOI.SS.Formula.Functions;
  7. using OpenCvSharp;
  8. using Prism.Commands;
  9. using Prism.Events;
  10. using Prism.Ioc;
  11. using Prism.Mvvm;
  12. using Prism.Regions;
  13. using Prism.Services.Dialogs;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Drawing;
  17. using System.Linq;
  18. using System.Reflection.Metadata;
  19. using System.Text;
  20. using System.Threading.Tasks;
  21. using System.Windows;
  22. using System.Windows.Media.Media3D;
  23. using Team.FFFeederService.Interfaces;
  24. using TeamAAS_VP.Controls;
  25. using TeamAAS_VP.Core;
  26. using TeamAAS_VP.Events;
  27. using TeamAAS_VP.Interfaces;
  28. using TeamAAS_VP.Models;
  29. using TeamAAS_VP;
  30. using static OpenCvSharp.LineIterator;
  31. using TeamAAS_VP.Resources.Languages;
  32. using TeamAAS_VP.Models.Calibration;
  33. using TeamAAS_VP.Services;
  34. using System.Threading;
  35. namespace TeamAAS_VP.ViewModels.Calibration
  36. {
  37. public class CalibToolViewModel : BindableBase, IDialogAware
  38. {
  39. IRegionManager _regionManager;
  40. IRegionNavigationService _regionNavigationService;
  41. IContainerProvider _container;
  42. IDialogService _dialogService;
  43. IEventAggregator _eventAggregator;
  44. IConfigService _configService;
  45. IRobotService _robotService;
  46. ICameraService _cameraService;
  47. IFeederService _feederService;
  48. ICameraCalibrationService _cameraCalibrationService;
  49. private CancellationTokenSource _cts;
  50. #region 属性
  51. private ICogImage _Image;
  52. public ICogImage Image
  53. {
  54. get { return _Image; }
  55. set { SetProperty(ref _Image, value); }
  56. }
  57. private Cognex.VisionPro.CogGraphicCollection _Graphic;
  58. public Cognex.VisionPro.CogGraphicCollection Graphic
  59. {
  60. get { return _Graphic; }
  61. set { SetProperty(ref _Graphic, value); }
  62. }
  63. private CalibrationInfo _SelectCalibration;
  64. public CalibrationInfo SelectCalibration
  65. {
  66. get { return _SelectCalibration; }
  67. set { SetProperty(ref _SelectCalibration, value); }
  68. }
  69. public string Title=> "校准工具坐标";
  70. private double _Angle = 180;
  71. /// <summary>
  72. /// 机器人移动的范围U
  73. /// </summary>
  74. public double Angle
  75. {
  76. get { return _Angle; }
  77. set { SetProperty(ref _Angle, value); }
  78. }
  79. public RobotTool Tool { get; set; }
  80. /// <summary>
  81. /// 机器人与相机之间的旋转矩阵
  82. /// </summary>
  83. public Matrix<double> RobotCameraRotationMatrix { get; set; }
  84. public Management management { get; set; }
  85. public IRobot Robot { get; set; }
  86. public IVoiceCoilMotorFeeder Feeder { get; set; }
  87. private bool _IsRunning=true;
  88. public bool IsRunning
  89. {
  90. get { return _IsRunning; }
  91. set { SetProperty(ref _IsRunning,value); }
  92. }
  93. private ICamera _Camera;
  94. public ICamera Camera
  95. {
  96. get { return _Camera; }
  97. set { SetProperty(ref _Camera, value); }
  98. }
  99. #endregion
  100. #region 命令
  101. private DelegateCommand _ConfirmCommand;
  102. public DelegateCommand ConfirmCommand =>
  103. _ConfirmCommand ?? (_ConfirmCommand = new DelegateCommand(ExecuteConfirmCommand).ObservesCanExecute(() => IsRunning));
  104. private DelegateCommand _CancelCommand;
  105. public DelegateCommand CancelCommand =>
  106. _CancelCommand ?? (_CancelCommand = new DelegateCommand(ExecuteCancelCommand).ObservesCanExecute(() => IsRunning));
  107. private DelegateCommand _StartCalibCommand;
  108. public DelegateCommand StartCalibCommand =>
  109. _StartCalibCommand ?? (_StartCalibCommand = new DelegateCommand(ExecuteStartCalibCommand).ObservesCanExecute(()=> IsRunning));
  110. #endregion
  111. #region 事件
  112. public event Action<IDialogResult> RequestClose;
  113. #endregion
  114. public CalibToolViewModel(IRegionManager regionManager, IEventAggregator ea, IRegionNavigationService regionNavigationService, IContainerProvider container, IDialogService dialogService,
  115. IConfigService configService, IRobotService robotService, ICameraService cameraService, IFeederService feederService, ICameraCalibrationService cameraCalibrationService)
  116. {
  117. _regionManager = regionManager;
  118. _regionNavigationService = regionNavigationService;
  119. _container = container;
  120. _dialogService = dialogService;
  121. _eventAggregator = ea;
  122. _configService = configService;
  123. _robotService = robotService;
  124. _cameraService = cameraService;
  125. _feederService = feederService;
  126. _cameraCalibrationService = cameraCalibrationService;
  127. }
  128. #region 方法
  129. /// <summary>
  130. /// 确定
  131. /// </summary>
  132. void ExecuteConfirmCommand()
  133. {
  134. if (Tool==null)
  135. {
  136. return;
  137. }
  138. IDialogParameters parameters = new DialogParameters();
  139. parameters.Add("Tool", Tool);
  140. parameters.Add("RobotCameraRotationMatrix", RobotCameraRotationMatrix);
  141. parameters.Add("Angle", Angle);
  142. RequestClose?.Invoke(new DialogResult(ButtonResult.OK, parameters));
  143. }
  144. /// <summary>
  145. /// 取消
  146. /// </summary>
  147. void ExecuteCancelCommand()
  148. {
  149. IDialogParameters parameters = new DialogParameters();
  150. parameters.Add("Tool", Tool);
  151. RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel, parameters));
  152. }
  153. /// <summary>
  154. /// 开始校准
  155. /// </summary>
  156. async void ExecuteStartCalibCommand()
  157. {
  158. if (SelectCalibration == null) return;
  159. if (Robot == null || !Robot.IsConnected) return;
  160. Robot.Timeout = 600000;
  161. try
  162. {
  163. if (Angle == 0)
  164. Angle = 10;
  165. var view = new ShowMessage(Lang.Tool校准, Lang.是否开始自动校准工具坐标);
  166. //show the dialog
  167. var result = await DialogHost.Show(view, "CalibToolDialog", null, null, (sender,e) =>{
  168. try
  169. {
  170. if (_cts != null && !_cts.IsCancellationRequested)
  171. {
  172. _cts.Cancel();
  173. _cts.Dispose();
  174. _cts = null;
  175. }
  176. }
  177. catch (Exception)
  178. {
  179. }
  180. });
  181. if (!((bool)result)) return;
  182. IsRunning = false;
  183. SelectCalibration.Angle = Angle;
  184. _cts = new CancellationTokenSource();
  185. var toolResult = await _cameraCalibrationService.CalibrateUncalibratedCameraTool(SelectCalibration, Robot, _cts.Token);
  186. if (toolResult.IsSuccess)
  187. {
  188. if (Tool == null)
  189. {
  190. Tool = new RobotTool();
  191. }
  192. Tool.X = toolResult.ToolX;
  193. Tool.Y = toolResult.ToolY;
  194. RobotCameraRotationMatrix = toolResult.RotationMatrix;
  195. //MessageBox.Show("校准完成");
  196. view = new ShowMessage(Lang.Tool校准, Lang.校准完成, false);
  197. await DialogHost.Show(view, "CalibToolDialog", null, null, null);
  198. IDialogParameters parameters = new DialogParameters();
  199. parameters.Add("Tool", Tool);
  200. parameters.Add("RobotCameraRotationMatrix", RobotCameraRotationMatrix);
  201. parameters.Add("Angle", Angle);
  202. RequestClose?.Invoke(new DialogResult(ButtonResult.OK, parameters));
  203. }
  204. else
  205. {
  206. view = new ShowMessage(Lang.Tool校准, Lang.校准失败, false);
  207. //show the dialog
  208. await DialogHost.Show(view, "CalibToolDialog", null, null, null);
  209. }
  210. }
  211. catch (Exception ex)
  212. {
  213. LogHelper.WriteLogError("相机校准-校准验证界面示加载时出错!", ex);
  214. var view = new ShowMessage(Lang.Tool校准, $"{ex.Message}", false);
  215. //show the dialog
  216. var result = await DialogHost.Show(view, "CalibToolDialog", null, null, null);
  217. }
  218. finally
  219. {
  220. try
  221. {
  222. if (_cts != null && !_cts.IsCancellationRequested)
  223. {
  224. _cts.Cancel();
  225. _cts.Dispose();
  226. }
  227. _cts = null;
  228. }
  229. catch (Exception)
  230. {
  231. }
  232. IsRunning = true;
  233. }
  234. }
  235. public bool CanCloseDialog()
  236. {
  237. return true;
  238. }
  239. public void OnDialogClosed()
  240. {
  241. _cameraCalibrationService.CaptureAndProcessCallback = null;
  242. }
  243. public void OnDialogOpened(IDialogParameters parameters)
  244. {
  245. SelectCalibration = parameters.GetValue<CalibrationInfo>("SelectCalibration");
  246. management = _container.Resolve<Management>();
  247. if (SelectCalibration != null)
  248. {
  249. Camera = _cameraService.GetCamera(SelectCalibration.CameraID);
  250. Robot = _robotService.GetRobot(SelectCalibration.RobotId);
  251. if (SelectCalibration.FeederId!=Guid.Empty)
  252. {
  253. Feeder = _feederService.GetFeeder(SelectCalibration.FeederId);
  254. }
  255. Angle = SelectCalibration.Angle;
  256. }
  257. _cameraCalibrationService.CaptureAndProcessCallback = null;
  258. _cameraCalibrationService.CaptureAndProcessCallback = CaptureAndProcess;
  259. }
  260. /// <summary>
  261. /// 相机拍照
  262. /// </summary>
  263. /// <returns></returns>
  264. private async Task<(bool IsSuccess, double X, double Y, double U, int ImageWidth, int ImageHeight)> CaptureAndProcess()
  265. {
  266. if (Feeder != null)
  267. {
  268. Feeder.OpenLight();
  269. Feeder.SetLightTimeOut((ushort)SelectCalibration.Brightness);
  270. }
  271. await Task.Delay(200);
  272. //采集图像
  273. if (Camera != null)
  274. {
  275. SelectCalibration.ToolBlock.Inputs["InputImage"].Value = Camera.Grab();
  276. }
  277. App.Current.Dispatcher.Invoke(() =>
  278. {
  279. Image = (ICogImage)SelectCalibration.ToolBlock.Inputs["InputImage"].Value;
  280. Graphic = null;
  281. });
  282. SelectCalibration.ToolBlock.Run();
  283. CogToolBlockTerminalCollection outputCollection = SelectCalibration.ToolBlock.Outputs;
  284. App.Current.Dispatcher.Invoke(() =>
  285. {
  286. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection;
  287. });
  288. bool Found = (bool)(outputCollection["Found"].Value);
  289. if (Found)
  290. {
  291. var strpoints = outputCollection["Point"].Value.ToString();
  292. string[] items = strpoints.Split(',');
  293. double x = double.Parse(items[0]);
  294. double y = double.Parse(items[1]);
  295. return (true, x, y, 0, Image.Width, Image.Height);
  296. }
  297. else
  298. {
  299. return (false, 0, 0, 0, Image.Width, Image.Height);
  300. }
  301. }
  302. #endregion
  303. }
  304. }