AsyncSerialPort.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.ComponentModel;
  4. using System.IO.Ports;
  5. using System.Reflection;
  6. using System.Runtime.InteropServices;
  7. using System.Security;
  8. using System.Security.Permissions;
  9. using System.Text;
  10. using Aitex.Core.RT.Event;
  11. using Aitex.Core.RT.Log;
  12. using Aitex.Core.RT.SCCore;
  13. using MECF.Framework.Common.Utilities;
  14. using Microsoft.Win32.SafeHandles;
  15. namespace MECF.Framework.Common.Communications
  16. {
  17. public class AsyncSerialPort : IDisposable
  18. {
  19. public string PortName
  20. {
  21. get { return _port.PortName; }
  22. set
  23. {
  24. {
  25. _port.PortName = value;
  26. }
  27. }
  28. }
  29. public event Action<string> OnErrorHappened;
  30. public event Action<string> OnDataChanged;
  31. public event Action<byte[]> OnBinaryDataChanged;
  32. private static Object _locker = new Object();
  33. protected SerialPort _port;
  34. private string _buff = "";
  35. public bool EnableLog { get; set; }
  36. public ConcurrentQueue<string> SendOrReceiveLog = new ConcurrentQueue<string>();
  37. private string _COMLogConfig;
  38. private bool _isAsciiMode;
  39. public bool IsAsciiMode
  40. {
  41. get => _isAsciiMode;
  42. set { _isAsciiMode = value; }
  43. }
  44. private bool _isLineBased;
  45. public AsyncSerialPort(string name, int baudRate, int dataBits, Parity parity = Parity.None, StopBits stopBits = StopBits.One, string newline = "\r", bool isAsciiMode = true)
  46. {
  47. _COMLogConfig = SC.GetStringValue("System.COMLogFlag");
  48. _isAsciiMode = isAsciiMode;
  49. _isLineBased = !string.IsNullOrEmpty(newline);
  50. _port = new SerialPort();
  51. _port.PortName = name;
  52. _port.BaudRate = baudRate;
  53. _port.DataBits = dataBits;
  54. _port.Parity = parity;
  55. _port.StopBits = stopBits;
  56. _port.RtsEnable = false;
  57. _port.DtrEnable = false;
  58. _port.ReadTimeout = 1000;
  59. _port.WriteTimeout = 1000;
  60. if (!string.IsNullOrEmpty(newline))
  61. {
  62. _port.NewLine = newline;
  63. }
  64. _port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
  65. _port.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceived);
  66. }
  67. public void Dispose()
  68. {
  69. Close();
  70. }
  71. public bool Open()
  72. {
  73. if (_port.IsOpen) Close();
  74. //Close();
  75. try
  76. {
  77. _port.Open();
  78. _port.DiscardInBuffer();
  79. _port.DiscardOutBuffer();
  80. _buff = "";
  81. }
  82. catch (Exception e)
  83. {
  84. string reason = _port.PortName + " port open failed,please check configuration." + e.Message;
  85. //ProcessError( reason );
  86. LOG.Write(reason);
  87. return false;
  88. }
  89. return true;
  90. }
  91. public bool IsOpen()
  92. {
  93. return _port.IsOpen;
  94. }
  95. public bool Close()
  96. {
  97. if (_port.IsOpen)
  98. {
  99. try
  100. {
  101. _port.Close();
  102. }
  103. catch (Exception e)
  104. {
  105. string reason = _port.PortName + " port close failed." + e.Message;
  106. ProcessError(reason);
  107. return false;
  108. }
  109. }
  110. return true;
  111. }
  112. //结束符号, 由调用者 负责加上
  113. public bool Write(string msg)
  114. {
  115. try
  116. {
  117. lock (_locker)
  118. {
  119. if (_port.IsOpen)
  120. {
  121. _port.Write(msg);
  122. if (EnableLog)
  123. {
  124. LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, msg));
  125. LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))));
  126. }
  127. AppendSendOrReceiveLog("Write", string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2"))));
  128. }
  129. }
  130. return true;
  131. }
  132. catch (Exception e)
  133. {
  134. string reason = string.Format("Communication {0} Send {1} failed. {2}.", _port.PortName, msg, e.Message);
  135. LOG.Info(reason);
  136. ProcessError(reason);
  137. return false;
  138. }
  139. }
  140. public bool Write(byte[] msg)
  141. {
  142. try
  143. {
  144. lock (_locker)
  145. {
  146. if (_port.IsOpen)
  147. {
  148. _port.Write(msg, 0, msg.Length);
  149. if (EnableLog)
  150. {
  151. LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2")))));
  152. LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, Encoding.ASCII.GetString(msg)));
  153. }
  154. AppendSendOrReceiveLog("Write", string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2"))));
  155. }
  156. }
  157. return true;
  158. }
  159. catch (Exception e)
  160. {
  161. string reason = string.Format("Communication {0} Send {1} failed. {2}.", _port.PortName, string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2"))), e.Message);
  162. LOG.Info(reason);
  163. ProcessError(reason);
  164. return false;
  165. }
  166. }
  167. public void DataReceived(object sender, SerialDataReceivedEventArgs e)
  168. {
  169. if (!_port.IsOpen)
  170. {
  171. LOG.Write($"discard {_port.PortName} received data, but port not open");
  172. return;
  173. }
  174. if (_isAsciiMode)
  175. {
  176. AsciiDataReceived();
  177. }
  178. else
  179. {
  180. BinaryDataReceived();
  181. }
  182. }
  183. private void AsciiDataReceived()
  184. {
  185. string str = _port.ReadExisting(); //字符串方式读
  186. if (_isLineBased)
  187. {
  188. _buff += str;
  189. int index = _buff.LastIndexOf(_port.NewLine, StringComparison.Ordinal);
  190. if (index > 0)
  191. {
  192. index += _port.NewLine.Length;
  193. string msg = _buff.Substring(0, index);
  194. _buff = _buff.Substring(index);
  195. if (EnableLog)
  196. {
  197. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, msg));
  198. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))));
  199. }
  200. if (OnDataChanged != null)
  201. OnDataChanged(msg);
  202. AppendSendOrReceiveLog("Read", string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2"))));
  203. }
  204. }
  205. else
  206. {
  207. string msg = str;
  208. if (EnableLog)
  209. {
  210. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, msg));
  211. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))));
  212. }
  213. if (OnDataChanged != null)
  214. OnDataChanged(msg);
  215. AppendSendOrReceiveLog("Read", string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2"))));
  216. }
  217. }
  218. public void BinaryDataReceived()
  219. {
  220. byte[] readBuffer = new byte[_port.BytesToRead];
  221. int readCount = _port.Read(readBuffer, 0, readBuffer.Length);
  222. if (readCount == 0)
  223. {
  224. //LOG.Write($"read zero length data, {_port.PortName}");
  225. return;
  226. }
  227. byte[] buffer = new byte[readCount];
  228. Buffer.BlockCopy(readBuffer, 0, buffer, 0, readCount);
  229. if (EnableLog)
  230. {
  231. StringBuilder str = new StringBuilder(512);
  232. Array.ForEach(buffer, x => str.Append(x.ToString("X2") + " "));
  233. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, str));
  234. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, Encoding.ASCII.GetString(buffer)));
  235. }
  236. if (OnBinaryDataChanged != null)
  237. OnBinaryDataChanged(buffer);
  238. AppendSendOrReceiveLog("Read", string.Join(" ", Array.ConvertAll(buffer, x => x.ToString("X2"))));
  239. }
  240. void ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
  241. {
  242. string reason = string.Format("Communication {0} {1}.", _port.PortName, e.EventType.ToString());
  243. LOG.Error(reason);
  244. ProcessError(reason);
  245. }
  246. public void ClearPortBuffer()
  247. {
  248. _port.DiscardInBuffer();
  249. _port.DiscardOutBuffer();
  250. }
  251. void ProcessError(string reason)
  252. {
  253. if (OnErrorHappened != null)
  254. OnErrorHappened(reason);
  255. }
  256. internal const int FBINARY = 0;
  257. internal const int FPARITY = 1;
  258. internal const int FOUTXCTSFLOW = 2;
  259. internal const int FOUTXDSRFLOW = 3;
  260. internal const int FDTRCONTROL = 4;
  261. internal const int FDSRSENSITIVITY = 6;
  262. internal const int FTXCONTINUEONXOFF = 7;
  263. internal const int FOUTX = 8;
  264. internal const int FINX = 9;
  265. internal const int FERRORCHAR = 10;
  266. internal const int FNULL = 11;
  267. internal const int FRTSCONTROL = 12;
  268. internal const int FABORTONOERROR = 14;
  269. internal const int FDUMMY2 = 15;
  270. public bool UpdateComm()
  271. {
  272. if (_port.IsOpen)
  273. {
  274. _port.DiscardInBuffer();
  275. _port.DiscardOutBuffer();
  276. _port.SetFlag(FBINARY, 1);
  277. _port.SetFlag(FOUTXCTSFLOW, 0x00);
  278. _port.SetFlag(FOUTXDSRFLOW, 0x00);
  279. _port.SetFlag(FDSRSENSITIVITY, 0x00);
  280. _port.SetFlag(FDTRCONTROL, 0x01);
  281. _port.SetFlag(FRTSCONTROL, 0x01);
  282. _port.SetFlag(FOUTX, 0x00);
  283. _port.SetFlag(FINX, 0x00);
  284. _port.SetField("EofChar", (byte)0x0);
  285. _port.SetField("XonChar", (byte)0x11);
  286. _port.SetField("XoffChar", (byte)0x13);
  287. _port.SetField("EvtChar", (byte)0x0);
  288. _port.SetField("XonLim", (ushort)2048);
  289. _port.SetField("XoffLim", (ushort)512);
  290. _port.UpdateComm();
  291. }
  292. return true;
  293. }
  294. private void AppendSendOrReceiveLog(string title, string content)
  295. {
  296. if (string.IsNullOrWhiteSpace(_COMLogConfig) || !_COMLogConfig.Contains(_port.PortName)) return;
  297. var count = SendOrReceiveLog.Count;
  298. for (var i = count; i > 400; i--)
  299. {
  300. SendOrReceiveLog.TryDequeue(out string _);
  301. }
  302. SendOrReceiveLog.Enqueue($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} {_port?.PortName} {title ?? string.Empty} [{content ?? string.Empty}]");
  303. }
  304. public void ClearSendOrReceiveLog()
  305. {
  306. if (!SendOrReceiveLog.IsEmpty)
  307. {
  308. var count = SendOrReceiveLog.Count;
  309. for (var i = 0; i < count; i++)
  310. {
  311. SendOrReceiveLog.TryDequeue(out string _);
  312. }
  313. }
  314. }
  315. }
  316. internal static class SerialPortExtensions
  317. {
  318. [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
  319. public static void SetField(this SerialPort port, string field, object value)
  320. {
  321. if (port == null)
  322. throw new NullReferenceException();
  323. if (port.BaseStream == null)
  324. throw new InvalidOperationException("Cannot change fields until after the port has been opened.");
  325. try
  326. {
  327. object baseStream = port.BaseStream;
  328. Type baseStreamType = baseStream.GetType();
  329. FieldInfo dcbFieldInfo = baseStreamType.GetField("dcb", BindingFlags.NonPublic | BindingFlags.Instance);
  330. object dcbValue = dcbFieldInfo.GetValue(baseStream);
  331. Type dcbType = dcbValue.GetType();
  332. dcbType.GetField(field).SetValue(dcbValue, value);
  333. dcbFieldInfo.SetValue(baseStream, dcbValue);
  334. }
  335. catch (SecurityException) { throw; }
  336. catch (OutOfMemoryException) { throw; }
  337. catch (Win32Exception) { throw; }
  338. catch (Exception)
  339. {
  340. throw;
  341. }
  342. }
  343. [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
  344. public static void SetFlag(this SerialPort port, int flag, int value)
  345. {
  346. object BaseStream = port.BaseStream;
  347. Type SerialStream = BaseStream.GetType();
  348. SerialStream.GetMethod("SetDcbFlag", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(BaseStream, new object[] { flag, value });
  349. }
  350. [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
  351. public static void UpdateComm(this SerialPort port)
  352. {
  353. object baseStream = port.BaseStream;
  354. Type baseStreamType = baseStream.GetType();
  355. FieldInfo dcbFieldInfo = baseStreamType.GetField("dcb", BindingFlags.NonPublic | BindingFlags.Instance);
  356. object dcbValue = dcbFieldInfo.GetValue(baseStream);
  357. SafeFileHandle portFileHandle = (SafeFileHandle)baseStreamType.GetField("_handle", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(baseStream);
  358. IntPtr hGlobal = Marshal.AllocHGlobal(Marshal.SizeOf(dcbValue));
  359. try
  360. {
  361. Marshal.StructureToPtr(dcbValue, hGlobal, false);
  362. if (!SetCommState(portFileHandle, hGlobal))
  363. throw new Win32Exception(Marshal.GetLastWin32Error());
  364. }
  365. finally
  366. {
  367. if (hGlobal != IntPtr.Zero)
  368. Marshal.FreeHGlobal(hGlobal);
  369. }
  370. }
  371. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  372. private static extern bool SetCommState(SafeFileHandle hFile, IntPtr lpDCB);
  373. }
  374. }