using System; using System.Collections.Concurrent; using System.ComponentModel; using System.IO.Ports; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using Aitex.Core.RT.Event; using Aitex.Core.RT.Log; using Aitex.Core.RT.SCCore; using MECF.Framework.Common.Utilities; using Microsoft.Win32.SafeHandles; 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 ConcurrentQueue SendOrReceiveLog = new ConcurrentQueue(); private string _COMLogConfig; private bool _isAsciiMode; public bool IsAsciiMode { get => _isAsciiMode; set { _isAsciiMode = value; } } private bool _isLineBased; public AsyncSerialPort(string name, int baudRate, int dataBits, Parity parity = Parity.None, StopBits stopBits = StopBits.One, string newline = "\r", bool isAsciiMode = true) { _COMLogConfig = SC.GetStringValue("System.COMLogFlag"); _isAsciiMode = isAsciiMode; _isLineBased = !string.IsNullOrEmpty(newline); _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; if (!string.IsNullOrEmpty(newline)) { _port.NewLine = newline; } _port.DataReceived += new SerialDataReceivedEventHandler(DataReceived); _port.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceived); } public void Dispose() { Close(); } public bool Open() { if (_port.IsOpen) Close(); //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)); LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2"))))); } AppendSendOrReceiveLog("Write", string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))); } } 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"))))); LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, Encoding.ASCII.GetString(msg))); } AppendSendOrReceiveLog("Write", 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 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(); //字符串方式读 if (_isLineBased) { _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)); LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2"))))); } if (OnDataChanged != null) OnDataChanged(msg); AppendSendOrReceiveLog("Read", string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))); } } else { string msg = str; if (EnableLog) { LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, msg)); LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2"))))); } if (OnDataChanged != null) OnDataChanged(msg); AppendSendOrReceiveLog("Read", string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))); } } 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)); LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, Encoding.ASCII.GetString(buffer))); } if (OnBinaryDataChanged != null) OnBinaryDataChanged(buffer); AppendSendOrReceiveLog("Read", string.Join(" ", Array.ConvertAll(buffer, x => x.ToString("X2")))); } 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); } internal const int FBINARY = 0; internal const int FPARITY = 1; internal const int FOUTXCTSFLOW = 2; internal const int FOUTXDSRFLOW = 3; internal const int FDTRCONTROL = 4; internal const int FDSRSENSITIVITY = 6; internal const int FTXCONTINUEONXOFF = 7; internal const int FOUTX = 8; internal const int FINX = 9; internal const int FERRORCHAR = 10; internal const int FNULL = 11; internal const int FRTSCONTROL = 12; internal const int FABORTONOERROR = 14; internal const int FDUMMY2 = 15; public bool UpdateComm() { if (_port.IsOpen) { _port.DiscardInBuffer(); _port.DiscardOutBuffer(); _port.SetFlag(FBINARY, 1); _port.SetFlag(FOUTXCTSFLOW, 0x00); _port.SetFlag(FOUTXDSRFLOW, 0x00); _port.SetFlag(FDSRSENSITIVITY, 0x00); _port.SetFlag(FDTRCONTROL, 0x01); _port.SetFlag(FRTSCONTROL, 0x01); _port.SetFlag(FOUTX, 0x00); _port.SetFlag(FINX, 0x00); _port.SetField("EofChar", (byte)0x0); _port.SetField("XonChar", (byte)0x11); _port.SetField("XoffChar", (byte)0x13); _port.SetField("EvtChar", (byte)0x0); _port.SetField("XonLim", (ushort)2048); _port.SetField("XoffLim", (ushort)512); _port.UpdateComm(); } return true; } private void AppendSendOrReceiveLog(string title, string content) { if (string.IsNullOrWhiteSpace(_COMLogConfig) || !_COMLogConfig.Contains(_port.PortName)) return; var count = SendOrReceiveLog.Count; for (var i = count; i > 400; i--) { SendOrReceiveLog.TryDequeue(out string _); } SendOrReceiveLog.Enqueue($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} {_port?.PortName} {title ?? string.Empty} [{content ?? string.Empty}]"); } public void ClearSendOrReceiveLog() { if (!SendOrReceiveLog.IsEmpty) { var count = SendOrReceiveLog.Count; for (var i = 0; i < count; i++) { SendOrReceiveLog.TryDequeue(out string _); } } } } internal static class SerialPortExtensions { [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static void SetField(this SerialPort port, string field, object value) { if (port == null) throw new NullReferenceException(); if (port.BaseStream == null) throw new InvalidOperationException("Cannot change fields until after the port has been opened."); try { object baseStream = port.BaseStream; Type baseStreamType = baseStream.GetType(); FieldInfo dcbFieldInfo = baseStreamType.GetField("dcb", BindingFlags.NonPublic | BindingFlags.Instance); object dcbValue = dcbFieldInfo.GetValue(baseStream); Type dcbType = dcbValue.GetType(); dcbType.GetField(field).SetValue(dcbValue, value); dcbFieldInfo.SetValue(baseStream, dcbValue); } catch (SecurityException) { throw; } catch (OutOfMemoryException) { throw; } catch (Win32Exception) { throw; } catch (Exception) { throw; } } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static void SetFlag(this SerialPort port, int flag, int value) { object BaseStream = port.BaseStream; Type SerialStream = BaseStream.GetType(); SerialStream.GetMethod("SetDcbFlag", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(BaseStream, new object[] { flag, value }); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static void UpdateComm(this SerialPort port) { object baseStream = port.BaseStream; Type baseStreamType = baseStream.GetType(); FieldInfo dcbFieldInfo = baseStreamType.GetField("dcb", BindingFlags.NonPublic | BindingFlags.Instance); object dcbValue = dcbFieldInfo.GetValue(baseStream); SafeFileHandle portFileHandle = (SafeFileHandle)baseStreamType.GetField("_handle", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(baseStream); IntPtr hGlobal = Marshal.AllocHGlobal(Marshal.SizeOf(dcbValue)); try { Marshal.StructureToPtr(dcbValue, hGlobal, false); if (!SetCommState(portFileHandle, hGlobal)) throw new Win32Exception(Marshal.GetLastWin32Error()); } finally { if (hGlobal != IntPtr.Zero) Marshal.FreeHGlobal(hGlobal); } } [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool SetCommState(SafeFileHandle hFile, IntPtr lpDCB); } }