Example #1
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();
            }
        }
Example #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);
        }
Example #3
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();
            }
        }
Example #4
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();
            }
        }
Example #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);
        }
        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();
            }
        }
Example #7
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();
        }
Example #8
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);
        }
Example #9
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();
            }
        }
Example #10
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();
        }
Example #11
0
        public async Task MqttServer_SameClientIdConnectDisconnectEventOrder()
        {
            var serverAdapter = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger());
            var s             = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());

            var connectedClient = false;
            var connecteCalledBeforeConnectedClients = false;

            s.ClientConnected += (_, __) =>
            {
                connecteCalledBeforeConnectedClients |= connectedClient;
                connectedClient = true;
            };

            s.ClientDisconnected += (_, __) =>
            {
                connectedClient = false;
            };

            var clientOptions = new MqttClientOptionsBuilder()
                                .WithTcpServer("localhost")
                                .WithClientId(Guid.NewGuid().ToString())
                                .Build();

            await s.StartAsync(new MqttServerOptions());

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

            await c1.ConnectAsync(clientOptions);

            await Task.Delay(100);

            await c2.ConnectAsync(clientOptions);

            await Task.Delay(100);

            await c1.DisconnectAsync();

            await c2.DisconnectAsync();

            await s.StopAsync();

            await Task.Delay(100);

            Assert.IsFalse(connecteCalledBeforeConnectedClients, "ClientConnected was called before ClientDisconnect was called");
        }
Example #12
0
        public async Task Connect_And_Disconnect()
        {
            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.DisconnectAsync();
            }
            finally
            {
                await server.StopAsync();
            }
        }
Example #13
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();
        }
Example #14
0
        public async Task MqttServer_Client_Disconnect_Without_Errors()
        {
            var errors = 0;

            MqttNetGlobalLogger.LogMessagePublished += (_, e) =>
            {
                System.Diagnostics.Debug.WriteLine($"[{e.TraceMessage.Timestamp:s}] {e.TraceMessage.Source} {e.TraceMessage.Message}");

                if (e.TraceMessage.Level == MqttNetLogLevel.Error)
                {
                    errors++;
                }
            };

            bool clientWasConnected;

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

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

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

                await client.ConnectAsync(clientOptions);

                clientWasConnected = true;

                await client.DisconnectAsync();

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

            Assert.IsTrue(clientWasConnected);
            Assert.AreEqual(0, errors);
        }
Example #15
0
        public async Task MqttServer_ConnectionDenied()
        {
            var server = new MqttFactory().CreateMqttServer();
            var client = new MqttFactory().CreateMqttClient();

            try
            {
                var options = new MqttServerOptionsBuilder().WithConnectionValidator(context =>
                {
                    context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized;
                }).Build();

                await server.StartAsync(options);


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

                try
                {
                    await client.ConnectAsync(clientOptions);

                    Assert.Fail("An exception should be raised.");
                }
                catch (Exception exception)
                {
                    if (exception is MqttConnectingFailedException)
                    {
                    }
                    else
                    {
                        Assert.Fail("Wrong exception.");
                    }
                }
            }
            finally
            {
                await client.DisconnectAsync();

                await server.StopAsync();

                client.Dispose();
            }
        }
Example #16
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();
            }
        }
Example #17
0
        public async Task Publish_QoS_2()
        {
            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.PublishAsync("a", "b", MqttQualityOfServiceLevel.ExactlyOnce);

                await client.DisconnectAsync();

                Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode);
            }
            finally
            {
                await server.StopAsync();
            }
        }
Example #18
0
        public async Task PublishRemoveIDMCommand(Guid moduleId)
        {
            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($"idm/remove/{moduleId}")
                          .WithPayload(1.ToString())
                          .WithExactlyOnceQoS()
                          .Build();

            await mqttClient.PublishAsync(message);

            await mqttClient.DisconnectAsync();
        }
Example #19
0
        public async Task MqttServer_HandleCleanDisconnect()
        {
            MqttNetGlobalLogger.LogMessagePublished += (_, e) =>
            {
                System.Diagnostics.Debug.WriteLine($"[{e.TraceMessage.Timestamp:s}] {e.TraceMessage.Source} {e.TraceMessage.Message}");
            };

            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);
        }
        static async Task Main(string[] args)
        {
            // Set up mqttClient
            var mqttClient = new MqttFactory().CreateMqttClient();
            var options    = new MqttClientOptionsBuilder()
                             .WithClientId(mqttClientId)
                             .WithWebSocketServer(mqttBrokerAddress)
                             //.WithTcpServer(mqttBrokerAddress)
                             .WithCredentials(mqttUser, mqttPassword)
                             .WithTls()
                             //.WithCleanSession()
                             .Build();

            mqttClient.UseApplicationMessageReceivedHandler(async e =>
            {
                var parsedMessage = parseMqttMessage(e.ApplicationMessage.Payload);
                await sendDeviceMessage(parsedMessage);

                /*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}"); */
            });

            mqttClient.UseConnectedHandler(async e =>
            {
                Console.WriteLine("Connected to MQTT Server");

                // Subscribe to a topic
                await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(mqttTopic).Build());
            });

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

            Console.WriteLine("Press any key to close MQTT - HTTP bridge");
            Console.ReadKey();
            await mqttClient.DisconnectAsync();
        }
Example #21
0
        public static async Task Run(CancellationToken cancelToken)
        {
            Console.Write("MIC Hostname: ");
            var hostname = await ConsoleUtils.ReadLineAsync(cancelToken);

            Console.WriteLine("Getting MIC manifest . . .");
            using (var micClient = await CreateMicClient(hostname, cancelToken))
            {
                var micClientConfig = micClient.Config;
                micClientConfig.LogMetrics = true;

                Console.Write("Username: "******"Password: "******"Logging in . . . ");
                var login = await micClient.AuthLogin(
                    username, password, cancelToken);

                ((IMicModel)(login.User)).AdditionalData.TryGetValue("domainPath", out object domainPath);
                Console.WriteLine("Successful!");
                Console.WriteLine();

                var awsCredentials = ((IMicClient)micClient).AwsCredentials;
                Console.WriteLine($"Cognito Identity pool: {awsCredentials.IdentityPoolId}");
                Console.WriteLine($"  Identity Id: {login.Credentials.IdentityId}");
                Console.WriteLine($"  Login provider: {micClient.Manifest.GetCognitoProviderName()}");
                Console.WriteLine($"  Token: {login.Credentials.Token}");
                Console.WriteLine();

                var immutableCredentials = await awsCredentials.GetCredentialsAsync();

                Console.WriteLine("AWS Immutable Credentials:");
                Console.WriteLine($"  Access key: {immutableCredentials.AccessKey}");
                Console.WriteLine($"  Secret key: {immutableCredentials.SecretKey}");
                if (immutableCredentials.UseToken)
                {
                    Console.WriteLine($"  Token:      {immutableCredentials.Token}");
                }
                Console.WriteLine();

                var userInfo = await micClient.UserGet(login.User.Username, cancelToken);

                Console.WriteLine(JsonConvert.SerializeObject(userInfo, Formatting.Indented));
                Console.WriteLine();

                Console.WriteLine($"IoT Endpoint: {micClient.Manifest.IotEndpoint}");
                Console.Write("Connecting MQTT Client . . . ");
                var iotConfig = micClientConfig.Create <AmazonIoTDeviceGatewayConfig>();
                using (var iotClient = new AmazonIoTDeviceGatewayClient(awsCredentials, iotConfig))
                {
                    var mqttOptionsTask = iotClient.CreateMqttWebSocketClientOptionsAsync(micClient.Manifest.IotEndpoint, cancelToken);

                    using (var mqttClient = new MqttFactory().CreateMqttClient())
                    {
                        var mqttConsoleSync = new object();
                        mqttClient.ApplicationMessageReceived += (sender, e) =>
                        {
                            Task.Run(() =>
                            {
                                lock (mqttConsoleSync)
                                {
                                    Console.WriteLine($"Application Message received by client {e.ClientId}");
                                    Console.WriteLine($"Topic: {e.ApplicationMessage.Topic}, QoS: {e.ApplicationMessage.QualityOfServiceLevel}");
                                    if (e.ApplicationMessage.Retain)
                                    {
                                        Console.WriteLine("  Message should be retained");
                                    }
                                    int payloadLength = e.ApplicationMessage.Payload?.Length ?? 0;
                                    Console.WriteLine($"  Message Payload: ({payloadLength} byte{(payloadLength == 1 ? "" : "s")})");
                                    Console.WriteLine();
                                    string payload = e.ApplicationMessage.ConvertPayloadToString();
                                    try
                                    {
                                        var jtoken = JToken.Parse(payload);
                                        payload    = jtoken.ToString(Formatting.Indented);
                                    }
                                    catch { }
                                    Console.WriteLine(payload);
                                    Console.WriteLine();
                                    Console.WriteLine(new string('-', count: 20));
                                    Console.WriteLine();
                                }
                            }, cancelToken);
                        };

                        var mqttOptions = await mqttOptionsTask;
                        var connectInfo = await mqttClient.ConnectAsync(mqttOptions);

                        try
                        {
                            cancelToken.ThrowIfCancellationRequested();
                            Console.WriteLine("Successful!");
                            Console.Write($"Subscribing to events . . . ");
                            var subscriptions = await mqttClient.SubscribeAsync($"event{domainPath}");

                            cancelToken.ThrowIfCancellationRequested();
                            var subscriptionsWild = await mqttClient.SubscribeAsync($"event{domainPath}#");

                            cancelToken.ThrowIfCancellationRequested();
                            var thingUpdateSubs = await mqttClient.SubscribeAsync($"thing-update{domainPath}#");

                            cancelToken.ThrowIfCancellationRequested();
                            int subCount = subscriptions.Count + subscriptionsWild.Count + thingUpdateSubs.Count;
                            Console.WriteLine($"{subCount} subscription{(subCount == 1 ? "" : "s")}.");
                            foreach (var sub in subscriptions.Concat(subscriptionsWild).Concat(thingUpdateSubs))
                            {
                                var tf = sub.TopicFilter;
                                Console.WriteLine($"{tf.Topic} (QoS: {tf.QualityOfServiceLevel}): {sub.ReturnCode}");
                            }
                            Console.WriteLine();
                            cancelToken.ThrowIfCancellationRequested();

                            var resetEvent = new ManualResetEventSlim();
                            resetEvent.Wait(cancelToken);
                        }
                        finally
                        {
                            await mqttClient.DisconnectAsync();
                        }
                    }
                }
            }
        }
Example #22
0
        public override async Task SendAsync(PayloadRoot payload, HostChannel channel)
        {
            if (channel == HostChannel.Undefined || payload.Row.Count == 0)
            {
                return;
            }

            string clientId = null, topic = null;

            switch (channel)
            {
            case HostChannel.Status:
                clientId = payload.MachineNo + "#" + nameof(HostChannel.Status);
                topic    = $"/{nameof(HostTransaction.Smmp).ToLower()}/{payload.MachineNo}/{nameof(WorkTasks.Collection).ToLower()}/{nameof(HostChannel.Status).ToLower()}";
                break;

            case HostChannel.Parameter:
                clientId = payload.MachineNo + "#" + nameof(HostChannel.Parameter);
                topic    = $"/{nameof(HostTransaction.Smmp).ToLower()}/{payload.MachineNo}/{nameof(WorkTasks.Collection).ToLower()}/{nameof(HostChannel.Parameter).ToLower()}";
                break;

            case HostChannel.Production:
                clientId = payload.MachineNo + "#" + nameof(HostChannel.Production);
                topic    = $"/{nameof(HostTransaction.Smmp).ToLower()}/{payload.MachineNo}/{nameof(WorkTasks.Collection).ToLower()}/{nameof(HostChannel.Production).ToLower()}";
                break;
            }

            payload.Row.ForEach(c =>
            {
                if (YamlBase.Propertie.Debug)
                {
                    Console.WriteLine($"[{DateTime.Now:MM/dd HH:mm ss}] ModbusTCP => NO.{payload.MachineNo} - {c.AttribNo}:{c.AttribValue}");
                }
            });

            try
            {
                FoundationProvider box = new();

                IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
                IConfigurationRoot    config  = builder.Build();

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

                await client.ConnectAsync(new MqttClientOptionsBuilder()
                                          .WithTcpServer(box.FoundationBasic.Server.Address.Split('/')[2].Split(':')[0], box.FoundationBasic.Server.MqttPort)
                                          .WithCredentials(config.GetValue <string>("Server:Account"), config.GetValue <string>("Server:Password"))
                                          .WithClientId(clientId)
                                          .Build());

                await client.PublishAsync(new MqttApplicationMessageBuilder()
                                          .WithTopic(topic)
                                          .WithPayload(JsonConvert.SerializeObject(payload))
                                          .WithExactlyOnceQoS()
                                          .WithRetainFlag()
                                          .Build());

                await client.DisconnectAsync();

                client.Dispose();
            }
            catch (Exception e)
            {
                LogBuilder.WriteLog(LogEventLevel.Error, "MQTT Server => " + e.Message);
            }
        }
Example #23
0
        public async Task Loading1000PublishClient()
        {
            //Create 1000 publish client
            var publishServers = 1000;

            //send tries
            var sendTries = 10;

            //Add extra message
            var extraMessage = "oiservtionseopteoprvtwetnuioertrptuiweptprovirtuoeriopvtwuipertnoweuioertuvpert" +
                               "uwpoerutvipetnwueiroprtuipwueotuweioprtuowpetuioueroptuwvoenutwewepvtornutoivweweirvtuepr";

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

            //Create publish client(s)
            var publishers = new List <IMqttClient>();

            for (int i = 0; i < publishServers; i++)
            {
                var publishClient = new MqttFactory().CreateMqttClient();
                await publishClient.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer(ServerAddress).Build());

                publishers.Add(publishClient);
            }

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

            receniveClient.ApplicationMessageReceived += (object o, MqttApplicationMessageReceivedEventArgs e) =>
            {
                var receiveMessage = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                var receiveIndex   = int.Parse(receiveMessage.Replace(extraMessage, ""));
                receiveIndexes.Add(receiveIndex);
            };

            //Receive client subscribe a topic
            await receniveClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(Topic).WithQualityOfServiceLevel(ConnectQuality).Build());

            //Sending message
            for (int i = 0; i < sendTries; i++)
            {
                for (int j = 0; j < publishServers; j++)
                {
                    var index = j + i * publishServers;

                    //Publish Client send a message
                    await publishers[j].PublishAsync(new MqttApplicationMessage()
                    {
                        Topic = Topic,
                        QualityOfServiceLevel = ConnectQuality,
                        Payload = Encoding.UTF8.GetBytes(index.ToString() + extraMessage),
                    });
                }
            }

            //Wait
            await Task.Delay(1000);

            //check receive message
            for (int i = 0; i < sendTries * publishServers; i++)
            {
                if (!receiveIndexes.Contains(i))
                {
                    Assert.AreEqual(-1, i);
                }
            }

            Console.WriteLine($"Total receive : {receiveIndexes.Count}");

            //Success
            Assert.IsTrue(true);

            //stop server
            await receniveClient.DisconnectAsync();

            foreach (var publisher in publishers)
            {
                await publisher.DisconnectAsync();
            }
            await server.StopAsync();
        }