Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

62 рядки
2.1 KiB

  1. using System;
  2. using System.Collections.Concurrent;
  3. using MQTTnet.Core.Packets;
  4. using MQTTnet.Core.Protocol;
  5. namespace MQTTnet.Core.Server
  6. {
  7. public sealed class MqttClientSubscriptionsManager
  8. {
  9. private readonly ConcurrentDictionary<string, MqttQualityOfServiceLevel> _subscribedTopics = new ConcurrentDictionary<string, MqttQualityOfServiceLevel>();
  10. public MqttSubAckPacket Subscribe(MqttSubscribePacket subscribePacket)
  11. {
  12. if (subscribePacket == null) throw new ArgumentNullException(nameof(subscribePacket));
  13. var responsePacket = subscribePacket.CreateResponse<MqttSubAckPacket>();
  14. foreach (var topicFilter in subscribePacket.TopicFilters)
  15. {
  16. _subscribedTopics[topicFilter.Topic] = topicFilter.QualityOfServiceLevel;
  17. responsePacket.SubscribeReturnCodes.Add(MqttSubscribeReturnCode.SuccessMaximumQoS1); // TODO: Add support for QoS 2.
  18. }
  19. return responsePacket;
  20. }
  21. public MqttUnsubAckPacket Unsubscribe(MqttUnsubscribePacket unsubscribePacket)
  22. {
  23. if (unsubscribePacket == null) throw new ArgumentNullException(nameof(unsubscribePacket));
  24. foreach (var topicFilter in unsubscribePacket.TopicFilters)
  25. {
  26. MqttQualityOfServiceLevel _;
  27. _subscribedTopics.TryRemove(topicFilter, out _);
  28. }
  29. return unsubscribePacket.CreateResponse<MqttUnsubAckPacket>();
  30. }
  31. public bool IsTopicSubscribed(MqttPublishPacket publishPacket)
  32. {
  33. if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket));
  34. foreach (var subscribedTopic in _subscribedTopics)
  35. {
  36. if (!MqttTopicFilterComparer.IsMatch(publishPacket.Topic, subscribedTopic.Key))
  37. {
  38. continue;
  39. }
  40. if (subscribedTopic.Value < publishPacket.QualityOfServiceLevel)
  41. {
  42. continue;
  43. }
  44. return true;
  45. }
  46. return false;
  47. }
  48. }
  49. }