using System; using System.Diagnostics; using System.Collections.Generic; using System.Collections.Concurrent; using System.Text.RegularExpressions; using MECF.Framework.Common.Communications; using MECF.Framework.Common.Equipment; using Aitex.Core.RT.SCCore; using Aitex.Core.RT.Device; using Aitex.Core.RT.Log; using Venus_Core; using MECF.Framework.Common.Device.Bases; using System.Linq; using System.Net.Sockets; namespace Venus_RT.Devices { class AdixenTurboPump : PumpBase { public enum Operation { SetAddress, GetChecksum, GetFaultList, SetDatalogInterval, EnableDatalog, EnableEcho, DisableEcho, IdentifyDevice, IdentifyProduct, GetCurrentValues, SwitchSpeedToNormal, SwitchSpeedToStandbyValue, SetStandbySpeed, GetParametersState, GetIntervalParametersState, SetPumpWorkingTime, SetElectronicWorkingTime, SetStartDelay, SetTimeToVent, SetVentingTime, SetSpeedThreshold, SetControlTemperatrue, StopPumpThermostage, SetBearingThreshold, GetCurrentSpeed, StartPumpRotation, StopPump, SetVersions, SetAnalogOutput, SetTemperatureUnit, SetBuzzerOpt, SetCommandMode, SetBraking, Invalid, } private readonly Dictionary _noneParaCommandOp = new Dictionary { {Operation.EnableDatalog, "#{0:D3}DLR\r" }, {Operation.EnableEcho, "#{0:D3}ECHON\r" }, {Operation.DisableEcho, "#{0:D3}ECHOFF\r" }, {Operation.SwitchSpeedToNormal, "#{0:D3}NSP\r" }, {Operation.SwitchSpeedToStandbyValue, "#{0:D3}SBY\r" }, {Operation.StopPumpThermostage, "#{0:D3}SET31,30\r" }, {Operation.StartPumpRotation, "#{0:D3}TMPON\r" }, {Operation.StopPump, "#{0:D3}TMPOFF\r" }, }; private readonly Dictionary _readDataCommandOp = new Dictionary { {Operation.GetChecksum, "#{0:D3}CHKVS\r" }, {Operation.GetFaultList, "#{0:D3}DEF\r" }, {Operation.IdentifyDevice, "#{0:D3}IDN\r" }, {Operation.IdentifyProduct, "#{0:D3}IDP\r" }, {Operation.GetCurrentValues, "#{0:D3}LEV10\r" }, {Operation.GetParametersState, "#{0:D3}SEL10\r" }, {Operation.GetCurrentSpeed, "#{0:D3}SPD\r" }, {Operation.GetIntervalParametersState, "#{0:D3}STA\r" }, }; private readonly Dictionary _setDataCommandOp = new Dictionary { {Operation.SetAddress, "#{0:D3}ADR {1:D3}\r" }, {Operation.SetDatalogInterval, "#{0:D3}DLI {1:D3}\r" }, {Operation.SetStandbySpeed, "#{0:D3}RPM,{1:D4}\r" }, {Operation.SetPumpWorkingTime, "#{0:D3}SET10,{1:D5}\r" }, {Operation.SetElectronicWorkingTime, "#{0:D3}SET11,{1:D5}\r" }, {Operation.SetStartDelay, "#{0:D3}SET13,{1:D5}\r" }, {Operation.SetTimeToVent, "#{0:D3}SET14,{1:D5}\r" }, {Operation.SetVentingTime, "#{0:D3}SET15,{1:D4}\r" }, {Operation.SetSpeedThreshold, "#{0:D3}SET30,{1:D2}\r" }, {Operation.SetControlTemperatrue, "#{0:D3}SET31,{1:D2}\r" }, {Operation.SetBearingThreshold, "#{0:D3}SET32,{1:D3}\r" }, {Operation.SetAnalogOutput, "#{0:D3}OPT01,{1:D1}\r" }, {Operation.SetTemperatureUnit, "#{0:D3}OPT02,{1:D1}\r" }, {Operation.SetBuzzerOpt, "#{0:D3}OPT11,{1:D1}\r" }, {Operation.SetCommandMode, "#{0:D3}OPT14,{1:D1}\r" }, {Operation.SetBraking, "#{0:D3}OPT25,{1:D1}\r" }, }; private readonly Dictionary _comError = new Dictionary { {"Err0", "adjustment error(out of bounds)" }, {"Err1", "command error (syntax) " }, {"Err2", "parameter error (e.g. non hexadecimal character)" }, {"Err3", "context error" }, {"Err4", "checksum error" }, }; private readonly ushort PUMP_ON_FLAG = 0x02; private readonly ushort PUMP_ERROR_FLAG = 0x40; private readonly ushort ISO_VALVE_OPEN_FLAG = 0x01; private readonly ushort WATER_VALVE_OEPN_FLAG = 0x08; private readonly ushort VALVE_AT_SPEED_FLAG = 0x40; public override bool IsConnected { get { if (_serial.IsOpen() && System.IO.Ports.SerialPort.GetPortNames().Contains(_port.ToUpper())) { return true; } else { if (_serial.IsOpen()) { _serial.Close(); } return false; } } } public override bool IsRunning { get { return (_pumpStatus & PUMP_ON_FLAG) == PUMP_ON_FLAG; } } public override bool IsError { get { return (_pumpStatus & PUMP_ERROR_FLAG) == PUMP_ERROR_FLAG; } } public bool IsISOValveOpen { get { return (_valveStatus & ISO_VALVE_OPEN_FLAG) == ISO_VALVE_OPEN_FLAG; } } public bool IsWaterValveOpen { get { return (_valveStatus & WATER_VALVE_OEPN_FLAG) == WATER_VALVE_OEPN_FLAG; } } public bool AtSpeed { get { return (_valveStatus & VALVE_AT_SPEED_FLAG) == VALVE_AT_SPEED_FLAG; } } public string sTemperature { get { return Temperature.ToString(); } } public string RotationalSpeed { get { return Speed.ToString(); } } private readonly int _timeout = 2000; private readonly int _address = 0; private readonly int _internal_parameters_length = 78; private readonly AsyncSerialPort _serial; private Stopwatch _queryWatch = new Stopwatch(); private Stopwatch _responseWatch = new Stopwatch(); private readonly int _readInterval = 1000; private ConcurrentQueue _queCommands = new ConcurrentQueue(); private Operation _lastCommand = Operation.Invalid; private string _lastAlarmString = string.Empty; private Regex _rex_ok = new Regex(@"#\d{1,3},OK"); private Regex _rex_err = new Regex(@"#\d{1,3},Err"); private byte _pumpStatus = 0; private byte _valveStatus = 0; private string _port; public AdixenTurboPump(ModuleName mod) { Name = VenusDevice.TurboPump.ToString(); Module = mod.ToString(); var _PortNum = SC.GetStringValue($"{mod}.TurboPump.Port"); _serial = new AsyncSerialPort(_PortNum, 9600, 8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One, "\r", false); _port = _PortNum; //SerachCommandList = new List() //{ //SkyPumpMessage.READ_DATA //}; //sendDataChangedEvent += AdixenTurboPump_sendDataChangedEvent; //baseStopwatch.Start(); //baseTimer.Enabled = true; } private void AdixenTurboPump_sendDataChangedEvent(string obj) { } public override bool Initialize() { if (!_serial.Open()) { LOG.Write(eEvent.ERR_TURBO_PUMP, Module, "Adixen Turbo Pump 串口无法打开"); return false; } _serial.OnDataChanged += OnPortDataChanged; _serial.OnBinaryDataChanged += OnPortBinaryDataChanged; _serial.OnErrorHappened += OnErrorOccurred; _queryWatch.Start(); return true; } public override void Monitor() { if (_queryWatch.ElapsedMilliseconds > _readInterval) { _queryWatch.Restart(); if (_lastCommand == Operation.Invalid) { if (_queCommands.IsEmpty) { _sendCommand(Operation.GetIntervalParametersState); } else { Operation command; if (_queCommands.TryDequeue(out command)) { _sendCommand(command); _lastCommand = command; } } } else if (_responseWatch.ElapsedMilliseconds > _timeout) { _serial.ClearPortBuffer(); _lastCommand = Operation.Invalid; } } var isopen = _serial.IsOpen(); } public override void Reset() { Operation result; while (_queCommands.TryDequeue(out result)) ; //_serial.ClearPortBuffer(); _lastCommand = Operation.Invalid; } public override void Terminate() { _serial?.Close(); } private void OnErrorOccurred(string obj) { _noRepeatAlarm($"[{Module}] Adixen Turbo Pump serial port error: [{obj}]"); } private void OnPortDataChanged(string obj) { try { _lastCommand = Operation.Invalid; if (obj.Substring(0, 2) == "OK") { return; } if (obj.Substring(0, 3) == "Err") { if (_comError.ContainsKey(obj.Substring(0, 4))) { _noRepeatAlarm($"Adixen Turbo Pump communication error: {_comError[obj.Substring(0, 4)]}"); } else { _noRepeatAlarm($"Adixen Turbo Pump unknown communication error: {obj}"); } return; } var result_data = obj.Trim().Split(','); if (result_data.Length >= 9) { int speed = 0; int temp = 0; if (int.TryParse(result_data[0], out speed)) { Speed = speed; } if (int.TryParse(result_data[8], out temp)) { Temperature = temp; } } } catch (Exception ex) { _noRepeatAlarm($"[{Module}] Adixen Turbo Pump error: [{ex.Message}], Data: {obj}"); } } private void _OnHandleBinaryData(byte[] obj) { //System.Threading.Monitor.Enter(_Lock); byte start = System.Text.Encoding.Default.GetBytes("#")[0]; _serial.HandlePorts(obj, 78, start, Module, eEvent.ERR_TURBO_PUMP, 9); if (_serial.bValidate == true) { _pumpStatus = _serial.GetData[6]; _valveStatus = _serial.GetData[7]; //int nOffset = 9; //_serial.str.Remove(0, nOffset); OnPortDataChanged(_serial.str.ToString()); _serial.str.Clear(); _serial.GetData = new byte[] { }; _serial.bValidate = false; } } private byte[] GetData = new byte[] { }; private void OnHandleBinaryData(byte[] obj) { bool bValidate = false; GetData = (byte[])GetData.Concat(obj).ToArray(); var strData1 = System.Text.Encoding.Default.GetString(GetData); for (int i = 0; i < GetData.Length; i++) { if (GetData[i] == (byte)'#') { if ((GetData.Length - i) >= 78) { _pumpStatus = GetData[i + 6]; _valveStatus = GetData[i + 7]; int nOffset = 9; byte[] array = new byte[GetData.Length - i - nOffset]; Array.Copy(GetData, i + nOffset, array, 0, GetData.Length - i - nOffset); int _start = i + 78; int _end = GetData.Length - 1; //GetData = (byte[])GetData.Skip(_start).Take(_end - _start + 1).ToArray(); GetData = new byte[] { }; var strData = System.Text.Encoding.Default.GetString(array); OnPortDataChanged(strData); bValidate = true; break; } } } if (GetData.Length > 156 && !bValidate) { var strData = System.Text.Encoding.Default.GetString(GetData); _noRepeatAlarm($"Receive invalidate data:{strData} "); } } private void OnPortBinaryDataChanged(byte[] obj) { bool bValidate = false; for (int i = 0; i < obj.Length; i++) { if (obj[i] == (byte)'#' && obj.Length > i + 5 && obj[i + 4] == (byte)',') { int nOffset = 5; if (obj.Length - i >= _internal_parameters_length) { _pumpStatus = obj[i + 6]; _valveStatus = obj[i + 7]; nOffset = 9; } byte[] array = new byte[obj.Length - i - nOffset]; Array.Copy(obj, i + nOffset, array, 0, obj.Length - i - nOffset); var strData = System.Text.Encoding.Default.GetString(array); OnPortDataChanged(strData); bValidate = true; break; } } if (!bValidate) { var strData = System.Text.Encoding.Default.GetString(obj); _noRepeatAlarm($"Receive invalidate data:{strData} "); } } public override void SetPumpOnOff(bool on) { var _chamber = DEVICE.GetDevice(Module); if (on && !_chamber.TurboPumpInterlock) { LOG.Write(eEvent.ERR_TURBO_PUMP, Module, "Cannot Run Turbo Pump for Turbo Pump Interlock(DI-9) is off."); return; } _queCommands.Enqueue(on ? Operation.StartPumpRotation : Operation.StopPump); } private bool _sendCommand(Operation op) { if (_noneParaCommandOp.ContainsKey(op)) { var cmd = string.Format(_noneParaCommandOp[op], _address); return _sendCmd(cmd); } else if (_readDataCommandOp.ContainsKey(op)) { var cmd = string.Format(_readDataCommandOp[op], _address); return _sendCmd(cmd); } _noRepeatAlarm($"Adixen Turbo Pump: The {op} command need parameters"); return false; } private bool _sendCommand(Operation op, int data) { if (_setDataCommandOp.ContainsKey(op)) { var cmd = string.Format(_setDataCommandOp[op], _address, data); return _sendCmd(cmd); } _noRepeatAlarm($"Adixen Turbo Pump: The command {op} does not need one parameter"); return false; } private bool _sendCmd(string cmd) { _responseWatch.Restart(); return _serial.Write(cmd); } private void _noRepeatAlarm(string alarm) { if (_lastAlarmString != alarm) { _lastAlarmString = alarm; LOG.Write(eEvent.ERR_TURBO_PUMP, Module, alarm); } } public override bool ReConnect() { return _serial.ReConnect(); } } }