Exemplo n.º 1
0
        static string ReceiveMesHandler(MQTTnet.Client.IMqttClient mqttClient)
        {
            string mes = null;

            do
            {
                mqttClient.UseApplicationMessageReceivedHandler(e =>
                {
                    try
                    {
                        string topic = e.ApplicationMessage.Topic;

                        if (string.IsNullOrWhiteSpace(topic) == false)
                        {
                            mes = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        }
                    }
                    catch (Exception ex)
                    {
                        mes = ex.Message;
                    }
                });
            } while (mes == null);
            return(mes);
        }
        public MqttClient(ILogger <MqttClient> logger)
        {
            _logger = logger;

            var factory = new MqttFactory();

            _client = factory.CreateMqttClient();
        }
Exemplo n.º 3
0
 public MQTTnetClient(string host, int port, bool isSsl)
 {
     this.host  = host;
     this.port  = port;
     this.isSsl = isSsl;
     client     = new MqttFactory().CreateMqttClient();
     mqttApplicationMessageReceivedHandler = new MQTTnetApplicationMessageReceivedHandler();
 }
        public MqttClient(ILogger <MqttClient> logger, IOptions <MqttSettings> settings, IHostApplicationLifetime applicationLifetime)
        {
            this.logger              = logger;
            this.settings            = settings;
            this.applicationLifetime = applicationLifetime;
            var factory = new MQTTnet.MqttFactory();

            client = factory.CreateMqttClient();

            options = new MqttClientOptionsBuilder()
                      .WithTcpServer(settings.Value.HostName)
                      .WithCredentials(settings.Value.Username, settings.Value.Password)
                      .Build();
        }
Exemplo n.º 5
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());
            }
        }
Exemplo n.º 6
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);
        }