Beispiel #1
0
        public void Should_initialize_MQTTClient()
        {
            var args = new List <IManagedMqttClientOptions>();

            MqttClientMock.Setup(m => m.StartAsync(Capture.In(args)));

            var subject       = new MqttSink(Options, MqttClientMock.Object);
            var actualOptions = args.First();
            MqttClientTcpOptions actualChannelOptions = actualOptions.ClientOptions.ChannelOptions as MqttClientTcpOptions;

            MqttClientMock.Verify(it => it.StartAsync(It.IsAny <IManagedMqttClientOptions>()));

            Assert.AreEqual(actualOptions.ClientOptions.Credentials.Username, MqttClientOptions.ClientOptions.Credentials.Username);
            Assert.AreEqual(actualOptions.ClientOptions.Credentials.Password, MqttClientOptions.ClientOptions.Credentials.Password);
            Assert.AreEqual(actualChannelOptions.Server, MqttClientTcpOptions.Server);
            Assert.AreEqual(actualChannelOptions.Port, MqttClientTcpOptions.Port);
        }
Beispiel #2
0
        private void MqttClient_Disconnected(object sender, EventArgs e)
        {
            Invoke((new Action(() =>
            {
                richTextBox_Subscribe.AppendText("已断开MQTT连接!" + Environment.NewLine);
            })));

            //Reconnecting
            if (isReconnect)
            {
                Invoke((new Action(() =>
                {
                    richTextBox_Subscribe.AppendText("正在尝试重新连接" + Environment.NewLine);
                })));

                var options = new MqttClientTcpOptions
                {
                    Server       = "10.204.138.7",
                    Port         = 1883,
                    ClientId     = "claa_001",// Guid.NewGuid().ToString().Substring(0, 5),
                    UserName     = "******",
                    Password     = "******",
                    CleanSession = true
                };
                Invoke((new Action(async() =>
                {
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    try
                    {
                        await mqttClient.ConnectAsync(options);
                    }
                    catch
                    {
                        richTextBox_Subscribe.AppendText("### RECONNECTING FAILED ###" + Environment.NewLine);
                    }
                })));
            }
            else
            {
                Invoke((new Action(() =>
                {
                    richTextBox_Subscribe.AppendText("已下线!" + Environment.NewLine);
                })));
            }
        }
Beispiel #3
0
        public static async Task RunClientTaskAsync()
        {
            MyTrueWriteLine("Creating a new client.....");
            var mqttclient = new MqttFactory().CreateMqttClient();
            MqttClientTcpOptions mqttClientTcpOptions = new MqttClientTcpOptions()
            {
                Server = "127.0.0.1",
                Port   = 1883,
            };
            var optionbuilder = new MqttClientOptionsBuilder()
                                .WithWillMessage(BuildMessage())
                                .WithTcpServer("127.0.0.1", 1883)
                                .WithClientId("Test1")
                                .WithCredentials("user", "password")
                                .WithTls()
                                .WithCommunicationTimeout(new TimeSpan(0, 0, 20))
                                .WithKeepAlivePeriod(new TimeSpan(0, 0, 20))
                                .WithCleanSession(true);

            var options = optionbuilder.Build();


            MyTrueWriteLine("Client starting to connect the server......");
            try
            {
                MqttClientConnectResult clientConnectResult = await mqttclient.ConnectAsync(options);

                MyTrueWriteLine("The result of action:" + clientConnectResult.ToString());
            }
            catch (Exception e)
            {
                MyTrueWriteLine("Failed:" + Environment.NewLine + e);
            }

            mqttclient.Connected += (s, e) =>
            {
                MyTrueWriteLine("Client has connected to server successfully!");
                MyTrueWriteLine($"Detail:{e.ConnectResult.ToString()}");
            };
            mqttclient.Disconnected += (s, e) =>
            {
                MyTrueWriteLine("Client has disconnected from the server");
            };
        }
Beispiel #4
0
        public MqttTcpChannel(IMqttClientOptions clientOptions)
        {
            _clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
            _options       = (MqttClientTcpOptions)clientOptions.ChannelOptions;

            var builder = new SocketOptionBuilder()
                          .UseStream()
                          .SetIP(_options.Server)
                          .SetPort(_options.Port ?? 1883);

            if (_options.TlsOptions.UseTls)
            {
                builder = builder.WithSsl(_options.TlsOptions.SslProtocol);
            }

            var option = builder.Build();

            _clientSocket = SocketFactory.CreateClientSocket(option);
        }
        private static async void testi()
        {
            var factory    = new MqttFactory();
            var mqttClient = factory.CreateMqttClient();

            //var mqttClient = new MqttClientFactory().CreateMqttClient();
            var _mqttOptions = new MqttClientTcpOptions();

            _mqttOptions.CleanSession = true;
            _mqttOptions.ClientId     = "TEST";
            _mqttOptions.DefaultCommunicationTimeout = TimeSpan.FromSeconds(20);
            _mqttOptions.KeepAlivePeriod             = TimeSpan.FromSeconds(31);
            _mqttOptions.Server     = "127.0.0.1";
            _mqttOptions.UserName   = "******";
            _mqttOptions.Port       = 8883;
            _mqttOptions.TlsOptions = new MqttClientTlsOptions
            {
                UseTls = true,
                AllowUntrustedCertificates        = true,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true
            };
            MqttTcpChannel.CustomCertificateValidationCallback = remoteValidation;
            await mqttClient.ConnectAsync(_mqttOptions);

            mqttClient.Disconnected += async(s, e) =>
            {
                Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                await Task.Delay(TimeSpan.FromSeconds(5));

                try
                {
                    await mqttClient.ConnectAsync(_mqttOptions);
                }
                catch
                {
                    Console.WriteLine("### RECONNECTING FAILED ###");
                }
            };
        }
Beispiel #6
0
        public void Setup()
        {
            Options = new MqttSinkOptions
            {
                Server   = "wayne-foundation.com",
                Port     = 1863,
                Password = "******",
                Username = "******",
                Topics   = Topics
            };

            var clientOptions = new MqttClientOptionsBuilder()
                                .WithTcpServer(Options.Server, Options.Port)
                                .WithCredentials(Options.Username, Options.Password);


            MqttClientOptions = new ManagedMqttClientOptionsBuilder()
                                .WithClientOptions(clientOptions)
                                .Build();

            MqttClientTcpOptions = MqttClientOptions.ClientOptions.ChannelOptions as MqttClientTcpOptions;
        }
Beispiel #7
0
 private static bool CustomCertificateValidationCallback(X509Certificate certificate,
                                                         X509Chain chain,
                                                         SslPolicyErrors sslPolicyErrors,
                                                         MqttClientTcpOptions arg4
                                                         )
 {
     Logger.Info($"SSL Policy Erros: {sslPolicyErrors}");
     if (certificate == null)
     {
         Logger.Info("No client certificate received.");
     }
     else
     {
         Logger.Info("Received Client Certificate:");
         Logger.Info(certificate.ToString());
     }
     if (chain == null)
     {
         Logger.Info("No certificate chain.");
     }
     else
     {
         Logger.Info("Certificate Chain:");
         foreach (X509ChainElement element in chain.ChainElements)
         {
             Logger.Info($"Chain Element Information: {element.Information}");
             foreach (X509ChainStatus elementStatus in element.ChainElementStatus)
             {
                 Logger.Info($"Status: {elementStatus.Status}");
                 Logger.Info($"Status Information: {elementStatus.StatusInformation}");
             }
             Logger.Info($"Certificate: {element.Certificate}");
         }
     }
     Logger.Info("Accepting Client Certifiacte");
     return(true);
 }
Beispiel #8
0
        private async Task ConnectMqttServerAsync()
        {
            if (mqttClient == null)
            {
                mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient;
                mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
                mqttClient.Connected    += MqttClient_Connected;
                mqttClient.Disconnected += MqttClient_Disconnected;
            }

            try
            {
                var options = new MqttClientTcpOptions
                {
                    Server       = "116.236.186.130",
                    ClientId     = Guid.NewGuid().ToString().Substring(0, 5),
                    UserName     = "******",
                    Password     = "******",
                    CleanSession = true,
                    Port         = 8042
                };

                await mqttClient.ConnectAsync(options);

                await mqttClient.SubscribeAsync(new List <TopicFilter> {
                    new TopicFilter("aaaaaaaa", MqttQualityOfServiceLevel.AtMostOnce)
                });
            }
            catch (Exception ex)
            {
                Invoke((new Action(() =>
                {
                    txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
                })));
            }
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello chkr1011/MQTTnet World! See; https://github.com/chkr1011/MQTTnet/wiki/Client");

            //


            // https://github.com/chkr1011/MQTTnet/issues/552
            var certificate = new X509Certificate2(@"C:\jstuff\TLS\debbie\selfsignedxamarinclient.pfx", "xamarin", X509KeyStorageFlags.Exportable);


            var factory      = new MqttFactory();
            var mqttClient   = factory.CreateMqttClient();
            var _mqttOptions = new MqttClientTcpOptions();

            _mqttOptions.TlsOptions = new MqttClientTlsOptions
            {
                UseTls = true,
                AllowUntrustedCertificates        = true,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true
            };

            var options = new MqttClientOptionsBuilder()
                          .WithClientId("Chkr1011MQTTnetConsoleApp")
                          .WithTcpServer("iot.eclipse.org")
                          .WithProtocolVersion(MqttProtocolVersion.V311)


                          //.WithCredentials("bud", "%spencer%")
                          //.WithTls()
                          //.TlsEndpointOptions.Certificate = new X509Certificate2(File.ReadAllBytes(@"C:\Certs\cert.pem")).RawData;


                          //options.TlsOptions = new MqttClientTlsOptions
                          //{
                          //    UseTls = true,
                          //    AllowUntrustedCertificates = true,
                          //    IgnoreCertificateChainErrors = true,
                          //    IgnoreCertificateRevocationErrors = true
                          //};


                          .WithCleanSession()
                          .Build();


            mqttClient.ConnectAsync(options);

            mqttClient.Connected += async(s, e) =>
            {
                // Subscribe to a topic
                await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("xamtest").Build());
            };

            mqttClient.ApplicationMessageReceived += (s, e) =>
            {
                Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
            };

            MqttTcpChannel.CustomCertificateValidationCallback = (x509Certificate, x509Chain, sslPolicyErrors, mqttClientTcpOptions) =>
            {
                if (mqttClientTcpOptions.Server == "server_with_revoked_cert")
                {
                    return(true);
                }

                return(false);
            };

            Console.ReadKey();
        }
Beispiel #10
0
        private static async Task RunClientAsync(int msgChunkSize, TimeSpan interval)
        {
            try
            {
                var options = new MqttClientTcpOptions
                {
                    Server       = "localhost",
                    ClientId     = "XYZ",
                    CleanSession = true,
                    DefaultCommunicationTimeout = TimeSpan.FromMinutes(10)
                };

                var client = new MqttClientFactory().CreateMqttClient();
                client.ApplicationMessageReceived += (s, e) =>
                {
                };

                client.Connected += async(s, e) =>
                {
                    Console.WriteLine("### CONNECTED WITH SERVER ###");

                    await client.SubscribeAsync(new List <TopicFilter>
                    {
                        new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
                    });

                    Console.WriteLine("### SUBSCRIBED ###");
                };

                client.Disconnected += async(s, e) =>
                {
                    Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                    await Task.Delay(TimeSpan.FromSeconds(5));

                    try
                    {
                        await client.ConnectAsync(options);
                    }
                    catch
                    {
                        Console.WriteLine("### RECONNECTING FAILED ###");
                    }
                };

                try
                {
                    await client.ConnectAsync(options);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
                }

                Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");

                var testMessageCount = 10000;
                var message          = CreateMessage();
                var stopwatch        = Stopwatch.StartNew();
                for (var i = 0; i < testMessageCount; i++)
                {
                    await client.PublishAsync(message);
                }

                stopwatch.Stop();
                Console.WriteLine($"Sent 10.000 messages within {stopwatch.ElapsedMilliseconds} ms ({stopwatch.ElapsedMilliseconds / (float)testMessageCount} ms / message).");

                stopwatch.Restart();
                var sentMessagesCount = 0;
                while (stopwatch.ElapsedMilliseconds < 1000)
                {
                    await client.PublishAsync(message);

                    sentMessagesCount++;
                }

                Console.WriteLine($"Sending {sentMessagesCount} messages per second.");

                var last     = DateTime.Now;
                var msgCount = 0;

                while (true)
                {
                    var msgs = Enumerable.Range(0, msgChunkSize)
                               .Select(i => CreateMessage())
                               .ToList();

                    if (true)
                    {
                        //send concurrent (test for raceconditions)
                        var sendTasks = msgs
                                        .Select(msg => PublishSingleMessage(client, msg, ref msgCount))
                                        .ToList();

                        await Task.WhenAll(sendTasks);
                    }
                    else
                    {
                        await client.PublishAsync(msgs);

                        msgCount += msgs.Count;
                        //send multiple
                    }



                    var now = DateTime.Now;
                    if (last < now - TimeSpan.FromSeconds(1))
                    {
                        Console.WriteLine($"sending {msgCount} intended {msgChunkSize / interval.TotalSeconds}");
                        msgCount = 0;
                        last     = now;
                    }

                    await Task.Delay(interval).ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
 public MqttTcpChannel(IMqttClientOptions clientOptions)
 {
     _options    = (MqttClientTcpOptions)clientOptions.ChannelOptions;
     _bufferSize = _options.BufferSize;
 }
Beispiel #12
0
        public static async Task RunMQTTClientAsync()
        {
            try
            {
                AutoReconnect = true;
                Settings settings = Program.Settings;
                var      factory  = new MqttFactory();
                mqttClient = factory.CreateMqttClient();

                var ClientID = settings.MQTT_CLIENT_ID.Replace("%rnd%", new Guid().ToString());

                var WillMessage = new MqttApplicationMessageBuilder()
                                  .WithTopic((BasePublishingTopic + "/$state").Replace("//", "/"))
                                  .WithPayload("lost")
                                  .WithAtLeastOnceQoS()
                                  .WithRetainFlag(false)
                                  .Build();

                var Credentials = new MqttClientCredentials
                {
                    Username = settings.MQTT_CRED_USERNAME,
                    Password = settings.MQTT_CRED_PASSWORD
                };

                var TlsOptions = new MqttClientTlsOptions
                {
                    UseTls = settings.MQTT_USE_TLS
                };

                var ChannelOptions_WebSocket = new MqttClientWebSocketOptions
                {
                    Uri        = settings.MQTT_SERVER_WEBSOCKET,
                    TlsOptions = TlsOptions
                };

                var ChannelOptions_TCP = new MqttClientTcpOptions
                {
                    Server     = settings.MQTT_SERVER_TCP,
                    TlsOptions = TlsOptions
                };

                clientOptions = new MqttClientOptions();

                if (settings.MQTT_CONNECTION_METHOD == MQTT_CONNECTION_METHOD.TCP)
                {
                    clientOptions = new MqttClientOptions
                    {
                        CleanSession         = settings.MQTT_CLEAN_SESSION,
                        ClientId             = ClientID,
                        Credentials          = Credentials,
                        ChannelOptions       = ChannelOptions_TCP,
                        CommunicationTimeout = TimeSpan.FromSeconds(3),
                        WillMessage          = WillMessage
                    };
                }
                else
                {
                    clientOptions = new MqttClientOptions
                    {
                        CleanSession         = settings.MQTT_CLEAN_SESSION,
                        ClientId             = ClientID,
                        Credentials          = Credentials,
                        ChannelOptions       = ChannelOptions_WebSocket,
                        CommunicationTimeout = TimeSpan.FromSeconds(3),
                        WillMessage          = WillMessage
                    };
                }

                // Assign events
                mqttClient.ApplicationMessageReceived += async(s, e) => { await MqttClient_ApplicationMessageReceived(s, e); };
                mqttClient.Connected    += async(s, e) => { await MqttClient_Connected(s, e); };
                mqttClient.Disconnected += async(s, e) => { await MqttClient_Disconnected(s, e); };

                // Connect to the MQTT broker/server
                try
                {
                    DoLog("Connecting to MQTT server...", false);
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    await mqttClient.ConnectAsync(clientOptions);

                    if (mqttClient.IsConnected)
                    {
                        DoLog("OK", 3, false, 10);
                        //await SendMQTTMessageAsync("$state", "init", true);
                        stopwatch.Stop();
                        DoLog($"{stopwatch.ElapsedMilliseconds}ms", 3, true, 14);
                    }
                    else
                    {
                        DoLog("FAIL", 3, true, 14);
                        Program.BootWithoutError = false;
                    }
                }
                catch (Exception exception)
                {
                    DoLog("ERROR", 3, true, 12);
                    Program.BootWithoutError = false;
                    LogException(exception);
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                Program.BootWithoutError = false;
            }
            return;
        }
Beispiel #13
0
 public MqttTcpChannel CreateTcpChannel(MqttClientTcpOptions tcpOptions)
 {
     return(new MqttTcpChannel(tcpOptions));
 }
Beispiel #14
0
 private bool RemoteValidation(X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors, MqttClientTcpOptions options)
 {
     _logger.LogDebug($"RemoteValidation: {sslPolicyErrors}");
     return(true);
 }
 private static bool remoteValidation(X509Certificate certificate,
                                      X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors, MqttClientTcpOptions options)
 {
     return(true);
 }
 /// <summary>
 /// called on client sockets are created in connect
 /// </summary>
 public MqttTcpChannel(MqttClientTcpOptions options)
 {
     _options = options ?? throw new ArgumentNullException(nameof(options));
 }
Beispiel #17
0
 /// <summary>
 /// called on client sockets are created in connect
 /// </summary>
 public MqttTcpChannel(IMqttClientOptions clientOptions)
 {
     _clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
     _options       = (MqttClientTcpOptions)clientOptions.ChannelOptions;
 }
Beispiel #18
0
 private void BuildTcpServerOptions(MqttClientTcpOptions x)
 {
     x.Server     = Server;
     x.Port       = Port;
     x.TlsOptions = GetTlsOptions();
 }