| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087 | using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Text;using System.Text.RegularExpressions;using System.Threading;using Aitex.Core.Common.DeviceData;using Aitex.Core.RT.ConfigCenter;using Aitex.Core.RT.DataCenter;using Aitex.Core.RT.Event;using Aitex.Core.RT.IOCore;using Aitex.Core.RT.Log;using Aitex.Core.RT.OperationCenter;using Aitex.Core.RT.SCCore;using Aitex.Core.RT.Tolerance;using Aitex.Core.Util;using Aitex.Core.RT.Device;using Aitex.Sorter.Common;using MECF.Framework.Common.Communications;using MECF.Framework.Common.DataCenter;using MECF.Framework.Common.Device.Bases;using MECF.Framework.Common.Equipment;using Venus_Core;using Venus_RT.Modules;namespace Venus_RT.Devices{    public enum Mode { Read = 0, Write }    public enum MatchingAutoMode { Hold = 0, Preset }    static class CometRFCommand    {        public const int Model = 11;        public const int Type = 12;        public const int SerialNumber = 13;        public const int NominalPower = 15;        public const int NominalFrequency = 16;        public const int Command = 1001;        public const int FrequencyMode = 1101;        public const int ControlMode = 1201;        public const int PowerSetPoint = 1206;        public const int TurnPulseMode = 1301;        public const int PulsePeriod = 1302;        public const int PulseDutyCycle = 1303;        public const int RFOnTime = 1701;        public const int ForwardPowerLimit = 1702;        public const int ReflectedPowerLimit = 1703;        public const int MatchingMode = 1703;        public const int State = 8000;        public const int NumberOfErrors = 8100;        public const int NumberOfWarnings = 8150;        public const int ForwardPower = 8021;        public const int ReflectedPower = 8022;        public const int MatchinMode = 8201;        public const int MatchingAutoMode = 8202;        public const int ActCLoadPosition = 8213;        public const int ActCTunePosition = 8214;        public const int CLoadRefPosition = 8203;        public const int CTuneRefPosition = 8204;        public const int MatchingState = 9201;        public const int MatchingActive = 9202;        public const int CLoadPosition = 9203;        public const int CTunePosition = 9204;        public const int CLoad = 9205;        public const int CTune = 9206;        public const int CLoadRefPos = 9210;        public const int CTuneRefPos = 9212;        public const int ProcessControlMatching = 9251;    }    class CometRF : RfPowerBase    {        private double _total;        private double _fromLast;        private readonly SCConfigItem _scPowerAlarmTime;        private readonly SCConfigItem _scPowerAlarmRange;        private readonly SCConfigItem _scReflectPowerAlarmTime;        private readonly SCConfigItem _scReflectPowerAlarmRange;        private readonly SCConfigItem _scPowerRange;        private int TransactionNumber = 0;        private static byte ProtocolIdentifierHighByte = 0x00;        private static byte ProtocolIdentifierLowByte = 0x00;        private static byte _address = 0x0A;        private static byte _read = 0x41;        private static byte _write = 0x42;        private static byte _readInvalid = 0xC1;        private static byte _writeInvalid = 0xC2;        private static byte[] _sendData;        private const int QUERY_INTERVAL = 500;        protected bool _commErr = false;        protected bool _exceuteErr = false;        protected string _addr;        protected static Object _locker = new Object();        private int _currentCommandNumber = 0;        public GeneratorStatus Status { get; set; }        public GeneratorStatus StatusMatch { get; set; }        public MatchingAutoMode MatchMode { get; set; }        public int ErrorCode { get; set; }        public bool Initalized { get; set; }        public const string delimiter = "\r";        //private string AlarmRobotError = "RF Error";        protected AsyncSocketDevice _socket;        private DateTime _powerOnStartTime;        private TimeSpan _powerOnElapsedTime;        private readonly DeviceTimer _timerQueryStatus = new DeviceTimer();        private readonly DeviceTimer _timerTotal = new DeviceTimer();        private readonly DeviceTimer _timerFromLast = new DeviceTimer();        private readonly RD_TRIG _rfOnTrigger = new RD_TRIG();        private readonly R_TRIG _ErrTrigger = new R_TRIG();        private readonly R_TRIG _trigPMNeeded = new R_TRIG();        private readonly RD_TRIG _trigOnOff = new RD_TRIG();        private StatsDataItemRFAndPump _statRFOnTime;        private ToleranceChecker _checkerPower;        private ToleranceChecker _checkerReflectPower;        private readonly DIAccessor _diIntlk;        private bool _isPowerOn;        public override float ScalePower => (float)_scPowerRange.DoubleValue;        public string Address        {            get { return _addr; }        }        public bool IsConnected        {            get            {                if (_socket == null)                    return false;                else                    return _socket.IsConnected;            }        }        public bool Disconnect()        {            return true;        }        public bool Communication        {            get            {                return !_commErr || _commErr || _exceuteErr;            }        }        public bool Error        {            get            {                return ErrorCode > 0;            }        }        public int MatchProcessMode        {            get            {                return (int)MatchMode;            }        }        public override bool IsPowerOn        {            get => Status == GeneratorStatus.ON;            set { }        }        public override bool IsMatchOn        {            get => StatusMatch == GeneratorStatus.ON;            set { }        }        public override bool IsError        {            get => Status == GeneratorStatus.ERROR;            set { }        }        public override bool IsMatchError        {            get => StatusMatch == GeneratorStatus.ERROR;            set { }        }        public string LastPMTime        {            get            {                return _statRFOnTime != null ? _statRFOnTime.LastPMTime.ToString() : "";            }        }        public double DaysFromLastPM        {            get            {                return _statRFOnTime == null ? 0 : _statRFOnTime.fromLastPM;            }            set            {                if (_statRFOnTime != null)                    _statRFOnTime.fromLastPM = value;            }        }        public double TotalDays        {            get            {                return _statRFOnTime != null ? _statRFOnTime.Total : 0;            }            set            {                if (_statRFOnTime != null)                    _statRFOnTime.Total = value;            }        }        public double PMIntervalDays        {            get            {                return _statRFOnTime != null ? _statRFOnTime.PMInterval : 0;            }        }        public bool IsPMNeeded        {            get            {                return DaysFromLastPM > PMIntervalDays;            }        }        public bool EnableAlarm        {            get            {                return _statRFOnTime == null || _statRFOnTime.AlarmEnable;            }        }        [Subscription("PowerOnTime")]        public string PowerOnTime        {            get            {                if (IsPowerOn)                    _powerOnElapsedTime = DateTime.Now - _powerOnStartTime;                return $"{(int)_powerOnElapsedTime.TotalHours:00}:{_powerOnElapsedTime.Minutes:00}:{(_powerOnElapsedTime.Seconds > 0 ? (_powerOnElapsedTime.Seconds + 1) : 0):00}";            }        }        public bool RFInterlock => _diIntlk == null || _diIntlk.Value;        private float _forwardPower;        public override float ForwardPower        {            get            {                return _forwardPower;            }            set            {                _forwardPower = CalibrationData(value, false);            }        }        public new AITRfData DeviceData =>           new AITRfData           {               Module = Module,               DeviceName = Name,               ScalePower = ScalePower,               ForwardPower = ForwardPower,               ReflectPower = ReflectPower,               IsRfOn = IsPowerOn,               PowerSetPoint = PowerSetPoint,               PowerOnElapsedTime = PowerOnTime,               IsInterlockOk = RFInterlock,               IsMatchOn = IsMatchOn,               MatchPositionC1 = CLoad,               MatchPositionC2 = CTune,               MatchVPP = VPP,               MatchPresetMode = MatchProcessMode,               MatchPositionC1SetPoint = CLoadSet,               MatchPositionC2SetPoint = CTuneSet,               WorkMode = (int)RfMode.ContinuousWaveMode,               DisplayName = "Bias RF",           };        public CometRF(ModuleName mod, string address) : base(mod.ToString(), VenusDevice.BiasRf.ToString())        {            if (SC.GetValue<bool>("System.IsSimulatorMode"))            {                address = "127.0.0.1:502";            }            Status = GeneratorStatus.Unknown;            StatusMatch = GeneratorStatus.Unknown;            MatchMode = MatchingAutoMode.Preset;            _addr = address;            _socket = new AsyncSocketDevice(address);            _socket.OnDataChanged += new AsyncSocketDevice.MessageHandler(OnDataChanged);            _socket.OnErrorHappened += new AsyncSocketDevice.ErrorHandler(OnErrorHandler);            _scPowerAlarmTime = SC.GetConfigItem($"{Module}.{Name}.PowerAlarmTime");            _scPowerAlarmRange = SC.GetConfigItem($"{Module}.{Name}.PowerAlarmRange");            _scReflectPowerAlarmTime = SC.GetConfigItem($"{Module}.{Name}.ReflectPowerAlarmTime");            _scReflectPowerAlarmRange = SC.GetConfigItem($"{Module}.{Name}.ReflectPowerAlarmRange");            _scPowerRange = SC.GetConfigItem($"{Module}.{Name}.PowerRange");            _scEnableCalibration = SC.GetConfigItem($"{Module}.{Name}.EnableCalibration");            _scCalibrationTable = SC.GetConfigItem($"{Module}.{Name}.CalibrationTable");            _diIntlk = IO.DI[$"{Module}.DI_RF_Generator_Interlock"];            Initalized = false;        }        ErrorEventArgsDevice oldargs;        private void OnErrorHandler(ErrorEventArgsDevice args)        {            //SetPowerOnOff(false, out _);            Status = GeneratorStatus.ERROR;            StatusMatch = GeneratorStatus.ERROR;            if (oldargs != null && oldargs.Code == args.Code) return;            LOG.Write(eEvent.ERR_RF,Module, $"{Module} Comet RF Error {args.Reason}");            oldargs = args;        }        public override bool Initialize()        {            base.Initialize();            DATA.Subscribe($"{Module}.{Name}.DeviceData", () => DeviceData);            Connect();            _statRFOnTime = StatsDataManager.Instance.GetItemRFAndPump($"{Module}.BiasRfOnTime");            _timerQueryStatus.Start(QUERY_INTERVAL);            _checkerPower = new ToleranceChecker(_scPowerAlarmTime.DoubleValue);            _checkerReflectPower = new ToleranceChecker(_scReflectPowerAlarmTime.DoubleValue);            OP.Subscribe($"{Module}.{Name}.Reconnect", (string cmd, object[] args) =>            {                return Connect();            });            OP.Subscribe($"{Module}.{Name}.{AITRfOperation.SetPowerOnOff}", (out string reason, int time, object[] param) =>            {                SetPowerOnOff(Convert.ToBoolean((string)param[0]), out reason);                return true;            });            OP.Subscribe($"{Module}.{Name}.{AITRfOperation.SetPower}", (out string reason, int time, object[] param) =>            {                reason = "";                ushort val = Convert.ToUInt16(param[0]);                SetPower(val);                return true;            });            OP.Subscribe($"{Module}.{Name}.{AITRfOperation.SetContinuousPower}", (out string reason, int time, object[] param) =>            {                reason = "";                ushort val = Convert.ToUInt16(param[0]);                SetPower(val);                return true;            });            OP.Subscribe($"{Module}.{Name}.{AITRfOperation.SetMatchProcessMode}", (out string reason, int time, object[] param) =>            {                BiasRfMatchMode mode = (BiasRfMatchMode)Enum.Parse(typeof(BiasRfMatchMode), (string)param[0], true);                reason = "";                if (mode == BiasRfMatchMode.Hold)                    SetMatchingAutoMode(false, out reason);                else                    SetMatchingAutoMode(true, out reason);                return true;            });            OP.Subscribe($"{Module}.{Name}.{AITRfOperation.SetMatchPositionC1}", (out string reason, int time, object[] param) =>            {                if (MatchMode == MatchingAutoMode.Hold)                {                    reason = string.Empty;                    return true;                }                float c1 = (float)Convert.ToDouble((string)param[0]);                reason = string.Format("Set RF match position c1 :{0}", c1);                if (c1 <= 100 && c1 >= 0)                {                    SendCmd(Mode.Write, CometRFCommand.CLoadRefPosition, (int)(c1 * 10));                }                return true;            });            OP.Subscribe($"{Module}.{Name}.{AITRfOperation.SetMatchPositionC2}", (out string reason, int time, object[] param) =>            {                if (MatchMode == MatchingAutoMode.Hold)                {                    reason = string.Empty;                    return true;                }                float c2 = (float)Convert.ToDouble((string)param[0]);                reason = string.Format("Set RF match position c2 :{0}", c2);                if (c2 <= 100 && c2 >= 0)                {                    SendCmd(Mode.Write, CometRFCommand.CTuneRefPosition, (int)(c2 * 10));                }                return true;            });            OP.Subscribe($"{Module}.{Name}.{AITRfOperation.SetMatchPosition}", (out string reason, int time, object[] param) =>            {                return SetMatchPosition(Convert.ToDouble((string)param[0]), Convert.ToDouble((string)param[1]), out reason);            });            DATA.Subscribe($"{Module}.{Name}.CommunicationStatus", () => _socket == null ? false : _socket.IsConnected);            //EV.Subscribe(new EventItem("Event", AlarmRobotError, "Robot error", EventLevel.Alarm, Aitex.Core.RT.Event.EventType.HostNotification));            //DATA.Subscribe($"{Module}.BiasMatch.C1", () => CLoad);            //DATA.Subscribe($"{Module}.BiasMatch.C2", () => CTune);            ////DATA.Subscribe($"{Module}.BiasMatch.VPP", () => VPP);            //DATA.Subscribe($"{Module}.BiasMatch.MatchProcessMode", () => (int)MatchMode);            Reset();            SendCmd(Mode.Write, CometRFCommand.ControlMode, 0);            SendCmd(Mode.Write, CometRFCommand.MatchinMode, 2);            Thread thread = new Thread(() =>            {                while (true)                {                    SendCmd(Mode.Read, CometRFCommand.State, 1);                    SendCmd(Mode.Read, CometRFCommand.ForwardPower, 1);                    SendCmd(Mode.Read, CometRFCommand.ReflectedPower, 1);                    SendCmd(Mode.Read, CometRFCommand.MatchingState, 1);                    SendCmd(Mode.Read, CometRFCommand.MatchingActive, 1);                    SendCmd(Mode.Read, CometRFCommand.CLoadPosition, 1);                    SendCmd(Mode.Read, CometRFCommand.CTunePosition, 1);                    SendCmd(Mode.Read, CometRFCommand.ProcessControlMatching, 1);                    //if(IsError)                    //{                    //    SendCmd(Mode.Read, CometRFCommand.NumberOfErrors, 1);                    //    SendCmd(Mode.Read, CometRFCommand.NumberOfWarnings, 1);                    //}                }            });            thread.Start();            return true;        }        public virtual bool Connect()        {            _commErr = false;            _socket?.Connect(this._addr);            return true;        }        public void OnDataChanged(byte[] rawMessage)        {            try            {                int recTransactionNumber = BitConverter.ToInt32(new byte[] { rawMessage[1], rawMessage[0], 0x00, 0x00 }, 0);                if (recTransactionNumber != TransactionNumber)                {                    if (!SC.GetValue<bool>("System.IsSimulatorMode"))                        LOG.Write(eEvent.ERR_RF, Module, $"RF transaction number is different");                    return;                }                if (rawMessage[6] != _address)                {                    LOG.Write(eEvent.ERR_RF, Module, $"RF invalid address byte");                }                if (rawMessage[7] == _read)                {                    if (rawMessage[8] == 4)                    {                        int DataValue = BytesToInt(new byte[] { rawMessage[9], rawMessage[10], rawMessage[11], rawMessage[12] }, 0);                        byte[] abc = IntToBytes(DataValue);                        ParseReceiveData(_currentCommandNumber, DataValue);                    }                    else                    {                        string ReadData = Encoding.ASCII.GetString(rawMessage, 9, Convert.ToInt32(rawMessage[8]));                        ParseReceiveData(_currentCommandNumber, 0, ReadData);                    }                }                else if (rawMessage[7] == _write)                {                    int CommandNumber = BitConverter.ToInt32(new byte[] { rawMessage[9], rawMessage[8], 0x00, 0x00 }, 0);                    int DataValue = BytesToInt(new byte[] { rawMessage[10], rawMessage[11], rawMessage[12], rawMessage[13] }, 0);                    ParseReceiveData(CommandNumber, DataValue);                }                else if (rawMessage[7] == _readInvalid)                {                    int DataValue = BitConverter.ToInt32(new byte[] { rawMessage[8], 0x00, 0x00, 0x00 }, 0);                    LOG.Write(eEvent.ERR_RF, Module, $"{Module} [{Display} Read] invalid request, Command Number is {_currentCommandNumber.ToString()}, Exception Code is 0x{DataValue.ToString("X")}");                }                else if (rawMessage[7] == _writeInvalid)                {                    int DataValue = BitConverter.ToInt32(new byte[] { rawMessage[8], 0x00, 0x00, 0x00 }, 0);                    LOG.Write(eEvent.ERR_RF, Module, $"{Module} [{Display} Write] invalid request, Command Number is {_currentCommandNumber.ToString()}, Exception Code is 0x{DataValue.ToString("X")}");                }                else                {                    LOG.Write(eEvent.ERR_RF, Module, $"RF invalid function code");                }            }            //catch (ExcuteFailedException e)            //{            //    EV.PostMessage("RF", EventEnum.DefaultWarning, string.Format("executed failed. {0}", e.Message));            //    OnError();            //    _exceuteErr = false;            //}            //catch (InvalidPackageException e)            //{            //    EV.PostMessage("RF", EventEnum.DefaultWarning, string.Format("receive invalid package. {0}", e.Message));            //    OnError();            //}            catch (System.Exception ex)            {                _commErr = true;                LOG.WriteExeption("RF failed:" , ex);            }        }        private void ParseReceiveData(int cometCommand, int value, string sValue = "")        {            switch (cometCommand)            {                case 8000:                    switch (value)                    {                        case 0:                            LOG.Write(eEvent.ERR_RF, Module, $"{Module} [{Display} Read] Device is not ready");                            break;                        case 1:                            //LOG.Info($"{Module} [{Display} Read] Device is ready, RF is off");                            Status = GeneratorStatus.OFF;                            break;                        case 2:                            //LOG.Info($"{Module} [{Display} Read] Device is active, RF is on");                            Status = GeneratorStatus.ON;                            break;                        case 3:                            //LOG.Info($"{Module} [{Display} Read] Device is in error state");                            Status = GeneratorStatus.ERROR;                            break;                        case 4:                            //LOG.Info($"{Module} [{Display} Read] Device is in calibration state");                            break;                        case 5:                            //LOG.Info($"{Module} [{Display} Read] Device is waiting for firmware update");                            break;                        case 6:                            //LOG.Info($"{Module} [{Display} Read] Device is blocked for configuration update");                            break;                        default:                            break;                    }                    break;                case 8021:                    //LOG.Info($"{Module} [{Display} Read] RF Forward power is {value / 1000} W");                    ForwardPower = value / 1000;                    break;                case 8022:                    //LOG.Info($"{Module} [{Display} Read] RF Reflected power is {value / 1000} W");                    ReflectPower = value / 1000;                    break;                case 8100:                    //LOG.Info($"{Module} [{Display} Read] RF Number of Errors is {value}");                    break;                case 8101:                    //LOG.Info($"{Module} [{Display} Read] RF Error 1 is {sValue}");                    break;                case 8102:                    //LOG.Info($"{Module} [{Display} Read] RF Error 1 state is {value}");                    break;                case 8103:                    //LOG.Info($"{Module} [{Display} Read] RF Error 2 is {sValue}");                    break;                case 8104:                    //LOG.Info($"{Module} [{Display} Read] RF Error 2 state is {value}");                    break;                case 8105:                    //LOG.Info($"{Module} [{Display} Read] RF Error 3 is {sValue}");                    break;                case 8106:                    //LOG.Info($"{Module} [{Display} Read] RF Error 3 state is {value}");                    break;                case 8107:                    //LOG.Info($"{Module} [{Display} Read] RF Error 4 is {sValue}");                    break;                case 8108:                    //LOG.Info($"{Module} [{Display} Read] RF Error 4 state is {value}");                    break;                case 8109:                    //LOG.Info($"{Module} [{Display} Read] RF Error 5 is {sValue}");                    break;                case 8110:                    //LOG.Info($"{Module} [{Display} Read] RF Error 5 state is {value}");                    break;                case 8111:                    //LOG.Info($"{Module} [{Display} Read] RF Error 6 is {sValue}");                    break;                case 8112:                    //LOG.Info($"{Module} [{Display} Read] RF Error 6 state is {value}");                    break;                case 8113:                    //LOG.Info($"{Module} [{Display} Read] RF Error 7 is {sValue}");                    break;                case 8114:                    //LOG.Info($"{Module} [{Display} Read] RF Error 7 state is {value}");                    break;                case 8115:                    //LOG.Info($"{Module} [{Display} Read] RF Error 8 is {sValue}");                    break;                case 8116:                    //LOG.Info($"{Module} [{Display} Read] RF Error 8 state is {value}");                    break;                case 8150:                    //LOG.Info($"{Module} [{Display} Read] RF Number of warnings is {value}");                    break;                case 8151:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 1 is {sValue}");                    break;                case 8152:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 2 is {sValue}");                    break;                case 8153:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 3 is {sValue}");                    break;                case 8154:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 4 is {sValue}");                    break;                case 8155:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 5 is {sValue}");                    break;                case 8156:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 6 is {sValue}");                    break;                case 8157:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 7 is {sValue}");                    break;                case 8158:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 8 is {sValue}");                    break;                case 8159:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 9 is {sValue}");                    break;                case 8160:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 10 is {sValue}");                    break;                case 8161:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 11 is {sValue}");                    break;                case 8162:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 12 is {sValue}");                    break;                case 8163:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 13 is {sValue}");                    break;                case 8164:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 14 is {sValue}");                    break;                case 8165:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 15 is {sValue}");                    break;                case 8166:                    //LOG.Info($"{Module} [{Display} Read] RF Warning 16 is {sValue}");                    break;                case 9201:                    switch (value)                    {                        case 0:                            //LOG.Info($"{Module} [BiasMatch Read] No connected");                            StatusMatch = GeneratorStatus.OFF;                            break;                        case 1:                            //LOG.Info($"{Module} [BiasMatch Read] Manual matching mode");                            StatusMatch = GeneratorStatus.ON;                            break;                        case 2:                            //LOG.Info($"{Module} [BiasMatch Read] Automatic matching mode");                            StatusMatch = GeneratorStatus.ON;                            break;                        case 11:                            //LOG.Info($"{Module} [BiasMatch Read] Manual matching mode (remote)");                            StatusMatch = GeneratorStatus.ON;                            break;                        case 12:                            //LOG.Info($"{Module} [BiasMatch Read] Automatic matching mode (remote)");                            StatusMatch = GeneratorStatus.ON;                            break;                        case 21:                            //LOG.Info($"{Module} [BiasMatch Read] Error matching mode");                            StatusMatch = GeneratorStatus.ERROR;                            break;                        default:                            break;                    }                    break;                case 9202:                    switch (value)                    {                        case 0:                            //LOG.Info($"{Module} [BiasMatch Read] holding position");                            break;                        case 1:                            //LOG.Info($"{Module} [BiasMatch Read] moving");                            break;                        default:                            break;                    }                    break;                case 9203:                    //LOG.Info($"{Module} [BiasMatch Read] C load position is {value} %");                    CLoad = value / 10f;                    break;                case 9204:                    //LOG.Info($"{Module} [BiasMatch Read] C tune position is {value} %");                    CTune = value / 10f;                    break;                case 9205:                    //LOG.Info($"{Module} [BiasMatch Read] C load is {value} pF");                    break;                case 9206:                    //LOG.Info($"{Module} [BiasMatch Read] C tune is {value} pF");                    break;                case 9210:                    //LOG.Info($"{Module} [BiasMatch Read] C load ref pos is {value} %");                    break;                case 9212:                    //LOG.Info($"{Module} [BiasMatch Read] C tune ref pos {value} %");                    break;                case 9251:                    //LOG.Info($"{Module} [BiasMatch Read] Process control Matching {value} V");                    VPP = value / 1000;                    break;                case 1001:                    switch (value)                    {                        case 0:                            //LOG.Info($"{Module} [{Display} Write] Switch off RF");                            break;                        case 1:                            //LOG.Info($"{Module} [{Display} Write] Switch on RF");                            break;                        case 9:                            //LOG.Info($"{Module} [{Display} Write] RF Reset errors");                            break;                        default:                            break;                    }                    break;                case 1201:                    switch (value)                    {                        case 0:                            //LOG.Info($"{Module} [{Display} Write] RF Control mode is Forward power");                            break;                        case 1:                            //LOG.Info($"{Module} [{Display} Write] RF Control mode is Load power");                            break;                        case 2:                            //LOG.Info($"{Module} [{Display} Write] RF Control mode is Process control");                            break;                        default:                            break;                    }                    break;                case 1206:                    //LOG.Info($"{Module} [{Display} Write] RF Power Set point is {value / 1000} W");                    PowerSetPoint = (_scEnableCalibration.BoolValue ? value : CalibrationData(value, false)) / 1000;                    break;                case 8201:                    switch (value)                    {                        case 1:                            //LOG.Info($"{Module} [BiasMatch Write] Manual matching mode");                            break;                        case 2:                            //LOG.Info($"{Module} [BiasMatch Write] Automatic matching mode");                            break;                        default:                            break;                    }                    break;                case 8202:                    switch (value)                    {                        case 0:                            //LOG.Info($"{Module} [BiasMatch Write] BiasMatch is Automatic hold mode");                            MatchMode = MatchingAutoMode.Hold;                            break;                        case 1:                            //LOG.Info($"{Module} [BiasMatch Write] BiasMatch is Automatic preset mode");                            MatchMode = MatchingAutoMode.Preset;                            break;                        default:                            break;                    }                    break;                case 8203:                    //LOG.Info($"{Module} [{Display} Write] Set C load ref position is {value / 10} %");                    CLoadSet = value / 10f;                    break;                case 8204:                    //LOG.Info($"{Module} [{Display} Write] Set C tune ref position is {value / 10} %");                    CTuneSet = value / 10f;                    break;                default:                    break;            }        }        public override void Monitor()        {            // power on triggered            _rfOnTrigger.CLK = PowerSetPoint > 0 && _isPowerOn;            if (_rfOnTrigger.R)            {                _total = TotalDays;                _fromLast = DaysFromLastPM;                _timerTotal.Start(0);                _timerFromLast.Start(0);                _powerOnStartTime = DateTime.Now;                _checkerPower.Reset(_scPowerAlarmTime.DoubleValue);                _checkerReflectPower.Reset(_scReflectPowerAlarmTime.DoubleValue);            }            if (_rfOnTrigger.M)            {                TotalDays = _total + _timerTotal.GetElapseTime() / 1000 / 60 / 60;                DaysFromLastPM = _fromLast + _timerFromLast.GetElapseTime() / 1000 / 60 / 60;                _checkerPower.Monitor(ForwardPower, PowerSetPoint - _scPowerAlarmRange.DoubleValue, PowerSetPoint + _scPowerAlarmRange.DoubleValue, _scPowerAlarmTime.DoubleValue);                if (_checkerPower.Trig)                {                    LOG.Write(eEvent.ERR_RF, Module,                        $"{Display} Forward power {ForwardPower:0} out of range[{PowerSetPoint - _scPowerAlarmRange.DoubleValue:0},{PowerSetPoint + _scPowerAlarmRange.DoubleValue:0}] in {_scPowerAlarmTime.DoubleValue:0} seconds");                    SetPowerOnOff(false, out _);                }                _checkerReflectPower.Monitor(ReflectPower, double.MinValue, _scReflectPowerAlarmRange.DoubleValue, _scReflectPowerAlarmTime.DoubleValue);                if (_checkerReflectPower.Trig)                {                    LOG.Write(eEvent.ERR_RF, Module,                        $"{Display} Reflect power {ReflectPower:0} out of range[0,{_scReflectPowerAlarmRange.DoubleValue:0}] in {_scReflectPowerAlarmTime.DoubleValue:0} seconds");                    SetPowerOnOff(false, out _);                }            }            if (PMIntervalDays > 0)            {                _trigPMNeeded.CLK = IsPMNeeded;                if (_trigPMNeeded.Q)                {                    if (EnableAlarm)                    {                        LOG.Write(eEvent.ERR_RF, Module, "rf on time value larger than setting interval days");                    }                }            }            if(_rfOnTrigger.T)                StatsDataManager.Instance.Increase($"{Module}.BiasRfOnTime", $"{Module} RfOnTime", DaysFromLastPM, TotalDays);            if (!_rfOnTrigger.CLK)            {                ForwardPower = 0;                ReflectPower = 0;            }            base.Monitor();        }        public override void Terminate()        {            _socket?.Dispose();        }        public override void SetPower(float val)        {            var power = !_scEnableCalibration.BoolValue ? val : CalibrationData(val, true);            SendCmd(Mode.Write, CometRFCommand.PowerSetPoint, (int)power * 1000);        }        public override bool SetPowerOnOff(bool on, out string str)        {            str = "";            var _chamber = DEVICE.GetDevice<JetPMBase>(Module);            if (on && !_chamber.CheckGeneratorAndHVInterlock(VenusDevice.Rf))            {                return false;            }            _isPowerOn = on;            SendCmd(Mode.Write, CometRFCommand.Command, on ? 1 : 0);            return true;        }        public override bool SetMatchingAutoMode(bool on, out string str)        {            str = "";            SendCmd(Mode.Write, CometRFCommand.MatchingAutoMode, on ? 1 : 0);            return true;        }        public override bool SetMatchPosition(double c1, double c2, out string reason)        {            reason = string.Empty;            if (c1 <= 100 && c1 >= 0)            {                double c1FilterValue = c1;                SendCmd(Mode.Write, CometRFCommand.CLoadRefPosition, (int)(c1 * 10));                reason = string.Format("Match position C1 set to {0} ", c1FilterValue);            }            if (c2 <= 100 && c2 >= 0)            {                double c2FilterValue = c2;                SendCmd(Mode.Write, CometRFCommand.CTuneRefPosition, (int)(c2 * 10));                reason += string.Format("Match position C2 set to {0}", c2FilterValue);            }            return true;        }        public override void SetPulseMode(bool on)        {            SendCmd(Mode.Write, CometRFCommand.TurnPulseMode, on ? 2 : 0);        }        public override void SetPulseRateFreq(int nFreq)        {            if(nFreq > 0)            {                int nPeriod = 10000000 / nFreq;                SendCmd(Mode.Write, CometRFCommand.PulsePeriod, nPeriod);            }            else            {                LOG.Write(eEvent.ERR_RF, Module, $"{Name},SetPulseRateFreq() parameter error: {nFreq}");            }                    }        public override void SetPulseDutyCycle(int percentage)        {            if(percentage >= 10 && percentage <= 90)            {                SendCmd(Mode.Write, CometRFCommand.PulseDutyCycle, percentage * 10);            }            else            {                LOG.Write(eEvent.ERR_RF, Module, $"{Name},SetPulseDutyCycle() parameter error: {percentage}");            }        }        private bool SendCmd(Mode mode, int command, int argument)        {            if (command == CometRFCommand.Command && argument == 0)            {                LOG.Write(eEvent.EV_DEVICE_INFO, Module, $"Bias Generator send RF off");            }            else if (command == CometRFCommand.Command && argument == 1)            {                LOG.Write(eEvent.EV_DEVICE_INFO, Module, $"Bias Generator send RF on");            }            if (command == CometRFCommand.PowerSetPoint)            {                LOG.Write(eEvent.EV_DEVICE_INFO, Module, $"Bias Generator send [{argument / 1000}W]");            }            _currentCommandNumber = command;            _sendData = BuildMessage(mode, command, argument);            _socket?.Write(_sendData);            Thread.Sleep(100);            return true;        }        protected byte[] BuildMessage(Mode mode, int commandNumber, int argumentNumber)        {            List<byte> buffer = new List<byte>();            TransactionNumber++;            if (TransactionNumber > 65535) TransactionNumber = 0;            buffer.Add(BitConverter.GetBytes(TransactionNumber)[1]);            buffer.Add(BitConverter.GetBytes(TransactionNumber)[0]);            buffer.Add(ProtocolIdentifierHighByte);            buffer.Add(ProtocolIdentifierLowByte);            if (mode == Mode.Read)            {                buffer.Add(0x00);                buffer.Add(0x06);            }            else if (mode == Mode.Write)            {                buffer.Add(0x00);                buffer.Add(0x08);            }            buffer.Add(_address);            if (mode == Mode.Read)            {                buffer.Add(_read);            }            else if (mode == Mode.Write)            {                buffer.Add(_write);            }            buffer.Add(BitConverter.GetBytes(commandNumber)[1]);            buffer.Add(BitConverter.GetBytes(commandNumber)[0]);            if (mode == Mode.Read)            {                buffer.Add(0x00);                buffer.Add(0x01);            }            else if (mode == Mode.Write)            {                buffer.Add(BitConverter.GetBytes(argumentNumber)[3]);                buffer.Add(BitConverter.GetBytes(argumentNumber)[2]);                buffer.Add(BitConverter.GetBytes(argumentNumber)[1]);                buffer.Add(BitConverter.GetBytes(argumentNumber)[0]);            }            //byte checkSum = 0;            //for (int i = 0; i < buffer.Count; i++)            //{            //    checkSum += buffer[i];            //}            //buffer.Add(checkSum);            return buffer.ToArray();        }        public int BytesToInt(byte[] src, int offset)        {            int value;            value = (int)((src[offset + 3] & 0xFF)                    | ((src[offset + 2] & 0xFF) << 8)                    | ((src[offset + 1] & 0xFF) << 16)                    | ((src[offset] & 0xFF) << 24));            return value;        }        public byte[] IntToBytes(int value)        {            byte[] src = new byte[4];            src[0] = (byte)((value >> 24) & 0xFF);            src[1] = (byte)((value >> 16) & 0xFF);            src[2] = (byte)((value >> 8) & 0xFF);            src[3] = (byte)(value & 0xFF);            return src;        }        public override void Reset()        {            _rfOnTrigger.RST = true;            _ErrTrigger.RST = true;            _trigPMNeeded.RST = true;            SendCmd(Mode.Write, CometRFCommand.Command, 9);            Status = GeneratorStatus.OFF;            StatusMatch = GeneratorStatus.OFF;            _exceuteErr = false;            if (_commErr)            {                Connect();            }        }        ~CometRF()        {            _socket?.Dispose();        }    }}
 |