Exemple #1
0
        public async Task ConnectAsync()
        {
            if (mqttClient == null)
            {
                mqttClient = new MqttFactory().CreateMqttClient();
            }

            var mqBuild = new MqttClientOptionsBuilder().WithTcpServer(connectIP, port);

            mqoptions = mqBuild.WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V310).Build();

            mqttClient.UseApplicationMessageReceivedHandler(ReceivedHandler);

            mqttClient.UseConnectedHandler(ConnectedHandler);

            mqttClient.UseDisconnectedHandler(DisconnectedHandler);

            Console.WriteLine("开始连接MQTT");

            try
            {
                var mqttConnectResult = await mqttClient.ConnectAsync(mqoptions);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemple #2
0
        /// <summary>
        /// Converts the connection options to client options.
        /// </summary>
        public IMqttClientOptions ToMqttClientOptions()
        {
            MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder()
                                               .WithTcpServer(Server, Port > 0 ? Port : null);

            if (!string.IsNullOrEmpty(ClientID))
            {
                builder.WithClientId(ClientID);
            }

            if (!string.IsNullOrEmpty(Username))
            {
                builder.WithCredentials(Username, Password);
            }

            if (Timeout > 0)
            {
                builder.WithCommunicationTimeout(TimeSpan.FromMilliseconds(Timeout));
            }

            if (ProtocolVersion > MqttProtocolVersion.Unknown)
            {
                builder.WithProtocolVersion(ProtocolVersion);
            }

            return(builder.Build());
        }
Exemple #3
0
        public async Task MQTTClientConnect(string URI)
        {
            MqttClientOptionsBuilder MQOptions = new MqttClientOptionsBuilder();

            MQOptions.WithClientId(MQTT_CLIENT_ID);
            MQOptions.WithWebSocketServer(URI);
            MQOptions.WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311);
            MQOptions.WithTls();

            await mqClient.ConnectAsync(MQOptions.Build()).ConfigureAwait(false);
        }
Exemple #4
0
        public async Task Connect(string username, string server, int port)
        {
            var clientOptionsBuilder = new MqttClientOptionsBuilder();

            clientOptionsBuilder.WithProtocolVersion((MqttProtocolVersion.V310));
            if (!string.IsNullOrWhiteSpace(username))
            {
                MqttClientCredentials credentials = new MqttClientCredentials();
                credentials.Username = username;
                clientOptionsBuilder.WithCredentials(credentials);
            }

            clientOptionsBuilder.WithTcpServer(server, port);

            await _mqttClient.ConnectAsync(clientOptionsBuilder.Build());
        }
Exemple #5
0
 /// <inheritdoc cref="IMqttClientConfigBuilder.UseProtocolVersion" />
 public IMqttClientConfigBuilder UseProtocolVersion(MqttProtocolVersion value)
 {
     _builder.WithProtocolVersion(value);
     return(this);
 }
Exemple #6
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);
            }
        }
Exemple #7
0
        public static MqttStatus Connect(string url, MqttConfig config)
        {
            Guid key = Guid.NewGuid();

            try
            {
#if DEBUG
                IMqttClient client = new MqttFactory().CreateMqttClient(new ConsoleLogger());
#else
                IMqttClient client = new MqttFactory().CreateMqttClient();
#endif

                var b = new MqttClientOptionsBuilder()
                        .WithTcpServer(url, config.Port)
                        .WithKeepAlivePeriod(TimeSpan.FromSeconds(config.KeepAlive))
                        .WithMaximumPacketSize(Convert.ToUInt32(config.BufferSize))
                        .WithCommunicationTimeout(TimeSpan.FromSeconds(config.ConnectionTimeout))
                        .WithCleanSession(config.CleanSession);

                if (config.SessionExpiryInterval > 0)
                {
                    b = b.WithSessionExpiryInterval((uint)config.SessionExpiryInterval);
                }

                if (!string.IsNullOrEmpty(config.ClientId))
                {
                    b = b.WithClientId(config.ClientId);
                }

                if (!config.SSLConnection)
                {
                    b = b.WithCredentials(config.UserName, config.Password);
                }

                switch (config.ProtocolVersion)
                {
                case 310:
                    b = b.WithProtocolVersion(MqttProtocolVersion.V310);
                    break;

                case 311:
                    b = b.WithProtocolVersion(MqttProtocolVersion.V311);
                    break;

                case 500:
                    b = b.WithProtocolVersion(MqttProtocolVersion.V500);
                    break;

                default:
                    throw new InvalidDataException("Invalid protocol versions. Valid versions are 310, 311 or 500");
                }


                if (config.SSLConnection)
                {
                    string           base64CACert = RSAKeys.GetPlainBase64(config.CAcertificate);
                    X509Certificate2 caCert       = new X509Certificate2(Convert.FromBase64String(base64CACert));
                    byte[]           caBytes      = caCert.Export(X509ContentType.Cert);

                    string           base64Client = RSAKeys.GetPlainBase64(config.ClientCertificate);
                    X509Certificate2 cliCert      = new X509Certificate2(Convert.FromBase64String(base64Client), config.ClientCerificatePassphrase);
                    cliCert = cliCert.CopyWithPrivateKey(RSAKeys.ImportPrivateKey(config.PrivateKey, new PasswordFinder(config.ClientCerificatePassphrase)));
                    byte[] cliBytes = cliCert.Export(X509ContentType.Pfx);

                    try
                    {
                        var tls = new MqttClientOptionsBuilderTlsParameters
                        {
                            SslProtocol = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls,
                            UseTls      = true,
                            AllowUntrustedCertificates        = true,
                            IgnoreCertificateChainErrors      = true,
                            IgnoreCertificateRevocationErrors = true,

                            Certificates = new List <X509Certificate>()
                            {
                                caCert, cliCert
                            },
                            //CertificateValidationHandler = context => true
                            CertificateValidationCallback = (certificate, chain, sslError, opts) => true
                        };

                        b = b.WithTls(tls);
                    }
                    finally
                    {
                        caCert.Dispose();
                        cliCert.Dispose();
                    }
                }


                client.UseDisconnectedHandler(async e =>
                {
                    try
                    {
                        if (Connections.ContainsKey(key))
                        {
                            await Task.Delay(TimeSpan.FromSeconds(config.AutoReconnectDelay));
                            MqttClientAuthenticateResult reconnectResult = await client.ConnectAsync(b.Build());
                            SubscribePreviousConnection(key, reconnectResult);
                        }
                    }
                    catch
                    {
                        Connections.Remove(key);
                        client.Dispose();
                    }
                });

                MqttClientAuthenticateResult result = client.ConnectAsync(b.Build()).GetAwaiter().GetResult();

                MqttClient mqtt = new MqttClient(client, config);

                Connections[key] = mqtt;

                SubscribePreviousConnection(key, result);
            }
            catch (Exception ex)
            {
                return(MqttStatus.Fail(Guid.Empty, ex));
            }

            return(MqttStatus.Success(key));
        }