123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439 |
- 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<string> OnErrorHappened;
- public event Action<string> OnDataChanged;
- public event Action<byte[]> OnBinaryDataChanged;
- private static Object _locker = new Object();
- protected SerialPort _port;
- private string _buff = "";
- public bool EnableLog { get; set; }
- public ConcurrentQueue<string> SendOrReceiveLog = new ConcurrentQueue<string>();
- 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);
- }
- }
|