Example #1
0
        public async Task ConnectAsync(string clientId, string username, string password, bool cleanSession, TimeSpan keepAlivePeriod, CancellationToken cancellationToken)
        {
            var builder = new MqttClientOptionsBuilder()
                          .WithTcpServer(host, port)
                          .WithClientId(clientId)
                          .WithCredentials(username, password)
                          .WithCleanSession(cleanSession)
                          .WithKeepAlivePeriod(keepAlivePeriod);

            // default is V311, supports V500
            // builder.WithProtocolVersion(MqttProtocolVersion.V500);
            if (isSsl)
            {
                builder.WithTls();
            }

            client.UseConnectedHandler(HandleConnection);
            client.UseDisconnectedHandler(HandleDisconnection);
            client.ApplicationMessageReceivedHandler = mqttApplicationMessageReceivedHandler;

            MqttClientAuthenticateResult connectResult;

            try
            {
                connectResult = await client.ConnectAsync(builder.Build(), cancellationToken);
            }
            catch (Exception e)
            {
                throw new MqttException(cause: e);
            }

            ValidateConnectResult(connectResult);
        }
        public async Task ConnectAsync()
        {
            logger.LogInformation($"Connecting MQTT on {settings.Value.HostName}");

            await client.ConnectAsync(options, CancellationToken.None);

            client.UseApplicationMessageReceivedHandler(async message =>
            {
                var payload = message.ApplicationMessage.ConvertPayloadToString();
                logger.LogInformation($"Received {message.ApplicationMessage.Topic} {payload}");

                if (commandActions.TryGetValue(message.ApplicationMessage.Topic, out var command))
                {
                    await command(payload);
                }
            });

            client.UseDisconnectedHandler(p =>
            {
                logger.LogInformation("MQTT disconnected, terminating application");
                applicationLifetime.StopApplication();
            });

            logger.LogInformation("Connected");
        }
Example #3
0
        public async void ConnectAsync(string ip, string username, string password, List <string> topics)
        {
            var factory = new MqttFactory();

            mqttClient = factory.CreateMqttClient();
            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(ip)
                          .WithCredentials(username, password)
                          .Build();

            mainOptions = options;
            await mqttClient.ConnectAsync(options, CancellationToken.None);

            foreach (var t in topics)
            {
                await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(t).Build());
            }
        }
Example #4
0
 public void Reconnect(List <string> topics)
 {
     mqttClient.UseDisconnectedHandler(async e =>
     {
         await Task.Delay(TimeSpan.FromSeconds(5));
         try
         {
             await mqttClient.ConnectAsync(mainOptions, CancellationToken.None);
             if (mqttClient.IsConnected)
             {
                 foreach (var t in topics)
                 {
                     await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(t).Build());
                 }
             }
         }
         catch
         {
         }
     });
 }
Example #5
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 { }
         });
     }
 }
        public async Task ConnectToBrokerAsync(string nelloTopicId)
        {
            try
            {
                _nelloTopicId = nelloTopicId;

                var options = new MqttClientOptionsBuilder()
                              .WithTcpServer(SERVER_ADDRESS, SERVER_PORT)
                              .Build();

                _client.UseDisconnectedHandler(async e =>
                {
                    try
                    {
                        await _client.ReconnectAsync();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString());
                    }
                });

                _client.UseConnectedHandler(async e =>
                {
                    try
                    {
                        foreach (var topic in _mqttListeningTopics)
                        {
                            await SubscribeToTopicAsync(string.Format("{0}{1}/{2}", TOPIC_PREFIX, _nelloTopicId, topic));
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString());
                    }
                });

                _client.UseApplicationMessageReceivedHandler(e =>
                {
                    try
                    {
                        if (e.ApplicationMessage.Topic.StartsWith("/nello_one"))
                        {
                            var args      = new MqttMessageEventArgs();
                            args.ClientId = e.ClientId;
                            args.Message  = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                            args.Topic    = e.ApplicationMessage.Topic;
                            MqttMessageReceived?.Invoke(this, args);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString());
                    }
                });

                await _client.ConnectAsync(options);
            }
            catch (Exception ex)
            {
                _logger.LogError("ConnectToBrokerAsync error:\n" + ex.ToString());
            }
        }
Example #7
0
        public async Task <bool> ConnectAsync(string clientId, string host, int port, bool tls, string username, string password)
        {
            this.mqttState.AddMessage($"connecting to {host}");
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(clientId)
                          .WithTcpServer(host, port)
                          .WithCleanSession();

            if (!string.IsNullOrEmpty(username))
            {
                options = options.WithCredentials(username, password);
            }

            if (tls)
            {
                options = options.WithTls();
            }

            client = new MqttFactory().CreateMqttClient();

            var t  = new TaskCompletionSource <Boolean>();
            var ct = new CancellationTokenSource(5000); // timeout ms

            ct.Token.Register(() => { if (!t.Task.IsCompleted)
                                      {
                                          t.SetResult(false);
                                      }
                              }, useSynchronizationContext: false);
            client.UseConnectedHandler(e => {
                this.mqttState.AddMessage("Connected");
                mqttState.SetConnected(true);
                t.SetResult(true);
            });

            client.UseDisconnectedHandler(e => {
                this.mqttState.AddMessage("Disconnected");
                mqttState.SetConnected(false);
            });

            client.UseApplicationMessageReceivedHandler(e =>
            {
                var subscription = mqttState.Subscriptions.SingleOrDefault(s => s.Topic == e.ApplicationMessage.Topic);
                if (subscription != null)
                {
                    subscription.AddMessage(
                        new MqttSubscriptionMessage(
                            e.ApplicationMessage.Topic,
                            Encoding.Default.GetString(e.ApplicationMessage.Payload),
                            DateTime.Now)
                        );
                }
            });


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

                if (result.ResultCode != MQTTnet.Client.Connecting.MqttClientConnectResultCode.Success)
                {
                    this.mqttState.AddMessage("Error: " + result.ReasonString);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message + " : " + e.StackTrace);
                t.SetResult(false);
            }

            return(await t.Task);
        }