Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

59 rindas
2.4 KiB

  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Text;
  5. using MQTTnet.Core.Protocol;
  6. namespace MQTTnet.Core
  7. {
  8. public class MqttApplicationMessageFactory
  9. {
  10. public MqttApplicationMessage CreateApplicationMessage(string topic, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false)
  11. {
  12. if (topic == null) throw new ArgumentNullException(nameof(topic));
  13. return CreateApplicationMessage(topic, new byte[0], qualityOfServiceLevel, retain);
  14. }
  15. public MqttApplicationMessage CreateApplicationMessage(string topic, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false)
  16. {
  17. if (topic == null) throw new ArgumentNullException(nameof(topic));
  18. if (payload == null)
  19. {
  20. payload = new byte[0];
  21. }
  22. return new MqttApplicationMessage(topic, payload, qualityOfServiceLevel, retain);
  23. }
  24. public MqttApplicationMessage CreateApplicationMessage<TPayload>(string topic, TPayload payload, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false)
  25. {
  26. if (topic == null) throw new ArgumentNullException(nameof(topic));
  27. var payloadString = Convert.ToString(payload, CultureInfo.InvariantCulture);
  28. var payloadBuffer = string.IsNullOrEmpty(payloadString) ? new byte[0] : Encoding.UTF8.GetBytes(payloadString);
  29. return CreateApplicationMessage(topic, payloadBuffer, qualityOfServiceLevel, retain);
  30. }
  31. public MqttApplicationMessage CreateApplicationMessage(string topic, Stream payload, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false)
  32. {
  33. if (topic == null) throw new ArgumentNullException(nameof(topic));
  34. byte[] payloadBuffer;
  35. if (payload == null || payload.Length == 0)
  36. {
  37. payloadBuffer = new byte[0];
  38. }
  39. else
  40. {
  41. payloadBuffer = new byte[payload.Length - payload.Position];
  42. payload.Read(payloadBuffer, 0, payloadBuffer.Length);
  43. }
  44. return CreateApplicationMessage(topic, payloadBuffer, qualityOfServiceLevel, retain);
  45. }
  46. }
  47. }