using Cognex.VisionPro; using MahApps.Metro.Controls; using MaterialDesignThemes.Wpf; using MathNet.Numerics.LinearAlgebra; using NPOI.SS.Formula.Functions; using OpenCvSharp.Flann; using Prism.Commands; using Prism.Events; using Prism.Ioc; using Prism.Mvvm; using Prism.Regions; using Prism.Services.Dialogs; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using TeamAAS_VP.Controls; using TeamAAS_VP.Core; using TeamAAS_VP.Core.PLCs; using TeamAAS_VP.Core.Robots; using TeamAAS_VP.DxfModule; using TeamAAS_VP.Enums; using TeamAAS_VP.Events; using TeamAAS_VP.Interfaces; using TeamAAS_VP.Models; using TeamAAS_VP.Models.PLC; using TeamAAS_VP.Models.Robot; using TeamAAS_VP.Resources.Languages; using TeamAAS_VP.Services; using TeamAAS_VP.Views.Product; using static TeamAAS_VP.ViewModels.Product.AutoCorrectLockPointViewModel; namespace TeamAAS_VP.ViewModels.Product { public class PlcPointParamsViewModel : BindableBase, IConfirmNavigationRequest { IRegionManager _regionManager; IEventAggregator _eventAggregator; IContainerProvider _container; IDialogService _dialogService; IConfigService _configService; IRobotService _robotService; ISystemDatabaseService _systemDatabaseService; IRemoteCommandService _remoteCommandService; ICalibrationService _calibrationService; ICameraService _cameraService; IProductService _productService; #region 属性 private ObservableCollection _AdditionalAxisList; public ObservableCollection AdditionalAxisList { get { return _AdditionalAxisList; } set { SetProperty(ref _AdditionalAxisList, value); } } private ProductModel _SelectProduct; /// /// 选中的产品 /// public ProductModel SelectProduct { get { return _SelectProduct; } set { SetProperty(ref _SelectProduct, value); } } private PlcPoint _SelectedPoint; public PlcPoint SelectedPoint { get { return _SelectedPoint; } set { SetProperty(ref _SelectedPoint, value); } } private PlcPoint _selectedPointInDataGrid; public PlcPoint SelectedPointInDataGrid { get { return _selectedPointInDataGrid; } set { if (SetProperty(ref _selectedPointInDataGrid, value)) { SelectedPointInComboBox = value; // update command availability _MovePointUpCommand?.RaiseCanExecuteChanged(); _MovePointDownCommand?.RaiseCanExecuteChanged(); // 更新依赖可执行状态的命令 _TechPointCommand?.RaiseCanExecuteChanged(); _ExecuteMotion?.RaiseCanExecuteChanged(); } // 可以同步到 SelectPoint 属性 SelectedPoint = value; } } private PlcPoint _selectedPointInComboBox; public PlcPoint SelectedPointInComboBox { get { return _selectedPointInComboBox; } set { if (SetProperty(ref _selectedPointInComboBox, value)) { SelectedPointInDataGrid = value; } // 可以同步到 SelectPoint 属性 SelectedPoint = value; } } private ObservableCollection _Points = new ObservableCollection(); /// /// 点位集合 /// public ObservableCollection Points { get { return _Points; } set { SetProperty(ref _Points, value); } } private MotionCommand _SelectMotionCommand; /// /// 选中的运动指令 /// public MotionCommand SelectMotionCommand { get { return _SelectMotionCommand; } set { SetProperty(ref _SelectMotionCommand, value); } } public Management management { get; set; } private XYZU_Robot _Robot; public XYZU_Robot Robot { get { return _Robot; } set { SetProperty(ref _Robot, value); } } private int _SelectedIndex; public int SelectedIndex { get { return _SelectedIndex; } set { SetProperty(ref _SelectedIndex, value); } } private double _Distance = 1; public double Distance { get { return _Distance; } set { SetProperty(ref _Distance, value); try { if (Robot == null) { return; } _configService.UpdateRobotStepDistance(Robot.Id, value); } catch (Exception) { } } } private ObservableCollection _ProcedureModels; /// /// 流程集合 /// public ObservableCollection ProcedureModels { get { return _ProcedureModels; } set { SetProperty(ref _ProcedureModels, value); } } private ProcedureModel _SelectProcedure; /// /// 选中的流程 /// public ProcedureModel SelectProcedure { get { return _SelectProcedure; } set { SetProperty(ref _SelectProcedure, value); } } private bool _IsGrap; public bool IsGrap { get { return _IsGrap; } set { SetProperty(ref _IsGrap, value); } } private ObservableCollection _CameraList; public ObservableCollection CameraList { get { return _CameraList; } set { SetProperty(ref _CameraList, value); } } private CameraInfo _SelectedCamera; public CameraInfo SelectedCamera { get { return _SelectedCamera; } set { SetProperty(ref _SelectedCamera, value); if (value != null) { if (Camera != null) { if (Camera.IsGrabbing) { Camera.StopGrabbing(); } Camera.ImageCallbackEvent -= Camera_ImageCallbackEvent; } Camera = _cameraService.GetCamera(value.Id); Camera.ImageCallbackEvent += Camera_ImageCallbackEvent; } } } private ICamera _Camera; public ICamera Camera { get { return _Camera; } set { SetProperty(ref _Camera, value); } } private ICogImage _Image; public ICogImage Image { get { return _Image; } set { SetProperty(ref _Image, value); } } private string _Message; public string Message { get { return _Message; } set { SetProperty(ref _Message, value); } } private bool _IsLeftDrawerOpen; public bool IsLeftDrawerOpen { get { return _IsLeftDrawerOpen; } set { SetProperty(ref _IsLeftDrawerOpen, value); if (!value) { if (IsGrap) { ExecuteStopGrabbingCommand(); } } } } private int _Inhal = 1; /// /// 吸真空编号 /// public int Inhal { get { return _Inhal; } set { SetProperty(ref _Inhal, value); } } private PalletEx _Pallet1; /// /// 托盘1 /// public PalletEx Pallet1 { get { return _Pallet1; } set { SetProperty(ref _Pallet1, value); } } private PalletEx _Pallet2; /// /// 托盘2 /// public PalletEx Pallet2 { get { return _Pallet2; } set { SetProperty(ref _Pallet2, value); } } #endregion #region 命令 private DelegateCommand _NextCommand; public DelegateCommand NextCommand => _NextCommand ?? (_NextCommand = new DelegateCommand(ExecuteNextCommand)); private DelegateCommand _BackCommand; public DelegateCommand BackCommand => _BackCommand ?? (_BackCommand = new DelegateCommand(ExecuteBackCommand)); private DelegateCommand _LoadedCommand; public DelegateCommand LoadedCommand => _LoadedCommand ?? (_LoadedCommand = new DelegateCommand(ExecuteLoadedCommand)); private DelegateCommand _ExecuteMotion; public DelegateCommand ExecuteMotion => _ExecuteMotion ?? (_ExecuteMotion = new DelegateCommand(ExecuteExecuteMotion).ObservesCanExecute(() => CanExecutePointCommand).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute).ObservesProperty(() => SelectedPointInDataGrid)); private DelegateCommand _JogCommand; public DelegateCommand JogCommand => _JogCommand ?? (_JogCommand = new DelegateCommand(ExecuteJogCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute)); private DelegateCommand _TechPointCommand; public DelegateCommand TechPointCommand => _TechPointCommand ?? (_TechPointCommand = new DelegateCommand(ExecuteTechPointCommand).ObservesCanExecute(() => CanExecutePointCommand).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute).ObservesProperty(() => SelectedPointInDataGrid)); private DelegateCommand _MotorCommand; public DelegateCommand MotorCommand => _MotorCommand ?? (_MotorCommand = new DelegateCommand(ExecuteMotorCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute)); private DelegateCommand _ResetCommand; public DelegateCommand ResetCommand => _ResetCommand ?? (_ResetCommand = new DelegateCommand(ExecuteResetCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute)); private DelegateCommand _sFreeCommand; public DelegateCommand sFreeCommand => _sFreeCommand ?? (_sFreeCommand = new DelegateCommand(ExecutesFreeCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute)); private DelegateCommand _SLockCommand; public DelegateCommand SLockCommand => _SLockCommand ?? (_SLockCommand = new DelegateCommand(ExecuteSLockCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute)); private DelegateCommand _SelectionChangedCommand; public DelegateCommand SelectionChangedCommand => _SelectionChangedCommand ?? (_SelectionChangedCommand = new DelegateCommand(ExecuteSelectionChangedCommand)); private DelegateCommand _AddPointCommand; public DelegateCommand AddPointCommand => _AddPointCommand ?? (_AddPointCommand = new DelegateCommand(ExecuteAddPointCommand)); private DelegateCommand _DeletePointCommand; public DelegateCommand DeletePointCommand => _DeletePointCommand ?? (_DeletePointCommand = new DelegateCommand(ExecuteDeletePointCommand, CanExecuteDeletePointCommand).ObservesProperty(() => SelectedPointInDataGrid)); private DelegateCommand _MovePointUpCommand; public DelegateCommand MovePointUpCommand => _MovePointUpCommand ?? (_MovePointUpCommand = new DelegateCommand(ExecuteMovePointUpCommand, CanMovePointUp)); private DelegateCommand _MovePointDownCommand; public DelegateCommand MovePointDownCommand => _MovePointDownCommand ?? (_MovePointDownCommand = new DelegateCommand(ExecuteMovePointDownCommand, CanMovePointDown)); private DelegateCommand _ImportCadPointCommand; public DelegateCommand ImportCadPointCommand => _ImportCadPointCommand ?? (_ImportCadPointCommand = new DelegateCommand(ExecuteImportCadPointCommand)); private DelegateCommand _StartGrabbingCommand; public DelegateCommand StartGrabbingCommand => _StartGrabbingCommand ?? (_StartGrabbingCommand = new DelegateCommand(ExecuteStartGrabbingCommand, CanExecuteStartGrabbingCommand).ObservesProperty(() => IsGrap).ObservesProperty(() => SelectedCamera)); private DelegateCommand _StopGrabbingCommand; public DelegateCommand StopGrabbingCommand => _StopGrabbingCommand ?? (_StopGrabbingCommand = new DelegateCommand(ExecuteStopGrabbingCommand, CanExecuteStopGrabbingCommand).ObservesProperty(() => IsGrap).ObservesProperty(() => SelectedCamera)); private DelegateCommand _GoPickCommand; public DelegateCommand GoPickCommand => _GoPickCommand ?? (_GoPickCommand = new DelegateCommand(ExecuteGoPickCommand, CanExecuteCommandGoPickCommandName).ObservesProperty(() => SelectedPoint)); private DelegateCommand _GoRepositionCommand; public DelegateCommand GoRepositionCommand => _GoRepositionCommand ?? (_GoRepositionCommand = new DelegateCommand(ExecuteGoRepositionCommand, CanExecuteCommandGoPickCommandName).ObservesProperty(() => SelectedPoint)); private DelegateCommand _TakeProductPhotoCommand; public DelegateCommand TakeProductPhotoCommand => _TakeProductPhotoCommand ?? (_TakeProductPhotoCommand = new DelegateCommand(ExecuteTakeProductPhotoCommand, CanExecuteCommandGoPickCommandName).ObservesProperty(() => SelectedPoint)); private DelegateCommand _TakeProductCommand; public DelegateCommand TakeProductCommand => _TakeProductCommand ?? (_TakeProductCommand = new DelegateCommand(ExecuteTakeProductCommand, CanExecuteCommandGoPickCommandName).ObservesProperty(() => SelectedPoint)); //附加轴,轴点动+命令 private DelegateCommand _AdditionalAxisJogPlusCommand; public DelegateCommand AdditionalAxisJogPlusCommand => _AdditionalAxisJogPlusCommand ?? (_AdditionalAxisJogPlusCommand = new DelegateCommand(ExecuteAdditionalAxisJogPlusCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute)); //附加轴,轴点动-命令 private DelegateCommand _AdditionalAxisJogMinusCommand; public DelegateCommand AdditionalAxisJogMinusCommand => _AdditionalAxisJogMinusCommand ?? (_AdditionalAxisJogMinusCommand = new DelegateCommand(ExecuteAdditionalAxisJogMinusCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute)); private DelegateCommand _AdditionalAxisMotorOnCommand; public DelegateCommand AdditionalAxisMotorOnCommand => _AdditionalAxisMotorOnCommand ?? (_AdditionalAxisMotorOnCommand = new DelegateCommand(ExecuteAdditionalAxisMotorOnCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute)); private DelegateCommand _AdditionalAxisMotorOffCommand; public DelegateCommand AdditionalAxisMotorOffCommand => _AdditionalAxisMotorOffCommand ?? (_AdditionalAxisMotorOffCommand = new DelegateCommand(ExecuteAdditionalAxisMotorOffCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute)); private DelegateCommand _PickTechCommand; public DelegateCommand PickTechCommand => _PickTechCommand ?? (_PickTechCommand = new DelegateCommand(ExecutePickTechCommand)); private DelegateCommand _PickMoveCommand; public DelegateCommand PickMoveCommand => _PickMoveCommand ?? (_PickMoveCommand = new DelegateCommand(ExecutePickMoveCommand)); private DelegateCommand _CalPickPosCommand; public DelegateCommand CalPickPosCommand => _CalPickPosCommand ?? (_CalPickPosCommand = new DelegateCommand(ExecuteCalPickPosCommand)); private DelegateCommand _DynamicTestAnalyzerCommand; public DelegateCommand DynamicTestAnalyzerCommand => _DynamicTestAnalyzerCommand ?? (_DynamicTestAnalyzerCommand = new DelegateCommand(ExecuteDynamicTestAnalyzerCommand)); private DelegateCommand _SetOffsetCommand; public DelegateCommand SetOffsetCommand => _SetOffsetCommand ?? (_SetOffsetCommand = new DelegateCommand(ExecuteSetOffsetCommand)); #endregion #region 事件 #endregion public PlcPointParamsViewModel(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IDialogService dialogService, IConfigService configService, IRobotService robotService, ISystemDatabaseService systemDatabaseService, IRemoteCommandService remoteCommandService, ICalibrationService calibrationService, ICameraService cameraService, IProductService productService) { _regionManager = regionManager; _eventAggregator = ea; _container = container; _dialogService = dialogService; _configService = configService; _systemDatabaseService = systemDatabaseService; //订阅权限登录事件 _eventAggregator.GetEvent().Subscribe(LoginChange); management = _container.Resolve(); _robotService = robotService; _remoteCommandService = remoteCommandService; _calibrationService = calibrationService; _cameraService = cameraService; _productService = productService; } #region 方法 /// /// 下一步 /// void ExecuteNextCommand() { NavigationParameters param = new NavigationParameters(); param.Add("SelectProduct", SelectProduct); _regionManager.RequestNavigate("ProductRegionContext", "ProductParams", param); } /// /// 上一步 /// void ExecuteBackCommand() { NavigationParameters param = new NavigationParameters(); param.Add("SelectProduct", SelectProduct); param.Add("SelectedProcedure", null); _regionManager.RequestNavigate("ProductRegionContext", "ProcessBasics", param); } /// /// 点动 /// /// private async void ExecuteJogCommand(object obj) { if (Robot == null || !Robot.IsConnected) return; try { var items = ((string)obj).Split(':'); //如果移动距离大于10mm,则提示用户确认 double distance = double.Parse(items[1]); if (Math.Abs(distance) >= 10) { if (MessageBox.Show($"确认要点动距离 {distance} mm 吗?", "确认点动", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } } Robot.Timeout = 6000000; switch (items[0]) { case "X+": await Robot.JogAsync("X", distance); break; case "X-": await Robot.JogAsync("X", -distance); break; case "Y+": await Robot.JogAsync("Y", distance); break; case "Y-": await Robot.JogAsync("Y", -distance); break; case "Z+": await Robot.JogAsync("Z", distance); break; case "Z-": await Robot.JogAsync("Z", -distance); break; case "U+": await Robot.JogAsync("U", distance); break; case "U-": await Robot.JogAsync("U", -distance); break; case "V+": await Robot.JogAsync("V", distance); break; case "V-": await Robot.JogAsync("V", -distance); break; case "W+": await Robot.JogAsync("W", distance); break; case "W-": await Robot.JogAsync("W", -distance); break; default: break; } Robot.Timeout = 5000; _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } catch (Exception ex) { LogHelper.WriteLogError("机器人点位-机器人点动时出错", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 执行运动 /// /// async void ExecuteExecuteMotion(object parameter) { if (parameter == null) { return; } if (SelectedPoint == null) { return; } var values = (object[])parameter; var point = new RPoint() { X = SelectedPoint.X_Position, Y = SelectedPoint.Y_Position, Z = SelectedPoint.Z_Position_Start, U = SelectedPoint.U_Position, V = SelectedPoint.R_Position, }; MotionCommand motionCmd = (MotionCommand)values[1]; if (Robot == null || !Robot.IsConnected) return; try { //确认要执行该点位的该运动指令吗 if (MessageBox.Show($"确认要执行点位 {SelectedPoint.Number} 的 {motionCmd} 指令吗?", "执行点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } if (SelectedIndex == 6) { await Robot.WaitCameraMoveFinishedAsync(point.Number, point); } else if (SelectedIndex == 8) { //弹窗用户是否确认要示教该点位 if (MessageBox.Show($"确认要示教点位 {SelectedPoint.Number} 吗?", "示教点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } await Robot.AdditionalAxisMoveAsync(Robot.AdditionalAxisList[1].Name, SelectedPoint.Z_Position_Start); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); return; } else if (SelectedIndex == 1) { var curpos = await Robot.GetRobotPosAsync(); //var addpos = await Robot.GetAdditionalAxisCurrentPosAsync(Robot.AdditionalAxisList[0].Name); curpos.Z = 0; await Robot.CalibMotionAsync(curpos, 0); await Robot.AdditionalAxisMoveAsync(Robot.AdditionalAxisList[0].Name, SelectedPoint.Z_Position_Stop); curpos.X = SelectedPoint.X_Position; curpos.Y = SelectedPoint.Y_Position; curpos.Z = SelectedPoint.Z_Position_Start; curpos.U = SelectedPoint.U_Position; await Robot.CalibMotionAsync(curpos, 0); } else { //Robot.Timeout = 6000000; switch (motionCmd) { case MotionCommand.Go: await Robot.GoAsync(point); break; case MotionCommand.Jump: await Robot.JumpAsync(point, null); break; case MotionCommand.Move: await Robot.MoveAsync(point); break; } } _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } catch (Exception ex) { LogHelper.WriteLogError("机器人点位-执行点位时出错", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 示教点位 /// /// async void ExecuteTechPointCommand() { if (Robot == null || !Robot.IsConnected) return; if (SelectedPoint == null) return; try { //如果当前的选项卡处于锁付点位,则提示用户当前模式不允许进行示教 if (SelectedIndex == 4) { ////如果local为空,则必须先通过相机定位产品,否则无法示教锁付点位 //if (toolCoord == null) //{ // _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "当前模式不允许直接示教贴敷点位,请先通过相机定位产品和定位辅料!", Duration = 1 }); // return; //} //弹窗用户是否确认要示教该点位 if (MessageBox.Show($"确认要示教点位 {SelectedPoint.Number} 吗?", "示教点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } double upCameraU = Common.CalculateAngleBetweenPointsDegrees(new PointF((float)_PutPoints[0].X, (float)_PutPoints[0].Y), new PointF((float)_PutPoints[1].X, (float)_PutPoints[1].Y)); var curpos1 = await Robot.GetRobotPosAsync(); //var addpos = await Robot.GetAdditionalAxisCurrentPosAsync(Robot.AdditionalAxisList[1].Name); //将当前点位转换为产品Local坐标系下的点位 SelectedPoint.X_Position = (float)curpos1.X; SelectedPoint.Y_Position = (float)curpos1.Y; SelectedPoint.Z_Position_Start = curpos1.Z; SelectedPoint.U_Position = curpos1.U; SelectedPoint.R_Position = curpos1.V; //SelectedPoint.Z_Position_Stop = addpos; _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); return; } else if (SelectedIndex == 1) { //弹窗用户是否确认要示教该点位 if (MessageBox.Show($"确认要示教点位 {SelectedPoint.Number} 吗?", "示教点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } var curpos1 = await Robot.GetRobotPosAsync(); var addpos = await Robot.GetAdditionalAxisCurrentPosAsync(Robot.AdditionalAxisList[0].Name); //将当前点位转换为产品Local坐标系下的点位 SelectedPoint.X_Position = (float)curpos1.X; SelectedPoint.Y_Position = (float)curpos1.Y; SelectedPoint.Z_Position_Start = curpos1.Z; SelectedPoint.Z_Position_Stop = addpos; SelectedPoint.U_Position = curpos1.U; SelectedPoint.R_Position = curpos1.V; _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); return; } else if (SelectedIndex == 6) { //弹窗用户是否确认要示教该点位 if (MessageBox.Show($"确认要示教点位 {SelectedPoint.Number} 吗?", "示教点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } var curpos1 = await Robot.GetCameraPosAsync(SelectedPoint.Number); //将当前点位转换为产品Local坐标系下的点位 SelectedPoint.X_Position = (float)curpos1.X; SelectedPoint.Y_Position = (float)curpos1.Y; SelectedPoint.Z_Position_Start = curpos1.Z; SelectedPoint.U_Position = curpos1.U; SelectedPoint.R_Position = curpos1.V; _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); return; } else if (SelectedIndex == 8) { //弹窗用户是否确认要示教该点位 if (MessageBox.Show($"确认要示教点位 {SelectedPoint.Number} 吗?", "示教点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } var addpos = await Robot.GetAdditionalAxisCurrentPosAsync(Robot.AdditionalAxisList[1].Name); SelectedPoint.Z_Position_Start = addpos; _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); return; } else { //弹窗用户是否确认要示教该点位 if (MessageBox.Show($"确认要示教点位 {SelectedPoint.Number} 吗?", "示教点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } var curpos = await Robot.GetRobotPosAsync(); SelectedPoint.X_Position = curpos.X; SelectedPoint.Y_Position = curpos.Y; SelectedPoint.Z_Position_Start = curpos.Z; SelectedPoint.U_Position = curpos.U; SelectedPoint.R_Position = curpos.V; _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } } catch (Exception ex) { LogHelper.WriteLogError("机器人点位-示教点位时出错", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } void ExecuteLoadedCommand() { if (_systemDatabaseService.GetCurrentUser().userPart == Enums.UserPart.Operator) { IsAllowEdit = false; } else { IsAllowEdit = true; } } /// /// 电机 /// /// private async void ExecuteMotorCommand(string obj) { if (Robot == null || !Robot.IsConnected) return; try { await Robot.MotorAsync(Convert.ToBoolean(obj)); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } catch (Exception ex) { LogHelper.WriteLogError("机器人点击操作时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 重置 /// private async void ExecuteResetCommand() { if (Robot == null || !Robot.IsConnected) return; try { await Robot.ResetAsync(); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } catch (Exception ex) { LogHelper.WriteLogError("重置机器人时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 锁定刹车 /// private async void ExecuteSLockCommand() { if (Robot == null || !Robot.IsConnected) return; try { await Robot.SLockAsync(); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } catch (Exception ex) { LogHelper.WriteLogError("机器人锁定刹车时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 释放刹车 /// private async void ExecutesFreeCommand() { if (Robot == null || !Robot.IsConnected) return; try { await Robot.SFreeAsync(); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } catch (Exception ex) { LogHelper.WriteLogError("机器人释放刹车时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } private bool CanExecute { get { // 命令可执行仅当机器人可执行且已选择点位 if (Robot != null && Robot.IsConnected && Robot.CanExecute) { return true; } return false; } } //是否可以示教或者执行点位 private bool CanExecutePointCommand { get { if (Robot != null && Robot.IsConnected && Robot.CanExecute) { return SelectedPointInDataGrid != null; } return false; } } /// /// 点位表切换时 /// void ExecuteSelectionChangedCommand() { switch (SelectedIndex) { case 0: Points = SelectProduct.PickCameraPoints; break; case 1: Points = SelectProduct.PickPoints; break; case 2: Points = SelectProduct.SecPosCameraPoints; break; case 3: Points = SelectProduct.ScrewCameraPoints; break; case 4: Points = SelectProduct.ScrewPoints; break; case 5: Points = SelectProduct.CheckCameraPoints; break; case 6: Points = SelectProduct.IndependentCamerPoints; break; case 7: Points = SelectProduct.RemovePoints; break; case 8: Points = SelectProduct.PressurePlacePoints; break; default: break; } } /// /// 增加点位 /// void ExecuteAddPointCommand() { //添加点位 Points.Add(new PlcPoint() { Number = Points.Count + 1, X_Velocity = 100, Y_Velocity = 100, Z_Velocity_Start = 100, Z_Velocity_Stop = 100, U_Velocity = 100, R_Velocity = 100, }); // update commands _MovePointUpCommand?.RaiseCanExecuteChanged(); _MovePointDownCommand?.RaiseCanExecuteChanged(); } /// /// 移除点位 /// void ExecuteDeletePointCommand() { if (SelectedPoint == null) { return; } // 确认删除 if (MessageBox.Show("确认要删除选中的点位吗?", "删除点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } int removedIndex = Points.IndexOf(SelectedPoint); Points.Remove(SelectedPoint); //重新编号 for (int i = 0; i < Points.Count; i++) { Points[i].Number = i + 1; } // adjust selection if (Points.Count > 0) { int newIndex = Math.Min(removedIndex, Points.Count - 1); SelectedPointInDataGrid = Points[newIndex]; } else { SelectedPointInDataGrid = null; } // update commands _MovePointUpCommand?.RaiseCanExecuteChanged(); _MovePointDownCommand?.RaiseCanExecuteChanged(); } bool CanExecuteDeletePointCommand() { return SelectedPointInDataGrid != null; } private bool CanMovePointUp() { return SelectedPointInDataGrid != null && Points.IndexOf(SelectedPointInDataGrid) > 0; } private bool CanMovePointDown() { return SelectedPointInDataGrid != null && Points.IndexOf(SelectedPointInDataGrid) >= 0 && Points.IndexOf(SelectedPointInDataGrid) < Points.Count - 1; } /// /// 向上移动点位 /// void ExecuteMovePointUpCommand() { if (SelectedPointInDataGrid == null) return; // 确认移动 if (MessageBox.Show("确认将选中点位上移一位吗?", "移动点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } int idx = Points.IndexOf(SelectedPointInDataGrid); if (idx <= 0) return; var item = SelectedPointInDataGrid; Points.Move(idx, idx - 1); // renumber for (int i = 0; i < Points.Count; i++) Points[i].Number = i + 1; SelectedPointInDataGrid = item; _MovePointUpCommand?.RaiseCanExecuteChanged(); _MovePointDownCommand?.RaiseCanExecuteChanged(); } /// /// 向下移动点位 /// void ExecuteMovePointDownCommand() { if (SelectedPointInDataGrid == null) return; // 确认移动 if (MessageBox.Show("确认将选中点位下移一位吗?", "移动点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } int idx = Points.IndexOf(SelectedPointInDataGrid); if (idx < 0 || idx >= Points.Count - 1) return; var item = SelectedPointInDataGrid; Points.Move(idx, idx + 1); // renumber for (int i = 0; i < Points.Count; i++) Points[i].Number = i + 1; SelectedPointInDataGrid = item; _MovePointUpCommand?.RaiseCanExecuteChanged(); _MovePointDownCommand?.RaiseCanExecuteChanged(); } /// /// CAD导入点位 /// async void ExecuteImportCadPointCommand() { try { var view = new DxfView(); //show the dialog var result = await DialogHost.Show(view, "RootDialog", null, null, null); if (result != null) { var cadPoints = view.Points; if (cadPoints != null && cadPoints.Count > 0) { //要导入的开始点编号 int startNumber = view.StartIndex; //弹窗提示用户是否确认要导入从该编号开始的点位,点位数量为cadPoints.Count if (MessageBox.Show($"确认要从点位编号 {startNumber} 开始导入 {cadPoints.Count} 个点位吗?", "导入点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } //导入点位 for (int i = 0; i < cadPoints.Count; i++) { //如果点位编号已存在,则更新该点位,否则新增点位,只更新XY坐标 var point = cadPoints[i]; var existingPoint = Points.FirstOrDefault(p => p.Number == startNumber + i); if (existingPoint != null) { existingPoint.X_Position = point.X; existingPoint.Y_Position = point.Y; } else { Points.Add(new PlcPoint() { Number = startNumber + i, X_Position = point.X, Y_Position = point.Y, X_Velocity = 100, Y_Velocity = 100, Z_Velocity_Start = 100, Z_Velocity_Stop = 100, U_Velocity = 100, R_Velocity = 100, }); } } //对所有的点位重新编号,确保编号连续 var sortedPoints = Points.OrderBy(p => p.Number).ToList(); Points.Clear(); for (int i = 0; i < sortedPoints.Count; i++) { sortedPoints[i].Number = i + 1; Points.Add(sortedPoints[i]); } _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } } } catch (Exception ex) { LogHelper.WriteLogError("导入CAD点位时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 设置偏移 /// void ExecuteSetOffsetCommand() { if (SelectedIndex < 0) return; IDialogParameters parameters1 = new DialogParameters(); if (SelectedIndex == 0) { parameters1.Add("Title", "取料拍照点位-补偿值设置"); } else if (SelectedIndex == 1) { parameters1.Add("Title", "取料点位-补偿值设置"); } else if (SelectedIndex == 2) { parameters1.Add("Title", "下相机二次定位点位-补偿值设置"); } else if (SelectedIndex == 3) { parameters1.Add("Title", "锁附拍照点位-补偿值设置"); } else if (SelectedIndex == 4) { parameters1.Add("Title", "锁附点位-补偿值设置"); } else if (SelectedIndex == 5) { parameters1.Add("Title", "复检点位-补偿值设置"); } else { parameters1.Add("Title", "点位-补偿值设置"); } List _points = new List(); foreach (var item in Points) { _points.Add(item.Clone()); } parameters1.Add("Points", _points.ToArray()); _dialogService.ShowDialog("PlcPointOffserParams", parameters1, rst => { //对话框关闭之后的回调函数,可以在这解析结果。 ButtonResult result1 = rst.Result; if (result1 == ButtonResult.OK) { var param = rst.Parameters.GetValue("Points"); //更新点位 for (int i = 0; i < Points.Count; i++) { Points[i].X_Offset = param[i].X_Offset; Points[i].Y_Offset = param[i].Y_Offset; Points[i].Z_Start_Offset = param[i].Z_Start_Offset; Points[i].Z_Stop_Offset = param[i].Z_Stop_Offset; Points[i].U_Offset = param[i].U_Offset; Points[i].R_Offset = param[i].R_Offset; } _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}", Duration = 1 }); } }); } /// /// 停止采集 /// void ExecuteStopGrabbingCommand() { if (Camera != null) Camera.StopGrabbing(); IsGrap = false; } bool CanExecuteStopGrabbingCommand() { return IsGrap; } /// /// 开始采集 /// void ExecuteStartGrabbingCommand() { if (Camera != null) Camera.StartGrabbing(); IsGrap = true; } bool CanExecuteStartGrabbingCommand() { return SelectedCamera != null && !IsGrap; } private void Camera_ImageCallbackEvent(ICogImage image, TimeSpan totaltime, string errormessage) { Image = image; App.Current.Dispatcher.Invoke(new Action(() => { if (errormessage != null && !string.IsNullOrEmpty(errormessage)) { Message = $"{Lang.耗时}:{totaltime.TotalMilliseconds.ToString("F1")} ms Error:{errormessage}"; } else { Message = $"{Lang.耗时}:{totaltime.TotalMilliseconds.ToString("F1")} ms"; } })); } /// /// 去取料 /// async void ExecuteGoPickCommand() { try { if (SelectedPoint == null) { return; } if (Robot == null || !Robot.IsConnected) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "机器人未连接,无法执行取料!", Duration = 1 }); return; } if (MessageBox.Show("确认要执行取料吗?", "去取料", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } var waiting = new WaitingControl(); //show the dialog var task = DialogHost.Show(waiting, "RootDialog", null, null, null); // 1. 控制机器人移动至拍照点位 var rpoint = new RPoint() { X = SelectedPoint.X_Position, Y = SelectedPoint.Y_Position, Z = SelectedPoint.Z_Position_Start, U = SelectedPoint.U_Position, V = SelectedPoint.R_Position, }; await Robot.CalibMotionAsync(rpoint, null); await Robot.CalibParameAsync(new PickInfo() { Inhal = Inhal, Blow = 1 }, 20, 20, true, 200, 200); //打开吸真空 await Robot.CalibOutIOAsync(true); await Task.Delay(500); rpoint.Z = 0; await Robot.CalibMotionAsync(rpoint, null); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "取料完成!", Duration = 0.4 }); } catch (Exception ex) { LogHelper.WriteLogError("取料时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } bool CanExecuteCommandGoPickCommandName() { return SelectedPoint != null; } ToolCoord toolCoord = null; double _FixedUpCameraTempletAngle = 0; OpenCvSharp.Point3f[] _PutPoints = new OpenCvSharp.Point3f[2]; /// /// 去二次定位 /// async void ExecuteGoRepositionCommand() { try { if (SelectedPoint == null) { return; } if (Robot == null || !Robot.IsConnected) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "机器人未连接,无法执行二次定位!", Duration = 1 }); return; } if (MessageBox.Show("确认要执行下相机拍产二次定位吗?", "去下相机拍照", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } var waiting = new WaitingControl(); //show the dialog var task = DialogHost.Show(waiting, "RootDialog", null, null, null); // 1. 控制机器人移动至拍照点位 var rpoint = new RPoint() { X = SelectedPoint.X_Position, Y = SelectedPoint.Y_Position, Z = SelectedPoint.Z_Position_Start, U = SelectedPoint.U_Position, V = SelectedPoint.R_Position, }; await Robot.CalibMotionAsync(rpoint, null); await Task.Delay(200); //获取固定向上相机1的流程 var process1 = _productService.GetCurrentProductProcedureModelById(SelectProduct.FixedUpCamera1ProcedureId); if (process1 == null) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"固定向上相机1视觉流程,流程ID:{SelectProduct.FixedUpCamera1ProcedureId} 未找到!", Duration = 1 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; return; } //获取固定向上相机2的流程 var process2 = _productService.GetCurrentProductProcedureModelById(SelectProduct.FixedUpCamera2ProcedureId); if (process2 == null) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"固定向上相机2视觉流程,流程ID:{SelectProduct.FixedUpCamera2ProcedureId} 未找到!", Duration = 1 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; return; } // 执行视觉任务 var _cts = new CancellationTokenSource(); var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token); var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token); var visionResults = await Task.WhenAll(task1, task2); if (visionResults[0].IsSucceed && visionResults[1].IsSucceed) { float toolX = (float)(visionResults[0].X + visionResults[1].X) / 2; float toolY = (float)(visionResults[0].Y + visionResults[1].Y) / 2; _FixedUpCameraTempletAngle = Common.CalculateAngleBetweenPointsDegrees(new PointF((float)visionResults[0].X, (float)visionResults[0].Y), new PointF((float)visionResults[1].X, (float)visionResults[1].Y)); toolCoord = new ToolCoord(); toolCoord.SetTool(toolX, toolY); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "视觉定位成功!", Duration = 0.4 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; return; } else { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "视觉定位失败,无法进行二次定位!", Duration = 1 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; return; } } catch (Exception ex) { LogHelper.WriteLogError("二次定位时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } } } /// /// 执行产品拍照 /// async void ExecuteTakeProductPhotoCommand() { try { if (SelectedPoint == null) { return; } if (Robot == null || !Robot.IsConnected) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "机器人未连接,无法执行产品拍照!", Duration = 1 }); return; } if (MessageBox.Show("确认要执行产品拍照吗?", "去产品位置拍照", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } //如果二次定位的工具坐标为空,则提示用户先进行二次定位 if (toolCoord == null) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "二次定位的工具坐标为空,无法执行产品拍照!", Duration = 1 }); return; } var waiting = new WaitingControl(); //show the dialog var task = DialogHost.Show(waiting, "RootDialog", null, null, null); // 1. 控制机器人移动至拍照点位 var rpoint = new RPoint() { X = Points[0].X_Position, Y = Points[0].Y_Position, Z = Points[0].Z_Position_Start, U = Points[0].U_Position, V = Points[0].R_Position, }; await Robot.CalibMotionAsync(rpoint, null); await Task.Delay(200); //获取移动向下相机1的流程 var process1 = _productService.GetCurrentProductProcedureModelById(SelectProduct.MoveDownCamera1LockPhotoProcedureId); if (process1 == null) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"移动向下相机1视觉流程,流程ID:{SelectProduct.MoveDownCamera1LockPhotoProcedureId} 未找到!", Duration = 1 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; return; } // 执行视觉任务 var _cts = new CancellationTokenSource(); var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token); if (visionResult.IsSucceed) { _PutPoints[0] = new OpenCvSharp.Point3f((float)visionResult.X, (float)visionResult.Y, (float)visionResult.U); } else { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "视觉定位失败,无法进行产品拍照!", Duration = 1 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; return; } // 2. 控制机器人移动至拍照点位 rpoint = new RPoint() { X = Points[1].X_Position, Y = Points[1].Y_Position, Z = Points[1].Z_Position_Start, U = Points[1].U_Position, V = Points[1].R_Position, }; await Robot.CalibMotionAsync(rpoint, null); await Task.Delay(200); //获取移动向下相机1的流程 var process2 = _productService.GetCurrentProductProcedureModelById(SelectProduct.MoveDownCamera2LockPhotoProcedureId); if (process2 == null) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"移动向下相机2视觉流程,流程ID:{SelectProduct.MoveDownCamera2LockPhotoProcedureId} 未找到!", Duration = 1 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; return; } // 执行视觉任务 _cts = new CancellationTokenSource(); visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token); if (visionResult.IsSucceed) { _PutPoints[1] = new OpenCvSharp.Point3f((float)visionResult.X, (float)visionResult.Y, (float)visionResult.U); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; return; } else { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "视觉定位失败,无法进行产品拍照!", Duration = 1 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; return; } } catch (Exception ex) { LogHelper.WriteLogError("执行产品拍照时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } } } /// /// 执行产品贴敷 /// async void ExecuteTakeProductCommand() { try { if (SelectedPoint == null) { return; } if (Robot == null || !Robot.IsConnected) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "机器人未连接,无法执行产品贴敷!", Duration = 1 }); return; } if (MessageBox.Show("确认要执行产品贴敷吗?", "去产品贴敷", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } //如果二次定位的工具坐标为空,则提示用户先进行二次定位 if (toolCoord == null) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "二次定位的工具坐标为空,无法执行产品拍照!", Duration = 1 }); return; } if (_PutPoints[0].X == 0 && _PutPoints[0].Y == 0 && _PutPoints[1].X == 0 && _PutPoints[1].Y == 0) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "检测到未定位产品", Duration = 1 }); return; } var waiting = new WaitingControl(); //show the dialog var task = DialogHost.Show(waiting, "RootDialog", null, null, null); double upCameraX = (_PutPoints[0].X + _PutPoints[1].X) / 2; double upCameraY = (_PutPoints[0].Y + _PutPoints[1].Y) / 2; double upCameraU = Common.CalculateAngleBetweenPointsDegrees(new PointF((float)_PutPoints[0].X, (float)_PutPoints[0].Y), new PointF((float)_PutPoints[1].X, (float)_PutPoints[1].Y)); var pn = Vector.Build.Dense(new double[] { upCameraX, upCameraY }); //目标角度: double angle = SelectedPoint.U_Position + (_FixedUpCameraTempletAngle - SelectProduct.FixedUpCameraTempletAngle) + (upCameraU - SelectProduct.MoveDownCamerTempletAngle); //将_PutPoint转换为Tool0下要走的点 var p0 = toolCoord.GetTool0Coord(pn, angle); // 1. 控制机器人移动至拍照点位 var rpoint = new RPoint() { X = (float)p0[0], Y = (float)p0[1], Z = SelectedPoint.Z_Position_Start, U = (float)angle, V = SelectedPoint.R_Position, }; await Robot.CalibMotionAsync(rpoint, null); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } await task; return; } catch (Exception ex) { LogHelper.WriteLogError("执行产品贴敷时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); if (DialogHost.IsDialogOpen("RootDialog")) { DialogHost.Close("RootDialog"); } } } /// /// 附加轴+点动 /// /// async void ExecuteAdditionalAxisJogPlusCommand(object obj) { if (Robot == null || !Robot.IsConnected) return; try { if (obj is AxisExtended axis) { //如果移动距离大于10mm,则提示用户确认 if (Math.Abs(Distance) >= 10) { if (MessageBox.Show($"确认要点动距离 {Distance} mm 吗?", "确认点动", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } } await Robot.AdditionalAxisJogAsync(axis.Name, Distance); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } } catch (Exception ex) { LogHelper.WriteLogError("附加轴点动+时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 附加轴-点动 /// /// async void ExecuteAdditionalAxisJogMinusCommand(object obj) { if (Robot == null || !Robot.IsConnected) return; try { if (obj is AxisExtended axis) { //如果移动距离大于10mm,则提示用户确认 if (Math.Abs(Distance) >= 10) { if (MessageBox.Show($"确认要点动距离 {Distance} mm 吗?", "确认点动", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } } await Robot.AdditionalAxisJogNegAsync(axis.Name, Distance); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } } catch (Exception ex) { LogHelper.WriteLogError("附加轴点动-时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 附加轴下使能 /// /// async void ExecuteAdditionalAxisMotorOffCommand(object obj) { if (Robot == null || !Robot.IsConnected) return; try { if (obj is AxisExtended axis) { await Robot.AdditionalAxisMotorAsync(axis.Name, false); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } } catch (Exception ex) { LogHelper.WriteLogError("附加轴上使能时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 附加轴上使能 /// /// async void ExecuteAdditionalAxisMotorOnCommand(object obj) { if (Robot == null || !Robot.IsConnected) return; try { if (obj is AxisExtended axis) { await Robot.AdditionalAxisMotorAsync(axis.Name, true); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } } catch (Exception ex) { LogHelper.WriteLogError("附加轴下使能时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 移动取料托盘点 /// async void ExecutePickMoveCommand(string parameter) { if (Robot == null || !Robot.IsConnected) return; try { //弹窗用户是否确认要示教该点位 if (MessageBox.Show($"确认要移动取料点位 {parameter} 吗?", "移动点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } int palletIndex = int.Parse(parameter.Split('-')[0]); int pointIndex = int.Parse(parameter.Split('-')[1]); var curpos = await Robot.GetRobotPosAsync(); var addpos = await Robot.GetAdditionalAxisCurrentPosAsync(Robot.AdditionalAxisList[0].Name); PlcPoint pn = null; if (palletIndex == 1) { switch (pointIndex) { case 1: pn = Pallet1.P0.Clone(); break; case 2: pn = Pallet1.P1.Clone(); break; case 3: pn = Pallet1.P2.Clone(); break; default: break; } } else { switch (pointIndex) { case 1: pn = Pallet2.P0.Clone(); break; case 2: pn = Pallet2.P1.Clone(); break; case 3: pn = Pallet2.P2.Clone(); break; default: break; } } if (pn == null) { return; } // 1.Z轴上升到安全高度 curpos.Z = 0; bool isSuccess = await Robot.CalibMotionAsync(curpos, null); if (!isSuccess) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "机器人移动失败!", Duration = 1 }); return; } // 2.附加轴移动 isSuccess = await Robot.AdditionalAxisMoveAsync(Robot.AdditionalAxisList[0].Name, pn.Z_Position_Stop); if (!isSuccess) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "附加轴移动失败!", Duration = 1 }); return; } // 3.移动XY轴到位 curpos.X = pn.X_Position; curpos.Y = pn.Y_Position; curpos.Z = pn.Z_Position_Start; curpos.U = pn.U_Position; isSuccess = await Robot.CalibMotionAsync(curpos, null); if (!isSuccess) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "机器人移动失败!", Duration = 1 }); return; } _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } catch (Exception ex) { LogHelper.WriteLogError("示教取料托盘点时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 示教取料托盘点 /// /// async void ExecutePickTechCommand(string parameter) { if (Robot == null || !Robot.IsConnected) return; try { //弹窗用户是否确认要示教该点位 if (MessageBox.Show($"确认要示教取料点位 {parameter} 吗?", "示教点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } int palletIndex = int.Parse(parameter.Split('-')[0]); int pointIndex = int.Parse(parameter.Split('-')[1]); var curpos = await Robot.GetRobotPosAsync(); var addpos = await Robot.GetAdditionalAxisCurrentPosAsync(Robot.AdditionalAxisList[0].Name); if (palletIndex == 1) { switch (pointIndex) { case 1: Pallet1.P0.X_Position = curpos.X; Pallet1.P0.Y_Position = curpos.Y; Pallet1.P0.Z_Position_Start = curpos.Z; Pallet1.P0.U_Position = curpos.U; Pallet1.P0.Z_Position_Stop = addpos; break; case 2: Pallet1.P1.X_Position = curpos.X; Pallet1.P1.Y_Position = curpos.Y; Pallet1.P1.Z_Position_Start = curpos.Z; Pallet1.P1.U_Position = curpos.U; Pallet1.P1.Z_Position_Stop = addpos; break; case 3: Pallet1.P2.X_Position = curpos.X; Pallet1.P2.Y_Position = curpos.Y; Pallet1.P2.Z_Position_Start = curpos.Z; Pallet1.P2.U_Position = curpos.U; Pallet1.P2.Z_Position_Stop = addpos; break; default: break; } } else { switch (pointIndex) { case 1: Pallet2.P0.X_Position = curpos.X; Pallet2.P0.Y_Position = curpos.Y; Pallet2.P0.Z_Position_Start = curpos.Z; Pallet2.P0.U_Position = curpos.U; Pallet2.P0.Z_Position_Stop = addpos; break; case 2: Pallet2.P1.X_Position = curpos.X; Pallet2.P1.Y_Position = curpos.Y; Pallet2.P1.Z_Position_Start = curpos.Z; Pallet2.P1.U_Position = curpos.U; Pallet2.P1.Z_Position_Stop = addpos; break; case 3: Pallet2.P2.X_Position = curpos.X; Pallet2.P2.Y_Position = curpos.Y; Pallet2.P2.Z_Position_Start = curpos.Z; Pallet2.P2.U_Position = curpos.U; Pallet2.P2.Z_Position_Stop = addpos; break; default: break; } } _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } catch (Exception ex) { LogHelper.WriteLogError("示教取料托盘点时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 计算所有托盘点 /// void ExecuteCalPickPosCommand(string parameter) { try { int palletIndex = int.Parse(parameter); if (palletIndex == 1) { PalletTool palletTool = new PalletTool(Pallet1); //托盘中所有的点‘ var points = palletTool.PlcPoints; //将所有的点写入到取料点中,如果当前定义的取料点不存在,则新增 for (int i = 0; i < points.Length; i++) { //如果当前的取料点数量小于等于i,则新增一个取料点 if (SelectProduct.PickPoints.Count <= i) { SelectProduct.PickPoints.Add(new PlcPoint() { Number = i + 1, X_Position = points[i].X_Position, X_Velocity = 100, Y_Position = points[i].Y_Position, Y_Velocity = 100, Z_Position_Start = points[i].Z_Position_Start, Z_Velocity_Start = 100, U_Position = points[i].U_Position, U_Velocity = 100, Z_Position_Stop = points[i].Z_Position_Stop, Z_Velocity_Stop = 100, }); } else { //否则更新当前的取料点 SelectProduct.PickPoints[i].Number = i + 1; SelectProduct.PickPoints[i].X_Position = points[i].X_Position; SelectProduct.PickPoints[i].Y_Position = points[i].Y_Position; SelectProduct.PickPoints[i].Z_Position_Start = points[i].Z_Position_Start; SelectProduct.PickPoints[i].U_Position = points[i].U_Position; SelectProduct.PickPoints[i].Z_Position_Stop = points[i].Z_Position_Stop; } } } else { //如果当前的取料点数量小于托盘1的点数量,则提示用户先计算托盘1的点 if (SelectProduct.PickPoints.Count < Pallet1.Row * Pallet1.Column) { _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = "请先计算托盘1的点位!", Duration = 1 }); return; } PalletTool palletTool = new PalletTool(Pallet2); //托盘中所有的点‘ var points = palletTool.PlcPoints; //将所有的点写入到取料点中,如果当前定义的取料点不存在,则新增 for (int i = 0; i < points.Length; i++) { int index = i + Pallet1.Row * Pallet1.Column; //如果当前的取料点数量小于等于index,则新增一个取料点 if (SelectProduct.PickPoints.Count <= index) { SelectProduct.PickPoints.Add(new PlcPoint() { Number = index + 1, X_Position = points[i].X_Position, X_Velocity = 100, Y_Position = points[i].Y_Position, Y_Velocity = 100, Z_Position_Start = points[i].Z_Position_Start, Z_Velocity_Start = 100, U_Position = points[i].U_Position, U_Velocity = 100, Z_Position_Stop = points[i].Z_Position_Stop, Z_Velocity_Stop = 100, }); } else { //否则更新当前的取料点 SelectProduct.PickPoints[index].Number = index + 1; SelectProduct.PickPoints[index].X_Position = points[i].X_Position; SelectProduct.PickPoints[index].Y_Position = points[i].Y_Position; SelectProduct.PickPoints[index].Z_Position_Start = points[i].Z_Position_Start; SelectProduct.PickPoints[index].U_Position = points[i].U_Position; SelectProduct.PickPoints[index].Z_Position_Stop = points[i].Z_Position_Stop; } } } _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 }); } catch (Exception ex) { LogHelper.WriteLogError("示教取料托盘点时出错!", ex); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 }); } } /// /// 动态测试分析仪 /// void ExecuteDynamicTestAnalyzerCommand() { try { IDialogParameters parameters = new DialogParameters(); parameters.Add("SelectProduct", SelectProduct); parameters.Add("Robot", Robot); _dialogService.Show("VisionDynamicAccuracyAnalyzer", parameters, rst => { //对话框关闭之后的回调函数,可以在这解析结果。 ButtonResult result1 = rst.Result; if (result1 == ButtonResult.OK) { //var param = rst.Parameters.GetValue("Tool"); //var param1 = rst.Parameters.GetValue>("RobotCameraRotationMatrix"); //var param2 = rst.Parameters.GetValue("Angle"); _eventAggregator.GetEvent().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 }); } }); } catch (Exception ex) { LogHelper.WriteLogError("执行动态测试分析仪命令时出错", ex); MessageBox.Show(ex.Message); } } #endregion #region 继承 /// /// 确认导航请求时调用。此方法允许您在导航之前执行一些操作。 /// /// /// public void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) { continuationCallback(true); } /// /// 接收导航请求时调用。传入导航参数,包含有关导航目标的信息。 /// /// /// public async void OnNavigatedTo(NavigationContext navigationContext) { try { toolCoord = null; SelectProduct = navigationContext.Parameters.GetValue("SelectProduct"); SelectedIndex = 0; Points = SelectProduct.PickCameraPoints; if (Robot == null) { Robot = _robotService.GetRobotByNumber(1) as XYZU_Robot; } if (Robot != null && Robot.IsConnected) { this.Distance = _configService.GetRobotStepDistance(Robot.Id); Robot.EnterDebugMode = true; AdditionalAxisList = Robot.AdditionalAxisList; } else if (Robot != null) { Robot.EnterDebugMode = true; } ProcedureModels = new ObservableCollection(); foreach (var item in SelectProduct.CameraProcedures) { foreach (var item1 in item.ProcedureModels) { ProcedureModels.Add(item1); } } CameraList = new ObservableCollection(_configService.GetAllCameras()); Pallet1 = new PalletEx() { Row = 4, Column = 2, P1 = new PlcPoint(), P0 = new PlcPoint(), P2 = new PlcPoint() }; Pallet2 = new PalletEx() { Row = 4, Column = 2, P1 = new PlcPoint(), P0 = new PlcPoint(), P2 = new PlcPoint() }; if (SelectProduct.PickCameraPoints == null) { SelectProduct.PickCameraPoints = new ObservableCollection(); } if (SelectProduct.PickPoints == null) { SelectProduct.PickPoints = new ObservableCollection(); } if (SelectProduct.SecPosCameraPoints == null) { SelectProduct.SecPosCameraPoints = new ObservableCollection(); } if (SelectProduct.ScrewCameraPoints == null) { SelectProduct.ScrewCameraPoints = new ObservableCollection(); } if (SelectProduct.ScrewPoints == null) { SelectProduct.ScrewPoints = new ObservableCollection(); } if (SelectProduct.CheckCameraPoints == null) { SelectProduct.CheckCameraPoints = new ObservableCollection(); } if (SelectProduct.IndependentCamerPoints == null) { SelectProduct.IndependentCamerPoints = new ObservableCollection(); } if (SelectProduct.RemovePoints == null) { SelectProduct.RemovePoints = new ObservableCollection(); } if (SelectProduct.PressurePlacePoints == null) { SelectProduct.PressurePlacePoints = new ObservableCollection(); } } catch (Exception ex) { LogHelper.WriteLogError("机器人点位界面进入时出错!", ex); } } /// /// 是否允许导航到此视图模型。 /// /// /// public bool IsNavigationTarget(NavigationContext navigationContext) { return true; } /// /// 导航离开此视图模型时调用。您可以在此处执行清理操作或保存状态。 /// /// public void OnNavigatedFrom(NavigationContext navigationContext) { //if (Robot != null) //{ // Robot.EnterDebugMode = false; //} try { IsGrap = false; if (Camera != null) { if (Camera.IsGrabbing) { Camera.StopGrabbing(); } Camera.ImageCallbackEvent -= Camera_ImageCallbackEvent; Camera = null; } SelectedCamera = null; IsLeftDrawerOpen = false; } catch (Exception) { } } #endregion private bool _IsAllowEdit = false; public bool IsAllowEdit { get { return _IsAllowEdit; } set { SetProperty(ref _IsAllowEdit, value); } } private void LoginChange(Models.User user) { if (user.userPart == Enums.UserPart.Operator) { IsAllowEdit = false; } else { IsAllowEdit = true; } } } }