Exemplo n.º 1
0
        public static async Task SubscribeMQTT(List <string> topicList)
        {
            foreach (string topic in topicList)
            {
                if (topic != "")
                {
                    var topicFilter = new MqttTopicFilterBuilder()
                                      .WithAtLeastOnceQoS()
                                      .WithTopic(topic)
                                      .Build();
                    await mqttClient.SubscribeAsync(topicFilter);
                }
            }
            mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                MqttMessageEventArgs messageReceivedEventArgs = new()
                {
                    Topic   = e.ApplicationMessage.Topic,
                    Message = System.Text.Encoding.Default.GetString(e.ApplicationMessage.Payload),
                };
                MqttMessageReceived?.Invoke(null, messageReceivedEventArgs);
                Debug.WriteLine("Received Message int topic: " + e.ApplicationMessage.Topic + " : " + System.Text.Encoding.Default.GetString(e.ApplicationMessage.Payload));
            });

            return;
        }
Exemplo n.º 2
0
        private void Client_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            var match = regex.Match(e.ApplicationMessage.Topic);

            if (!match.Success)
            {
                return;
            }

            MqttMessageReceived?.Invoke(match.Groups.Cast <Group>().Skip(1).Select(o => o.Value).ToList(), e);
        }
        public async Task ConnectToBrokerAsync(string nelloTopicId)
        {
            try
            {
                _nelloTopicId = nelloTopicId;

                var options = new MqttClientOptionsBuilder()
                              .WithTcpServer(SERVER_ADDRESS, SERVER_PORT)
                              .Build();

                _client.UseDisconnectedHandler(async e =>
                {
                    try
                    {
                        await _client.ReconnectAsync();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString());
                    }
                });

                _client.UseConnectedHandler(async e =>
                {
                    try
                    {
                        foreach (var topic in _mqttListeningTopics)
                        {
                            await SubscribeToTopicAsync(string.Format("{0}{1}/{2}", TOPIC_PREFIX, _nelloTopicId, topic));
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString());
                    }
                });

                _client.UseApplicationMessageReceivedHandler(e =>
                {
                    try
                    {
                        if (e.ApplicationMessage.Topic.StartsWith("/nello_one"))
                        {
                            var args      = new MqttMessageEventArgs();
                            args.ClientId = e.ClientId;
                            args.Message  = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                            args.Topic    = e.ApplicationMessage.Topic;
                            MqttMessageReceived?.Invoke(this, args);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString());
                    }
                });

                await _client.ConnectAsync(options);
            }
            catch (Exception ex)
            {
                _logger.LogError("ConnectToBrokerAsync error:\n" + ex.ToString());
            }
        }
Exemplo n.º 4
0
        public async Task InitializeAsync()
        {
            Logger        = new TestableLogger();
            LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(c => c.ConfigureTestableLogger(Logger));

            LogoHardwareMock = new LogoHardwareMock();

            var brokerIpAddress = IPAddress.Loopback;
            var brokerPort      = 1889;

            var mqttFactory = new MqttFactory();

            mqttServer = mqttFactory.CreateMqttServer();
            MqttClient = mqttFactory.CreateMqttClient();
            MqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(args => MqttMessageReceived?.Invoke(this, args));

            var mqttServerOptions = new MqttServerOptionsBuilder()
                                    .WithClientId(nameof(IntegrationTestEnvironment) + "Broker")
                                    .WithDefaultEndpointBoundIPAddress(brokerIpAddress)
                                    .WithDefaultEndpointPort(brokerPort)
                                    .Build();

            var mqttClientOptions = new MqttClientOptionsBuilder()
                                    .WithClientId(nameof(IntegrationTestEnvironment) + "Client")
                                    .WithTcpServer(brokerIpAddress.ToString(), brokerPort)
                                    .Build();

            await mqttServer
            .StartAsync(mqttServerOptions)
            .ConfigureAwait(false);

            await MqttClient
            .ConnectAsync(mqttClientOptions)
            .ConfigureAwait(false);

            var config = IntegrationTests.GetConfig(brokerIpAddress.ToString(), brokerPort);

            config.Validate();
            appContext = Logic
                         .Initialize(LoggerFactory, config);
            await appContext
            .Connect()
            .ConfigureAwait(false);
        }