using System; using System.Collections; using System.IO.Ports; using System.Text; using System.Diagnostics; using Aitex.Core.RT.Event; using Aitex.Core.RT.Log; using MECF.Framework.Common.Utilities; using Aitex.Core.RT.SCCore; using MECF.Framework.Common.SCCore; using Aitex.Core.Util; using System.Linq; using DocumentFormat.OpenXml.Drawing; namespace MECF.Framework.Common.Communications { public class AsyncSerialPort : IDisposable { public string PortName { get { return _port.PortName; } set { { _port.PortName = value; } } } public event Action OnErrorHappened; public event Action OnDataChanged; public event Action OnBinaryDataChanged; private static Object _locker = new Object(); protected SerialPort _port; private string _buff = ""; public bool EnableLog { get; set; } public StringBuilder str { get; set; } public byte[] GetData { get; set; } public bool bValidate { get; set; } private bool _isAsciiMode; private static BitArray _EnableLog; public AsyncSerialPort(string name, int baudRate, int dataBits, Parity parity = Parity.None, StopBits stopBits = StopBits.One, string newline = "\r", bool isAsciiMode=true) { _isAsciiMode = isAsciiMode; _port = new SerialPort(); _port.PortName = name; _port.BaudRate = baudRate; _port.DataBits = dataBits; _port.Parity = parity; _port.StopBits = stopBits; _port.RtsEnable = false; _port.DtrEnable = false; _port.ReadTimeout = 1000; _port.WriteTimeout = 1000; _port.NewLine = newline; _port.Handshake = Handshake.None; _port.DataReceived += new SerialDataReceivedEventHandler(DataReceived); _port.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceived); EnableLog = GetEnableFlag(name); str = new StringBuilder(); bValidate = false; GetData = new byte[] { }; } public void Dispose() { Close(); } public bool Open() { if (_port.IsOpen) Close(); try { _port.Open(); _port.DiscardInBuffer(); _port.DiscardOutBuffer(); _buff = ""; } catch (Exception e) { string reason = _port.PortName + " port open failed,please check configuration。" + e.Message; //ProcessError( reason ); //LOG.Write(reason); return false; } return true; } public bool IsOpen() { return _port.IsOpen; } public bool Close() { if (_port.IsOpen) { try { _port.Close(); } catch (Exception e) { string reason = _port.PortName + " port close failed。" + e.Message; ProcessError( reason ); return false; } } return true; } //结束符号, 由调用者 负责加上 public bool Write(string msg) { try { lock (_locker) { if (_port.IsOpen) { _port.Write(msg); if (EnableLog) { //LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, msg)); } } } return true; } catch (Exception e) { string reason = string.Format("Communication {0} Send {1} failed. {2}.", _port.PortName, msg, e.Message); //LOG.Info(reason); ProcessError( reason ); return false; } } public bool Write(byte[] msg) { try { lock (_locker) { if (_port.IsOpen) { _port.Write(msg, 0, msg.Length); if (EnableLog) { //LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2"))))); } } } return true; } catch (Exception e) { string reason = string.Format("Communication {0} Send {1} failed. {2}.", _port.PortName, string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2"))), e.Message); //LOG.Info(reason); ProcessError(reason); return false; } } public void HandlePorts(byte[] obj, int _length, byte start, string Module, eEvent errdevice,int nOffset) { lock (_locker) { GetData = (byte[])GetData.Concat(obj).ToArray(); //str.Append(System.Text.Encoding.Default.GetString(obj)); var strData1 = System.Text.Encoding.Default.GetString(GetData); for (int i = 0; i < GetData.Length; i++) { if (GetData[i] == start) { if ((GetData.Length - i) >= _length) { bValidate = true; byte[] array = new byte[GetData.Length - i - nOffset]; Array.Copy(GetData, i + nOffset, array, 0, _length - nOffset); str.Append(System.Text.Encoding.Default.GetString(array)); //str.Remove(0, i); //str.Remove(i + _length - 1, str.Length - i - _length); break; } } } if (GetData.Length > _length * 3 && !bValidate) { LOG.Write(errdevice, Module, $"Receive invalidate data:{str} "); } } } public void DataReceived(object sender, SerialDataReceivedEventArgs e) { if (!_port.IsOpen) { //LOG.Write($"discard {_port.PortName} received data, but port not open"); return; } if (_isAsciiMode) { AsciiDataReceived(); } else { BinaryDataReceived(); } } private void AsciiDataReceived() { string str = _port.ReadExisting(); //字符串方式读 _buff += str; int index = _buff.LastIndexOf(_port.NewLine, StringComparison.Ordinal); if (index > 0) { index += _port.NewLine.Length; string msg = _buff.Substring(0, index); _buff = _buff.Substring(index); if (EnableLog) { //LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, msg)); } if (OnDataChanged != null) OnDataChanged(msg); } } public void BinaryDataReceived( ) { byte[] readBuffer = new byte[_port.BytesToRead]; int readCount = _port.Read(readBuffer, 0, readBuffer.Length); if (readCount == 0) { //LOG.Write($"read zero length data, {_port.PortName}"); return; } byte[] buffer = new byte[readCount]; Buffer.BlockCopy(readBuffer, 0, buffer, 0, readCount); if (EnableLog) { StringBuilder str = new StringBuilder(512); Array.ForEach(buffer, x => str.Append(x.ToString("X2") + " ")); //LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, str)); } if (OnBinaryDataChanged != null) OnBinaryDataChanged(buffer); } void ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { string reason = string.Format("Communication {0} {1}.", _port.PortName, e.EventType.ToString()); //LOG.Error(reason); ProcessError( reason ); } public void ClearPortBuffer() { _port.DiscardInBuffer(); _port.DiscardOutBuffer(); } void ProcessError(string reason) { if (OnErrorHappened != null) OnErrorHappened(reason); } bool GetEnableFlag(string portName) { if (_EnableLog == null) { Process cur = Process.GetCurrentProcess(); if (cur.ProcessName != "Venus_RT") return false; string[] strArray = SC.GetStringValue("System.COMLogFlag").Split(','); int[] bitData = new int[8]; for (int i = 0; i < strArray.Length; i++) { if (int.TryParse(strArray[i], System.Globalization.NumberStyles.HexNumber, null, out int Flag)) { bitData[i] = Flag; } else { bitData[i] = 0; LOG.Write(eEvent.WARN_DEVICE_INFO, "System", $"Parse System.COMLogFlag failed: {strArray[i]}."); } } _EnableLog = new BitArray(bitData); } if (int.TryParse(portName.Substring(3), out int nCom)) { if (_EnableLog.Length > nCom) { return _EnableLog[nCom]; } } return false; } } }