Exemplo n.º 1
0
        private IMqttClientOptions GetMqttClientOptions(MqttConnectionString connectionString)
        {
            var mqttClientOptionsBuilder = new MqttClientOptionsBuilder()
                                           .WithClientId(connectionString.ClientId)
                                           .WithTcpServer(connectionString.Server, connectionString.Port);

            if (!string.IsNullOrEmpty(connectionString.Username) || !string.IsNullOrEmpty(connectionString.Password))
            {
                _logger.LogTrace($"Using authentication, username: '******'");
                mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithCredentials(connectionString.Username, connectionString.Password);
            }

            if (connectionString.Tls)
            {
                var certificates = new List <byte[]>();
                if (connectionString.Certificate != null)
                {
                    using (var cert = new X509Certificate(connectionString.Certificate))
                    {
                        var serializedServerCertificate = cert.Export(X509ContentType.Cert);
                        certificates.Add(serializedServerCertificate);
                    }
                }

                mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithTls(new MqttClientOptionsBuilderTlsParameters
                {
                    UseTls       = true,
                    Certificates = certificates,
#if DEBUG
                    CertificateValidationCallback = (X509Certificate x, X509Chain y, SslPolicyErrors z, IMqttClientOptions o) =>
                    {
                        return(true);
                    },
#endif
                    AllowUntrustedCertificates        = false,
                    IgnoreCertificateChainErrors      = false,
                    IgnoreCertificateRevocationErrors = false
                });
            }

            return(mqttClientOptionsBuilder.Build());
        }
        private IMqttClientOptions GetMqttClientOptions(MqttConnectionString connectionString)
        {
            var mqttClientOptionsBuilder = new MqttClientOptionsBuilder()
                                           .WithClientId(connectionString.ClientId)
                                           .WithTcpServer(connectionString.Server, connectionString.Port);

            if (!string.IsNullOrEmpty(connectionString.Username) || !string.IsNullOrEmpty(connectionString.Password))
            {
                _logger.LogTrace($"Using authentication, username: '******'");
                mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithCredentials(connectionString.Username, connectionString.Password);
            }

            if (connectionString.Tls)
            {
                // Need to implement TLS verification sometime
                mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithTls(true, false, false);
            }

            return(mqttClientOptionsBuilder.Build());
        }
Exemplo n.º 3
0
        public virtual ManagedMqttClientOptions GetMqttClientOptions()
        {
            var clientOptions = new MqttClientOptionsBuilder();

            if (MqttBrokerSettings.IsEncryptedCommunication)
            {
                clientOptions.WithTls();
            }

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(clientOptions
                                             .WithClientId(MqttClientId)
                                             .WithTcpServer(MqttBrokerSettings.BrokerAddress, MqttBrokerSettings.Port)
                                             .WithCredentials(EboEwsSettings.UserName, EboEwsSettings.Password).Build())
                          .WithStorage(new ClientRetainedMessageHandler(this.Name))
                          .Build();

            return(options);
        }
Exemplo n.º 4
0
        public async Task Connect(string clientIdPrefix, Func <Task> connected = null, Func <Task> disconnected = null)
        {
            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId($"{clientIdPrefix}-{_options.ClientId}")
                                 .WithKeepAlivePeriod(TimeSpan.FromSeconds(90))
                                 .WithCredentials(_options.User, _options.Password)
                                 .WithTcpServer(_options.URI, _options.Port)
                                 .WithCleanSession();

            var options = _options.Secure
              ? messageBuilder
                          .WithTls()
                          .Build()
              : messageBuilder
                          .Build();

            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)
                                 .Build();

            _client = new MqttFactory()
                      .CreateManagedMqttClient();
            _client.UseConnectedHandler(async e =>
            {
                _logger.LogInformation("Connected from MQTT Broker.");
                if (connected != null)
                {
                    await connected();
                }
            })
            .UseDisconnectedHandler(async e =>
            {
                _logger.LogWarning(e.Exception, $"Disconnected from MQTT Broker.");
                if (disconnected != null)
                {
                    await disconnected();
                }
            });
            await _client.StartAsync(managedOptions);
        }
Exemplo n.º 5
0
        private IMqttClientOptions GetMqttOption(string clientId)
        {
            var builder = new MqttClientOptionsBuilder()
                          .WithProtocolVersion(MqttProtocolVersion.V311)
                          .WithKeepAlivePeriod(TimeSpan.FromSeconds(5))
                          .WithCommunicationTimeout(TimeSpan.FromSeconds(15))
                          .WithClientId(clientId)
                          // this message will be sent to all clients
                          // subscribed to <clientId>/status topic
                          // if this client gets disconnected
                          .WithWillMessage(new MqttApplicationMessage
            {
                Payload = Encoding.UTF8.GetBytes("disconnected"),
                Topic   = String.Format("/{0}/status", clientId),
                Retain  = true,
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce
            });

            // TODO: ?
            // .WithCleanSession();
            if (usingWebSockets)
            {
                builder.WithWebSocketServer(endPoint.Address + ":" + endPoint.Port + "/mqtt");
            }
            else
            {
                builder.WithTcpServer(endPoint.Address, endPoint.Port);
            }
            if (networkCredential != null)
            {
                builder.WithCredentials(networkCredential.UserName, networkCredential.Password);
            }
            if (useSsl)
            {
                var tlsParameters = new MqttClientOptionsBuilderTlsParameters {
                    UseTls = true
                };
                builder.WithTls(tlsParameters);
            }
            return(builder.Build());
        }
Exemplo n.º 6
0
        public void Connect()
        {
            MqttClientOptionsBuilder messageBuilder = new MqttClientOptionsBuilder()
                                                      .WithClientId(clientId)
                                                      .WithCredentials(User, Password)
                                                      .WithTcpServer(URI, Port)
                                                      .WithCleanSession();
            IMqttClientOptions options = Secure ? messageBuilder
                                         .WithTls()
                                         .Build() : messageBuilder.Build();
            ManagedMqttClientOptions managedOptions = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(5)).WithClientOptions(options).Build();

            MQTTClient = new MqttFactory().CreateManagedMqttClient();
            Task task = MQTTClient.StartAsync(managedOptions);

            while (task.Status != TaskStatus.RanToCompletion)
            {
                Thread.Sleep(50);
            }
            MQTTClient.ApplicationMessageReceivedHandler = this;
        }
Exemplo n.º 7
0
 private void ConnectButton_Click(object sender, RoutedEventArgs e)
 {
     if (mqttClient.IsConnected)
     {
         Task.Run(async() =>
         {
             try
             {
                 await mqttClient.DisconnectAsync();
             }
             catch { }
         });
     }
     else
     {
         MqttIsConnected = true;
         var temp = new MqttClientOptionsBuilder()
                    .WithClientId(Tools.Global.setting.mqttClientID)
                    .WithTcpServer(Tools.Global.setting.mqttServer, Tools.Global.setting.mqttPort)
                    .WithCredentials(Tools.Global.setting.mqttUser, Tools.Global.setting.mqttPassword)
                    .WithKeepAlivePeriod(new TimeSpan(0, 0, Tools.Global.setting.mqttKeepAlive));
         if (Tools.Global.setting.mqttTLS)
         {
             temp.WithTls();
         }
         if (Tools.Global.setting.mqttCleanSession)
         {
             temp.WithCleanSession();
         }
         var options = temp.Build();
         Task.Run(async() =>
         {
             try
             {
                 await mqttClient.ConnectAsync(options, CancellationToken.None);
             }
             catch { }
         });
     }
 }
Exemplo n.º 8
0
        private static IMqttClientOptions UnwrapOptions(IClientOptions wrappedOptions, IWillMessage willMessage)
        {
            var optionsBuilder = new MqttClientOptionsBuilder();

            if (wrappedOptions.ConnectionType == ConnectionType.Tcp)
            {
                optionsBuilder.WithTcpServer(wrappedOptions.Uri.Host, wrappedOptions.Uri.Port);
            }
            else
            {
                optionsBuilder.WithWebSocketServer(wrappedOptions.Uri.AbsoluteUri);
            }

            if (wrappedOptions.UseTls)
            {
                optionsBuilder
                .WithTls(new MqttClientOptionsBuilderTlsParameters
                {
                    AllowUntrustedCertificates = wrappedOptions.AllowUntrustedCertificates,
                    Certificates = UnwrapCertificates(wrappedOptions.Certificates),
                    IgnoreCertificateChainErrors = wrappedOptions.IgnoreCertificateChainErrors,
                    UseTls = wrappedOptions.UseTls
                });
            }

            return(optionsBuilder
                   .WithWillMessage(WrapWillMessage(willMessage))
                   .WithCleanSession(wrappedOptions.CleanSession)
                   .WithClientId(wrappedOptions.ClientId ?? Guid.NewGuid().ToString().Replace("-", string.Empty))

                   .WithProtocolVersion(UnwrapProtocolVersion(wrappedOptions.ProtocolVersion))
                   .WithCommunicationTimeout(wrappedOptions.DefaultCommunicationTimeout == default
                    ? TimeSpan.FromSeconds(10)
                    : wrappedOptions.DefaultCommunicationTimeout)
                   .WithKeepAlivePeriod(wrappedOptions.KeepAlivePeriod == default
                    ? TimeSpan.FromSeconds(5)
                    : wrappedOptions.KeepAlivePeriod)
                   .WithCredentials(wrappedOptions.UserName, wrappedOptions.Password)
                   .Build());
        }
Exemplo n.º 9
0
        IMqttClient ProvideMQTTClient()
        {
            var configuration = _getContainer().Get <Configuration>();

            _logger.Information($"Connecting to MQTT broker '{configuration.Connection.Host}:{configuration.Connection.Port}'");

            var optionsBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(configuration.Connection.ClientId)
                                 .WithTcpServer(configuration.Connection.Host, configuration.Connection.Port);

            if (configuration.Connection.UseTls)
            {
                optionsBuilder = optionsBuilder.WithTls();
            }

            var options = optionsBuilder.Build();

            _mqttOptions = options;

            var factory = new MqttFactory();

            var mqttClient = factory.CreateMqttClient();

            mqttClient.UseDisconnectedHandler(async e =>
            {
                await Task.Delay(TimeSpan.FromSeconds(5));
                try
                {
                    await mqttClient.ConnectAsync(options, CancellationToken.None);
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, "Couldn't reconnect MQTT client");
                }
            });
            _logger.Information($"Connect to MQTT broker");

            return(mqttClient);
        }
Exemplo n.º 10
0
        static MqttHub()
        {
            string clientId     = Guid.NewGuid().ToString();
            string mqttURI      = "localhost";
            string mqttUser     = "";
            string mqttPassword = "";
            int    mqttPort     = 1883;
            bool   mqttSecure   = true;

            //configure options
            var optionsBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId("proxy")
                                 .WithTcpServer("localhost", 8883)
                                 .WithCredentials("sanjay", "%Welcome@123%")
                                 .WithCleanSession(false);

            var _options = mqttSecure ? optionsBuilder.WithTls(new MqttClientOptionsBuilderTlsParameters()
            {
                AllowUntrustedCertificates = true,
                UseTls       = true,
                SslProtocol  = SslProtocols.Tls11,
                Certificates = new List <X509Certificate>()
                {
                    new X509Certificate2(@"C:\Certs\client.crt")
                },
                CertificateValidationHandler      = delegate { return(true); },
                IgnoreCertificateChainErrors      = false,
                IgnoreCertificateRevocationErrors = false
            }).Build() : optionsBuilder.Build();
            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(_options)
                                 .Build();

            _client = new MqttFactory().CreateManagedMqttClient();

            //actually connect
            _client.StartAsync(managedOptions).Wait();
        }
Exemplo n.º 11
0
        public MqttClientForMultipleSubscribers(ILogger <MqttClientForMultipleSubscribers> logger, IOptions <MqttConfiguration> mqttConfiguration)
        {
            Logger            = logger;
            MqttConfiguration = mqttConfiguration.Value;

            Logger.LogInformation("Creating MqttClient at: {time}. Uri:{1}", DateTimeOffset.Now, MqttConfiguration.MqttUri);

            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(MqttConfiguration.ClientId.Replace("-", "").Replace(" ", ""))
                                 .WithCredentials(MqttConfiguration.MqttUser, MqttConfiguration.MqttUserPassword)
                                 .WithTcpServer(MqttConfiguration.MqttUri, MqttConfiguration.MqttPort)
                                 .WithCleanSession();

            var options = MqttConfiguration.MqttSecure ?
                          messageBuilder.WithTls().Build() :
                          messageBuilder.Build();

            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)
                                 .Build();

            MqttClient = new MqttFactory()
                         .CreateManagedMqttClient();

            MqttClient.StartAsync(managedOptions).Wait();

            // wait for connection
            while (!MqttClient.IsConnected)
            {
                Logger.LogTrace("MqttClient not connected... Go to sleep for a second...");
                Thread.Sleep(1000);
            }

            MqttClient.UseApplicationMessageReceivedHandler(async e => await MessageReceive(e));

            Logger.LogInformation("Creating MqttClient done at: {time}", DateTimeOffset.Now);
        }
Exemplo n.º 12
0
        public MqttService(IHubContext <DevicesHub> hubContext)
        {
            _hubContext = hubContext;
            var messageBuilder = new MqttClientOptionsBuilder().WithClientId(clientId) /*.WithCredentials(mqttUser, mqttPassword)*/.WithTcpServer(mqttURI, mqttPort).WithCleanSession();

            var options = mqttSecure
              ? messageBuilder
                          .WithTls()
                          .Build()
              : messageBuilder
                          .Build();

            var managedOptions = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)
                                 .Build();

            client = new MqttFactory().CreateManagedMqttClient();
            client.StartAsync(managedOptions);

            client.UseConnectedHandler(ClientConnectedHandler);
            client.UseDisconnectedHandler(ClientDisconnectedHandler);
            client.UseApplicationMessageReceivedHandler(ClientMessageReceivedHandler);
        }
        protected async Task Connect(string user, string passwd)
        {
            var factory = new MqttFactory();
            MqttClientOptionsBuilder builder;

            this.Client = factory.CreateMqttClient();
            builder     = new MqttClientOptionsBuilder()
                          .WithClientId(this._id)
                          .WithTcpServer(this._host, this._port)
                          .WithCleanSession();

            if (this._ssl)
            {
                builder.WithTls(new MqttClientOptionsBuilderTlsParameters {
                    AllowUntrustedCertificates = true,
                    UseTls = true
                });
            }

            if (string.IsNullOrEmpty(user))
            {
                user   = null;
                passwd = null;
            }

            if (user != null)
            {
                builder.WithCredentials(user, passwd);
            }

            this.Client.UseDisconnectedHandler(e => { this.OnDisconnect_HandlerAsync(); });
            this.Client.UseConnectedHandler(e => { this.OnConnect_Handler(); });
            this.Client.UseApplicationMessageReceivedHandler(this.OnMessage_Handler);

            this._client_options = builder.Build();
            await this.Client.ConnectAsync(this._client_options).ConfigureAwait(false);
        }
Exemplo n.º 14
0
        private async Task <IManagedMqttClient> ConnectAsync(string clientId, string mqttServerAddress, int port, string username, string password, bool useTLS, CancellationToken token)
        {
            var mqttClientFactory = new MqttFactory();
            var builder           = new MqttClientOptionsBuilder();

            builder.WithTcpServer(mqttServerAddress, port);
            if (!string.IsNullOrWhiteSpace(clientId))
            {
                builder.WithClientId(clientId);
            }

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                builder.WithCredentials(username, password);
            }

            if (useTLS)
            {
                builder.WithTls();
            }

            var options = builder.Build();


            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)
                                 .Build();

            //todo add a logger provided to the function CreateMqttClient
            var client = mqttClientFactory.CreateManagedMqttClient(new MqttNetLogger(logger));
            await client.StartAsync(managedOptions);

            await client.WaitForConnectAsync(2000, token);

            return(client);
        }
        private IMqttClientOptions GetConnectOptions()
        {
            var builder = new MqttClientOptionsBuilder()
                          .WithTcpServer(Configuration.Host, Configuration.Port)
                          .WithProtocolVersion(MqttProtocolVersion.V311);

            if (!string.IsNullOrWhiteSpace(Configuration.Session.ClientId))
            {
                // use a session but expire the session after 6h
                // we accept short outages less than 6h
                if (Configuration.Session.Clean)
                {
                    Console.WriteLine("Starting with a clean mqtt session ..");
                }

                builder
                .WithClientId(Configuration.Session.ClientId)
                .WithCleanSession(Configuration.Session.Clean)
                .WithSessionExpiryInterval(60 * 60 * 6);
            }

            if (Configuration.Auth.Enable)
            {
                builder.WithCredentials(Configuration.Auth.Username, Configuration.Auth.Password);
            }

            if (Configuration.Ssl.Enable)
            {
                builder.WithTls(parameters =>
                {
                    parameters.UseTls = true;
                    parameters.AllowUntrustedCertificates = Configuration.Ssl.AllowUntrustedCertificates;
                });
            }

            return(builder.Build());
        }
        private IMqttClientOptions GetMqttClientOptions(MqttConnectionString connectionString)
        {
            var mqttClientOptionsBuilder = new MqttClientOptionsBuilder()
                                           .WithClientId(connectionString.ClientId)
                                           .WithTcpServer(connectionString.Server, connectionString.Port);

            if (!string.IsNullOrEmpty(connectionString.Username) || !string.IsNullOrEmpty(connectionString.Password))
            {
                _logger.LogTrace($"Using authentication, username: '******'");
                mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithCredentials(connectionString.Username, connectionString.Password);
            }

            if (connectionString.Tls)
            {
                var certificates = new List <X509Certificate>();
                if (connectionString.Certificate != null)
                {
                    using (var cert = new X509Certificate(connectionString.Certificate))
                    {
                        certificates.Add(cert);
                    }
                }

                mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithTls(new MqttClientOptionsBuilderTlsParameters
                {
                    UseTls       = true,
                    Certificates = certificates,

                    AllowUntrustedCertificates        = false,
                    IgnoreCertificateChainErrors      = false,
                    IgnoreCertificateRevocationErrors = false
                });
            }

            return(mqttClientOptionsBuilder.Build());
        }
Exemplo n.º 17
0
        public IMqttClientOptions GetOptions()
        {
            var builder = new MqttClientOptionsBuilder()
                          .WithClientId(ClientId)
                          .WithTcpServer(Server)
                          .WithCleanSession();

            if (Tls)
            {
                builder = builder.WithTls(new MqttClientOptionsBuilderTlsParameters
                {
                    UseTls      = true,
                    SslProtocol = System.Security.Authentication.SslProtocols.Tls12,
                    CertificateValidationHandler = _ => true
                });
            }

            if (User != null)
            {
                builder = builder.WithCredentials(User, Password);
            }

            return(Configure(builder).Build());
        }
        public async Task ConnectAsync()
        {
            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(_MQTTSettings.Value.ClientId)
                                 .WithCredentials(_MQTTSettings.Value.Username, _MQTTSettings.Value.Password)
                                 .WithTcpServer(_MQTTSettings.Value.Server, _MQTTSettings.Value.Port)
                                 .WithCleanSession();

            var options = _MQTTSettings.Value.MqttSecure ?
                          messageBuilder
                          .WithTls()
                          .Build() :
                          messageBuilder
                          .Build();

            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(System.TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)
                                 .Build();

            _client = new MqttFactory().CreateManagedMqttClient();

            await _client.StartAsync(managedOptions);
        }
Exemplo n.º 19
0
 /// <inheritdoc cref="IMqttClientConfigBuilder.DisableTls" />
 public IMqttClientConfigBuilder DisableTls()
 {
     _builder.WithTls(parameters => { parameters.UseTls = false; });
     return(this);
 }
Exemplo n.º 20
0
        private static int _iLastUpdateThreshold      = 5;    // Minutes

        public static async void StartMQTT(string strMQTTServer, bool bMQTTTLS, string strClientId, string strUser, string strPassword, MessageHandler messageHandler)
        {
            IManagedMqttClientOptions             options;
            MqttClientOptionsBuilder              clientOptions;
            MqttClientOptionsBuilderTlsParameters optionsTLS;
            int iPort = 0;

            string[] strMQTTServerArray;
            string   strMQTTBroker;

            Logging.WriteDebugLog("MQTT.StartMQTT()");

            if (strMQTTServer == null || strMQTTServer == "")
            {
                return;
            }

            _timerMQTT = new Timer(Update, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30));

            _strClientId    = strClientId;
            _messageHandler = messageHandler;

            if (strMQTTServer.Contains(":"))
            {
                strMQTTServerArray = strMQTTServer.Split(new char[] { ':' });
                if (strMQTTServerArray.Length != 2)
                {
                    Logging.WriteDebugLog("MQTT.StartMQTT() MQTTBroker field has incorrect syntax (host or host:port)");
                    return;
                }

                if (!int.TryParse(strMQTTServerArray[1], out iPort) || iPort == 0)
                {
                    Logging.WriteDebugLog("MQTT.StartMQTT() MQTTBroker field has incorrect syntax - port not non-zero numeric (host or host:port)");
                    return;
                }

                if (strMQTTServerArray[0].Length == 0)
                {
                    Logging.WriteDebugLog("MQTT.StartMQTT() MQTTBroker field has incorrect syntax - missing host (host or host:port)");
                    return;
                }

                strMQTTBroker = strMQTTServerArray[0];

                Logging.WriteDebugLog("MQTT.StartMQTT() Host: {0}, Port: {1}", strMQTTBroker, iPort);
            }
            else
            {
                strMQTTBroker = strMQTTServer;

                Logging.WriteDebugLog("MQTT.StartMQTT() Host: {0}", strMQTTBroker);
            }

            clientOptions = new MqttClientOptionsBuilder().WithClientId(_strClientId).WithTcpServer(strMQTTBroker, (iPort == 0 ? null : iPort));
            if (strUser != "")
            {
                clientOptions = clientOptions.WithCredentials(strUser, strPassword);
            }
            if (bMQTTTLS)
            {
                optionsTLS = new MqttClientOptionsBuilderTlsParameters
                {
                    IgnoreCertificateChainErrors = true,
                    UseTls = true,
                    IgnoreCertificateRevocationErrors = true,
                    AllowUntrustedCertificates        = true,
                    SslProtocol = System.Security.Authentication.SslProtocols.Tls12
                };

                clientOptions = clientOptions.WithTls(optionsTLS);
            }

            options = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(5)).WithClientOptions(clientOptions.Build()).Build();

            _mqtt = new MqttFactory().CreateManagedMqttClient();

            _mqtt.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(MessageProcessor);

            await _mqtt.StartAsync(options);
        }
Exemplo n.º 21
0
    /// <summary>
    /// Connects the Sparkplug node to the MQTT broker.
    /// </summary>
    /// <exception cref="ArgumentNullException">The options are null.</exception>
    /// <returns>A <see cref="Task"/> representing any asynchronous operation.</returns>
    private async Task ConnectInternal()
    {
        if (this.options is null)
        {
            throw new ArgumentNullException(nameof(this.options));
        }

        // Increment the session number.
        this.IncrementLastSessionNumber();

        // Reset the sequence number.
        this.ResetLastSequenceNumber();

        // Get the will message.
        var willMessage = this.MessageGenerator.GetSparkPlugNodeDeathMessage(
            this.NameSpace,
            this.options.GroupIdentifier,
            this.options.EdgeNodeIdentifier,
            this.LastSessionNumber);

        // Build up the MQTT client and connect.
        this.options.CancellationToken ??= CancellationToken.None;

        var builder = new MqttClientOptionsBuilder()
                      .WithClientId(this.options.ClientId)
                      .WithCredentials(this.options.UserName, this.options.Password)
                      .WithCleanSession(false)
                      .WithProtocolVersion(MqttProtocolVersion.V311);

        if (this.options.UseTls)
        {
            builder.WithTls();
        }

        if (this.options.WebSocketParameters is null)
        {
            builder.WithTcpServer(this.options.BrokerAddress, this.options.Port);
        }
        else
        {
            builder.WithWebSocketServer(this.options.BrokerAddress, this.options.WebSocketParameters);
        }

        if (this.options.ProxyOptions != null)
        {
            builder.WithProxy(
                this.options.ProxyOptions.Address,
                this.options.ProxyOptions.Username,
                this.options.ProxyOptions.Password,
                this.options.ProxyOptions.Domain,
                this.options.ProxyOptions.BypassOnLocal);
        }

        builder.WithWillMessage(willMessage);
        this.ClientOptions = builder.Build();

        // Debug output.
        this.Logger?.Debug("CONNECT Message: {@ClientOptions}", this.ClientOptions);

        await this.Client.ConnectAsync(this.ClientOptions, this.options.CancellationToken.Value);
    }
Exemplo n.º 22
0
        public static async Task Connect()
        {
            string clientId     = "OnGuard";
            string mqttURI      = Storage.GetGlobalString("MQTTServerAddress");
            string mqttUser     = Storage.GetGlobalString("MQTTUser");
            string mqttPassword = Storage.GetGlobalString("MQTTPassword");
            int    mqttPort     = Storage.GetGlobalInt("MQTTPort");
            bool   mqttSecure   = Storage.GetGlobalBool("MQTTUseSecureLink");


            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(clientId)
                                 .WithCredentials(mqttUser, mqttPassword)
                                 .WithTcpServer(mqttURI, mqttPort)
                                 .WithCleanSession();

            var options = mqttSecure
        ? messageBuilder
                          .WithTls()
                          .Build()
        : messageBuilder
                          .Build();



            if (s_client.IsConnected == false)
            {
                try
                {
                    MqttClientAuthenticateResult result = await s_client.ConnectAsync(options, CancellationToken.None).ConfigureAwait(false);

                    if (result.ResultCode == MqttClientConnectResultCode.Success)
                    {
                        Dbg.Write("MQTTPublish - Connected to server!");
                        _loggedError        = false;
                        _loggedNotConnected = false;
                    }
                    else
                    {
                        HandleError(result); // Here we let it go setup the disconnect handler -- things may improve in the future
                    }
                }
                catch (MqttCommunicationException ex)
                {
                    if (!_loggedNotConnected)
                    {
                        Dbg.Write("MQTTPublish - The Connection to server failed - it is unreachable - check your server status and your MQTT settings: " + ex.Message);
                        _loggedNotConnected = true;
                    }

                    return;
                }
                catch (Exception ex)
                {
                    if (!_loggedNotConnected)
                    {
                        Dbg.Write("MQTTPublish - Connection to server failed: " + ex.Message);
                        _loggedNotConnected = true;
                    }
                    return;
                }
            }
        }
Exemplo n.º 23
0
        public static async Task <bool> Connect()
        {
            if (File.Exists(Path.Combine(App.ExePath, "mqtt.config")))
            {
                var configMap = new ExeConfigurationFileMap
                {
                    ExeConfigFilename = Path.Combine(App.ExePath, "mqtt.config")
                };

                var config =
                    ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

                var myParamsSection = config.GetSection("mqtt");

                var myParamsSectionRawXml = myParamsSection.SectionInformation.GetRawXml();
                var sectionXmlDoc         = new XmlDocument();
                sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml));
                var handler = new NameValueSectionHandler();

                var appSection =
                    handler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection;

                mqttURI      = appSection["mqttURI"];
                mqttUser     = appSection["mqttUser"];
                mqttPassword = appSection["mqttPassword"];
                mqttPort     = Convert.ToInt32(appSection["mqttPort"]);
                mqttSecure   = appSection["mqttSecure"] == "True";

                if (string.IsNullOrEmpty(mqttURI))
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }

            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(ClientId)
                                 .WithCredentials(mqttUser, mqttPassword)
                                 .WithTcpServer(mqttURI, mqttPort)
                                 .WithCleanSession();

            var options = mqttSecure
              ? messageBuilder
                          .WithTls()
                          .Build()
              : messageBuilder
                          .Build();

            try
            {
                var result = await mqttClient.ConnectAsync(options, CancellationToken.None);

                if (result.ResultCode != MqttClientConnectResultCode.Success)
                {
                    App.Log.Error($"MQTT CONNECT FAILED: {result.ResultCode} {result.ReasonString}");
                }

                return(result.ResultCode == MqttClientConnectResultCode.Success);
            }
            catch (Exception ex)
            {
                // ignore this exception
                App.Log.Error($"MQTT CONNECT FAILED", ex);
            }

            return(false);
        }
Exemplo n.º 24
0
        private async void Connect_Click(object sender, EventArgs e)
        {
            if (mqttClient == null)
            {
                mqttClient = new MqttFactory().CreateMqttClient();
                mqttClient.UseApplicationMessageReceivedHandler(new
                                                                Action <MqttApplicationMessageReceivedEventArgs>(MqttClient_ApplicationMessageReceived));
                mqttClient.UseDisconnectedHandler(new
                                                  Action <MqttClientDisconnectedEventArgs>(MqttClient_Disconnected));
                mqttClient.UseConnectedHandler(new
                                               Action <MqttClientConnectedEventArgs>(MqttClient_Connected));
            }
            if (mqttClient.IsConnected)
            {
                return;
            }
            status.Text = "Connecting...";
            var clientOptionsBuilder = new MqttClientOptionsBuilder();

            clientOptionsBuilder.WithProtocolVersion((MqttProtocolVersion)version.SelectedValue);
            if (!string.IsNullOrWhiteSpace(username.Text))
            {
                if (!string.IsNullOrWhiteSpace(password.Text))
                {
                    clientOptionsBuilder.WithCredentials(username.Text, password.Text);
                }
                else
                {
                    clientOptionsBuilder.WithCredentials(username.Text);
                }
            }
            if (!string.IsNullOrWhiteSpace(clientId.Text))
            {
                clientOptionsBuilder.WithClientId(clientId.Text);
            }
            if (useTls.Checked)
            {
                clientOptionsBuilder.WithTls();
            }
            if (useWebSocket.Checked)
            {
                clientOptionsBuilder.WithWebSocketServer(host.Text);
            }
            else
            {
                clientOptionsBuilder.WithTcpServer(host.Text, int.Parse(port.Text));
            }
            if (cleanSession.Checked)
            {
                clientOptionsBuilder.WithCleanSession(true);
            }
            else
            {
                clientOptionsBuilder.WithCleanSession(false);
            }
            if (setWill.Checked && !string.IsNullOrWhiteSpace(input.TextValue))
            {
                clientOptionsBuilder.WithWillMessage(BuildMessage());
            }
            try
            {
                await mqttClient.ConnectAsync(clientOptionsBuilder.Build());

                clientId.Text = mqttClient.Options.ClientId;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
        }
Exemplo n.º 25
0
        public static async Task ConnectAsync()
        {
            string clientId       = Guid.NewGuid().ToString();
            string mqttURI        = "127.0.0.1";
            string mqttUser       = "******";
            string mqttPassword   = "******";
            int    mqttPort       = 1883;
            bool   mqttSecure     = false;
            var    messageBuilder = new MqttClientOptionsBuilder()
                                    .WithClientId(clientId)
                                    .WithCredentials(mqttUser, mqttPassword)
                                    .WithTcpServer(mqttURI, mqttPort)
                                    .WithProtocolVersion(MqttProtocolVersion.V500)
                                    //.WithTls()
                                    .WithCleanSession();

            var options        = mqttSecure ? messageBuilder.WithTls().Build() : messageBuilder.Build();
            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)

                                 .Build();

            client = new MqttFactory().CreateManagedMqttClient();
            await client.StartAsync(managedOptions);



            client.UseConnectedHandler(e =>
            {
                Console.WriteLine("Connected successfully with MQTT Brokers.");
            });


            await SubscribeAsync("+/+/+/+");

            //await SubscribeAsync("let/me/in/pep");

            Console.WriteLine(client.IsStarted + " " + client.IsConnected);

            client.UseDisconnectedHandler(e =>
            {
                Console.WriteLine("Disconnected from MQTT Brokers." + e.ClientWasConnected + " " + e?.AuthenticateResult?.ReasonString);
            });

            client.UseApplicationMessageReceivedHandler(e =>
            {
                try
                {
                    string topic = e.ApplicationMessage.Topic;
                    if (string.IsNullOrWhiteSpace(topic) == false)
                    {
                        string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        Console.WriteLine($"Topic: {topic}. Message Received: {payload}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ex);
                }
            });
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            IMessageQueue messageQueue     = new LoggingMQWrapper();
            bool          debugEnvironment = false;

            try
            {
                ConnectionFactory rmqFactory = new ConnectionFactory
                {
                    HostName = Environment.GetEnvironmentVariable("RABBITMQ_HOST"),
                    UserName = Environment.GetEnvironmentVariable("RABBITMQ_USER"),
                    Password = Environment.GetEnvironmentVariable("RABBITMQ_PASSWORD")
                };

                if (rmqFactory.HostName != null)
                {
                    Console.WriteLine($"Connecting to RabbitMQ host {rmqFactory.HostName} as {rmqFactory.UserName} ...");
                    messageQueue = new RabbitMQWrapper(rmqFactory.CreateConnection());
                }
                else
                {
                    debugEnvironment = true;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"RabbitMQ Exception: {e.Message}");
                if (debugEnvironment == false)
                {
                    System.Environment.Exit(1);
                }
            }

            var contextBrokerURL    = Environment.GetEnvironmentVariable("DIWISE_CONTEXT_BROKER_URL");
            var fiwareContextBroker = new ContextBrokerProxy(contextBrokerURL);

            MQTTDecoderRegistry decoders = new MQTTDecoderRegistry(messageQueue, fiwareContextBroker);

            //TestParseData(decoders);

            var mqttFactory = new MqttFactory();

            var mqttUsername = Environment.GetEnvironmentVariable("MQTT_USER");
            var mqttPassword = Environment.GetEnvironmentVariable("MQTT_PASSWORD");
            var mqttHost     = Environment.GetEnvironmentVariable("MQTT_HOST");
            var mqttPort     = Convert.ToInt32(GetEnvVariableOrDefault("MQTT_PORT", "1883"));

            List <string> list = new List <string>();

            // Check if we should subscribe to multiple topics
            var topic      = Environment.GetEnvironmentVariable("MQTT_TOPIC_0");
            var topicIndex = 0;

            while (string.IsNullOrEmpty(topic) == false)
            {
                list.Add(topic);

                topicIndex++;
                topic = Environment.GetEnvironmentVariable($"MQTT_TOPIC_{topicIndex}");
            }

            // If no indexed list of topics was found, we assume that a single topic has been configured the old way
            if (list.Count == 0)
            {
                topic = GetEnvVariableOrDefault("MQTT_TOPIC", "#");
                list.Add(topic);
            }

            var mqttTopics = list.ToArray();

            var builder = new MqttClientOptionsBuilder()
                          .WithClientId(Guid.NewGuid().ToString())
                          .WithTcpServer(mqttHost, mqttPort);

            if (mqttUsername != null)
            {
                if (IsTlsEnabled())
                {
                    builder = builder.WithTls(new MqttClientOptionsBuilderTlsParameters
                    {
                        UseTls = true,
                        AllowUntrustedCertificates        = true,
                        IgnoreCertificateChainErrors      = true,
                        IgnoreCertificateRevocationErrors = true
                    });
                }

                builder = builder
                          .WithCredentials(mqttUsername, mqttPassword)
                          .WithCleanSession();
            }

            var options = builder.Build();

            var client = mqttFactory.CreateMqttClient();

            client.UseConnectedHandler(async(e) =>
            {
                Console.WriteLine("Connected!");

                List <TopicFilter> topicFilters = new List <TopicFilter>();
                foreach (string topic in mqttTopics)
                {
                    Console.WriteLine("Subscribing to topic " + topic + " ...");
                    topicFilters.Add(new TopicFilterBuilder().WithTopic(topic).Build());
                }

                await client.SubscribeAsync(topicFilters.ToArray());
            });

            client.UseApplicationMessageReceivedHandler(e =>
            {
                try
                {
                    ParseMessagePayload(DateTime.Now.ToUniversalTime(), e.ApplicationMessage.Topic, e.ApplicationMessage.Payload, decoders);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Exception caught when calling ParseMessagePayload: {ex.Message}");
                }
            });

            client.UseDisconnectedHandler(async(e) =>
            {
                Console.WriteLine("### MQTT Server dropped connection. Sleeping and reconnecting ... ###");
                Console.WriteLine(e.Exception);
                Console.WriteLine(e.AuthenticateResult);
                await Task.Delay(TimeSpan.FromSeconds(5));

                try
                {
                    await client.ConnectAsync(options);
                    Console.WriteLine("Successfully reconnected to server.");
                }
                catch
                {
                    Console.WriteLine("### RECONNECTING FAILED ###");

                    itIsNotTimeToShutDown = false;
                    terminationEvent.Set();
                }
            });

            Console.WriteLine($"Connecting to MQTT host {mqttHost} ...");
            client.ConnectAsync(options, CancellationToken.None);

            while (itIsNotTimeToShutDown)
            {
                terminationEvent.WaitOne();
            }

            Console.WriteLine("### SHUTTING DOWN ###");
        }
Exemplo n.º 27
0
        private void _connect()
        {
            try
            {
                if (_mqttClient != null && _mqttClient.IsConnected)
                {
                    return;
                }

                if (Options == null)
                {
                    return;
                }

                LastWillMessage        lastWillMsg = new LastWillMessage();
                string                 payload     = JsonConvert.SerializeObject(lastWillMsg);
                MqttApplicationMessage msg         = new MqttApplicationMessage()
                {
                    Payload = Encoding.UTF8.GetBytes(payload),
                    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                    Retain = true,
                    Topic  = string.Format(MQTTTopic.ScadaConnTopic, Options.ScadaId)
                };

                string clientId = "EdgeAgent_" + Guid.NewGuid().ToString("N");
                var    ob       = new MqttClientOptionsBuilder();
                ob.WithClientId(clientId)
                .WithCredentials(Options.MQTT.Username, Options.MQTT.Password)
                .WithCleanSession()
                .WithWillMessage(msg);

                switch (Options.MQTT.ProtocolType)
                {
                case Protocol.TCP:
                    ob.WithTcpServer(Options.MQTT.HostName, Options.MQTT.Port);
                    break;

                case Protocol.WebSocket:
                    ob.WithWebSocketServer(Options.MQTT.HostName);
                    break;

                default:
                    ob.WithTcpServer(Options.MQTT.HostName, Options.MQTT.Port);
                    break;
                }

                if (Options.UseSecure)
                {
                    ob.WithTls();
                }

                var mob = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromMilliseconds(Options.ReconnectInterval))
                          .WithClientOptions(ob.Build())
                          .Build();

                _mqttClient.StartAsync(mob);
            }
            catch (Exception ex)
            {
                //_logger.Error( ex.ToString() );
            }
        }
Exemplo n.º 28
0
        private MqttClientOptionsBuilder CreateOptionsBuilder(ClientCredentials credentials = null)
        {
            MqttClientOptionsBuilder clientOptionsBuilder       = new MqttClientOptionsBuilder();
            MqttClientOptionsBuilderTlsParameters tlsParameters = null;
            string hostName = Settings.Client.BrokerHostname;
            int    portNum  = Settings.Client.BrokerPort;

            //check if broker endpoint for local connections is defined in environment, only possible for connections without credentials
            if (credentials == null)
            {
                string brokerEndpoint = Environment.GetEnvironmentVariable("GE_BROKER_CONNECTION_ENDPOINT");
                if (!string.IsNullOrEmpty(brokerEndpoint))
                {
                    string[] tokens = brokerEndpoint.Split(':');
                    if (tokens.Length == 2)
                    {
                        hostName = tokens[0];
                        portNum  = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture);
                    }
                }
            }
            clientOptionsBuilder.WithCleanSession();
            clientOptionsBuilder.WithClientId(ClientId);
            if (portNum == 443)
            {
                clientOptionsBuilder.WithWebSocketServer(hostName);
            }
            else
            {
                clientOptionsBuilder.WithTcpServer(hostName, portNum);
            }
            if (credentials != null)
            {
                if (credentials.HasCertificates())
                {
                    tlsParameters = new MqttClientOptionsBuilderTlsParameters
                    {
                        UseTls = true,
                        AllowUntrustedCertificates        = Settings.Client.AllowUntrustedCertificates,
                        IgnoreCertificateChainErrors      = Settings.Client.IgnoreCertificateChainErrors,
                        IgnoreCertificateRevocationErrors = Settings.Client.IgnoreCertificateRevocationErrors,
                        CertificateValidationHandler      = CertificateValidationCallback,
                        Certificates = credentials.ClientCertAndCaChain,
                        SslProtocol  = SslProtocols.Tls12
                    };
                    clientOptionsBuilder.WithTls(tlsParameters);
                }
                if (credentials.IsUserNameAndPasswordRequired())
                {
                    credentials.GetUserNameAndPassword(ClientId, out string username, out string password);
                    clientOptionsBuilder.WithCredentials(username, password);
                }
            }

            // settings for connection timeout and MQTT kepp alive interval, given in seconds
            // (defaults in MQTTnet stack are CommunicationTimeout = 10 sec and KeepAlivePeriod = 15 sec.,
            //  see in MqttClientOptions.cs of MQTTnet)
            clientOptionsBuilder.WithCommunicationTimeout(new TimeSpan(0, 0, Settings.Client.CommunicationTimeout));
            clientOptionsBuilder.WithKeepAlivePeriod(new TimeSpan(0, 0, Settings.Client.MqttKeepAlivePeriod));
            return(clientOptionsBuilder);
        }
Exemplo n.º 29
0
        private async Task ConnectionMqttDeviceClient(CancellationToken stopToken)
        {
            downstreamClient = factory.CreateMqttClient();

            var optionsBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(downstreamClientCredentials.ClientId)
                                 .WithTcpServer(downstreamClientCredentials.BrokerAddress, downstreamClientCredentials.BrokerPort)
                                 .WithCleanSession(this.device.MqttUseCleanSession);

            if (downstreamClientCredentials.UseCredentials)
            {
                optionsBuilder = optionsBuilder.WithCredentials(downstreamClientCredentials.UserName, downstreamClientCredentials.Password);
            }

            if (downstreamClientCredentials.UseTls)
            {
                IList <X509Certificate2> certificates = new List <X509Certificate2>();
                var caCert     = new X509Certificate2(downstreamClientCredentials.CACertificateFile);
                var clientCert = new X509Certificate2(downstreamClientCredentials.ClientCertificateFile);
                X509Certificate2 clientCertPrivateKeyPair = null;

                certificates.Add(caCert);

                if (downstreamClientCredentials.RequiresClientKeyFile)
                {
                    byte[] privateKeyBuffer = GetPrivateKeyBytesFromPem(downstreamClientCredentials.ClientKeyFile, out TlsAlgorithm algorithm);
                    switch (algorithm)
                    {
                    case TlsAlgorithm.ECC:
                        var ecdsa = ECDsa.Create();
                        ecdsa.ImportECPrivateKey(privateKeyBuffer, out _);
                        clientCertPrivateKeyPair = clientCert.CopyWithPrivateKey(ecdsa);
                        break;

                    case TlsAlgorithm.RSA:
                        var rsa = RSA.Create();
                        rsa.ImportRSAPrivateKey(privateKeyBuffer, out _);
                        clientCertPrivateKeyPair = clientCert.CopyWithPrivateKey(rsa);
                        break;

                    case TlsAlgorithm.Unknown:
                        throw new Exception("Failed to detect private key algorithm");
                    }

                    // Export the certificate in PFX format to ensure the private key is included
                    clientCertPrivateKeyPair = new X509Certificate2(clientCertPrivateKeyPair.Export(X509ContentType.Pfx));
                    certificates.Add(clientCertPrivateKeyPair);
                }
                else
                {
                    certificates.Add(clientCert);
                }

                // Add the CA certificate to the users CA store
                using (var caCertStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser))
                {
                    caCertStore.Open(OpenFlags.ReadWrite);
                    caCertStore.Add(caCert);
                }

                // Add the client certificate to the users personal store
                using (var personalCertsStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
                {
                    personalCertsStore.Open(OpenFlags.ReadWrite);
                    if (clientCertPrivateKeyPair != null)
                    {
                        personalCertsStore.Add(clientCertPrivateKeyPair);
                    }
                    else
                    {
                        personalCertsStore.Add(clientCert);
                    }
                }

                optionsBuilder = optionsBuilder.WithTls(new MqttClientOptionsBuilderTlsParameters {
                    Certificates = certificates,
                    UseTls       = true,
                    AllowUntrustedCertificates        = false,
                    IgnoreCertificateChainErrors      = false,
                    IgnoreCertificateRevocationErrors = true,
                    CertificateValidationHandler      = (MqttClientCertificateValidationCallbackContext c) =>
                    {
                        Console.WriteLine("Certificate--> issuer: " + c.Certificate.Issuer + " subject: " + c.Certificate.Subject);
                        return(true);
                    }
                });
            }

            var downstreamOptions = optionsBuilder.Build();

            try
            {
                logger.LogInformation($"Connecting downstream client {downstreamClientCredentials.ClientId}");

                downstreamClient.UseConnectedHandler(async e => {
                    logger.LogInformation($"Device {downstreamClientCredentials.ClientId} connected");

                    // Subscribe to cloud to device messages
                    logger.LogDebug($"Begin Device to Cloud subscription for Device {downstreamClientCredentials.ClientId} connected");
                    foreach (var topic in device.LocalDeviceMqttSubscriptions.DeviceToCloudTopics)
                    {
                        logger.LogDebug($"Subscribing to topic {topic}");
                        await downstreamClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(topic.Topic).Build());
                    }


                    // Subscribe to twin request messages
                    logger.LogDebug($"Begin Twin Request subscription for Device {downstreamClientCredentials.ClientId} connected");
                    foreach (var topic in device.LocalDeviceMqttSubscriptions.TwinRequestTopics)
                    {
                        logger.LogDebug($"Subscribing to topic {topic}");
                        await downstreamClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(topic.Topic).Build());
                    }
                    await Task.CompletedTask;
                });

                downstreamClient.UseDisconnectedHandler(async e => {
                    logger.LogInformation($"Device {downstreamClientCredentials.ClientId} disconnected");
                    await Task.CompletedTask;
                });

                downstreamClient.UseApplicationMessageReceivedHandler(async e => {
                    await mqttClient.MessageReceivedHandler(e, stopToken);
                });

                await downstreamClient.ConnectAsync(downstreamOptions, stopToken);
            } catch (Exception ex)
            {
                logger.LogError($"{ex}");
            }
            await Task.CompletedTask;
        }
Exemplo n.º 30
0
        /// <summary>
        /// Adds the MQTT service both Subscribe and Publish
        /// </summary>
        /// <param name="services">The services.</param>
        /// <param name="server">The server.</param>
        /// <param name="defaultTopic">The default topic.</param>
        /// <param name="port">The port.</param>
        /// <param name="ssl">if set to <c>true</c> [SSL].</param>
        /// <param name="certSubject">The cert subject.</param>
        /// <param name="certIssuer">The cert issuer.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">
        /// services
        /// or
        /// server
        /// </exception>
        /// <exception cref="System.ArgumentNullException">services
        /// or
        /// server</exception>
        public static IServiceCollection AddMqttService(this IServiceCollection services,
                                                        string server,
                                                        string defaultTopic,
                                                        int?port           = null,
                                                        bool ssl           = false,
                                                        string certSubject = null,
                                                        string certIssuer  = null,
                                                        string username    = null,
                                                        string password    = null)
        {
            if (services is null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (string.IsNullOrWhiteSpace(server))
            {
                throw new ArgumentNullException(nameof(server));
            }

            services.AddSingleton <MqttService>(i =>
            {
                var optionBuilder = new MqttClientOptionsBuilder()
                                    .WithTcpServer(server, port);

                if (!string.IsNullOrWhiteSpace(username) &&
                    !string.IsNullOrWhiteSpace(password))
                {
                    optionBuilder.WithCredentials(username, password);
                }

                if (ssl)
                {
                    optionBuilder.WithTls(p =>
                    {
                        p.UseTls = true;
                        if (!string.IsNullOrWhiteSpace(certSubject) &&
                            !string.IsNullOrWhiteSpace(certIssuer))
                        {
                            p.CertificateValidationHandler = c =>
                            {
                                return
                                (string.Equals(certSubject, c.Certificate.Subject, StringComparison.OrdinalIgnoreCase) &&
                                 string.Equals(certIssuer, c.Certificate.Issuer, StringComparison.OrdinalIgnoreCase));
                            };
                        }
                    });
                }

                var options = optionBuilder
                              .Build();

                return(new MqttService(defaultTopic,
                                       options,
                                       i,
                                       i.GetService <IConfiguration>(),
                                       i.GetService <ILogger <MqttService> >()));
            });

            services.AddSingleton <IMqttClientPublishService>(i => i.GetService <MqttService>());
            services.AddSingleton <IMqttClientSubscribeService>(i => i.GetService <MqttService>());

            services.AddSingleton <IHostedService>(i => i.GetService <MqttService>());

            return(services);
        }