DeviceBase.cs 13.7 KB
using OnlineStore;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using RemoteSheardObject;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DeviceLibrary
{
    public class DeviceBase
    {
        public static Dictionary<int, IDevice> DeviceListByAddr = new Dictionary<int, IDevice>();
        public string CurrrentRFID = "";
        public TrayInfo CurrrentTrayInfo { get => TrayManager.Traylist[CurrrentRFID]; }
        public MsgService Msg { get; set; }
        public string Name { get; set; }
        public string GroupName { get; set; }
        System.Timers.Timer timer;
        public DeviceBase() {
            timer = new System.Timers.Timer(5000);
            timer.Elapsed += Timer_Elapsed;
            timer.Enabled = true;
            
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            EquipMsgData equipMsg = new EquipMsgData();
            equipMsg.msgList = new List<EquipMessage>();
            equipMsg.status = 0;
            Msg.msg.ForEach(ml =>
            {
                equipMsg.msgList.Add(new EquipMessage()
                {
                    msg = ml.msgtxt,
                    type = EquipMessage.ConvertType(ml.msgLevel.ToString())
                });
                if (ml.msgLevel == MsgLevel.alarm)
                    equipMsg.status = 2;
                else
                    equipMsg.status = 1;
            });
            equipMsg.equipName = GroupName;
            TheLine.UploadStatus(equipMsg);
        }

        public static bool FwdFree(int curaddr) {
            int nextaddr = curaddr + 1;
            if (nextaddr > 20)
                nextaddr = 0;

            if (!DeviceListByAddr.ContainsKey(nextaddr))
                return true;

            return DeviceListByAddr[nextaddr].FrontCheck(nextaddr);
        }
        public void StopMove(bool ServoOff = false)
        {
            //runStatus = RunStatus.Stop;
            //MoveInfo.List.ForEach((m) => { m.EndMove(); });
            if (AxisBean.List.ContainsKey(GroupName))
                AxisBean.StopMultiAxis(AxisBean.List[GroupName]);

            if (ServoOff)
            {
                if (AxisBean.List.ContainsKey(GroupName))
                    AxisBean.CloseMultiAxis(AxisBean.List[GroupName]);
            }
        }
        public void OpenAllServo()
        {
            if (AxisBean.List.ContainsKey(GroupName))
                AxisBean.RunMultiAxis(true, out _, AxisBean.List[GroupName]);
            else
                LogUtil.info($"{GroupName},没有伺服");
        }
        int logType = 1000;
        string WarnMsg = "";
        public bool CheckWait(MoveInfo MoveInfo)
        {
            if (Msg == null) {
                LogUtil.info("msg为空");
            }
            //当等待超过一分钟时,需要打印提示 
            TimeSpan span = DateTime.Now - MoveInfo.LastSetpTime;
            string NotOkMsg = "";
            if (MoveInfo.WaitList.Count <= 0)
            {
                MoveInfo.EndStepWait();
                return false;
            }
            bool isOk = true;
            if (MoveInfo.OneWaitCanEndStep)
            {
                isOk = false;
            }
            MoveInfo.WaitList.ToList().ForEach((w) => {
                if (w.WaitType.Equals(WaitEnum.W014_Msg)) {
                    w.IsEnd = true;
                    Msg.add(w.ActionMsg, w.Data);
                }
            });
            foreach (WaitResultInfo wait in MoveInfo.WaitList)
            {
                if (wait.IsEnd)
                {
                    if (!wait.WaitType.Equals(WaitEnum.W002_IOValue))
                    {
                        continue;
                    }

                }
                NotOkMsg = wait.ToStr();
                if (wait.WaitType.Equals(WaitEnum.W001_AxisMove))
                {
                    string msg = "";
                    if (wait.IsHomeMove)
                    {
                        wait.IsEnd = AxisBean.HomeMoveIsEnd(MoveInfo, wait.AxisInfo, out msg);
                    }
                    else
                    {
                        wait.IsEnd = AxisBean.ACAxisMoveIsEnd(MoveInfo, wait.AxisInfo, wait.TargetPosition, wait.TargetSpeed, out msg);
                    }
                    if (!msg.Equals(""))
                    {
                        isOk = false;
                        WarnMsg = msg;
                        Alarm(AlarmType.AxisMoveError, WarnMsg);
                        Msg.add(WarnMsg, MsgLevel.alarm);
                        break;
                    }
                }
                else if (wait.WaitType.Equals(WaitEnum.W002_IOValue))
                {
                    ConfigIO io = RobotManage.Config.GetWaitIO(wait.IoType, GroupName);
                    if (io == null)
                        throw new Exception($"找不到io:{wait.IoType},{GroupName}");
                    NotOkMsg = MoveInfo.Name + crc.GetString("Res0157", "等待") + "【" + io.DisplayStr + "】=【" + wait.IoValue + "】";
                    wait.IsEnd = IOManager.IOValue(wait.IoType, GroupName).Equals(wait.IoValue);
                    if (!wait.IsEnd)
                    {
                        int timeOutMs = RobotManage.Config.IOSingle_TimerOut * 1000;
                        if (span.TotalMilliseconds > timeOutMs && NoAlarm())
                        {

                            WarnMsg = MoveInfo.Name + "[" + MoveInfo.MoveStep + "] " + crc.GetString("Res0157", "等待") + "(" + io.DisplayStr + "=" + wait.IoValue + $")" + crc.GetString("Res0158", "超时");
                            if (wait.NeedAlarm)
                            {
                                Msg.add(WarnMsg, wait.NeedAlarm ? MsgLevel.alarm : MsgLevel.warning);
                                RobotManage.UserPause(WarnMsg);
                                return true;
                            }

                            if (NoAlarm())
                            {
                                //Alarm(AlarmType.IoSingleTimeOut, WarnMsg);
                                //MoveInfo.error(WarnMsg);
                                //MoveInfo.errlog(WarnMsg);
                                if (!MoveInfo.OneWaitCanEndStep)
                                {
                                    isOk = false;
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (wait.WaitType.Equals(WaitEnum.W003_Time))
                {
                    wait.IsEnd = (span.TotalMilliseconds >= wait.TimeMSeconds);
                }
                else if (wait.WaitType.Equals(WaitEnum.W013_Action))
                {
                    wait.IsEnd = wait.Action.Invoke(wait);
                    MoveInfo.log($"{Name} 自定义等待 IsEnd={wait.IsEnd},Type={wait.Action.GetType()}");
                }


                if (wait.IsEnd)
                {
                    if (MoveInfo.OneWaitCanEndStep)
                    {
                        isOk = true;
                        break;
                    }
                }
                else
                {
                    if (!MoveInfo.OneWaitCanEndStep)
                    {
                        isOk = false;
                        break;
                    }
                }
            }
            if (isOk)
            {
                MoveInfo.EndStepWait();
                return false;
            }
            else if (span.TotalSeconds > MoveInfo.TimeOutSeconds)
            {
                WarnMsg = MoveInfo.Name + "[" + MoveInfo.MoveStep + "]" + crc.GetString("Res0157", "等待") + NotOkMsg + crc.GetString("Res0158", "超时");

                int second = (int)(MoveInfo.TimeOutSeconds / span.TotalSeconds) * 10;
                if (second > 120)
                {
                    second = 120;
                }
                else if (second < 10)
                {
                    second = 10;
                }
                MoveInfo.error(WarnMsg);
                //MoveInfo.errlog(WarnMsg);
                //Alarm(AlarmType.IoSingleTimeOut,  WarnMsg);
                Msg.add(WarnMsg, MsgLevel.alarm);
            }
            return true;
        }
        /// <summary>
        /// 是否再报警中
        /// </summary>
        protected AlarmType alarmType = AlarmType.None;
        DateTime LastAlarmTime = DateTime.Now;
        public void Alarm(AlarmType _alarmType, string alarmMsg = "")
        {
            if (_alarmType.Equals(AlarmType.None).Equals(false))
            {
                LastAlarmTime = DateTime.Now;
            }
            //SaveAlarmInfo(alarmType, alarmDetial, alarmMsg, storeMoveType);

            if (this.alarmType.Equals(_alarmType))
            {
                return;
            }
            LogUtil.error(Name + " 报警,报警类型:" + _alarmType);


            this.alarmType = _alarmType;
            if (_alarmType.Equals(AlarmType.AxisAlarm) || _alarmType.Equals(AlarmType.AxisMoveError))
            {
                LogUtil.error(Name + "轴报警, 停止运动, 打开报警灯");

                StopMove(true);
            }
            else if (_alarmType == AlarmType.SuddenStop)
            {
                //isInSuddenDown = true;
                LogUtil.error(Name + "收到急停信号,停止运动, 打开报警灯 ");
                StopMove(true);
                //storeStatus = StoreStatus.SuddenStop;
            }
        }
        internal bool NoAlarm()
        {
            if (alarmType.Equals(AlarmType.None))
            {
                return true;
            }
            return false;
        }
        public void CylinderMove(MoveInfo moveInfo, string IoLowType, string IoHighType, IO_VALUE iO_VALUE = IO_VALUE.HIGH)
        {
            if (iO_VALUE == IO_VALUE.LOW)
            {
                //if (IOManager.DOValue(IoLowType).Equals(IO_VALUE.HIGH))
                //    return;
                (IoLowType, IoHighType) = (IoHighType, IoLowType);
            }
            //if (IOManager.DOValue(IoHighType).Equals(IO_VALUE.HIGH))
            //    return;
            IOMove(IoLowType, IO_VALUE.LOW);
            IOMove(IoHighType, IO_VALUE.HIGH);
            if (moveInfo != null)
            {
                moveInfo.WaitList.Add(WaitResultInfo.WaitIO(IoLowType, IO_VALUE.LOW, true));
                moveInfo.WaitList.Add(WaitResultInfo.WaitIO(IoHighType, IO_VALUE.HIGH, true));
            }
        }
        public IO_VALUE IOValue(string ioType) => IOManager.IOValue(ioType, GroupName);
        public void IOMove(string IoType, IO_VALUE value, int msTime = 0)
        {

            if (msTime <= 0)
            {
                IOManager.IOMove(IoType, value, GroupName);
                //if (IoType == "Ls_A_BufStop_Fwd" || IoType == "Ls_B_BufStop_Fwd")
                //{
                //    LogUtil.info($"{IoType}=={value},device={GroupName},msTime={msTime}");
                //    StackTrace stackTrace = new StackTrace();
                //    for (int i = 0; i < stackTrace.FrameCount; i++)
                //    {
                //        StackFrame stackFrame = stackTrace.GetFrame(i);
                //        string fileName = stackFrame.GetFileName();
                //        int lineNumber = stackFrame.GetFileLineNumber();

                //        LogUtil.info($"-Function {stackFrame.GetMethod().Name} called from {fileName}, line {lineNumber}");
                //    }
                //}
            }
            else
            {
                Task.Run(() =>
                {
                    //if (IoType == "Ls_A_BufStop_Fwd" || IoType == "Ls_B_BufStop_Fwd")
                    //{
                    //    LogUtil.info($"Task {IoType}=={value},device={GroupName},msTime={msTime}");
                    //    StackTrace stackTrace = new StackTrace();
                    //    for (int i = 0; i < stackTrace.FrameCount; i++)
                    //    {
                    //        StackFrame stackFrame = stackTrace.GetFrame(i);
                    //        string fileName = stackFrame.GetFileName();
                    //        int lineNumber = stackFrame.GetFileLineNumber();

                    //        LogUtil.info($"Task -Function {stackFrame.GetMethod().Name} called from {fileName}, line {lineNumber}");
                    //    }
                    //}
                    IOManager.IOMove(IoType, value, GroupName);
                    Thread.Sleep(msTime);
                    IO_VALUE tValue = value.Equals(IO_VALUE.HIGH) ? IO_VALUE.LOW : IO_VALUE.HIGH;

                    //LogUtil.info("[" + GroupName + "]定时回写IO:  [" + IoType + "]=[" + value + "],msTime=" + msTime);

                    IOManager.IOMove(IoType, tValue, GroupName);
                });
            }
        }

        public void IOMove(string IoType, IO_VALUE value, string whenIoType, IO_VALUE whenvalue, int msTime = 0)
        {
            IOMove(IoType, value, msTime);
            return;
            Task.Run(() =>
            {
                IOManager.IOMove(IoType, value, GroupName);
                //Thread.Sleep(msTime);
                IO_VALUE tValue = value.Equals(IO_VALUE.HIGH) ? IO_VALUE.LOW : IO_VALUE.HIGH;
                for (int i = 0; i < 30; i++)
                {
                    Task.Delay(100).Wait();
                    if (IOManager.IOValue(whenIoType, GroupName).Equals(whenvalue))
                    {
                        break;
                    }
                }
                //Task.Delay(msTime).Wait();
                IOManager.IOMove(IoType, tValue, GroupName);
            });
        }

    }
}