|
- using MQTTnet;
- using MQTTnet.Client;
- using MQTTnet.Client.Options;
- using MQTTnet.Client.Disconnecting;
- using MQTTnet.Client.Connecting;
-
- using System.Text;
-
- namespace MQttConnection
- {
- /// <summary>
- /// CLass Connector to connect MQTT Server
- /// </summary>
- public class Connector
- {
- private string _host;
- private int _port;
- private bool _tls = true;
- private string? _username;
- private string? _password;
- private string _payload;
- private string _topic;
- private string _clientid = "Client";
- public event MessageHandler messagehandler;
- public delegate void MessageHandler(Connector c, Message e);
- public static IMqttClient client = new MqttFactory().CreateMqttClient();
-
- public string Host { get { return _host; } set { _host = value; } }
- public int Port { get { return _port; } set { _port = value; } }
- public string Payload { get { return _payload; } set { _payload = value; } }
- public bool Tls { get { return _tls; } set { _tls = value; } }
- public string topic { get { return _topic; } set { _topic = value; } }
- public string clientid { get { return _clientid; } set { _clientid = value; } }
-
-
- private static MqttClientOptionsBuilder mqttClientOptionsBuilder = new MqttClientOptionsBuilder();
-
- /// <summary>
- /// default constructor
- /// </summary>
- public Connector()
- {
- _host = "localhost";
- _port = 1883;
- _payload = "";
- }
-
- /// <summary>
- /// constructor with parameters
- /// </summary>
- /// <param name="host">MQTT Hostname</param>
- /// <param name="port">Port</param>
- public Connector(string host, int port)
- {
- _host = host;
- _port = port;
- _payload = "";
- }
-
- /// <summary>
- /// constructor with parameters
- /// </summary>
- /// <param name="host">MQTT Hostname</param>
- /// <param name="port">Port</param>
- /// <param name="username">Username</param>
- /// <param name="password">Password</param>
- public Connector(string host, int port, string username, string password)
- {
- _host = host;
- _port = port;
- _username = username;
- _password = password;
- _payload = "";
- }
-
- /// <summary>
- /// Start Mqtt connection
- /// </summary>
- /// <returns>async Task</returns>
- public async Task Initialize()
- {
- try
- {
- client.UseApplicationMessageReceivedHandler(MessageRecieved);
- client.UseConnectedHandler(ConnectionHandler);
- client.UseDisconnectedHandler(DisconnectHandler);
-
- var options = BuildClientOptions();
- await client.ConnectAsync(options, CancellationToken.None);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
-
- }
-
- /// <summary>
- /// Close Mqtt connection
- /// </summary>
- /// <returns>async Task of bool type</bool></returns>
- public async Task<bool> CloseConnection()
- {
- await client.DisconnectAsync();
- return true;
- }
-
- /// <summary>
- /// Unsubscribe Mqtt Topic
- /// </summary>
- /// <param name="topic">Topic to unsubscribe</param>
- public async void UnsubscribeTopic(string topic)
- {
- await client.UnsubscribeAsync(topic);
-
- }
-
- /// <summary>
- /// Subscribe Mqtt Topic
- /// </summary>
- /// <param name="topic">Topic to subscribe</param>
- public async void SubscribeTopic(string topic)
- {
- await client.SubscribeAsync(topic);
- }
-
- /// <summary>
- /// Publish asynchronusly
- /// </summary>
- /// <param name="topic">Topic to publish</param>
- /// <param name="payload">Payload</param>
- /// <param name="retainFlag">default true</param>
- /// <param name="qos">default 1</param>
- /// <returns>async Task</returns>
- public async Task PublishAsync(string topic, string payload, bool retainFlag = true, int qos = 1) =>
- await client.PublishAsync(new MqttApplicationMessageBuilder()
- .WithTopic(topic)
- .WithPayload(payload)
- .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos)
- .WithRetainFlag(retainFlag)
- .Build());
-
- /// <summary>
- /// Handler for connection
- /// </summary>
- /// <param name="e">Returns MqttClientConnectedEventArgs </param>
- private void ConnectionHandler(MqttClientConnectedEventArgs e)
- {
-
- Message message = new ();
- message.EventMessage = e.ConnectResult.ResultCode.ToString();
- messagehandler(this, message);
-
- }
-
- /// <summary>
- /// Handler for disconnection
- /// </summary>
- /// <param name="e">Returns MqttClientDisconnectedEventArgs</param>
- private void DisconnectHandler(MqttClientDisconnectedEventArgs e)
- {
- Message message = new ();
- message.EventMessage = "Connection Closed";
- messagehandler(this, message);
- }
-
- /// <summary>
- /// Message Handler
- /// </summary>
- /// <param name="mq_message">Message of type MqttApplicationMessageReceivedEventArgs</param>
- private void MessageRecieved(MqttApplicationMessageReceivedEventArgs mq_message)
- {
- Payload = Encoding.UTF8.GetString(mq_message.ApplicationMessage.Payload);
-
- Message message = new ();
- message.EventMessage = Payload;
- messagehandler(this, message);
- }
-
- /// <summary>
- /// Option Builder
- /// </summary>
- /// <returns>IMqttClientOptions</returns>
- /// <exception cref="ArgumentException"></exception>
- private IMqttClientOptions BuildClientOptions()
- {
- if (_host == null || _port == 0)
- {
- throw new ArgumentException("No Host or Port");
- }
- mqttClientOptionsBuilder.WithClientId(_clientid);
- mqttClientOptionsBuilder.WithTcpServer(_host, _port);
- mqttClientOptionsBuilder.WithCleanSession();
- if (_username != null && _password != null)
- {
- mqttClientOptionsBuilder.WithCredentials(_username, _password);
- }
- if (_tls)
- {
- mqttClientOptionsBuilder.WithTls();
- }
-
- var options = mqttClientOptionsBuilder.Build();
- return options;
- }
-
- }
- }
|