123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987 |
- using System;
- using System.Collections;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- using Aitex.Core.Common.DeviceData;
- using Aitex.Core.RT.DataCenter;
- using Aitex.Core.RT.Device;
- 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 MECF.Framework.Common.Communications;
- using MECF.Framework.Common.DataCenter;
- using MECF.Framework.Common.Device.Bases;
- using MECF.Framework.Common.Equipment;
- namespace JetVirgoPM.Devices
- {
- static class MicrowareRFCommand
- {
- public const ushort PowerOnOrOff = 0x0080; //1:开 0:关 RW
- public const ushort RFPowerOnOrOff = 0x0081; //1:开 0:关 RW
- public const ushort PowerSetPoint = 0x0082; //功率设定值(W) RW
- public const ushort State = 0x008C; //设备故障 R
- public const ushort Reset = 0x009F; //清除异常 RW
- public const ushort Warning = 0x00A0; //整机预警 R
- public const ushort ForwardPower = 0x00A1; //整机输出功率 R
- public const ushort ReflectedPower = 0x00B2; //整机反射功率 R
- }
- class MicrowareRF : RfPowerBase
- {
- // ----------------------------Fields--------------------------
- //
- private int Write_INTERVAL = 400;
- private readonly DeviceTimer _timerWriteStatus = new DeviceTimer();
- private int QUERY_INTERVAL = 5000;
- private double _total;
- private double _fromLast;
- private bool _bRFPowerOn = false;
- private readonly AsyncSerialPort _serial;
- private readonly DeviceTimer _timerQueryStatus = new DeviceTimer();
- private readonly DeviceTimer _timerTotal = new DeviceTimer();
- private readonly DeviceTimer _timerFromLast = new DeviceTimer();
- private readonly DeviceTimer _timerRFTurnOn = new DeviceTimer();
- private DateTime _powerOnStartTime;
- private TimeSpan _powerOnElapsedTime;
- 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 ToleranceChecker _alarmChecker;
- private ToleranceChecker _warningChecker;
- private ToleranceChecker _checkerReflectPower;
- private readonly double _scPowerAlarmTime;
- private readonly double _scPowerAlarmRange;
- private readonly double _scPowerWarningTime;
- private readonly double _scPowerWarningRange;
- private readonly double _scReflectPowerAlarmTime;
- private readonly double _scReflectPowerAlarmRange;
- private readonly double _scPowerRange;
- private readonly DIAccessor _diIntlk;
- private StatsDataItemRFAndPump _statRFOnTime;
- private ushort _currentCommandNumber = 0;
- private byte[] _sendData;
- private Queue<ushort> _readCommand;
- private GeneratorStatus PreStatus { get; set; }
- private ushort _setPowerFlag { get; set; }
- private ushort _stateErrorFlag { get; set; }
- private ushort _warningErrorFlag { get; set; }
- // --------------------------Properties------------------------
- //
- protected float _recipeAlarmRange;
- protected float _recipeWarningRange;
- protected int _recipeIgnoreTimeMS;
- protected ToleranceChecker _recipeAlarmChecker = new ToleranceChecker();
- protected ToleranceChecker _recipeWarningChecker = new ToleranceChecker();
- protected DeviceTimer _recipeIgnoreTimer = new DeviceTimer();
- public bool ConnectedStatus { get; set; }
- public override float ScalePower => (float)_scPowerRange;
- public GeneratorStatus Status { get; private 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;
- }
- }
- public override bool IsPowerOn
- {
- get => Status == GeneratorStatus.ON;
- set { }
- }
- public override bool IsError
- {
- get => Status == GeneratorStatus.ERROR;
- set { }
- }
- [Subscription("PowerOnTime")]
- public string PowerOnTime
- {
- get
- {
- if (_bRFPowerOn)
- _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,
- MatchPositionC1 = CLoad,
- MatchPositionC2 = CTune,
- IsRfOn = IsPowerOn,
- PowerSetPoint = PowerSetPoint,
- PowerOnElapsedTime = PowerOnTime,
- IsInterlockOk = RFInterlock,
- WorkMode = (int)RfMode.ContinuousWaveMode,
- DisplayName = "Microware RF",
- };
- // --------------------------Constructor-----------------------
- //
- public MicrowareRF(ModuleName mod, string name) : base(mod.ToString(), name)
- {
- var portNum = SC.GetStringValue($"{mod}.{name}.Port");
- this.Status = GeneratorStatus.Unknown;
- this.PreStatus = this.Status;
- this._stateErrorFlag = 0;
- this._warningErrorFlag = 0;
- _serial = new AsyncSerialPort(portNum, 9600, 8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One, "\r\r", false);
- _scPowerAlarmTime = SC.GetValue<double>($"{Module}.{Name}.PowerAlarmTime");
- _scPowerAlarmRange = SC.GetValue<double>($"{Module}.{Name}.PowerAlarmRange");
- _scPowerWarningTime = SC.GetValue<double>($"{Module}.{Name}.PowerWarningTime");
- _scPowerWarningRange = SC.GetValue<double>($"{Module}.{Name}.PowerWarningRange");
- _scReflectPowerAlarmTime = SC.GetValue<double>($"{Module}.{Name}.ReflectPowerAlarmTime");
- _scReflectPowerAlarmRange = SC.GetValue<double>($"{Module}.{Name}.ReflectPowerAlarmRange");
- _scPowerRange = SC.GetValue<double>($"{Module}.{Name}.PowerRange");
- _scEnableCalibration = SC.GetConfigItem($"{Module}.{Name}.EnableCalibration");
- _scCalibrationTable = SC.GetConfigItem($"{Module}.{Name}.CalibrationTable");
- _scRFPhysicalMaxPower = SC.GetConfigItem($"{Module}.{Name}.RFPhysicalMaxPower");
- _scCurrentRFMaxPower = SC.GetConfigItem($"{Module}.{Name}.CurrentRFMaxPower");
- _serial.EnableLog = SC.GetValue<bool>($"{Module}.{Name}.EnableLog");
- _diIntlk = IO.DI[$"{Module}.DI_Generator_Hardware_Interlock"];
- }
- ~MicrowareRF()
- {
- _serial?.Close();
- }
- private void InitReadQueue()
- {
- _readCommand = new Queue<ushort>();
- _readCommand.Enqueue(MicrowareRFCommand.RFPowerOnOrOff);
- _readCommand.Enqueue(MicrowareRFCommand.PowerSetPoint);
- _readCommand.Enqueue(MicrowareRFCommand.State);
- _readCommand.Enqueue(MicrowareRFCommand.Reset);
- _readCommand.Enqueue(MicrowareRFCommand.Warning);
- _readCommand.Enqueue(MicrowareRFCommand.ForwardPower);
- _readCommand.Enqueue(MicrowareRFCommand.ReflectedPower);
- }
- public override bool Initialize()
- {
- base.Initialize();
- DATA.Subscribe($"{Module}.{Name}.DeviceData", () => DeviceData);
- 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}.SetRecipeTolerance", (out string reason, int time, object[] param) =>
- {
- reason = string.Empty;
- _recipeIgnoreTimeMS = Convert.ToInt32(param[0]) * 1000;
- _recipeWarningRange = Convert.ToSingle(param[1]);
- _recipeAlarmRange = Convert.ToSingle(param[2]);
- _recipeAlarmChecker.RST = true;
- _recipeWarningChecker.RST = true;
- if (_recipeIgnoreTimeMS > 0)
- _recipeIgnoreTimer.Start(0);
- return true;
- });
- if (_serial.Open())
- {
- this.ConnectedStatus = true;
- _serial.OnBinaryDataChanged += SerialPortDataReceived;
- _serial.OnErrorHappened += SerialPortErrorOccurred;
- _setPowerFlag = 1;
- SendCmd(Mode.Write, MicrowareRFCommand.PowerOnOrOff, 1);
- InitReadQueue();
- }
- else
- {
- this.ConnectedStatus = false;
- EV.PostAlarmLog(this.Module, "Microware 射频发生器串口无法打开");
- return false;
- }
- _statRFOnTime = StatsDataManager.Instance.GetItemRFAndPump($"{Module}.{Name}.RfOnTime");
- _timerQueryStatus.Start(QUERY_INTERVAL);
- _alarmChecker = new ToleranceChecker(_scPowerAlarmTime);
- _warningChecker = new ToleranceChecker(_scPowerWarningTime);
- _checkerReflectPower = new ToleranceChecker(_scReflectPowerAlarmTime);
- _recipeAlarmChecker = new ToleranceChecker(0);
- _recipeWarningChecker = new ToleranceChecker(0);
- _timerWriteStatus.Start(Write_INTERVAL);
- //SetCommunicationMode(1);
- return true;
- }
- public override void Monitor()
- {
- if(_timerWriteStatus.IsTimeout())
- {
- this.WriteCommand();
- _timerWriteStatus.Start(Write_INTERVAL);
- }
- // 状态查询
- if (_timerQueryStatus.IsTimeout())
- {
- this.QueryCommand();
- _timerQueryStatus.Start(QUERY_INTERVAL);
- }
- // power on triggered
- _rfOnTrigger.CLK = IsPowerOn;
- if (_rfOnTrigger.R)
- {
- _total = TotalDays;
- _fromLast = DaysFromLastPM;
- _timerTotal.Start(0);
- _timerFromLast.Start(0);
- _alarmChecker.Reset(_scPowerAlarmTime);
- _warningChecker.Reset(_scPowerWarningTime);
- _checkerReflectPower.Reset(_scReflectPowerAlarmTime);
- }
- if (_rfOnTrigger.M)
- {
- TotalDays = _total + _timerTotal.GetElapseTime() / 1000 / 60 / 60;
- DaysFromLastPM = _fromLast + _timerFromLast.GetElapseTime() / 1000 / 60 / 60;
- //_checkerPower.Monitor(ForwardPower, PowerSetPoint - _scPowerAlarmRange, PowerSetPoint + _scPowerAlarmRange, _scPowerAlarmTime);
- //if (_checkerPower.Trig)
- //{
- // EV.PostAlarmLog($"{Module}",
- // $"{Display} Forward power {ForwardPower:0} out of range[{PowerSetPoint - _scPowerAlarmRange:0},{PowerSetPoint + _scPowerAlarmRange:0}] in {_scPowerAlarmTime:0} seconds");
- // SetPowerOnOff(false, out _);
- //}
- if (_recipeAlarmRange > 0 && _recipeAlarmRange / 100.0 * PowerSetPoint < _scPowerAlarmRange)
- {
- if (_recipeIgnoreTimer.GetElapseTime() > _recipeIgnoreTimeMS)
- {
- _recipeAlarmChecker.Monitor(ForwardPower, PowerSetPoint - Math.Abs(_recipeAlarmRange / 100.0 * PowerSetPoint), PowerSetPoint + Math.Abs(_recipeAlarmRange / 100.0 * PowerSetPoint), _scPowerAlarmTime);
- if (_recipeAlarmChecker.Trig)
- {
- EV.PostAlarmLog(Module, Display + $" Microware ForwardPower={ForwardPower }, PowerSetPoint ={PowerSetPoint} out of tolerance({PowerSetPoint - Math.Abs(_recipeAlarmRange / 100.0 * PowerSetPoint)},{PowerSetPoint + Math.Abs(_recipeAlarmRange / 100.0 * PowerSetPoint)}) in {_scPowerAlarmTime:0} seconds");
- SetPowerOnOff(false, out _);
- }
- }
- }
- else
- {
- _alarmChecker.Monitor(ForwardPower, PowerSetPoint - Math.Abs(_scPowerAlarmRange), PowerSetPoint + Math.Abs(_scPowerAlarmRange), _scPowerAlarmTime);
- if (_alarmChecker.Trig)
- {
- EV.PostAlarmLog(Module, Display + $" Microware ForwardPower={ForwardPower}, PowerSetPoint={PowerSetPoint} out of tolerance({ PowerSetPoint - Math.Abs(_scPowerAlarmRange)},{PowerSetPoint + Math.Abs(_scPowerAlarmRange)}) in {_scPowerAlarmTime:0} seconds");
- }
- }
- if (_recipeWarningRange > 0 && _recipeWarningRange / 100.0 * PowerSetPoint < _scPowerWarningRange)
- {
- if (_recipeIgnoreTimer.GetElapseTime() > _recipeIgnoreTimeMS)
- {
- _recipeWarningChecker.Monitor(ForwardPower, PowerSetPoint - Math.Abs(_recipeWarningRange / 100.0 * PowerSetPoint), PowerSetPoint + Math.Abs(_recipeWarningRange / 100.0 * PowerSetPoint), _scPowerWarningTime);
- if (_recipeWarningChecker.Trig)
- {
- EV.PostWarningLog(Module, Display + $" Microware ForwardPower={ForwardPower}, PowerSetPoint={PowerSetPoint} out of tolerance({PowerSetPoint - Math.Abs(_recipeWarningRange / 100.0 * PowerSetPoint)},{PowerSetPoint + Math.Abs(_recipeWarningRange / 100.0 * PowerSetPoint)}) in {_scPowerWarningTime:0} seconds");
- }
- }
- }
- else
- {
- _warningChecker.Monitor(ForwardPower, PowerSetPoint - Math.Abs(_scPowerWarningRange), PowerSetPoint + Math.Abs(_scPowerWarningRange), _scPowerWarningTime);
- if (_warningChecker.Trig)
- {
- EV.PostWarningLog(Module, Display + $" Microware Pressure={ForwardPower}, PowerSetPoint={PowerSetPoint} out of tolerance({PowerSetPoint - Math.Abs(_scPowerWarningRange)},{PowerSetPoint + Math.Abs(_scPowerWarningRange)}) in {_scPowerWarningTime:0} seconds");
- }
- }
- _checkerReflectPower.Monitor(ReflectPower, double.MinValue, _scReflectPowerAlarmRange, _scReflectPowerAlarmTime);
- if (_checkerReflectPower.Trig)
- {
- EV.PostAlarmLog($"{Module}",
- $" Microware {Display} Reflect power {ReflectPower:0} out of range[0,{_scReflectPowerAlarmRange:0}] in {_scReflectPowerAlarmTime:0} seconds");
- SetPowerOnOff(false, out _);
- }
- }
- if (PMIntervalDays > 0)
- {
- _trigPMNeeded.CLK = IsPMNeeded;
- if (_trigPMNeeded.Q)
- {
- if (EnableAlarm)
- {
- EV.PostAlarmLog($"{Module}", $"Microware {Module} {Name} rf on time value larger than setting interval days");
- }
- }
- }
- if (_rfOnTrigger.T)
- StatsDataManager.Instance.Increase($"{Module}.{Name}.RfOnTime", $"{Module} {Name} RfOnTime", DaysFromLastPM, TotalDays);
- if (!_rfOnTrigger.CLK)
- {
- ForwardPower = 0;
- ReflectPower = 0;
- }
- // 通信 checking, 2 second 一次
- //if (_timerComm.IsTimeout() && !_bQueryComm)
- //{
- // this.SendCmd(AdTecRfMessage.CHK_COMM);
- // _bQueryComm = true;
- // _timerComm.Start(CHK_COMM_INTERVAL);
- //}
- // RF Turn On & Off Timeout Check
- _trigOnOff.CLK = _bRFPowerOn;
- if (_trigOnOff.R) //RF Turn On
- {
- _timerRFTurnOn.Start(SC.GetValue<int>($"{Module}.{Name}.RFTurnOnTimeout") * 1000);
- }
- if (_trigOnOff.M) //RF Stay On
- {
- if (_timerRFTurnOn.IsTimeout())
- {
- if (!IsPowerOn)
- {
- EV.PostAlarmLog($"{Module}", $"Microware {Module} {Name} Turn On Failed");
- _timerRFTurnOn.Stop();
- }
- }
- }
- if (_trigOnOff.T)
- {
- _timerRFTurnOn.Stop();
- }
- base.Monitor();
- }
- public override void Terminate()
- {
- _serial?.Close();
- }
- public override void Reset()
- {
- _rfOnTrigger.RST = true;
- _ErrTrigger.RST = true;
- _trigPMNeeded.RST = true;
- this.SetCommand(MicrowareRFCommand.Reset, 1);
- this.Status = GeneratorStatus.OFF;
- this.PreStatus = this.Status;
- this._stateErrorFlag = 0;
- this._warningErrorFlag = 0;
- _bRFPowerOn = false;
- }
- public void SetRfMode(RfMode mode)
- {
- throw new NotImplementedException();
- }
- public override float CLoad
- {
- get
- {
- string matchName = "";
- if (Name.StartsWith("Rf"))
- {
- matchName = Name.Replace("Rf", "match");
- }
- if (Name.StartsWith("BiasRf"))
- {
- matchName = Name + "Match";
- }
- if (SC.ContainsItem($"{Module}.{matchName}.EnableMatch") &&
- SC.GetValue<bool>($"{Module}.{matchName}.EnableMatch") &&
- SC.GetValue<int>($"{Module}.{matchName}.CommunicationType") == (int)CommunicationType.RS232 &&
- SC.GetValue<int>($"{Module}.{matchName}.MFG") == (int)MatchMFG.AdTec)
- {
- var match = DEVICE.GetDevice<AdTecMatch>($"{Module}.{matchName}");
- if (match != null)
- return match.TunePosition1;
- }
- return 0;
- }
- }
- public override float CTune
- {
- get
- {
- string matchName = "";
- if (Name.StartsWith("Rf"))
- {
- matchName = Name.Replace("Rf", "match");
- }
- if (Name.StartsWith("BiasRf"))
- {
- matchName = Name + "Match";
- }
- if (SC.ContainsItem($"{Module}.{matchName}.EnableMatch") &&
- SC.GetValue<bool>($"{Module}.{matchName}.EnableMatch") &&
- SC.GetValue<int>($"{Module}.{matchName}.CommunicationType") == (int)CommunicationType.RS232 &&
- SC.GetValue<int>($"{Module}.{matchName}.MFG") == (int)MatchMFG.AdTec)
- {
- var match = DEVICE.GetDevice<AdTecMatch>($"{Module}.{matchName}");
- if (match != null)
- return match.TunePosition2;
- }
- return 0;
- }
- }
- //public override void SetCommunicationMode(int mode)
- //{
- // CommunicationType t1 = (CommunicationType)mode;
- // switch (t1)
- // {
- // case CommunicationType.Analogue:
- // this.SendCmd(AdTecRfMessage.ANALOG);
- // break;
- // case CommunicationType.RS232:
- // this.SendCmd(AdTecRfMessage.RS232);
- // break;
- // default:
- // throw new ArgumentOutOfRangeException("Communication mode error");
- // }
- //}
- public override void SetPower(float val)
- {
- //if (!(this.ControlMode == EnumRfPowerControlMode.RS232Mode)) SetCommunicationMode(1);
- ushort a = !_scEnableCalibration.BoolValue ? (ushort)val : (ushort)CalibrationData(val, true);
- //if (SendCmd($"{a:D4}{AdTecRfMessage.SET_POWER}"))
- if(SetCommand(MicrowareRFCommand.PowerSetPoint, a))
- {
- PowerSetPoint = val;
- }
- }
- public override bool SetPowerOnOff(bool on, out string str)
- {
- if (!(this.ControlMode == EnumRfPowerControlMode.RS232Mode)) SetCommunicationMode(1);
- str = "";
- if (on)
- {
- SetCommand(MicrowareRFCommand.RFPowerOnOrOff, 1);
- _bRFPowerOn = true;
- _powerOnStartTime = DateTime.Now;
- QUERY_INTERVAL = 500;
- }
- else
- {
- SetCommand(MicrowareRFCommand.RFPowerOnOrOff, 0);
- _bRFPowerOn = false;
- ForwardPower = 0;
- ReflectPower = 0;
- QUERY_INTERVAL = 500;
- _ErrTrigger.RST = true;
- }
- _timerQueryStatus.Start(QUERY_INTERVAL);
- return true;
- }
- //----------------------------------Private Method-------------------------------
- //
- private void SerialPortDataReceived(byte[] receiveContent)
- {
- if (receiveContent == null || receiveContent.Length == 0)
- {
- EV.PostAlarmLog(Module, $"{Module} {Name} Microware 无数据反馈");
- return;
- }
- //string str2 = str.Trim('\r');
- //if (str2 == AdTecRfMessage.ERR_RES)
- //{
- // EV.PostWarningLog(Module, $"AdTEC 收到 [{str2}]");
- // return;
- //}
- //try
- //{
- // //LOG.Info($"{Module} Generator rec [{str2}]");
- // Match match1 = Regex.Match(str2, INFO_PATTERN);
- // if (!match1.Success)
- // {
- // LOG.Write($"{Module}, AdTec 数据格式错误");
- // return;
- // }
- // string[] str1 =
- // {
- // match1.Groups[1].Value,
- // match1.Groups[2].Value,
- // match1.Groups[3].Value,
- // match1.Groups[4].Value,
- // match1.Groups[5].Value
- // };
- // this.ParseQueryData(str1);
- try
- {
- var addr = receiveContent[0];
- var functionCode = receiveContent[1];
- if(functionCode == 0x03)
- {
- _readTimeOut.TryRemove(_currentCommandNumber, out DateTime _);
- var len = receiveContent[2];
- var dh = receiveContent[3];
- var dl = receiveContent[4];
- ushort data = BitConverter.ToUInt16(new byte[] { dl, dh }, 0 );
- ParseData(data, _currentCommandNumber);
- }
- else if(functionCode == 0x06)
- {
- var ah = receiveContent[2];
- var al = receiveContent[3];
- ushort address = BitConverter.ToUInt16(new byte[] { al,ah }, 0);
- var dh = receiveContent[4];
- var dl = receiveContent[5];
- ushort data = BitConverter.ToUInt16(new byte[] { dl, dh }, 0);
- ParseData(data, address);
- }
- }
- catch (Exception ex)
- {
- LOG.Write(ex);
- }
- }
- private void ParseData(ushort data, ushort cmd)
- {
- //_readCommand.Enqueue(MicrowareRFCommand.PowerOnOrOff);
- //_readCommand.Enqueue(MicrowareRFCommand.PowerSetPoint);
- //_readCommand.Enqueue(MicrowareRFCommand.State);
- //_readCommand.Enqueue(MicrowareRFCommand.Reset);
- //_readCommand.Enqueue(MicrowareRFCommand.Warning);
- //_readCommand.Enqueue(MicrowareRFCommand.ForwardPower);
- //_readCommand.Enqueue(MicrowareRFCommand.ReflectedPower);
- switch (cmd)
- {
- case MicrowareRFCommand.RFPowerOnOrOff:
- {
- if (PreStatus != Status) LOG.Info($"{Module} {Name} Microware Source Generator status change, data=[{data}]");
- Status = data == 1 ? GeneratorStatus.ON : data == 0 ? GeneratorStatus.OFF : GeneratorStatus.ERROR;
- PreStatus = Status;
- break;
- }
- case MicrowareRFCommand.PowerSetPoint:
- {
- break;
- }
- case MicrowareRFCommand.State:
- {
- if(data != 0 && _stateErrorFlag != data)
- {
- EV.PostAlarmLog(Module, $"{Module} {Name} Microware Source Generator error code [{data}] ");
- _stateErrorFlag = data;
- }
- break;
- }
- case MicrowareRFCommand.Reset:
- {
- break;
- }
- case MicrowareRFCommand.Warning:
- {
- if (data != 0 && _warningErrorFlag != data)
- {
- EV.PostWarningLog(Module, $"{Module} {Name} Microware Source Generator warning code " + data);
- _warningErrorFlag = data;
- }
- break;
- }
- case MicrowareRFCommand.ForwardPower:
- {
- this.ForwardPower = Convert.ToUInt64(data);
- break;
- }
- case MicrowareRFCommand.ReflectedPower:
- {
- this.ReflectPower = Convert.ToUInt64(data);
- break;
- }
- case MicrowareRFCommand.PowerOnOrOff:
- {
- if(_setPowerFlag != data)
- {
- EV.PostWarningLog(Module, $"{Module} {Name} Microware Source Generator power code " + data);
- _setPowerFlag = data;
- }
- break;
- }
- }
- }
- private void ParseQueryData(string[] strInfo)
- {
- //// Control mode
- //string s2 = strInfo[0].Substring(0, 1);
- //this.ControlMode = (EnumRfPowerControlMode)Convert.ToUInt16(s2);
- //// output mode
- //string s0 = strInfo[0].Substring(1, 1);
- //this.WorkMode = (EnumRfPowerWorkMode)Convert.ToUInt16(s0);
- //// ON/OFF
- //char s1 = strInfo[0][2];
- //if (s1 == '1')
- //{
- // Status = GeneratorStatus.ON;
- //}
- //else if (s1 == '0')
- //{
- // Status = GeneratorStatus.OFF;
- //}
- //// error code
- //string alarm = strInfo[0].Substring(5, 2);
- //byte errCode = Convert.ToByte(alarm);
- //_ErrTrigger.CLK = errCode > 0;
- //if (_ErrTrigger.Q)
- //{
- // string code = errCode == 1 ? "Ref Over" :
- // errCode == 2 ? "Ref Limit" :
- // errCode == 3 ? "Cur Over" :
- // errCode == 4 ? "Cur Limit" :
- // errCode == 5 ? "Temp Over" :
- // errCode == 6 ? "Temp Sensor Short" :
- // errCode == 7 ? "Temp Sensor Open" :
- // errCode == 8 ? "Sensor Error" :
- // errCode == 9 ? "Fwd Power Over" :
- // errCode == 10 ? "RF ON Timer" :
- // errCode == 11 ? "RS232C error" :
- // errCode == 12 ? "Amp Unbalance" :
- // errCode == 14 ? "Fan error" :
- // errCode == 15 ? "Coolant Error" :
- // errCode == 16 ? "Voltage Error" :
- // errCode == 17 ? "Fwd Power Down" :
- // errCode == 22 ? "PD Over" :
- // errCode == 23 ? "PD Limit" :
- // errCode == 26 ? "Dew Condensation" :
- // errCode == 29 ? "SW Failure" :
- // errCode == 99 ? "Safety Lock" : string.Empty;
- // if (!string.IsNullOrEmpty(code))
- // {
- // if (errCode == 99)
- // EV.PostInfoLog(Module, "Source Generator " + code);
- // else
- // EV.PostAlarmLog(Module, "Source Generator " + code);
- // }
- //}
- //// forward power
- //this.ForwardPower = Convert.ToUInt64(strInfo[2]);
- //// reflect power
- //this.ReflectPower = Convert.ToUInt64(strInfo[3]);
- }
- private void SerialPortErrorOccurred(string obj)
- {
- Status = GeneratorStatus.ERROR;
- this.PreStatus = this.Status;
- EV.PostAlarmLog(this.Module, $"{Module} {Name} Microware RF 串口出错, [{obj}]");
- }
- private ConcurrentDictionary<ushort, DateTime> _readTimeOut = new ConcurrentDictionary<ushort, DateTime>();
- private void QueryCommand()
- {
- if (!ConnectedStatus)
- return;
- if(_readTimeOut.Count == 0)
- {
- var readCommand = _readCommand.Dequeue();
- ReadCommand(readCommand, 0);
- _readCommand.Enqueue(readCommand);
- _currentCommandNumber = readCommand;
- _readTimeOut.TryAdd(_currentCommandNumber, DateTime.Now);
- }
- else
- {
- if(_readTimeOut.TryGetValue(_currentCommandNumber, out DateTime dateTime))
- {
- var ts = DateTime.Now - dateTime;
- if(ts.TotalSeconds < 1)
- {
- ReadCommand(_currentCommandNumber, 0);
- }
- else if(ts.TotalSeconds >= 2)
- {
- _readTimeOut.TryRemove(_currentCommandNumber, out DateTime dateTime2);
- LOG.Info($"{Module} {Name} Microware command address=[{_currentCommandNumber}] read timeout(2s), first send time = [{dateTime2}] ");
- }
- }
- }
- }
- //private ConcurrentDictionary<ushort, ushort> _writeCommand = new ConcurrentDictionary<ushort, ushort>();
- private ConcurrentQueue<RFHelper> _writeCommand = new ConcurrentQueue<RFHelper>();
- private void WriteCommand()
- {
- if(_writeCommand.Count > 0)
- {
- if(_writeCommand.TryDequeue(out RFHelper comandAndArgument))
- {
- var command = comandAndArgument.Command;
- var argument = comandAndArgument.Argument;
- if (command == MicrowareRFCommand.RFPowerOnOrOff && argument == 0)
- {
- EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send off");
- }
- else if (command == MicrowareRFCommand.RFPowerOnOrOff && argument == 1)
- {
- EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send on");
- }
- else if (command == MicrowareRFCommand.PowerSetPoint)
- {
- EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send [{argument}W]");
- }
- else if (command == MicrowareRFCommand.PowerOnOrOff)
- {
- EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send, {(argument == 0 ? "power off" : "power on")}");
- }
- if (_serial.Write(BuildMessage(Mode.Write, command, argument)))
- {
- LOG.Info($" {Module} {Name} Send command=[{command}] value=[{argument}] and remove comand from list. ");
- }
- }
- }
- }
- private bool SetCommand(ushort command, ushort argument)
- {
- return SendCmd(Mode.Write, command, argument);
- }
- private bool ReadCommand(ushort command, ushort argument)
- {
- return SendCmd(Mode.Read, command, argument);
- }
- private bool SendCmd(Mode mode, ushort command, ushort argument)
- {
- if(mode == Mode.Write)
- {
- _writeCommand.Enqueue(new RFHelper() {Command = command,Argument = argument });
- //if (_writeCommand.AddOrUpdate(command, argument, (item1, item2) => argument) != argument)
- //{
- // EV.PostAlarmLog(this.Module, $"Microware {Module} {Name} command={command} value={argument} add command list failed ");
- // return false;
- //}
- return true;
- //if (command == MicrowareRFCommand.RFPowerOnOrOff && argument == 0)
- //{
- // EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send off");
- //}
- //else if (command == MicrowareRFCommand.RFPowerOnOrOff && argument == 1)
- //{
- // EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send on");
- //}
- //else if (command == MicrowareRFCommand.PowerSetPoint)
- //{
- // EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send [{argument}W]");
- //}
- //else if(command == MicrowareRFCommand.PowerOnOrOff)
- //{
- // EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send, {(argument == 0 ? "power off" : "power on")}");
- //}
- }
- return _serial.Write(BuildMessage(mode, command, argument));
- }
- protected byte[] BuildMessage(Mode mode, ushort commandNumber, ushort argumentNumber, byte readCount = 0x01)
- {
- List<byte> buffer = new List<byte>();
- buffer.Add(0x0A); //机器识别码
- if (mode == Mode.Read)
- {
- buffer.Add(0x03);
- }
- else if (mode == Mode.Write)
- {
- buffer.Add(0x06);
- }
- buffer.Add(BitConverter.GetBytes(commandNumber)[1]);
- buffer.Add(BitConverter.GetBytes(commandNumber)[0]);//起始地址
-
- if (mode == Mode.Read)
- {
- buffer.Add(0x00);
- buffer.Add(readCount);//读寄存器个数
- }
- else if (mode == Mode.Write)
- {
- buffer.Add(BitConverter.GetBytes(argumentNumber)[1]);
- buffer.Add(BitConverter.GetBytes(argumentNumber)[0]);
- }
- buffer.AddRange(CRC16(buffer.ToArray()));
- return buffer.ToArray();
- }
- public static byte[] CRC16(byte[] data)
- {
- ushort crc = 0xFFFF;
- for (int i = 0; i < data.Length; i++)
- {
- crc = (ushort)(crc ^ (data[i]));
- for (int j = 0; j < 8; j++)
- {
- crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
- }
- }
- byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
- byte lo = (byte)(crc & 0x00FF); //低位置
- return new byte[] { hi, lo };
- }
- }
- public class RFHelper
- {
- public ushort Command { get; set; }
- public ushort Argument { get; set; }
- public DateTime SendTime { get; set; }
- }
- }
|