SerialCommunication.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. using DefaultEdit.Enums;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO.Ports;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using TouchSocket.Core;
  9. using TouchSocket.SerialPorts;
  10. using TouchSocket.Sockets;
  11. namespace DefaultEdit.Communication
  12. {
  13. public class SerialCommunication : IDisposable
  14. {
  15. /// <summary>
  16. /// 串口名称
  17. /// </summary>
  18. public string PortName { get; private set; }
  19. /// <summary>
  20. /// 波特率
  21. /// </summary>
  22. public int BaudRate { get; private set; }
  23. /// <summary>
  24. /// 奇偶校验位
  25. /// </summary>
  26. public Parity Parity { get; private set; }
  27. /// <summary>
  28. /// 停止位
  29. /// </summary>
  30. public StopBits StopBits { get; private set; }
  31. /// <summary>
  32. /// 数据位
  33. /// </summary>
  34. public int DataBits { get; private set; }
  35. public Encoding Encoding { get; set; } = Encoding.ASCII;
  36. /// <summary>
  37. /// 当前连接状态
  38. /// </summary>
  39. public bool IsConnected
  40. {
  41. get
  42. {
  43. if ( client != null )
  44. {
  45. return client.Online;
  46. }
  47. else
  48. {
  49. return false;
  50. }
  51. }
  52. }
  53. private SerialPortClient client;
  54. private IWaitingClient<ISerialPortClient, IReceiverResult> WaitClient;
  55. /// <summary>
  56. /// 接收到的数据
  57. /// </summary>
  58. public string Data { get; private set; }
  59. /// <summary>
  60. /// 连接状态变化事件
  61. /// </summary>
  62. public event Action<SerialCommunication, bool> ConnectionChanged;
  63. /// <summary>
  64. /// 数据接收事件
  65. /// </summary>
  66. public event Action<SerialCommunication, string> DataReceived;
  67. /// <summary>
  68. /// 发送数据事件
  69. /// </summary>
  70. public event Action<SerialCommunication, string> SendData;
  71. public Terminator terminator;
  72. public SerialCommunication(Terminator terminator, string portName, int baudRate = 9600, Parity parity = Parity.None, StopBits stopBits = StopBits.One, int dataBits = 8)
  73. {
  74. PortName = portName;
  75. BaudRate = baudRate;
  76. Parity = parity;
  77. StopBits = stopBits;
  78. DataBits = dataBits;
  79. client = new SerialPortClient();
  80. client.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到端口
  81. client.Connected = (client, e) =>
  82. {
  83. ConnectionChanged?.Invoke(this, IsConnected);
  84. return EasyTask.CompletedTask;
  85. };//成功连接到端口
  86. client.Closing = (client, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
  87. client.Closed = (client, e) =>
  88. {
  89. ConnectionChanged?.Invoke(this, IsConnected);
  90. return EasyTask.CompletedTask;
  91. };//从端口断开连接,当连接不成功时不会触发。
  92. client.Received = async (c, e) =>
  93. {
  94. Data = e.ByteBlock.Span.ToString(Encoding); //接收到数据
  95. DataReceived?.Invoke(this, Data);
  96. };
  97. TouchSocketConfig touchSocket = new TouchSocketConfig();
  98. touchSocket.SetSerialPortOption(new SerialPortOption()
  99. {
  100. BaudRate = BaudRate,//波特率
  101. DataBits = DataBits,//数据位
  102. Parity = Parity,//校验位
  103. PortName = PortName,//COM
  104. StopBits = StopBits//停止位
  105. });
  106. if ( terminator == Terminator.None )
  107. {
  108. touchSocket.SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromSeconds(0.8) });
  109. }
  110. if ( terminator == Terminator.CRLF )
  111. {
  112. touchSocket.SetSerialDataHandlingAdapter(() => new TerminatorPackageAdapter("\r\n"));
  113. }
  114. client.Setup(touchSocket);
  115. }
  116. /// <summary>
  117. /// 异步连接到串口扫描枪
  118. /// </summary>
  119. /// <returns></returns>
  120. public async Task<bool> ConnectAsync()
  121. {
  122. if ( ( await client.TryConnectAsync() ).IsSuccess )
  123. {
  124. ConnectionChanged?.Invoke(this, IsConnected);
  125. //调用CreateWaitingClient获取到IWaitingClient的对象。
  126. WaitClient = client.CreateWaitingClient(new WaitingOptions()
  127. {
  128. FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
  129. {
  130. return true;
  131. }
  132. });
  133. return true;
  134. }
  135. return false;
  136. }
  137. /// <summary>
  138. /// 连接到串口扫描枪
  139. /// </summary>
  140. /// <returns></returns>
  141. public bool Connect()
  142. {
  143. if ( client.TryConnect().IsSuccess )//尝试连接到端口
  144. {
  145. //调用CreateWaitingClient获取到IWaitingClient的对象。
  146. WaitClient = client.CreateWaitingClient(new WaitingOptions()
  147. {
  148. FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
  149. {
  150. return true;
  151. }
  152. });
  153. return true;
  154. }
  155. return false;
  156. }
  157. /// <summary>
  158. /// 断开连接到串口扫描枪
  159. /// </summary>
  160. public void Disconnect()
  161. {
  162. if ( IsConnected )
  163. {
  164. client.Close();
  165. ConnectionChanged?.Invoke(this, IsConnected);
  166. }
  167. }
  168. /// <summary>
  169. /// 发送数据到串口扫描枪,并等待返回数据。
  170. /// </summary>
  171. /// <param name="msg"></param>
  172. /// <param name="millisecondsTimeout"></param>
  173. /// <returns></returns>
  174. public string SendThenReturn(string msg, int millisecondsTimeout = 5000)
  175. {
  176. //然后使用SendThenReturn。
  177. SendData?.Invoke(this, msg);
  178. byte[] returnData = WaitClient.SendThenReturn(Encoding.GetBytes(msg), millisecondsTimeout);
  179. DataReceived?.Invoke(this, Encoding.GetString(returnData));
  180. return Encoding.GetString(returnData);
  181. }
  182. /// <summary>
  183. /// 异步发送数据到串口扫描枪,并等待返回数据。
  184. /// </summary>
  185. /// <param name="msg"></param>
  186. /// <param name="millisecondsTimeout"></param>
  187. /// <returns></returns>
  188. public async Task<string> SendThenReturnAsync(string msg, int millisecondsTimeout = 5000)
  189. {
  190. SendData?.Invoke(this, msg);
  191. byte[] returnData = await WaitClient.SendThenReturnAsync(Encoding.GetBytes(msg), millisecondsTimeout);
  192. DataReceived?.Invoke(this, Encoding.GetString(returnData));
  193. return Encoding.GetString(returnData);
  194. }
  195. /// <summary>
  196. /// 发送数据到串口扫描枪
  197. /// </summary>
  198. /// <param name="msg"></param>
  199. public void Send(string msg)
  200. {
  201. if ( IsConnected )
  202. {
  203. SendData?.Invoke(this, msg);
  204. client.Send(Encoding.GetBytes(msg)); //发送数据到串口扫描枪
  205. }
  206. }
  207. public void Dispose()
  208. {
  209. if ( WaitClient != null )
  210. {
  211. WaitClient = null;
  212. }
  213. if ( client != null )
  214. {
  215. client.Dispose();
  216. client = null;
  217. }
  218. }
  219. }
  220. }