Esempio n. 1
0
        private IMqttClient CreateMqttClient(MqttAddress addr)
        {
            var ClientOptions = new MqttClientOptions
            {
                ClientId       = addr.ClientId,
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = addr.BindAddress,
                    Port   = addr.Port,
                }
            };

            var mqttClient = new MqttFactory().CreateMqttClient();

            mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e =>
            {
                //Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                await Task.Delay(TimeSpan.FromSeconds(1));

                try
                {
                    await mqttClient.ReconnectAsync();
                    logger.Trace("RECONNECTED BROKER");
                }
                catch
                {
                    logger.Trace("### RECONNECTING FAILED ###");
                }
            });
            bool IsSuccess = false;

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    mqttClient.ConnectAsync(ClientOptions);
                    IsSuccess = true;
                    break;
                }
                catch (Exception ex)
                {
                    logger.Error(ex, $"#### MQTT BROKER CONNECTING FAILED ### \n{addr.ToJson()}");
                    Thread.Sleep(TimeSpan.FromSeconds(30));
                    continue;
                }
            }

            if (IsSuccess == false)
            {
                logger.Error("#### 브로커 접속에 실패했습니다. 다시 실행해주세요. ####");
                return(null);
            }
            return(mqttClient);
        }