コード例 #1
0
ファイル: MQTTnetClient.cs プロジェクト: davilu/edge-test
        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);
        }
コード例 #2
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (initial)
            {
                return;
            }

            BrokerTextBox.DataContext     = Tools.Global.setting;
            PortTextBox.DataContext       = Tools.Global.setting;
            ClientTextBox.DataContext     = Tools.Global.setting;
            TLSCheckBox.DataContext       = Tools.Global.setting;
            UserTextBox.DataContext       = Tools.Global.setting;
            PasswordTextBox.DataContext   = Tools.Global.setting;
            KeepAliveTextBox.DataContext  = Tools.Global.setting;
            CleanTextBox.DataContext      = Tools.Global.setting;
            HexCheckBox.DataContext       = Tools.Global.setting;
            ConnectButton.DataContext     = this;
            SettingStackPanel.DataContext = this;

            mqttClient.UseConnectedHandler(async e =>
            {
                this.Dispatcher.Invoke(new Action(delegate
                {
                    MqttIsConnected = mqttClient.IsConnected;
                    subListBox.Items.Clear();
                }));
            });
            mqttClient.UseDisconnectedHandler(async e =>
            {
                this.Dispatcher.Invoke(new Action(delegate
                {
                    MqttIsConnected = mqttClient.IsConnected;
                    subListBox.Items.Clear();
                    subListBox.Items.Add(TryFindResource("MQTTNotConnect") as string ?? "?!");
                }));
            });
            //
            mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                this.Dispatcher.Invoke(new Action(delegate
                {
                    Tools.Logger.ShowDataRaw(new Tools.DataShowRaw {
                        title = $"MQTT → {e.ApplicationMessage.Topic}({(int)e.ApplicationMessage.QualityOfServiceLevel})",
                        data  = e.ApplicationMessage.Payload,
                        color = Brushes.DarkGreen
                    });
                }));
            });


            initial = true;
        }
コード例 #3
0
        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());
            }
        }
コード例 #4
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);
        }