You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

115 rivejä
3.1 KiB

  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. using MQTTnet.Exceptions;
  6. using MQTTnet.Protocol;
  7. namespace MQTTnet
  8. {
  9. public class MqttApplicationMessageBuilder
  10. {
  11. private MqttQualityOfServiceLevel _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
  12. private string _topic;
  13. private byte[] _payload;
  14. private bool _retain;
  15. public MqttApplicationMessageBuilder WithTopic(string topic)
  16. {
  17. _topic = topic;
  18. return this;
  19. }
  20. public MqttApplicationMessageBuilder WithPayload(IEnumerable<byte> payload)
  21. {
  22. if (payload == null)
  23. {
  24. _payload = null;
  25. return this;
  26. }
  27. _payload = payload.ToArray();
  28. return this;
  29. }
  30. public MqttApplicationMessageBuilder WithPayload(MemoryStream payload)
  31. {
  32. if (payload == null)
  33. {
  34. _payload = null;
  35. return this;
  36. }
  37. if (payload.Length == 0)
  38. {
  39. _payload = new byte[0];
  40. }
  41. else
  42. {
  43. _payload = new byte[payload.Length - payload.Position];
  44. payload.Read(_payload, 0, _payload.Length);
  45. }
  46. return this;
  47. }
  48. public MqttApplicationMessageBuilder WithPayload(string payload)
  49. {
  50. if (payload == null)
  51. {
  52. _payload = null;
  53. return this;
  54. }
  55. _payload = string.IsNullOrEmpty(payload) ? new byte[0] : Encoding.UTF8.GetBytes(payload);
  56. return this;
  57. }
  58. public MqttApplicationMessageBuilder WithQualityOfServiceLevel(MqttQualityOfServiceLevel qualityOfServiceLevel)
  59. {
  60. _qualityOfServiceLevel = qualityOfServiceLevel;
  61. return this;
  62. }
  63. public MqttApplicationMessageBuilder WithRetainFlag(bool value = true)
  64. {
  65. _retain = value;
  66. return this;
  67. }
  68. public MqttApplicationMessageBuilder WithAtLeastOnceQoS()
  69. {
  70. _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce;
  71. return this;
  72. }
  73. public MqttApplicationMessageBuilder WithAtMostOnceQoS()
  74. {
  75. _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
  76. return this;
  77. }
  78. public MqttApplicationMessageBuilder WithExactlyOnceQoS()
  79. {
  80. _qualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce;
  81. return this;
  82. }
  83. public MqttApplicationMessage Build()
  84. {
  85. if (string.IsNullOrEmpty(_topic))
  86. {
  87. throw new MqttProtocolViolationException("Topic is not set.");
  88. }
  89. return new MqttApplicationMessage
  90. {
  91. Topic = _topic,
  92. Payload = _payload ?? new byte[0],
  93. QualityOfServiceLevel = _qualityOfServiceLevel,
  94. Retain = _retain
  95. };
  96. }
  97. }
  98. }