using Aitex.Core.RT.Device;
using Aitex.Core.RT.Routine;
using Aitex.Core.RT.SCCore;
using MECF.Framework.Common.Beckhoff.ModuleIO;
using MECF.Framework.Common.CommonData.PUF;
using MECF.Framework.Common.Equipment;
using MECF.Framework.Common.Routine;
using MECF.Framework.Common.TwinCat;
using CyberX8_Core;
using CyberX8_RT.Devices.Loader;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MECF.Framework.Common.IOCore;
namespace CyberX8_RT.Devices.AXIS.CANOpen
{
   
    public class LoaderSideBernoulliN2PressureRoutine : RoutineBase, IRoutine
    {
        private enum BernoulliN2Step
        {
            WriteBernoulliN2,
            End
        }
        #region 常量 
        private const string BERNOULLI_N2 = "BernoulliN2";
        #endregion
        #region 内部变量
        private int _timeout = 5000;
        private LoaderSideDevice _loaderSide;
        private bool _bernoulliN2 = false;
        private double _minBernoulliN2Pressure = 0;
        #endregion
        /// 
        /// 构造函数
        /// 
        /// 
        public LoaderSideBernoulliN2PressureRoutine(string module) : base(module)
        {
        }
        /// 
        /// 中止
        /// 
        public void Abort()
        {
            Runner.Stop("Manual Abort");
        }
        /// 
        /// 监控
        /// 
        /// 
        public RState Monitor()
        {
            Runner.Run(BernoulliN2Step.WriteBernoulliN2, WriteBernoulliN2, CheckBernoulliN2,_timeout)
                .End(BernoulliN2Step.End,NullFun,100);
            return Runner.Status;
        }
        /// 
        /// 写入Bernoulli N2数值
        /// 
        /// 
        private bool WriteBernoulliN2()
        {
            string ioName = BeckhoffModuleIOManager.Instance.GetIoNameByInnerModuleName($"{Module}.{BERNOULLI_N2}");
            return IOModuleManager.Instance.WriteIoValue(ioName, _bernoulliN2);
        }
        /// 
        /// 检验Bernoulli N2状态
        /// 
        /// 
        private bool CheckBernoulliN2()
        {
            if (_bernoulliN2)
            {
                return _loaderSide.SideData.BernoulliN2 == _bernoulliN2&& _loaderSide.SideData.BernoulliPressure > _minBernoulliN2Pressure;
            }
            else
            {
                return _loaderSide.SideData.BernoulliN2 == _bernoulliN2;
            }
        }
        /// 
        /// 启动
        /// 
        /// 
        /// 
        public RState Start(params object[] objs)
        {
            _loaderSide = DEVICE.GetDevice(Module);
            if (SC.ContainsItem($"{ModuleName.Loader1}.MinBernoulliN2Pressure"))
            {
                _minBernoulliN2Pressure = SC.GetValue($"{ModuleName.Loader1}.MinBernoulliN2Pressure");
            }
            _bernoulliN2 = (bool)objs[0];
            return Runner.Start(Module, "Bernoulli N2");
        }
    }
}