Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

473 řádky
19 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MQTTnet.Core.Adapter;
  7. using MQTTnet.Core.Exceptions;
  8. using MQTTnet.Core.Internal;
  9. using MQTTnet.Core.Packets;
  10. using MQTTnet.Core.Protocol;
  11. using Microsoft.Extensions.Logging;
  12. namespace MQTTnet.Core.Client
  13. {
  14. public class MqttClient : IMqttClient
  15. {
  16. private readonly HashSet<ushort> _unacknowledgedPublishPackets = new HashSet<ushort>();
  17. private readonly MqttPacketDispatcher _packetDispatcher;
  18. private readonly IMqttCommunicationAdapterFactory _communicationAdapterFactory;
  19. private readonly ILogger<MqttClient> _logger;
  20. private IMqttClientOptions _options;
  21. private bool _isReceivingPackets;
  22. private int _latestPacketIdentifier;
  23. private CancellationTokenSource _cancellationTokenSource;
  24. private IMqttCommunicationAdapter _adapter;
  25. private IDisposable _scopeHandle;
  26. public MqttClient(IMqttCommunicationAdapterFactory communicationAdapterFactory, ILogger<MqttClient> logger, MqttPacketDispatcher packetDispatcher)
  27. {
  28. _communicationAdapterFactory = communicationAdapterFactory ?? throw new ArgumentNullException(nameof(communicationAdapterFactory));
  29. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  30. _packetDispatcher = packetDispatcher ?? throw new ArgumentNullException(nameof(packetDispatcher));
  31. }
  32. public event EventHandler<MqttClientConnectedEventArgs> Connected;
  33. public event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
  34. public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
  35. public bool IsConnected { get; private set; }
  36. public async Task<MqttClientConnectResult> ConnectAsync(IMqttClientOptions options)
  37. {
  38. if (options == null) throw new ArgumentNullException(nameof(options));
  39. if (options.ChannelOptions == null) throw new ArgumentException("ChannelOptions are not set.");
  40. ThrowIfConnected("It is not allowed to connect with a server after the connection is established.");
  41. try
  42. {
  43. _options = options;
  44. _cancellationTokenSource = new CancellationTokenSource();
  45. _latestPacketIdentifier = 0;
  46. _packetDispatcher.Reset();
  47. _adapter = _communicationAdapterFactory.CreateClientMqttCommunicationAdapter(options);
  48. _scopeHandle = _logger.BeginScope(options.LogId ?? options.ClientId);
  49. _logger.LogTrace("Trying to connect with server.");
  50. await _adapter.ConnectAsync(_options.CommunicationTimeout).ConfigureAwait(false);
  51. _logger.LogTrace("Connection with server established.");
  52. await SetupIncomingPacketProcessingAsync();
  53. var connectResponse = await AuthenticateAsync(options.WillMessage);
  54. _logger.LogTrace("MQTT connection with server established.");
  55. if (_options.KeepAlivePeriod != TimeSpan.Zero)
  56. {
  57. StartSendKeepAliveMessages(_cancellationTokenSource.Token);
  58. }
  59. IsConnected = true;
  60. Connected?.Invoke(this, new MqttClientConnectedEventArgs(connectResponse.IsSessionPresent));
  61. return new MqttClientConnectResult(connectResponse.IsSessionPresent);
  62. }
  63. catch (Exception exception)
  64. {
  65. _logger.LogError(new EventId(), exception, "Error while connecting with server.");
  66. await DisconnectInternalAsync().ConfigureAwait(false);
  67. throw;
  68. }
  69. }
  70. public async Task DisconnectAsync()
  71. {
  72. if (!IsConnected)
  73. {
  74. return;
  75. }
  76. try
  77. {
  78. await SendAsync(new MqttDisconnectPacket()).ConfigureAwait(false);
  79. }
  80. finally
  81. {
  82. await DisconnectInternalAsync().ConfigureAwait(false);
  83. _scopeHandle.Dispose();
  84. }
  85. }
  86. public async Task<IList<MqttSubscribeResult>> SubscribeAsync(IEnumerable<TopicFilter> topicFilters)
  87. {
  88. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  89. ThrowIfNotConnected();
  90. var subscribePacket = new MqttSubscribePacket
  91. {
  92. PacketIdentifier = GetNewPacketIdentifier(),
  93. TopicFilters = topicFilters.ToList()
  94. };
  95. var response = await SendAndReceiveAsync<MqttSubAckPacket>(subscribePacket).ConfigureAwait(false);
  96. if (response.SubscribeReturnCodes.Count != subscribePacket.TopicFilters.Count)
  97. {
  98. throw new MqttProtocolViolationException("The return codes are not matching the topic filters [MQTT-3.9.3-1].");
  99. }
  100. return subscribePacket.TopicFilters.Select((t, i) => new MqttSubscribeResult(t, response.SubscribeReturnCodes[i])).ToList();
  101. }
  102. public async Task UnsubscribeAsync(IEnumerable<string> topicFilters)
  103. {
  104. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  105. ThrowIfNotConnected();
  106. var unsubscribePacket = new MqttUnsubscribePacket
  107. {
  108. PacketIdentifier = GetNewPacketIdentifier(),
  109. TopicFilters = topicFilters.ToList()
  110. };
  111. await SendAndReceiveAsync<MqttUnsubAckPacket>(unsubscribePacket);
  112. }
  113. public async Task PublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages)
  114. {
  115. ThrowIfNotConnected();
  116. var publishPackets = applicationMessages.Select(m => m.ToPublishPacket());
  117. foreach (var qosGroup in publishPackets.GroupBy(p => p.QualityOfServiceLevel))
  118. {
  119. var qosPackets = qosGroup.ToArray();
  120. switch (qosGroup.Key)
  121. {
  122. case MqttQualityOfServiceLevel.AtMostOnce:
  123. {
  124. // No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
  125. await _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, qosPackets);
  126. break;
  127. }
  128. case MqttQualityOfServiceLevel.AtLeastOnce:
  129. {
  130. foreach (var publishPacket in qosPackets)
  131. {
  132. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  133. await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket);
  134. }
  135. break;
  136. }
  137. case MqttQualityOfServiceLevel.ExactlyOnce:
  138. {
  139. foreach (var publishPacket in qosPackets)
  140. {
  141. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  142. var pubRecPacket = await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket).ConfigureAwait(false);
  143. await SendAndReceiveAsync<MqttPubCompPacket>(pubRecPacket.CreateResponse<MqttPubRelPacket>()).ConfigureAwait(false);
  144. }
  145. break;
  146. }
  147. default:
  148. {
  149. throw new InvalidOperationException();
  150. }
  151. }
  152. }
  153. }
  154. private async Task<MqttConnAckPacket> AuthenticateAsync(MqttApplicationMessage willApplicationMessage)
  155. {
  156. var connectPacket = new MqttConnectPacket
  157. {
  158. ClientId = _options.ClientId,
  159. Username = _options.Credentials?.Username,
  160. Password = _options.Credentials?.Password,
  161. CleanSession = _options.CleanSession,
  162. KeepAlivePeriod = (ushort) _options.KeepAlivePeriod.TotalSeconds,
  163. WillMessage = willApplicationMessage
  164. };
  165. var response = await SendAndReceiveAsync<MqttConnAckPacket>(connectPacket).ConfigureAwait(false);
  166. if (response.ConnectReturnCode != MqttConnectReturnCode.ConnectionAccepted)
  167. {
  168. throw new MqttConnectingFailedException(response.ConnectReturnCode);
  169. }
  170. return response;
  171. }
  172. private async Task SetupIncomingPacketProcessingAsync()
  173. {
  174. _isReceivingPackets = false;
  175. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  176. Task.Factory.StartNew(
  177. () => ReceivePackets(_cancellationTokenSource.Token),
  178. _cancellationTokenSource.Token,
  179. TaskCreationOptions.LongRunning,
  180. TaskScheduler.Default).ConfigureAwait(false);
  181. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  182. while (!_isReceivingPackets && _cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested)
  183. {
  184. await Task.Delay(TimeSpan.FromMilliseconds(100));
  185. }
  186. }
  187. private void ThrowIfNotConnected()
  188. {
  189. if (!IsConnected) throw new MqttCommunicationException("The client is not connected.");
  190. }
  191. private void ThrowIfConnected(string message)
  192. {
  193. if (IsConnected) throw new MqttProtocolViolationException(message);
  194. }
  195. private async Task DisconnectInternalAsync()
  196. {
  197. var clientWasConnected = IsConnected;
  198. IsConnected = false;
  199. var cts = _cancellationTokenSource;
  200. if (cts == null || cts.IsCancellationRequested)
  201. {
  202. return;
  203. }
  204. cts.Cancel(false);
  205. cts.Dispose();
  206. _cancellationTokenSource = null;
  207. try
  208. {
  209. await _adapter.DisconnectAsync(_options.CommunicationTimeout).ConfigureAwait(false);
  210. _logger.LogInformation("Disconnected from adapter.");
  211. }
  212. catch (Exception exception)
  213. {
  214. _logger.LogWarning(new EventId(), exception, "Error while disconnecting from adapter.");
  215. }
  216. finally
  217. {
  218. Disconnected?.Invoke(this, new MqttClientDisconnectedEventArgs(clientWasConnected));
  219. }
  220. }
  221. private async Task ProcessReceivedPacketAsync(MqttBasePacket packet)
  222. {
  223. try
  224. {
  225. _logger.LogInformation("Received <<< {0}", packet);
  226. if (packet is MqttPingReqPacket)
  227. {
  228. await SendAsync(new MqttPingRespPacket());
  229. return;
  230. }
  231. if (packet is MqttDisconnectPacket)
  232. {
  233. await DisconnectAsync();
  234. return;
  235. }
  236. if (packet is MqttPublishPacket publishPacket)
  237. {
  238. await ProcessReceivedPublishPacket(publishPacket);
  239. return;
  240. }
  241. if (packet is MqttPubRelPacket pubRelPacket)
  242. {
  243. await ProcessReceivedPubRelPacket(pubRelPacket);
  244. return;
  245. }
  246. _packetDispatcher.Dispatch(packet);
  247. }
  248. catch (Exception exception)
  249. {
  250. _logger.LogError(new EventId(), exception, "Unhandled exception while processing received packet.");
  251. }
  252. }
  253. private void FireApplicationMessageReceivedEvent(MqttPublishPacket publishPacket)
  254. {
  255. try
  256. {
  257. var applicationMessage = publishPacket.ToApplicationMessage();
  258. ApplicationMessageReceived?.Invoke(this, new MqttApplicationMessageReceivedEventArgs(_options.ClientId, applicationMessage));
  259. }
  260. catch (Exception exception)
  261. {
  262. _logger.LogError(new EventId(), exception, "Unhandled exception while handling application message.");
  263. }
  264. }
  265. private async Task ProcessReceivedPublishPacket(MqttPublishPacket publishPacket)
  266. {
  267. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
  268. {
  269. FireApplicationMessageReceivedEvent(publishPacket);
  270. return;
  271. }
  272. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
  273. {
  274. FireApplicationMessageReceivedEvent(publishPacket);
  275. await SendAsync(new MqttPubAckPacket {PacketIdentifier = publishPacket.PacketIdentifier});
  276. return;
  277. }
  278. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
  279. {
  280. // QoS 2 is implement as method "B" [4.3.3 QoS 2: Exactly once delivery]
  281. lock (_unacknowledgedPublishPackets)
  282. {
  283. _unacknowledgedPublishPackets.Add(publishPacket.PacketIdentifier);
  284. }
  285. FireApplicationMessageReceivedEvent(publishPacket);
  286. await SendAsync(new MqttPubRecPacket {PacketIdentifier = publishPacket.PacketIdentifier});
  287. return;
  288. }
  289. throw new MqttCommunicationException("Received a not supported QoS level.");
  290. }
  291. private Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket)
  292. {
  293. lock (_unacknowledgedPublishPackets)
  294. {
  295. _unacknowledgedPublishPackets.Remove(pubRelPacket.PacketIdentifier);
  296. }
  297. return SendAsync(pubRelPacket.CreateResponse<MqttPubCompPacket>());
  298. }
  299. private Task SendAsync(MqttBasePacket packet)
  300. {
  301. return _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, packet);
  302. }
  303. private async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttBasePacket requestPacket) where TResponsePacket : MqttBasePacket
  304. {
  305. var packetAwaiter = _packetDispatcher.WaitForPacketAsync(requestPacket, typeof(TResponsePacket), _options.CommunicationTimeout);
  306. await _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, requestPacket).ConfigureAwait(false);
  307. return (TResponsePacket) await packetAwaiter.ConfigureAwait(false);
  308. }
  309. private ushort GetNewPacketIdentifier()
  310. {
  311. return (ushort) Interlocked.Increment(ref _latestPacketIdentifier);
  312. }
  313. private async Task SendKeepAliveMessagesAsync(CancellationToken cancellationToken)
  314. {
  315. _logger.LogInformation("Start sending keep alive packets.");
  316. try
  317. {
  318. while (!cancellationToken.IsCancellationRequested)
  319. {
  320. await Task.Delay(_options.KeepAlivePeriod, cancellationToken).ConfigureAwait(false);
  321. if (cancellationToken.IsCancellationRequested)
  322. {
  323. return;
  324. }
  325. await SendAndReceiveAsync<MqttPingRespPacket>(new MqttPingReqPacket()).ConfigureAwait(false);
  326. }
  327. }
  328. catch (OperationCanceledException)
  329. {
  330. }
  331. catch (MqttCommunicationException exception)
  332. {
  333. if (cancellationToken.IsCancellationRequested)
  334. {
  335. return;
  336. }
  337. _logger.LogWarning(new EventId(), exception, "MQTT communication exception while sending/receiving keep alive packets.");
  338. await DisconnectInternalAsync().ConfigureAwait(false);
  339. }
  340. catch (Exception exception)
  341. {
  342. _logger.LogWarning(new EventId(), exception, "Unhandled exception while sending/receiving keep alive packets.");
  343. await DisconnectInternalAsync().ConfigureAwait(false);
  344. }
  345. finally
  346. {
  347. _logger.LogInformation("Stopped sending keep alive packets.");
  348. }
  349. }
  350. private async Task ReceivePackets(CancellationToken cancellationToken)
  351. {
  352. _logger.LogInformation("Start receiving packets.");
  353. try
  354. {
  355. while (!cancellationToken.IsCancellationRequested)
  356. {
  357. _isReceivingPackets = true;
  358. var packet = await _adapter.ReceivePacketAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
  359. if (cancellationToken.IsCancellationRequested)
  360. {
  361. return;
  362. }
  363. StartProcessReceivedPacket(packet, cancellationToken);
  364. }
  365. }
  366. catch (OperationCanceledException)
  367. {
  368. }
  369. catch (MqttCommunicationException exception)
  370. {
  371. if (cancellationToken.IsCancellationRequested)
  372. {
  373. return;
  374. }
  375. _logger.LogWarning(new EventId(), exception, "MQTT communication exception while receiving packets.");
  376. await DisconnectInternalAsync().ConfigureAwait(false);
  377. }
  378. catch (Exception exception)
  379. {
  380. _logger.LogError(new EventId(), exception, "Unhandled exception while receiving packets.");
  381. await DisconnectInternalAsync().ConfigureAwait(false);
  382. }
  383. finally
  384. {
  385. _logger.LogInformation(nameof(MqttClient), "Stopped receiving packets.");
  386. }
  387. }
  388. private void StartProcessReceivedPacket(MqttBasePacket packet, CancellationToken cancellationToken)
  389. {
  390. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  391. Task.Run(() => ProcessReceivedPacketAsync(packet), cancellationToken).ConfigureAwait(false);
  392. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  393. }
  394. private void StartSendKeepAliveMessages(CancellationToken cancellationToken)
  395. {
  396. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  397. Task.Factory.StartNew(() => SendKeepAliveMessagesAsync(cancellationToken), cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default)
  398. .ConfigureAwait(false);
  399. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  400. }
  401. }
  402. }