Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

208 строки
6.8 KiB

  1. using MQTTnet;
  2. using MQTTnet.Client;
  3. using MQTTnet.Client.Options;
  4. using MQTTnet.Client.Disconnecting;
  5. using MQTTnet.Client.Connecting;
  6. using System.Text;
  7. namespace MQttConnection
  8. {
  9. /// <summary>
  10. /// CLass Connector to connect MQTT Server
  11. /// </summary>
  12. public class Connector
  13. {
  14. private string _host;
  15. private int _port;
  16. private bool _tls = true;
  17. private string? _username;
  18. private string? _password;
  19. private string _payload;
  20. private string _topic;
  21. private string _clientid = "Client";
  22. public event MessageHandler messagehandler;
  23. public delegate void MessageHandler(Connector c, Message e);
  24. public static IMqttClient client = new MqttFactory().CreateMqttClient();
  25. public string Host { get { return _host; } set { _host = value; } }
  26. public int Port { get { return _port; } set { _port = value; } }
  27. public string Payload { get { return _payload; } set { _payload = value; } }
  28. public bool Tls { get { return _tls; } set { _tls = value; } }
  29. public string topic { get { return _topic; } set { _topic = value; } }
  30. public string clientid { get { return _clientid; } set { _clientid = value; } }
  31. private static MqttClientOptionsBuilder mqttClientOptionsBuilder = new MqttClientOptionsBuilder();
  32. /// <summary>
  33. /// default constructor
  34. /// </summary>
  35. public Connector()
  36. {
  37. _host = "localhost";
  38. _port = 1883;
  39. _payload = "";
  40. }
  41. /// <summary>
  42. /// constructor with parameters
  43. /// </summary>
  44. /// <param name="host">MQTT Hostname</param>
  45. /// <param name="port">Port</param>
  46. public Connector(string host, int port)
  47. {
  48. _host = host;
  49. _port = port;
  50. _payload = "";
  51. }
  52. /// <summary>
  53. /// constructor with parameters
  54. /// </summary>
  55. /// <param name="host">MQTT Hostname</param>
  56. /// <param name="port">Port</param>
  57. /// <param name="username">Username</param>
  58. /// <param name="password">Password</param>
  59. public Connector(string host, int port, string username, string password)
  60. {
  61. _host = host;
  62. _port = port;
  63. _username = username;
  64. _password = password;
  65. _payload = "";
  66. }
  67. /// <summary>
  68. /// Start Mqtt connection
  69. /// </summary>
  70. /// <returns>async Task</returns>
  71. public async Task Initialize()
  72. {
  73. try
  74. {
  75. client.UseApplicationMessageReceivedHandler(MessageRecieved);
  76. client.UseConnectedHandler(ConnectionHandler);
  77. client.UseDisconnectedHandler(DisconnectHandler);
  78. var options = BuildClientOptions();
  79. await client.ConnectAsync(options, CancellationToken.None);
  80. }
  81. catch (Exception ex)
  82. {
  83. Console.WriteLine(ex.Message);
  84. }
  85. }
  86. /// <summary>
  87. /// Close Mqtt connection
  88. /// </summary>
  89. /// <returns>async Task of bool type</bool></returns>
  90. public async Task<bool> CloseConnection()
  91. {
  92. await client.DisconnectAsync();
  93. return true;
  94. }
  95. /// <summary>
  96. /// Unsubscribe Mqtt Topic
  97. /// </summary>
  98. /// <param name="topic">Topic to unsubscribe</param>
  99. public async void UnsubscribeTopic(string topic)
  100. {
  101. await client.UnsubscribeAsync(topic);
  102. }
  103. /// <summary>
  104. /// Subscribe Mqtt Topic
  105. /// </summary>
  106. /// <param name="topic">Topic to subscribe</param>
  107. public async void SubscribeTopic(string topic)
  108. {
  109. await client.SubscribeAsync(topic);
  110. }
  111. /// <summary>
  112. /// Publish asynchronusly
  113. /// </summary>
  114. /// <param name="topic">Topic to publish</param>
  115. /// <param name="payload">Payload</param>
  116. /// <param name="retainFlag">default true</param>
  117. /// <param name="qos">default 1</param>
  118. /// <returns>async Task</returns>
  119. public async Task PublishAsync(string topic, string payload, bool retainFlag = true, int qos = 1) =>
  120. await client.PublishAsync(new MqttApplicationMessageBuilder()
  121. .WithTopic(topic)
  122. .WithPayload(payload)
  123. .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos)
  124. .WithRetainFlag(retainFlag)
  125. .Build());
  126. /// <summary>
  127. /// Handler for connection
  128. /// </summary>
  129. /// <param name="e">Returns MqttClientConnectedEventArgs </param>
  130. private void ConnectionHandler(MqttClientConnectedEventArgs e)
  131. {
  132. Message message = new ();
  133. message.EventMessage = e.ConnectResult.ResultCode.ToString();
  134. messagehandler(this, message);
  135. }
  136. /// <summary>
  137. /// Handler for disconnection
  138. /// </summary>
  139. /// <param name="e">Returns MqttClientDisconnectedEventArgs</param>
  140. private void DisconnectHandler(MqttClientDisconnectedEventArgs e)
  141. {
  142. Message message = new ();
  143. message.EventMessage = "Connection Closed";
  144. messagehandler(this, message);
  145. }
  146. /// <summary>
  147. /// Message Handler
  148. /// </summary>
  149. /// <param name="mq_message">Message of type MqttApplicationMessageReceivedEventArgs</param>
  150. private void MessageRecieved(MqttApplicationMessageReceivedEventArgs mq_message)
  151. {
  152. Payload = Encoding.UTF8.GetString(mq_message.ApplicationMessage.Payload);
  153. Message message = new ();
  154. message.EventMessage = Payload;
  155. messagehandler(this, message);
  156. }
  157. /// <summary>
  158. /// Option Builder
  159. /// </summary>
  160. /// <returns>IMqttClientOptions</returns>
  161. /// <exception cref="ArgumentException"></exception>
  162. private IMqttClientOptions BuildClientOptions()
  163. {
  164. if (_host == null || _port == 0)
  165. {
  166. throw new ArgumentException("No Host or Port");
  167. }
  168. mqttClientOptionsBuilder.WithClientId(_clientid);
  169. mqttClientOptionsBuilder.WithTcpServer(_host, _port);
  170. mqttClientOptionsBuilder.WithCleanSession();
  171. if (_username != null && _password != null)
  172. {
  173. mqttClientOptionsBuilder.WithCredentials(_username, _password);
  174. }
  175. if (_tls)
  176. {
  177. mqttClientOptionsBuilder.WithTls();
  178. }
  179. var options = mqttClientOptionsBuilder.Build();
  180. return options;
  181. }
  182. }
  183. }