Exemplo n.º 1
0
        public async Task PublishAsync(string message, CancellationToken cancellationToken)
        {
            // Setup and start a managed MQTT client.
            var _options = ManagedMqttClientBuilderExtensions.DefaultManagedMqttClient(this.options).Build();

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

            mqttClient = SetupConnectionHandler(mqttClient, _options);
            mqttClient.UseApplicationMessageReceivedHandler(new ApplicationMessageReceiverHandler(this.options.Topic));

            await mqttClient.SubscribeAsync(GetTopicBuilder(this.options.Topic).Build());

            await mqttClient.StartAsync(_options);
        }
        //public static async Task<IDependencyResolver> SetupMqttClientAsync(this IDependencyResolver dependencyResolver, SensorDataCallback callback)
        public static async Task <IManagedMqttClient> SetupMqttClientAsync(MqttNetOptions options)
        {
            //var receiver = dependencyResolver.Resolve<IGenericDataReceiverService>();

            //if (!dependencyResolver.IsRegistered<MqttNetOptions>())
            //{
            //    dependencyResolver.ConfigureSettingsPerType<MqttNetOptions>(false);
            //}

            // Setup and start a managed MQTT client.
            //var options = ManagedMqttClientBuilderExtensions.DefaultManagedMqttClient(dependencyResolver).Build();
            var _options = ManagedMqttClientBuilderExtensions.DefaultManagedMqttClient(options).Build();

            var mqttClient = new MqttFactory()
                             .CreateManagedMqttClient()
                             .SetupConnectionHandler(_options)
                             //.UseApplicationMessageReceivedHandler(new ApplicationMessageReceiverHandler(receiver, callback));
                             .UseApplicationMessageReceivedHandler(new ApplicationMessageReceiverHandler(options.Topic ?? new string[] { "$sys" }));

            //Todo: Get topics from somewhere (DB or Config?)
            //var topics = new List<string> {
            //    MqttConstants.MqttClient.Topic.SensorData
            //};

            await mqttClient.SubscribeAsync(GetTopicBuilder(options.Topic).Build());

            await mqttClient.StartAsync(_options);

            // StartAsync returns immediately, as it starts a new thread using Task.Run,
            // and so the calling thread needs to wait.
            //Console.ReadLine();
            //dependencyResolver.RegisterInstance(mqttClient);

            //return dependencyResolver;
            return(mqttClient);
        }