/// <summary>
        /// Call this method to disconnect the client
        /// </summary>
        public async Task Disconnect()
        {
            await mqttClient.DisconnectAsync();

            ctSource.Cancel();
            ConnectionStatus = MqttClientConnectResultCode.UnspecifiedError;
        }
        /// <summary>
        /// Connects to the MQTT broker.
        /// </summary>
        public bool Connect()
        {
            try
            {
                log.WriteLine();

                // delay before connecting
                DateTime utcNow       = DateTime.UtcNow;
                TimeSpan connectDelay = ReconnectDelay - (utcNow - connAttemptDT);

                if (connectDelay > TimeSpan.Zero)
                {
                    log.WriteAction(Locale.IsRussian ?
                                    "Задержка перед соединением {0} с" :
                                    "Delay before connecting {0} sec",
                                    connectDelay.TotalSeconds.ToString("N1"));
                    Thread.Sleep(connectDelay);
                }

                // connect to MQTT broker
                log.WriteAction(Locale.IsRussian ?
                                "Соединение с {0}:{1}" :
                                "Connect to {0}:{1}",
                                connectionOptions.Server, connectionOptions.Port);

                connAttemptDT = DateTime.UtcNow;
                MqttClientConnectResultCode resultCode =
                    mqttClient.ConnectAsync(clientOptions, CancellationToken.None).Result.ResultCode;

                if (resultCode == MqttClientConnectResultCode.Success)
                {
                    log.WriteLine(Locale.IsRussian ?
                                  "Соединение установлено успешно" :
                                  "Connected successfully");
                    return(true);
                }
                else
                {
                    log.WriteLine(Locale.IsRussian ?
                                  "Не удалось установить соединение: {0}" :
                                  "Unable to connect: {0}", resultCode);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                log.WriteError(Locale.IsRussian ?
                               "Ошибка при установке соединения: {0}" :
                               "Error connecting: {0}", ex.Message);
                return(false);
            }
        }
        /// <summary>
        /// Call this method to (re)connect
        /// </summary>
        public async Task Connect(string username, string password, string brokerUrl = "mqtt.ardich.com", int serverport = 8883)
        {
            ctSource = new CancellationTokenSource();
            // Setup and start a managed MQTT client.
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(ClientId)
                          .WithTcpServer(brokerUrl, serverport)
                          .WithCredentials(username, password)
                          .WithTls()
                          .Build();

            mqttClient = new MqttFactory().CreateMqttClient();

            ConnectionStatus = (await mqttClient.ConnectAsync(options, ctSource.Token)).ResultCode;
            if (ConnectionStatus == MqttClientConnectResultCode.Success)
            {
                Listen();
            }
        }
Exemple #4
0
 public MqttConnectingFailedException(MqttClientConnectResultCode resultCode)
     : base($"Connecting with MQTT server failed ({resultCode.ToString()}).")
 {
     ResultCode = resultCode;
 }
Exemple #5
0
 bool IsTemporaryFailure(MqttClientConnectResultCode connectResultCode) => connectResultCode == MqttClientConnectResultCode.ServerUnavailable ||
 connectResultCode == MqttClientConnectResultCode.ServerBusy ||
 connectResultCode == MqttClientConnectResultCode.QuotaExceeded ||
 connectResultCode == MqttClientConnectResultCode.ConnectionRateExceeded;
Exemple #6
0
        /// <summary>
        /// Reads the topics from Wiren Board.
        /// </summary>
        private void ReadTopics()
        {
            IMqttClient mqttClient = null;

            try
            {
                MqttFactory mqttFactory = new();
                mqttClient = mqttFactory.CreateMqttClient();
                mqttClient.UseApplicationMessageReceivedHandler(MqttClient_ApplicationMessageReceived);

                logHelper.WriteMessage(string.Format(Locale.IsRussian ?
                                                     "Соединение с {0}:{1}" :
                                                     "Connect to {0}:{1}",
                                                     connOptions.Server, connOptions.Port));

                MqttClientConnectResultCode resultCode =
                    mqttClient.ConnectAsync(connOptions.ToMqttClientOptions(), tokenSource.Token)
                    .Result.ResultCode;

                if (resultCode == MqttClientConnectResultCode.Success)
                {
                    logHelper.WriteMessage(Locale.IsRussian ?
                                           "Соединение установлено успешно" :
                                           "Connected successfully");

                    logHelper.WriteMessage(string.Format(Locale.IsRussian ?
                                                         "Подписка на {0}" :
                                                         "Subscribe to {0}", MainTopic));
                    MqttClientSubscribeOptions subscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
                                                                  .WithTopicFilter(f => f.WithTopic(MainTopic)).Build();
                    mqttClient.SubscribeAsync(subscribeOptions, tokenSource.Token).Wait();

                    while (!stopReading && !tokenSource.IsCancellationRequested)
                    {
                        Thread.Sleep(ScadaUtils.ThreadDelay);

                        lock (mqttLock)
                        {
                            if (DateTime.UtcNow - messageDT > ReadTimeout)
                            {
                                stopReading = true;
                                logHelper.WriteMessage(Locale.IsRussian ?
                                                       "Таймаут чтения истёк" :
                                                       "Read timeout expired");
                            }
                        }
                    }

                    if (WirenBoardModel.Devices.Count > 0)
                    {
                        logHelper.WriteSuccess(Locale.IsRussian ?
                                               "Чтение топиков завершено успешно" :
                                               "Reading topics completed successfully");
                        ReadResult = true;
                    }
                    else
                    {
                        logHelper.WriteError(Locale.IsRussian ?
                                             "Подключенные устройства не найдены" :
                                             "Connected devices not found");
                    }
                }
                else
                {
                    logHelper.WriteError(string.Format(Locale.IsRussian ?
                                                       "Не удалось установить соединение: {0}" :
                                                       "Unable to connect: {0}", resultCode));
                }
            }
            catch (Exception ex)
            {
                logHelper.WriteError(ex.Message);
            }
            finally
            {
                Disconnect(mqttClient);
                OnCompleted();
            }
        }