MachineBase.cs 16.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace DeviceLibrary
{
    using crc = OnlineStore.CodeResourceControl;
    public class MachineBase
    {
        public virtual DeviceConfig Config { get; set; }
        public virtual string DeviceName { get; }
        public virtual string DeviceNameShow { get=>crc.GetString(DeviceName, DeviceName);  }
        public virtual bool UserPause { get; set; }
        public RunStatus runStatus { get; set; } = RunStatus.Stop;
        protected MoveInfo ResetMoveInfo;
        public MoveInfo MoveInfo;        
        protected List<Msg> Msg = new List<Msg>();
        //public delegate void Event(List<Msg> msg);
        public event EventHandler<List<Msg>> ProcessMsgEvent;
        
        //public delegate void ProcessMoveinfo(List<MoveInfo> moveinfoList);
        public event EventHandler<List<MoveInfo>> ProcessMoveinfoEvent;

        ReelParam _preReelParam = null;
        public ReelParam preReelParam
        {
            get => _preReelParam;
            set
            {
                if (value == null)
                    _preReelParam = null;
                else
                    _preReelParam = value.clone();
            }
        }
        ReelParam _secPreReelParam = null;
        public ReelParam secPreReelParam
        {
            get => _secPreReelParam;
            set
            {
                if (value == null)
                    _secPreReelParam = null;
                else
                    _secPreReelParam = value.clone();
            }
        }
        Thread thread;
        /// <summary>
        /// 整机启动变量,设置为false后将退出线程,只在停止时调用
        /// </summary>
        protected bool mstart = false;
        protected int stepDelaytime =100;
        public virtual void Run()
        {
            if (!mstart)
            {
                thread = new Thread(new ThreadStart(LoopProcess));
                thread.Start();
            }
            LogUtil.info(DeviceName + " 主线程已启动.");
            GC.KeepAlive(thread);
        }
        public virtual void Stop()
        {
            LogUtil.info(DeviceName + " 停止设备.");
            mstart = false;
            StopMove(true);
        }
        protected virtual void LoopProcess() {
            throw new NotImplementedException();
        }
        public bool SafeCheck()
        {
            bool ok = true;
            if (UserPause) {
                Msg.add(crc.GetString("device_user_pause","用户暂停设备"), MsgLevel.warning);
                DeviceSuddenStop();
                ok = false;
            }
            //if (IOManager.GetDIValue("",0,16).Equals(IO_VALUE.LOW))
            //{
            //    ok = false;
            //    DeviceSuddenStop();
            //    Msg.add(crc.GetString("device_safedoor_open", "贴标或出料机构门禁被打开"), MsgLevel.warning);
            //}
            lastSafeCheckStatus = ok;
            return ok;
        }
        bool lastSafeCheckStatus = true;
        void DeviceSuddenStop()
        {
            if (lastSafeCheckStatus)
            {
                //lastSafeCheckStatus = false;
                var al = new Dictionary<string, List<AxisBean>>(AxisBean.List);

                AxisBean.StopMultiAxis(AxisBean.List[RobotManage.xrayMachine.DeviceName]);
                //AxisBean.StopMultiAxis();
                MoveInfo.List.ForEach((m) => { m.CanWhileCount = 5; });

                if (runStatus == RunStatus.HomeReset)
                {
                    ResetMoveInfo.NewMove(MoveStep.H01_HomeReset);
                }
            }
        }
        protected void ProcessMsgEventFire(List<Msg> msg) {
            ProcessMsgEvent?.Invoke(this,msg);
        }
        protected void ProcessMoveinfoEventFire(List<MoveInfo> moveinfoList)
        {
            ProcessMoveinfoEvent?.Invoke(this, moveinfoList);
        }
        /// <summary>
        /// 是否再报警中
        /// </summary>
        public AlarmType alarmType = AlarmType.None;
        protected DateTime LastAlarmTime = DateTime.Now;
        protected DateTime checkAlarmTime = DateTime.Now;
        protected void Alarm(AlarmType alarmType, string alarmMsg = "")
        {
            if (alarmType.Equals(AlarmType.None).Equals(false))
            {
                LastAlarmTime = DateTime.Now;
            }

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

            this.alarmType = alarmType;
            if (alarmType.Equals(AlarmType.AxisAlarm) || alarmType.Equals(AlarmType.AxisMoveError))
            {
                LogUtil.error(DeviceName + "轴报警, 停止运动, 打开报警灯");
                StopMove(true);
            }
            else if (alarmType == AlarmType.SuddenStop)
            {
                LogUtil.error(DeviceName + "收到急停信号,停止运动, 打开报警灯 ");
                StopMove(true);
            }
            else if (alarmType.Equals(AlarmType.NoAirCheck))
            {
                LogUtil.error(DeviceName + " 未检测到气压信号 ,停止运动, 打开报警灯 ");
                StopMove(true);
            }
            //LogUtil.info();
        }
        protected bool NoAlarm()
        {
            if (alarmType.Equals(AlarmType.None))
            {
                return true;
            }
            return false;
        }
        int logType = 1000;
        public string WarnMsg = "";
        /// <summary>
        /// 返回true代表需要等待
        /// </summary>
        /// <param name="MoveInfo"></param>
        /// <returns></returns>
        protected bool CheckWait(MoveInfo MoveInfo) {

            if (MoveInfo.IsInWait)
            {
                if (!CheckWait2(MoveInfo)) {
                    if (alarmType == AlarmType.IoSingleTimeOut) {
                        alarmType = AlarmType.None;
                    }
                }
               
            }
            return MoveInfo.IsInWait;

        }
        /// <summary>
        /// 返回true代表需要等待
        /// </summary>
        /// <param name="MoveInfo"></param>
        /// <returns></returns>
        protected bool CheckWait2(MoveInfo MoveInfo)
        {
            //当等待超过一分钟时,需要打印提示 
            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.ForEach((w) =>
            {
                if (w.WaitType.Equals(WaitEnum.W014_Msg))
                {
                    w.IsEnd = true;
                    Msg.add(w.ActionMsg, (MsgLevel)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 if(wait.IsRelMove)
                    {
                        wait.IsEnd = AxisBean.ACAxisRELMoveIsEnd(MoveInfo, wait.AxisInfo, wait.TargetPosition, wait.TargetSpeed, out msg);
                    }
                    else
                    {
                        wait.IsEnd = AxisBean.ACAxisMoveIsEnd(MoveInfo, wait.AxisInfo, wait.TargetPosition, wait.TargetSpeed, out msg);
                    }
                    if (!msg.Equals(""))
                    {
                        isOk = false;
                        WarnMsg = msg;
                        if (!UserPause)
                            Alarm(AlarmType.AxisMoveError, WarnMsg);
                        Msg.add(WarnMsg, MsgLevel.warning);
                        break;
                    }
                }
                else if (wait.WaitType.Equals(WaitEnum.W002_IOValue))
                {
                    ConfigIO io = Config.getWaitIO(wait.IoType);
                    NotOkMsg = $" {crc.GetString("wait","等待")}【" + io.DisplayStr + "】=【" + wait.IoValue + "】";
                    wait.IsEnd = IOManager.IOValue(wait.IoType,Config).Equals(wait.IoValue);
                    if (!wait.IsEnd)
                    {
                        int timeOutMs = 15*1000;// Config.IOSingle_TimerOut;
                        if (span.TotalMilliseconds > timeOutMs)// && NoAlarm())
                        {

                            WarnMsg = DeviceNameShow + "[" + MoveInfo.MoveStep + $"] {crc.GetString("wait", "等待")}(" + io.DisplayStr + "=" + wait.IoValue + $"){crc.GetString("timeout","超时")}";
                            Alarm(AlarmType.IoSingleTimeOut, WarnMsg);
                            Msg.add(WarnMsg, MsgLevel.warning);
                            LogUtil.error(WarnMsg, logType + 14);
                            //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);
                    LogUtil.info($"{DeviceName} 自定义等待 IsEnd={wait.IsEnd},Type={wait.Action.GetType()}");
                }
                else if (wait.WaitType.Equals(WaitEnum.W008_BatchAxis))
                {
                    AxisBean axisBean=null;
                    //if (wait.AxisInfo.ProName == "Right_Batch_Axis")
                    //    axisBean = Right_Batch_Axis;
                    //else
                    //    axisBean = Left_Batch_Axis;

                    //等待信号亮或者走到绝对位置才停止
                    if (IOValue(axisBean.TargetIoType).Equals(axisBean.TargetIoValue))
                    {
                        LogUtil.debug(DeviceName + "CheckWaitResult 检测到" + axisBean.TargetIoType + "=" + axisBean.TargetIoValue + ",停止运行");
                        axisBean.StopAxisCheckMove();
                        //if (AxisManager.GetBusyStatus(wait.AxisInfo.DeviceName, wait.AxisInfo.GetAxisValue()).Equals(1))
                        //{
                            axisBean.SuddenStop();
                        //}
                        wait.IsEnd = true;
                    }
                    else
                    {
                        bool isbusy = AxisManager.GetBusyStatus(wait.AxisInfo.DeviceName, wait.AxisInfo.GetAxisValue()).Equals(1);
                        if (!isbusy)
                        {
                            int outCount = AxisManager.GetActualtPosition(wait.AxisInfo.DeviceName, wait.AxisInfo.GetAxisValue());
                            int errorCount = Math.Abs(outCount - wait.TargetPosition);
                            if (errorCount <= wait.AxisInfo.CanErrorCountMax)
                            {
                                axisBean.StopAxisCheckMove();
                                wait.IsEnd = true;
                            }
                            else
                            {
                                axisBean.AbsMove(null, wait.TargetPosition, wait.TargetSpeed);
                                wait.IsEnd = false;
                            }
                        }
                    }
                }
                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 = DeviceNameShow + "[" + MoveInfo.MoveStep + $"]{crc.GetString("wait","等待")}" + NotOkMsg + $"{crc.GetString("timeout","超时")}[" + Math.Round(span.TotalSeconds, 1) + "s]";

                int second = (int)(MoveInfo.TimeOutSeconds / span.TotalSeconds) * 10;
                if (second > 120)
                {
                    second = 120;
                }
                else if (second < 10)
                {
                    second = 10;
                }
                LogUtil.error(WarnMsg, logType + 100, second);
                //MoveInfo.errlog(WarnMsg);
                if (!UserPause)
                    Alarm(AlarmType.IoSingleTimeOut, WarnMsg);
                Msg.add(WarnMsg, MsgLevel.warning);
            }
            return true;
        }
        protected void OpenAllServo()
        {
            AxisBean.RunMultiAxis(true, out _, AxisBean.GetList(DeviceName));

        }
        protected virtual void StopMove(bool ServoOff = false)
        {
            runStatus = RunStatus.Stop;
            MoveInfo.EndMove();
            AxisBean.StopMultiAxis(AxisBean.GetList(DeviceName));

            if (ServoOff)
                AxisBean.CloseMultiAxis(AxisBean.GetList(DeviceName));
        }
        public void CylinderMove(MoveInfo moveInfo, string IoLowType, string IoHighType, IO_VALUE iO_VALUE=IO_VALUE.HIGH)
        {
            if (iO_VALUE == IO_VALUE.LOW)
            {
                var t = IoHighType;
                IoHighType = IoLowType;
                IoLowType = t;
            }

            IOMove(IoLowType, IO_VALUE.LOW);
            IOMove(IoHighType, IO_VALUE.HIGH);
            if (moveInfo != null)
            {
                moveInfo.WaitList.Add(WaitResultInfo.WaitIO(IoLowType, IO_VALUE.LOW));
                moveInfo.WaitList.Add(WaitResultInfo.WaitIO(IoHighType, IO_VALUE.HIGH));
            }
        }
        public IO_VALUE IOValue(string ioType)
        {
            return IOManager.IOValue(ioType, Config);
        }
        public bool IOValue(string ioType, IO_VALUE Test_VALUE, int DebounceCount=3)
        {
            return IODebounce<bool>.Test(ioType, IOManager.IOValue(ioType, Config), Test_VALUE, DebounceCount);
            //return IOManager.IOValue(ioType, Config);
        }
        public void IOMove(string IoType, IO_VALUE value, bool isCheck = false, int msTime = 0)
        {
            if (msTime <= 0)
            {
                if (isCheck && (IOValue(IoType).Equals(value)))
                {
                    return;
                }
                IOManager.IOMove(IoType, value, Config);
            }
            else
            {
                Task.Run(() =>
                {
                    IOManager.IOMove(IoType, value, Config);
                    Thread.Sleep(msTime);
                    IO_VALUE tValue = value.Equals(IO_VALUE.HIGH) ? IO_VALUE.LOW : IO_VALUE.HIGH;

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

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

        protected bool WaitIo(string ioType, IO_VALUE value, int timeOut)
        {
            Task w = Task.Delay(timeOut);

            Task p = Task.Run(() =>
            {
                while (!IOValue(ioType).Equals(value))
                {
                    Task.Delay(100).Wait();
                }
            });
            Task.WaitAny(w, p);
            return true;
        }
    }
}