No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

71 líneas
2.3 KiB

  1. using System;
  2. using System.Collections.Generic;
  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 Dictionary<string, MqttQualityOfServiceLevel> _subscribedTopics = new Dictionary<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. lock (_subscribedTopics)
  15. {
  16. foreach (var topicFilter in subscribePacket.TopicFilters)
  17. {
  18. _subscribedTopics[topicFilter.Topic] = topicFilter.QualityOfServiceLevel;
  19. responsePacket.SubscribeReturnCodes.Add(MqttSubscribeReturnCode.SuccessMaximumQoS1); // TODO: Add support for QoS 2.
  20. }
  21. }
  22. return responsePacket;
  23. }
  24. public MqttUnsubAckPacket Unsubscribe(MqttUnsubscribePacket unsubscribePacket)
  25. {
  26. if (unsubscribePacket == null) throw new ArgumentNullException(nameof(unsubscribePacket));
  27. lock (_subscribedTopics)
  28. {
  29. foreach (var topicFilter in unsubscribePacket.TopicFilters)
  30. {
  31. _subscribedTopics.Remove(topicFilter);
  32. }
  33. }
  34. return unsubscribePacket.CreateResponse<MqttUnsubAckPacket>();
  35. }
  36. public bool IsSubscribed(MqttPublishPacket publishPacket)
  37. {
  38. if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket));
  39. lock (_subscribedTopics)
  40. {
  41. foreach (var subscribedTopic in _subscribedTopics)
  42. {
  43. if (publishPacket.QualityOfServiceLevel > subscribedTopic.Value)
  44. {
  45. continue;
  46. }
  47. if (!MqttTopicFilterComparer.IsMatch(publishPacket.Topic, subscribedTopic.Key))
  48. {
  49. continue;
  50. }
  51. return true;
  52. }
  53. }
  54. return false;
  55. }
  56. }
  57. }