Channel.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. using ivf_tl_Entity.GlobalEnums;
  2. using System.IO.Ports;
  3. namespace ivf_tl_Entity.ComEntitys
  4. {
  5. /// <summary>
  6. /// 串口发送接收助手
  7. /// </summary>
  8. public class Channel
  9. {
  10. /// <summary>
  11. /// 异常日志
  12. /// 异常、名称、参数
  13. /// </summary>
  14. public event Action<Exception, string, string, LogEnum> ExceptionLogEvent;
  15. /// <summary>
  16. /// 错误日志
  17. /// </summary>
  18. public event Action<string, LogEnum> ErrorLogEvent;
  19. /// <summary>
  20. /// 指令记录日志
  21. /// </summary>
  22. public event Action<int, DateTime, string, LogEnum> CommandLogEvent;
  23. /// <summary>
  24. /// 接收指令
  25. /// </summary>
  26. public event Action<CustomProtocol> DataReceived;
  27. /// <summary>
  28. ///
  29. /// </summary>
  30. /// <param name="house"></param>
  31. /// <param name="comName"></param>
  32. /// <param name="bufferManagerSize"></param>
  33. /// <param name="BaudRate"></param>
  34. /// <param name="DataBits"></param>
  35. /// <param name="stopBits"></param>
  36. /// <param name="parity"></param>
  37. /// <param name="ReadTimeout"></param>
  38. /// <param name="WriteTimeout"></param>
  39. public Channel(int house, string comName, int bufferManagerSize, int BaudRate, int DataBits, StopBits stopBits, Parity parity, int ReadTimeout, int WriteTimeout)
  40. {
  41. _comName = comName;
  42. _house = house;
  43. _bufferManagerSize = bufferManagerSize;
  44. _baudRate = BaudRate;
  45. _dataBits = DataBits;
  46. _stopBits = stopBits;
  47. _parity = parity;
  48. _readTimeout = ReadTimeout;
  49. _writeTimeout = WriteTimeout;
  50. ringBufferManager = new RingBufferManager(_bufferManagerSize);
  51. GetSerialPortValue(_house, _comName, _baudRate, _dataBits, _stopBits, _parity, _readTimeout, _writeTimeout);
  52. }
  53. /// <summary>
  54. ///
  55. /// </summary>
  56. /// <param name="house"></param>
  57. /// <param name="comName"></param>
  58. public Channel(int house, string comName)
  59. {
  60. _comName = comName;
  61. _house = house;
  62. ringBufferManager = new RingBufferManager(_bufferManagerSize);
  63. GetSerialPortValue(_house, _comName, _baudRate, _dataBits, _stopBits, _parity, _readTimeout, _writeTimeout);
  64. }
  65. public RingBufferManager ringBufferManager;
  66. public SerialPort serialPort;
  67. private CustomProtocol customProtocol;
  68. private int _house = 0;
  69. private string _comName;
  70. private int _bufferManagerSize = 1024;
  71. /// <summary>
  72. /// 波特率
  73. /// </summary>
  74. private int _baudRate = 9600;
  75. /// <summary>
  76. /// 数据位
  77. /// </summary>
  78. private int _dataBits = 8;
  79. /// <summary>
  80. /// 停止位
  81. /// </summary>
  82. private StopBits _stopBits = StopBits.One;
  83. /// <summary>
  84. /// 奇偶校验位
  85. /// </summary>
  86. private Parity _parity = Parity.None;
  87. /// <summary>
  88. /// 串口读取超时
  89. /// </summary>
  90. private int _readTimeout = 3000;
  91. /// <summary>
  92. /// 串口写入超时
  93. /// </summary>
  94. private int _writeTimeout = 3000;
  95. /// <summary>
  96. /// 获取实例
  97. /// </summary>
  98. /// <param name="house">houseid</param>
  99. /// <param name="comName">串口名称</param>
  100. /// <param name="bufferManagerSize">缓冲区大小</param>
  101. /// <param name="BaudRate">波特率</param>
  102. /// <param name="DataBits">数据位</param>
  103. /// <param name="stopBits">停止位</param>
  104. /// <param name="parity">奇偶校验位</param>
  105. /// <param name="ReadTimeout">串口读取超时</param>
  106. /// <param name="WriteTimeout">串口写入超时</param>
  107. /// <returns></returns>
  108. public bool GetSerialPortValue(int house, string comName, int BaudRate, int DataBits, StopBits stopBits, Parity parity, int ReadTimeout, int WriteTimeout)
  109. {
  110. try
  111. {
  112. serialPort = new SerialPort();
  113. serialPort.PortName = comName;
  114. //波特率
  115. serialPort.BaudRate = BaudRate;
  116. //数据位
  117. serialPort.DataBits = DataBits;
  118. //两个停止位
  119. serialPort.StopBits = stopBits;
  120. //无奇偶校验位
  121. serialPort.Parity = parity;
  122. serialPort.ReadTimeout = ReadTimeout;
  123. serialPort.WriteTimeout = WriteTimeout;
  124. serialPort.DataReceived += SerialPort_DataReceived;
  125. return true;
  126. }
  127. catch (Exception ex)
  128. {
  129. ExceptionLogEvent?.Invoke(ex, $"[{_house}][{_comName}]创建SerialPort实例", $"[house:{house}][com:{comName}]", LogEnum.RunException);
  130. return false;
  131. }
  132. }
  133. /// <summary>
  134. /// 接收数据
  135. /// </summary>
  136. /// <param name="sender"></param>
  137. /// <param name="e"></param>
  138. /// <exception cref="NotImplementedException"></exception>
  139. private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
  140. {
  141. string loginfo = $"[{_house}][{customProtocol.comName}][{customProtocol.commandNumber}][{customProtocol.commandType}]";
  142. try
  143. {
  144. DateTime dateTime = DateTime.Now;
  145. byte[] buffer = new byte[serialPort.BytesToRead];
  146. serialPort.Read(buffer, 0, buffer.Length);
  147. CommandLogEvent?.Invoke(_house, DateTime.Now, $"{loginfo}[Rec:{StringHelper.ByteToHexStr(buffer)}]", LogEnum.PortComRecord);
  148. ringBufferManager.WriteBuffer(buffer, 0, buffer.Length);
  149. if (ringBufferManager.DataCount >= customProtocol.lenght)
  150. {
  151. if (ringBufferManager.DataCount > customProtocol.lenght)
  152. {
  153. ErrorLogEvent?.Invoke($"{loginfo}缓冲区字节数大于预期", LogEnum.RunError);
  154. }
  155. byte[] receivedBuffer = new byte[customProtocol.lenght];
  156. ringBufferManager.ReadBuffer(receivedBuffer, 0, customProtocol.lenght);
  157. //ringBufferManager.Clear(customProtocol.lenght);
  158. ringBufferManager.Clear();
  159. customProtocol.receivedBuffer = receivedBuffer;
  160. if (customProtocol.receivedBuffer[customProtocol.lenght - 2] != 0)
  161. {
  162. customProtocol.IsSuccess = false;
  163. ErrorLogEvent?.Invoke($"{loginfo}[Send:{StringHelper.ByteToHexStr(customProtocol.sendBuffer)}][Receive:{StringHelper.ByteToHexStr(customProtocol.receivedBuffer)}]下位机操作失败回复", LogEnum.RunError);
  164. }
  165. var check = Commander.CheckORC(customProtocol.receivedBuffer);
  166. CommandLogEvent?.Invoke(_house, DateTime.Now, $"{loginfo}[Send:{StringHelper.ByteToHexStr(customProtocol.sendBuffer)}][Receive:{StringHelper.ByteToHexStr(customProtocol.receivedBuffer)}][校验结果:{check}]", LogEnum.HouseComRecord);
  167. if (!check)
  168. {
  169. ErrorLogEvent?.Invoke($"{loginfo}[Send:{StringHelper.ByteToHexStr(customProtocol.sendBuffer)}][Receive:{StringHelper.ByteToHexStr(customProtocol.receivedBuffer)}]下位机回复校验失败", LogEnum.RunError);
  170. }
  171. CommandLogEvent?.Invoke(_house, DateTime.Now, $"{loginfo}[Send:{StringHelper.ByteToHexStr(customProtocol.sendBuffer)}][Receive:{StringHelper.ByteToHexStr(customProtocol.receivedBuffer)}]", LogEnum.PortComRecord);
  172. DataReceived?.Invoke(customProtocol);
  173. }
  174. }
  175. catch (Exception ex)
  176. {
  177. string canshu = $"{loginfo}[Send:{StringHelper.ByteToHexStr(customProtocol.sendBuffer)}]";
  178. ExceptionLogEvent?.Invoke(ex, $"[{_house}][{customProtocol.comName}][{customProtocol.commandNumber}]串口接收数据", canshu, LogEnum.RunException);
  179. }
  180. }
  181. /// <summary>
  182. /// 发送数据
  183. /// </summary>
  184. /// <param name="protocol"></param>
  185. public bool Send(CustomProtocol protocol)
  186. {
  187. customProtocol = protocol;
  188. customProtocol.comName = _comName;
  189. string logInfo = $"[{_house}][{protocol.comName}][{protocol.commandNumber}][{protocol.commandType}][Send:{StringHelper.ByteToHexStr(protocol.sendBuffer)}]";
  190. try
  191. {
  192. serialPort.Write(customProtocol.sendBuffer, 0, customProtocol.sendBuffer.Length);
  193. CommandLogEvent?.Invoke(_house, DateTime.Now, logInfo, LogEnum.PortComRecord);
  194. return true;
  195. }
  196. catch (Exception e1)
  197. {
  198. ExceptionLogEvent?.Invoke(e1, $"[{_house}][{_comName}]发送指令", logInfo, LogEnum.RunException);
  199. return false;
  200. }
  201. }
  202. /// <summary>
  203. /// 打开串口
  204. /// </summary>
  205. public bool OpenPort()
  206. {
  207. try
  208. {
  209. serialPort.Open();
  210. return true;
  211. }
  212. catch (Exception ex)
  213. {
  214. ExceptionLogEvent?.Invoke(ex, $"{_house}模块{serialPort.PortName}串口打开", null, LogEnum.RunException);
  215. return false;
  216. }
  217. }
  218. /// <summary>
  219. /// 关闭串口
  220. /// </summary>
  221. public bool ClosePort()
  222. {
  223. try
  224. {
  225. serialPort.Close();
  226. return true;
  227. }
  228. catch (Exception ex)
  229. {
  230. ExceptionLogEvent?.Invoke(ex, $"{_house}模块{serialPort.PortName}串口关闭", null, LogEnum.RunException);
  231. return false;
  232. }
  233. }
  234. /// <summary>
  235. /// 清理串口缓冲区
  236. /// </summary>
  237. /// <returns></returns>
  238. public bool DiscardPortBuffer()
  239. {
  240. try
  241. {
  242. serialPort.DiscardInBuffer();
  243. serialPort.DiscardOutBuffer();
  244. return true;
  245. }
  246. catch (Exception ex)
  247. {
  248. ExceptionLogEvent?.Invoke(ex, $"[{_house}][{_comName}]清理串口缓冲区", null, LogEnum.RunException);
  249. return false;
  250. }
  251. }
  252. /// <summary>
  253. /// 释放串口类
  254. /// </summary>
  255. /// <returns></returns>
  256. public bool PortDispose()
  257. {
  258. try
  259. {
  260. serialPort.Dispose();
  261. return true;
  262. }
  263. catch (Exception ex)
  264. {
  265. ExceptionLogEvent?.Invoke(ex, $"[{_house}][{_comName}]释放串口类", null, LogEnum.RunException);
  266. return false;
  267. }
  268. }
  269. /// <summary>
  270. /// 重新打开串口
  271. /// </summary>
  272. /// <returns></returns>
  273. public bool ReopenPort()
  274. {
  275. ringBufferManager.Clear();
  276. for (int i = 0; i < 3; i++)
  277. {
  278. try
  279. {
  280. bool DiscardBuffer = DiscardPortBuffer();
  281. bool closePort = ClosePort();
  282. bool portdispose = PortDispose();
  283. var a = GetSerialPortValue(_house, _comName, _baudRate, _dataBits, _stopBits, _parity, _readTimeout, _writeTimeout);
  284. if (a)
  285. {
  286. var b = OpenPort();
  287. if (b)
  288. {
  289. return true;
  290. }
  291. }
  292. }
  293. catch (Exception ex)
  294. {
  295. ExceptionLogEvent?.Invoke(ex, $"[{_house}][{_comName}]重新打开串口", null, LogEnum.RunException);
  296. }
  297. }
  298. return false;
  299. }
  300. }
  301. }