Channel.cs 12 KB

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