Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

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