Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

117 wiersze
3.2 KiB

  1. using System;
  2. using MQTTnet.Core.Serializer;
  3. namespace MQTTnet.Core.Client
  4. {
  5. public class MqttClientOptionsBuilder
  6. {
  7. private readonly MqttClientOptions _options = new MqttClientOptions();
  8. private MqttClientTcpOptions _tcpOptions;
  9. private MqttClientWebSocketOptions _webSocketOptions;
  10. private MqttClientTlsOptions _tlsOptions;
  11. public MqttClientOptionsBuilder WithProtocolVersion(MqttProtocolVersion protocolVersion)
  12. {
  13. _options.ProtocolVersion = protocolVersion;
  14. return this;
  15. }
  16. public MqttClientOptionsBuilder WithCommunicationTimeout(TimeSpan communicationTimeout)
  17. {
  18. _options.CommunicationTimeout = communicationTimeout;
  19. return this;
  20. }
  21. public MqttClientOptionsBuilder WithCleanSession(bool value = true)
  22. {
  23. _options.CleanSession = value;
  24. return this;
  25. }
  26. public MqttClientOptionsBuilder WithKeepAlivePeriod(TimeSpan keepAlivePeriod)
  27. {
  28. _options.KeepAlivePeriod = keepAlivePeriod;
  29. return this;
  30. }
  31. public MqttClientOptionsBuilder WithClientId(string clientId)
  32. {
  33. _options.ClientId = clientId;
  34. return this;
  35. }
  36. public MqttClientOptionsBuilder WithWillMessage(MqttApplicationMessage applicationMessage)
  37. {
  38. _options.WillMessage = applicationMessage;
  39. return this;
  40. }
  41. public MqttClientOptionsBuilder WithCredentials(string username, string password = null)
  42. {
  43. _options.Credentials = new MqttClientCredentials
  44. {
  45. Username = username,
  46. Password = password
  47. };
  48. return this;
  49. }
  50. public MqttClientOptionsBuilder WithTcpServer(string server, int? port = null)
  51. {
  52. _tcpOptions = new MqttClientTcpOptions
  53. {
  54. Server = server,
  55. Port = port
  56. };
  57. return this;
  58. }
  59. public MqttClientOptionsBuilder WithWebSocketServer(string uri)
  60. {
  61. _webSocketOptions = new MqttClientWebSocketOptions
  62. {
  63. Uri = uri
  64. };
  65. return this;
  66. }
  67. public MqttClientOptionsBuilder WithTls()
  68. {
  69. _tlsOptions = new MqttClientTlsOptions
  70. {
  71. UseTls = true
  72. };
  73. return this;
  74. }
  75. public IMqttClientOptions Build()
  76. {
  77. if (_tlsOptions != null)
  78. {
  79. if (_tcpOptions == null && _webSocketOptions == null)
  80. {
  81. throw new InvalidOperationException("A channel (TCP or WebSocket) must be set if TLS is configured.");
  82. }
  83. if (_tcpOptions != null)
  84. {
  85. _options.ChannelOptions = _tcpOptions;
  86. }
  87. else
  88. {
  89. _options.ChannelOptions = _webSocketOptions;
  90. }
  91. }
  92. _options.ChannelOptions = (IMqttClientChannelOptions)_tcpOptions ?? _webSocketOptions;
  93. return _options;
  94. }
  95. }
  96. }