示例#1
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);
            }
        }
示例#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);
            }
        }
示例#3
0
        private void _disconnect()
        {
            try
            {
                if (_mqttClient != null && _mqttClient.IsConnected == false)
                {
                    return;
                }

                DisconnectMessage disconnectMsg = new DisconnectMessage();
                disconnectMsg.ScadaList = new Dictionary <string, DisconnectMessage.DObject>();
                DisconnectMessage.DObject scada = new DisconnectMessage.DObject();
                disconnectMsg.ScadaList.Add(_options.ScadaId, scada);
                string payload = JsonConvert.SerializeObject(disconnectMsg);

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic((_options.Type == EdgeType.Gateway) ? _scadaConnTopic : _deviceConnTopic)
                              .WithPayload(payload)
                              .WithAtLeastOnceQoS()
                              .WithRetainFlag(true)
                              .Build();

                _mqttClient.PublishAsync(message).ContinueWith(t => _mqttClient.StopAsync());
            }
            catch (Exception ex)
            {
                //_logger.Error( ex.ToString() );
            }
        }
示例#4
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();
            }
        }
示例#5
0
        private void _disconnect()
        {
            try
            {
                if (_mqttClient != null && _mqttClient.IsConnected == false)
                {
                    return;
                }

                DisconnectMessage disconnectMsg = new DisconnectMessage();
                string            payload       = JsonConvert.SerializeObject(disconnectMsg);

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(_scadaConnTopic)
                              .WithPayload(payload)
                              .WithAtLeastOnceQoS()
                              .WithRetainFlag(true)
                              .Build();

                _mqttClient.PublishAsync(message).ContinueWith(t => _mqttClient.StopAsync());
            }
            catch (Exception ex)
            {
                //_logger.Error( ex.ToString() );
            }
        }
示例#6
0
        protected override IEnumerable <Prompt> Execute_Subclass()
        {
            if (Signals == null || !Signals.Any())
            {
                GetSignalNullReason();
                return(Prompts);
            }

            try
            {
                StartMqttClient().Wait();
            }
            catch (Exception ex)
            {
                Logger.LogError(LogCategory.Processor, this.Name, $"Starting MQTT Client failed");
                Prompts.Add(ex.ToPrompt());
                return(Prompts);
            }

            _tempSignals = Signals.ToList();
            // Read existing subscriptions
            if (!ReadExistingSubscriptions(_tempSignals).Result)
            {
                Prompts.Add(new Prompt {
                    Message = $"Did not successfully read all existing subscriptions."
                });
            }

            // Subscribe and read new subscriptions
            if (!SubscribeAndReadNew(_tempSignals).Result)
            {
                Prompts.Add(new Prompt {
                    Message = $"Did not successfully read all new subscriptions."
                });
            }

            Logger.LogTrace(LogCategory.Processor, this.Name, "Waiting for all messages be be published...");
            while (ManagedMqttClient.PendingApplicationMessagesCount > 0)
            {
                Logger.LogTrace(LogCategory.Processor, this.Name, $"{ManagedMqttClient.PendingApplicationMessagesCount} messages left waiting to be published..");
                if (this.IsCancellationRequested)
                {
                    return(new List <Prompt>());
                }
                Task.Delay(1000).Wait();
            }

            Logger.LogTrace(LogCategory.Processor, this.Name, "Stopping Managed MQTT Client..");
            ManagedMqttClient.StopAsync().Wait();
            while (ManagedMqttClient.IsStarted)
            {
                Logger.LogTrace(LogCategory.Processor, this.Name, "Still waiting for MQTT Client to Stop...");
                Task.Delay(1000).Wait();
            }

            // Update the cache with new values..
            Signals = _tempSignals;
            return(Prompts);
        }
 protected override void CleanupBeforeCancellation()
 {
     try
     {
         ManagedMqttClient.StopAsync().Wait();
         ManagedMqttClient.StopAsync().Dispose();
     }
     catch (Exception ex)
     {
         Logger.LogError(LogCategory.Processor, this.Name, "Managed MQTT Client failed to stop..");
     }
 }
示例#8
0
        protected override IEnumerable <Prompt> Execute_Subclass()
        {
            StartMqttClient().Wait();

            for (;;)
            {
                if (IsCancellationRequested)
                {
                    ManagedMqttClient.StopAsync().Wait();
                    return(Prompts);
                }
                Task.Delay(5000).Wait();
            }
        }
示例#9
0
        protected override IEnumerable <Prompt> Execute_Subclass()
        {
            try
            {
                StartMqttClient().Wait();
            }
            catch (Exception ex)
            {
                Logger.LogError(LogCategory.Processor, this.Name, $"Starting MQTT Client failed");
                Prompts.Add(ex.ToPrompt());
                return(Prompts);
            }

            if (Signals == null)
            {
                Prompts.Add(new Prompt
                {
                    Message  = "There are no signals in the cache, please run the SetupProcessor or verify that it has run successfully.",
                    Severity = PromptSeverity.MayNotContinue
                });
                return(Prompts);
            }

            // Read existing subscriptions
            if (!ReadExistingSubscriptions(Signals).Result)
            {
                Prompts.Add(new Prompt {
                    Message = $"Did not successfully read all existing subscriptions."
                });
            }

            // Subscribe and read new subscriptions
            if (!SubscribeAndReadNew(Signals).Result)
            {
                Prompts.Add(new Prompt {
                    Message = $"Did not successfully read all new subscriptions."
                });
            }

            ManagedMqttClient.StopAsync().Wait();
            ManagedMqttClient.Dispose();

            // Update the cache with new values..
            Signals = Signals;
            return(Prompts);
        }
示例#10
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();
            }
        }
示例#11
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);
 }
示例#12
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);
            }
        }
示例#13
0
 private async Task Disconnect()
 {
     await mqttClient.StopAsync();
 }