AsyncSerialPort.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. using System;
  2. using System.IO.Ports;
  3. using System.Text;
  4. using Aitex.Core.RT.Event;
  5. using Aitex.Core.RT.Log;
  6. using MECF.Framework.Common.Utilities;
  7. namespace MECF.Framework.Common.Communications
  8. {
  9. public class AsyncSerialPort : IDisposable
  10. {
  11. public string PortName
  12. {
  13. get { return _port.PortName; }
  14. set
  15. {
  16. {
  17. _port.PortName = value;
  18. }
  19. }
  20. }
  21. public event Action<string> OnErrorHappened;
  22. public event Action<string> OnDataChanged;
  23. public event Action<byte[]> OnBinaryDataChanged;
  24. private static Object _locker = new Object();
  25. protected SerialPort _port;
  26. private string _buff = "";
  27. public bool EnableLog { get; set; }
  28. private bool _isAsciiMode;
  29. public bool IsAsciiMode
  30. {
  31. get => _isAsciiMode;
  32. set { _isAsciiMode = value; }
  33. }
  34. private bool _isLineBased;
  35. public AsyncSerialPort(string name, int baudRate, int dataBits, Parity parity = Parity.None, StopBits stopBits = StopBits.One, string newline = "\r", bool isAsciiMode = true)
  36. {
  37. _isAsciiMode = isAsciiMode;
  38. _isLineBased = !string.IsNullOrEmpty(newline);
  39. _port = new SerialPort();
  40. _port.PortName = name;
  41. _port.BaudRate = baudRate;
  42. _port.DataBits = dataBits;
  43. _port.Parity = parity;
  44. _port.StopBits = stopBits;
  45. _port.RtsEnable = false;
  46. _port.DtrEnable = false;
  47. _port.ReadTimeout = 1000;
  48. _port.WriteTimeout = 1000;
  49. if (!string.IsNullOrEmpty(newline))
  50. {
  51. _port.NewLine = newline;
  52. }
  53. _port.Handshake = Handshake.None;
  54. _port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
  55. _port.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceived);
  56. }
  57. public void Dispose()
  58. {
  59. Close();
  60. }
  61. public bool Open()
  62. {
  63. if (_port.IsOpen) Close();
  64. //Close();
  65. try
  66. {
  67. _port.Open();
  68. _port.DiscardInBuffer();
  69. _port.DiscardOutBuffer();
  70. _buff = "";
  71. }
  72. catch (Exception e)
  73. {
  74. string reason = _port.PortName + " port open failed,please check configuration." + e.Message;
  75. //ProcessError( reason );
  76. LOG.Write(reason);
  77. return false;
  78. }
  79. return true;
  80. }
  81. public bool IsOpen()
  82. {
  83. return _port.IsOpen;
  84. }
  85. public bool Close()
  86. {
  87. if (_port.IsOpen)
  88. {
  89. try
  90. {
  91. _port.Close();
  92. }
  93. catch (Exception e)
  94. {
  95. string reason = _port.PortName + " port close failed." + e.Message;
  96. ProcessError(reason);
  97. return false;
  98. }
  99. }
  100. return true;
  101. }
  102. //结束符号, 由调用者 负责加上
  103. public bool Write(string msg)
  104. {
  105. try
  106. {
  107. lock (_locker)
  108. {
  109. if (_port.IsOpen)
  110. {
  111. _port.Write(msg);
  112. if (EnableLog)
  113. {
  114. LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, msg));
  115. LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))));
  116. }
  117. }
  118. }
  119. return true;
  120. }
  121. catch (Exception e)
  122. {
  123. string reason = string.Format("Communication {0} Send {1} failed. {2}.", _port.PortName, msg, e.Message);
  124. LOG.Info(reason);
  125. ProcessError(reason);
  126. return false;
  127. }
  128. }
  129. public bool Write(byte[] msg)
  130. {
  131. try
  132. {
  133. lock (_locker)
  134. {
  135. if (_port.IsOpen)
  136. {
  137. _port.Write(msg, 0, msg.Length);
  138. if (EnableLog)
  139. {
  140. LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2")))));
  141. LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, Encoding.ASCII.GetString(msg)));
  142. }
  143. }
  144. }
  145. return true;
  146. }
  147. catch (Exception e)
  148. {
  149. string reason = string.Format("Communication {0} Send {1} failed. {2}.", _port.PortName, string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2"))), e.Message);
  150. LOG.Info(reason);
  151. ProcessError(reason);
  152. return false;
  153. }
  154. }
  155. public void DataReceived(object sender, SerialDataReceivedEventArgs e)
  156. {
  157. if (!_port.IsOpen)
  158. {
  159. LOG.Write($"discard {_port.PortName} received data, but port not open");
  160. return;
  161. }
  162. if (_isAsciiMode)
  163. {
  164. AsciiDataReceived();
  165. }
  166. else
  167. {
  168. BinaryDataReceived();
  169. }
  170. }
  171. private void AsciiDataReceived()
  172. {
  173. string str = _port.ReadExisting(); //字符串方式读
  174. LOG.Info($"AsciiDataReceived dataStr:{str}");
  175. if (_isLineBased)
  176. {
  177. _buff += str;
  178. int index = _buff.LastIndexOf(_port.NewLine, StringComparison.Ordinal);
  179. if (index > 0)
  180. {
  181. index += _port.NewLine.Length;
  182. string msg = _buff.Substring(0, index);
  183. _buff = _buff.Substring(index);
  184. if (EnableLog)
  185. {
  186. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, msg));
  187. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))));
  188. }
  189. if (OnDataChanged != null)
  190. OnDataChanged(msg);
  191. }
  192. }
  193. else
  194. {
  195. string msg = str;
  196. if (EnableLog)
  197. {
  198. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, msg));
  199. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))));
  200. }
  201. if (OnDataChanged != null)
  202. OnDataChanged(msg);
  203. }
  204. }
  205. public void BinaryDataReceived()
  206. {
  207. byte[] readBuffer = new byte[_port.BytesToRead];
  208. int readCount = _port.Read(readBuffer, 0, readBuffer.Length);
  209. if (readCount == 0)
  210. {
  211. //LOG.Write($"read zero length data, {_port.PortName}");
  212. return;
  213. }
  214. byte[] buffer = new byte[readCount];
  215. Buffer.BlockCopy(readBuffer, 0, buffer, 0, readCount);
  216. if (EnableLog)
  217. {
  218. StringBuilder str = new StringBuilder(512);
  219. Array.ForEach(buffer, x => str.Append(x.ToString("X2") + " "));
  220. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, str));
  221. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, Encoding.ASCII.GetString(buffer)));
  222. }
  223. if (OnBinaryDataChanged != null)
  224. OnBinaryDataChanged(buffer);
  225. }
  226. void ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
  227. {
  228. string reason = string.Format("Communication {0} {1}.", _port.PortName, e.EventType.ToString());
  229. LOG.Error(reason);
  230. ProcessError(reason);
  231. }
  232. public void ClearPortBuffer()
  233. {
  234. _port.DiscardInBuffer();
  235. _port.DiscardOutBuffer();
  236. }
  237. void ProcessError(string reason)
  238. {
  239. if (OnErrorHappened != null)
  240. OnErrorHappened(reason);
  241. }
  242. }
  243. }