Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

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