Esempio n. 1
0
        public async Task Drop_New_Messages_On_Full_Queue()
        {
            var factory       = new MqttFactory();
            var managedClient = factory.CreateManagedMqttClient();

            var clientOptions = new ManagedMqttClientOptionsBuilder()
                                .WithMaxPendingMessages(5)
                                .WithPendingMessagesOverflowStrategy(MqttPendingMessagesOverflowStrategy.DropNewMessage);

            clientOptions.WithClientOptions(o => o.WithTcpServer("localhost"));

            await managedClient.StartAsync(clientOptions.Build());

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

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

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

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

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

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

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

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

            Assert.AreEqual(5, managedClient.PendingApplicationMessagesCount);
        }
Esempio n. 2
0
        public MessageSender(MessageSenderConfiguration messageSenderConfiguration)
        {
            _messageSenderConfiguration = messageSenderConfiguration;

            if (!_messageSenderConfiguration.Enabled)
            {
                return;
            }

            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(messageSenderConfiguration.ClientId)
                                 .WithTcpServer(messageSenderConfiguration.Uri, messageSenderConfiguration.PortNumber)
                                 .WithCleanSession();

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

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

            var clientFactory = new MqttFactory();

            _messageClient = clientFactory.CreateManagedMqttClient();

            _messageClient.StartAsync(managedOptions);
        }
Esempio n. 3
0
        public void Create_ManagedMqttClient()
        {
            var factory = new MqttFactory();
            var client  = factory.CreateManagedMqttClient();

            Assert.IsNotNull(client);
        }
Esempio n. 4
0
        private async void button1_Click(object sender, EventArgs e)
        {
            var factory = new MqttFactory();

            _mqttClient = factory.CreateManagedMqttClient();

            _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);

            _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);

            _mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived);

            await _mqttClient
            .SubscribeAsync(new TopicFilterBuilder()
                            .WithTopic($"devices/{IdentifierBox.Text}/config")
                            .WithAtMostOnceQoS()
                            .Build());

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithKeepAlivePeriod(TimeSpan.FromSeconds(5))
                                             .WithClientId(IdentifierBox.Text)
                                             .WithCredentials(UserName.Text, Password.Text)
                                             .WithTcpServer(IpAddressBox.Text, int.Parse(ServerPort.Text))
                                             .WithCleanSession())
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .Build();

            await _mqttClient.StartAsync(options);
        }
Esempio n. 5
0
        static async Task Main(string[] args)
        {
            var mqttFactory = new MqttFactory();

            var tlsOptions = new MqttClientTlsOptions
            {
                UseTls = false,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates        = true
            };

            var options = new MqttClientOptions
            {
                ClientId        = "Note",
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions  = new MqttClientTcpOptions
                {
                    Server     = "xx.xx.xx.xx",
                    Port       = 1883,
                    TlsOptions = tlsOptions
                }
            };

            if (options.ChannelOptions == null)
            {
                throw new InvalidOperationException();
            }

            options.Credentials = new MqttClientCredentials
            {
                Username = "******",
                Password = Encoding.UTF8.GetBytes("123456")
            };

            var topicFilter = new MqttTopicFilter {
                Topic = "esp32/dht/temperature"
            };


            options.CleanSession    = true;
            options.KeepAlivePeriod = TimeSpan.FromSeconds(5);

            managedMqttClientSubscriber = mqttFactory.CreateManagedMqttClient();
            managedMqttClientSubscriber.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);
            managedMqttClientSubscriber.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);
            managedMqttClientSubscriber.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived);

            await managedMqttClientSubscriber.SubscribeAsync(topicFilter);

            await managedMqttClientSubscriber.StartAsync(
                new ManagedMqttClientOptions
            {
                ClientOptions = options
            });

            while (true)
            {
            }
        }
Esempio n. 6
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();
 }
Esempio n. 7
0
        public (IManagedMqttClient client, ManagedMqttClientOptions options) CreateManagedClient(string clientId)
        {
            var mqttClientOpts = BuildClientOpts(clientId);
            var mqttOpts       = BuildManagedClientOpts(mqttClientOpts);
            var factory        = new MqttFactory();

            return(factory.CreateManagedMqttClient(), mqttOpts);
        }
Esempio n. 8
0
        public LuGaMqtt(
            LuGaMqttConfig config,
            IRepository <Event> eventRepository)
        {
            this.eventRepository = eventRepository;

            var factory = new MqttFactory();

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(Constants.ReconnectDelay))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId(config.ClientId)
                                             .WithTcpServer(config.Host, config.Port)
                                             .WithCredentials(config.Username, config.Password)
                                             .Build())
                          .Build();

            client = factory.CreateManagedMqttClient();

            client.ApplicationMessageReceived += (s, e) =>
            {
                if (e.ApplicationMessage.Topic.IndexOf(Constants.MessageTopic1, StringComparison.Ordinal) <= -1 ||
                    e.ApplicationMessage.Topic.IndexOf(Constants.MessageTopic2, StringComparison.Ordinal) != -1)
                {
                    return;
                }

                var pulled = e.ApplicationMessage.Topic.Split(Constants.SplitCharacter);

                var @event = new Event()
                {
                    DeviceId  = pulled[1],
                    Action    = pulled[3].Split("_").ElementAt(0),
                    Zone      = pulled[3].Split("_").ElementAt(1),
                    Value     = Encoding.UTF8.GetString(e.ApplicationMessage.Payload),
                    TimeStamp = DateTime.UtcNow
                };

                this.eventRepository.Add(@event);
            };

            client.Connected += async(s, e) =>
            {
                Debug.WriteLine(Constants.ConnectedOutput);
                await client.SubscribeAsync(
                    new TopicFilterBuilder()
                    .WithTopic(Constants.SubscribeTopic)
                    .Build()
                    );
            };

            client.Disconnected += (s, e) => {
                Debug.WriteLine(Constants.DisconnectedOutput);
            };

            Task.Run(() => Background(options));
        }
Esempio n. 9
0
        public async Task Create_Managed_Client_With_Logger()
        {
            var factory = new MqttFactory();

            // This test compares
            // 1. correct logID
            var logId           = "logId";
            var hasInvalidLogId = false;

            // 2. if the total log calls are the same for global and local
            //var globalLogCount = 0;
            var localLogCount = 0;

            var logger = new MqttNetEventLogger(logId);

            logger.LogMessagePublished += (s, e) =>
            {
                if (e.LogMessage.LogId != logId)
                {
                    hasInvalidLogId = true;
                }

                Interlocked.Increment(ref localLogCount);
            };

            var managedClient = factory.CreateManagedMqttClient(logger);

            try
            {
                var clientOptions = new ManagedMqttClientOptionsBuilder();

                clientOptions.WithClientOptions(o => o.WithTcpServer("this_is_an_invalid_host").WithTimeout(TimeSpan.FromSeconds(1)));

                // try connect to get some log entries
                await managedClient.StartAsync(clientOptions.Build());

                // wait at least connect timeout or we have some log messages
                var tcs = new TaskCompletionSource <object>();
                managedClient.ConnectingFailedAsync += e =>
                {
                    tcs.TrySetResult(null);
                    return(PlatformAbstractionLayer.CompletedTask);
                };

                await Task.WhenAny(Task.Delay(managedClient.Options.ClientOptions.Timeout), tcs.Task);
            }
            finally
            {
                await managedClient.StopAsync();
            }

            await Task.Delay(500);

            Assert.IsFalse(hasInvalidLogId);
            Assert.AreNotEqual(0, localLogCount);
        }
Esempio n. 10
0
        public LuGaMqtt(
            LuGaMqttConfig config,
            IRepository <Reading> readingRepository)
        {
            var factory = new MqttFactory();

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(Constants.ReconnectDelay))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId(config.ClientId)
                                             .WithTcpServer(config.Host, config.Port)
                                             .WithCredentials(config.Username, config.Password)
                                             .Build())
                          .Build();

            _client = factory.CreateManagedMqttClient();

            _client.ApplicationMessageReceived += (s, e) =>
            {
                if (e.ApplicationMessage.Topic.IndexOf("/value", StringComparison.Ordinal) <= -1 ||
                    e.ApplicationMessage.Topic.IndexOf("$", StringComparison.Ordinal) != -1)
                {
                    return;
                }

                var reading = new Reading();
                var pulled  = e.ApplicationMessage.Topic.Split("/");

                reading.DeviceId    = pulled[1];
                reading.ReadingType = pulled[2];
                reading.Value       = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                reading.TimeStamp   = DateTime.UtcNow;

                Console.WriteLine($"DeviceId: {reading.DeviceId}");
                Console.WriteLine($"ReadingType: {reading.ReadingType}");
                Console.WriteLine($"Value: {reading.Value}");

                readingRepository.Add(reading);
            };

            _client.Connected += async(s, e) =>
            {
                Console.WriteLine(Constants.ConnectedOutput);
                await _client.SubscribeAsync(
                    new TopicFilterBuilder()
                    .WithTopic(Constants.SubscribeTopic)
                    .Build()
                    );
            };

            _client.Disconnected += (s, e) => {
                Console.WriteLine(Constants.DisconnectedOutput);
            };

            Task.Run(() => Background(options));
        }
Esempio n. 11
0
        static void Main()
        {
            Thread subscriber = new Thread(async() =>
            {
                // Setup and start a managed MQTT client.
                var options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithClientId("Sink")
                                                 .WithTcpServer("127.0.0.1")
                                                 .Build())
                              .Build();

                var factory = new MqttFactory();

                var mqttSubscriberClient = factory.CreateManagedMqttClient(new MqttNetLogger("MyCustomID"));
                MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace =
                        $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                    if (e.TraceMessage.Exception != null)
                    {
                        trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
                    }

                    Debug.WriteLine('\x2' + trace);
                };

                mqttSubscriberClient.ApplicationMessageReceived += (s, 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();
                };

                await mqttSubscriberClient.StartAsync(options);
                Console.WriteLine("Sink client started");

                for (int i = 0; i < 10; ++i)
                {
                    var topic = $"source/property/i{i}";
                    await mqttSubscriberClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).WithExactlyOnceQoS()
                                                              .Build());
                    Console.WriteLine($"Subscribed to {topic}");
                }

                Console.WriteLine("\nSubscriptions complete.\n\n");
                Console.ReadLine();
            });

            subscriber.Start();
        }
        private async Task StartMqttClient()
        {
            var factory = new MqttFactory();

            _mqttClient = factory.CreateManagedMqttClient();
            _mqttClient.ConnectedHandler    = this;
            _mqttClient.DisconnectedHandler = this;
            _mqttClient.ApplicationMessageReceivedHandler = this;

            await _mqttClient.StartAsync(_options);
        }
Esempio n. 13
0
        private async Task <IManagedMqttClient> StartClientSubscriber(MqttFactory factory, string server, int port, string name)
        {
            var tlsOptions = new MqttClientTlsOptions
            {
                UseTls = false,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates        = true
            };

            var options = new MqttClientOptions
            {
                ClientId        = $"{name}.listener",
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions  = new MqttClientTcpOptions
                {
                    Server     = server,
                    Port       = port,
                    TlsOptions = tlsOptions
                }
            };

            if (options.ChannelOptions == null)
            {
                throw new InvalidOperationException();
            }

            options.Credentials = new MqttClientCredentials
            {
                Username = "******",
                Password = Encoding.UTF8.GetBytes("password")
            };

            options.CleanSession    = true;
            options.KeepAlivePeriod = TimeSpan.FromSeconds(5);


            IManagedMqttClient managedMqttClientSubscriber = factory.CreateManagedMqttClient();

            managedMqttClientSubscriber.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(Client_OnClientConnected);
            managedMqttClientSubscriber.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(Client_OnClientDisconnected);
            managedMqttClientSubscriber.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(Client_OnSubscriberMessageReceived);
            await managedMqttClientSubscriber.StartAsync(
                new ManagedMqttClientOptions
            {
                ClientOptions = options
            });

            return(managedMqttClientSubscriber);
        }
Esempio n. 14
0
    /// <summary>
    /// The method that handles the button click to start the subscriber.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The event args.</param>
    private async void ButtonSubscriberStartClick(object sender, EventArgs e)
    {
        var mqttFactory = new MqttFactory();

        var tlsOptions = new MqttClientTlsOptions
        {
            UseTls = false,
            IgnoreCertificateChainErrors      = true,
            IgnoreCertificateRevocationErrors = true,
            AllowUntrustedCertificates        = true
        };

        var options = new MqttClientOptions
        {
            ClientId        = "ClientSubscriber",
            ProtocolVersion = MqttProtocolVersion.V311,
            ChannelOptions  = new MqttClientTcpOptions
            {
                Server     = "localhost",
                Port       = int.Parse(this.TextBoxPort.Text.Trim()),
                TlsOptions = tlsOptions
            }
        };

        if (options.ChannelOptions == null)
        {
            throw new InvalidOperationException();
        }

        options.Credentials = new MqttClientCredentials
        {
            Username = "******",
            Password = Encoding.UTF8.GetBytes("password")
        };

        options.CleanSession    = true;
        options.KeepAlivePeriod = TimeSpan.FromSeconds(5);

        this.managedMqttClientSubscriber = mqttFactory.CreateManagedMqttClient();
        this.managedMqttClientSubscriber.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);
        this.managedMqttClientSubscriber.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);
        this.managedMqttClientSubscriber.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(this.OnSubscriberMessageReceived);

        await this.managedMqttClientSubscriber.StartAsync(
            new ManagedMqttClientOptions
        {
            ClientOptions = options
        });
    }
        /// <summary>
        /// Start the publisher thread
        /// </summary>
        private async void PublisherStart()
        {
            var mqttFactory = new MqttFactory();

            var tlsOptions = new MqttClientTlsOptions
            {
                UseTls = false,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates        = true
            };

            var options = new MqttClientOptions
            {
                ClientId        = "ClientPublisher-" + MqttClientId,
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions  = new MqttClientTcpOptions
                {
                    Server     = BrokerAddress,
                    Port       = BrokerPort,
                    TlsOptions = tlsOptions
                }
            };

            if (options.ChannelOptions == null)
            {
                throw new InvalidOperationException();
            }

            //no password required
            //options.Credentials = new MqttClientCredentials
            //{
            //    Username = "******",
            //    Password = Encoding.UTF8.GetBytes("password")
            //};

            options.CleanSession            = true;
            options.KeepAlivePeriod         = TimeSpan.FromSeconds(5);
            this.managedMqttClientPublisher = mqttFactory.CreateManagedMqttClient();
            this.managedMqttClientPublisher.UseApplicationMessageReceivedHandler(this.HandleReceivedApplicationMessage);
            this.managedMqttClientPublisher.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(OnPublisherConnected);
            this.managedMqttClientPublisher.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnPublisherDisconnected);

            await this.managedMqttClientPublisher.StartAsync(
                new ManagedMqttClientOptions
            {
                ClientOptions = options
            });
        }
Esempio n. 16
0
        public MqttQueue(string name, IConnectionSetting connectionSetting)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            this.Name = name.Trim();
            this.ConnectionSetting = connectionSetting;

            _client      = Factory.CreateManagedMqttClient();
            _subscribers = new Dictionary <string, MqttSubscriber>();

            _client.UseApplicationMessageReceivedHandler(OnHandleAsync);
        }
Esempio n. 17
0
        public Func <Task <IManagedMqttClient> > CreateManagedClient(IMqttClientOptions clientOpts)
        {
            var mqttOpts = BuildManagedClientOpts(clientOpts);

            return(async() =>
            {
                var factory = new MqttFactory();
                var client = factory.CreateManagedMqttClient();
                //await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());
                Console.WriteLine($"Starting mqtt client");
                await client.StartAsync(mqttOpts);

                return client;
            });
        }
Esempio n. 18
0
        public MQTTConnectionManager(string masterIP, int masterPort, int activeDevice)
        {
            var factory = new MqttFactory();

            client = factory.CreateManagedMqttClient();

            MasterIP     = masterIP;
            MasterPort   = masterPort;
            ActiveDevice = activeDevice;
            _recorder    = new Recorder(ActiveDevice);

            Console.WriteLine("MQTT Client Initializing");

            Setup();
        }
Esempio n. 19
0
        public async Task <bool> Open()
        {
            if (_client != null)
            {
                if (_client.IsConnected)
                {
                    return(true);
                }

                _client.Dispose();
                _client = null;
            }

            try
            {
                _tokenSource?.Cancel();
                _tokenSource = new CancellationTokenSource();

                _client = _mqttFactory.CreateManagedMqttClient();
                _client.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(ConnectedHandler);
                _client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(DisconnectedHandler);
                _client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(MessageReceived);

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

                await _client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic($"{_mqttConfig.BaseTopic}/#").Build());

                await _client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("home-assistant/#").Build());

                await _client.StartAsync(options);

                _keepAliveThread = new Thread(Keepalive);
                _keepAliveThread.Start(_tokenSource.Token);

                return(true);
            }
            catch (Exception e)
            {
                _client?.Dispose();
                _client = null;
                _logger.LogError(e, $"Failed connection to mqtt{(_mqttConfig.UseSsl ? "s" : string.Empty)}://{_mqttConfig.Server}:{_mqttConfig.Port}");
                return(false);
            }
        }
Esempio n. 20
0
        private async void MqttConnect(string ServerUrl, int ServerPort, string ClientId, string username, string password)
        {
            var mqttFactory = new MqttFactory();

            var tlsOptions = new MqttClientTlsOptions
            {
                UseTls = false,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates        = true
            };

            var options = new MqttClientOptions
            {
                ClientId        = ClientId,
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions  = new MqttClientTcpOptions
                {
                    Server     = ServerUrl,
                    Port       = ServerPort,
                    TlsOptions = tlsOptions
                }
            };

            if (string.IsNullOrWhiteSpace(username) && string.IsNullOrWhiteSpace(password))
            {
                options.Credentials = new MqttClientCredentials
                {
                    Username = username,
                    Password = Encoding.UTF8.GetBytes(password)
                };
            }


            options.CleanSession    = true;
            options.KeepAlivePeriod = TimeSpan.FromSeconds(5);
            client = mqttFactory.CreateManagedMqttClient();
            client.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage);
            client.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(OnConnected);
            client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnDisconnected);
            //client.ConnectingFailedHandler = new MqttClientConnectFailedDelegate(OnConnected);
            await client.StartAsync(
                new ManagedMqttClientOptions
            {
                ClientOptions = options
            });
        }
        /// <summary>
        /// subscribe to car coordinate messages and register a method to process them
        /// </summary>
        public void ListenForCarCoordinates()
        {
            var mqttFactory = new MqttFactory();

            var tlsOptions = new MqttClientTlsOptions
            {
                UseTls = false,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates        = true
            };

            var options = new MqttClientOptions
            {
                ClientId        = "ClientSubscriber",
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions  = new MqttClientTcpOptions
                {
                    Server     = "localhost",
                    Port       = BrokerPort,
                    TlsOptions = tlsOptions
                }
            };

            if (options.ChannelOptions == null)
            {
                throw new InvalidOperationException();
            }

            options.CleanSession    = true;
            options.KeepAlivePeriod = TimeSpan.FromSeconds(5);

            this.managedMqttClientSubscriber = mqttFactory.CreateManagedMqttClient();
            this.managedMqttClientSubscriber.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);
            this.managedMqttClientSubscriber.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);
            this.managedMqttClientSubscriber.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(this.OnSubscriberMessageReceived);

            this.managedMqttClientSubscriber.StartAsync(
                new ManagedMqttClientOptions
            {
                ClientOptions = options
            });


            this.managedMqttClientSubscriber.SubscribeAsync(new TopicFilterBuilder().WithTopic(CarCoordinatesTopic).Build());
        }
Esempio n. 22
0
        public async void Start()
        {
            MqttFactory factory = new MqttFactory();

            var options = new MqttClientOptions
            {
                ClientId        = name,
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions  = new MqttClientTcpOptions
                {
                    Server     = server,
                    Port       = port,
                    TlsOptions = tlsOptions
                }
            };

            if (options.ChannelOptions == null)
            {
                throw new InvalidOperationException();
            }

            options.Credentials = new MqttClientCredentials
            {
                Username = username,
                Password = Encoding.UTF8.GetBytes(password)
            };

            options.CleanSession    = true;
            options.KeepAlivePeriod = TimeSpan.FromSeconds(5);

            subscriber = factory.CreateManagedMqttClient();
            subscriber.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(Client_OnSubscriberConnected);
            subscriber.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(Client_OnSubscriberDisconnected);
            subscriber.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(Client_OnSubscriberMessageReceived);
            await subscriber.StartAsync(
                new ManagedMqttClientOptions
            {
                ClientOptions = options
            });

            if (subscriber is null)
            {
                throw new InvalidOperationException();
            }
        }
        public void ConfigureServices(IServiceCollection services)
        {
            var managedClient = GetManagedMqttClientOptions(GetOptions(), TimeSpan.FromSeconds(10));
            var clientFactory = new MqttFactory();
            var client        = clientFactory.CreateManagedMqttClient();


            services
            .AddHealthChecksUI()
            .AddInMemoryStorage()
            .Services
            .AddHealthChecks()
            .AddPortainer(new Uri("http://localhost:9000/"))
            .AddCheck <RandomHealthCheck>("random")
            .AddUrlGroup(new Uri("http://httpbin.org/status/200"))
            .Services
            .AddControllers();
        }
Esempio n. 24
0
        private async void MQTTConnect()
        {
            mqttFactory = new MqttFactory();
            var tlsOptions = new MqttClientTlsOptions
            {
                UseTls = false,
                IgnoreCertificateChainErrors = true,
                IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates = true
            };
            var options = new MqttClientOptions
            {
                ClientId = "ClientPublisher",
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions = new MqttClientTcpOptions
                {
                    Server = "10.1.1.83",
                    Port = 1883,
                    TlsOptions = tlsOptions
                }
            };
            if (options.ChannelOptions == null)
            {
                throw new InvalidOperationException();
            }
            options.Credentials = new MqttClientCredentials
            {
                Username = "******",
                Password = Encoding.UTF8.GetBytes("password")
            };
            options.CleanSession = true;
            options.KeepAlivePeriod = TimeSpan.FromSeconds(5);
            managedMqttClientPublisher = mqttFactory.CreateManagedMqttClient();
            managedMqttClientPublisher.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage);
            managedMqttClientPublisher.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnPublisherConnected);
            managedMqttClientPublisher.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnPublisherDisconnected);
            await managedMqttClientPublisher.StartAsync(
                new ManagedMqttClientOptions
                {
                    ClientOptions = options
                });


        }
Esempio n. 25
0
        public Publisher()
        {
            var mqttFactory = new MqttFactory();

            var tlsOptions = new MqttClientTlsOptions
            {
                UseTls = false,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates        = true,
            };

            var options = new MqttClientOptions
            {
                ClientId        = "ClientPublisher",
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions  = new MqttClientTcpOptions
                {
                    Server     = "localhost",
                    Port       = 1883,
                    TlsOptions = tlsOptions
                }
            };

            //options.Credentials = new MqttClientCredentials
            //{
            //    Username = "******",
            //    Password = Encoding.UTF8.GetBytes("password")
            //};

            options.CleanSession = true;
            //options.KeepAlivePeriod = TimeSpan.FromSeconds(5);
            managedMqttClientPublisher = mqttFactory.CreateManagedMqttClient();
            managedMqttClientPublisher.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage);
            managedMqttClientPublisher.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(OnPublisherConnected);
            managedMqttClientPublisher.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnPublisherDisconnected);

            managedMqttClientPublisher.StartAsync(
                new ManagedMqttClientOptions
            {
                ClientOptions = options
            });
        }
Esempio n. 26
0
        private void Connect()
        {
            var clientOptions = new MqttClientOptionsBuilder()
                                .WithClientId("DeconzToMqtt2")
                                .WithTcpServer(_hostname)
                                .WithWillMessage(new MqttApplicationMessageBuilder()
                                                 .WithRetainFlag(true)
                                                 .WithTopic("tele/deconztomqtt/LWT")
                                                 .WithPayload("offline")
                                                 .Build());

            if (!string.IsNullOrWhiteSpace(_username))
            {
                clientOptions.WithCredentials(_username, _password);
            }


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

            var factory = new MqttFactory(new MqttNetLogger(_logProvider));

            _client = factory.CreateManagedMqttClient();

            _client.UseDisconnectedHandler(async e =>
            {
                _logger.Warn("Disconnected from MQTT server. Try reconnect...");
            });
            _client.UseConnectedHandler(async e =>
            {
                _logger.Info("Connected to MQTT server");

                await _client.PublishAsync(new MqttApplicationMessageBuilder()
                                           .WithRetainFlag(true)
                                           .WithTopic("tele/deconztomqtt/LWT")
                                           .WithPayload("online")
                                           .Build());
            });

            _logger.Info("Connecting to MQTT server '{0}'", _hostname);
            _client.StartAsync(managedOptions.Build()).Wait(_cancelationToken.Token);
        }
Esempio n. 27
0
        public async Task <IManagedMqttClient> Subscribe(string topic, Func <string, byte[], Task> messageHandler)
        {
            if (_clients.ContainsKey(topic))
            {
                return(_clients[topic]);
            }

            // Create a new MQTT client.
            var factory    = new MqttFactory();
            var mqttClient = factory.CreateManagedMqttClient();

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId(Guid.NewGuid().ToString())
                                             .WithTcpServer(ServerConfigurationProvider.ServerAddress, ServerConfigurationProvider.Port)
                                             .Build())
                          .Build();

            mqttClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate((args =>
            {
                _logger.LogError(args.Exception.ToString());
                throw args.Exception;
            }));

            mqttClient.UseConnectedHandler(e =>
            {
                _logger.LogInformation($"Connected: {e.AuthenticateResult.ToJson()}");
            });

            mqttClient.UseApplicationMessageReceivedHandler(async e =>
            {
                await messageHandler(e.ClientId, e.ApplicationMessage.Payload).ConfigureAwait(false);
            });

            await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build());

            await mqttClient.StartAsync(options);

            _clients.TryAdd(topic, mqttClient);
            return(mqttClient);
        }
        private async Task Connect()
        {
            Disconnect();

            _logger.LogInformation("Starting MqttConnectionService...");
            await Task.Yield();

            var settings = _settings.CurrentSettings;

            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(settings.MqttServer, settings.MqttPort)
                          .WithTls(x =>
            {
                x.UseTls = settings.MqttSecure != TlsMode.False;
                x.AllowUntrustedCertificates        = settings.MqttSecure == TlsMode.Insecure;
                x.IgnoreCertificateRevocationErrors = true;
            })
                          .WithCredentials(settings.MqttUsername, settings.MqttPassword)
                          .Build();

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

            _client = _mqttFactory.CreateManagedMqttClient();

            _client.ConnectedHandler    = this;
            _client.DisconnectedHandler = this;
            _client.ApplicationMessageReceivedHandler = this;
            await _client.StartAsync(managedOptions);

            _connection.Disposable = Disposable.Create(() =>
            {
                _logger.LogInformation("Disconnection from MQTT server...");
                _client.Dispose();
            });

            _logger.LogInformation("Subscribing to MQTT topics...");
            await Subscribe();
        }
Esempio n. 29
0
        public MqttWorker(EvoHomeSettings evoHomeSettings, ILogger <MqttWorker> logger)
        {
            _settings = evoHomeSettings;
            _logger   = logger;

            if (evoHomeSettings.DisableMqtt)
            {
                _logger.LogInformation("Mqtt Disabled");
                return;
            }

            var builder = new MqttClientOptionsBuilder()
                          .WithClientId(evoHomeSettings.MqttClientName);

            if (!string.IsNullOrWhiteSpace(evoHomeSettings.MqttUser))
            {
                builder.WithCredentials(evoHomeSettings.MqttUser, evoHomeSettings.MqttPassword);
            }

            if (evoHomeSettings.MqttWebSockets)
            {
                builder.WithWebSocketServer($"{evoHomeSettings.MqttConnection}:{evoHomeSettings.MqttPort}");
            }
            else
            {
                builder.WithTcpServer(evoHomeSettings.MqttConnection, evoHomeSettings.MqttPort);
            }

            var options = builder.Build();

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

            var factory = new MqttFactory();

            _mqttClient = factory.CreateManagedMqttClient();
        }
Esempio n. 30
0
        public MqttPublisher(
            ILogger <MqttPublisher> logger,
            DeviceConfigModel deviceConfigModel,
            IConfigurationService configurationService)
        {
            this.Subscribers           = new List <AbstractCommand>();
            this._logger               = logger;
            this.DeviceConfigModel     = deviceConfigModel;
            this._configurationService = configurationService;

            var options = _configurationService.GetMqttClientOptionsAsync().Result;

            _configurationService.MqqtConfigChangedHandler = this.ReplaceMqttClient;

            var factory = new MqttFactory();

            this._mqttClient = factory.CreateManagedMqttClient();

            if (options != null)
            {
                this._mqttClient.StartAsync(options);
                this._mqttClientMessage = "Connecting...";
            }
            else
            {
                this._mqttClientMessage = "Not configured";
            }

            this._mqttClient.UseConnectedHandler(e => {
                this._mqttClientMessage = "All good";
            });
            this._mqttClient.UseApplicationMessageReceivedHandler(e => this.HandleMessageReceived(e.ApplicationMessage));

            // configure what happens on disconnect
            this._mqttClient.UseDisconnectedHandler(e =>
            {
                this._mqttClientMessage = e.ReasonCode.ToString();
            });
        }