Exemplo n.º 1
0
 private async void OnStopped()
 {
     foreach (var plugin in _plugins)
     {
         plugin.QuitAction();
     }
     await _mqttClient.DisconnectAsync();
 }
        public void Cleanup()
        {
            _mqttClient.DisconnectAsync().GetAwaiter().GetResult();
            _mqttClient.Dispose();

            _host.StopAsync().GetAwaiter().GetResult();
            _host.Dispose();
        }
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            // o app ser encerrado

            if (cancellationToken.IsCancellationRequested)
            {
                var disconnectOption = new MqttClientDisconnectOptions
                {
                    ReasonCode   = MqttClientDisconnectReason.NormalDisconnection,
                    ReasonString = "NormalDiconnection"
                };
                await mqttClient.DisconnectAsync(disconnectOption, cancellationToken);
            }
            await mqttClient.DisconnectAsync();

            _logger.LogInformation("Encerrando...");
        }
Exemplo n.º 4
0
 public void Disconnect()
 {
     if (!_mqttClient.IsConnected)
     {
         return;
     }
     _mqttClient.DisconnectAsync().Wait();
 }
Exemplo n.º 5
0
        /// <summary>
        /// Connect to MQTT Broker
        /// </summary>
        /// <returns></returns>
        public async Task Connect()
        {
            try
            {
                // 1. Get Device Credentials from flash disk
                var mqttCredential = await GetCredentials();

                //   1.1. Call Api to get MQTT credentials if no credentials found
                if (mqttCredential == null)
                {
                    var device = new DeviceModel
                    {
                        macAddress = MacAddress,
                        uuid       = UUID,
                    };

                    mqttCredential = await PutCredentials(device);

                    if (mqttCredential == null)
                    {
                        throw new Exception("Can not get MQTT credential");
                        //Debug.WriteLine("Can not get MQTT credential");
                    }
                    //   1.2. Store credential to flash disk
                    await SetCredentials(mqttCredential);
                }

                if (mqttClient == null)
                {
                    mqttClient = new MqttFactory().CreateMqttClient();
                }

                // clear the old connection
                try
                {
                    await mqttClient.DisconnectAsync();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("error", ex);
                }

                // 2. Connect to MQTT broker
                var options = new MqttClientOptionsBuilder()
                              .WithTcpServer(mqttCredential.Endpoint, mqttCredential.Port)
                              .WithClientId(mqttCredential.ClientId)
                              .WithCredentials(mqttCredential.Username, mqttCredential.Password)
                              //.WithKeepAlivePeriod(System.TimeSpan.FromSeconds(20))
                              //.WithCommunicationTimeout(System.TimeSpan.FromSeconds(60))
                              .WithCleanSession(false)
                              .Build();
                await mqttClient.ConnectAsync(options, CancellationToken.None);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Connect mqtt ", ex);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Остановка задачи
        /// </summary>
        public async void Stop()
        {
            if (_client.IsConnected)
            {
                await _client.DisconnectAsync();

                Log.Debug(MQTT_TAG, "Disconnected");
            }
        }
Exemplo n.º 7
0
        private async static void SendCommandToDevice(string ipAddress, string port, string topic, string command)
        {
            if (client != null && client.IsConnected)
            {
                await client.DisconnectAsync();
            }
            configuration = new MqttConfiguration {
                Port = Convert.ToInt32(port)
            };
            client = await MqttClient.CreateAsync(ipAddress, configuration);

            var sessionState = await client.ConnectAsync(new MqttClientCredentials(clientId : "mrpclient"));

            await client.SubscribeAsync(topic + "_client", MqttQualityOfService.AtLeastOnce);

            client.MessageStream.Subscribe(msg => OnMessageReceived(msg.Topic, System.Text.Encoding.UTF8.GetString(msg.Payload)));
            await client.PublishAsync(new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(command)), MqttQualityOfService.AtLeastOnce);
        }
Exemplo n.º 8
0
 /// <summary>
 /// Disconnect from the Broker
 /// </summary>
 public void Disconnect()
 {
     if (!_mqttClient.IsConnected)
     {
         return;
     }
     _mqttClient.DisconnectAsync();
     IsActive = false;
 }
Exemplo n.º 9
0
 public async Task StopAsync()
 {
     if (!_client.IsConnected)
     {
         return;
     }
     Message?.Invoke("[MQTT server] disconnect");
     await _client.DisconnectAsync();
 }
Exemplo n.º 10
0
        public static Task DisconnectAsync(this IMqttClient client, MqttClientDisconnectOptions options)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(client.DisconnectAsync(options, CancellationToken.None));
        }
Exemplo n.º 11
0
 private async void Disconnect_Click(object sender, EventArgs e)
 {
     if (mqttClient == null)
     {
         return;
     }
     status.Text = "Disconnecting...";
     await mqttClient.DisconnectAsync();
 }
        public async Task when_connecting_client_with_clean_session_false_then_session_is_preserved()
        {
            using (IMqttClient client = await GetClientAsync())
            {
                string clientId = MqttTestHelper.GetClientId();

                SessionState sessionState1 = await client.ConnectAsync(new MqttClientCredentials( clientId ), cleanSession : false);

                await client.DisconnectAsync();

                SessionState sessionState2 = await client.ConnectAsync(new MqttClientCredentials( clientId ), cleanSession : false);

                await client.DisconnectAsync();

                sessionState1.Should().Be(SessionState.CleanSession);
                sessionState2.Should().Be(SessionState.SessionPresent);
            }
        }
Exemplo n.º 13
0
        public Object publishMQTT(MqttCon mqtt)
        {
            // Inicializar respuesta
            string result = string.Empty;

            // Generar un client_id aleatorio para evitar conflictos en mqtt
            var client_id = Guid.NewGuid().ToString();


            // Debug
            Console.WriteLine(mqtt.topic);
            Console.WriteLine(mqtt.msg);

            var clientSettinigs    = AppSettingsProvider.ClientSettings;
            var brokerHostSettings = AppSettingsProvider.BrokerHostSettings;

            // Parametros para la configuracion del cliente MQTT.
            var options = new MqttClientOptionsBuilder()
                          .WithCredentials(clientSettinigs.UserName, clientSettinigs.Password)
                          .WithClientId(client_id)
                          .WithTcpServer(brokerHostSettings.Host, brokerHostSettings.Port)
                          .WithCleanSession()
                          .Build();

            // Consruye el mensaje MQTT
            var msg = new MqttApplicationMessageBuilder()
                      .WithTopic(mqtt.topic)
                      .WithPayload(mqtt.msg)
                      .WithExactlyOnceQoS()
                      .WithRetainFlag()
                      .Build();

            // Console.WriteLine(msg.ConvertPayloadToString());

            // Envia mensaje MQTT

            try
            {
                // Establece conexion con el Broker
                mqttClient.ConnectAsync(options).Wait();
                // Envia el mensaje
                mqttClient.PublishAsync(msg).Wait();
                //Desconecta el cliente
                mqttClient.DisconnectAsync().Wait();
            }
            catch (Exception e)
            {
                System.Console.WriteLine("Error enviando por MQTT : " + e.Message + e.StackTrace);
            }


            // Cierra la conexion
            //

            // Retorna Json indicando que fue exitoso
            return(Json(new { success = true }));
        }
Exemplo n.º 14
0
        public static Task DisconnectAsync(this IMqttClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(client.DisconnectAsync(new MqttClientDisconnectOptions()));
        }
Exemplo n.º 15
0
        public async void Terminate()
        {
            if (_client.IsConnected)
            {
                await _client.DisconnectAsync();

                _client = null;
            }
        }
Exemplo n.º 16
0
 public void Dispose()
 {
     CancellationTokenSource.Cancel();
     if (client.IsConnected)
     {
         client.DisconnectAsync();
         client.Dispose();
     }
 }
    public async void OnClickReConectMqtt()
    {
        //
        MqttURL = mqttUrlText.text;
        //responseTextMqtt.text = "接続中";
        await mqttClient.DisconnectAsync();

        ConnectMqtt();
    }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Starting Subsriber....");

                //create subscriber client
                var factory = new MqttFactory();
                _client = factory.CreateMqttClient();

                //configure options
                _options = new MqttClientOptionsBuilder()
                           .WithClientId("SubscriberId")
                           .WithTcpServer("127.0.0.1", 1884)
                           .WithCredentials("sanjay", "%Welcome@123%")
                           .WithCleanSession()
                           .Build();

                //Handlers
                _client.UseConnectedHandler(e =>
                {
                    Console.WriteLine("Connected successfully with MQTT Brokers.");

                    //Subscribe to topic
                    _client.SubscribeAsync(new TopicFilterBuilder().WithTopic("/ABB/Factory/Office").Build()).Wait();
                    _client.SubscribeAsync(new TopicFilterBuilder().WithTopic("mqttdotnet/pubtest").Build()).Wait();
                });
                _client.UseDisconnectedHandler(e =>
                {
                    Console.WriteLine("Disconnected from MQTT Brokers.");
                });
                _client.UseApplicationMessageReceivedHandler(e =>
                {
                    Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                    Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                    Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                    Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                    Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                    Console.WriteLine();
                    //Task.Run(() => _client.PublishAsync("hello/world"));
                });

                //actually connect
                _client.ConnectAsync(_options).Wait();

                Console.WriteLine("Press key to exit");
                Console.ReadLine();

                Task.Run(() => Thread.Sleep(Timeout.Infinite)).Wait();
                _client.DisconnectAsync().Wait();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemplo n.º 19
0
        private void Disconnect()
        {
#if HAVE_SYNC
            if (IsSync)
                Client.Disconnect();
            else
#endif
                Client.DisconnectAsync().Wait();
        }
Exemplo n.º 20
0
        private async Task DisconnectAsync()
        {
            if (!Connected)
            {
                return;
            }

            await _mqttClient.DisconnectAsync();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
#if DEBUG
            // Write all trace messages to the console window.
            MqttNetGlobalLogger.LogMessagePublished -= OnShowMsg;
#endif

            if (_client != null)
            {
                _tcpServer = null;
                _client.DisconnectedHandler = null;
                _client.ApplicationMessageReceivedHandler = null;
                if (_client.IsConnected)
                {
                    _client.DisconnectAsync().Wait();
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Disconnect from the MQTT broker.
        /// </summary>
        /// <param name="entities"></param>
        public async Task Disconnect()
        {
            // Do not attempt to reconnect when we disconnect
            AttemptReconnectOnDisconnect = false;

            if (MqttClient.IsConnected)
            {
                await MqttClient.DisconnectAsync();
            }
        }
        public async Task CloseAsync()
        {
            await client.UnsubscribeAsync(GetTopicFilters().Select(tp => tp.Topic));

            await client.UnsubscribeAsync(nameof(Format));

            await client.UnsubscribeAsync(nameof(AudioData));

            await client.DisconnectAsync();
        }
Exemplo n.º 24
0
 /// <summary>
 /// Will cleanup MQTT client
 /// </summary>
 public void Cleanup()
 {
     Console.WriteLine("MQTTSensor cleaning up");
     client.UnsubscribeAsync(Topic);
     client.DisconnectAsync();
     client.Connected    -= Client_Connected;
     client.Disconnected -= Client_Disconnected;
     client.ApplicationMessageReceived -= Client_ApplicationMessageReceived;
     client = null;
 }
Exemplo n.º 25
0
        private async Task MaintainConnectionAsync(CancellationToken cancellationToken)
        {
            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    var connectionState = await ReconnectIfRequiredAsync().ConfigureAwait(false);

                    if (connectionState == ReconnectionResult.NotConnected)
                    {
                        _publishingCancellationToken?.Cancel(false);
                        _publishingCancellationToken = null;

                        await Task.Delay(_options.AutoReconnectDelay, cancellationToken).ConfigureAwait(false);

                        continue;
                    }

                    if (connectionState == ReconnectionResult.Reconnected || _subscriptionsNotPushed)
                    {
                        await PushSubscriptionsAsync();

                        _publishingCancellationToken = new CancellationTokenSource();

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                        Task.Factory.StartNew(() => PublishQueuedMessagesAsync(_publishingCancellationToken.Token), _publishingCancellationToken.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                        continue;
                    }

                    if (connectionState == ReconnectionResult.StillConnected)
                    {
                        await Task.Delay(100, _connectionCancellationToken.Token).ConfigureAwait(false); // Consider using the _Disconnected_ event here. (TaskCompletionSource)
                    }
                }
            }
            catch (OperationCanceledException)
            {
            }
            catch (MqttCommunicationException exception)
            {
                _logger.LogWarning(new EventId(), exception, "Communication exception while maintaining connection.");
            }
            catch (Exception exception)
            {
                _logger.LogError(new EventId(), exception, "Unhandled exception while maintaining connection.");
            }
            finally
            {
                await _mqttClient.DisconnectAsync().ConfigureAwait(false);

                _logger.LogInformation("Stopped");
            }
        }
        public async Task when_publish_with_client_with_session_clared_then_subscriptions_are_not_re_used(int count)
        {
            CleanSession = true;

            string topic = "topic/foo/bar";

            using (IMqttClient publisher = await GetClientAsync())
                using (IMqttClient subscriber = await GetClientAsync())
                {
                    string subscriberId = subscriber.Id;

                    ManualResetEventSlim subscriberDone = new ManualResetEventSlim();
                    int subscriberReceived = 0;

                    await subscriber
                    .SubscribeAsync(topic, MqttQualityOfService.AtMostOnce);

                    subscriber
                    .MessageStream
                    .Where(m => m.Topic == topic)
                    .Subscribe(m =>
                    {
                        Interlocked.Increment(ref subscriberReceived);

                        if (subscriberReceived == count)
                        {
                            subscriberDone.Set();
                        }
                    });

                    await subscriber.DisconnectAsync();

                    SessionState sessionState = await subscriber.ConnectAsync(new MqttClientCredentials( subscriberId ), cleanSession : true);

                    List <Task> tasks = new List <Task>();

                    for (int i = 1; i <= count; i++)
                    {
                        TestMessage            testMessage = GetTestMessage(i);
                        MqttApplicationMessage message     = new MqttApplicationMessage(topic, Serializer.Serialize(testMessage));

                        tasks.Add(publisher.PublishAsync(message, MqttQualityOfService.AtMostOnce));
                    }

                    await Task.WhenAll(tasks);

                    bool completed = subscriberDone.Wait(TimeSpan.FromSeconds(Configuration.WaitTimeoutSecs));

                    Assert.False(completed);
                    SessionState.CleanSession.Should().Be(sessionState);
                    0.Should().Be(subscriberReceived);

                    await subscriber.UnsubscribeAsync(topic);
                }
        }
Exemplo n.º 27
0
        private async Task MaintainConnectionAsync(CancellationToken cancellationToken)
        {
            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    var connectionState = await ReconnectIfRequiredAsync().ConfigureAwait(false);

                    if (connectionState == ReconnectionResult.NotConnected)
                    {
                        _publishingCancellationToken?.Cancel(false);
                        _publishingCancellationToken = null;

                        await Task.Delay(_options.AutoReconnectDelay, cancellationToken).ConfigureAwait(false);

                        continue;
                    }

                    if (connectionState == ReconnectionResult.Reconnected || _subscriptionsNotPushed)
                    {
                        await PushSubscriptionsAsync();

                        _publishingCancellationToken = new CancellationTokenSource();

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                        Task.Run(async() => await PublishQueuedMessagesAsync(_publishingCancellationToken.Token), _publishingCancellationToken.Token).ConfigureAwait(false);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                        continue;
                    }

                    if (connectionState == ReconnectionResult.StillConnected)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(1), _connectionCancellationToken.Token).ConfigureAwait(false);
                    }
                }
            }
            catch (OperationCanceledException)
            {
            }
            catch (MqttCommunicationException exception)
            {
                _logger.Warning <ManagedMqttClient>(exception, "Communication exception while maintaining connection.");
            }
            catch (Exception exception)
            {
                _logger.Error <ManagedMqttClient>(exception, "Unhandled exception while maintaining connection.");
            }
            finally
            {
                await _mqttClient.DisconnectAsync().ConfigureAwait(false);

                _logger.Info <ManagedMqttClient>("Stopped");
            }
        }
Exemplo n.º 28
0
        public void SetText(string text)
        {
            try
            {
                // InvokeRequired required compares the thread ID of the
                // calling thread to the thread ID of the creating thread.
                // If these threads are different, it returns true.
                if (this.rtxtLoginMessage.InvokeRequired)
                {
                    //SetTextCallback d = new SetTextCallback(SetText);
                    //this.Invoke(d, new object[] {  text });
                    this.rtxtLoginMessage.Invoke((Action)(() => SetText(text)));
                }
                else
                {
                    if (this.rtxtLoginMessage.Lines.Count() > 300)
                    {
                        this.rtxtLoginMessage.Text = "";
                    }

                    rtxtLoginMessage.Select(0, 0);
                    rtxtLoginMessage.SelectedText = text + Environment.NewLine;

                    string filenminfo = "ServerStatus_Info_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                    string fullpath2  = Path.Combine(TraceFilePath, filenminfo);
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(fullpath2, true))
                    {
                        file.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "-" + text);
                    }
                }
            }
            catch (Exception ex)
            {
                if (mqtc.IsConnected)
                {
                    mqtc.Disconnected -= mqtc_Disconnected;
                    mqtc.ApplicationMessageReceived -= mqtc_MsgEventHandler;
                    mqtc.Connected -= mqtc_Connected;
                    mqtc.DisconnectAsync();
                }
            }
        }
Exemplo n.º 29
0
 public void DisconnectServer(IMqttClient mqttClient)
 {
     try
     {
         mqttClient.DisconnectAsync();
     }
     catch (MqttCommunicationException ee)
     {
         throw ee;
     }
 }
Exemplo n.º 30
0
 private static async Task CloseIntern(IMqttClient client)
 {
     try {
         await client.DisconnectAsync();
     }
     catch (Exception) { }
     try {
         client.Dispose();
     }
     catch (Exception) { }
 }