AsyncSerialPort.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. using System;
  2. using System.Collections;
  3. using System.IO.Ports;
  4. using System.Text;
  5. using System.Diagnostics;
  6. using Aitex.Core.RT.Log;
  7. using Aitex.Core.RT.SCCore;
  8. using System.Linq;
  9. namespace MECF.Framework.Common.Communications
  10. {
  11. public class AsyncSerialPort : IDisposable
  12. {
  13. public string PortName { get { return _port.PortName; } set {
  14. {
  15. _port.PortName = value;
  16. } } }
  17. public event Action<string> OnErrorHappened;
  18. public event Action<string> OnDataChanged;
  19. public event Action<byte[]> OnBinaryDataChanged;
  20. private static Object _locker = new Object();
  21. protected SerialPort _port;
  22. private string _buff = "";
  23. public bool EnableLog { get; set; }
  24. public StringBuilder str { get; set; }
  25. public byte[] GetData { get; set; }
  26. public bool bValidate { get; set; }
  27. private bool _isAsciiMode;
  28. private static BitArray _EnableLog;
  29. public AsyncSerialPort(string name, int baudRate, int dataBits, Parity parity = Parity.None, StopBits stopBits = StopBits.One, string newline = "\r", bool isAsciiMode=true)
  30. {
  31. _isAsciiMode = isAsciiMode;
  32. _port = new SerialPort();
  33. _port.PortName = name;
  34. _port.BaudRate = baudRate;
  35. _port.DataBits = dataBits;
  36. _port.Parity = parity;
  37. _port.StopBits = stopBits;
  38. _port.RtsEnable = false;
  39. _port.DtrEnable = false;
  40. _port.ReadTimeout = 1000;
  41. _port.WriteTimeout = 1000;
  42. _port.NewLine = newline;
  43. _port.Handshake = Handshake.None;
  44. _port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
  45. _port.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceived);
  46. EnableLog = GetEnableFlag(name);
  47. str = new StringBuilder();
  48. bValidate = false;
  49. GetData = new byte[] { };
  50. }
  51. public void Dispose()
  52. {
  53. Close();
  54. }
  55. public bool Open()
  56. {
  57. if (_port.IsOpen) Close();
  58. try
  59. {
  60. _port.Open();
  61. _port.DiscardInBuffer();
  62. _port.DiscardOutBuffer();
  63. _buff = "";
  64. }
  65. catch (Exception e)
  66. {
  67. string reason = _port.PortName + " port open failed,please check configuration。" + e.Message;
  68. //ProcessError( reason );
  69. //LOG.Write(reason);
  70. return false;
  71. }
  72. return true;
  73. }
  74. public bool IsOpen()
  75. {
  76. return _port.IsOpen;
  77. }
  78. public bool Close()
  79. {
  80. if (_port.IsOpen)
  81. {
  82. try
  83. {
  84. _port.Close();
  85. }
  86. catch (Exception e)
  87. {
  88. string reason = _port.PortName + " port close failed。" + e.Message;
  89. ProcessError( reason );
  90. return false;
  91. }
  92. }
  93. return true;
  94. }
  95. //结束符号, 由调用者 负责加上
  96. public bool Write(string msg)
  97. {
  98. try
  99. {
  100. lock (_locker)
  101. {
  102. if (_port.IsOpen)
  103. {
  104. _port.Write(msg);
  105. if (EnableLog)
  106. {
  107. //LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, msg));
  108. }
  109. }
  110. }
  111. return true;
  112. }
  113. catch (Exception e)
  114. {
  115. string reason = string.Format("Communication {0} Send {1} failed. {2}.", _port.PortName, msg, e.Message);
  116. //LOG.Info(reason);
  117. ProcessError( reason );
  118. return false;
  119. }
  120. }
  121. public bool Write(byte[] msg)
  122. {
  123. try
  124. {
  125. lock (_locker)
  126. {
  127. if (_port.IsOpen)
  128. {
  129. _port.Write(msg, 0, msg.Length);
  130. if (EnableLog)
  131. {
  132. //LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2")))));
  133. }
  134. }
  135. }
  136. return true;
  137. }
  138. catch (Exception e)
  139. {
  140. string reason = string.Format("Communication {0} Send {1} failed. {2}.", _port.PortName, string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2"))), e.Message);
  141. //LOG.Info(reason);
  142. ProcessError(reason);
  143. return false;
  144. }
  145. }
  146. public void HandlePorts(byte[] obj, int _length, byte start, string Module, eEvent errdevice,int nOffset)
  147. {
  148. lock (_locker)
  149. {
  150. GetData = (byte[])GetData.Concat(obj).ToArray();
  151. //str.Append(System.Text.Encoding.Default.GetString(obj));
  152. var strData1 = System.Text.Encoding.Default.GetString(GetData);
  153. for (int i = 0; i < GetData.Length; i++)
  154. {
  155. if (GetData[i] == start)
  156. {
  157. if ((GetData.Length - i) >= _length)
  158. {
  159. bValidate = true;
  160. byte[] array = new byte[GetData.Length - i - nOffset];
  161. Array.Copy(GetData, i + nOffset, array, 0, _length - nOffset);
  162. str.Append(System.Text.Encoding.Default.GetString(array));
  163. //str.Remove(0, i);
  164. //str.Remove(i + _length - 1, str.Length - i - _length);
  165. break;
  166. }
  167. }
  168. }
  169. if (GetData.Length > _length * 3 && !bValidate)
  170. {
  171. LOG.Write(errdevice, Module, $"Receive invalidate data:{str} ");
  172. }
  173. }
  174. }
  175. public void DataReceived(object sender, SerialDataReceivedEventArgs e)
  176. {
  177. if (!_port.IsOpen)
  178. {
  179. //LOG.Write($"discard {_port.PortName} received data, but port not open");
  180. return;
  181. }
  182. if (_isAsciiMode)
  183. {
  184. AsciiDataReceived();
  185. }
  186. else
  187. {
  188. BinaryDataReceived();
  189. }
  190. }
  191. private void AsciiDataReceived()
  192. {
  193. string str = _port.ReadExisting(); //字符串方式读
  194. _buff += str;
  195. int index = _buff.LastIndexOf(_port.NewLine, StringComparison.Ordinal);
  196. if (index > 0)
  197. {
  198. index += _port.NewLine.Length;
  199. string msg = _buff.Substring(0, index);
  200. _buff = _buff.Substring(index);
  201. if (EnableLog)
  202. {
  203. //LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, msg));
  204. }
  205. if (OnDataChanged != null)
  206. OnDataChanged(msg);
  207. }
  208. }
  209. public void BinaryDataReceived( )
  210. {
  211. byte[] readBuffer = new byte[_port.BytesToRead];
  212. int readCount = _port.Read(readBuffer, 0, readBuffer.Length);
  213. if (readCount == 0)
  214. {
  215. //LOG.Write($"read zero length data, {_port.PortName}");
  216. return;
  217. }
  218. byte[] buffer = new byte[readCount];
  219. Buffer.BlockCopy(readBuffer, 0, buffer, 0, readCount);
  220. if (EnableLog)
  221. {
  222. StringBuilder str = new StringBuilder(512);
  223. Array.ForEach(buffer, x => str.Append(x.ToString("X2") + " "));
  224. //LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, str));
  225. }
  226. if (OnBinaryDataChanged != null)
  227. OnBinaryDataChanged(buffer);
  228. }
  229. void ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
  230. {
  231. string reason = string.Format("Communication {0} {1}.", _port.PortName, e.EventType.ToString());
  232. //LOG.Error(reason);
  233. ProcessError( reason );
  234. }
  235. public void ClearPortBuffer()
  236. {
  237. _port.DiscardInBuffer();
  238. _port.DiscardOutBuffer();
  239. }
  240. void ProcessError(string reason)
  241. {
  242. if (OnErrorHappened != null)
  243. OnErrorHappened(reason);
  244. }
  245. bool GetEnableFlag(string portName)
  246. {
  247. if (_EnableLog == null)
  248. {
  249. Process cur = Process.GetCurrentProcess();
  250. if (cur.ProcessName != "Venus_RT")
  251. return false;
  252. string[] strArray = SC.GetStringValue("System.COMLogFlag").Split(',');
  253. int[] bitData = new int[8];
  254. for (int i = 0; i < strArray.Length; i++)
  255. {
  256. if (int.TryParse(strArray[i], System.Globalization.NumberStyles.HexNumber, null, out int Flag))
  257. {
  258. bitData[i] = Flag;
  259. }
  260. else
  261. {
  262. bitData[i] = 0;
  263. LOG.Write(eEvent.WARN_DEVICE_INFO, "System", $"Parse System.COMLogFlag failed: {strArray[i]}.");
  264. }
  265. }
  266. _EnableLog = new BitArray(bitData);
  267. }
  268. if (int.TryParse(portName.Substring(3), out int nCom))
  269. {
  270. if (_EnableLog.Length > nCom)
  271. {
  272. return _EnableLog[nCom];
  273. }
  274. }
  275. return false;
  276. }
  277. public bool ReConnect()
  278. {
  279. string[] coms = SerialPort.GetPortNames();
  280. for (int i = 0; i < coms.Length; i++)
  281. {
  282. //找到目标串口
  283. if (coms[i].ToUpper() == PortName)
  284. {
  285. //判断目标串口是否打开
  286. if (_port.IsOpen)
  287. {
  288. return true;
  289. }
  290. else
  291. {
  292. Open();
  293. return _port.IsOpen;
  294. }
  295. }
  296. }
  297. return false;
  298. }
  299. }
  300. }