AsyncSerialPort.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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
  14. {
  15. get { return _port.PortName; }
  16. set
  17. {
  18. {
  19. _port.PortName = value;
  20. }
  21. }
  22. }
  23. public event Action<string> OnErrorHappened;
  24. public event Action<string> OnDataChanged;
  25. public event Action<byte[]> OnBinaryDataChanged;
  26. private static Object _locker = new Object();
  27. protected SerialPort _port;
  28. private string _buff = "";
  29. public bool EnableLog { get; set; }
  30. public StringBuilder str { get; set; }
  31. public byte[] GetData { get; set; }
  32. public bool bValidate { get; set; }
  33. private bool _isAsciiMode;
  34. private static BitArray _EnableLog;
  35. private Stopwatch timeoutStopWatch = new Stopwatch();
  36. public bool IsConnected => timeoutStopWatch.ElapsedMilliseconds < 5 * 1000;
  37. public AsyncSerialPort(string name, int baudRate, int dataBits, Parity parity = Parity.None, StopBits stopBits = StopBits.One, string newline = "\r", bool isAsciiMode = true)
  38. {
  39. _isAsciiMode = isAsciiMode;
  40. _port = new SerialPort();
  41. _port.PortName = name;
  42. _port.BaudRate = baudRate;
  43. _port.DataBits = dataBits;
  44. _port.Parity = parity;
  45. _port.StopBits = stopBits;
  46. _port.RtsEnable = false;
  47. _port.DtrEnable = false;
  48. _port.ReadTimeout = 1000;
  49. _port.WriteTimeout = 1000;
  50. _port.NewLine = newline;
  51. _port.Handshake = Handshake.None;
  52. _port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
  53. _port.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceived);
  54. EnableLog = GetEnableFlag(name);
  55. str = new StringBuilder();
  56. bValidate = false;
  57. GetData = new byte[] { };
  58. }
  59. public void Dispose()
  60. {
  61. Close();
  62. }
  63. public bool Open()
  64. {
  65. if (_port.IsOpen) Close();
  66. try
  67. {
  68. _port.Open();
  69. _port.DiscardInBuffer();
  70. _port.DiscardOutBuffer();
  71. _buff = "";
  72. }
  73. catch (Exception e)
  74. {
  75. string reason = _port.PortName + " port open failed,please check configuration。" + e.Message;
  76. //ProcessError( reason );
  77. //LOG.Write(reason);
  78. return false;
  79. }
  80. return true;
  81. }
  82. public bool IsOpen()
  83. {
  84. return _port.IsOpen;
  85. }
  86. public bool Close()
  87. {
  88. if (_port.IsOpen)
  89. {
  90. try
  91. {
  92. _port.Close();
  93. }
  94. catch (Exception e)
  95. {
  96. string reason = _port.PortName + " port close failed。" + e.Message;
  97. ProcessError(reason);
  98. return false;
  99. }
  100. }
  101. return true;
  102. }
  103. //结束符号, 由调用者 负责加上
  104. public bool Write(string msg)
  105. {
  106. try
  107. {
  108. lock (_locker)
  109. {
  110. if (_port.IsOpen)
  111. {
  112. _port.Write(msg);
  113. if (EnableLog)
  114. {
  115. //LOG.Info(string.Format("Communication {0} Send {1} succeeded.", _port.PortName, msg));
  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. }
  142. }
  143. }
  144. return true;
  145. }
  146. catch (Exception e)
  147. {
  148. string reason = string.Format("Communication {0} Send {1} failed. {2}.", _port.PortName, string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2"))), e.Message);
  149. //LOG.Info(reason);
  150. ProcessError(reason);
  151. return false;
  152. }
  153. }
  154. public void HandlePorts(byte[] obj, int _length, byte start, string Module, eEvent errdevice, int nOffset)
  155. {
  156. lock (_locker)
  157. {
  158. GetData = (byte[])GetData.Concat(obj).ToArray();
  159. //str.Append(System.Text.Encoding.Default.GetString(obj));
  160. var strData1 = System.Text.Encoding.Default.GetString(GetData);
  161. for (int i = 0; i < GetData.Length; i++)
  162. {
  163. if (GetData[i] == start)
  164. {
  165. if ((GetData.Length - i) >= _length)
  166. {
  167. bValidate = true;
  168. byte[] array = new byte[GetData.Length - i - nOffset];
  169. Array.Copy(GetData, i + nOffset, array, 0, _length - nOffset);
  170. str.Append(System.Text.Encoding.Default.GetString(array));
  171. //str.Remove(0, i);
  172. //str.Remove(i + _length - 1, str.Length - i - _length);
  173. break;
  174. }
  175. }
  176. }
  177. if (GetData.Length > _length * 3 && !bValidate)
  178. {
  179. LOG.Write(errdevice, Module, $"Receive invalidate data:{str} ");
  180. }
  181. }
  182. }
  183. public void DataReceived(object sender, SerialDataReceivedEventArgs e)
  184. {
  185. if (!_port.IsOpen)
  186. {
  187. //LOG.Write($"discard {_port.PortName} received data, but port not open");
  188. return;
  189. }
  190. timeoutStopWatch.Restart();
  191. if (_isAsciiMode)
  192. {
  193. AsciiDataReceived();
  194. }
  195. else
  196. {
  197. BinaryDataReceived();
  198. }
  199. }
  200. private void AsciiDataReceived()
  201. {
  202. string str = _port.ReadExisting(); //字符串方式读
  203. _buff += str;
  204. int index = _buff.LastIndexOf(_port.NewLine, StringComparison.Ordinal);
  205. if (index > 0)
  206. {
  207. index += _port.NewLine.Length;
  208. string msg = _buff.Substring(0, index);
  209. _buff = _buff.Substring(index);
  210. if (EnableLog)
  211. {
  212. //LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, msg));
  213. }
  214. if (OnDataChanged != null)
  215. OnDataChanged(msg);
  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. }
  235. if (OnBinaryDataChanged != null)
  236. OnBinaryDataChanged(buffer);
  237. }
  238. void ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
  239. {
  240. string reason = string.Format("Communication {0} {1}.", _port.PortName, e.EventType.ToString());
  241. //LOG.Error(reason);
  242. ProcessError(reason);
  243. }
  244. public void ClearPortBuffer()
  245. {
  246. _port.DiscardInBuffer();
  247. _port.DiscardOutBuffer();
  248. }
  249. void ProcessError(string reason)
  250. {
  251. if (OnErrorHappened != null)
  252. OnErrorHappened(reason);
  253. }
  254. bool GetEnableFlag(string portName)
  255. {
  256. if (_EnableLog == null)
  257. {
  258. Process cur = Process.GetCurrentProcess();
  259. if (cur.ProcessName != "Venus_RT")
  260. return false;
  261. string[] strArray = SC.GetStringValue("System.COMLogFlag").Split(',');
  262. int[] bitData = new int[8];
  263. for (int i = 0; i < strArray.Length; i++)
  264. {
  265. if (int.TryParse(strArray[i], System.Globalization.NumberStyles.HexNumber, null, out int Flag))
  266. {
  267. bitData[i] = Flag;
  268. }
  269. else
  270. {
  271. bitData[i] = 0;
  272. LOG.Write(eEvent.WARN_DEVICE_INFO, "System", $"Parse System.COMLogFlag failed: {strArray[i]}.");
  273. }
  274. }
  275. _EnableLog = new BitArray(bitData);
  276. }
  277. if (int.TryParse(portName.Substring(3), out int nCom))
  278. {
  279. if (_EnableLog.Length > nCom)
  280. {
  281. return _EnableLog[nCom];
  282. }
  283. }
  284. return false;
  285. }
  286. public bool ReConnect(string com = null)
  287. {
  288. if (IsConnected==true)
  289. {
  290. return true;
  291. }
  292. Close();
  293. string[] coms = SerialPort.GetPortNames();
  294. string newPortName = com == null ? PortName : com;
  295. for (int i = 0; i < coms.Length; i++)
  296. {
  297. if (coms[i].ToUpper() == newPortName)
  298. {
  299. if (_port.IsOpen)
  300. {
  301. return true;
  302. }
  303. else
  304. {
  305. _port.PortName = newPortName;
  306. Open();
  307. return _port.IsOpen;
  308. }
  309. }
  310. }
  311. return false;
  312. }
  313. }
  314. }