コード例 #1
0
        public async Task <bool> TryConnect(string ip)
        {
            if (String.IsNullOrWhiteSpace(ip))
            {
                return(false);
            }

            try
            {
                var factory = new MqttFactory();
                var builder = new MqttClientOptionsBuilder();

                IMqttClientOptions options = builder
                                             .WithClientId("LedTableSimulator")
                                             .WithTcpServer(ip)
                                             .Build();

                IMqttClient client = factory.CreateMqttClient();

                await client.ConnectAsync(options);

                await client.SubscribeAsync("ledtable/simulation/framebuffer");

                client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(Handler);

                return(client.IsConnected);
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #2
0
        static async Task runClient(int clientId, string topic)
        {
            var clientOptions = options.WithClientId($"dotnet-stress-test-{clientId}").Build();
            var mqttClient    = factory.CreateMqttClient();

            logClientEvents(mqttClient, clientId);
            await mqttClient.ConnectAsync(clientOptions);

            var sub = await mqttClient.SubscribeAsync(topic, connectionQOS);

            if (sub.Any(x => x.ReturnCode == MqttSubscribeReturnCode.Failure))
            {
                throw new Exception($"client {clientId} subscribing to {topic} failed with QOS {connectionQOS}");
            }

            var tasks = new List <Task>();

            int messageNumber = 0;

            while (true)
            {
                tasks.Add(mqttClient.PublishAsync(topic, $"from {clientId} - {messageNumber}th message"));
                messageNumber++;
                await Task.Delay(userMessageInterval);

                //if (messageNumber % userMessageCountBeforeReset == 0)
                //{
                //    await mqttClient.DisconnectAsync();
                //    await mqttClient.ConnectAsync(clientOptions);
                //}
            }
        }
コード例 #3
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());
        }
コード例 #4
0
        private IMqttClientOptions ToMqttClientOptions()
        {
            var builder = new MqttClientOptionsBuilder();

            builder.WithClientId(ClientId)
            .WithCleanSession(false)
            .WithTcpServer(HostName, Port)
            .WithCredentials(UserName, Password);

            if (ShouldUseTls)
            {
                builder
                .WithTls(o =>
                {
                    o.UseTls       = true;
                    o.Certificates = new[]
                    {
                        new X509Certificate2(Convert.FromBase64String(CertificatePfxBase64), CertificatePfxPassword)
                    };
                    o.AllowUntrustedCertificates = !ShouldValidateBrokerCertificate;
                });
            }

            return(builder.Build());
        }
コード例 #5
0
        /// <inheritdoc cref="IMqttClientConfigBuilder.WithClientId" />
        public IMqttClientConfigBuilder WithClientId(string value)
        {
            Check.NotEmpty(value, nameof(value));

            _builder.WithClientId(value);
            return(this);
        }
コード例 #6
0
        public FedNetClient(ConnectorData MQTTConnectorData, IFedNetLogger newlogSystem = null)
        {
            _logSystem = newlogSystem;
            if (_logSystem == null)
            {
                _logSystem = new DefaultLogger();
            }

            _MQTTHostAndPort = MQTTConnectorData.getHasSE();

            _ClientConfiguration = new MqttClientOptionsBuilder();
            _ClientConfiguration.WithClientId(String.Format("{0}-{1}_{2}", MQTTConnectorData.Username, DateTime.Now.ToString("ffffmmHHss"), FedNetWorker.getRandomString(10)));
            if (MQTTConnectorData.useCreditential)
            {
                _ClientConfiguration.WithCredentials(MQTTConnectorData.Username, MQTTConnectorData.Password);
            }
            _ClientConfiguration.WithTcpServer(MQTTConnectorData.Host, MQTTConnectorData.Port);

            _theGameClient = new MqttFactory().CreateMqttClient();
            _theGameClient.UseDisconnectedHandler(e => {
                _logSystem.Info("Disconnected (reason : " + (e.AuthenticateResult != null ? e.AuthenticateResult.ResultCode.ToString() : "unknow") + ")");
                if (Disconnected != null)
                {
                    Disconnected.Invoke(this, e);
                }
                if (reconnectOnDisco)
                {
                    Task.Delay(1000).Wait();
                    Connect();
                }
            });
            _theGameClient.UseConnectedHandler(e => {
                _logSystem.Info("Connected !!");
                _theGameClient.SubscribeAsync(FedNetConstante.SERVER_TO_CLIENT + FedNetConstante.DEFAULT_TOPIC_SEPARATOR + ClientId + FedNetConstante.DEFAULT_TOPIC_SEPARATOR + FedNetConstante.DEFAULT_TOPIC_JOKER, (MqttQualityOfServiceLevel)FedNetConstante.PRIORITY_SERVER_TO_CLIENT);
                _theGameClient.SubscribeAsync(FedNetConstante.SERVER_BROADCAST + FedNetConstante.DEFAULT_TOPIC_SEPARATOR + FedNetConstante.DEFAULT_TOPIC_JOKER, (MqttQualityOfServiceLevel)FedNetConstante.PRIORITY_SERVER_BROADCAST);
                if (Connected != null)
                {
                    Connected.Invoke(this, e);
                }
            });
            _theGameClient.UseApplicationMessageReceivedHandler(e => {
                if (e.ClientId == "" || e.ClientId == " " || e.ClientId == null)
                {
                    return;
                }
                if (MessageReceived != null)
                {
                    MessageReceived.Invoke(this, Message.getMessage(e.ApplicationMessage));
                }
            });

            reconnectOnDisco = true;

            _logSystem.Info("Client initialized !");
        }
コード例 #7
0
ファイル: AWS_MQTT.cs プロジェクト: Hosemans/airconcontrol
        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);
        }
コード例 #8
0
        public MQTTClient()
        {
            var mqttClient = new MqttFactory().CreateMqttClient();

            var optionBuilder = new MqttClientOptionsBuilder();

            optionBuilder
            .WithClientId("c001")
            .WithTcpServer(opts =>
            {
                opts.Server = "127.0.0.1";
                opts.Port   = 108;
            })
            .WithCredentials("u001", "p001")
            .WithCleanSession(true);

            var options = optionBuilder.Build();

            mqttClient.ConnectAsync(options, CancellationToken.None).Wait();

            var recieveHander = new MsgRecieveHandler();

            mqttClient.ApplicationMessageReceivedHandler = recieveHander;


            var topicBuilder = new TopicFilterBuilder();

            topicBuilder.WithTopic("家/客厅/空调/#")
            .WithAtMostOnceQoS();
            var topicHome = topicBuilder.Build();

            var subscribOptionBuilder = new MqttClientSubscribeOptionsBuilder();

            subscribOptionBuilder.WithTopicFilter(topicHome);

            var subOpt = subscribOptionBuilder.Build();

            mqttClient.SubscribeAsync(subOpt, CancellationToken.None).Wait();

            var appMsg = new MqttApplicationMessage();

            appMsg.Topic   = "家/客厅/空调/开关";
            appMsg.Payload = Encoding.UTF8.GetBytes("我来了~");
            appMsg.QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
            appMsg.Retain = false;


            mqttClient.PublishAsync(appMsg, CancellationToken.None).Wait();
            //var appMsg = new MqttApplicationMessage("家/客厅/空调/开关",
            //    Encoding.UTF8.GetBytes("消息内容"),
            //    MqttQualityOfServiceLevel.AtMostOnce, false);
        }
コード例 #9
0
        public static IServiceCollection AddMqttServices <TMqttSettings>(this IServiceCollection services, IConfiguration mqttConfiguration)
            where TMqttSettings : MqttSettings, new()
        {
            services.AddOptions <TMqttSettings>()
            .Bind(mqttConfiguration)
            .ValidateDataAnnotations();

            services.AddSingleton(sp =>
            {
                var mqttSettings = sp.GetRequiredService <IOptions <TMqttSettings> >().Value;

                var mqttClientOptionsBuilder = new MqttClientOptionsBuilder()
                                               .WithTcpServer(mqttSettings.Host, mqttSettings.Port)
                                               .WithProtocolVersion(mqttSettings.MqttProtocolVersion ?? MqttProtocolVersion.V500);

                if (mqttSettings.ClientId != null)
                {
                    mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithClientId(mqttSettings.ClientId);
                }

                if (mqttSettings.CommunicationTimeout.HasValue)
                {
                    mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithCommunicationTimeout(mqttSettings.CommunicationTimeout.Value);
                }

                mqttClientOptionsBuilder = mqttSettings.KeepAliveInterval.HasValue ?
                                           mqttClientOptionsBuilder.WithKeepAlivePeriod(mqttSettings.KeepAliveInterval.Value) :
                                           mqttClientOptionsBuilder.WithNoKeepAlive();

                var lastWillAndTestamentMessage = mqttSettings.GetLastWillAndTestamentApplicationMessage();
                if (lastWillAndTestamentMessage != null)
                {
                    mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithWillMessage(lastWillAndTestamentMessage);
                }

                return(mqttClientOptionsBuilder.Build());
            });

            services.AddSingleton <IMqttFactory, MqttFactory>();
            services.AddTransient(sp =>
            {
                var factory = sp.GetRequiredService <IMqttFactory>();
                var client  = factory.CreateMqttClient();
                return(client);
            });

            return(services);
        }
コード例 #10
0
 private MqttClientOptionsBuilder ConfigureClientOptions(MqttClientOptionsBuilder builder, MqttOptions options)
 {
     builder
     .WithClientId(options.ClientName)
     .WithTcpServer(options.Host, options.Port)
     .WithWillMessage(GetLastWill());
     if (options.UseTls)
     {
         builder = builder.WithTls();
     }
     if (options.HasCredentials)
     {
         builder = builder.WithCredentials(options.Username, options.Password);
     }
     return(builder);
 }
コード例 #11
0
        public void changeClientConfig(ConnectorData MQTTConnectorData)
        {
            _MQTTHostAndPort     = MQTTConnectorData.getHasSE();
            _ClientConfiguration = new MqttClientOptionsBuilder();
            _ClientConfiguration.WithClientId(String.Format("{0}-{1}_{2}", MQTTConnectorData.Username, DateTime.Now.ToString("ffffmmHHss"), FedNetWorker.getRandomString(10)));
            if (MQTTConnectorData.useCreditential)
            {
                _ClientConfiguration.WithCredentials(MQTTConnectorData.Username, MQTTConnectorData.Password);
            }
            if (!MQTTConnectorData.useCreditential)
            {
                _ClientConfiguration.WithCredentials(MQTTConnectorData.Username, "");
            }
            _ClientConfiguration.WithTcpServer(MQTTConnectorData.Host, MQTTConnectorData.Port);

            _logSystem.Info("MQTT Client reinitialized !");
        }
コード例 #12
0
        public virtual ManagedMqttClientOptions GetMqttClientOptions()
        {
            var clientOptions = new MqttClientOptionsBuilder();

            if (MqttBrokerSettings.IsEncryptedCommunication)
            {
                clientOptions.WithTls();
            }

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(clientOptions
                                             .WithClientId(MqttClientId)
                                             .WithTcpServer(MqttBrokerSettings.BrokerAddress, MqttBrokerSettings.Port)
                                             .WithCredentials(EboEwsSettings.UserName, EboEwsSettings.Password).Build())
                          .Build();

            return(options);
        }
コード例 #13
0
        private ManagedMqttClientOptions GetMqttClientOptions()
        {
            var clientOptions = new MqttClientOptionsBuilder();

            if (_moduleConfiguration.UseSecureCommunication)
            {
                clientOptions.WithTls();
            }

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(clientOptions
                                             .WithClientId(_moduleConfiguration.MqttClientId)
                                             .WithTcpServer(_moduleConfiguration.MqttBrokerAddress, _moduleConfiguration.MqttBrokerPort)
                                             .WithCredentials(_moduleConfiguration.MqttBrokerUserName, _moduleConfiguration.MqttBrokerPassword).Build())
                          .Build();

            return(options);
        }
コード例 #14
0
        public async Task Connect()
        {
            var certificate = new X509Certificate("C:\\Users\\Andre\\Desktop\\ESAMI\\Broker_Anto\\Resource\\certificate.pfx", "Guido2018", X509KeyStorageFlags.Exportable);
            //var certificate = new X509Certificate("C:\\Users\\Andre\\Desktop\\ESAMI\\Broker_Anto\\Resource\\esame.pfx", "Guido2018", X509KeyStorageFlags.Exportable);   ///idilio

            var caRoot = X509Certificate2.CreateFromSignedFile("C:\\Users\\Andre\\Desktop\\ESAMI\\Broker_Anto\\Resource\\CAroot.crt");
            MqttClientOptionsBuilder optionsBuilder = new MqttClientOptionsBuilder();
            var fact = new MqttFactory();

            client = fact.CreateMqttClient();
            client.ApplicationMessageReceived += Client_ApplicationMessageReceived;
            client.Connected += Client_Connected;

            optionsBuilder
            .WithClientId("pc-broker")
            .WithTcpServer(IoTEndPoint, 8883)
            .WithTls(true, true, true, certificate.Export(X509ContentType.Pfx), caRoot.Export(X509ContentType.Cert))
            .WithCleanSession()
            .WithProtocolVersion(MQTTnet.Serializer.MqttProtocolVersion.V311)
            .WithKeepAlivePeriod(new TimeSpan(0, 0, 5));

            try
            {
                await client.ConnectAsync(optionsBuilder.Build());
            }
            catch (Exception e)
            {
                w.Dispatcher.Invoke(v, "impossibile connect " + e.Message.ToString());
            }

            try
            {
                await client.SubscribeAsync("aws/misure");
            }
            catch (Exception e)
            {
                w.Dispatcher.Invoke(v, "impossibile subscribe " + e.Message.ToString());
            }
            while (!client.IsConnected)
            {
            }
        }
コード例 #15
0
ファイル: MQTTClient.cs プロジェクト: Jaasdsa/CityIoT
        public void Connect(out string errMsg)
        {
            errMsg = "";
            if (this.mqttClient != null && this.mqttClient.IsConnected)
            {
                return;
            }

            if (this.param == null)
            {
                errMsg = "连接MQTT服务端失败,没有指明服务参数";
                return;
            }
            try
            {
                mqttClient = new MqttFactory().CreateMqttClient() as MqttClient;
                this.OnloadEvents();

                MqttClientOptionsBuilder optionsBuilder = new MqttClientOptionsBuilder();

                optionsBuilder.WithCommunicationTimeout(TimeSpan.FromSeconds(10));// 只连接等待10秒
                optionsBuilder.WithTcpServer(this.param.ip, this.param.port);
                optionsBuilder.WithCredentials(this.param.userName, this.param.password);
                optionsBuilder.WithClientId(this.param.clientID);
                optionsBuilder.WithCleanSession(true);// 临时会话

                Task task = mqttClient.ConnectAsync(optionsBuilder.Build());
                task.Wait(5000);

                if (!this.IsConnected)
                {
                    errMsg = "连接MQTT服务器失败";
                }
            }
            catch (Exception ex)
            {
                errMsg = "连接到MQTT服务器失败!" + ex.Message;
            }
        }
コード例 #16
0
        private async Task <IManagedMqttClient> ConnectAsync(string clientId, string mqttServerAddress, int port, string username, string password, bool useTLS, CancellationToken token)
        {
            var mqttClientFactory = new MqttFactory();
            var builder           = new MqttClientOptionsBuilder();

            builder.WithTcpServer(mqttServerAddress, port);
            if (!string.IsNullOrWhiteSpace(clientId))
            {
                builder.WithClientId(clientId);
            }

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                builder.WithCredentials(username, password);
            }

            if (useTLS)
            {
                builder.WithTls();
            }

            var options = builder.Build();


            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)
                                 .Build();

            //todo add a logger provided to the function CreateMqttClient
            var client = mqttClientFactory.CreateManagedMqttClient(new MqttNetLogger(logger));
            await client.StartAsync(managedOptions);

            await client.WaitForConnectAsync(2000, token);

            return(client);
        }
コード例 #17
0
        private IMqttClientOptions GetConnectOptions()
        {
            var builder = new MqttClientOptionsBuilder()
                          .WithTcpServer(Configuration.Host, Configuration.Port)
                          .WithProtocolVersion(MqttProtocolVersion.V311);

            if (!string.IsNullOrWhiteSpace(Configuration.Session.ClientId))
            {
                // use a session but expire the session after 6h
                // we accept short outages less than 6h
                if (Configuration.Session.Clean)
                {
                    Console.WriteLine("Starting with a clean mqtt session ..");
                }

                builder
                .WithClientId(Configuration.Session.ClientId)
                .WithCleanSession(Configuration.Session.Clean)
                .WithSessionExpiryInterval(60 * 60 * 6);
            }

            if (Configuration.Auth.Enable)
            {
                builder.WithCredentials(Configuration.Auth.Username, Configuration.Auth.Password);
            }

            if (Configuration.Ssl.Enable)
            {
                builder.WithTls(parameters =>
                {
                    parameters.UseTls = true;
                    parameters.AllowUntrustedCertificates = Configuration.Ssl.AllowUntrustedCertificates;
                });
            }

            return(builder.Build());
        }
コード例 #18
0
ファイル: MainForm.cs プロジェクト: urbanoanderson/net-tools
        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);
            }
        }
コード例 #19
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));
        }
コード例 #20
0
        private void _connect()
        {
            try
            {
                if (_mqttClient != null && _mqttClient.IsConnected)
                {
                    return;
                }

                if (Options == null)
                {
                    return;
                }

                LastWillMessage        lastWillMsg = new LastWillMessage();
                string                 payload     = JsonConvert.SerializeObject(lastWillMsg);
                MqttApplicationMessage msg         = new MqttApplicationMessage()
                {
                    Payload = Encoding.UTF8.GetBytes(payload),
                    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                    Retain = true,
                    Topic  = string.Format(MQTTTopic.ScadaConnTopic, Options.ScadaId)
                };

                string clientId = "EdgeAgent_" + Guid.NewGuid().ToString("N");
                var    ob       = new MqttClientOptionsBuilder();
                ob.WithClientId(clientId)
                .WithCredentials(Options.MQTT.Username, Options.MQTT.Password)
                .WithCleanSession()
                .WithWillMessage(msg);

                switch (Options.MQTT.ProtocolType)
                {
                case Protocol.TCP:
                    ob.WithTcpServer(Options.MQTT.HostName, Options.MQTT.Port);
                    break;

                case Protocol.WebSocket:
                    ob.WithWebSocketServer(Options.MQTT.HostName);
                    break;

                default:
                    ob.WithTcpServer(Options.MQTT.HostName, Options.MQTT.Port);
                    break;
                }

                if (Options.UseSecure)
                {
                    ob.WithTls();
                }

                var mob = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromMilliseconds(Options.ReconnectInterval))
                          .WithClientOptions(ob.Build())
                          .Build();

                _mqttClient.StartAsync(mob);
            }
            catch (Exception ex)
            {
                //_logger.Error( ex.ToString() );
            }
        }
コード例 #21
0
        private MqttClientOptionsBuilder CreateOptionsBuilder(ClientCredentials credentials = null)
        {
            MqttClientOptionsBuilder clientOptionsBuilder       = new MqttClientOptionsBuilder();
            MqttClientOptionsBuilderTlsParameters tlsParameters = null;
            string hostName = Settings.Client.BrokerHostname;
            int    portNum  = Settings.Client.BrokerPort;

            //check if broker endpoint for local connections is defined in environment, only possible for connections without credentials
            if (credentials == null)
            {
                string brokerEndpoint = Environment.GetEnvironmentVariable("GE_BROKER_CONNECTION_ENDPOINT");
                if (!string.IsNullOrEmpty(brokerEndpoint))
                {
                    string[] tokens = brokerEndpoint.Split(':');
                    if (tokens.Length == 2)
                    {
                        hostName = tokens[0];
                        portNum  = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture);
                    }
                }
            }
            clientOptionsBuilder.WithCleanSession();
            clientOptionsBuilder.WithClientId(ClientId);
            if (portNum == 443)
            {
                clientOptionsBuilder.WithWebSocketServer(hostName);
            }
            else
            {
                clientOptionsBuilder.WithTcpServer(hostName, portNum);
            }
            if (credentials != null)
            {
                if (credentials.HasCertificates())
                {
                    tlsParameters = new MqttClientOptionsBuilderTlsParameters
                    {
                        UseTls = true,
                        AllowUntrustedCertificates        = Settings.Client.AllowUntrustedCertificates,
                        IgnoreCertificateChainErrors      = Settings.Client.IgnoreCertificateChainErrors,
                        IgnoreCertificateRevocationErrors = Settings.Client.IgnoreCertificateRevocationErrors,
                        CertificateValidationHandler      = CertificateValidationCallback,
                        Certificates = credentials.ClientCertAndCaChain,
                        SslProtocol  = SslProtocols.Tls12
                    };
                    clientOptionsBuilder.WithTls(tlsParameters);
                }
                if (credentials.IsUserNameAndPasswordRequired())
                {
                    credentials.GetUserNameAndPassword(ClientId, out string username, out string password);
                    clientOptionsBuilder.WithCredentials(username, password);
                }
            }

            // settings for connection timeout and MQTT kepp alive interval, given in seconds
            // (defaults in MQTTnet stack are CommunicationTimeout = 10 sec and KeepAlivePeriod = 15 sec.,
            //  see in MqttClientOptions.cs of MQTTnet)
            clientOptionsBuilder.WithCommunicationTimeout(new TimeSpan(0, 0, Settings.Client.CommunicationTimeout));
            clientOptionsBuilder.WithKeepAlivePeriod(new TimeSpan(0, 0, Settings.Client.MqttKeepAlivePeriod));
            return(clientOptionsBuilder);
        }
コード例 #22
0
        public void Connect()
        {
            try
            {
                bool con = false;
                if (Certificates.IsCertificateEnabled())
                {
                    Certificates.GetCertificate("ABB Ability Edge");
                }
                MqttFactory _mqttFactory = new MqttFactory(_clientLogger);
                var         certificate  = GetCert("ABB Ability Edge");
                if (certificate == null)
                {
                    certificate = new X509Certificate2(File.ReadAllBytes(this.certTxt.Text));
                }
                this.exMsg.Content = "";
                IMqttClientOptions       options;
                MqttClientOptionsBuilder builderObj;
                builderObj = new MqttClientOptionsBuilder()
                             .WithClientId(Guid.NewGuid().ToString())
                             .WithCleanSession();

                if (this.layerCbox.SelectedItem.ToString().ToLower().Contains("tcp"))
                {
                    builderObj = builderObj
                                 .WithClientId(Guid.NewGuid().ToString())
                                 .WithTcpServer(this.ipTxt.Text, int.Parse(this.portTxt.Text))
                                 .WithCleanSession();
                }
                else
                {
                    builderObj = builderObj
                                 .WithClientId(Guid.NewGuid().ToString())
                                 .WithWebSocketServer(this.ipTxt.Text)
                                 .WithCleanSession().WithRequestProblemInformation(true);
                }

                if (!withoutCert)
                {
                    builderObj = builderObj
                                 .WithTls(new MqttClientOptionsBuilderTlsParameters()
                    {
                        AllowUntrustedCertificates = true,
                        UseTls       = true,
                        Certificates = new List <byte[]> {
                            new X509Certificate2(certificate).Export(X509ContentType.Cert)
                        },
                        CertificateValidationCallback     = delegate { return(true); },
                        IgnoreCertificateChainErrors      = false,
                        IgnoreCertificateRevocationErrors = false
                    });
                }
                options = builderObj.Build();
                client  = _mqttFactory.CreateMqttClient();



                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(this.topicTxt.Text)
                              .WithPayload(this.msgTxt.Text + DateTime.Now.ToString())
                              .WithExactlyOnceQoS()
                              .WithRetainFlag()
                              .Build();

                var result = client.ConnectAsync(options);
                if (result != null)
                {
                    MessageBox.Show(result.ToString());
                }

                client.UseConnectedHandler(async e =>
                {
                    MessageBox.Show("Connected");
                    //this.connection_status_lbl.Content = "Connected";
                    con = true;
                    await client.PublishAsync(message);
                    MessageBox.Show("Published");
                });
                this.connection_status_lbl.Content = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.exMsg.Content = ex.StackTrace + Environment.NewLine;
            }
        }