| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633 | using Aitex.Core.RT.DataCenter;using Aitex.Core.RT.Device;using Aitex.Core.RT.Log;using Aitex.Core.RT.OperationCenter;using Aitex.Core.RT.RecipeCenter;using Aitex.Core.RT.SCCore;using Aitex.Core.Util;using MECF.Framework.Common.Beckhoff.ModuleIO;using MECF.Framework.Common.CommonData.Reservoir;using MECF.Framework.Common.Persistent.Reservoirs;using MECF.Framework.Common.RecipeCenter;using MECF.Framework.Common.ToolLayout;using MECF.Framework.Common.TwinCat;using CyberX8_Core;using CyberX8_RT.Devices.Facilities;using CyberX8_RT.Devices.Metal;using CyberX8_RT.Modules.Reservoir;using System;using System.Collections.Generic;using System.Reflection;using CyberX8_RT.Modules;using System.Collections.ObjectModel;using CyberX8_RT.Devices.Dose;using CyberX8_RT.Modules.Metal;using CyberX8_RT.Devices.Temperature;using CyberX8_RT.Devices.PowerSupplier;using System.Linq;using CyberX8_RT.Devices.Safety;using MECF.Framework.Common.IOCore;namespace CyberX8_RT.Devices.Reservoir{    public class StandardHotReservoirDevice : BaseDevice, IDevice    {        private enum ReservoirOperation        {            None,            ManualDiReplen,            AutoDiReplen        }        private enum DosingOperation        {            None,            ManualDosing,            AutoDosing,        }                #region 常量        private const string AUTO = "Auto";        private const string MANUAL = "Manual";        private const string DISABLE = "Disable";        private const string STRATUS = "Stratus";        private const string PERSISTENT_VALUE = "PersistentValue";        private const string FLOW = "Flow";        private const string HED_FLOW = "HedFlow";        private const string PH_FLOW_VALVE = "PHFlowValve";        private const string PH_VALUE = "PHValue";        private const string WATER_LEVEL = "WaterLevel";        private const string LOW_LEVEL = "LowLevel";        private const string HIGH_LEVEL = "HighLevel";        private const string DI_REPLEN = "DiReplen";        private const string RESERVOIRDEVICEDATA = "ReservoirDeviceData";        private const string REPLEN_LEVEL = "ReplenLevel";        private const double PUMP_SPEED_CONVERT = 0.0672;        private const int ENABLE = 5;        #endregion        #region 内部变量        /// <summary>        /// Level取样平均值        /// </summary>        private double _avgLevel;        /// <summary>        /// AN Level取样队列        /// </summary>        private Queue<double> _LevelSamples;        /// <summary>        /// Level计算平均值取样数        /// </summary>        private int levelSampleCount;        /// <summary>        /// Prewet 持久性数值对象        /// </summary>        private ReservoirsPersistentValue _persistentValue;        /// <summary>        /// 定时器Job        /// </summary>        PeriodicJob _periodicJob = null;        /// <summary>        /// 变量是否初始化字典        /// </summary>        private Dictionary<string, bool> _variableInitializeDic = new Dictionary<string, bool>();        /// <summary>        /// Reservoir数据        /// </summary>        private StandardHotReservoirData _reservoirData = new StandardHotReservoirData();        /// <summary>        /// 当前操作        /// </summary>        private ReservoirOperation _currentOperation = ReservoirOperation.None;        /// <summary>        /// 手动注水时间(秒)        /// </summary>        private int _manualReplenSecond = 0;        /// <summary>        /// Recipe        /// </summary>        private ResRecipe _resRecipe;        /// <summary>        /// 平均PH值        /// </summary>        private double _avaragePH;        /// <summary>        /// PH Routine        /// </summary>        private StandardHotPHRoutine _phRoutine;        /// <summary>        /// PH Routine状态        /// </summary>        private RState _phState=RState.Init;        /// <summary>        /// PH结束时间        /// </summary>        private DateTime _phRoutineEndTime=DateTime.Now;        /// <summary>        /// Direplen 逻辑对象        /// </summary>        private ReservoirDiReplenHelper _direplenHelper;        /// <summary>        /// Replen数量        /// </summary>        private int _replenNum = 0;        /// <summary>        /// Dose Replen数据        /// </summary>        private ReplenData[] _replenDatas;        /// <summary>        /// ReplenType        /// </summary>        private string _replenType;        /// <summary>        /// Replen Recipe集合        /// </summary>        private RdsRecipe[] _rdsRecipe;        /// <summary>        /// DosingSystemHelper对象列表        /// </summary>        private List<DosingSystemHelper> _dosingSystemHelperLst;        /// <summary>        /// ReplenLevel 列表        /// </summary>        private List<bool> _replenLevelLst;        /// <summary>        /// 当前操作        /// </summary>        private List<DosingOperation> _currentDosingOperation;        /// <summary>        /// 配置的metal device集合        /// </summary>        private ObservableCollection<StandardHotMetalDevice> _metalDevices = new ObservableCollection<StandardHotMetalDevice>();        /// <summary>        /// Replen Persistent Value        /// </summary>        private Dictionary<string, ReplenPersistentValue> _replenPersistentValue = new Dictionary<string, ReplenPersistentValue>();        /// <summary>        /// DosingCommonHelper        /// </summary>        private DosingCommonHelper _dosingCommonHelper;        /// <summary>        /// WarningFlag        /// </summary>        private List<bool> _isCAFlowRateWARN;        /// <summary>        /// CMM Flow High Error        /// </summary>        private double _reservoirCMMFlowHighError;        /// <summary>        /// CMM Flow Low Error        /// </summary>        private double _reservoirCMMFlowLowError;        private bool _isTCControlWARN = false;        private bool _isCMMPowerCurrentWARN = false;        private bool _isCMMPowerFlowWARN = false;        private bool _isExportCMMUsage = false;        private bool _isAutoDIReplenError = false;        #endregion        #region 属性        /// <summary>        /// 数据        /// </summary>        public StandardHotReservoirData ReservoirData { get { return _reservoirData; } }        /// <summary>        /// Replen数据        /// </summary>        public ReplenData[] ReplenDatas { get { return _replenDatas; } }        /// <summary>        /// DosingSystemHelper对象列表        /// </summary>        public List<DosingSystemHelper> DosingSystemHelpers { get { return _dosingSystemHelperLst; }}        /// <summary>        /// Replen数量        /// </summary>        public int ReplenNum { get { return _replenNum; } }        /// <summary>        /// 操作模式        /// </summary>        public string OperationMode { get { return _persistentValue.OperatingMode; } }        /// <summary>        /// 工程模式        /// </summary>        public string EngineerMode { get { return _persistentValue.RecipeOperatingMode; } }        /// <summary>        /// 是否自动        /// </summary>        public bool IsAuto { get { return _persistentValue.OperatingMode == AUTO; } }        /// <summary>        /// 是否需要补水        /// </summary>        public bool NeedAutoDireplen { get { return GetNeedAutoDireplen(); } }        /// <summary>        /// 正在补水        /// </summary>        public bool IsDireplenOn { get { return _reservoirData.DiReplen; } }        /// <summary>        /// 平均PH数值        /// </summary>        public double AveragePH { get { return _avaragePH; } set { _avaragePH = value; } }        /// <summary>        /// 当前Recipe        /// </summary>        public ResRecipe Recipe { get { return _resRecipe; } }        /// <summary>        /// 当前Rds Recipe        /// </summary>        public RdsRecipe[] RdsRecipe { get { return _rdsRecipe; } }        #endregion        /// <summary>        /// 构造函数        /// </summary>        /// <param name="moduleName"></param>        /// <param name="name"></param>        public StandardHotReservoirDevice(string moduleName) : base(moduleName, moduleName, moduleName, moduleName)        {            levelSampleCount = SC.GetValue<int>("Reservoir.LevelAvgSamples");            levelSampleCount = levelSampleCount == 0 ? 20 : levelSampleCount;            _LevelSamples = new Queue<double>(levelSampleCount);            _periodicJob = new PeriodicJob(100, OnTimer, $"{Module}.OnTimer", true);            _reservoirCMMFlowHighError = SC.GetValue<double>("Reservoir.CMM.CMMFlowHighFault");            _reservoirCMMFlowLowError = SC.GetValue<double>("Reservoir.CMM.CMMFlowLowFault");        }        /// <summary>        /// 定时器        /// </summary>        /// <returns></returns>        private bool OnTimer()        {            //计算AN/CA level的平均值            if (ReservoirData != null)            {                //AN                if (_LevelSamples.Count >= levelSampleCount)                {                    _LevelSamples.Dequeue();                    _LevelSamples.Enqueue(ReservoirData.Level);                }                else                {                    _LevelSamples.Enqueue(ReservoirData.Level);                }                _avgLevel = _LevelSamples.Count > 0 ? _LevelSamples.Average() : 0;            }            foreach (StandardHotMetalDevice device in _metalDevices)            {                device.OnTimer(_periodicJob.Interval);            }                       ReservoirEntity reservoirEntity = Singleton<RouteManager>.Instance.GetModule<ReservoirEntity>(Module);            //报错停DosingSystem            if (_replenType != "" && _replenNum != 0 && reservoirEntity != null && reservoirEntity.IsError)            {                for (int i = 0; i < _replenNum; i++)                {                    string replenName = "Replen" + (i + 1).ToString();                    if (_replenPersistentValue[replenName].IsDosingRunning)                    {                        _dosingSystemHelperLst[i].StopDosing();                        _currentDosingOperation[i] = DosingOperation.None;                    }                }            }                        //触发水位过高或者过低将reservoir切成error            if (!_reservoirData.LowLevel || ReservoirData.WaterLevel > SC.GetValue<double>($"Reservoir.{Module}.HighLevel"))            {                if (!_reservoirData.LowLevel && !reservoirEntity.IsError)                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"WaterLevel low is Activate");                }                if(ReservoirData.WaterLevel > SC.GetValue<double>($"Reservoir.{Module}.HighLevel") && !reservoirEntity.IsError)                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"WaterLevel:{ReservoirData.WaterLevel} is larger than  HighLevel Config:{SC.GetValue<double>($"Reservoir.{Module}.HighLevel")}");                    SystemFacilities systemFacilities = DEVICE.GetDevice<SystemFacilities>("System.Facilities");                    if (systemFacilities != null)                    {                        systemFacilities.DiFillDisableOperation("DIFillDisableOpeartion", null);                        systemFacilities.DiReplenDisableOperation("DiReplenDisableOperation", null);                        if (ReservoirData.DiReplen)                        {                            _currentOperation = ReservoirOperation.None;                            DIReplenOff("", null);                        }                    }                }                reservoirEntity.PostMsg(ReservoirMsg.Error);            }            if (!_reservoirData.LowLevel)   //true是正常的            {                ReservoirItem reservoirItem = ReservoirItemManager.Instance.GetReservoirItem(Module);                foreach (var metalDevice in _metalDevices)                {                    if (metalDevice.MetalDeviceData.Circulation)                    {                        LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Lowlevel was activate");                        metalDevice.SwitchToBypass($"{metalDevice.Name}.SwitchToBypass", null);                    }                    if (metalDevice.MetalDeviceData.CellFlow > 0)                    {                        LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Lowlevel was activate");                        metalDevice.PumpOff();                    }                    //水位过低时将起对应的metal也要切成error                    MetalEntity metalEntity = Singleton<RouteManager>.Instance.GetModule<MetalEntity>(metalDevice.DeviceID);                    if (metalEntity != null && !metalEntity.IsError)                    {                        metalEntity.PostMsg(MetalMsg.Error);                    }                }                //禁用TC                if (!String.IsNullOrEmpty(reservoirItem.TCID))                {                    TemperatureController temperatureController = DEVICE.GetDevice<TemperatureController>(reservoirItem.TCID);                    if (temperatureController != null && temperatureController.TemperatureData.ControlOperationModel == 5)                    {                        LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Lowlevel was activate");                        temperatureController.DisableOperation("", null);                    }                }            }            //水位触发reservoir里面的high/low将对应的reservoir切成error            if (_resRecipe != null && (ReservoirData.Level < _resRecipe.CALevelErrorLow || ReservoirData.Level > _resRecipe.CALevelErrorHigh))            {                if (ReservoirData.Level < _resRecipe.CALevelErrorLow && !reservoirEntity.IsError)                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Current level:{ReservoirData.Level} is lower than recipe's CA Errorlow paramater:{_resRecipe.CALevelErrorLow}");                }                if (ReservoirData.Level > _resRecipe.CALevelErrorHigh && !reservoirEntity.IsError)                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Current level:{ReservoirData.Level} is larger than recipe's CA Errorlow paramater:{_resRecipe.CALevelErrorHigh}");                }                reservoirEntity.PostMsg(ReservoirMsg.Error);            }            //触发Safetyhigh将reservoir切成error            SafetyDevice safetyDevice = DEVICE.GetDevice<SafetyDevice>("Safety");            if (safetyDevice != null && safetyDevice.SafetyData.ReservoirHighLevel && !reservoirEntity.IsError)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Safety high is Activate");                reservoirEntity.PostMsg(ReservoirMsg.Error);            }            //DIReplen            _direplenHelper.MonitorPeriodTime();            if (_currentOperation == ReservoirOperation.ManualDiReplen && _reservoirData.DiReplen)            {                bool result = _direplenHelper.MonitorManualDiReplenComplete(_manualReplenSecond, DIReplenOff);                if (result)                {                    _currentOperation = ReservoirOperation.None;                }            }            else if (_currentOperation == ReservoirOperation.AutoDiReplen && _reservoirData.DiReplen)            {                bool result = _direplenHelper.AutoDiReplenMonitorTimeOut(DIReplenOff);                if (result)                {                    _currentOperation = ReservoirOperation.None;                }                else                {                    //按液位补水                    result = _direplenHelper.AutoDiReplenMonitorComplete(_reservoirData.Level, _resRecipe.ReservoirCALevel, _resRecipe, DIReplenOff);                    if (result)                    {                        _currentOperation = ReservoirOperation.None;                    }                }            }                     if (reservoirEntity == null || !reservoirEntity.IsInitialized)            {                return true;            }            if (_persistentValue.OperatingMode == AUTO)            {                CAFlowRateCheck();                TemperatureCheck();                CMMPowerCheck();                //CMM用电量记录                                         if (_isExportCMMUsage && _persistentValue.CMMStartTime != DateTime.MinValue)                {                    ReservoirItem reservoirItem = ReservoirItemManager.Instance.GetReservoirItem(Module);                    if (!string.IsNullOrEmpty(reservoirItem.CMMSupplyID) && _resRecipe != null && _resRecipe.CMMEnable)                    {                        CellPowerSupplier powerSupplier = DEVICE.GetDevice<CellPowerSupplier>(reservoirItem.CMMSupplyID);                        double cmmUsage = powerSupplier.PowerSupplierData.Current * DateTime.Now.Subtract(_persistentValue.CMMStartTime).TotalHours;                        ReservoirUsageManager.Instance.UpdateReservoirCMMUsage(Module, Math.Round(cmmUsage, 3));                        _persistentValue.CMMStartTime = DateTime.Now;                        ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);                        _isExportCMMUsage = false;                    }                }            }            if (_phState == RState.Running)            {                _phState = _phRoutine.Monitor();                if (_phState == RState.End)                {                    _phRoutineEndTime = DateTime.Now;                }            }            else if (_phState != RState.Init)            {                double phUpdatePeriod = SC.GetValue<double>("Reservoir.PHUpdatePeriod");                if (DateTime.Now.Subtract(_phRoutineEndTime).TotalMilliseconds >= phUpdatePeriod * 1000)                {                    StartDetectPHValve();                }            }            if (_replenType != "" && _replenNum != 0)            {                //DosingSystem 状态监控                _dosingCommonHelper.DoseStatusMonitor();                //Dosing监控                if (_dosingCommonHelper.IsDosingSystemInitialized)                {                                      if (_replenPersistentValue["Replen1"].OperatingMode == "Manual")                    {                        //ManualDosing                              _dosingCommonHelper.ManualDoseSystemMonitor();                    }                                       if (_replenPersistentValue["Replen1"].OperatingMode == "Auto")                    {                        //AutoDosing                              _dosingCommonHelper.AutoDoseSystemMonitor();                    }                    else                    {                        _dosingCommonHelper.CheckDoseOperation();                    }                                 }            }                              return true;        }        /// <summary>        /// 获取是否需要补水        /// </summary>        /// <returns></returns>        private bool GetNeedAutoDireplen()        {            if (IsAuto&&_resRecipe!=null)            {                if (_resRecipe.DIReplenEnable && _resRecipe.DIReplenCurrentRate == 0 && _resRecipe.DIReplenTimeRate == 0)                {                    double levelHysteresis = SC.GetValue<double>("Reservoir.LevelHysteresis");                    return ReservoirData.Level < _resRecipe.ReservoirCALevel - levelHysteresis;                }                return false;            }            else            {                return false;            }        }        /// <summary>        /// 初始化        /// </summary>        /// <returns></returns>        public bool Initialize()        {            InitializeRoutine();            InitializeParameter();            SubscribeData();            InitializeOperation();            SubscribeValueAction();            return true;        }        /// <summary>        /// 初始化routine        /// </summary>        private void InitializeRoutine()        {            _phRoutine = new StandardHotPHRoutine(Module);        }        /// <summary>        /// 初始化参数        /// </summary>        private void InitializeParameter()        {              _persistentValue = ReservoirsPersistentManager.Instance.GetReservoirsPersistentValue(Module.ToString());            if (_persistentValue == null)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module.ToString(), "Persistent Value Object is not exist");            }            else            {                if (!string.IsNullOrEmpty(_persistentValue.Recipe))                {                    _resRecipe = RecipeFileManager.Instance.LoadGenericityRecipe<ResRecipe>(_persistentValue.Recipe);                }                _direplenHelper = new ReservoirDiReplenHelper(Module, _persistentValue);            }            ReservoirItem reservoirItem = ReservoirItemManager.Instance.GetReservoirItem(Module.ToString());            if (reservoirItem != null)            {                foreach (var item in reservoirItem.MetalCells)                {                    if (item.ModuleName != Module)                    {                        StandardHotMetalDevice metalDevice = DEVICE.GetDevice<StandardHotMetalDevice>(item.ModuleName);                        if (metalDevice != null)                        {                            _metalDevices.Add(metalDevice);                        }                    }                }            }            _isCAFlowRateWARN = new List<bool>(new bool[_metalDevices.Count]);            //DosingSystem数据初始化                        _replenType = reservoirItem.ChemReplenType;            _replenNum = reservoirItem.ChemReplenPumps;            if (_replenType != "" && _replenNum != 0)            {                                         _replenDatas = new ReplenData[_replenNum];                _rdsRecipe = new RdsRecipe[_replenNum];                _replenLevelLst = new List<bool>(new bool[_replenNum]);                _currentDosingOperation = new List<DosingOperation>();                for (int i = 0; i < _replenNum; i++)                {                    string replenName = "Replen" + (i + 1).ToString();                    _replenDatas[i] = new ReplenData();                    _replenDatas[i].ReplenName = replenName;                    _replenDatas[i].RecipeName = "";                    _replenDatas[i].BottleLevel = DosingSystemHelper.BottleLevelState.Empty.ToString();                    _replenDatas[i].IsAutoDosingError = false;                    if(_dosingSystemHelperLst==null) _dosingSystemHelperLst = new List<DosingSystemHelper> ();                    _dosingSystemHelperLst.Add(new DosingSystemHelper(Module, _replenDatas[i].ReplenName));                    _currentDosingOperation.Add(DosingOperation.None);                    _replenPersistentValue[replenName] = ReplenPersistentManager.Instance.GetReplenPersistentValue(Module, replenName);                }                _dosingCommonHelper = new DosingCommonHelper(Module, _replenNum);            }                    }        /// <summary>        /// 订阅数据        /// </summary>        private void SubscribeData()        {            DATA.Subscribe($"{Module}.DIValveMaxOnTime", () => SC.GetValue<double>($"Reservoir.{Module}.DIValveMaxOnTime")*60, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.IsManualReplen", () => { return _currentOperation == ReservoirOperation.ManualDiReplen; }, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.ReservoirData", () => _reservoirData, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.ReservoirAverageLevel", () => _avgLevel, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.{PERSISTENT_VALUE}", () => _persistentValue,SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.ReplenPersistentValue", () => _replenPersistentValue, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.PHValue", () => _avaragePH, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.CurrentRecipe", () => _resRecipe, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.ReplenType", () => _replenType, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.ReplenNum", () => _replenNum, SubscriptionAttribute.FLAG.IgnoreSaveDB);                       DATA.Subscribe($"{Module}.ReplenDatas", () => _replenDatas, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.DosingSystemState", () => _dosingCommonHelper != null ? _dosingCommonHelper.DosingSystemState : null, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.RecipeName", () => (_resRecipe != null ? _resRecipe.Ppid : ""), SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.HedFlow", () => _reservoirData.HedFlow, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"{Module}.PHEnable",()=>_reservoirData.PHFlowValve, SubscriptionAttribute.FLAG.IgnoreSaveDB);        }        /// <summary>        /// 初始化操作        /// </summary>        private void InitializeOperation()        {                        OP.Subscribe($"{Module}.DisabledAction", DisabledOperation);            OP.Subscribe($"{Module}.ManualAction", ManualOperation);            OP.Subscribe($"{Module}.AutoAction", AutoOperation);            OP.Subscribe($"{Module}.EngineeringModeAction", EngineeringModeOperation);            OP.Subscribe($"{Module}.ProductionModeAction", ProductionModeOperation);            OP.Subscribe($"{Module}.DiReplenOn", DIReplenOnOperation);            OP.Subscribe($"{Module}.DiReplenOff", DIReplenOff);            OP.Subscribe($"{Module}.ManualDiReplen", ManualDiReplen);            OP.Subscribe($"{Module}.ResetTotalTime", ResetTotalTime);            OP.Subscribe($"{Module}.LoadRecipe", LoadRecipeOperation);            OP.Subscribe($"{Module}.LoadDosingRecipe", LoadDosingRecipeOperation);            OP.Subscribe($"{Module}.ReplenPumpOn", ReplenPumpOnOperation);            OP.Subscribe($"{Module}.ReplenPumpOff", ReplenPumpOffOperation);            OP.Subscribe($"{Module}.SetPumpFactor", SetPumpFactor);            OP.Subscribe($"{Module}.ManualDosing", ManualDosing);            OP.Subscribe($"{Module}.StopManualDosing", StopManualDosing);            OP.Subscribe($"{Module}.ResetBottleVolume", ResetBottleVolume);            OP.Subscribe($"{Module}.DosingInitialize", DosingInitialize);        }        #region Operation        /// <summary>        /// 重置时长        /// </summary>        /// <param name="cmd"></param>        /// <param name="objs"></param>        /// <returns></returns>        private bool ResetTotalTime(string cmd, object[] objs)        {            _persistentValue.TotalReplen = 0;            _persistentValue.LastTotalReplen = 0;            ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);            return true;        }        /// <summary>        /// DisabledAction        /// </summary>        /// <param name="cmd"></param>        /// <param name="param"></param>        /// <returns></returns>        private bool DisabledOperation(string cmd, object[] args)        {            string currentOperation = "Disabled";            if (args.Length >= 1 && (bool)args[0])            {                foreach(var replenData in ReplenDatas)                {                    if (_replenPersistentValue != null && _replenPersistentValue[replenData.ReplenName] != null)                    {                        _replenPersistentValue[replenData.ReplenName].OperatingMode = currentOperation;                        ReplenPersistentManager.Instance.UpdatePersistentValue(Module, replenData.ReplenName);                    }                }                for (int i = 0; i < _replenNum; i++)                {                    string replenName = "Replen" + (i + 1).ToString();                    if (_replenPersistentValue[replenName].IsDosingRunning)                    {                        _dosingSystemHelperLst[i].StopDosing();                        _currentDosingOperation[i] = DosingOperation.None;                    }                }                DosingEnterInit();            }            else            {                if (_persistentValue != null)                {                    ReservoirEntity reservoirEntity = Singleton<RouteManager>.Instance.GetModule<ReservoirEntity>(Module);                    if (_persistentValue.OperatingMode == "Auto" && reservoirEntity.IsMetalBusy)                    {                        LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{Module} is Busy, can't change to disable mode");                        return false;                    }                    foreach (var metalDevice in _metalDevices)                    {                        metalDevice.DisabledOperation("", null);                                               MetalEntity metalEntity = Singleton<RouteManager>.Instance.GetModule<MetalEntity>(metalDevice.Module);                        metalEntity.AbortRecipe(null);                                                metalDevice.EnterDisabledOperation();                    }                    EnterDisabledOperation();                    if (_persistentValue.OperatingMode != "Disabled") reservoirEntity.EnterInit();                    _persistentValue.OperatingMode = currentOperation;                }                ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);                _currentOperation = ReservoirOperation.None;            }                        return true;        }        /// <summary>        /// ManualAction        /// </summary>        /// <param name="cmd"></param>        /// <param name="param"></param>        /// <returns></returns>        private bool ManualOperation(string cmd, object[] args)        {            string currentOperation = "Manual";            if (args.Length >= 1 && (bool)args[0])            {                foreach (var replenData in ReplenDatas)                {                    if (_replenPersistentValue != null && _replenPersistentValue[replenData.ReplenName] != null)                    {                        _replenPersistentValue[replenData.ReplenName].OperatingMode = currentOperation;                        ReplenPersistentManager.Instance.UpdatePersistentValue(Module, replenData.ReplenName);                    }                }                DosingEnterInit();            }            else            {                ReservoirEntity reservoirEntity = Singleton<RouteManager>.Instance.GetModule<ReservoirEntity>(Module);                if (reservoirEntity == null) return false;                                if (_persistentValue != null)                {                    if (_persistentValue.OperatingMode == "Auto" && reservoirEntity.IsMetalBusy)                    {                        LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{Module} is Busy, can't change to manual mode");                        return false;                    }                    foreach (var metalDevice in _metalDevices)                    {                        metalDevice.ManualOperation("", null);                    }                    if (_persistentValue.OperatingMode != "Manual" && reservoirEntity != null) reservoirEntity.EnterInit();                    _persistentValue.OperatingMode = currentOperation;                }                ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);                _currentOperation = ReservoirOperation.None;            }                            return true;        }        /// <summary>        /// AutoAction        /// </summary>        /// <param name="cmd"></param>        /// <param name="param"></param>        /// <returns></returns>        private bool AutoOperation(string cmd, object[] args)        {            if (!_reservoirData.LowLevel)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Lowlevel was activate");                return false;            }            string currentOperation = "Auto";            if (args.Length >= 1 && (bool)args[0])            {                foreach (var replenData in ReplenDatas)                {                    if (_replenPersistentValue != null && _replenPersistentValue[replenData.ReplenName] != null)                    {                        _replenPersistentValue[replenData.ReplenName].OperatingMode = currentOperation;                        ReplenPersistentManager.Instance.UpdatePersistentValue(Module, replenData.ReplenName);                    }                }                DosingEnterInit();            }            else            {                if (_persistentValue != null)                {                    ReservoirEntity reservoirEntity = Singleton<RouteManager>.Instance.GetModule<ReservoirEntity>(Module);                    if (_persistentValue.OperatingMode != "Auto" && reservoirEntity != null) reservoirEntity.EnterInit();                    _persistentValue.OperatingMode = currentOperation;                }                ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);            }                                    return true;        }        /// <summary>        /// EngineeringModeAction        /// </summary>        /// <param name="cmd"></param>        /// <param name="param"></param>        /// <returns></returns>        private bool EngineeringModeOperation(string cmd, object[] args)        {            string currentRecipeOperation = "Engineering";            if (_persistentValue != null)            {                _persistentValue.RecipeOperatingMode = currentRecipeOperation;            }            ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);            return true;        }        /// <summary>        /// ProductionAction        /// </summary>        /// <param name="cmd"></param>        /// <param name="param"></param>        /// <returns></returns>        private bool ProductionModeOperation(string cmd, object[] args)        {            string currentRecipeOperation = "Production";            if (_persistentValue != null)            {                _persistentValue.RecipeOperatingMode = currentRecipeOperation;            }            ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);            return true;        }        /// <summary>        /// 加载Recipe        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        private bool LoadRecipeOperation(string cmd, object[] args)        {            _persistentValue.Recipe = args[0].ToString();            string[] fileRoute = _persistentValue.Recipe.Split('\\');            string recipeRoute = "";            if (fileRoute.Length > 2)            {                recipeRoute = fileRoute[fileRoute.Length - 2];            }            try            {                _resRecipe = RecipeFileManager.Instance.LoadGenericityRecipe<ResRecipe>(_persistentValue.Recipe);                ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module.ToString());                LOG.WriteLog(eEvent.INFO_RESERVOIR, Module, $"Load {recipeRoute} Recipe {_resRecipe.Ppid} Success");            }            catch            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Load {recipeRoute} Recipe {_persistentValue.Recipe} failed");            }            return true;        }        /// <summary>        /// DiReplen On        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        public bool DIReplenOnOperation(string cmd, object[] args)        {            return DIReplenOn(true);        }        /// <summary>        /// 自动注水        /// </summary>        /// <returns></returns>        public bool DIReplenOn(bool showError)        {            if (ReservoirData.WaterLevel > SC.GetValue<double>($"Reservoir.{Module}.HighLevel"))            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, "Highlevel is activate");                return false;            }            if (!_reservoirData.LowLevel) //信号是相反的            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"WaterLevel low is Activate");                return false;            }            bool preCondition = CheckPreDiReplenCondition(showError);            if (!preCondition)            {                return false;            }            string ioName = BeckhoffModuleIOManager.Instance.GetIoNameByInnerModuleName($"{Module}.{DI_REPLEN}");            bool result = IOModuleManager.Instance.WriteIoValue(ioName, true);            if (result)            {                _persistentValue.IsDiReplenOn = true;            }            return result;        }        /// <summary>        /// 检验DiReplen前置条件        /// </summary>        /// <returns></returns>        public bool CheckPreDiReplenCondition(bool showError)        {            if (!CheckFacilitiesDiReplenStatus()&&showError)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, "Facilities DiReplen is Off");                return false;            }            SafetyDevice safetyDevice = DEVICE.GetDevice<SafetyDevice>("Safety");            if (safetyDevice != null && safetyDevice.SafetyData.ReservoirHighLevel)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Safety high is Activate");                return false;            }            if (CheckOtherReservoirDiReplenStatus(showError))            {                return false;            }            return true;        }        /// <summary>        /// 检验总Di有没有开        /// </summary>        /// <returns></returns>        private bool CheckFacilitiesDiReplenStatus()        {            SystemFacilities systemFacilities = DEVICE.GetDevice<SystemFacilities>("System.Facilities");            if(systemFacilities!=null)            {                return systemFacilities.DIReplenEnable;            }            return false;        }        /// <summary>        /// 检验是否其他Reservoir Direplen已经        /// </summary>        /// <returns></returns>        private bool CheckOtherReservoirDiReplenStatus(bool showError)        {            List<string> reservoirs = ReservoirItemManager.Instance.InstalledModules;            foreach (string item in reservoirs)            {                if(item!=Module)                {                    ReservoirItem reservoirItem=ReservoirItemManager.Instance.GetReservoirItem(item);                    if(reservoirItem.SubType==STRATUS)                    {                        StandardHotReservoirDevice tmpDevice = DEVICE.GetDevice<StandardHotReservoirDevice>(item);                        if(tmpDevice.ReservoirData.DiReplen && showError)                        {                            LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{item} direplen valve is on");                            return true;                        }                    }                    else                    {                        CompactMembranReservoirDevice tmpDevice = DEVICE.GetDevice<CompactMembranReservoirDevice>(item);                        if(tmpDevice.ReservoirData.ANDiReplen&&showError)                        {                            LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{item} ANDireplen valve is on");                            return true;                        }                        if(tmpDevice.ReservoirData.CADiReplen && showError)                        {                            LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{item} CADireplen valve is on");                            return true;                        }                    }                }            }            return false;        }        /// <summary>        /// DiReplen Off        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        private bool DIReplenOff(string cmd, object[] args)        {            string ioName = BeckhoffModuleIOManager.Instance.GetIoNameByInnerModuleName($"{Module}.{DI_REPLEN}");            bool result= IOModuleManager.Instance.WriteIoValue(ioName, false);            if(result)            {                _persistentValue.IsDiReplenOn = false;                if(_currentOperation==ReservoirOperation.ManualDiReplen||_currentOperation==ReservoirOperation.AutoDiReplen)                {                    _currentOperation = ReservoirOperation.None;                    _persistentValue.LastTotalReplen = _persistentValue.TotalReplen;                    ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);                }            }            return result;        }        /// <summary>        /// 手动注水        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        private bool ManualDiReplen(string cmd, object[] args)        {            if(_currentOperation!=ReservoirOperation.None)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"current operation is {_currentOperation},cannot execute ManualDireplen operation");                return false;            }            bool result = DIReplenOnOperation("", null);            if(result)            {                _currentOperation = ReservoirOperation.ManualDiReplen;                _persistentValue.DiReplenTime = DateTime.Now;                ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);                int.TryParse(args[0].ToString(), out _manualReplenSecond);            }            return result;        }        /// <summary>        /// 自动注水        /// </summary>        /// <returns></returns>        public bool AutoDireplen()        {            if (!_reservoirData.LowLevel && !_isAutoDIReplenError)            {                _isAutoDIReplenError = true;                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"LowLevel is activate,Can't AutoDireplen");                return false;            }            else            {                _isAutoDIReplenError = false;            }            if (_currentOperation != ReservoirOperation.None)            {                return false;            }            if(_resRecipe==null)            {                return false;            }            bool result = DIReplenOn(false);            if(result)            {                _currentOperation = ReservoirOperation.AutoDiReplen;                _persistentValue.DiReplenTime = DateTime.Now;            }            return result;        }        /// <summary>        /// 启动PH检测        /// </summary>        public bool StartDetectPHValve()        {            if(_persistentValue.OperatingMode==MANUAL)            {                return false;            }            _phState= _phRoutine.Start();            LOG.WriteLog(eEvent.INFO_RESERVOIR, Module, "Start Detect PH");            return true;        }        /// <summary>        /// 打开PH Valve        /// </summary>        /// <returns></returns>        public bool PHValveOn()        {            string ioName = BeckhoffModuleIOManager.Instance.GetIoNameByInnerModuleName($"{Module}.{PH_FLOW_VALVE}");            return IOModuleManager.Instance.WriteIoValue(ioName, true);        }        /// <summary>        /// 关闭PH Valve        /// </summary>        /// <returns></returns>        public bool PHValveOff()        {            string ioName = BeckhoffModuleIOManager.Instance.GetIoNameByInnerModuleName($"{Module}.{PH_FLOW_VALVE}");            return IOModuleManager.Instance.WriteIoValue(ioName, false);        }        /// <summary>        /// CAFlowRateCheck        /// </summary>        private void CAFlowRateCheck()        {            ReservoirEntity reservoirEntity = Singleton<RouteManager>.Instance.GetModule<ReservoirEntity>(Module);            if (_resRecipe == null) return;            for (int i = 0; i < _metalDevices.Count; i++)            {                StandardHotMetalDevice hotMetalDevice = _metalDevices[i];                                if (hotMetalDevice != null && !hotMetalDevice.IsDisable && hotMetalDevice.IsAuto)                {                    if (hotMetalDevice.MetalDeviceData == null || !hotMetalDevice.MetalDeviceData.Circulation) continue;                    if (!hotMetalDevice.FlowValveStable) continue;                    double cellFlow = hotMetalDevice.MetalDeviceData.CellFlow;                    if (cellFlow < _resRecipe.CAFlowRateErrorLow)                    {                        LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"cell {hotMetalDevice.Name} cellflow:{cellFlow} is less than recipe's CAFlowRateErrorLow parameter:{_resRecipe.CAFlowRateErrorLow}");                        reservoirEntity.PostMsg(ReservoirMsg.Error);                    }                    else if (cellFlow < _resRecipe.CAFlowRateWarningLow)                    {                        if (!_isCAFlowRateWARN[i])                        {                            LOG.WriteLog(eEvent.WARN_RESERVOIR, Module, $"cell {hotMetalDevice.Name} cellflow:{cellFlow} is less than recipe's CAFlowRateWarningLow parameter:{_resRecipe.CAFlowRateWarningLow}");                            _isCAFlowRateWARN[i] = true;                        }                    }                    else                    {                        _isCAFlowRateWARN[i] = false;                    }                }            }        }        /// <summary>        /// Temperature Check        /// </summary>        private void TemperatureCheck()        {            ReservoirEntity reservoirEntity = Singleton<RouteManager>.Instance.GetModule<ReservoirEntity>(Module);            ReservoirItem reservoirItem = ReservoirItemManager.Instance.GetReservoirItem(Module);            TemperatureController temperatureController = DEVICE.GetDevice<TemperatureController>(reservoirItem.TCID);            if (temperatureController == null || temperatureController.TemperatureData == null || _resRecipe == null                 || temperatureController.TemperatureData.ControlOperationModel != ENABLE) return;            double tempValue = temperatureController.TemperatureData.ReserviorTemperature;                        if (tempValue > _resRecipe.TemperatureErrorHigh && !reservoirEntity.IsError)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{temperatureController.Name} temperature:{tempValue} is over recipe's TemperatureErrorHigh parameter:{_resRecipe.TemperatureErrorHigh}");                reservoirEntity.PostMsg(ReservoirMsg.Error);            }            else if (tempValue < _resRecipe.TemperatureErrorLow && !reservoirEntity.IsError)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{temperatureController.Name} temperature:{tempValue} is less than recipe's TemperatureErrorLow parameter:{_resRecipe.TemperatureErrorLow}");                reservoirEntity.PostMsg(ReservoirMsg.Error);            }            else if (tempValue > _resRecipe.TemperatureWarningHigh)            {                if (!_isTCControlWARN)                {                    LOG.WriteLog(eEvent.WARN_RESERVOIR, Module, $"{temperatureController.Name} temperature:{tempValue} is over recipe's TemperatureWarningHigh parameter:{_resRecipe.TemperatureWarningHigh}");                    _isTCControlWARN = true;                }            }            else if (tempValue < _resRecipe.TemperatureWarningLow)            {                if (!_isTCControlWARN)                {                    LOG.WriteLog(eEvent.WARN_RESERVOIR, Module, $"{temperatureController.Name} temperature:{tempValue} is less than recipe's TemperatureWarningLow parameter:{_resRecipe.TemperatureWarningLow}");                    _isTCControlWARN = true;                }            }            else            {                _isTCControlWARN = false;            }        }        /// <summary>        /// CMMPowerCheck        /// </summary>        private void CMMPowerCheck()        {            ReservoirEntity reservoirEntity = Singleton<RouteManager>.Instance.GetModule<ReservoirEntity>(Module);            ReservoirItem _reservoirItem = ReservoirItemManager.Instance.GetReservoirItem(Module.ToString());                        if (!string.IsNullOrEmpty(_reservoirItem.CMMSupplyID))            {                CellPowerSupplier _powerSupplier = DEVICE.GetDevice<CellPowerSupplier>(_reservoirItem.CMMSupplyID);                if (_powerSupplier == null || _powerSupplier.PowerSupplierData == null || _resRecipe == null || !_resRecipe.CMMEnable||!_powerSupplier.PowerSupplierData.Enabled || _powerSupplier.PowerSupplierData.Current == 0) return;                //CMM Current Check                double current = _powerSupplier.PowerSupplierData.Current;                if (current > _resRecipe.CMMCurrentSetPoint * (1 + (double)_resRecipe.CMMCurrentFaultPercent / 100))                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{_powerSupplier.Name} current:{current} is over error upper limit:{_resRecipe.CMMCurrentSetPoint * (1 + (double)_resRecipe.CMMCurrentFaultPercent / 100)} based on recipe's CMMCurrentFaultPercent parameter:{_resRecipe.CMMCurrentFaultPercent} %");                    reservoirEntity.PostMsg(ReservoirMsg.Error);                    if (_powerSupplier.PowerSupplierData.Enabled)                    {                        _powerSupplier.DisableOperation("", null);                        _persistentValue.CMMStartTime = DateTime.MinValue;                        ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);                    }                                        }                else if (current < _resRecipe.CMMCurrentSetPoint * (1 - (double)_resRecipe.CMMCurrentFaultPercent / 100))                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{_powerSupplier.Name} current:{current} is less than error lower limit:{_resRecipe.CMMCurrentSetPoint * (1 - (double)_resRecipe.CMMCurrentFaultPercent / 100)} based on recipe's CMMCurrentFaultPercent parameter:{_resRecipe.CMMCurrentFaultPercent}%");                    reservoirEntity.PostMsg(ReservoirMsg.Error);                    if (_powerSupplier.PowerSupplierData.Enabled)                    {                        _powerSupplier.DisableOperation("", null);                        _persistentValue.CMMStartTime = DateTime.MinValue;                        ReservoirsPersistentManager.Instance.UpdatePersistentValue(Module);                    }                                        }                else if (current > _resRecipe.CMMCurrentSetPoint * (1 + (double)_resRecipe.CMMCurrentWarningPercent / 100))                {                    if (!_isCMMPowerCurrentWARN)                    {                        LOG.WriteLog(eEvent.WARN_RESERVOIR, Module, $"{_powerSupplier.Name} current:{current} is over warning upper limit:{_resRecipe.CMMCurrentSetPoint * (1 + (double)_resRecipe.CMMCurrentWarningPercent / 100)} based on recipe's CMMCurrentWarningPercent parameter:{_resRecipe.CMMCurrentWarningPercent}%");                        _isCMMPowerCurrentWARN = true;                    }                }                else if (current < _resRecipe.CMMCurrentSetPoint * (1 - (double)_resRecipe.CMMCurrentWarningPercent / 100))                {                    if (!_isCMMPowerCurrentWARN)                    {                        LOG.WriteLog(eEvent.WARN_RESERVOIR, Module, $"{_powerSupplier.Name} current:{current} is less than warning lower limit{_resRecipe.CMMCurrentSetPoint * (1 - (double)_resRecipe.CMMCurrentWarningPercent / 100)} based on recipe's CMMCurrentWarningPercent parameter:{_resRecipe.CMMCurrentWarningPercent}%");                        _isCMMPowerCurrentWARN = true;                    }                }                else                {                    _isCMMPowerCurrentWARN = false;                }                //CMM Voltage Check                double voltage = _powerSupplier.PowerSupplierData.Voltage;                if (voltage < _resRecipe.CMMMinVoltage)                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{_powerSupplier.Name} voltage:{voltage} is less than recipe's CMMMinVoltage parameter:{_resRecipe.CMMMinVoltage}");                    reservoirEntity.PostMsg(ReservoirMsg.Error);                    if (_powerSupplier.PowerSupplierData.Enabled) _powerSupplier.DisableOperation("", null);                }                //CMM Flow Check                double flow = ReservoirData.Flow;                double cmmFlowHighFault = SC.GetValue<double>($"Reservoir.CMM.CMMFlowHighFault");                double cmmFlowHighWarning = SC.GetValue<double>($"Reservoir.CMM.CMMFlowHighWarning");                double cmmFlowLowFault = SC.GetValue<double>($"Reservoir.CMM.CMMFlowLowFault");                double cmmFlowLowWarning = SC.GetValue<double>($"Reservoir.CMM.CMMFlowLowWarning");                if (flow < cmmFlowLowFault)                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{Module} CMM flow:{flow} is less than config item CMMFlowLowFault:{cmmFlowLowFault}");                    if (_powerSupplier.PowerSupplierData.Enabled) _powerSupplier.DisableOperation("", null);                    reservoirEntity.PostMsg(ReservoirMsg.Error);                }                else if (flow < cmmFlowLowWarning)                {                    if (!_isCMMPowerFlowWARN)                    {                        LOG.WriteLog(eEvent.WARN_RESERVOIR, Module, $"{Module} CMM flow:{flow} is less than config item CMMFlowLowWarning:{cmmFlowLowWarning}");                        _isCMMPowerFlowWARN = true;                    }                                    }                else if (flow > cmmFlowHighFault)                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{Module} CMM flow:{flow} is over config item CMMFlowHighFault:{cmmFlowLowFault}");                    if(_powerSupplier.PowerSupplierData.Enabled) _powerSupplier.DisableOperation("", null);                    reservoirEntity.PostMsg(ReservoirMsg.Error);                }                else if (flow > cmmFlowHighWarning)                {                    if (!_isCMMPowerFlowWARN)                    {                        LOG.WriteLog(eEvent.WARN_RESERVOIR, Module, $"{Module} CMM flow:{flow} is over config item CMMFlowHighWarning:{cmmFlowLowWarning}");                        _isCMMPowerFlowWARN = true;                     }                }                else                {                    _isCMMPowerFlowWARN = false;                }            }                    }        #region DosingSystem        /// <summary>        /// 加载Replen Recipe        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        private bool LoadDosingRecipeOperation(string cmd, object[] args)        {            string replenName = args[1].ToString();            int replenID = int.Parse(args[1].ToString().Substring(6,1));            string replenRecipe = args[0].ToString();            _rdsRecipe[replenID-1] = RecipeFileManager.Instance.LoadGenericityRecipe<RdsRecipe>(replenRecipe);            _replenDatas[replenID-1].RecipeName = args[2].ToString();            LOG.WriteLog(eEvent.INFO_RESERVOIR, Module, $"Load Replen Recipe {_rdsRecipe[replenID-1].Ppid} Success");            return true;        }        #region Replen Pump        /// <summary>        /// Replen Pump On 操作(根据PumpFactor和InitialDosingSpeed调速)        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        public bool ReplenPumpOnOperation(string cmd, object[] args)        {            string replenName = args[0].ToString();            int replenID = int.Parse(args[0].ToString().Substring(6, 1));            //加载InitialDosingSpeed            double InitialDosingSpeed = 0;            if (SC.ContainsItem($"Reservoir.{Module}.InitialDosingSpeed"))            {                InitialDosingSpeed = SC.GetValue<double>($"Reservoir.{Module}.InitialDosingSpeed");                if(InitialDosingSpeed == 0)                {                    _replenDatas[replenID - 1].ReplenPumpEnable = false;                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, "InitialDosingSpeed is zero. Can't open replen pump");                    return false;                }            }            else            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, "Configuration item of InitialDosingSpeed doesn't exist!");                return false;            }            //加载ReplenPumpFactor            double PumpFactor = 0;            PumpFactor = _replenPersistentValue[replenName].ReplenPumpFactor;            if(PumpFactor == 0)            {                _replenDatas[replenID - 1].ReplenPumpEnable = false;                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, "PumpFactor is zero. Can't open replen pump");                return false;            }            //计算PumpSpeed(mL/min)            double replenPumpSpeed = InitialDosingSpeed * PumpFactor;               SCConfigItem item = SC.GetConfigItem($"Reservoir.{Module}.InitialDosingSpeed");            double speedMax = double.Parse(item.Max);            if(replenPumpSpeed > speedMax) replenPumpSpeed = speedMax;            bool result = ReplenPump(replenPumpSpeed / PUMP_SPEED_CONVERT, replenID);            if (!result)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Opening replen{replenID} pump is failed");                _replenDatas[replenID - 1].ReplenPumpSpeed = 0;                _replenDatas[replenID - 1].ReplenPumpEnable = false;                return false;            }            _replenDatas[replenID - 1].ReplenPumpSpeed = replenPumpSpeed;            _replenDatas[replenID - 1].ReplenPumpEnable = true;            LOG.WriteLog(eEvent.INFO_RESERVOIR, Module, $"Replen{replenID} pump is opened");            return true;        }        /// <summary>        /// Replen Pump Off操作        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        public bool ReplenPumpOffOperation(string cmd, object[] args)        {            string replenName = args[0].ToString();            int replenID = int.Parse(args[0].ToString().Substring(6, 1));            bool result = ReplenPump(0, replenID);            if (!result)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Closing replen{replenID} pump is failed");                return false;            }            _replenDatas[replenID - 1].ReplenPumpSpeed = 0;            _replenDatas[replenID - 1].ReplenPumpEnable = false;            LOG.WriteLog(eEvent.INFO_RESERVOIR, Module, $"Replen{replenID} pump is closed");            return true;        }        /// <summary>        /// Replen Pump WriteIOValue        /// </summary>        /// <param name="speed"></param>        /// <returns></returns>        private bool ReplenPump(double speed, int replenNum)        {            string ioName = BeckhoffModuleIOManager.Instance.GetIoNameByInnerModuleName($"{Module}.Replen{replenNum}PumpSpeed");            return IOModuleManager.Instance.WriteIoValue(ioName, speed);        }               #endregion            /// <summary>        /// 设置PumpFactor        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        public bool SetPumpFactor(string cmd, object[] args)        {            int replenID = int.Parse(args[0].ToString().Substring(6, 1));            double targetPumpFactor = (double)args[1];            _dosingSystemHelperLst[replenID-1].SetPumpfactor(targetPumpFactor);                       return true;        }        /// <summary>        /// 手动Dosing        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        private bool ManualDosing(string cmd, object[] args)        {            ReservoirEntity reservoirEntity = Singleton<RouteManager>.Instance.GetModule<ReservoirEntity>(Module);            if (reservoirEntity == null || !_dosingCommonHelper.IsDosingSystemInitialized)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, "Dosing System is not initialized!");                return true;            }            string replenName = args[0].ToString();            int replenID = int.Parse(args[0].ToString().Substring(6, 1));            double manualDosingVolume = (double)args[1];            if(manualDosingVolume == 0)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, "Dosing Volume is zero, can't do manual dosing");                return false;            }            if (!CheckandUpdateBottleLevel(replenName, manualDosingVolume))            {                return false;            }            if (_replenPersistentValue[replenName].IsDosingRunning)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, "Dosing is runnning, can't do manual dosing");                return false;            }            LOG.WriteLog(eEvent.INFO_RESERVOIR, Module, "ManualDosing starts now");            _currentDosingOperation[replenID - 1] = DosingOperation.ManualDosing;            bool result = _dosingSystemHelperLst[replenID-1].StartDosing(manualDosingVolume, false);            return result;        }        /// <summary>        /// 停止手动Dosing        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        private bool StopManualDosing(string cmd, object[] args)        {                       string replenName = args[0].ToString();            int replenID = int.Parse(args[0].ToString().Substring(6, 1));            if (!_replenPersistentValue[replenName].IsDosingRunning)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, "ManualDosing is not running. Can't stop!");            }            _currentDosingOperation[replenID - 1] = DosingOperation.None;                      bool result = _dosingSystemHelperLst[replenID - 1].StopDosing();            if (result)            {                LOG.WriteLog(eEvent.INFO_RESERVOIR, Module, "ManualDosing has stopped now");            }            return result;        }                /// <summary>        /// 检查并更新BottleLevel状态        /// </summary>        /// <param name="replenName"></param>        /// <param name="targetVolume"></param>        public bool CheckandUpdateBottleLevel(string replenName, double targetVolume = -1, bool isError = true)        {            int replenId = int.Parse(replenName.Substring(6, 1));            double remainVolume = _replenPersistentValue[replenName].RemainDosingVolume;            bool result = true;            if (ReservoirData.ReplenLevel[replenId - 1])            {                ReplenDatas[replenId - 1].BottleLevel = DosingSystemHelper.BottleLevelState.Full.ToString();                if (targetVolume > remainVolume)                {                    ReplenDatas[replenId - 1].BottleLevel = DosingSystemHelper.BottleLevelState.Warning.ToString();                    if (isError)                    {                        LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Current Bottle is in Warning Level!");                    }                                        result = false;                }            }            else            {                ReplenDatas[replenId - 1].BottleLevel = DosingSystemHelper.BottleLevelState.Empty.ToString();                if (isError)                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"Current Bottle is in Empty Level!");                }                                  result = false;            }            return result;        }        /// <summary>        /// Reset BottleVolume        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        private bool ResetBottleVolume(string cmd, object[] args)        {            string replenName = args[0].ToString();            int replenID = int.Parse(args[0].ToString().Substring(6, 1));            if (SC.ContainsItem($"Reservoir.{Module}.BottleReserveVolume{replenID}"))            {                _replenPersistentValue[replenName].RemainDosingVolume = SC.GetValue<double>($"Reservoir.{Module}.BottleReserveVolume{replenID}");            }            ReplenPersistentManager.Instance.UpdatePersistentValue(Module, replenName);            LOG.WriteLog(eEvent.INFO_RESERVOIR, Module, $"Bottle Reserve Volume of Replen{replenID} has been reset now");            return true;        }                      /// <summary>        /// DosingSystem初始化        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        private bool DosingInitialize(string cmd, object[] args)        {            ReservoirEntity reservoirEntity = Singleton<RouteManager>.Instance.GetModule<ReservoirEntity>(Module);            if (reservoirEntity == null || !reservoirEntity.IsInitialized)            {                LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{Module} is not initialized");                return false;            }            return _dosingCommonHelper.DosingInitialize(); ;        }        /// <summary>        /// Enetr Init State        /// </summary>        /// <param name="cmd"></param>        /// <param name="args"></param>        /// <returns></returns>        private bool DosingEnterInit()        {            return _dosingCommonHelper.DosingEnterInit();        }        #endregion        /// <summary>        /// Enter Disabled Operation        /// </summary>        private void EnterDisabledOperation()        {                       ReservoirItem _reservoirItem = ReservoirItemManager.Instance.GetReservoirItem(Module.ToString());            //关CMMPower            if (!string.IsNullOrEmpty(_reservoirItem.CMMSupplyID))            {                CellPowerSupplier powerSupplier = DEVICE.GetDevice<CellPowerSupplier>(_reservoirItem.CMMSupplyID);                if(powerSupplier != null && powerSupplier.PowerSupplierData.Enabled) powerSupplier.DisableOperation("", null);            }            //关TC            if (!string.IsNullOrEmpty(_reservoirItem.TCID))            {                TemperatureController temperatureController = DEVICE.GetDevice<TemperatureController>(_reservoirItem.TCID);                if(temperatureController != null) temperatureController.DisableOperation("", null);            }            _phRoutine.Abort();            if (_reservoirData.PHFlowValve)            {                PHValveOff();            }            if (_reservoirData.DiReplen)            {                DIReplenOff("", null);            }        }        /// <summary>        /// Set Export CMMUsage        /// </summary>        public void SetExportCMMUsage()        {            _isExportCMMUsage = true;        }        #endregion        /// <summary>        /// 订阅变量数值发生变化        /// </summary>        private void SubscribeValueAction()        {            BeckhoffIoSubscribeUpdateVariable(FLOW);            BeckhoffIoSubscribeUpdateVariable(HED_FLOW);            BeckhoffIoSubscribeUpdateVariable(DI_REPLEN);            BeckhoffIoSubscribeUpdateVariable(PH_FLOW_VALVE);            BeckhoffIoSubscribeUpdateVariable(PH_VALUE);            BeckhoffIoSubscribeUpdateVariable(WATER_LEVEL);            BeckhoffIoSubscribeUpdateVariable(LOW_LEVEL);            BeckhoffIoSubscribeUpdateVariable(HIGH_LEVEL);            for(int i = 0;i < _replenNum;i++)            {                BeckhoffIoSubscribeUpdateVariable($"Replen{i+1}Level");            }                    }        /// <summary>        /// 订阅IO变量        /// </summary>        /// <param name="variable"></param>        private void BeckhoffIoSubscribeUpdateVariable(string variable)        {            _variableInitializeDic[variable] = false;            IOModuleManager.Instance.SubscribeModuleVariable(Module, variable, UpdateVariableValue);        }        /// <summary>        /// 更新变量数值        /// </summary>        /// <param name="variable"></param>        /// <param name="value"></param>        private void UpdateVariableValue(string variable, object value)        {            if (!ReservoirData.IsDataInitialized)            {                ReservoirData.IsDataInitialized = true;            }            PropertyInfo property = ReservoirData.GetType().GetProperty(variable);            if (property != null)            {                property.SetValue(_reservoirData, value);                if(variable==WATER_LEVEL)                {                    string levelCurve = SC.GetStringValue($"Reservoir.{Module}.LevelCurve");                    ReservoirData.Level = LevelCurveManager.Instance.CalculateLevelByWaterLevel(ReservoirData.WaterLevel, levelCurve);                }            }            if (variable.Contains("Replen") && variable.Substring(0,6) == "Replen")            {                property = ReservoirData.GetType().GetProperty(REPLEN_LEVEL);                _replenLevelLst[int.Parse(variable.Substring(6, 1)) - 1] = (bool)value;                property.SetValue(_reservoirData, _replenLevelLst);            }            if (_variableInitializeDic.ContainsKey(variable) && !_variableInitializeDic[variable])            {                _variableInitializeDic[variable] = true;            }        }        /// <summary>        /// 是否所有IO变量初始化完成        /// </summary>        /// <returns></returns>        private bool AllIoVariableInitialized()        {            foreach (string item in _variableInitializeDic.Keys)            {                if (!_variableInitializeDic[item])                {                    LOG.WriteLog(eEvent.ERR_RESERVOIR, Module, $"{item} is not initialized");                    return false;                }            }            return true;        }        public void Monitor()        {        }        public void Reset()        {        }        public void Terminate()        {        }    }}
 |