AsyncSerialPort.cs 11 KB

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