Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

MqttClient.cs 15 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MQTTnet.Core.Adapter;
  8. using MQTTnet.Core.Diagnostics;
  9. using MQTTnet.Core.Exceptions;
  10. using MQTTnet.Core.Internal;
  11. using MQTTnet.Core.Packets;
  12. using MQTTnet.Core.Protocol;
  13. namespace MQTTnet.Core.Client
  14. {
  15. public class MqttClient
  16. {
  17. private readonly ConcurrentDictionary<ushort, MqttPublishPacket> _pendingExactlyOncePublishPackets = new ConcurrentDictionary<ushort, MqttPublishPacket>();
  18. private readonly HashSet<ushort> _processedPublishPackets = new HashSet<ushort>();
  19. private readonly MqttPacketDispatcher _packetDispatcher = new MqttPacketDispatcher();
  20. private readonly MqttClientOptions _options;
  21. private readonly IMqttCommunicationAdapter _adapter;
  22. private int _latestPacketIdentifier;
  23. private CancellationTokenSource _cancellationTokenSource;
  24. public MqttClient(MqttClientOptions options, IMqttCommunicationAdapter adapter)
  25. {
  26. _options = options ?? throw new ArgumentNullException(nameof(options));
  27. _adapter = adapter ?? throw new ArgumentNullException(nameof(adapter));
  28. }
  29. public event EventHandler Connected;
  30. public event EventHandler Disconnected;
  31. public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
  32. public bool IsConnected { get; private set; }
  33. public async Task ConnectAsync(MqttApplicationMessage willApplicationMessage = null)
  34. {
  35. MqttTrace.Verbose(nameof(MqttClient), "Trying to connect.");
  36. if (IsConnected)
  37. {
  38. throw new MqttProtocolViolationException("It is not allowed to connect with a server after the connection is established.");
  39. }
  40. var connectPacket = new MqttConnectPacket
  41. {
  42. ClientId = _options.ClientId,
  43. Username = _options.UserName,
  44. Password = _options.Password,
  45. CleanSession = _options.CleanSession,
  46. KeepAlivePeriod = (ushort)_options.KeepAlivePeriod.TotalSeconds,
  47. WillMessage = willApplicationMessage
  48. };
  49. await _adapter.ConnectAsync(_options, _options.DefaultCommunicationTimeout);
  50. MqttTrace.Verbose(nameof(MqttClient), "Connection with server established.");
  51. _cancellationTokenSource = new CancellationTokenSource();
  52. _latestPacketIdentifier = 0;
  53. _processedPublishPackets.Clear();
  54. _packetDispatcher.Reset();
  55. IsConnected = true;
  56. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  57. Task.Run(() => ReceivePackets(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  58. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  59. var response = await SendAndReceiveAsync<MqttConnAckPacket>(connectPacket);
  60. if (response.ConnectReturnCode != MqttConnectReturnCode.ConnectionAccepted)
  61. {
  62. await DisconnectAsync();
  63. throw new MqttConnectingFailedException(response.ConnectReturnCode);
  64. }
  65. if (_options.KeepAlivePeriod != TimeSpan.Zero)
  66. {
  67. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  68. Task.Run(() => SendKeepAliveMessagesAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  69. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  70. }
  71. Connected?.Invoke(this, EventArgs.Empty);
  72. }
  73. public async Task DisconnectAsync()
  74. {
  75. await SendAsync(new MqttDisconnectPacket());
  76. await DisconnectInternalAsync();
  77. }
  78. public Task<IList<MqttSubscribeResult>> SubscribeAsync(params TopicFilter[] topicFilters)
  79. {
  80. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  81. return SubscribeAsync(topicFilters.ToList());
  82. }
  83. public async Task<IList<MqttSubscribeResult>> SubscribeAsync(IList<TopicFilter> topicFilters)
  84. {
  85. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  86. if (!topicFilters.Any()) throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.8.3-3].");
  87. ThrowIfNotConnected();
  88. var subscribePacket = new MqttSubscribePacket
  89. {
  90. PacketIdentifier = GetNewPacketIdentifier(),
  91. TopicFilters = topicFilters
  92. };
  93. var response = await SendAndReceiveAsync<MqttSubAckPacket>(subscribePacket);
  94. if (response.SubscribeReturnCodes.Count != topicFilters.Count)
  95. {
  96. throw new MqttProtocolViolationException("The return codes are not matching the topic filters [MQTT-3.9.3-1].");
  97. }
  98. return topicFilters.Select((t, i) => new MqttSubscribeResult(t, response.SubscribeReturnCodes[i])).ToList();
  99. }
  100. public Task Unsubscribe(params string[] topicFilters)
  101. {
  102. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  103. return Unsubscribe(topicFilters.ToList());
  104. }
  105. public async Task Unsubscribe(IList<string> topicFilters)
  106. {
  107. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  108. if (!topicFilters.Any()) throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.10.3-2].");
  109. ThrowIfNotConnected();
  110. var unsubscribePacket = new MqttUnsubscribePacket
  111. {
  112. PacketIdentifier = GetNewPacketIdentifier(),
  113. TopicFilters = topicFilters
  114. };
  115. await SendAndReceiveAsync<MqttUnsubAckPacket>(unsubscribePacket);
  116. }
  117. public async Task PublishAsync(MqttApplicationMessage applicationMessage)
  118. {
  119. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  120. ThrowIfNotConnected();
  121. var publishPacket = applicationMessage.ToPublishPacket();
  122. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
  123. {
  124. await SendAsync(publishPacket);
  125. }
  126. else if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
  127. {
  128. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  129. await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket);
  130. }
  131. else if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
  132. {
  133. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  134. await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket);
  135. await SendAsync(publishPacket.CreateResponse<MqttPubCompPacket>());
  136. }
  137. }
  138. private void ThrowIfNotConnected()
  139. {
  140. if (!IsConnected) throw new MqttCommunicationException("The client is not connected.");
  141. }
  142. private async Task DisconnectInternalAsync()
  143. {
  144. try
  145. {
  146. await _adapter.DisconnectAsync();
  147. }
  148. catch
  149. {
  150. }
  151. finally
  152. {
  153. _cancellationTokenSource?.Cancel();
  154. IsConnected = false;
  155. Disconnected?.Invoke(this, EventArgs.Empty);
  156. }
  157. }
  158. private Task ProcessReceivedPacketAsync(MqttBasePacket mqttPacket)
  159. {
  160. try
  161. {
  162. if (mqttPacket is MqttPingReqPacket)
  163. {
  164. return SendAsync(new MqttPingRespPacket());
  165. }
  166. if (mqttPacket is MqttDisconnectPacket)
  167. {
  168. return DisconnectAsync();
  169. }
  170. var publishPacket = mqttPacket as MqttPublishPacket;
  171. if (publishPacket != null)
  172. {
  173. return ProcessReceivedPublishPacket(publishPacket);
  174. }
  175. var pubRelPacket = mqttPacket as MqttPubRelPacket;
  176. if (pubRelPacket != null)
  177. {
  178. return ProcessReceivedPubRelPacket(pubRelPacket);
  179. }
  180. _packetDispatcher.Dispatch(mqttPacket);
  181. }
  182. catch (Exception exception)
  183. {
  184. MqttTrace.Error(nameof(MqttClient), exception, "Error while processing received packet.");
  185. }
  186. return Task.FromResult(0);
  187. }
  188. private void FireApplicationMessageReceivedEvent(MqttPublishPacket publishPacket)
  189. {
  190. if (publishPacket.QualityOfServiceLevel != MqttQualityOfServiceLevel.AtMostOnce)
  191. {
  192. _processedPublishPackets.Add(publishPacket.PacketIdentifier);
  193. }
  194. var applicationMessage = publishPacket.ToApplicationMessage();
  195. ApplicationMessageReceived?.Invoke(this, new MqttApplicationMessageReceivedEventArgs(applicationMessage));
  196. }
  197. private Task ProcessReceivedPublishPacket(MqttPublishPacket publishPacket)
  198. {
  199. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
  200. {
  201. FireApplicationMessageReceivedEvent(publishPacket);
  202. return Task.FromResult(0);
  203. }
  204. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
  205. {
  206. FireApplicationMessageReceivedEvent(publishPacket);
  207. return SendAsync(new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  208. }
  209. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
  210. {
  211. _pendingExactlyOncePublishPackets[publishPacket.PacketIdentifier] = publishPacket;
  212. return SendAsync(new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  213. }
  214. throw new InvalidOperationException();
  215. }
  216. private async Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket)
  217. {
  218. MqttPublishPacket originalPublishPacket;
  219. if (!_pendingExactlyOncePublishPackets.TryRemove(pubRelPacket.PacketIdentifier, out originalPublishPacket))
  220. {
  221. throw new MqttCommunicationException();
  222. }
  223. await SendAsync(originalPublishPacket.CreateResponse<MqttPubCompPacket>());
  224. FireApplicationMessageReceivedEvent(originalPublishPacket);
  225. }
  226. private Task SendAsync(MqttBasePacket packet)
  227. {
  228. return _adapter.SendPacketAsync(packet, _options.DefaultCommunicationTimeout);
  229. }
  230. private async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttBasePacket requestPacket) where TResponsePacket : MqttBasePacket
  231. {
  232. bool ResponsePacketSelector(MqttBasePacket p)
  233. {
  234. var p1 = p as TResponsePacket;
  235. if (p1 == null)
  236. {
  237. return false;
  238. }
  239. var pi1 = requestPacket as IPacketWithIdentifier;
  240. var pi2 = p as IPacketWithIdentifier;
  241. if (pi1 != null && pi2 != null)
  242. {
  243. if (pi1.PacketIdentifier != pi2.PacketIdentifier)
  244. {
  245. return false;
  246. }
  247. }
  248. return true;
  249. }
  250. await _adapter.SendPacketAsync(requestPacket, _options.DefaultCommunicationTimeout);
  251. return (TResponsePacket)await _packetDispatcher.WaitForPacketAsync(ResponsePacketSelector, _options.DefaultCommunicationTimeout);
  252. }
  253. private ushort GetNewPacketIdentifier()
  254. {
  255. return (ushort)Interlocked.Increment(ref _latestPacketIdentifier);
  256. }
  257. private async Task SendKeepAliveMessagesAsync(CancellationToken cancellationToken)
  258. {
  259. MqttTrace.Information(nameof(MqttClient), "Start sending keep alive packets.");
  260. try
  261. {
  262. while (!cancellationToken.IsCancellationRequested)
  263. {
  264. await Task.Delay(_options.KeepAlivePeriod, cancellationToken);
  265. await SendAndReceiveAsync<MqttPingRespPacket>(new MqttPingReqPacket());
  266. }
  267. }
  268. catch (MqttCommunicationException exception)
  269. {
  270. MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication error while receiving packets.");
  271. }
  272. catch (Exception exception)
  273. {
  274. MqttTrace.Warning(nameof(MqttClient), exception, "Error while sending/receiving keep alive packets.");
  275. }
  276. finally
  277. {
  278. MqttTrace.Information(nameof(MqttClient), "Stopped sending keep alive packets.");
  279. await DisconnectInternalAsync();
  280. }
  281. }
  282. private async Task ReceivePackets(CancellationToken cancellationToken)
  283. {
  284. MqttTrace.Information(nameof(MqttClient), "Start receiving packets.");
  285. try
  286. {
  287. while (!cancellationToken.IsCancellationRequested)
  288. {
  289. var mqttPacket = await _adapter.ReceivePacketAsync(TimeSpan.Zero);
  290. MqttTrace.Information(nameof(MqttClient), $"Received <<< {mqttPacket}");
  291. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  292. Task.Run(() => ProcessReceivedPacketAsync(mqttPacket), cancellationToken);
  293. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  294. }
  295. }
  296. catch (MqttCommunicationException exception)
  297. {
  298. MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication error while receiving packets.");
  299. }
  300. catch (Exception exception)
  301. {
  302. MqttTrace.Error(nameof(MqttClient), exception, "Error while receiving packets.");
  303. }
  304. finally
  305. {
  306. MqttTrace.Information(nameof(MqttClient), "Stopped receiving packets.");
  307. await DisconnectInternalAsync();
  308. }
  309. }
  310. }
  311. }