コード例 #1
0
        public static IManagedMqttClient UseConnectedHandler(this IManagedMqttClient client, Action <MqttClientConnectedEventArgs> handler)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (handler == null)
            {
                return(client.UseConnectedHandler((IMqttClientConnectedHandler)null));
            }

            return(client.UseConnectedHandler(new MqttClientConnectedHandlerDelegate(handler)));
        }
コード例 #2
0
 //MQTTClient topic cancelling subscription
 public static void ManagedMqttUnsubscribe(IManagedMqttClient managedMqttClient, string mqttTopic)
 {
     managedMqttClient.UseConnectedHandler(async e =>
     {
         await managedMqttClient.UnsubscribeAsync(mqttTopic);
     });
 }
コード例 #3
0
        public MqttService(
            IOptions <MqttOptions> mqttOptions,
            ILogger <MqttService> logger,
            DeviceState deviceState,
            IServiceScopeFactory serviceScopeFactory)
        {
            _mqttOptions = mqttOptions.Value;
            _logger      = logger;
            _deviceState = deviceState;

            _serviceScopeFactory = serviceScopeFactory;
            _client = new MqttFactory().CreateManagedMqttClient();

            _client.UseApplicationMessageReceivedHandler(e =>
            {
                HandleMqttMessage(e);
            });

            _client.UseConnectedHandler(e =>
            {
                HandleMqttConnected(e);
            });

            _client.UseDisconnectedHandler(e =>
            {
                HandleMqttDisconnected(e);
            });
        }
コード例 #4
0
        public bool TryConnect()
        {
            lock (_syncRoot)
            {
                if (IsConnected)
                {
                    // prevent duplicated concurrent re-connection
                    return(true);
                }

                if (!_mqttClient.IsStarted)
                {
                    _logger.LogInformation("Mqtt Client is trying to connect");
                    _mqttClient.StartAsync(_clientOptions).Wait();
                    _mqttClient.UseConnectedHandler(e => { _logger.LogInformation("MQTT Server connected!"); });
                    _mqttClient.UseDisconnectedHandler((e) =>
                    {
                        _logger.LogError("MQTT Server disconnected: " + e?.Exception?.Message);
                    });
                }


                return(_mqttClient.IsConnected);
            }
        }
コード例 #5
0
        public MqttService(IHubContext <DevicesHub> hubContext)
        {
#if true
            _hubContext = hubContext;
            var messageBuilder = new MqttClientOptionsBuilder().WithClientId(clientId) /*.WithCredentials(mqttUser, mqttPassword)*/.WithTcpServer(mqttURI, mqttPort).WithCleanSession();

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

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

            client = new MqttFactory().CreateManagedMqttClient();
            client.StartAsync(managedOptions);

            client.UseConnectedHandler(ClientConnectedHandler);
            //client.UseDisconnectedHandler(ClientDisconnectedHandler);
            client.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(OnConnectingFailed);
            client.UseApplicationMessageReceivedHandler(ClientMessageReceivedHandler);
#endif
        }
コード例 #6
0
        private async void OnStarted()
        {
            var brokerSettings = _configuration.GetSection("BrokerSettings").Get <BrokerSettings>();
            var options        = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(new MqttClientOptionsBuilder()
                                                    .WithClientId(_serviceSettings.NodeId)
                                                    .WithTcpServer(brokerSettings.Host, brokerSettings.Port)
                                                    .WithCredentials(brokerSettings.Username, brokerSettings.Password)
                                                    .WithCleanSession(false)
                                                    .Build())
                                 .Build();

            _client.UseConnectedHandler(handler =>
            {
                _logger.LogInformation("Connected successfully with MQTT Brokers.");
            });

            _client.UseDisconnectedHandler(handler =>
            {
                _logger.LogWarning("Disconnected from MQTT Brokers.");
            });

            await _client.StartAsync(options);

            _timer = new Timer(HandleTimerCallback, null, TimeSpan.Zero,
                               TimeSpan.FromMilliseconds(_serviceSettings.TimeSpan));
        }
コード例 #7
0
ファイル: MqttSink.cs プロジェクト: sparten11740/allmylights
        public MqttSink(MqttSinkOptions options, IManagedMqttClient client) : base(options)
        {
            MqttClient = client;
            Topics     = options.Topics.ToList();
            Options    = options;

            var builder = new MqttClientOptionsBuilder()
                          .WithTcpServer(options.Server, options.Port);

            if (options.Password != null && options.Username != null)
            {
                builder = builder.WithCredentials(options.Username, options.Password);
            }

            var clientOptions = builder.Build();

            MqttClientOptions = new ManagedMqttClientOptionsBuilder()
                                .WithPendingMessagesOverflowStrategy(MQTTnet.Server.MqttPendingMessagesOverflowStrategy.DropOldestQueuedMessage)
                                .WithClientOptions(clientOptions)
                                .WithMaxPendingMessages(1).WithAutoReconnectDelay(TimeSpan.FromSeconds(10)).Build();

            MqttClient.UseDisconnectedHandler(HandleDisconnected);
            MqttClient.UseConnectedHandler(HandleConnected);

            client.StartAsync(MqttClientOptions).Wait();


            Next.Subscribe(payload =>
            {
                Publish(payload).Wait();
            });
        }
コード例 #8
0
        /// <summary>
        /// Start the service by building the MQTT configuration
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _client = new MqttFactory().CreateManagedMqttClient();

            // Setup and start a managed MQTT client.
            var mqttClientOptions = new ManagedMqttClientOptionsBuilder()
                                    .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                    .WithClientOptions(new MqttClientOptionsBuilder()
                                                       .WithCommunicationTimeout(TimeSpan.FromSeconds(10))
                                                       .WithTcpServer(_options.BrokerAddress, _options.BrokerPort)
                                                       .Build())
                                    .Build();

            _client.UseConnectedHandler(async e =>
            {
                _logger.LogInformation("### CONNECTED WITH SERVER ###");

                await _client.SubscribeAsync(new TopicFilterBuilder().WithTopic(typeof(T).GetTopicName()).Build());

                _logger.LogInformation("### SUBSCRIBED ###");
            });

            _client.UseApplicationMessageReceivedHandler(e =>
            {
                var obj = JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
                _topicHandler.Work(_client, obj);
            });

            _logger.LogInformation($"Connecting to server [{JsonConvert.SerializeObject(mqttClientOptions)}]...");
            await _client.StartAsync(mqttClientOptions);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: kursatarslan/mqttBroker
        public static async Task ConnectAsync()
        {
            var clientId     = Guid.NewGuid().ToString();
            var mqttURI      = "localhost";
            var mqttUser     = "******";
            var mqttPassword = "******";
            var mqttPort     = 1883;

            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(clientId)
                                 .WithCredentials(mqttUser, mqttPassword)
                                 .WithTcpServer(mqttURI, mqttPort)
                                 .WithCleanSession();

            var options = messageBuilder
                          .Build();

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

            await client.StartAsync(managedOptions);

            client.UseConnectedHandler(e => { Console.WriteLine("Connected successfully with MQTT Brokers."); });

            client.UseDisconnectedHandler(e => { Console.WriteLine("Disconnected from MQTT Brokers."); });
        }
コード例 #10
0
        private static async Task ConnectAsync()
        {
            string mqttUri = configuration["mqttServerIp"];
            //const string mqttUri = "localhost";
            var mqttUser     = configuration["mqttUser"];
            var mqttPassword = configuration["mqttPassword"];
            var mqttPort     = Convert.ToInt32(configuration["mqttPort"]);

            Console.WriteLine($"MQTT Server:{mqttUri} Username:{mqttUser} ClientID:{clientId}");
            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(clientId)
                                 .WithCredentials(mqttUser, mqttPassword)
                                 .WithTcpServer(mqttUri, mqttPort)
                                 .WithKeepAlivePeriod(new TimeSpan(0, 0, 30))
                                 .WithCleanSession();

            var options = messageBuilder
                          .Build();

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

            await client.StartAsync(managedOptions);

            client.UseConnectedHandler(e => { Console.WriteLine("Connected successfully with MQTT Brokers."); });
            client.UseDisconnectedHandler(e =>
            {
                new MqttClientDisconnectedHandlerDelegate(e => MqttClient_Disconnected(e));
                Console.WriteLine("Disconnected from MQTT Brokers.Client Was Connected " + e.ClientWasConnected);
            });
            client.UseApplicationMessageReceivedHandler(e =>
            {
                try
                {
                    var topic = e.ApplicationMessage.Topic;

                    if (!string.IsNullOrWhiteSpace(topic))
                    {
                        var payload = HelperFunctions.GetPayload(e.ApplicationMessage.Payload);
                        Console.WriteLine($"Topic: {topic}. Message Received: {JsonConvert.SerializeObject(payload, Formatting.Indented)}");
                        var platoonId = topic.Replace("platooning/" + clientId + "/", "").Split("/").Last();
                        if (payload.Maneuver == 2)
                        {
                            _ = SubscribeAsync($@"platooning/broadcast/{platoonId}/#");
                            Console.WriteLine("Client SubscribeAsync as  " + "platooning/broadcast/" + platoonId + "/#");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ex);
                }
            });
        }
コード例 #11
0
 //MQTTClient topic subscription
 public static void ManagedMqttSubscribe(IManagedMqttClient managedMqttClient, string mqttTopic)
 {
     managedMqttClient.UseConnectedHandler(async e =>
     {
         // Subscribe to a topic
         await managedMqttClient.SubscribeAsync(new TopicFilter {
             Topic = mqttTopic, QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
         });
     });
 }
コード例 #12
0
        static void Main(string[] args)
        {
            WebClient webclient = new WebClient();

            Console.WriteLine("Started mqtt influx exporter");
            Task.Run(async() =>
            {
                await ConnectAsync();
                client.UseConnectedHandler(e =>
                {
                    Console.WriteLine("Connected successfully with MQTT Brokers.");
                });
                client.UseDisconnectedHandler(e =>
                {
                    Console.WriteLine("Disconnected from MQTT Brokers.");
                });
                client.UseApplicationMessageReceivedHandler(e =>
                {
                    try
                    {
                        string topic = e.ApplicationMessage.Topic;
                        if (string.IsNullOrWhiteSpace(topic) == false)
                        {
                            string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                            if (Environment.GetEnvironmentVariable("LOG_MQTT").ToLower() == "true")
                            {
                                Console.WriteLine($"Topic: {topic}. Message Received: {payload}");
                            }
                            string[] topicParts = topic.Split("/");
                            // "temperature, type="weather", device="mcu12390u0adaksnjl", value=25.23, timestamp (optional, nanosecond unix time)
                            string influxPayload = topicParts[2] + ",type=" + topicParts[1] + ",device=" + topicParts[3] + " value=" + payload;
                            string url           = Environment.GetEnvironmentVariable("INFLUXDB_URL");
                            if (string.IsNullOrEmpty(url))
                            {
                                url = "http://192.168.10.31:8086/write?db=iot";
                            }
                            var response = webclient.UploadString(url, influxPayload);
                            //Console.WriteLine(response);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message, ex);
                    }
                });

                // Subscribe to channels
                _ = SubscribeAsync("iot/weather/+/+", 1);
            });
            // Prevent immediate exit
            _quitEvent.WaitOne();
        }
コード例 #13
0
        public static async Task WaitForConnectAsync(this IManagedMqttClient client, CancellationToken token = default)
        {
            var asyncManualResetEvent = new Nito.AsyncEx.AsyncManualResetEvent(false);
            var oldHandler            = client.ConnectedHandler;

            client.UseConnectedHandler(e =>
            {
                asyncManualResetEvent.Set();
            });

            await asyncManualResetEvent.WaitAsync(token);

            client.ConnectedHandler = oldHandler;
        }
コード例 #14
0
ファイル: MqttReader.cs プロジェクト: bp2008/AcuRiteSniffer
        /// <summary>
        /// Starts the MQTT Client.
        /// </summary>
        /// <returns></returns>
        public async Task Start()
        {
            if (managedMqttClient != null)
            {
                return;
            }

            managedMqttClient = new MqttFactory().CreateManagedMqttClient();

            IMqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder()
                                                   .WithTcpServer(host, tcpPort)
                                                   .WithCredentials(user, pass)
                                                   .Build();

            ManagedMqttClientOptions managedMqttClientOptions = new ManagedMqttClientOptionsBuilder()
                                                                .WithClientOptions(mqttClientOptions)
                                                                .Build();

            managedMqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                IngestMessage(e.ApplicationMessage);
                return(Task.CompletedTask);
            });
            managedMqttClient.UseConnectedHandler(e =>
            {
                OnStatusUpdate(this, "MQTT connected.");
            });
            managedMqttClient.UseDisconnectedHandler(e =>
            {
                if (e.ClientWasConnected)
                {
                    OnStatusUpdate(this, "MQTT disconnected.");
                }
                else
                {
                    OnStatusUpdate(this, "MQTT failed to connect.");
                }
            });
            managedMqttClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(e =>
            {
                OnError(this, "MQTT connection failed: " + e.Exception.FlattenMessages());
            });

            await managedMqttClient.StartAsync(managedMqttClientOptions);

            string topic = "rtl_433/+/devices/#";

            OnStatusUpdate(this, "Will subscribe to topic \"" + topic + "\"");
            await managedMqttClient.SubscribeAsync(topic);
        }
コード例 #15
0
        public static async Task StartListener()
        {
            var mqttClientOptions = new MqttClientOptionsBuilder()
                                    .WithClientId("server")
                                    .WithTcpServer("localhost", 1884)
                                    .Build();

            listener = new MqttFactory().CreateManagedMqttClient();

            var opt = new ManagedMqttClientOptionsBuilder()
                      .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                      .WithClientOptions(mqttClientOptions)
                      .Build();

            listener.UseApplicationMessageReceivedHandler(context =>
            {
                Payload payload = null;
                var type        = PayloadUtilities.FindBinaryPayloadType(context.ApplicationMessage.Payload);
                switch (type)
                {
                case PayloadTypes.Generic:
                    payload = new Payload();
                    break;

                case PayloadTypes.Moisture:
                    payload = new MoisturePayload();
                    break;

                case PayloadTypes.Light:
                    payload = new LightPayload();
                    break;

                default:
                    Console.WriteLine($"Received packet type '{type.ToString()}' with no handler.");
                    return;
                }
                payload.FromBytes(context.ApplicationMessage.Payload);
                payload.SendInflux(connection, "plant");
                Console.WriteLine(payload.ToString());
            });
            listener.UseConnectedHandler(async e =>
            {
                await listener.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
            });
            await listener.StartAsync(opt);
        }
コード例 #16
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("MQTT background Service is starting ");

            await this.ConnectAsync();

            if (_client.IsStarted)
            {
                _logger.LogInformation("client is started");
            }

            _client.UseConnectedHandler(ConnectHandler);
            _client.UseDisconnectedHandler(DisconnectHandler);
            _client.UseApplicationMessageReceivedHandler(MessageRecievedHandler);

            await _client.SubscribeAsync("ESP/TOLLCOLLECTION");
        }
コード例 #17
0
        public void Setup()
        {
            client.UseApplicationMessageReceivedHandler(e =>
            {
                Console.WriteLine("");
                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();
                // Task.Run(() => client.PublishAsync("hello/world"));

                if (e.ApplicationMessage.Topic == "master/start")
                {
                    if (!recording)
                    {
                        recording = true;
                        publish("\nStart Signal received", "master/response");
                        _recorder.record();
                    }
                }
                else if (e.ApplicationMessage.Topic == "master/stop")
                {
                    if (recording)
                    {
                        recording = false;
                        publish("\nStop Signal received", "master/response");
                        _recorder.stop();
                    }
                }
            });

            client.UseDisconnectedHandler(e => {
                Console.WriteLine("Attempting to Connect to " + MasterIP);
                Console.WriteLine("\nDisconnected from MQTT Broker!");
                connected = false;
            });

            client.UseConnectedHandler(c => {
                Console.WriteLine("\nConnected to MQTT Broker @ " + MasterIP + ":" + MasterPort + "!");
                connected = true;
            });
        }
コード例 #18
0
        private async void OnStarted()
        {
            var brokerSettings = _configuration.GetSection("BrokerSettings").Get <BrokerSettings>();
            var options        = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(new MqttClientOptionsBuilder()
                                                    .WithClientId("bff")
                                                    .WithTcpServer(brokerSettings.Host, brokerSettings.Port)
                                                    .WithCredentials(brokerSettings.Username, brokerSettings.Password)
                                                    .WithCleanSession(false)
                                                    .Build())
                                 .Build();

            _client.UseConnectedHandler(async handler =>
            {
                _logger.LogInformation("Connected successfully with MQTT Brokers.");
                var topicFilters = new List <MqttTopicFilter>();
                topicFilters.Add(new MqttTopicFilterBuilder()
                                 .WithTopic("/count")
                                 .WithAtLeastOnceQoS()
                                 .Build());
                topicFilters.Add(new MqttTopicFilterBuilder()
                                 .WithTopic("/putmovie")
                                 .WithAtMostOnceQoS()
                                 .Build());
                await _client.SubscribeAsync(topicFilters);
            });

            _client.UseApplicationMessageReceivedHandler(async handler =>
            {
                switch (handler.ApplicationMessage.Topic)
                {
                case "/putmovie":
                    await SubscribeMovieAsync(handler);
                    break;

                default:
                    await SubscribeAsync(handler);
                    break;
                }
            });
            await _client.StartAsync(options);
        }
コード例 #19
0
ファイル: MqttClient.cs プロジェクト: jasase/deconz-to-mqtt
        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);
        }
コード例 #20
0
        public void Subscribe(string topic)
        {
            //_mqttClient.UseConnectedHandler(e =>
            //{
            //    _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build()).Wait();
            //});

            _mqttClient.UseConnectedHandler(async e =>
            {
                Debug.WriteLine("### CONNECTED WITH SERVER ###");

                // Subscribe to a topic
                await _mqttClient.SubscribeAsync(new TopicFilterBuilder()
                                                 .WithTopic(topic)
                                                 .Build());

                Debug.WriteLine($"### SUBSCRIBED TO TOPIC {topic} ###");
            });
        }
コード例 #21
0
        public void Create(ConnectionOptions options, Credentials credentials, string topic)
        {
            //configure options
            var mqttClientOptions = new MqttClientOptionsBuilder()
                                    .WithClientId(credentials.UserName)
                                    .WithTcpServer(options.IpAddress, options.Port)
                                    .WithCredentials(credentials.Login, credentials.Password)
                                    .WithCleanSession()
                                    .Build();


            var mqttManagedMqttClientOptions = _options = new ManagedMqttClientOptionsBuilder()
                                                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                                          .WithClientOptions(mqttClientOptions)
                                                          .Build();


            // Create a new MQTT client.
            _client = new MqttFactory().CreateManagedMqttClient();


            //handlers
            _client.UseConnectedHandler(e =>
            {
                OnConnected?.Invoke(e);

                //subscribing to a topic
                if (!string.IsNullOrEmpty(topic))
                {
                    _topic = topic;
                    _client.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build()).Wait();
                }
            });
            _client.UseDisconnectedHandler(e =>
            {
                OnDisconnected?.Invoke(e);
            });
            _client.UseApplicationMessageReceivedHandler(e =>
            {
                OnMessageReceived?.Invoke(e);
            });
        }
コード例 #22
0
    public static IManagedMqttClient ConfigureMqttEvents(this IManagedMqttClient mqttClient, IServiceProvider serviceProvider, CancellationToken cancellationToken)
    {
        MqttEvents mqttEvents = serviceProvider.GetService <MqttEvents>();

        if (mqttEvents == null)
        {
            throw new InvalidOperationException($"Unable to find {nameof(MqttEvents)} service. Did you forget to call {nameof(ServiceCollectionExtensions.AddMqttEvents)}()?");
        }

        mqttClient.UseDisconnectedHandler(async args =>
        {
            await mqttEvents.InvokeDisconnectHandler(args, cancellationToken);
        });
        mqttClient.UseConnectedHandler(async args =>
        {
            await mqttEvents.InvokeConnectHandler(args, cancellationToken);
        });

        return(mqttClient);
    }
コード例 #23
0
ファイル: MqttClient.cs プロジェクト: joanjane/jj-smarthome
        public async Task Connect(string clientIdPrefix, Func <Task> connected = null, Func <Task> disconnected = null)
        {
            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId($"{clientIdPrefix}-{_options.ClientId}")
                                 .WithKeepAlivePeriod(TimeSpan.FromSeconds(90))
                                 .WithCredentials(_options.User, _options.Password)
                                 .WithTcpServer(_options.URI, _options.Port)
                                 .WithCleanSession();

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

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

            _client = new MqttFactory()
                      .CreateManagedMqttClient();
            _client.UseConnectedHandler(async e =>
            {
                _logger.LogInformation("Connected from MQTT Broker.");
                if (connected != null)
                {
                    await connected();
                }
            })
            .UseDisconnectedHandler(async e =>
            {
                _logger.LogWarning(e.Exception, $"Disconnected from MQTT Broker.");
                if (disconnected != null)
                {
                    await disconnected();
                }
            });
            await _client.StartAsync(managedOptions);
        }
コード例 #24
0
        /// <summary>
        /// Constructor
        /// </summary>
        public Logic(ILogger <Logic> logger, IOptions <Config> config, IHostEnvironment hostEnvironment)
        {
            _logger          = logger;
            _config          = config.Value;
            _hostEnvironment = hostEnvironment;

            _mqttClient = new MqttFactory().CreateManagedMqttClient();
            _mqttClient.UseApplicationMessageReceivedHandler(MqttClientOnApplicationMessageReceived);
            _mqttClient.UseConnectedHandler(async e =>
            {
                _logger.LogInformation("Connected to MQTT server");

                await _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(_config.Mqtt.ShutdownTopic)
                                                 .Build());
            });
            _mqttClient.UseDisconnectedHandler(e =>
            {
                if (e.Exception != null && !e.ClientWasConnected)
                {
                    _logger.LogError(e.Exception, "Unable to connect to MQTT server");
                }

                if (e.Exception != null && e.ClientWasConnected)
                {
                    _logger.LogError("Disconnected from connect to MQTT server with error", e.Exception);
                }

                if (e.Exception == null && e.ClientWasConnected)
                {
                    _logger.LogInformation("Disconnected from MQTT server");
                }
            });

            _timeoutTimer          = new Timer(_config.TimeoutSeconds * 1000);
            _timeoutTimer.Elapsed += async(sender, args) =>
            {
                _timeoutTimer.Stop();

                InitiateShutdown();
            };
        }
コード例 #25
0
        public async Task ConnectAsync()
        {
            try
            {
                _mqttClient.UseConnectedHandler(e => { _logger.LogInformation("Connected to Mqtt Broker"); });
                _mqttClient.UseDisconnectedHandler(e =>
                {
                    if (e.Exception != null)
                    {
                        _logger.LogWarning("Disconnected from Mqtt Broker", e.Exception);
                    }
                });

                _mqttClient.UseApplicationMessageReceivedHandler(async e =>
                {
                    try
                    {
                        var topic = e.ApplicationMessage.Topic;
                        if (!string.IsNullOrWhiteSpace(topic))
                        {
                            var payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                            _logger.LogInformation($"Topic: {topic}. Message Received: {payload}");
                            await OnReceived(topic, payload);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.Message, ex);
                    }
                });
                await _mqttClient.StartAsync(_managedOptions);
            }
            catch (Exception e)
            {
                _logger.LogError("Failed to start Mqtt Client", e);
                throw;
            }
        }
コード例 #26
0
        public async Task SetupClientAsync(CancellationToken cancellationToken)
        {
            // Setup and start a managed MQTT client.
            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId("Server")
                                             //.WithWebSocketServer("localhost:50482/mqtt")
                                             .Build())
                          .Build();

            _mqttClient = new MqttFactory().CreateManagedMqttClient();

            await _mqttClient.StartAsync(options);


            await _mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("MqttWeatherForecast/90210/temperature").Build());

            _mqttClient.UseConnectedHandler(e =>
            {
                //Console.WriteLine($"Connection Result: {e.AuthenticateResult.ResultCode}");
            });

            _mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                //Console.WriteLine($"Message from {e.ClientId}: {e.ApplicationMessage.Payload.Length} bytes.");
            });

            await _mqttClient.StartAsync(options);

            await _mqttClient.PublishAsync(new ManagedMqttApplicationMessageBuilder().WithApplicationMessage(msg =>
            {
                msg.WithAtLeastOnceQoS();
                msg.WithPayload(BitConverter.GetBytes(98.6d));
                msg.WithTopic("inTopic");
            }).Build());
        }
コード例 #27
0
        public MqttListenerService(IManagedMqttClient client, IManagedMqttClientOptions options, IConfiguration configuration, IServiceId serviceId,
                                   ILogger <MqttListenerService> logger, IPointsOfSaleService posService, IServiceProvider serviceProvider, IPosTopicClassifier posTopicClassifier)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (serviceId == null)
            {
                throw new ArgumentNullException(nameof(serviceId));
            }

            _client             = client ?? throw new ArgumentNullException(nameof(client));
            _options            = options ?? throw new ArgumentNullException(nameof(options));
            _logger             = logger ?? throw new ArgumentNullException(nameof(logger));
            _posService         = posService ?? throw new ArgumentNullException(nameof(posService));
            _posTopicClassifier = posTopicClassifier ?? throw new ArgumentNullException(nameof(posTopicClassifier));

            _client.UseApplicationMessageReceivedHandler(OnMqttMessageReceived);
            _client.UseConnectedHandler(args => OnConnectedHandler(args));
            _client.UseDisconnectedHandler(args => OnDisconnectedHandler(args));

            _messageHandlers = serviceProvider.GetServices <IMqttMessageHandler>().ToArray();
        }
コード例 #28
0
        /// <summary>
        /// Initialize
        /// </summary>
        /// <param name="mqttHost"></param>
        /// <param name="mqttPort"></param>
        /// <param name="mqttRootTopic"></param>
        /// <param name="callbackAddress"></param>
        /// <param name="callbackPort"></param>
        /// <param name="bridgeUrl"></param>
        /// <param name="token"></param>
        /// <param name="hashToken"></param>
        /// <param name="infoInterval"></param>
        private void Initialize(string mqttHost, int?mqttPort, string mqttRootTopic, string callbackAddress,
                                int?callbackPort, string bridgeUrl, string token, bool hashToken, int?infoInterval)
        {
            _mqttRootTopic = !string.IsNullOrEmpty(mqttRootTopic) ? mqttRootTopic : "nukibridge";
            _mqttHost      = !string.IsNullOrEmpty(mqttHost) ? mqttHost : "localhost";
            _mqttPort      = mqttPort ?? 1883;

            _bridgeUrl   = !string.IsNullOrEmpty(bridgeUrl) ? bridgeUrl : NukiBridgeClient.DiscoverBridge();
            _bridgeToken = token;

            if (string.IsNullOrEmpty(_bridgeUrl) ||
                string.IsNullOrEmpty(_bridgeToken))
            {
                throw new Exception("No Bridge_URL and/or Bridge_Token defined");
            }

            _hashToken = hashToken;

            // Setup MQTT
            _mqttClient = new MqttFactory().CreateManagedMqttClient();
            _mqttClient.UseApplicationMessageReceivedHandler(e => MqttClientOnApplicationMessageReceived(e));
            _mqttClient.UseConnectedHandler(e =>
            {
                Log.Information("MQTT: Connected");

                SubscribeTopic("discover");
                SubscribeTopic("reset");
                SubscribeTopic("reboot");
                SubscribeTopic("fw-upgrade");
            });
            _mqttClient.UseDisconnectedHandler(e =>
            {
                if (e.ClientWasConnected)
                {
                    Log.Warning($"MQTT: Disconnected ({e.Exception?.Message ?? "clean"})");
                }
                else
                {
                    Log.Error($"MQTT: Unable to connect ({e.Exception?.Message ?? "clean"})");
                }
            });

            _nukiBridgeClient = new NukiBridgeClient(_bridgeUrl, _bridgeToken, _hashToken);

            // Setup callback
            _callbackAddress = callbackAddress ?? LocalIpAddress().ToString();
            _callbackPort    = callbackPort ?? 8080;

            _httpListener = new HttpListener
            {
                Prefixes = { $"http://+:{_callbackPort}/" }
            };

            _devices = new List <Device>();

            // Prevent info interval being set to 0
            if ((infoInterval ?? 0) == 0)
            {
                infoInterval = 300;
            }

            // Setup info interval
            _infoTimer          = new Timer((infoInterval ?? 300) * 1000);
            _infoTimer.Elapsed += async(sender, args) =>
            {
                _infoTimer.Stop();
                await PublishBridgeInfo();

                _infoTimer.Start();
            };
        }
コード例 #29
0
        public static async Task ConnectAsync()
        {
            string clientId       = Guid.NewGuid().ToString();
            string mqttURI        = "127.0.0.1";
            string mqttUser       = "******";
            string mqttPassword   = "******";
            int    mqttPort       = 1883;
            bool   mqttSecure     = false;
            var    messageBuilder = new MqttClientOptionsBuilder()
                                    .WithClientId(clientId)
                                    .WithCredentials(mqttUser, mqttPassword)
                                    .WithTcpServer(mqttURI, mqttPort)
                                    .WithProtocolVersion(MqttProtocolVersion.V500)
                                    //.WithTls()
                                    .WithCleanSession();

            var options        = mqttSecure ? messageBuilder.WithTls().Build() : messageBuilder.Build();
            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                 .WithClientOptions(options)

                                 .Build();

            client = new MqttFactory().CreateManagedMqttClient();
            await client.StartAsync(managedOptions);



            client.UseConnectedHandler(e =>
            {
                Console.WriteLine("Connected successfully with MQTT Brokers.");
            });


            await SubscribeAsync("+/+/+/+");

            //await SubscribeAsync("let/me/in/pep");

            Console.WriteLine(client.IsStarted + " " + client.IsConnected);

            client.UseDisconnectedHandler(e =>
            {
                Console.WriteLine("Disconnected from MQTT Brokers." + e.ClientWasConnected + " " + e?.AuthenticateResult?.ReasonString);
            });

            client.UseApplicationMessageReceivedHandler(e =>
            {
                try
                {
                    string topic = e.ApplicationMessage.Topic;
                    if (string.IsNullOrWhiteSpace(topic) == false)
                    {
                        string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        Console.WriteLine($"Topic: {topic}. Message Received: {payload}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ex);
                }
            });
        }
コード例 #30
0
        private static async Task ConnectAsync()
        {
            const string mqttUri      = "localhost";
            var          mqttUser     = "******";
            var          mqttPassword = "******";
            var          mqttPort     = 1883;

            Console.WriteLine($"MQTT Server:{mqttUri} Username:{mqttUser} ClientID:{leadvehicle}");
            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(leadvehicle)
                                 .WithCredentials(mqttUser, mqttPassword)
                                 .WithTcpServer(mqttUri, mqttPort)
                                 .WithKeepAlivePeriod(new TimeSpan(0, 0, 30))
                                 .WithCleanSession();

            var options = messageBuilder
                          .Build();

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

            await client.StartAsync(managedOptions);

            client.UseConnectedHandler(e => { Console.WriteLine("Connected successfully with MQTT Brokers."); });
            client.UseApplicationMessageReceivedHandler(e =>
            {
                Console.WriteLine("Connected UseApplicationMessageReceivedHandler with MQTT Brokers." + e.ApplicationMessage);
            });

            client.UseDisconnectedHandler(e =>
            {
                new MqttClientDisconnectedHandlerDelegate(e => MqttClient_Disconnected(e));
                Console.WriteLine("Disconnected from MQTT Brokers.Client Was Connected " + e.ClientWasConnected);
            });
            client.UseApplicationMessageReceivedHandler(e =>
            {
                try
                {
                    var topic = e.ApplicationMessage.Topic;

                    if (!string.IsNullOrWhiteSpace(topic))
                    {
                        var stringpayload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        var bitArray      = new BitArray(e.ApplicationMessage.Payload);
                        var payload       = HelperFunctions.GetPayload(e.ApplicationMessage.Payload);
                        var py            = HelperFunctions.ToBitString(new BitArray(e.ApplicationMessage.Payload), 0, 61);
                        Console.WriteLine($"Topic: {topic}. Message Received: {py}");
                        var followingVehicle = topic.Replace("platooning/" + leadvehicle + "/", "");
                        if (payload.Maneuver == 1 && !string.IsNullOrWhiteSpace(followingVehicle))
                        {
                            payload.Maneuver = 2;
                            var message      = new BitArray(61);
                            message.Set(0, false);
                            message.Set(1, true);
                            message.Set(2, false);
                            _ = PublishAsync("platooning/" + followingVehicle + "/" + leadvehicle + "/" + platoonId, Encoding.ASCII.GetString(HelperFunctions.BitArrayToByteArray(message)));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ex);
                }
            });
        }