Example #1
0
        public async Task ManagedClients_Will_Message_Send()
        {
            using (var testEnvironment = new TestEnvironment(TestContext))
            {
                var receivedMessagesCount = 0;

                await testEnvironment.StartServerAsync();

                var willMessage   = new MqttApplicationMessageBuilder().WithTopic("My/last/will").WithAtMostOnceQoS().Build();
                var clientOptions = new MqttClientOptionsBuilder()
                                    .WithTcpServer("localhost", testEnvironment.ServerPort)
                                    .WithWillMessage(willMessage);
                var dyingClient        = testEnvironment.CreateClient();
                var dyingManagedClient = new ManagedMqttClient(dyingClient, testEnvironment.ClientLogger);
                await dyingManagedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
                                                    .WithClientOptions(clientOptions)
                                                    .Build());

                var recievingClient = await testEnvironment.ConnectClientAsync();

                await recievingClient.SubscribeAsync("My/last/will");

                recievingClient.UseApplicationMessageReceivedHandler(context => Interlocked.Increment(ref receivedMessagesCount));

                dyingManagedClient.Dispose();

                await Task.Delay(1000);

                Assert.AreEqual(1, receivedMessagesCount);
            }
        }
Example #2
0
        public async Task Start_Stop()
        {
            using (var testEnvironment = new TestEnvironment(TestContext))
            {
                var server = await testEnvironment.StartServerAsync();

                var managedClient = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetLogger());
                var clientOptions = new MqttClientOptionsBuilder()
                                    .WithTcpServer("localhost", testEnvironment.ServerPort);

                var connected = GetConnectedTask(managedClient);

                await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
                                               .WithClientOptions(clientOptions)
                                               .Build());

                await connected;

                await managedClient.StopAsync();

                await Task.Delay(500);

                Assert.AreEqual(0, (await server.GetClientStatusAsync()).Count);
            }
        }
Example #3
0
        public async Task Start_Stop()
        {
            using (var testEnvironment = new TestEnvironment())
            {
                var factory = new MqttFactory();

                var server = await testEnvironment.StartServerAsync();

                var managedClient = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetLogger().CreateChildLogger());
                var clientOptions = new MqttClientOptionsBuilder()
                                    .WithTcpServer("localhost", testEnvironment.ServerPort);

                TaskCompletionSource <bool> connected = new TaskCompletionSource <bool>();
                managedClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e => { connected.SetResult(true); });

                await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
                                               .WithClientOptions(clientOptions)
                                               .Build());

                await connected.Task;

                await managedClient.StopAsync();

                Assert.AreEqual(0, (await server.GetClientStatusAsync()).Count);
            }
        }
Example #4
0
        async Task <ManagedMqttClient> CreateManagedClientAsync(
            TestEnvironment testEnvironment,
            IMqttClient underlyingClient     = null,
            TimeSpan?connectionCheckInterval = null)
        {
            await testEnvironment.StartServerAsync();

            var clientOptions = new MqttClientOptionsBuilder()
                                .WithTcpServer("localhost", testEnvironment.ServerPort);

            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithClientOptions(clientOptions)
                                 .Build();

            // Use a short connection check interval so that subscription operations are performed quickly
            // in order to verify against a previous implementation that performed subscriptions only
            // at connection check intervals
            managedOptions.ConnectionCheckInterval = connectionCheckInterval ?? TimeSpan.FromSeconds(0.1);

            var managedClient = new ManagedMqttClient(underlyingClient ?? testEnvironment.CreateClient(), new MqttNetLogger());

            var connected = GetConnectedTask(managedClient);

            await managedClient.StartAsync(managedOptions);

            await connected;

            return(managedClient);
        }
Example #5
0
        private async Task ConnectMQTT()
        {
            string clientId     = Guid.NewGuid().ToString();
            string mqttURI      = "124.107.183.2";
            string mqttUser     = "******";
            string mqttPassword = "******";
            int    mqttPort     = 1883;
            bool   mqttSecure   = false;

            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(clientId)
                                 .WithCredentials(mqttUser, mqttPassword)
                                 .WithTcpServer(mqttURI, mqttPort)
                                 .WithCleanSession();

            var options = mqttSecure
              ? messageBuilder
                          .WithTls()
                          .Build()
              : messageBuilder
                          .Build();

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

            mqttClient = (ManagedMqttClient) new MqttFactory().CreateManagedMqttClient();
            await mqttClient.StartAsync(managedOptions);
        }
Example #6
0
        public async Task Storage_Queue_Drains()
        {
            using (var testEnvironment = new TestEnvironment())
            {
                testEnvironment.IgnoreClientLogErrors = true;
                testEnvironment.IgnoreServerLogErrors = true;

                var factory = new MqttFactory();

                var server = await testEnvironment.StartServerAsync();

                var managedClient = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetLogger().CreateChildLogger());
                var clientOptions = new MqttClientOptionsBuilder()
                                    .WithTcpServer("localhost", testEnvironment.ServerPort);
                var storage = new ManagedMqttClientTestStorage();

                TaskCompletionSource <bool> connected = new TaskCompletionSource <bool>();
                managedClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
                {
                    managedClient.ConnectedHandler = null;
                    connected.SetResult(true);
                });

                await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
                                               .WithClientOptions(clientOptions)
                                               .WithStorage(storage)
                                               .WithAutoReconnectDelay(System.TimeSpan.FromSeconds(5))
                                               .Build());

                await connected.Task;

                await testEnvironment.Server.StopAsync();

                await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "1" });

                //Message should have been added to the storage queue in PublishAsync,
                //and we are awaiting PublishAsync, so the message should already be
                //in storage at this point (i.e. no waiting).
                Assert.AreEqual(1, storage.GetMessageCount());

                connected = new TaskCompletionSource <bool>();
                managedClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
                {
                    managedClient.ConnectedHandler = null;
                    connected.SetResult(true);
                });

                await testEnvironment.Server.StartAsync(new MqttServerOptionsBuilder()
                                                        .WithDefaultEndpointPort(testEnvironment.ServerPort).Build());

                await connected.Task;

                //Wait 500ms here so the client has time to publish the queued message
                await Task.Delay(500);

                Assert.AreEqual(0, storage.GetMessageCount());

                await managedClient.StopAsync();
            }
        }
Example #7
0
 public ManagedMqttContext(IManagedMqttContextOptions options)
 {
     Factory           = new MqttFactory();
     Logger            = Factory.DefaultLogger;
     Serializers       = options.MessageSerializers.ToImmutableSortedDictionary(serializer => serializer.ContentType, serializer => serializer);
     ManagedMqttClient = Factory.CreateManagedMqttClient();
     ManagedMqttClient.StartAsync(options.ManagedMqttClientOptions).ConfigureAwait(false).GetAwaiter().GetResult();
 }
Example #8
0
        public async Task Storage_Queue_Drains()
        {
            using (var testEnvironment = CreateTestEnvironment())
            {
                testEnvironment.IgnoreClientLogErrors = true;
                testEnvironment.IgnoreServerLogErrors = true;

                await testEnvironment.StartServer();

                var managedClient = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetEventLogger());
                var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("localhost", testEnvironment.ServerPort);
                var storage       = new ManagedMqttClientTestStorage();

                var connected = GetConnectedTask(managedClient);

                await managedClient.StartAsync(
                    new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).WithStorage(storage).WithAutoReconnectDelay(TimeSpan.FromSeconds(5)).Build());

                await connected;

                await testEnvironment.Server.StopAsync();

                await managedClient.EnqueueAsync("1");

                //Message should have been added to the storage queue in PublishAsync,
                //and we are awaiting PublishAsync, so the message should already be
                //in storage at this point (i.e. no waiting).
                Assert.AreEqual(1, storage.GetMessageCount());

                connected = GetConnectedTask(managedClient);

                await testEnvironment.Server.StartAsync();

                await connected;

                //Wait 500ms here so the client has time to publish the queued message
                await Task.Delay(500);

                Assert.AreEqual(0, storage.GetMessageCount());

                await managedClient.StopAsync();
            }
        }
Example #9
0
        public async Task ManagedClients_Will_Message_Send()
        {
            using (var testEnvironment = CreateTestEnvironment())
            {
                await testEnvironment.StartServer();

                var receivedMessagesCount = 0;

                var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
                                    .WithWillTopic("My/last/will")
                                    .WithWillQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
                                    .Build();

                var dyingClient        = testEnvironment.CreateClient();
                var dyingManagedClient = new ManagedMqttClient(dyingClient, testEnvironment.ClientLogger);

                await dyingManagedClient.StartAsync(new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).Build());

                // Wait until the managed client is fully set up and running.
                await Task.Delay(1000);

                var receivingClient = await testEnvironment.ConnectClient();

                receivingClient.ApplicationMessageReceivedAsync += e =>
                {
                    Interlocked.Increment(ref receivedMessagesCount);
                    return(PlatformAbstractionLayer.CompletedTask);
                };

                await receivingClient.SubscribeAsync("My/last/will");

                // Disposing the client will not sent a DISCONNECT packet so that connection is terminated
                // which will lead to the will publish.
                dyingManagedClient.Dispose();

                // Wait for arrival of the will message at the receiver.
                await Task.Delay(5000);

                Assert.AreEqual(1, receivedMessagesCount);
            }
        }
Example #10
0
 public static async Task <bool> ConnectMQTT()
 {
     if (mqttClient != null)
     {
         await mqttClient.StopAsync();
     }
     Debug.Write("Connecting to MQTT...");
     mqttClient = (ManagedMqttClient) new MqttFactory().CreateManagedMqttClient();
     try
     {
         var options = new MqttClientOptionsBuilder()
                       .WithClientId(Preferences.Get("deviceName", ""))                                               //client name
                       .WithTcpServer(Preferences.Get("brokerIp", ""))                                                //mqtt server
                       .WithCredentials(Preferences.Get("brokerUsername", ""), Preferences.Get("brokerPassword", "")) //username, password
                       .Build();
         var managedOptions = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(options)
                              .Build();
         await mqttClient.StartAsync(managedOptions);
     }
     catch (Exception e)
     {
         Debug.WriteLine("error while connecting: " + e.Message);
     };
     //            if (!mqttClient.IsConnected)
     //            {
     //#if !DEBUG
     //                if (await App.Current.MainPage.DisplayAlert("MQTT connection failed", "do you want to enter settings?", "yes", "no"))
     //                    await App.Current.MainPage.Navigation.PushAsync(new SettingsPassword( new SettingsPage()), true);
     //#endif
     //                Debug.WriteLine("connecting failed");
     //                return false;
     //            }
     //Debug.WriteLine("connected");
     return(true);
 }
Example #11
0
        public async Task Subscriptions_Are_Cleared_At_Logout()
        {
            using (var testEnvironment = new TestEnvironment(TestContext))
            {
                await testEnvironment.StartServerAsync().ConfigureAwait(false);

                var sendingClient = await testEnvironment.ConnectClientAsync().ConfigureAwait(false);

                await sendingClient.PublishAsync(new MqttApplicationMessage
                {
                    Topic   = "topic",
                    Payload = new byte[] { 1 },
                    Retain  = true
                });

                // Wait a bit for the retained message to be available
                await Task.Delay(500);

                await sendingClient.DisconnectAsync();

                // Now use the managed client and check if subscriptions get cleared properly.

                var clientOptions = new MqttClientOptionsBuilder()
                                    .WithTcpServer("localhost", testEnvironment.ServerPort);

                var receivedManagedMessages = new List <MqttApplicationMessage>();
                var managedClient           = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetLogger());
                managedClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(c =>
                {
                    receivedManagedMessages.Add(c.ApplicationMessage);
                });

                await managedClient.SubscribeAsync("topic");

                await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
                                               .WithClientOptions(clientOptions)
                                               .WithAutoReconnectDelay(TimeSpan.FromSeconds(1))
                                               .Build());

                await Task.Delay(500);

                Assert.AreEqual(1, receivedManagedMessages.Count);

                await managedClient.StopAsync();

                await Task.Delay(500);

                await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
                                               .WithClientOptions(clientOptions)
                                               .WithAutoReconnectDelay(TimeSpan.FromSeconds(1))
                                               .Build());

                await Task.Delay(1000);

                // After reconnect and then some delay, the retained message must not be received,
                // showing that the subscriptions were cleared
                Assert.AreEqual(1, receivedManagedMessages.Count);

                // Make sure that it gets received after subscribing again.
                await managedClient.SubscribeAsync("topic");

                await Task.Delay(500);

                Assert.AreEqual(2, receivedManagedMessages.Count);
            }
        }
Example #12
0
        private void _connect()
        {
            try
            {
                if (_mqttClient != null && _mqttClient.IsConnected)
                {
                    return;
                }

                if (Options == null)
                {
                    return;
                }

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

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

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

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

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

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

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

                _mqttClient.StartAsync(mob);
            }
            catch (Exception ex)
            {
                //_logger.Error( ex.ToString() );
            }
        }
Example #13
0
        public static void Main(string[] args)
        {
            // Read settings from env
            //Read settings:
            string MQTTServerAddress = Environment.GetEnvironmentVariable("MQTTServerAddress");

            if (MQTTServerAddress == null || MQTTServerAddress == "")
            {
                System.Console.WriteLine("ERROR:Missing MQTTServerAddress env variable. Process Exit.");
            }
            else
            {
                settings.MQTTServerAddress = MQTTServerAddress;
            }

            string GOST = Environment.GetEnvironmentVariable("GOST");

            if (GOST == null || GOST == "")
            {
                System.Console.WriteLine("ERROR:Missing GOST env variable. Process Exit.");
            }
            else
            {
                settings.GOST = GOST;
            }

            string DatabasePath = Environment.GetEnvironmentVariable("DatabasePath");

            if (DatabasePath == null || DatabasePath == "")
            {
                System.Console.WriteLine("ERROR:Missing DatabasePath env variable. Process Exit.");
            }
            else
            {
                settings.DatabasePath = DatabasePath;
            }

            string SettingsFile = Environment.GetEnvironmentVariable("SettingsFile");

            if (SettingsFile == null || SettingsFile == "")
            {
                System.Console.WriteLine("ERROR:Missing SettingsFile env variable. Process Exit.");
            }
            else
            {
                settings.SettingsFile = SettingsFile;
            }



            List <DatastreamControl> dsc    = new List <DatastreamControl>();
            ManagedMqttClient        mlSend = (ManagedMqttClient) new MqttFactory().CreateManagedMqttClient();
            // Setup and start a managed MQTT client.
            var optionsSend = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithClientId(System.Guid.NewGuid().ToString())
                                                 .WithKeepAlivePeriod(TimeSpan.FromSeconds(120))
                                                 .WithCommunicationTimeout(TimeSpan.FromSeconds(60))
                                                 .WithTcpServer(settings.MQTTServerAddress)
                                                 .Build())
                              .Build();

            mlSend.StartAsync(optionsSend).Wait();

            using (StreamReader r = new StreamReader(settings.SettingsFile))
            {
                string  json        = r.ReadToEnd();
                dynamic simulations = JsonConvert.DeserializeObject(json);
                foreach (var item in simulations.simulation)
                {
                    string datastreamID = "99999999999";
                    OGCServiceCatalogue.ManageDataStreams mds = new OGCServiceCatalogue.ManageDataStreams();
                    if (mds.FindOrCreateOGCDatastream(item.thing, item.sensor, item.observedProperties, item.datastream, ref datastreamID))
                    {
                        DatastreamControl sim = new DatastreamControl();
                        sim.Start(datastreamID, settings.DatabasePath + item.simulationFile, mlSend);
                        dsc.Add(sim);
                    }
                    Console.WriteLine("{0} {1}", item.temp, item.vcc);
                }
            }


            CreateWebHostBuilder(args).Build().Run();

            System.Console.ReadLine();

            foreach (DatastreamControl sim in dsc)
            {
                sim.stopped = true;
            }
        }