Пример #1
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();
            }
        }
Пример #2
0
        /// <summary>
        /// 4
        /// </summary>
        /// <returns></returns>
        static async Task ManagedClientTest()
        {
            var ms = new ClientRetainedMessageHandler();

            var options = new MqttManagedClientOptions
            {
                ClientOptions = new MqttClientOptions
                {
                    ClientId    = "MQTTnetManagedClientTest",
                    Credentials = new MqttClientCredentials()
                    {
                        Username = "******",
                        Password = Guid.NewGuid().ToString()
                    },
                    ChannelOptions = new MqttClientTcpOptions
                    {
                        Server = "broker.hivemq.com"
                    }
                },

                AutoReconnectDelay = TimeSpan.FromSeconds(1),
                Storage            = ms
            };

            try
            {
                var managedClient = new MqttFactory().CreateManagedMqttClient();

                managedClient.ApplicationMessageReceived += (s, e) =>
                {
                    Console.WriteLine(">> RECEIVED: " + e.ApplicationMessage.Topic);
                };

                await managedClient.PublishAsync(builder => builder.WithTopic("Step").WithPayload("1"));

                await managedClient.PublishAsync(builder => builder.WithTopic("Step").WithPayload("2").WithAtLeastOnceQoS());

                await managedClient.StartAsync(options);

                await managedClient.SubscribeAsync(new TopicFilter("xyz", MqttQualityOfServiceLevel.AtMostOnce));

                await managedClient.SubscribeAsync(new TopicFilter("abc", MqttQualityOfServiceLevel.AtMostOnce));

                await managedClient.PublishAsync(builder => builder.WithTopic("Step").WithPayload("3"));

                Console.WriteLine("Managed client started.");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #3
0
        static async Task CreateManagedClient(string topic)
        {
            string clientId      = "ManagedClient";
            var    clientOptions = new MqttClientOptionsBuilder()
                                   .WithClientId(clientId)
                                   .WithTcpServer(brokenHostName, port: 1883)
                                   .WithCleanSession()
                                   .Build();
            ManagedMqttClientOptions managedClientOptions = new ManagedMqttClientOptionsBuilder()
                                                            .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                                            .WithClientOptions(clientOptions)
                                                            .Build();
            var managedClient = new MqttFactory().CreateManagedMqttClient();
            //Subscribe to the topic
            //await managedClient.SubscribeAsync(new TopicFilterBuilder()
            //                                        .WithTopic(topic)
            //                                        .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce)
            //                                        .Build());
            await managedClient.StartAsync(managedClientOptions);

            await managedClient.PublishAsync(topic, "Hello from managed client, lets count from 0 to 99");

            //Show the received messege in form topic: message
            //managedClient.UseApplicationMessageReceivedHandler(e =>
            //{
            //    try
            //    {
            //        string topic = e.ApplicationMessage.Topic;
            //        if (string.IsNullOrWhiteSpace(topic) == false)
            //        {
            //            string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
            //            Console.WriteLine($"Topic: {topic}. Message Received: {payload}");
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine(ex.Message, ex);
            //    }
            //});

            //Sending messages 100 times every 3 seconds
            for (int i = 0; i < 100; i++)
            {
                await managedClient.PublishAsync(topic, i.ToString(), MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);

                Thread.Sleep(3000);
            }
            Console.ReadLine();
        }
Пример #4
0
        public static async Task RunAsync()
        {
            var ms = new ClientRetainedMessageHandler();

            var options = new ManagedMqttClientOptions
            {
                ClientOptions = new MqttClientOptions
                {
                    ClientId       = "MQTTnetManagedClientTest",
                    Credentials    = new RandomPassword(),
                    ChannelOptions = new MqttClientTcpOptions
                    {
                        Server = "broker.hivemq.com"
                    }
                },

                AutoReconnectDelay = TimeSpan.FromSeconds(1),
                Storage            = ms
            };

            try
            {
                var managedClient = new MqttFactory().CreateManagedMqttClient();
                managedClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
                {
                    Console.WriteLine(">> RECEIVED: " + e.ApplicationMessage.Topic);
                });

                await managedClient.StartAsync(options);

                await managedClient.PublishAsync(builder => builder.WithTopic("Step").WithPayload("1"));

                await managedClient.PublishAsync(builder => builder.WithTopic("Step").WithPayload("2").WithAtLeastOnceQoS());

                await managedClient.SubscribeAsync(new MqttTopicFilter { Topic = "xyz", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce });

                await managedClient.SubscribeAsync(new MqttTopicFilter { Topic = "abc", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce });

                await managedClient.PublishAsync(builder => builder.WithTopic("Step").WithPayload("3"));

                Console.WriteLine("Managed client started.");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #5
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);
        }
Пример #6
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);
            }
        }
Пример #7
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);
            }
        }
Пример #8
0
        public async Task MqttServer_Publish()
        {
            var serverAdapter         = new TestMqttServerAdapter();
            var s                     = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
            var receivedMessagesCount = 0;

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

                var c1 = await serverAdapter.ConnectTestClient(s, "c1");

                c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;

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

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

            Assert.AreEqual(1, receivedMessagesCount);
        }
Пример #9
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();
            }
        }
Пример #10
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();
            }
        }
Пример #11
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;
            }
        }
Пример #12
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);

            if (mqttClient.IsConnected)
            {
                logger?.Info("### CONNECTED WITH SERVER ###");
            }

            //publish AAS to AAS Topic
            foreach (AdminShell.AdministrationShell aas in package.AasEnv.AdministrationShells)
            {
                logger?.Info("Publish AAS");
                var message = new MqttApplicationMessageBuilder()
                              .WithTopic("AAS")
                              .WithPayload(Newtonsoft.Json.JsonConvert.SerializeObject(aas))
                              .WithExactlyOnceQoS()
                              .WithRetainFlag()
                              .Build();

                await mqttClient.PublishAsync(message);

                //publish submodels
                foreach (var sm in package.AasEnv.Submodels)
                {
                    logger?.Info("Publish " + "Submodel_" + sm.idShort);

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

                    await mqttClient.PublishAsync(message2);
                }
            }
        }
        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();
            }
        }
Пример #14
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");
        }
Пример #15
0
        static async Task Main(string[] args)
        {
            var mqttClientOptions = new MqttClientOptionsBuilder()
                                    .WithClientId("client1")
                                    .WithTcpServer("localhost", 1884)
                                    .Build();
            var opt = new ManagedMqttClientOptionsBuilder()
                      .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                      .WithClientOptions(mqttClientOptions)
                      .Build();

            var client = new MqttFactory().CreateManagedMqttClient();
            await client.StartAsync(opt);

            var generic_msg = new MqttApplicationMessageBuilder()
                              .WithTopic("farm/client1")
                              .WithPayload(new Payload().ToBytes(false))
                              .WithAtLeastOnceQoS()
                              .Build();
            var rng       = new Random();
            var prevValue = 0.0;

            for (var i = 0; i < 1000000; i++)
            {
                prevValue += rng.NextDouble() * 0.01;
                await client.PublishAsync(generic_msg);

                var moistureMsg = new MqttApplicationMessageBuilder()
                                  .WithTopic("farm/client1/moisture")
                                  .WithPayload(new MoisturePayload {
                    MoistureFraction = prevValue
                }.ToBytes(false))
                                  .WithAtLeastOnceQoS()
                                  .Build();
                await client.PublishAsync(moistureMsg);

                Console.WriteLine("Sent.");
                await Task.Delay(1000);
            }

            Console.ReadLine();
        }
Пример #16
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();
        }
Пример #17
0
        public async Task MqttSendTest()
        {
            var jsonEventFormatter = new JsonEventFormatter();
            var cloudEvent         = new CloudEvent("com.github.pull.create",
                                                    new Uri("https://github.com/cloudevents/spec/pull/123"))
            {
                Id          = "A234-1234-1234",
                Time        = new DateTime(2018, 4, 5, 17, 31, 0, DateTimeKind.Utc),
                ContentType = new ContentType(MediaTypeNames.Text.Xml),
                Data        = "<much wow=\"xml\"/>"
            };

            var attrs = cloudEvent.GetAttributes();

            attrs["comexampleextension1"] = "value";
            attrs["comexampleextension2"] = new { othervalue = 5 };

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

            var options = new MqttClientOptionsBuilder()
                          .WithClientId("Client1")
                          .WithTcpServer("localhost", 52355)
                          .WithCleanSession()
                          .Build();

            TaskCompletionSource <CloudEvent> tcs = new TaskCompletionSource <CloudEvent>();
            await client.ConnectAsync(options);

            client.ApplicationMessageReceived += (sender, args) =>
            {
                tcs.SetResult(args.ApplicationMessage.ToCloudEvent(jsonEventFormatter));
            };

            var result = await client.SubscribeAsync("abc");

            await client.PublishAsync(new MqttCloudEventMessage(cloudEvent, new JsonEventFormatter()) { Topic = "abc" });

            var receivedCloudEvent = await tcs.Task;

            Assert.Equal(CloudEventsSpecVersion.V0_2, receivedCloudEvent.SpecVersion);
            Assert.Equal("com.github.pull.create", receivedCloudEvent.Type);
            Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source);
            Assert.Equal("A234-1234-1234", receivedCloudEvent.Id);
            Assert.Equal(DateTime.Parse("2018-04-05T17:31:00Z").ToUniversalTime(),
                         receivedCloudEvent.Time.Value.ToUniversalTime());
            Assert.Equal(new ContentType(MediaTypeNames.Text.Xml), receivedCloudEvent.ContentType);
            Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data);

            var attr = receivedCloudEvent.GetAttributes();

            Assert.Equal("value", (string)attr["comexampleextension1"]);
            Assert.Equal(5, (int)((dynamic)attr["comexampleextension2"]).othervalue);
        }
Пример #18
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);
        }
Пример #19
0
        public static async Task RunQoS0Test()
        {
            try
            {
                //var mqttServer = new MqttFactory().CreateMqttServer();
                //await mqttServer.StartAsync(new MqttServerOptions());

                var options = new MqttClientOptions
                {
                    ChannelOptions = new MqttClientTcpOptions
                    {
                        Server = "127.0.0.1"
                    },
                    CleanSession = true
                };

                var client = new MqttFactory().CreateMqttClient();
                await client.ConnectAsync(options);

                var message = new MqttApplicationMessage
                {
                    Topic   = "A/B/C",
                    Payload = Encoding.UTF8.GetBytes("Hello World"),
                    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
                };

                var stopwatch = new Stopwatch();

                var iteration = 1;
                while (true)
                {
                    var sentMessagesCount = 0;

                    stopwatch.Restart();
                    while (stopwatch.ElapsedMilliseconds < 1000)
                    {
                        await client.PublishAsync(message).ConfigureAwait(false);

                        sentMessagesCount++;
                    }

                    Console.WriteLine($"Sent {sentMessagesCount} messages in iteration #" + iteration);

                    iteration++;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Пример #20
0
        static async Task Main(string[] args)
        {
            var mqttServer     = new MqttFactory().CreateMqttServer();
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionValidator(c =>
            {
                if (c.ClientId.Length < 10)
                {
                    c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                    return;
                }

                if (c.Username != "asd")
                {
                    c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                    return;
                }

                if (c.Password != "123Stella")
                {
                    c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                    return;
                }

                c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
            });
            await mqttServer.StartAsync(optionsBuilder.Build());

            mqttServer.ApplicationMessageReceivedHandler = new MessageHandler();
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
            await mqttServer.PublishAsync("set-on");

            await mqttServer.PublishAsync("set-on");

            await mqttServer.StopAsync();
        }
Пример #21
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();
            }

            {
                // Write all trace messages to the console window.
                MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace = $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                    if (e.TraceMessage.Exception != null)
                    {
                        trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
                    }

                    Console.WriteLine(trace);
                };
            }

            {
                // Use a custom log ID for the logger.
                var factory    = new MqttFactory();
                var mqttClient = factory.CreateMqttClient(new MqttNetLogger("MyCustomId"));
            }
        }
Пример #22
0
        public void Startup()
        {
            MqttClientOptionsBuilder options = new MqttClientOptionsBuilder()
                                               .WithTcpServer(Global.mqtt_server);

            if (!string.IsNullOrEmpty(Global.mqtt_username))
            {
                options = options
                          .WithCredentials(Global.mqtt_username, Global.mqtt_password);
            }

            ManagedMqttClientOptions manoptions = new ManagedMqttClientOptionsBuilder()
                                                  .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                                  .WithClientOptions(options.Build())
                                                  .Build();

            MqttClient            = new MqttFactory().CreateManagedMqttClient();
            MqttClient.Connected += (sender, e) =>
            {
                log.Debug("Connected");

                // For the initial connection wait for the controller connected event to publish config
                // For subsequent connections publish config immediately
                if (ControllerConnected)
                {
                    PublishConfig();
                }
            };
            MqttClient.ConnectingFailed += (sender, e) => { log.Debug("Error connecting " + e.Exception.Message); };

            MqttClient.StartAsync(manoptions);

            MqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;

            MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{Topic.command}").Build());
            MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{Topic.brightness_command}").Build());
            MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{Topic.temperature_heat_command}").Build());
            MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{Topic.temperature_cool_command}").Build());
            MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{Topic.humidify_command}").Build());
            MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{Topic.dehumidify_command}").Build());
            MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{Topic.mode_command}").Build());
            MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{Topic.fan_mode_command}").Build());
            MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{Topic.hold_command}").Build());

            // Wait until shutdown
            trigger.WaitOne();

            MqttClient.PublishAsync($"{Global.mqtt_prefix}/status", "offline", MqttQualityOfServiceLevel.AtMostOnce, true);
        }
Пример #23
0
        public async Task PublishAsync(MqttApplicationMessage message)
        {
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(_configuration.GetSection("MQTT").GetSection("MqttClientEnactorName").Value)
                          .WithTcpServer(_configuration.GetSection("MQTT").GetSection("IP").Value, int.Parse(_configuration.GetSection("MQTT").GetSection("Port").Value))
                          .Build();

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

            await client.ConnectAsync(options);

            await client.PublishAsync(message.Topic, Encoding.UTF8.GetString(message.Payload), MqttQualityOfServiceLevel.AtMostOnce);

            await client.DisconnectAsync();
        }
Пример #24
0
        static async Task Main(string[] args)
        {
            var name     = "test";
            var serverIp = "localhost:1883";
            var topic    = "swag";

            //var client = new Manager(name,serverIp);
            Console.ReadLine();
            var options = new ManagedMqttClientOptionsBuilder().
                          WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId(name)
                                             //.WithCredentials("panon", "dellaMarra")
                                             .WithTcpServer(serverIp)
                                             //.WithTls()
                                             .Build())
                          .Build();
            var managedMqttClient = new MqttFactory().CreateManagedMqttClient();
            await managedMqttClient.StartAsync(options);

            if (managedMqttClient.IsStarted)
            {
                Console.WriteLine("Client startato");
            }
            if (managedMqttClient.IsConnected)
            {
                Console.WriteLine("Client connesso");
            }
            Console.ReadLine();
            //await managedMqttClient.SubscribeAsync(topic);
            //Console.ReadLine();
            await managedMqttClient.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(topic)
                                                 .WithPayload("Hello World")
                                                 .WithExactlyOnceQoS()
                                                 .WithRetainFlag()
                                                 .Build()
                                                 );

            Console.ReadLine();
            //if (await client.SubscribeTopic(topic)) Console.WriteLine("Subscribed to " + topic);
            //else Console.WriteLine("Cannot subscribe");
            //Console.ReadLine();
            //if (client.SendMessage("swag", "Hello")) Console.WriteLine("Message sent to " + topic);
            //else Console.WriteLine("Cannot send message");
            //if (client.SendMessage("swag", "I'm Smenz")) Console.WriteLine("Message sent to " + topic);
            //else Console.WriteLine("Cannot send message");
        }
Пример #25
0
        static void Main(string[] args)
        {
            server.Start();

            if (args.Length == 0)
            {
                System.Console.WriteLine("podaj scieżkę do pliku z pozycjami cymbalistow...");
                return;
            }
            System.Console.WriteLine("Gdy na konsoli się pojawią informacje typu");
            System.Console.WriteLine("[jankiel1] subscribe [jankiel2]");
            System.Console.WriteLine("Nalezy wcisnąć ENTER by wysłać wiadomość od 'Mastera'");
            System.Console.WriteLine("poinformowania cymbalistów by rozpoczeli działanie");
            var positions = Helpers.GetPositions(args[0]);

            int D = 0;

            for (int i = 0; i < positions.GetLength(0); i++)
            {
                var name      = Helpers.GetJankielName(positions[i]);
                var neighbors = Helpers.GetNeighborsForI(positions, i, Settings.Default.HearDistance);
                if (D < neighbors.Length)
                {
                    D = neighbors.Length;
                }

                new Thread(new ThreadStart(new Jankiel.Jankiel(name, neighbors).Run)).Start();
            }
            var Master = new MqttFactory().CreateMqttClient();

            Master.Connected += (s, e) =>
            {
                System.Console.WriteLine("Master Connected");
            };
            Master.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost", 1884).Build());

            var msg   = new StartExMessage(D * 2, 5, positions.GetLength(0)).GetBytes();
            var mqMsg = new MqttApplicationMessageBuilder().WithTopic("Ex3Master").WithPayload(msg).Build();

            System.Console.WriteLine("enter by wysłac wiadomosc od mastera");
            System.Console.ReadLine();

            Master.PublishAsync(mqMsg);
            System.Console.WriteLine("enter by zakonczyc");
            System.Console.ReadLine();
            server.Stop();
        }
Пример #26
0
        static async Task Main(string[] args)
        {
            //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 publish client
            var publishClient = new MqttFactory().CreateMqttClient();
            await publishClient.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer(ServerAddress).Build());

            //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(receiveMessage);
            };

            //Receive client subscribe a topic
            await receniveClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).WithQualityOfServiceLevel(quality).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);
            }
        }
Пример #27
0
        public async Task <bool> OpenDoor()
        {
            using (var mqttClient = new MqttFactory().CreateMqttClient())
            {
                await mqttClient.ConnectAsync(_options, CancellationToken.None);

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(_topic)
                              .WithPayload("1")
                              .WithExactlyOnceQoS()
                              .Build();
                var result = await mqttClient.PublishAsync(message, CancellationToken.None);

                var isSuccess = result.ReasonCode == MqttClientPublishReasonCode.Success;

                return(isSuccess);
            }
        }
Пример #28
0
        public async Task MqttSendTest()
        {
            var jsonEventFormatter = new JsonEventFormatter();
            var cloudEvent         = new CloudEvent
            {
                Type                     = "com.github.pull.create",
                Source                   = new Uri("https://github.com/cloudevents/spec/pull/123"),
                Id                       = "A234-1234-1234",
                Time                     = new DateTimeOffset(2018, 4, 5, 17, 31, 0, TimeSpan.Zero),
                DataContentType          = MediaTypeNames.Text.Xml,
                Data                     = "<much wow=\"xml\"/>",
                ["comexampleextension1"] = "value"
            };

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

            var options = new MqttClientOptionsBuilder()
                          .WithClientId("Client1")
                          .WithTcpServer("localhost", 52355)
                          .WithCleanSession()
                          .Build();

            TaskCompletionSource <CloudEvent> tcs = new TaskCompletionSource <CloudEvent>();
            await client.ConnectAsync(options);

            client.ApplicationMessageReceived += (sender, args) =>
                                                 tcs.SetResult(args.ApplicationMessage.ToCloudEvent(jsonEventFormatter));

            var result = await client.SubscribeAsync("abc");

            await client.PublishAsync(cloudEvent.ToMqttApplicationMessage(ContentMode.Structured, new JsonEventFormatter(), topic: "abc"));

            var receivedCloudEvent = await tcs.Task;

            Assert.Equal(CloudEventsSpecVersion.Default, receivedCloudEvent.SpecVersion);
            Assert.Equal("com.github.pull.create", receivedCloudEvent.Type);
            Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source);
            Assert.Equal("A234-1234-1234", receivedCloudEvent.Id);
            AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time.Value);
            Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType);
            Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data);

            Assert.Equal("value", (string)receivedCloudEvent["comexampleextension1"]);
        }
Пример #29
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer("localhost", 5002)       // Port is optional
                          .Build();

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

            Console.WriteLine("Ready to Connect");

            Console.ReadLine();

            Console.WriteLine("Connecting");

            var task = client.ConnectAsync(options);

            task.ContinueWith(t =>
            {
                Console.WriteLine("Subscribing");
                client.SubscribeAsync("my/amazing/topic");
                client.SubscribeAsync("my/+/stuff");

                return(true);
            })
            .ContinueWith(t =>
            {
                if (t.Result)
                {
                    Task.Delay(10000).Wait();
                    Console.WriteLine("Sending Data");
                    client.PublishAsync("my/dance/stuff", "{ \"DanceMove\":\"Break Dancing\" }");
                }
            });


            Console.WriteLine("Hit Enter to Disconnect");
            Console.ReadLine();
            client.DisconnectAsync().Wait();
            Console.WriteLine("Disconnected");
            Console.WriteLine("Hit Enter to Shutdown");
            Console.ReadLine();
        }
Пример #30
0
        public async Task Subscribe_And_Publish()
        {
            var server  = new MqttFactory().CreateMqttServer();
            var client1 = new MqttFactory().CreateMqttClient();
            var client2 = new MqttFactory().CreateMqttClient();

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

                var receivedMessages = new List <MqttApplicationMessageReceivedEventArgs>();

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

                client1.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
                {
                    lock (receivedMessages)
                    {
                        receivedMessages.Add(e);
                    }
                });

                await client1.SubscribeAsync("a");

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

                await client2.PublishAsync("a", "b");

                await Task.Delay(500);

                await client2.DisconnectAsync();

                await client1.DisconnectAsync();

                Assert.AreEqual(1, receivedMessages.Count);
                Assert.AreEqual("client1", receivedMessages[0].ClientId);
                Assert.AreEqual("a", receivedMessages[0].ApplicationMessage.Topic);
                Assert.AreEqual("b", receivedMessages[0].ApplicationMessage.ConvertPayloadToString());
            }
            finally
            {
                await server.StopAsync();
            }
        }