领胜LDS 键盘AOI检测项目
src/Bro.Device.GTSCard/GTSCardDriver.cs
@@ -21,7 +21,7 @@
    public class GTSCardDriver : MotionCardBase
    {
        // 异常事件
        public Action<Exception> OnExceptionRaised;
        //public Action<Exception> OnExceptionRaised;
        public GTSCardInitialConfig IIConfig
        {
@@ -46,6 +46,8 @@
        /// 运动轴立即暂停
        /// </summary>
        Dictionary<int, ManualResetEvent> axisImmediatePauseHandleDict = new Dictionary<int, ManualResetEvent>();
        Dictionary<int, bool> axisImmediatePauseFlag = new Dictionary<int, bool>();
        Dictionary<int, bool> axisPauseResumeFlag = new Dictionary<int, bool>();
        //Dictionary<int, CancellationTokenSource> axisMoveCancelDict = new Dictionary<int, CancellationTokenSource>();
@@ -61,7 +63,7 @@
            {
                AxisInfo axisInfo = new AxisInfo();
                axisInfo.AxisName = axisSetting.AxisName;
                var axisMovingStatus = AxisMovingOptionValues.FirstOrDefault(u => u.AxisIndex == axisSetting.AxisIndex);
                var axisMovingStatus = AxisStatusList.FirstOrDefault(u => u.AxisIndex == axisSetting.AxisIndex);
                axisInfo.AxisLocation = axisMovingStatus == null ? 0 : Convert.ToDouble(axisMovingStatus.CurPosition);
                axisInfos.Add(axisInfo);
@@ -96,6 +98,8 @@
        protected override void Start()
        {
            AllAxisOn();
            base.Start();
        }
        protected override void Stop()
@@ -116,11 +120,17 @@
            {
                foreach (var operationSet in motionCardOperationConfig.OperationCollection)
                {
                    if (operationSet.DelayBefore > 0)
                        Thread.Sleep(operationSet.DelayBefore);
                    responseMessage = RunOperationSet(operationSet);
                    if (!responseMessage.Result)
                    {
                        return responseMessage;
                    }
                    if (operationSet.DelayAfter > 0)
                        Thread.Sleep(operationSet.DelayAfter);
                }
            }
            return responseMessage;
@@ -137,16 +147,22 @@
            {
                foreach (var preCheck in operationSet.PreCheckIOCollection)
                {
                    int timeout = operationSet.PreCheckIOTimeout;
                    _pauseHandle.Wait();
                    IOValue? ioData = null;
                    while (CurrentState == DeviceState.DSOpen)
                    if (CurrentState == DeviceState.DSOpen)
                    {
                        Thread.Sleep(10);
                        ioData = MonitorValues.FirstOrDefault(u => u.IONum == preCheck.IOItem.IONum && u.IOType == preCheck.IOItem.IOType)?.Value;//IO 是开、关 从MonitorValues 获取
                        timeout -= 10;
                        if (preCheck.CheckValue == ioData || (operationSet.PreCheckIOTimeout > 0 && timeout < 0))
                        int timeout = operationSet.PreCheckIOTimeout;
                        while (CurrentState == DeviceState.DSOpen)
                        {
                            break;
                            Thread.Sleep(10);
                            ioData = MonitorValues.FirstOrDefault(u => u.IONum == preCheck.IOItem.IONum && u.IOType == preCheck.IOItem.IOType)?.Value;//IO 是开、关 从MonitorValues 获取
                            timeout -= 10;
                            if (preCheck.CheckValue == ioData || (operationSet.PreCheckIOTimeout > 0 && timeout < 0))
                            {
                                break;
                            }
                        }
                    }
@@ -162,10 +178,15 @@
            // 2.板卡运动
            if (CurrentState == DeviceState.DSOpen)
            {
                responseMessage = MoveToPoint(new MotionOperationCollection() { MovingOps = operationSet.MovingOps });
                if (!responseMessage.Result)
                _pauseHandle.Wait();
                if (CurrentState == DeviceState.DSOpen)
                {
                    return responseMessage;
                    responseMessage = MoveToPoint(new MotionOperationCollection() { MovingOps = operationSet.MovingOps });
                    if (!responseMessage.Result)
                    {
                        return responseMessage;
                    }
                }
            }
@@ -173,14 +194,23 @@
            // 3.IO输出 不需要超时
            if (CurrentState == DeviceState.DSOpen)
            {
                foreach (var ioOutput in operationSet.IOOutputCollection)
                {
                    var ioData = MonitorValues.FirstOrDefault(u => u.IONum == ioOutput.IOItem.IONum && u.IOType == ioOutput.IOItem.IOType)?.Value;//IO 是开、关 从MonitorValues 获取
                    if (ioOutput.CheckValue != ioData)
                    _pauseHandle.Wait();
                    if (CurrentState == DeviceState.DSOpen)
                    {
                        responseMessage.Result = false;
                        responseMessage.Message = $"IO输出不通过,配置:{ioOutput.GetDisplayText()},当前值:{ioData}";
                        return responseMessage;
                        WriteOutput((short)ioOutput.IOItem.IONum, ioOutput.CheckValue);
                        //var ioData = MonitorValues.FirstOrDefault(u => u.IONum == ioOutput.IOItem.IONum && u.IOType == ioOutput.IOItem.IOType)?.Value;//IO 是开、关 从MonitorValues 获取
                        //if (ioOutput.CheckValue != ioData)
                        //{
                        //    responseMessage.Result = false;
                        //    responseMessage.Message = $"IO输出不通过,配置:{ioOutput.GetDisplayText()},当前值:{ioData}";
                        //    return responseMessage;
                        //}
                    }
                }
            }
@@ -217,20 +247,21 @@
        #endregion
        #region ImmediatePause
        ManualResetEventSlim _pauseHandle = new ManualResetEventSlim(true);
        /// <summary>
        /// 启动立即暂停
        /// </summary>
        public void SetImmediatePause()
        public override void SetImmediatePause()
        {
            if (!_isResetting)
            {
                var immediatePauseAxis = IConfig.AxisSettings.FindAll(a => a.IsAxisEnabled && a.IsImmediatePause).Select(u => u.AxisIndex).ToList();
                _pauseHandle.Reset();
                immediatePauseAxis.ForEach(async axisIndex =>
                {
                    axisImmediatePauseHandleDict[axisIndex].Reset();
                    //axisMoveCancelDict[axisIndex].Cancel();
                    axisImmediatePauseFlag[axisIndex] = true;
                    await MoveStop(axisIndex, 0);//所有轴都暂停
                });
@@ -240,15 +271,22 @@
        /// <summary>
        /// 恢复立即暂停
        /// </summary>
        public void ResetImmediatePause()
        public override void ResetImmediatePause(bool isResumeMoving)
        {
            var immediatePauseAxis = IConfig.AxisSettings.FindAll(a => a.IsAxisEnabled && a.IsImmediatePause).Select(u => u.AxisIndex).ToList();
            _pauseHandle.Set();
            immediatePauseAxis.ForEach(axisIndex =>
            {
                //axisMoveCancelDict[axisIndex] = new CancellationTokenSource();
                axisImmediatePauseFlag[axisIndex] = false;
                axisImmediatePauseHandleDict[axisIndex].Set();
                if (isResumeMoving)
                {
                    axisPauseResumeFlag[axisIndex] = true;
                }
                else
                {
                    axisPauseResumeFlag[axisIndex] = false;
                }
            });
        }
        #endregion
@@ -267,7 +305,7 @@
            ClearStatus(1, IConfig.AxisSettings.FindAll(u => u.IsAxisEnabled).Count);
            if (res != (short)GTSRetCode.GRCRunOK)
            {
                throw new Exception("板卡载入配置文件异常,错误码:" + res);
                throw new ProcessException("板卡载入配置文件异常,错误码:" + res);
            }
        }
@@ -336,15 +374,14 @@
            ResponseMessage responseMessage = new ResponseMessage();
            if (opConfig is MotionOperationCollection gtsOperationCollection)
            {
                List<Task<bool>> taskList = new List<Task<bool>>();
                foreach (var movingOp in gtsOperationCollection.MovingOps)
                List<bool> resultList = new List<bool>();
                Parallel.ForEach(gtsOperationCollection.MovingOps, movingOp =>
                {
                    var task = SingleAxisMoving(movingOp);
                    taskList.Add(task);
                }
                Task.WaitAll(taskList.ToArray());
                responseMessage.Result = taskList.All(u => u.GetAwaiter().GetResult());
                    axisImmediatePauseFlag[movingOp.AxisIndex] = false;
                    axisPauseResumeFlag[movingOp.AxisIndex] = true;
                    resultList.Add(SingleAxisMoving(movingOp).Result);
                });
                responseMessage.Result = resultList.All(u => u == true);
                if (!responseMessage.Result)
                {
                    responseMessage.Message = $"点位运动异常";
@@ -366,81 +403,96 @@
            resultCode.Add(GTSCardAPI.GT_PrfTrap((short)IConfig.CardNum, axisIndex));
            resultCode.Add(GTSCardAPI.GT_GetTrapPrm((short)IConfig.CardNum, axisIndex, out trapprm));
            trapprm.smoothTime = 1;
            trapprm.acc = optionPara.VelocityPara.Acc != 0 ? optionPara.VelocityPara.Acc : 1;
            trapprm.dec = optionPara.VelocityPara.Dec != 0 ? optionPara.VelocityPara.Dec : 1;
            if (optionPara.VelocityPara.Acc != 0)
            {
                trapprm.acc = optionPara.VelocityPara.Acc;
            }
            if (optionPara.VelocityPara.Dec != 0)
            {
                trapprm.dec = optionPara.VelocityPara.Dec;
            }
            resultCode.Add(GTSCardAPI.GT_SetTrapPrm((short)IConfig.CardNum, axisIndex, ref trapprm));
            resultCode.Add(GTSCardAPI.GT_SetVel((short)IConfig.CardNum, axisIndex, optionPara.VelocityPara.Velocity * IConfig.AxisVelocityRatio));
            if (optionPara.VelocityPara.Velocity != 0)
            {
                resultCode.Add(GTSCardAPI.GT_SetVel((short)IConfig.CardNum, axisIndex, optionPara.VelocityPara.Velocity * IConfig.AxisVelocityRatio));
            }
            var resultOK = resultCode.All(u => u == (short)GTSRetCode.GRCRunOK);
            if (!resultOK)
            {
                throw new Exception("轴" + optionPara.AxisIndex + "设置参数异常,错误码:" + string.Join(",", resultCode));
                throw new ProcessException("轴" + optionPara.AxisIndex + "设置参数异常,错误码:" + string.Join(",", resultCode));
            }
            return resultOK;
        }
        TaskFactory taskFactory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning);
        /// <summary>
        /// 单个轴 运动(点到点 jog 回零...)
        /// </summary>
        /// <param name="optionPara">运动参数对象</param>
        public override async Task<bool> SingleAxisMoving(MovingOption optionPara)
        public override Task<bool> SingleAxisMoving(MovingOption optionPara)
        {
            return await Task.Run(() =>
            return Task.Run(() =>
            {
                axisImmediatePauseHandleDict[optionPara.AxisIndex].WaitOne();
                bool isSuccessAndStop = false;
                try
                do
                {
                    if (IConfig.AxisSettings.FirstOrDefault(a => a.AxisIndex == optionPara.AxisIndex)?.IsAxisEnabled ?? false)
                    axisImmediatePauseHandleDict[optionPara.AxisIndex].WaitOne();
                    if (!axisPauseResumeFlag[optionPara.AxisIndex])
                        return true;
                    try
                    {
                        string _position = "";
                        string motionType = optionPara.MoveMode == EnumHelper.MotionMode.Normal ? (optionPara.IsAbsolute ? "Abs" : "Rel") : optionPara.MoveMode.ToString();
                        _position = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff},{optionPara.AxisIndex},{motionType},{GetPosition(optionPara.AxisIndex)},{GetPrfPosition(optionPara.AxisIndex)},{optionPara.Destination},";
                        switch (optionPara.MoveMode)
                        if (IConfig.AxisSettings.FirstOrDefault(a => a.AxisIndex == optionPara.AxisIndex)?.IsAxisEnabled ?? false)
                        {
                            case MotionMode.Normal:
                                {
                                    if (_isResetting)
                                    {
                                        LogAsync(DateTime.Now, "复位中启动运动异常", optionPara.AxisIndex + "启动运动异常");
                                        return false;
                                    }
                            string motionType = optionPara.MoveMode == EnumHelper.MotionMode.Normal ? (optionPara.IsAbsolute ? "Abs" : "Rel") : optionPara.MoveMode.ToString();
                                    if (optionPara.IsAbsolute)
                            switch (optionPara.MoveMode)
                            {
                                case MotionMode.Normal:
                                    {
                                        isSuccessAndStop = P2PMoveAbs(optionPara);
                                    }
                                    else
                                    {
                                        isSuccessAndStop = P2PMoveRel(optionPara);
                                    }
                                        if (_isResetting)
                                        {
                                            LogAsync(DateTime.Now, "复位中启动运动异常", optionPara.AxisIndex + "启动运动异常");
                                            return false;
                                        }
                                }
                                break;
                            case MotionMode.FindOri:
                                {
                                    isSuccessAndStop = GoHome(optionPara);
                                }
                                break;
                            case MotionMode.Jog:
                                {
                                    isSuccessAndStop = JogMove(optionPara);
                                }
                                break;
                                        if (optionPara.IsAbsolute)
                                        {
                                            isSuccessAndStop = P2PMoveAbs(optionPara);
                                        }
                                        //else
                                        //{
                                        //    isSuccessAndStop = P2PMoveRel(optionPara);
                                        //}
                                    }
                                    break;
                                case MotionMode.FindOri:
                                    {
                                        //isSuccessAndStop = GoHome(optionPara);
                                        isSuccessAndStop = P2PGoHome(optionPara);
                                    }
                                    break;
                                case MotionMode.Jog:
                                    {
                                        isSuccessAndStop = JogMove(optionPara);
                                    }
                                    break;
                            }
                        }
                        _position += $"{GetPosition(optionPara.AxisIndex)},";
                        _position += $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}";
                        LogAsync(DateTime.Now, "", _position);
                    }
                }
                catch (Exception ex)
                {
                    isSuccessAndStop = false;
                    LogAsync(DateTime.Now, $"轴{optionPara.AxisIndex}运动异常", ex.GetExceptionMessage());
                }
                    catch (Exception ex)
                    {
                        isSuccessAndStop = false;
                        LogAsync(DateTime.Now, $"轴{optionPara.AxisIndex}运动异常", ex.GetExceptionMessage());
                    }
                } while (axisImmediatePauseFlag[optionPara.AxisIndex]);
                return isSuccessAndStop;
            });
        }
@@ -457,10 +509,10 @@
            var ret = GTSCardAPI.GT_GetPrfPos((short)IConfig.CardNum, (short)axisNum, out prfpos, 1, out pclock);
            if (ret != (short)GTSRetCode.GRCRunOK)
            {
                throw new Exception("轴" + axisNum + "获取规划位置异常,错误码:" + ret);
                throw new ProcessException("轴" + axisNum + "获取规划位置异常,错误码:" + ret);
            }
            var AxisRatio = IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum) == null ? 1 : IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum).AxisRatio;
            position = prfpos / AxisRatio;
            //var AxisRatio = IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum) == null ? 1 : IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum).AxisRatio;
            position = prfpos;
            return position;
        }
@@ -474,14 +526,14 @@
            lock (moveLock)
            {
                double position = 0;
                int pPos = 0;
                var ret = GTSCardAPI.GT_GetPos((short)IConfig.CardNum, (short)axisNum, out pPos);
                double pPos = 0;
                var ret = GTSCardAPI.GT_GetPrfPos((short)IConfig.CardNum, (short)axisNum, out pPos, 1, out uint pclock);
                if (ret != (short)GTSRetCode.GRCRunOK)
                {
                    throw new Exception("轴" + axisNum + "获取目标位置异常,错误码:" + ret);
                    throw new ProcessException("轴" + axisNum + "获取目标位置异常,错误码:" + ret);
                }
                var AxisRatio = IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum) == null ? 1 : IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum).AxisRatio;
                position = pPos / AxisRatio;
                //var AxisRatio = IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum) == null ? 1 : IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum).AxisRatio;
                position = pPos;
                return position;
            }
        }
@@ -498,7 +550,7 @@
            var ret = GTSCardAPI.GT_GetPrfVel((short)IConfig.CardNum, (short)axisNum, out prfVel, 1, out pclock);
            if (ret != (short)GTSRetCode.GRCRunOK)
            {
                throw new Exception("轴" + axisNum + "获取规划速度异常,错误码:" + ret);
                throw new ProcessException("轴" + axisNum + "获取规划速度异常,错误码:" + ret);
            }
            return prfVel;
        }
@@ -514,7 +566,7 @@
            var ret = GTSCardAPI.GT_GetVel((short)IConfig.CardNum, (short)axisNum, out vel);
            if (ret != (short)GTSRetCode.GRCRunOK)
            {
                throw new Exception("轴" + axisNum + "获取当前速度异常,错误码:" + ret);
                throw new ProcessException("轴" + axisNum + "获取当前速度异常,错误码:" + ret);
            }
            return vel;
        }
@@ -554,7 +606,7 @@
            catch (Exception ex)
            {
                AllMoveStop(true);
                OnExceptionRaised?.Invoke(ex);
                OnExceptionOccured?.Invoke(DateTime.Now, ex);
                return false;
            }
        }
@@ -572,7 +624,7 @@
                if (_isResetting)
                {
                    LogAsync(DateTime.Now, "复位过程异常", "轴" + optionPara.AxisIndex + "试图在复位过程中运动");
                    throw new Exception("轴" + optionPara.AxisIndex + "试图在复位过程中运动");
                    throw new ProcessException("轴" + optionPara.AxisIndex + "试图在复位过程中运动");
                }
                int repeatTime = 30;
@@ -591,7 +643,7 @@
                if (CurrentState != EnumHelper.DeviceState.DSOpen)
                {
                    LogAsync(DateTime.Now, "非正常状态异常", "轴" + optionPara.AxisIndex + "试图在非正常状态运动");
                    throw new Exception("轴" + optionPara.AxisIndex + "试图在非正常状态运动", null);
                    throw new ProcessException("轴" + optionPara.AxisIndex + "试图在非正常状态运动", null);
                }
                LogAsync(DateTime.Now, "轴" + optionPara.AxisIndex + "开始运动", "目标坐标:" + optionPara.Destination);
@@ -605,7 +657,7 @@
                {
                    //设置 运动参数
                    isSuccessSetAxisParam = SetAxisParam(optionPara);
                    ret = GTSCardAPI.GT_SetPrfPos((short)IConfig.CardNum, (short)optionPara.AxisIndex, (int)(dPosition * AxisRatio));// 设置规划位置
                    ret = GTSCardAPI.GT_SetPos((short)IConfig.CardNum, (short)optionPara.AxisIndex, (int)(dPosition));// 设置目的位置
                    ret = GTSCardAPI.GT_Update((short)IConfig.CardNum, 1 << (optionPara.AxisIndex - 1));//更新运动
                    if (ret != (short)GTSRetCode.GRCRunOK)
@@ -625,8 +677,8 @@
                repeatTime = 1000;
                do
                {
                    isStop = IsStop((short)optionPara.AxisIndex);
                    Thread.Sleep(50);
                    isStop = IsStop((short)optionPara.AxisIndex);
                    repeatTime--;
                } while (!isStop && repeatTime > 0);
@@ -635,7 +687,7 @@
            catch (Exception ex)
            {
                AllMoveStop(true);
                OnExceptionRaised?.Invoke(ex);
                OnExceptionOccured?.Invoke(DateTime.Now, ex);
                return false;
            }
        }
@@ -653,7 +705,7 @@
                if (_isResetting)
                {
                    LogAsync(DateTime.Now, "复位过程异常", "轴" + optionPara.AxisIndex + "试图在复位过程中运动");
                    throw new Exception("轴" + optionPara.AxisIndex + "试图在复位过程中运动");
                    throw new ProcessException("轴" + optionPara.AxisIndex + "试图在复位过程中运动");
                }
                int repeatTime = 30;
                while (CurrentState != EnumHelper.DeviceState.DSOpen && repeatTime > 0)
@@ -670,18 +722,18 @@
                if (CurrentState != EnumHelper.DeviceState.DSOpen)
                {
                    LogAsync(DateTime.Now, "非正常状态异常", "轴" + optionPara.AxisIndex + "试图在非正常状态运动");
                    throw new Exception("轴" + optionPara.AxisIndex + "试图在非正常状态运动", null);
                    throw new ProcessException("轴" + optionPara.AxisIndex + "试图在非正常状态运动", null);
                }
                LogAsync(DateTime.Now, "轴" + optionPara.AxisIndex + "开始运动", "目标坐标:" + optionPara.Destination);
                short ret = 0;
                bool isSuccessSetAxisParam = false;
                int timeout = optionPara.MovingTimeout;
                var AxisRatio = IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == optionPara.AxisIndex) == null ? 1 : IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == optionPara.AxisIndex).AxisRatio;
                //var AxisRatio = IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == optionPara.AxisIndex) == null ? 1 : IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == optionPara.AxisIndex).AxisRatio;
                while (CurrentState == DeviceState.DSOpen && !_isPause)
                {
                    //设置 运动参数
                    isSuccessSetAxisParam = SetAxisParam(optionPara);
                    ret = GTSCardAPI.GT_SetPrfPos((short)IConfig.CardNum, (short)optionPara.AxisIndex, (int)(optionPara.Destination * AxisRatio));// 设置规划位置
                    ret = GTSCardAPI.GT_SetPos((short)IConfig.CardNum, (short)optionPara.AxisIndex, (int)(optionPara.Destination));// 设置目标位置
                    ret = GTSCardAPI.GT_Update((short)IConfig.CardNum, 1 << (optionPara.AxisIndex - 1));//更新运动
                    if (ret != (short)GTSRetCode.GRCRunOK)
@@ -700,8 +752,8 @@
                repeatTime = 1000;
                while (!isStop && repeatTime > 0)
                {
                    isStop = IsStop((short)optionPara.AxisIndex);
                    Thread.Sleep(50);
                    isStop = IsStop((short)optionPara.AxisIndex);
                    repeatTime--;
                }
@@ -710,7 +762,7 @@
            catch (Exception ex)
            {
                AllMoveStop(true);
                OnExceptionRaised?.Invoke(ex);
                OnExceptionOccured?.Invoke(DateTime.Now, ex);
                return false;
            }
        }
@@ -734,7 +786,7 @@
                if (ret != (short)GTSRetCode.GRCRunOK)
                {
                    LogAsync(DateTime.Now, "轴" + axisNum + "运动停止异常", "错误码:" + ret);
                    throw new Exception("轴" + axisNum + "运动停止异常,错误码:" + ret);
                    throw new ProcessException("轴" + axisNum + "运动停止异常,错误码:" + ret);
                }
                else
                {
@@ -743,8 +795,8 @@
                int repeatTime = 100;
                do
                {
                    isStop = IsStop((short)axisNum);
                    Thread.Sleep(10);
                    isStop = IsStop((short)axisNum);
                    repeatTime--;
                } while (!isStop && repeatTime > 0);
@@ -770,54 +822,160 @@
            var resultOK = taskList.All(u => u.GetAwaiter().GetResult());
        }
        ///// <summary>
        ///// 回原点
        ///// </summary>
        ///// <param name="movingOption">卡号</param>
        ///// <param name="axisn">轴号</param>
        ///// <param name="homests">轴回原点状态</param>
        //public bool GoHome(MovingOption movingOption)
        //{
        //    try
        //    {
        //        PositionReset(movingOption.AxisIndex, 1);
        //        GTSCardAPI.THomePrm thomeprm;
        //        GTSCardAPI.THomeStatus homests;
        //        // 启动Home捕获
        //        short rtn = GTSCardAPI.GT_SetCaptureMode((short)IConfig.CardNum, (short)movingOption.AxisIndex, GTSCardAPI.CAPTURE_HOME);
        //        // 切换到点位运动模式
        //        rtn = GTSCardAPI.GT_PrfTrap((short)IConfig.CardNum, (short)movingOption.AxisIndex);
        //        // 读取点位模式运动参数
        //        rtn = GTSCardAPI.GT_GetHomePrm((short)IConfig.CardNum, (short)movingOption.AxisIndex, out thomeprm);
        //        thomeprm.mode = movingOption.GoHomePara.HomeMode;//回零方式
        //        thomeprm.moveDir = movingOption.GoHomePara.HomeDir;//回零方向
        //        thomeprm.edge = movingOption.GoHomePara.Edge;
        //        thomeprm.velHigh = movingOption.GoHomePara.HighVelocity;
        //        thomeprm.velLow = movingOption.GoHomePara.LowVelocity;
        //        thomeprm.acc = movingOption.VelocityPara.Acc;
        //        thomeprm.dec = movingOption.VelocityPara.Dec;
        //        thomeprm.searchHomeDistance = movingOption.GoHomePara.SearchHomeDistance;//搜索距离
        //        thomeprm.homeOffset = movingOption.GoHomePara.HomeOffset;  //偏移距离
        //        thomeprm.escapeStep = movingOption.GoHomePara.EscapeStep;
        //        rtn = GTSCardAPI.GT_GoHome((short)IConfig.CardNum, (short)movingOption.AxisIndex, ref thomeprm);  //启动回零
        //        bool isStop = false;
        //        int repeatTime = 1000;
        //        do
        //        {
        //            Thread.Sleep(10);
        //            GTSCardAPI.GT_GetHomeStatus((short)IConfig.CardNum, (short)movingOption.AxisIndex, out homests);
        //            isStop = homests.run == 0;
        //            if (isStop && homests.error == 0)
        //            {
        //                Thread.Sleep(200);
        //                PositionReset(movingOption.AxisIndex, 1);
        //            }
        //            repeatTime--;
        //        } while (!isStop && repeatTime > 0);
        //        return isStop;
        //    }
        //    catch (Exception ex)
        //    {
        //        AllMoveStop(true);
        //        OnExceptionOccured?.Invoke(DateTime.Now, ex);
        //        return false;
        //    }
        //}
        /// <summary>
        /// 回原点
        /// P2P方式回原点
        /// </summary>
        /// <param name="movingOption">卡号</param>
        /// <param name="axisn">轴号</param>
        /// <param name="homests">轴回原点状态</param>
        public bool GoHome(MovingOption movingOption)
        /// <param name="movingOption">运动参数</param>
        public bool P2PGoHome(MovingOption movingOption)
        {
            try
            {
                PositionReset(movingOption.AxisIndex, 1);
                GTSCardAPI.THomePrm thomeprm;
                GTSCardAPI.THomeStatus homests;
                short rtn = GTSCardAPI.GT_GetHomePrm((short)IConfig.CardNum, (short)movingOption.AxisIndex, out thomeprm);
                thomeprm.mode = movingOption.GoHomePara.HomeMode;//回零方式
                thomeprm.moveDir = movingOption.GoHomePara.HomeDir;//回零方向
                thomeprm.edge = movingOption.GoHomePara.Edge;
                thomeprm.velHigh = movingOption.GoHomePara.HighVelocity;
                thomeprm.velLow = movingOption.GoHomePara.LowVelocity;
                thomeprm.acc = movingOption.VelocityPara.Acc;
                thomeprm.dec = movingOption.VelocityPara.Dec;
                thomeprm.searchHomeDistance = movingOption.GoHomePara.SearchHomeDistance;//搜搜距离
                thomeprm.homeOffset = movingOption.GoHomePara.HomeOffset;  //偏移距离
                thomeprm.escapeStep = movingOption.GoHomePara.EscapeStep;
                rtn = GTSCardAPI.GT_GoHome((short)IConfig.CardNum, (short)movingOption.AxisIndex, ref thomeprm);  //启动回零
                StartCapture:
                PositionReset(movingOption.AxisIndex, 1);
                ClearStatus(movingOption.AxisIndex, 1);
                GTSCardAPI.TTrapPrm trapPrm;
                bool isStop = false;
                //搜索距离 阶段1
                // 启动Home捕获
                short sRtn = GTSCardAPI.GT_SetCaptureMode((short)IConfig.CardNum, (short)movingOption.AxisIndex, GTSCardAPI.CAPTURE_HOME);
                // 切换到点位运动模式
                sRtn = GTSCardAPI.GT_PrfTrap((short)IConfig.CardNum, (short)movingOption.AxisIndex);
                // 读取点位模式运动参数
                sRtn = GTSCardAPI.GT_GetTrapPrm((short)IConfig.CardNum, (short)movingOption.AxisIndex, out trapPrm);
                trapPrm.acc = movingOption.VelocityPara.Acc;
                trapPrm.dec = movingOption.VelocityPara.Dec;
                // 设置点位模式运动参数
                sRtn = GTSCardAPI.GT_SetTrapPrm((short)IConfig.CardNum, (short)movingOption.AxisIndex, ref trapPrm);
                // 设置点位模式目标速度,即回原点速度
                sRtn = GTSCardAPI.GT_SetVel((short)IConfig.CardNum, (short)movingOption.AxisIndex, movingOption.GoHomePara.HighVelocity);
                // 设置点位模式目标位置,即原点搜索距离
                sRtn = GTSCardAPI.GT_SetPos((short)IConfig.CardNum, (short)movingOption.AxisIndex, movingOption.GoHomePara.HomeDir == 1 ? 99999999 : -99999999);
                // 启动运动
                sRtn = GTSCardAPI.GT_Update((short)IConfig.CardNum, 1 << (movingOption.AxisIndex - 1));
                int repeatTime = 1000;
                short capture;
                int pos;
                uint clk;//时钟参数
                do
                {
                    Thread.Sleep(10);
                    GTSCardAPI.GT_GetHomeStatus((short)IConfig.CardNum, (short)movingOption.AxisIndex, out homests);
                    isStop = homests.run == 0;
                    if (isStop && homests.error == 0)
                    {
                        Thread.Sleep(200);
                        PositionReset(movingOption.AxisIndex, 1);
                    }
                    Thread.Sleep(20);
                    // 读取捕获状态
                    GTSCardAPI.GT_GetCaptureStatus((short)IConfig.CardNum, (short)movingOption.AxisIndex, out capture, out pos, 1, out clk);
                    isStop = IsStop((short)movingOption.AxisIndex);
                    repeatTime--;
                } while (!isStop && repeatTime > 0);
                } while (!(isStop || capture == 1 || repeatTime <= 0));
                return isStop;
                if (repeatTime <= 0)
                {
                    MoveStop((short)movingOption.AxisIndex, 0);
                    throw new ProcessException($"运动轴{movingOption.AxisIndex} ,回原点超时异常");
                }
                if (isStop && capture != 1)
                {
                    ClearStatus((short)movingOption.AxisIndex, 1);
                    var axisStatus = AxisStatusList.FirstOrDefault(u => u.AxisIndex == movingOption.AxisIndex);
                    if (((axisStatus.AxisStatus & 0x20) != 0) || ((axisStatus.AxisStatus & 0x40) != 0))
                    {
                        movingOption.GoHomePara.HomeDir = (short)(movingOption.GoHomePara.HomeDir == 1 ? -1 : 1);
                        goto StartCapture;
                    }
                    throw new ProcessException($"运动轴{movingOption.AxisIndex} ,回原点超时异常");
                }
                if (capture == 1)
                {
                    //先stop
                    MoveStop((short)movingOption.AxisIndex, 0);
                    ClearStatus((short)movingOption.AxisIndex, 1);
                    //已经捕获到Home才可以回零 阶段2
                    // 运动到"捕获位置+偏移量"
                    sRtn = GTSCardAPI.GT_SetPos((short)IConfig.CardNum, (short)movingOption.AxisIndex, pos + movingOption.GoHomePara.HomeOffset);
                    // 在运动状态下更新目标位置
                    sRtn = GTSCardAPI.GT_Update((short)IConfig.CardNum, 1 << (movingOption.AxisIndex - 1));
                    isStop = false;
                    repeatTime = 1000;
                    do
                    {
                        Thread.Sleep(20);
                        isStop = IsStop((short)movingOption.AxisIndex);
                        repeatTime--;
                    } while (!isStop && repeatTime > 0);
                    PositionReset(movingOption.AxisIndex, 1);
                    return (sRtn == (short)GTSRetCode.GRCRunOK) && isStop;
                }
                return false;
            }
            catch (Exception ex)
            {
                AllMoveStop(true);
                OnExceptionRaised?.Invoke(ex);
                OnExceptionOccured?.Invoke(DateTime.Now, ex);
                return false;
            }
        }
@@ -854,13 +1012,13 @@
        /// 按位设置数字 IO 输出状态
        /// </summary>
        /// <param name="index">输出口,返回1-16</param>
        /// <param name="value">false表示输出,true表示关闭</param>
        /// <param name="value">false表示关,true表示开,板卡要设置取反</param>
        public override void WriteOutput(short index, IOValue value)
        {
            short outNum = (short)(index % 100 + 1);
            if ((int)value <= 1)
            {
                GTSCardAPI.GT_SetDoBit((short)IConfig.CardNum, GTSCardAPI.MC_GPO, outNum, (short)value);
                GTSCardAPI.GT_SetDoBit((short)IConfig.CardNum, GTSCardAPI.MC_GPO, outNum, IConfig.IsOutputReversed ? (short)(value == IOValue.TRUE ? 0 : 1) : (short)value);
            }
            else
            {
@@ -877,7 +1035,7 @@
        /// <returns></returns>
        public bool IsStop(short axisNum)
        {
            int sts = GetAxisStatus(axisNum);
            int sts = AxisStatusList.FirstOrDefault(u => u.AxisIndex == axisNum).AxisStatus;
            if ((sts & 0x400) == 0) return true;//停止返回true
            else return false;              //运行中返回false
        }
@@ -931,10 +1089,10 @@
                AxisMovingStatus axisMovingStatus = new AxisMovingStatus();
                axisMovingStatus.AxisIndex = axisConfig.AxisIndex;
                axisMovingStatus.AxisName = axisConfig.AxisName;
                axisMovingStatus.CurPosition = Convert.ToInt32(GetPosition(axisMovingStatus.AxisIndex));
                //axisMovingStatus.CurPosition = Convert.ToInt32(GetPosition(axisMovingStatus.AxisIndex));
                axisMovingStatus.Destination = Convert.ToInt32(GetPrfPosition(axisMovingStatus.AxisIndex));
                axisMovingStatus.CurVelocity = GetVelocity(axisMovingStatus.AxisIndex);
                axisMovingStatus.PrfVelocity = GetPrfVelocity(axisMovingStatus.AxisIndex);
                //axisMovingStatus.CurVelocity = GetVelocity(axisMovingStatus.AxisIndex);
                //axisMovingStatus.PrfVelocity = GetPrfVelocity(axisMovingStatus.AxisIndex);
                axisMovingStatus.AxisStatus = GetAxisStatus(axisMovingStatus.AxisIndex);
                axisMovingStatusesList.Add(axisMovingStatus);
@@ -956,7 +1114,7 @@
            GTSCardAPI.GT_GetDo((short)IConfig.CardNum, GTSCardAPI.MC_GPO, out outValue);
            //解析结果
            for (var index = 1; index <= 16; index++)
            for (var index = 0; index < 16; index++)
            {
                IOItem inItem = new IOItem()
                {
@@ -987,28 +1145,39 @@
                    {
                        if (!IConfig.IsEnableMonitor)
                            return;
                        var newValues = GetMonitorValues();
                        var newAxisMovingStatus = GetAxisMovingStatus();
                        if (newValues == null || newValues.Count == 0 || newAxisMovingStatus == null || newAxisMovingStatus.Count == 0)
                            continue;
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        //Stopwatch sw = new Stopwatch();
                        //sw.Start();
                        if (MonitorValues.Count == newValues.Count)
                        {
                            var tempNew = newValues.DeepSerializeClone();//clone
                            var tempOld = MonitorValues.DeepSerializeClone();
                            //var tempNew = newValues.DeepSerializeClone();//clone
                            //var tempOld = MonitorValues.DeepSerializeClone();
                            var tempNew = new List<IOItem>(newValues);//clone
                            var tempOld = new List<IOItem>(MonitorValues);
                            MonitorCheckAndInvoke(tempNew, tempOld);
                        }
                        AxisMovingOptionValues = new List<AxisMovingStatus>(newAxisMovingStatus);
                        MonitorValues = new List<IOItem>(newValues);
                        sw.Stop();
                        if (sw.ElapsedMilliseconds > 20)
                        if (AxisStatusList.Count == newAxisMovingStatus.Count)
                        {
                            LogAsync(DateTime.Now, $"{this.Name}轮询时间:{sw.ElapsedMilliseconds}", "");
                            var tempNew = new List<AxisMovingStatus>(newAxisMovingStatus);//clone
                            var tempOld = new List<AxisMovingStatus>(AxisStatusList);
                            AxisStatusCheck(tempNew, tempOld);
                        }
                        AxisStatusList = new List<AxisMovingStatus>(newAxisMovingStatus);
                        MonitorValues = new List<IOItem>(newValues);
                        //sw.Stop();
                        //if (sw.ElapsedMilliseconds > 20)
                        //{
                        //    LogAsync(DateTime.Now, $"{this.Name}轮询时间:{sw.ElapsedMilliseconds}", "");
                        //}
                        if (IConfig.MonitorInterval > 0)
                        {
@@ -1021,6 +1190,29 @@
                        if (CurrentState == DeviceState.DSOpen)
                        {
                            LogAsync(DateTime.Now, $"{this.Name}监听异常", ex.GetExceptionMessage());
                        }
                    }
                }
            });
        }
        private async void AxisStatusCheck(List<AxisMovingStatus> tempNew, List<AxisMovingStatus> tempOld)
        {
            await Task.Run(() =>
            {
                foreach (var newSts in tempNew)
                {
                    var oldSts = tempOld.FirstOrDefault(u => u.AxisIndex == newSts.AxisIndex);
                    if (oldSts != null)
                    {
                        if (oldSts.AxisStatus != newSts.AxisStatus)
                        {
                            AxisStatusChanged(newSts.AxisIndex, oldSts.AxisStatus, newSts.AxisStatus);
                        }
                        if (((newSts.AxisStatus >> 1 & 1) == 1) && ((oldSts.AxisStatus >> 1 & 1) == 0)) //初次报警
                        {
                            AxisAlarmRaised(newSts.AxisStatus, $"轴{newSts.AxisIndex}:{newSts.AxisName}轴伺服报警");
                        }
                    }
                }
@@ -1094,8 +1286,9 @@
                        //monitorSet.OpConfig.InputPara = monitorSet.InputDataIndex.ConvertAll(index =>
                        //{
                        //    return tempNew[index].Value;
                        //    return tempNew[index].Value == IOValue.TRUE ? 1 : 0;
                        //}).ToList();
                        monitorSet.OpConfig.InputPara = new List<int>() { (int)newIOItem.Value };
                        ExcuteMonitorInvoke(DateTime.Now, monitorSet.InvokeDevice, this, monitorSet);
                    }
@@ -1109,15 +1302,22 @@
            int axis_sts;
            var axisSettings = IConfig.AxisSettings.FindAll(u => u.IsAxisEnabled);
            ClearStatus(1, axisSettings.Count);
            if (AxisStatusList.Count == 0)
            {
                Thread.Sleep(10);
            }
            foreach (var axisSetting in axisSettings)
            {
                axis_sts = GetAxisStatus((short)axisSetting.AxisIndex);
                //axis_sts = GetAxisStatus((short)axisSetting.AxisIndex);
                axis_sts = AxisStatusList.FirstOrDefault(u => u.AxisIndex == axisSetting.AxisIndex)?.AxisStatus ?? 0;
                if ((axis_sts & 0x200) == 0)
                {
                    var rst = GTSCardAPI.GT_AxisOn((short)IConfig.CardNum, (short)axisSetting.AxisIndex);
                }
                // 所有位置请零
                PositionReset(1, axisSettings.Count);
                //// 所有位置请零
                //PositionReset(1, axisSettings.Count);
                // 正极限报警
                if ((axis_sts & 0x20) != 0)
                {