Пример #1
0
 private void subcribeButton_Click(object sender, RoutedEventArgs e)
 {
     if (mqttClient.IsConnected)
     {
         var topic = subcribeTextBox.Text;
         var qos   = int.Parse(subQOSComboBox.Text);
         Task.Run(async() =>
         {
             try
             {
                 var r = await mqttClient.SubscribeAsync(
                     new MqttTopicFilterBuilder()
                     .WithTopic(topic)
                     .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos)
                     .Build());
                 this.Dispatcher.Invoke(new Action(delegate
                 {
                     foreach (string i in subListBox.Items)
                     {
                         if (i == topic)
                         {
                             return;
                         }
                     }
                     subListBox.Items.Add(topic);
                 }));
             }
             catch { }
         });
     }
 }
Пример #2
0
        public async Task <Dictionary <string, Qos> > SubscribeAsync(Dictionary <string, Qos> subscriptions, CancellationToken cancellationToken)
        {
            var builder = new MqttClientSubscribeOptionsBuilder();

            foreach (var entry in subscriptions)
            {
                builder.WithTopicFilter(entry.Key, MapQos(entry.Value));
            }

            try
            {
                var subscribeResult = await client.SubscribeAsync(builder.Build(), cancellationToken);

                var gainedQoses = new Dictionary <string, Qos>();
                foreach (var item in subscribeResult.Items)
                {
                    var gained = (int)item.ResultCode;
                    if (gained < 0 || gained > 2)
                    {
                        throw new MqttException(message: $"Subscribe [topiic={item.TopicFilter.Topic}, qos={item.TopicFilter.QualityOfServiceLevel} failed: [resultCode={item.ResultCode}].");
                    }

                    gainedQoses[item.TopicFilter.Topic] = (Qos)gained;
                }
                return(gainedQoses);
            }
            catch (Exception e)
            {
                throw new MqttException(cause: e);
            }
        }
Пример #3
0
        public async Task <MqttSubscription> SubscribeAsync(string topic)
        {
            var subscription = new MqttSubscription(topic);

            await client.SubscribeAsync(topic);

            mqttState.AddSubscription(subscription);
            return(subscription);
        }
 public async Task SubscribeToTopicAsync(string topicName)
 {
     try
     {
         await _client.SubscribeAsync(new TopicFilterBuilder().WithTopic(topicName).Build());
     }
     catch (Exception ex)
     {
         _logger.LogError("SubscribeToTopicAsync error:\n" + ex.ToString());
     }
 }
        public async Task SubscribeCommandTopicAsync(string topic, Func <string, Task> commandAction)
        {
            if (commandActions.ContainsKey($"{settings.Value.TopicRoot}/{ topic}"))
            {
                return;
            }

            await client.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{settings.Value.TopicRoot}/{topic}").Build());

            commandActions.TryAdd($"{settings.Value.TopicRoot}/{ topic}", commandAction);
            logger.LogInformation($"Subscribed to topic '{settings.Value.TopicRoot}/{topic}'");
        }
Пример #6
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());
            }
        }
Пример #7
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
         {
         }
     });
 }