25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

371 lines
14 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. Task.Run(() => ReceivePackets(_cancellationTokenSource.Token), _cancellationTokenSource.Token).Forget();
  57. var response = await SendAndReceiveAsync<MqttConnAckPacket>(connectPacket);
  58. if (response.ConnectReturnCode != MqttConnectReturnCode.ConnectionAccepted)
  59. {
  60. throw new MqttConnectingFailedException(response.ConnectReturnCode);
  61. }
  62. if (_options.KeepAlivePeriod != TimeSpan.Zero)
  63. {
  64. Task.Run(() => SendKeepAliveMessagesAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token).Forget();
  65. }
  66. Connected?.Invoke(this, EventArgs.Empty);
  67. }
  68. public async Task DisconnectAsync()
  69. {
  70. await SendAsync(new MqttDisconnectPacket());
  71. await DisconnectInternalAsync();
  72. }
  73. public Task<IList<MqttSubscribeResult>> SubscribeAsync(params TopicFilter[] topicFilters)
  74. {
  75. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  76. return SubscribeAsync(topicFilters.ToList());
  77. }
  78. public async Task<IList<MqttSubscribeResult>> SubscribeAsync(IList<TopicFilter> topicFilters)
  79. {
  80. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  81. if (!topicFilters.Any()) throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.8.3-3].");
  82. ThrowIfNotConnected();
  83. var subscribePacket = new MqttSubscribePacket
  84. {
  85. PacketIdentifier = GetNewPacketIdentifier(),
  86. TopicFilters = topicFilters
  87. };
  88. var response = await SendAndReceiveAsync<MqttSubAckPacket>(subscribePacket);
  89. if (response.SubscribeReturnCodes.Count != topicFilters.Count)
  90. {
  91. throw new MqttProtocolViolationException("The return codes are not matching the topic filters [MQTT-3.9.3-1].");
  92. }
  93. return topicFilters.Select((t, i) => new MqttSubscribeResult(t, response.SubscribeReturnCodes[i])).ToList();
  94. }
  95. public Task Unsubscribe(params string[] topicFilters)
  96. {
  97. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  98. return Unsubscribe(topicFilters.ToList());
  99. }
  100. public async Task Unsubscribe(IList<string> topicFilters)
  101. {
  102. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  103. if (!topicFilters.Any()) throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.10.3-2].");
  104. ThrowIfNotConnected();
  105. var unsubscribePacket = new MqttUnsubscribePacket
  106. {
  107. PacketIdentifier = GetNewPacketIdentifier(),
  108. TopicFilters = topicFilters
  109. };
  110. await SendAndReceiveAsync<MqttUnsubAckPacket>(unsubscribePacket);
  111. }
  112. public async Task PublishAsync(MqttApplicationMessage applicationMessage)
  113. {
  114. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  115. ThrowIfNotConnected();
  116. var publishPacket = applicationMessage.ToPublishPacket();
  117. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
  118. {
  119. await SendAsync(publishPacket);
  120. }
  121. else if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
  122. {
  123. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  124. await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket);
  125. }
  126. else if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
  127. {
  128. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  129. await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket);
  130. await SendAsync(publishPacket.CreateResponse<MqttPubCompPacket>());
  131. }
  132. }
  133. private void ThrowIfNotConnected()
  134. {
  135. if (!IsConnected) throw new MqttCommunicationException("The client is not connected.");
  136. }
  137. private async Task DisconnectInternalAsync()
  138. {
  139. try
  140. {
  141. await _adapter.DisconnectAsync();
  142. }
  143. catch
  144. {
  145. }
  146. finally
  147. {
  148. _cancellationTokenSource?.Cancel();
  149. IsConnected = false;
  150. Disconnected?.Invoke(this, EventArgs.Empty);
  151. }
  152. }
  153. private async void ProcessReceivedPacket(MqttBasePacket mqttPacket)
  154. {
  155. try
  156. {
  157. if (mqttPacket is MqttPingReqPacket)
  158. {
  159. await SendAsync(new MqttPingRespPacket());
  160. return;
  161. }
  162. if (mqttPacket is MqttDisconnectPacket)
  163. {
  164. await DisconnectAsync();
  165. return;
  166. }
  167. var publishPacket = mqttPacket as MqttPublishPacket;
  168. if (publishPacket != null)
  169. {
  170. await ProcessReceivedPublishPacket(publishPacket);
  171. return;
  172. }
  173. var pubRelPacket = mqttPacket as MqttPubRelPacket;
  174. if (pubRelPacket != null)
  175. {
  176. await ProcessReceivedPubRelPacket(pubRelPacket);
  177. return;
  178. }
  179. _packetDispatcher.Dispatch(mqttPacket);
  180. }
  181. catch (Exception exception)
  182. {
  183. MqttTrace.Error(nameof(MqttClient), exception, "Error while processing received packet.");
  184. }
  185. }
  186. private void FireApplicationMessageReceivedEvent(MqttPublishPacket publishPacket)
  187. {
  188. if (publishPacket.QualityOfServiceLevel != MqttQualityOfServiceLevel.AtMostOnce)
  189. {
  190. _processedPublishPackets.Add(publishPacket.PacketIdentifier);
  191. }
  192. var applicationMessage = new MqttApplicationMessage(
  193. publishPacket.Topic,
  194. publishPacket.Payload,
  195. publishPacket.QualityOfServiceLevel,
  196. publishPacket.Retain
  197. );
  198. ApplicationMessageReceived?.Invoke(this, new MqttApplicationMessageReceivedEventArgs(applicationMessage));
  199. }
  200. private async Task ProcessReceivedPublishPacket(MqttPublishPacket publishPacket)
  201. {
  202. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
  203. {
  204. FireApplicationMessageReceivedEvent(publishPacket);
  205. }
  206. else
  207. {
  208. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
  209. {
  210. FireApplicationMessageReceivedEvent(publishPacket);
  211. await SendAsync(new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  212. }
  213. else if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
  214. {
  215. _pendingExactlyOncePublishPackets[publishPacket.PacketIdentifier] = publishPacket;
  216. await SendAsync(new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  217. }
  218. }
  219. }
  220. private async Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket)
  221. {
  222. MqttPublishPacket originalPublishPacket;
  223. if (!_pendingExactlyOncePublishPackets.TryRemove(pubRelPacket.PacketIdentifier, out originalPublishPacket))
  224. {
  225. throw new MqttCommunicationException();
  226. }
  227. await SendAsync(originalPublishPacket.CreateResponse<MqttPubCompPacket>());
  228. FireApplicationMessageReceivedEvent(originalPublishPacket);
  229. }
  230. private Task SendAsync(MqttBasePacket packet)
  231. {
  232. return _adapter.SendPacketAsync(packet, _options.DefaultCommunicationTimeout);
  233. }
  234. private async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttBasePacket requestPacket) where TResponsePacket : MqttBasePacket
  235. {
  236. bool ResponsePacketSelector(MqttBasePacket p)
  237. {
  238. var p1 = p as TResponsePacket;
  239. if (p1 == null)
  240. {
  241. return false;
  242. }
  243. var pi1 = requestPacket as IPacketWithIdentifier;
  244. var pi2 = p as IPacketWithIdentifier;
  245. if (pi1 != null && pi2 != null)
  246. {
  247. if (pi1.PacketIdentifier != pi2.PacketIdentifier)
  248. {
  249. return false;
  250. }
  251. }
  252. return true;
  253. }
  254. await _adapter.SendPacketAsync(requestPacket, _options.DefaultCommunicationTimeout);
  255. return (TResponsePacket)await _packetDispatcher.WaitForPacketAsync(ResponsePacketSelector, _options.DefaultCommunicationTimeout);
  256. }
  257. private ushort GetNewPacketIdentifier()
  258. {
  259. return (ushort)Interlocked.Increment(ref _latestPacketIdentifier);
  260. }
  261. private async Task SendKeepAliveMessagesAsync(CancellationToken cancellationToken)
  262. {
  263. MqttTrace.Information(nameof(MqttClient), "Start sending keep alive packets.");
  264. try
  265. {
  266. while (!cancellationToken.IsCancellationRequested)
  267. {
  268. await Task.Delay(_options.KeepAlivePeriod, cancellationToken);
  269. await SendAndReceiveAsync<MqttPingRespPacket>(new MqttPingReqPacket());
  270. }
  271. }
  272. catch (MqttCommunicationException exception)
  273. {
  274. MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication error while receiving packets.");
  275. }
  276. catch (Exception exception)
  277. {
  278. MqttTrace.Warning(nameof(MqttClient), exception, "Error while sending/receiving keep alive packets.");
  279. }
  280. finally
  281. {
  282. MqttTrace.Information(nameof(MqttClient), "Stopped sending keep alive packets.");
  283. await DisconnectInternalAsync();
  284. }
  285. }
  286. private async Task ReceivePackets(CancellationToken cancellationToken)
  287. {
  288. MqttTrace.Information(nameof(MqttClient), "Start receiving packets.");
  289. try
  290. {
  291. while (!cancellationToken.IsCancellationRequested)
  292. {
  293. var mqttPacket = await _adapter.ReceivePacketAsync(TimeSpan.Zero);
  294. MqttTrace.Information(nameof(MqttClient), $"Received <<< {mqttPacket}");
  295. Task.Run(() => ProcessReceivedPacket(mqttPacket), cancellationToken).Forget();
  296. }
  297. }
  298. catch (MqttCommunicationException exception)
  299. {
  300. MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication error while receiving packets.");
  301. }
  302. catch (Exception exception)
  303. {
  304. MqttTrace.Error(nameof(MqttClient), exception, "Error while receiving packets.");
  305. }
  306. finally
  307. {
  308. MqttTrace.Information(nameof(MqttClient), "Stopped receiving packets.");
  309. await DisconnectInternalAsync();
  310. }
  311. }
  312. }
  313. }