领胜LDS 键盘AOI检测项目
xcd
2020-07-09 5b6ffebeeee53e375cf8f8d5c30c51f03ad1d96e
src/Bro.Device.GTSCard/GTSCardDriver.cs
@@ -37,6 +37,18 @@
        /// </summary>
        bool _isResetting = false;
        /// <summary>
        /// 是否暂停中
        /// </summary>
        bool _isPause = false;
        /// <summary>
        /// 运动轴立即暂停
        /// </summary>
        Dictionary<int, ManualResetEvent> axisImmediatePauseHandleDict = new Dictionary<int, ManualResetEvent>();
        //Dictionary<int, CancellationTokenSource> axisMoveCancelDict = new Dictionary<int, CancellationTokenSource>();
        public void SetResetFlag(bool isReset)
        {
            _isResetting = isReset;
@@ -44,7 +56,17 @@
        public override List<AxisInfo> GetCurrentAxisInfo(params string[] axisName)
        {
            throw new NotImplementedException();
            List<AxisInfo> axisInfos = new List<AxisInfo>();
            IConfig.AxisSettings.FindAll(a => a.IsAxisEnabled).ForEach(axisSetting =>
            {
                AxisInfo axisInfo = new AxisInfo();
                axisInfo.AxisName = axisSetting.AxisName;
                var axisMovingStatus = AxisMovingOptionValues.FirstOrDefault(u => u.AxisIndex == axisSetting.AxisIndex);
                axisInfo.AxisLocation = axisMovingStatus == null ? 0 : Convert.ToDouble(axisMovingStatus.CurPosition);
                axisInfos.Add(axisInfo);
            });
            return axisInfos;
        }
        #region DeviceBase
@@ -52,16 +74,23 @@
        protected override void Init()
        {
            InitialMotionCard();
            axisImmediatePauseHandleDict = IConfig.AxisSettings.FindAll(a => a.IsAxisEnabled).ToDictionary(a => a.AxisIndex, a => new ManualResetEvent(true));
            //axisMoveCancelDict = IConfig.AxisSettings.FindAll(a => a.IsAxisEnabled).ToDictionary(a => a.AxisIndex, a => new CancellationTokenSource());
            //axisMoveCancelDict.Values.ToList().ForEach(c =>
            //{
            //    c = new CancellationTokenSource();
            //});
        }
        protected override void Pause()
        {
            throw new NotImplementedException();
        }
        protected override void Resume()
        {
            throw new NotImplementedException();
        }
        protected override void Start()
@@ -83,13 +112,15 @@
        public override ResponseMessage Run(IOperationConfig config)
        {
            ResponseMessage responseMessage = new ResponseMessage();
            var motionCardOperationConfig = config as MotionCardOperationConfigBase;
            foreach (var operationSet in motionCardOperationConfig.OperationCollection)
            if (config is MotionCardOperationConfigBase motionCardOperationConfig)
            {
                responseMessage = RunOperationSet(operationSet);
                if (!responseMessage.Result)
                foreach (var operationSet in motionCardOperationConfig.OperationCollection)
                {
                    return responseMessage;
                    responseMessage = RunOperationSet(operationSet);
                    if (!responseMessage.Result)
                    {
                        return responseMessage;
                    }
                }
            }
            return responseMessage;
@@ -131,7 +162,7 @@
            // 2.板卡运动
            if (CurrentState == DeviceState.DSOpen)
            {
                responseMessage = MoveToPoint(operationSet.MotionOperationCollection);
                responseMessage = MoveToPoint(new MotionOperationCollection() { MovingOps = operationSet.MovingOps });
                if (!responseMessage.Result)
                {
                    return responseMessage;
@@ -185,6 +216,43 @@
        }
        #endregion
        #region ImmediatePause
        /// <summary>
        /// 启动立即暂停
        /// </summary>
        public void SetImmediatePause()
        {
            if (!_isResetting)
            {
                var immediatePauseAxis = IConfig.AxisSettings.FindAll(a => a.IsAxisEnabled && a.IsImmediatePause).Select(u => u.AxisIndex).ToList();
                immediatePauseAxis.ForEach(async axisIndex =>
                {
                    axisImmediatePauseHandleDict[axisIndex].Reset();
                    //axisMoveCancelDict[axisIndex].Cancel();
                    await MoveStop(axisIndex, 0);//所有轴都暂停
                });
            }
        }
        /// <summary>
        /// 恢复立即暂停
        /// </summary>
        public void ResetImmediatePause()
        {
            var immediatePauseAxis = IConfig.AxisSettings.FindAll(a => a.IsAxisEnabled && a.IsImmediatePause).Select(u => u.AxisIndex).ToList();
            immediatePauseAxis.ForEach(axisIndex =>
            {
                //axisMoveCancelDict[axisIndex] = new CancellationTokenSource();
                axisImmediatePauseHandleDict[axisIndex].Set();
            });
        }
        #endregion
        #region GTSCard
        /// <summary>
@@ -196,7 +264,7 @@
        {
            var res = GTSCardAPI.GT_Open((short)IConfig.CardNum, 0, 1); //打开运动控制器。参数必须为(0,1),不能修改。     
            res += GTSCardAPI.GT_LoadConfig((short)IConfig.CardNum, IConfig.InitialConfigFilePath);
            res += GTSCardAPI.GT_ClrSts(0, 1, 8);
            ClearStatus(1, IConfig.AxisSettings.FindAll(u => u.IsAxisEnabled).Count);
            if (res != (short)GTSRetCode.GRCRunOK)
            {
                throw new Exception("板卡载入配置文件异常,错误码:" + res);
@@ -204,13 +272,13 @@
        }
        public bool AllAxisOn()
        public override bool AllAxisOn()
        {
            List<Task<bool>> taskList = new List<Task<bool>>(); ;
            // 如果是多个轴的运动 等每个轴开启
            IConfig.AxisSettings.Where(a => a.IsAxisEnabled).ToList().ForEach(axisNum =>
            IConfig.AxisSettings.FindAll(a => a.IsAxisEnabled).ForEach(axisNum =>
            {
                var task = AxisOnAsync((short)IConfig.CardNum, (short)axisNum.AxisIndex);
                var task = AxisOnAsync(axisNum.AxisIndex);
                taskList.Add(task);
            });
            Task.WaitAll(taskList.ToArray());
@@ -218,13 +286,13 @@
            return resultOK;
        }
        public bool AllAxisOff()
        public override bool AllAxisOff()
        {
            List<Task<bool>> taskList = new List<Task<bool>>(); ;
            // 如果是多个轴的运动 等每个轴关闭
            IConfig.AxisSettings.Where(a => a.IsAxisEnabled).ToList().ForEach(axisNum =>
            IConfig.AxisSettings.FindAll(a => a.IsAxisEnabled).ForEach(axisNum =>
            {
                var task = AxisOffAsync((short)IConfig.CardNum, (short)axisNum.AxisIndex);
                var task = AxisOffAsync(axisNum.AxisIndex);
                taskList.Add(task);
            });
            Task.WaitAll(taskList.ToArray());
@@ -236,11 +304,11 @@
        /// 单个轴开启
        /// </summary>
        /// <returns></returns>
        public async Task<bool> AxisOnAsync(short cardNum, short axisNum)
        public override async Task<bool> AxisOnAsync(int axisNum)
        {
            return await Task.Run(() =>
            {
                var ret = GTSCardAPI.GT_AxisOn(cardNum, axisNum);
                var ret = GTSCardAPI.GT_AxisOn((short)IConfig.CardNum, (short)axisNum);
                return ret == (short)GTSRetCode.GRCRunOK;
            });
        }
@@ -249,11 +317,11 @@
        /// 单个轴关闭
        /// </summary>
        /// <returns></returns>
        public async Task<bool> AxisOffAsync(short cardNum, short axisNum)
        public override async Task<bool> AxisOffAsync(int axisNum)
        {
            return await Task.Run(() =>
            {
                var ret = GTSCardAPI.GT_AxisOff(cardNum, axisNum);
                var ret = GTSCardAPI.GT_AxisOff((short)IConfig.CardNum, (short)axisNum);
                return ret == (short)GTSRetCode.GRCRunOK;
            });
        }
@@ -266,19 +334,21 @@
        public override ResponseMessage MoveToPoint(IOperationConfig opConfig)
        {
            ResponseMessage responseMessage = new ResponseMessage();
            var gtsOperationCollection = opConfig as MotionOperationCollection;
            List<Task<bool>> taskList = new List<Task<bool>>();
            foreach (var movingOp in gtsOperationCollection.MovingOps)
            if (opConfig is MotionOperationCollection gtsOperationCollection)
            {
                var task = SingleAxisMoving(movingOp);
                taskList.Add(task);
            }
                List<Task<bool>> taskList = new List<Task<bool>>();
                foreach (var movingOp in gtsOperationCollection.MovingOps)
                {
                    var task = SingleAxisMoving(movingOp);
                    taskList.Add(task);
                }
            Task.WaitAll(taskList.ToArray());
            responseMessage.Result = taskList.All(u => u.GetAwaiter().GetResult());
            if (!responseMessage.Result)
            {
                responseMessage.Message = $"点位运动异常";
                Task.WaitAll(taskList.ToArray());
                responseMessage.Result = taskList.All(u => u.GetAwaiter().GetResult());
                if (!responseMessage.Result)
                {
                    responseMessage.Message = $"点位运动异常";
                }
            }
            return responseMessage;
        }
@@ -292,14 +362,15 @@
        {
            List<short> resultCode = new List<short>() { 0 };
            GTSCardAPI.TTrapPrm trapprm = new GTSCardAPI.TTrapPrm();
            resultCode.Add(GTSCardAPI.GT_PrfTrap((short)IConfig.CardNum, (short)optionPara.AxisIndex));
            resultCode.Add(GTSCardAPI.GT_GetTrapPrm((short)IConfig.CardNum, (short)optionPara.AxisIndex, out trapprm));
            short axisIndex = short.Parse(optionPara.AxisIndexStr);
            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;
            resultCode.Add(GTSCardAPI.GT_SetTrapPrm((short)IConfig.CardNum, (short)optionPara.AxisIndex, ref trapprm));
            resultCode.Add(GTSCardAPI.GT_SetVel((short)IConfig.CardNum, (short)optionPara.AxisIndex, optionPara.VelocityPara.Velocity * IConfig.AxisVelocityRatio));
            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));
            var resultOK = resultCode.All(u => u == (short)GTSRetCode.GRCRunOK);
            if (!resultOK)
@@ -313,10 +384,11 @@
        /// 单个轴 运动(点到点 jog 回零...)
        /// </summary>
        /// <param name="optionPara">运动参数对象</param>
        public async Task<bool> SingleAxisMoving(MovingOption optionPara)
        public override async Task<bool> SingleAxisMoving(MovingOption optionPara)
        {
            return await Task.Run(() =>
            {
                axisImmediatePauseHandleDict[optionPara.AxisIndex].WaitOne();
                bool isSuccessAndStop = false;
                try
                {
@@ -387,7 +459,8 @@
            {
                throw new Exception("轴" + axisNum + "获取规划位置异常,错误码:" + ret);
            }
            position = prfpos / IConfig.AxisVelocityRatio;
            var AxisRatio = IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum) == null ? 1 : IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum).AxisRatio;
            position = prfpos / AxisRatio;
            return position;
        }
@@ -407,7 +480,8 @@
                {
                    throw new Exception("轴" + axisNum + "获取目标位置异常,错误码:" + ret);
                }
                position = pPos / IConfig.AxisVelocityRatio;
                var AxisRatio = IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum) == null ? 1 : IConfig.AxisSettings.FirstOrDefault(u => u.AxisIndex == axisNum).AxisRatio;
                position = pPos / AxisRatio;
                return position;
            }
        }
@@ -416,7 +490,7 @@
        /// 获取规划速度
        /// </summary>
        /// <param name="axisNum">Axis number</param>
        /// <returns></returns>
        /// <returns>速度脉冲</returns>
        public double GetPrfVelocity(int axisNum)
        {
            double prfVel = 0;
@@ -426,7 +500,6 @@
            {
                throw new Exception("轴" + axisNum + "获取规划速度异常,错误码:" + ret);
            }
            prfVel = prfVel / IConfig.AxisVelocityRatio;
            return prfVel;
        }
@@ -434,7 +507,7 @@
        /// 获取当前速度
        /// </summary>
        /// <param name="axisNum">Axis number</param>
        /// <returns></returns>
        /// <returns>速度脉冲</returns>
        public double GetVelocity(int axisNum)
        {
            double vel = 0;
@@ -443,7 +516,6 @@
            {
                throw new Exception("轴" + axisNum + "获取当前速度异常,错误码:" + ret);
            }
            vel = vel / IConfig.AxisVelocityRatio;
            return vel;
        }
@@ -528,11 +600,12 @@
                int currentPosition = (int)GetPosition(optionPara.AxisIndex);
                int dPosition = optionPara.Destination + currentPosition;
                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;
                while (CurrentState == DeviceState.DSOpen)
                {
                    //设置 运动参数
                    isSuccessSetAxisParam = SetAxisParam(optionPara);
                    ret = GTSCardAPI.GT_SetPrfPos((short)IConfig.CardNum, (short)optionPara.AxisIndex, (int)(dPosition * IConfig.AxisVelocityRatio));// 设置规划位置
                    ret = GTSCardAPI.GT_SetPrfPos((short)IConfig.CardNum, (short)optionPara.AxisIndex, (int)(dPosition * AxisRatio));// 设置规划位置
                    ret = GTSCardAPI.GT_Update((short)IConfig.CardNum, 1 << (optionPara.AxisIndex - 1));//更新运动
                    if (ret != (short)GTSRetCode.GRCRunOK)
@@ -575,6 +648,8 @@
        {
            try
            {
                axisImmediatePauseHandleDict[optionPara.AxisIndex].WaitOne();
                if (_isResetting)
                {
                    LogAsync(DateTime.Now, "复位过程异常", "轴" + optionPara.AxisIndex + "试图在复位过程中运动");
@@ -601,11 +676,12 @@
                short ret = 0;
                bool isSuccessSetAxisParam = false;
                int timeout = optionPara.MovingTimeout;
                while (CurrentState == DeviceState.DSOpen)
                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 * IConfig.AxisVelocityRatio));// 设置规划位置
                    ret = GTSCardAPI.GT_SetPrfPos((short)IConfig.CardNum, (short)optionPara.AxisIndex, (int)(optionPara.Destination * AxisRatio));// 设置规划位置
                    ret = GTSCardAPI.GT_Update((short)IConfig.CardNum, 1 << (optionPara.AxisIndex - 1));//更新运动
                    if (ret != (short)GTSRetCode.GRCRunOK)
@@ -622,12 +698,12 @@
                bool isStop = false;
                repeatTime = 1000;
                do
                while (!isStop && repeatTime > 0)
                {
                    isStop = IsStop((short)optionPara.AxisIndex);
                    Thread.Sleep(50);
                    repeatTime--;
                } while (!isStop && repeatTime > 0);
                }
                return (ret == (short)GTSRetCode.GRCRunOK) && isStop;
            }
@@ -645,7 +721,7 @@
        /// <param name="axisNum">axisNo</param>
        /// <param name="option">0表示平滑停止,1表示紧急停止</param>
        /// <returns></returns>
        public async Task<bool> MoveStop(int axisNum, int option)
        public override async Task<bool> MoveStop(int axisNum, int option)
        {
            return await Task.Run(() =>
            {
@@ -704,7 +780,7 @@
        {
            try
            {
                GTSCardAPI.GT_ZeroPos((short)IConfig.CardNum, (short)movingOption.AxisIndex, 1);
                PositionReset(movingOption.AxisIndex, 1);
                GTSCardAPI.THomePrm thomeprm;
                GTSCardAPI.THomeStatus homests;
                short rtn = GTSCardAPI.GT_GetHomePrm((short)IConfig.CardNum, (short)movingOption.AxisIndex, out thomeprm);
@@ -731,7 +807,7 @@
                    if (isStop && homests.error == 0)
                    {
                        Thread.Sleep(200);
                        GTSCardAPI.GT_ZeroPos((short)IConfig.CardNum, (short)movingOption.AxisIndex, 1);
                        PositionReset(movingOption.AxisIndex, 1);
                    }
                    repeatTime--;
                } while (!isStop && repeatTime > 0);
@@ -809,10 +885,9 @@
        /// <summary>
        /// 读取轴状态
        /// </summary>
        /// <param name="cardNum">板卡号</param>
        /// <param name="axisNum">轴号</param>
        /// <returns></returns>
        public int GetAxisStatus(int axisNum)
        public override int GetAxisStatus(int axisNum)
        {
            lock (moveLock)
            {
@@ -822,6 +897,28 @@
                return sts;
            }
        }
        public override bool ClearStatus(int startAxisIndex, int count)
        {
            var rtn = GTSCardAPI.GT_ClrSts((short)IConfig.CardNum, (short)startAxisIndex, (short)count);
            return rtn == (short)GTSRetCode.GRCRunOK;
        }
        /// <summary>
        /// 位置回零
        /// </summary>
        /// <param name="startAxisIndex"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public override bool PositionReset(int startAxisIndex, int count)
        {
            lock (moveLock)
            {
                var rtn = GTSCardAPI.GT_ZeroPos((short)IConfig.CardNum, (short)startAxisIndex, (short)count);
                return rtn == (short)GTSRetCode.GRCRunOK;
            }
        }
        #endregion
        #region IMonitor
@@ -932,27 +1029,27 @@
        public override void OnMethodInvoked(IAsyncResult ar)
        {
            MotionCardMonitorSet monitorSet = ar.AsyncState as MotionCardMonitorSet;
            ProcessResponse resValues = monitorSet.Response;
            if (resValues.ResultValue == (int)ReplyValue.IGNORE)
            {
                return;
            }
            //MotionCardMonitorSet monitorSet = ar.AsyncState as MotionCardMonitorSet;
            //ProcessResponse resValues = monitorSet.Response;
            //if (resValues.ResultValue == (int)ReplyValue.IGNORE)
            //{
            //    return;
            //}
            Stopwatch sw = new Stopwatch();
            sw.Start();
            // 将指定IOItem写入板卡
            foreach (var replyIOData in monitorSet.ReplyIODatas)
            {
                //写入IO输出
                if (replyIOData.IOType == IOType.OUTPUT)
                {
                    GTSCardAPI.GT_SetDoBit((short)IConfig.CardNum, GTSCardAPI.MC_GPI, (short)replyIOData.IONum, (short)replyIOData.Value);
                }
                // in只读不能写
            }
            sw.Stop();
            LogAsync(DateTime.Now, $"{Name}反馈完成,耗时{sw.ElapsedMilliseconds}ms", $"{resValues.GetDisplayText()}");
            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            //// 将指定IOItem写入板卡
            //foreach (var replyIOData in monitorSet.ReplyIODatas)
            //{
            //    //写入IO输出
            //    if (replyIOData.IOType == IOType.OUTPUT)
            //    {
            //        GTSCardAPI.GT_SetDoBit((short)IConfig.CardNum, GTSCardAPI.MC_GPI, (short)replyIOData.IONum, (short)replyIOData.Value);
            //    }
            //    // in只读不能写
            //}
            //sw.Stop();
            //LogAsync(DateTime.Now, $"{Name}反馈完成,耗时{sw.ElapsedMilliseconds}ms", $"{resValues.GetDisplayText()}");
        }
        protected void MonitorCheckAndInvoke(List<IOItem> tempNew, List<IOItem> tempOld)
@@ -1011,7 +1108,7 @@
        {
            int axis_sts;
            var axisSettings = IConfig.AxisSettings.FindAll(u => u.IsAxisEnabled);
            GTSCardAPI.GT_ClrSts((short)IConfig.CardNum, 1, (short)axisSettings.Count);
            ClearStatus(1, axisSettings.Count);
            foreach (var axisSetting in axisSettings)
            {
                axis_sts = GetAxisStatus((short)axisSetting.AxisIndex);
@@ -1019,8 +1116,8 @@
                {
                    var rst = GTSCardAPI.GT_AxisOn((short)IConfig.CardNum, (short)axisSetting.AxisIndex);
                }
                // 位置请零
                GTSCardAPI.GT_ZeroPos((short)IConfig.CardNum, 1, (short)axisSettings.Count);
                // 所有位置请零
                PositionReset(1, axisSettings.Count);
                // 正极限报警
                if ((axis_sts & 0x20) != 0)
                {
@@ -1045,7 +1142,7 @@
            }
            // 清除状态
            GTSCardAPI.GT_ClrSts((short)IConfig.CardNum, 1, (short)IConfig.AxisSettings.FindAll(u => u.IsAxisEnabled).Count);
            ClearStatus(1, axisSettings.Count);
        }
        object _alarmLock = new object();