Пример #1
0
        private async Task <IMqttClient> CreateMqttClient(MqttAddress addr)
        {
            var ClientOptions = new MqttClientOptions
            {
                ClientId       = addr.ClientId,
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = addr.BindAddress,
                    Port   = addr.Port,
                }
            };

            var mqttClient = new MqttFactory().CreateMqttClient();

            mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e =>
            {
                //Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                await Task.Delay(TimeSpan.FromSeconds(1));

                try
                {
                    await mqttClient.ConnectAsync(ClientOptions);
                }
                catch
                {
                    Console.WriteLine("### RECONNECTING FAILED ###");
                }
            });
            bool IsSuccess = false;

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    await mqttClient.ConnectAsync(ClientOptions);

                    IsSuccess = true;
                    break;
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, $"#### MQTT BROKER CONNECTING FAILED ###");
                    Thread.Sleep(TimeSpan.FromSeconds(30));
                    continue;
                }
            }

            if (IsSuccess == false)
            {
                logger.LogError("#### 브로커 접속에 실패했습니다. 다시 실행해주세요. ####");
                return(null);
            }
            return(mqttClient);
        }
Пример #2
0
        public async Task MqttServer_HandleCleanDisconnect()
        {
            var serverAdapter = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger());
            var s             = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());

            var clientConnectedCalled    = 0;
            var clientDisconnectedCalled = 0;

            s.ClientConnected    += (_, __) => clientConnectedCalled++;
            s.ClientDisconnected += (_, __) => clientDisconnectedCalled++;

            var clientOptions = new MqttClientOptionsBuilder()
                                .WithTcpServer("localhost")
                                .Build();

            await s.StartAsync(new MqttServerOptions());

            var c1 = new MqttFactory().CreateMqttClient();

            await c1.ConnectAsync(clientOptions);

            await Task.Delay(100);

            await c1.DisconnectAsync();

            await Task.Delay(100);

            await s.StopAsync();

            await Task.Delay(100);

            Assert.AreEqual(clientConnectedCalled, clientDisconnectedCalled);
        }
Пример #3
0
        public async Task MqttServer_SessionTakeover()
        {
            var server = new MqttFactory().CreateMqttServer();

            try
            {
                await server.StartAsync(new MqttServerOptions());

                var client1 = new MqttFactory().CreateMqttClient();
                var client2 = new MqttFactory().CreateMqttClient();

                var options = new MqttClientOptionsBuilder()
                              .WithTcpServer("localhost")
                              .WithCleanSession(false)
                              .WithClientId("a").Build();

                await client1.ConnectAsync(options);

                await Task.Delay(500);

                await client2.ConnectAsync(options);

                await Task.Delay(500);

                Assert.IsFalse(client1.IsConnected);
                Assert.IsTrue(client2.IsConnected);
            }
            finally
            {
                await server.StopAsync();
            }
        }
Пример #4
0
        public async Task <IMqttClient> Connect()
        {
            var options = ReadConfiguration();
            var client  = new MqttFactory().CreateMqttClient();

            try
            {
                await client.ConnectAsync(options, CancellationToken.None);
            }
            catch
            {
                var json   = Helpers.MqttConfigJson;
                var config = JsonConvert.DeserializeObject <Config>(json);

                var stringBuilder = new StringBuilder();
                stringBuilder.Append("Clinet could not connect to bridge\n");
                stringBuilder.Append("MQTT Configuration Options:\n");
                stringBuilder.Append($"Bridge: {config.BridgeUrl}:{config.BridgePort}\n");
                stringBuilder.Append($"Username: {config.BridgeUser.UserName}\n");
                stringBuilder.Append($"ClientId: {config.BridgeUser.ClientId}");

                throw new MqttConfigurationException(stringBuilder.ToString());
            }

            return(client);
        }
Пример #5
0
        private static async Task MainAsync()
        {
            Console.Title = "Listener";

            var mqttClient = new MqttFactory().CreateMqttClient();

            var options = new MqttClientOptionsBuilder()
                          .WithClientId("Console_App_Listener")
                          .WithTcpServer("{Ip Address}", 1883)
                          .Build();

            await mqttClient.ConnectAsync(options);

            Console.Write("Subscribe To Topic: ");
            string topic = Console.ReadLine();

            await mqttClient.SubscribeAsync(topic, MqttQualityOfServiceLevel.AtLeastOnce);

            mqttClient.UseApplicationMessageReceivedHandler(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();
            });

            Console.ReadLine();
        }
Пример #6
0
        public async Task MqttServer_ShutdownDisconnectsClientsGracefully()
        {
            var serverAdapter = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger());
            var s             = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());

            var clientOptions = new MqttClientOptionsBuilder()
                                .WithTcpServer("localhost")
                                .Build();

            var disconnectCalled = 0;

            await s.StartAsync(new MqttServerOptions());

            var c1 = new MqttFactory().CreateMqttClient();

            c1.Disconnected += (sender, args) => disconnectCalled++;

            await c1.ConnectAsync(clientOptions);

            await Task.Delay(100);

            await s.StopAsync();

            await Task.Delay(100);

            Assert.AreEqual(1, disconnectCalled);
        }
Пример #7
0
        static async Task Main(string[] args)
        {
            //Sending properties
            var topic   = "andy840119/iot";
            var quality = MqttQualityOfServiceLevel.AtLeastOnce;

            //Run a MQTT publish client
            var publishClient = new MqttFactory().CreateMqttClient();
            await publishClient.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer(ServerAddress).Build());

            while (true)
            {
                Console.WriteLine("Type any message to send message from publisher to subscripter...");
                string line = Console.ReadLine();

                Console.WriteLine("Message sent : " + line);
                await publishClient.PublishAsync(new MqttApplicationMessage()
                {
                    Topic = topic,
                    QualityOfServiceLevel = quality,
                    Payload = Encoding.UTF8.GetBytes(line),
                });

                await Task.Delay(500);
            }
        }
Пример #8
0
        public static async Task <IMqttClient> ConnectAsync(string clientId)
        {
            Console.WriteLine("In ConnectAsync");
            var             client = new MqttFactory().CreateMqttClient();
            X509Certificate ca_crt = new X509Certificate("certs/ca.crt");

            var tlsOptions = new MqttClientOptionsBuilderTlsParameters();

            tlsOptions.SslProtocol  = System.Security.Authentication.SslProtocols.Tls11;
            tlsOptions.Certificates = new List <IEnumerable <byte> >()
            {
                ca_crt.Export(X509ContentType.Cert).Cast <byte>()
            };
            tlsOptions.UseTls = true;
            tlsOptions.AllowUntrustedCertificates        = true;
            tlsOptions.IgnoreCertificateChainErrors      = false;
            tlsOptions.IgnoreCertificateRevocationErrors = false;

            Console.WriteLine("MQTT_BROKER_ADDRESS: {0}", MQTT_BROKER_ADDRESS);
            Console.WriteLine("MQTT_BROKER_PORT: {0}", MQTT_BROKER_PORT);

            // TLS support on port 4321 (8883 already in use with Azure IoT Edge)
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(clientId)
                          .WithTcpServer(MQTT_BROKER_ADDRESS, MQTT_BROKER_PORT)
                          .WithTls(tlsOptions)
                          .Build();

            await client.ConnectAsync(options);

            return(client);
        }
Пример #9
0
        public static async Task <IMqttClient> StartClient(BaseMessageHandler handler)
        {
            var client = new MqttFactory().CreateMqttClient();

            client.UseApplicationMessageReceivedHandler(e =>
            {
                var Payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                if (Payload.IndexOf('|') != -1)
                {
                    var Channel = e.ApplicationMessage.Topic;
                    var Type    = Payload.Split("|")[0];
                    var Context = Payload.Substring(Type.Length + 1);

                    GeneratedMessage.Dispatch(handler, Channel, Type, Context);
                }
            });

            var clientOptions = new MqttClientOptionsBuilder()
                                .WithClientId("ClientID")
                                .WithTcpServer("127.0.0.1")
                                .WithCleanSession()
                                .Build();

            await client.ConnectAsync(clientOptions);

            foreach (var channel in GeneratedMessage.channels)
            {
                await client.SubscribeAsync(new TopicFilterBuilder().WithTopic(channel).Build());
            }

            return(client);
        }
Пример #10
0
        public async Task <bool> PublishLockCommand(Guid moduleId, bool isLocked)
        {
            var dlm = await _repository.GetDLMByGuid(moduleId);

            if (dlm == null)
            {
                return(false);
            }

            dlm.IsLocked = isLocked;

            await _repository.Commit();

            var mqttOptions = new MqttClientOptionsBuilder()
                              .WithClientId("LiveboltServer")
                              .WithTcpServer("localhost")
                              .WithCredentials("livebolt", "livebolt")
                              .Build();

            var mqttClient = new MqttFactory().CreateMqttClient();

            await mqttClient.ConnectAsync(mqttOptions);

            var message = new MqttApplicationMessageBuilder()
                          .WithTopic($"dlm/lock/{moduleId}")
                          .WithPayload((isLocked ? 1 : 0).ToString())
                          .WithExactlyOnceQoS()
                          .Build();

            await mqttClient.PublishAsync(message);

            await mqttClient.DisconnectAsync();

            return(true);
        }
Пример #11
0
        public async Task Post(DataValue value)
        {
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(ClientId)
                          .WithTcpServer("106.14.142.74", 1883)
                          .WithCredentials("admin", "123456")
                          .WithCleanSession()
                          .Build();
            var mqttclient = new MqttFactory().CreateMqttClient();

            if (null == mqttclient)
            {
                throw new Exception("mqttclient有点问题");
            }
            await mqttclient.ConnectAsync(options);

            var sendTopic = $"topic/narojay";
            var sendMsg   = JsonConvert.SerializeObject(value);
            var msg       = new MqttApplicationMessageBuilder().WithTopic(sendTopic).WithPayload(sendMsg)
                            .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce).WithRetainFlag(false)
                            .Build();

            for (var i = 0; i < 1000; i++)
            {
                mqttclient.PublishAsync(msg);
            }
        }
Пример #12
0
        public async Task MqttServer_StopAndRestart()
        {
            var server = new MqttFactory().CreateMqttServer();
            await server.StartAsync(new MqttServerOptions());

            var client = new MqttFactory().CreateMqttClient();
            await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build());

            await server.StopAsync();

            try
            {
                var client2 = new MqttFactory().CreateMqttClient();
                await client2.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build());

                Assert.Fail("Connecting should fail.");
            }
            catch (Exception)
            {
            }

            await server.StartAsync(new MqttServerOptions());

            var client3 = new MqttFactory().CreateMqttClient();
            await client3.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build());

            await server.StopAsync();
        }
Пример #13
0
        public async Task Publish_With_Properties()
        {
            var server = new MqttFactory().CreateMqttServer();
            var client = new MqttFactory().CreateMqttClient();

            try
            {
                await server.StartAsync(new MqttServerOptions());

                var applicationMessage = new MqttApplicationMessageBuilder()
                                         .WithTopic("Hello")
                                         .WithPayload("World")
                                         .WithAtMostOnceQoS()
                                         .WithUserProperty("x", "1")
                                         .WithUserProperty("y", "2")
                                         .WithResponseTopic("response")
                                         .WithContentType("text")
                                         .WithMessageExpiryInterval(50)
                                         .WithCorrelationData(new byte[12])
                                         .WithTopicAlias(2)
                                         .Build();

                await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());

                var result = await client.PublishAsync(applicationMessage);

                await client.DisconnectAsync();

                Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode);
            }
            finally
            {
                await server.StopAsync();
            }
        }
Пример #14
0
        /// <summary>
        /// Initialize MQTT
        /// </summary>
        /// <returns></returns>
        private async Task InitialMQTTServer()
        {
            //Sending properties
            var topic   = "andy840119/iot";
            var quality = MqttQualityOfServiceLevel.AtLeastOnce;

            //Run a MQTT Server
            var server = new MqttFactory().CreateMqttServer();
            await server.StartAsync(new MqttServerOptions());

            //Run a MQTT receive client
            var receniveClient = new MqttFactory().CreateMqttClient();
            await receniveClient.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer(ServerAddress).Build());

            receniveClient.ApplicationMessageReceived += (object o, MqttApplicationMessageReceivedEventArgs e) =>
            {
                //Record received message.
                var receiveBytes   = e.ApplicationMessage.Payload;
                var receiveMessage = Encoding.UTF8.GetString(receiveBytes);


                Console.WriteLine("Message received :");
                Console.WriteLine(receiveMessage);

                var result = Task.Run(
                    async() =>
                {
                    await SendMessageToEveryConnectUser(receiveMessage, default(CancellationToken));
                });
                result.Wait();
            };

            //Receive client subscribe a topic
            await receniveClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).WithQualityOfServiceLevel(quality).Build());
        }
Пример #15
0
        public async Task Connect_To_Wrong_Host()
        {
            var client  = new MqttFactory().CreateLowLevelMqttClient();
            var options = new MqttClientOptionsBuilder().WithTcpServer("123.456.789.10").Build();

            await client.ConnectAsync(options, CancellationToken.None).ConfigureAwait(false);
        }
Пример #16
0
        public static async void MqttclientConnect()
        {
            try
            {
                var clientoptions = new MqttClientOptions();
                clientoptions.ChannelOptions = new MqttClientTcpOptions()
                {
                    Server = "192.168.137.1",
                    Port   = 1883
                };
                clientoptions.Credentials = new MqttClientCredentials()
                {
                    Username = "******",
                    Password = "******"
                };
                clientoptions.CleanSession          = true;
                clientoptions.KeepAlivePeriod       = TimeSpan.FromSeconds(100.0);
                clientoptions.KeepAliveSendInterval = TimeSpan.FromSeconds(20000);

                var mqttclient = new MqttFactory().CreateMqttClient();

                await mqttclient.ConnectAsync(clientoptions);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #17
0
        public async Task Connect_To_Not_Existing_Broker()
        {
            var client  = new MqttFactory().CreateLowLevelMqttClient();
            var options = new MqttClientOptionsBuilder().WithTcpServer("localhost").Build();

            await client.ConnectAsync(options, CancellationToken.None).ConfigureAwait(false);
        }
Пример #18
0
        public async Task Unsubscribe()
        {
            var server = new MqttFactory().CreateMqttServer();
            var client = new MqttFactory().CreateMqttClient();

            try
            {
                await server.StartAsync(new MqttServerOptions());

                await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());

                await client.SubscribeAsync("a");

                var result = await client.UnsubscribeAsync("a");

                await client.DisconnectAsync();

                Assert.AreEqual(1, result.Items.Count);
                Assert.AreEqual(MqttClientUnsubscribeResultCode.Success, result.Items[0].ReasonCode);
            }
            finally
            {
                await server.StopAsync();
            }
        }
Пример #19
0
        // This code is used at the Wiki on GitHub!
        // ReSharper disable once UnusedMember.Local
        private static async void WikiCode()
        {
            {
                var client = new MqttFactory().CreateMqttClient();

                var options = new MqttClientOptionsBuilder()
                              .WithClientId("Client1")
                              .WithTcpServer("broker.hivemq.com")
                              .WithCredentials("bud", "%spencer%")
                              .WithTls()
                              .Build();

                await client.ConnectAsync(options);

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic("MyTopic")
                              .WithPayload("Hello World")
                              .WithExactlyOnceQoS()
                              .WithRetainFlag()
                              .Build();

                await client.PublishAsync(message);
            }

            {
                var factory = new MqttFactory();
                var client  = factory.CreateMqttClient();
            }
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await _sync.WaitAsync(cancellationToken);

            try
            {
                if (_client is null)
                {
                    var client = new MqttFactory().CreateMqttClient();
                    client.ConnectedHandler    = this;
                    client.DisconnectedHandler = this;
                    await client.ConnectAsync(_clientOptions, cancellationToken);

                    _client = client;
                    _logger.LogDebug("MQTT service started successfully.");
                }
                else
                {
                    _logger.LogWarning("MQTT service is already running.");
                }
            }
            finally
            {
                _sync.Release();
            }
        }
Пример #21
0
        public async Task Subscribe()
        {
            var server = new MqttFactory().CreateMqttServer();
            var client = new MqttFactory().CreateMqttClient();

            try
            {
                await server.StartAsync(new MqttServerOptions());

                await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").WithProtocolVersion(MqttProtocolVersion.V500).Build());

                var result = await client.SubscribeAsync(new MqttClientSubscribeOptions()
                {
                    SubscriptionIdentifier = 1,
                    TopicFilters           = new List <TopicFilter>
                    {
                        new TopicFilter {
                            Topic = "a", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce
                        }
                    }
                });

                await client.DisconnectAsync();

                Assert.AreEqual(1, result.Items.Count);
                Assert.AreEqual(MqttClientSubscribeResultCode.GrantedQoS1, result.Items[0].ResultCode);
            }
            finally
            {
                await server.StopAsync();
            }
        }
Пример #22
0
        public static async Task StartAsync(AdminShellPackageEnv[] package, GrapevineLoggerSuper logger = null)
        {
            // Create TCP based options using the builder.
            var options = new MqttClientOptionsBuilder()
                          .WithClientId("AASXPackageXplorer MQTT Client")
                          .WithTcpServer("localhost", 1883)
                          .Build();

            //create MQTT Client and Connect using options above
            IMqttClient mqttClient = new MqttFactory().CreateMqttClient();
            await mqttClient.ConnectAsync(options);

            int iAASEnv = 0;

            for (iAASEnv = 0; iAASEnv < package.Length; iAASEnv++)
            {
                if (iAASEnv == lastAASEnv && package[iAASEnv] != null)
                {
                    //publish AAS to AAS Topic
                    foreach (AdminShell.AdministrationShell aas in package[iAASEnv].AasEnv.AdministrationShells)
                    {
                        //publish submodels
                        int iSubmodel = 0;
                        foreach (var sm in package[iAASEnv].AasEnv.Submodels)
                        {
                            if (iSubmodel == lastSubmodel)
                            {
                                Console.WriteLine("Publish MQTT AAS " + aas.idShort + " Submodel_" + sm.idShort);

                                var message2 = new MqttApplicationMessageBuilder()
                                               .WithTopic("Submodel_" + sm.idShort)
                                               .WithPayload(Newtonsoft.Json.JsonConvert.SerializeObject(sm))
                                               .WithExactlyOnceQoS()
                                               .WithRetainFlag()
                                               .Build();

                                await mqttClient.PublishAsync(message2);

                                lastSubmodel++;
                                iSubmodel = -1;
                                break;
                            }
                            iSubmodel++;
                        }
                        if (iSubmodel != -1)
                        {
                            lastSubmodel = 0;
                            lastAASEnv++;
                        }
                        break;
                    }
                    break;
                }
            }
            if (package[lastAASEnv] == null)
            {
                lastAASEnv = 0;
            }
        }
Пример #23
0
        public async Task MqttServer_Publish_MultipleClients()
        {
            var serverAdapter         = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger());
            var s                     = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
            var receivedMessagesCount = 0;
            var locked                = new object();

            var clientOptions = new MqttClientOptionsBuilder()
                                .WithTcpServer("localhost")
                                .Build();
            var clientOptions2 = new MqttClientOptionsBuilder()
                                 .WithTcpServer("localhost")
                                 .Build();

            try
            {
                await s.StartAsync(new MqttServerOptions());

                var c1 = new MqttFactory().CreateMqttClient();
                var c2 = new MqttFactory().CreateMqttClient();

                await c1.ConnectAsync(clientOptions);

                await c2.ConnectAsync(clientOptions2);

                c1.ApplicationMessageReceived += (_, __) =>
                {
                    lock (locked)
                    {
                        receivedMessagesCount++;
                    }
                };

                c2.ApplicationMessageReceived += (_, __) =>
                {
                    lock (locked)
                    {
                        receivedMessagesCount++;
                    }
                };

                var message = new MqttApplicationMessageBuilder().WithTopic("a").WithAtLeastOnceQoS().Build();
                await c1.SubscribeAsync(new TopicFilter("a", MqttQualityOfServiceLevel.AtLeastOnce));

                await c2.SubscribeAsync(new TopicFilter("a", MqttQualityOfServiceLevel.AtLeastOnce));

                //await Task.WhenAll(Publish(c1, message), Publish(c2, message));
                await Publish(c1, message);

                await Task.Delay(500);
            }
            finally
            {
                await s.StopAsync();
            }

            Assert.AreEqual(2000, receivedMessagesCount);
        }
        public static PythonDictionary publish_external(PythonDictionary parameters)
        {
            if (parameters is null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            var server   = Convert.ToString(parameters.get("server"));
            var port     = Convert.ToInt32(parameters.get("port", 1883));
            var username = Convert.ToString(parameters.get("username"));
            var password = Convert.ToString(parameters.get("password"));
            var clientId = Convert.ToString(parameters.get("client_id", Guid.NewGuid().ToString("N")));
            var topic    = Convert.ToString(parameters.get("topic"));
            var qos      = Convert.ToInt32(parameters.get("qos", 0));
            var retain   = Convert.ToBoolean(parameters.get("retain", false));
            var tls      = Convert.ToBoolean(parameters.get("tls", false));
            var timeout  = Convert.ToInt32(parameters.get("timeout", 5000));
            var payload  = parameters.get("payload", null);

            var mqttClient = new MqttFactory().CreateMqttClient();

            try
            {
                var options = new MqttClientOptionsBuilder().WithTcpServer(server, port).WithCredentials(username, password).WithClientId(clientId)
                              .WithTimeout(TimeSpan.FromMilliseconds(timeout)).WithTls(new MqttClientOptionsBuilderTlsParameters
                {
                    UseTls = tls
                }).Build();

                mqttClient.ConnectAsync(options).GetAwaiter().GetResult();

                var message = new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(PythonConvert.ToPayload(payload))
                              .WithQualityOfServiceLevel((MqttQualityOfServiceLevel)qos).WithRetainFlag(retain).Build();

                mqttClient.PublishAsync(message).GetAwaiter().GetResult();

                return(new PythonDictionary
                {
                    ["type"] = "success"
                });
            }
            catch (MqttConnectingFailedException)
            {
                return(new PythonDictionary
                {
                    ["type"] = "exception.connecting_failed"
                });
            }
            catch (Exception exception)
            {
                return(PythonConvert.ToPythonDictionary(new ExceptionPythonModel(exception).ToDictionary()));
            }
            finally
            {
                mqttClient?.DisconnectAsync().GetAwaiter().GetResult();
                mqttClient?.Dispose();
            }
        }
Пример #25
0
        public async Task InitializeSubscriber(ClientConfiguration configuration)
        {
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(configuration.ClientId)
                          .WithCleanSession(false)
                          .WithTcpServer(configuration.Host, configuration.Port)
                          .WithCredentials(configuration.Username, configuration.Password)
                          .WithKeepAlivePeriod(TimeSpan.FromMilliseconds(configuration.KeepAlivePeriod))
                          .WithCommunicationTimeout(TimeSpan.FromMilliseconds(configuration.CommunicationTimeout)).Build();

            var mqttClient = new MqttFactory().CreateMqttClient();

            string responsePayload = string.Empty;

            mqttClient.UseApplicationMessageReceivedHandler(args =>
            {
                var payloadMqtt = args.ApplicationMessage.Payload;
                var topic       = args.ApplicationMessage.Topic;

                var payload = Encoding.Default.GetString(payloadMqtt);
                var message = JsonConvert.DeserializeObject <CommandDto>(payload);

                Console.WriteLine($"Subscriber have received message from topic : {topic}");

                if (topic.StartsWith("MQTTnet.RPC/"))
                {
                    if (topic.EndsWith("/DoWork"))
                    {
                        Console.WriteLine($"Subscriber have done work with id : {message.Id}");
                        responsePayload = "Work done with success";
                    }

                    if (topic.EndsWith("/DoOtherWork"))
                    {
                        responsePayload = "Other Work done with success";
                    }

                    var messageMqtt = new MqttApplicationMessageBuilder()
                                      .WithTopic(topic + "/response")
                                      .WithPayload(responsePayload)
                                      .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                                      .WithRetainFlag(false)
                                      .Build();

                    Task.Run(async() => await mqttClient.PublishAsync(messageMqtt));
                }
            });

            var connectResult = await mqttClient.ConnectAsync(options);

            Console.WriteLine($"Subscriber connection result : {connectResult.ResultCode}");

            //await mqttClient.SubscribeAsync("#");
            await mqttClient.SubscribeAsync("MQTTnet.RPC/+/DoWork");

            await mqttClient.SubscribeAsync("MQTTnet.RPC/+/DoOtherWork");
        }
Пример #26
0
        public async Task Connect_To_Invalid_Server_Wrong_IP()
        {
            var client = new MqttFactory().CreateMqttClient();

            using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2)))
            {
                await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("1.2.3.4").Build(), timeout.Token);
            }
        }
Пример #27
0
        public async Task MqttServer_SameClientIdConnectDisconnectEventOrder()
        {
            var s = new MqttFactory().CreateMqttServer();

            var events = new List <string>();

            s.ClientConnected += (_, __) =>
            {
                lock (events)
                {
                    events.Add("c");
                }
            };

            s.ClientDisconnected += (_, __) =>
            {
                lock (events)
                {
                    events.Add("d");
                }
            };

            var clientOptions = new MqttClientOptionsBuilder()
                                .WithTcpServer("localhost")
                                .WithClientId("same_id")
                                .Build();

            await s.StartAsync(new MqttServerOptions());

            var c1 = new MqttFactory().CreateMqttClient();
            var c2 = new MqttFactory().CreateMqttClient();

            await c1.ConnectAsync(clientOptions);

            await Task.Delay(250);

            await c2.ConnectAsync(clientOptions);

            await Task.Delay(250);

            await c1.DisconnectAsync();

            await Task.Delay(250);

            await c2.DisconnectAsync();

            await Task.Delay(250);

            await s.StopAsync();

            var flow = string.Join(string.Empty, events);

            Assert.AreEqual("cdcd", flow);
        }
Пример #28
0
        public async Task MqttServer_LotsOfRetainedMessages()
        {
            const int ClientCount = 100;

            var server = new MqttFactory().CreateMqttServer();

            try
            {
                await server.StartAsync(new MqttServerOptionsBuilder().Build());

                Parallel.For(
                    0,
                    ClientCount,
                    new ParallelOptions {
                    MaxDegreeOfParallelism = 10
                },
                    i =>
                {
                    using (var client = new MqttFactory().CreateMqttClient())
                    {
                        client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build())
                        .GetAwaiter().GetResult();

                        for (var j = 0; j < 10; j++)
                        {
                            // Clear retained message.
                            client.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("r" + i)
                                                .WithPayload(new byte[0]).WithRetainFlag().Build()).GetAwaiter().GetResult();

                            // Set retained message.
                            client.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("r" + i)
                                                .WithPayload("value" + j).WithRetainFlag().Build()).GetAwaiter().GetResult();
                        }

                        client.DisconnectAsync().GetAwaiter().GetResult();
                    }
                });

                await Task.Delay(100);

                var retainedMessages = server.GetRetainedMessages();

                Assert.AreEqual(ClientCount, retainedMessages.Count);

                for (var i = 0; i < ClientCount; i++)
                {
                    Assert.IsTrue(retainedMessages.Any(m => m.Topic == "r" + i));
                }
            }
            finally
            {
                await server.StopAsync();
            }
        }
Пример #29
0
        public static void Main()
        {
            var currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         // ReSharper disable once AssignNullToNotNullAttribute
                         .WriteTo.File(Path.Combine(currentPath,
                                                    @"log\MqttBridge_.txt"), rollingInterval: RollingInterval.Day)
                         .WriteTo.Console()
                         .CreateLogger();

            var config = ReadConfiguration(currentPath);

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithDefaultEndpoint().WithApplicationMessageInterceptor(
                async c =>
            {
                IMqttClientOptions options;

                if (config.UseSsl)
                {
                    options = new MqttClientOptionsBuilder()
                              .WithClientId(config.BridgeUser.ClientId)
                              .WithTcpServer(config.BridgeUrl, config.BridgePort)
                              .WithCredentials(config.BridgeUser.UserName, config.BridgeUser.Password)
                              .WithTls()
                              .WithCleanSession()
                              .Build();
                }
                else
                {
                    options = new MqttClientOptionsBuilder()
                              .WithClientId(config.BridgeUser.ClientId)
                              .WithTcpServer(config.BridgeUrl, config.BridgePort)
                              .WithCredentials(config.BridgeUser.UserName, config.BridgeUser.Password)
                              .WithCleanSession()
                              .Build();
                }

                var mqttClient = new MqttFactory().CreateMqttClient();
                await mqttClient.ConnectAsync(options, CancellationToken.None);
                await mqttClient.PublishAsync(c.ApplicationMessage, CancellationToken.None);
                await mqttClient.DisconnectAsync(null, CancellationToken.None);

                c.AcceptPublish = true;
                LogMessage(c);
            });

            var mqttServer = new MqttFactory().CreateMqttServer();

            mqttServer.StartAsync(optionsBuilder.Build());
            Console.ReadLine();
        }
Пример #30
0
    /// <summary>
    ///   Sets up a connection to the MQTT server specified by <c>uid</c>, <c>host</c> and <c>port</c>.
    ///   Sets up a connection to the Hyker platform using <c>uid</c> and the settings in <c>config</c>.
    ///   Registers the UID if it does not already exist in the system.
    /// </summary>
    /// <exception cref="System.Exception">
    ///   Thrown when configuration file does not exist or contains badly formatted properties,
    ///   if the UID is already registered on another device,
    ///   or if the connection to the KDS cannot be established.
    /// </exception>
    /// <param name="uid">The unique identifier of the current device.</param>
    /// <param name="password">The password for the private key of the current device.</param>
    /// <param name="config">The dictionary containing the Riks settings, API keys, etc. to be used.</param>
    public static async Task <RiksMQTTClient> Connect(string uid, string password, string host, int port, Dictionary <string, object> config)
    {
        var mqttClient = new MqttFactory().CreateMqttClient();
        var options    = new MqttClientOptionsBuilder()
                         .WithClientId(uid)
                         .WithTcpServer(host, port)
                         .Build();
        await mqttClient.ConnectAsync(options);

        return(new RiksMQTTClient(mqttClient, uid, password, config));
    }