You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

378 rivejä
15 KiB

  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 = new MqttApplicationMessage(
  195. publishPacket.Topic,
  196. publishPacket.Payload,
  197. publishPacket.QualityOfServiceLevel,
  198. publishPacket.Retain
  199. );
  200. ApplicationMessageReceived?.Invoke(this, new MqttApplicationMessageReceivedEventArgs(applicationMessage));
  201. }
  202. private Task ProcessReceivedPublishPacket(MqttPublishPacket publishPacket)
  203. {
  204. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
  205. {
  206. FireApplicationMessageReceivedEvent(publishPacket);
  207. return Task.FromResult(0);
  208. }
  209. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
  210. {
  211. FireApplicationMessageReceivedEvent(publishPacket);
  212. return SendAsync(new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  213. }
  214. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
  215. {
  216. _pendingExactlyOncePublishPackets[publishPacket.PacketIdentifier] = publishPacket;
  217. return SendAsync(new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  218. }
  219. throw new InvalidOperationException();
  220. }
  221. private async Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket)
  222. {
  223. MqttPublishPacket originalPublishPacket;
  224. if (!_pendingExactlyOncePublishPackets.TryRemove(pubRelPacket.PacketIdentifier, out originalPublishPacket))
  225. {
  226. throw new MqttCommunicationException();
  227. }
  228. await SendAsync(originalPublishPacket.CreateResponse<MqttPubCompPacket>());
  229. FireApplicationMessageReceivedEvent(originalPublishPacket);
  230. }
  231. private Task SendAsync(MqttBasePacket packet)
  232. {
  233. return _adapter.SendPacketAsync(packet, _options.DefaultCommunicationTimeout);
  234. }
  235. private async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttBasePacket requestPacket) where TResponsePacket : MqttBasePacket
  236. {
  237. bool ResponsePacketSelector(MqttBasePacket p)
  238. {
  239. var p1 = p as TResponsePacket;
  240. if (p1 == null)
  241. {
  242. return false;
  243. }
  244. var pi1 = requestPacket as IPacketWithIdentifier;
  245. var pi2 = p as IPacketWithIdentifier;
  246. if (pi1 != null && pi2 != null)
  247. {
  248. if (pi1.PacketIdentifier != pi2.PacketIdentifier)
  249. {
  250. return false;
  251. }
  252. }
  253. return true;
  254. }
  255. await _adapter.SendPacketAsync(requestPacket, _options.DefaultCommunicationTimeout);
  256. return (TResponsePacket)await _packetDispatcher.WaitForPacketAsync(ResponsePacketSelector, _options.DefaultCommunicationTimeout);
  257. }
  258. private ushort GetNewPacketIdentifier()
  259. {
  260. return (ushort)Interlocked.Increment(ref _latestPacketIdentifier);
  261. }
  262. private async Task SendKeepAliveMessagesAsync(CancellationToken cancellationToken)
  263. {
  264. MqttTrace.Information(nameof(MqttClient), "Start sending keep alive packets.");
  265. try
  266. {
  267. while (!cancellationToken.IsCancellationRequested)
  268. {
  269. await Task.Delay(_options.KeepAlivePeriod, cancellationToken);
  270. await SendAndReceiveAsync<MqttPingRespPacket>(new MqttPingReqPacket());
  271. }
  272. }
  273. catch (MqttCommunicationException exception)
  274. {
  275. MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication error while receiving packets.");
  276. }
  277. catch (Exception exception)
  278. {
  279. MqttTrace.Warning(nameof(MqttClient), exception, "Error while sending/receiving keep alive packets.");
  280. }
  281. finally
  282. {
  283. MqttTrace.Information(nameof(MqttClient), "Stopped sending keep alive packets.");
  284. await DisconnectInternalAsync();
  285. }
  286. }
  287. private async Task ReceivePackets(CancellationToken cancellationToken)
  288. {
  289. MqttTrace.Information(nameof(MqttClient), "Start receiving packets.");
  290. try
  291. {
  292. while (!cancellationToken.IsCancellationRequested)
  293. {
  294. var mqttPacket = await _adapter.ReceivePacketAsync(TimeSpan.Zero);
  295. MqttTrace.Information(nameof(MqttClient), $"Received <<< {mqttPacket}");
  296. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  297. Task.Run(() => ProcessReceivedPacketAsync(mqttPacket), cancellationToken);
  298. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  299. }
  300. }
  301. catch (MqttCommunicationException exception)
  302. {
  303. MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication error while receiving packets.");
  304. }
  305. catch (Exception exception)
  306. {
  307. MqttTrace.Error(nameof(MqttClient), exception, "Error while receiving packets.");
  308. }
  309. finally
  310. {
  311. MqttTrace.Information(nameof(MqttClient), "Stopped receiving packets.");
  312. await DisconnectInternalAsync();
  313. }
  314. }
  315. }
  316. }