public static IManagedMqttClient UseApplicationMessageReceivedHandler(this IManagedMqttClient client, Func <MqttApplicationMessageReceivedEventArgs, Task> handler) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (handler == null) { return(client.UseApplicationMessageReceivedHandler((IMqttApplicationMessageReceivedHandler)null)); } return(client.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(handler))); }
/// <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); }
public HslMqttService(IManagedMqttClient client, ManagedMqttClientOptions options) { _options = options; _client = client; _client.UseApplicationMessageReceivedHandler(MessageReceived); _batchTimer = new Timer(BatchTimerTick); }
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); }); }
static async Task Main(string[] args) { var options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId("Ali_Consumer") .WithCredentials("testuser", "testpass") .WithTcpServer("www.baltavista.com", 8883) .WithCleanSession(true) .Build()) .Build(); _mqttClient = new MqttFactory().CreateManagedMqttClient(); await _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("test1").Build()); await _mqttClient.StartAsync(options); _mqttClient.UseApplicationMessageReceivedHandler(e => { Console.WriteLine($"({DateTime.Now}):{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); }); Console.WriteLine("-- MQTT Consumer started ---"); Console.ReadLine(); }
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 }
public async Task Start() { var optionsBuilder = new ManagedMqttClientOptionsBuilder(); optionsBuilder = optionsBuilder.WithClientOptions( o => o .WithTcpServer(_parameters.Server, _parameters.Port) .WithCredentials(_parameters.Username, _parameters.Password) .WithClientId(_parameters.ClientId) .WithTls(new MqttClientOptionsBuilderTlsParameters { UseTls = _parameters.UseTls })); if (!string.IsNullOrEmpty(_parameters.ClientId)) { optionsBuilder = optionsBuilder.WithClientOptions(o => o.WithClientId(_parameters.ClientId)); } var options = optionsBuilder.Build(); if (_mqttService.IsLowLevelMqttLoggingEnabled) { _mqttClient = new MqttFactory().CreateManagedMqttClient(); //new LoggerAdapter(_logger)); } else { _mqttClient = new MqttFactory().CreateManagedMqttClient(); } await _mqttClient.SubscribeAsync(_parameters.Topic, _parameters.QualityOfServiceLevel).ConfigureAwait(false); _mqttClient.UseApplicationMessageReceivedHandler(e => OnApplicationMessageReceived(e)); await _mqttClient.StartAsync(options).ConfigureAwait(false); }
private async void cloudCred(string di, string ak, string ass) { clientId = di; string mqttURI = "broker.losant.com"; string mqttUser = ak; string mqttPassword = ass; int mqttPort = 1883; bool mqttSecure = false; 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.ConnectedHandler = new MqttClientConnectedHandlerDelegate(connected); client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(disconnected); client.UseApplicationMessageReceivedHandler(e => { HandleMessageReceived(e.ApplicationMessage); }); await client.StartAsync(managedOptions); }
public void Start() { var optionsBuilder = new ManagedMqttClientOptionsBuilder(); optionsBuilder = optionsBuilder.WithClientOptions( o => o .WithTcpServer(_parameters.Server, _parameters.Port) .WithCredentials(_parameters.Username, _parameters.Password) .WithClientId(_parameters.ClientId) .WithTls(new MqttClientOptionsBuilderTlsParameters { UseTls = _parameters.UseTls })); if (!string.IsNullOrEmpty(_parameters.ClientId)) { optionsBuilder = optionsBuilder.WithClientOptions(o => o.WithClientId(_parameters.ClientId)); } var options = optionsBuilder.Build(); _mqttClient = new MqttFactory().CreateManagedMqttClient(new LoggerAdapter(_logger)); _mqttClient.SubscribeAsync(_parameters.Topic, _parameters.QualityOfServiceLevel).GetAwaiter().GetResult(); _mqttClient.UseApplicationMessageReceivedHandler(e => OnApplicationMessageReceived(e)); _mqttClient.StartAsync(options).GetAwaiter().GetResult(); }
public async Task Subscribe(string topic, Func <MqttApplicationMessageReceivedEventArgs, Task> handler) { await _client.SubscribeAsync(new TopicFilterBuilder() .WithTopic(topic) .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce) .Build()); _client.UseApplicationMessageReceivedHandler(handler); }
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); } }); }
public async Task <DeviceMqtt> ReceivePayload(MqttApplicationMessage message, DeviceMqtt device) { if (clientMqtt != null) { await clientMqtt.PublishAsync(message); clientMqtt.UseApplicationMessageReceivedHandler(e => device.Status = Encoding.UTF8.GetString(e.ApplicationMessage.Payload)); } return(device); }
public void OnMessage(string topic, Action <MqttMessage> action) { _logger.LogInformation($"Subscribing for messages on {topic}."); _mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(topic).Build()); _mqttClient.UseApplicationMessageReceivedHandler(e => { var rawMessage = e.ApplicationMessage; var message = new StringMessage(rawMessage.Topic, new StringPayload(Encoding.UTF8.GetString(rawMessage.Payload))); _logger.LogDebug($"Received message {message.Topic}: {message.Payload}"); action(message); }); }
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(); }
/// <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); }
/// <summary> /// Subscribe topic. /// </summary> /// <param name="topic">Topic.</param> /// <param name="qos">Quality of Service.</param> /// <returns>Task.</returns> public async Task SubscribeAsync(string topic, int qos = 1) { await client.SubscribeAsync(new TopicFilterBuilder() .WithTopic(topic) .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos) .Build()); client.UseApplicationMessageReceivedHandler(e => { OnTopicRecieved.Invoke( this, Encoding.UTF8.GetString(e.ApplicationMessage.Payload) ); }); }
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); }
// Credit to => https://dzone.com/articles/mqtt-publishing-and-subscribing-messages-to-mqtt-b public static async Task MqttConnectAsync() { string clientId = Guid.NewGuid().ToString(); // create a random ID string mqttURI = "test.mosquitto.org"; string mqttUser = ""; string mqttPassword = ""; int mqttPort = 1883; bool mqttSecure = false; 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.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); } }); await client.StartAsync(managedOptions); }
private async Task SubscribeToSensorTopics() { foreach (var topic in _sensorTopics) { Console.WriteLine($"subscribe to topic {topic}"); await _mqttClient.SubscribeAsync(topic); } _mqttClient.UseApplicationMessageReceivedHandler(async(e) => { Console.WriteLine($"Got message on topic {e.ApplicationMessage.Topic}"); var payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); Console.WriteLine($"Payload {payload}"); await HandleSensorData(e.ApplicationMessage.Topic, payload); }); }
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"); }
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); }
public MqttClient(Options options) { // Create a new MQTT client. var opt = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId($"{ClientID}_{options.ClientId}") .WithTcpServer(options.DisplayEndpoint, options.Port) .Build() ) .Build(); _mqttClient = new MqttFactory().CreateManagedMqttClient(); //_mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build()).Wait(); _mqttClient.StartAsync(opt).Wait(); _mqttClient.UseApplicationMessageReceivedHandler(ReceiveMessage); }
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; }); }
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 }); }
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 }); }
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); }
private async Task InitializeClient() { var options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId(_mqttOptions.ClientId) .WithTcpServer(_mqttOptions.Server) .WithCredentials(_mqttOptions.User, _mqttOptions.Password) .Build()) .Build(); await _client.StartAsync(options); _client.UseApplicationMessageReceivedHandler(async e => { await HandleMqttMessage(e); }); }
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); }); }
/// <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(); }; }
private async Task Consume() { var options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId("Ali_SgnlaR_Consumer") .WithCredentials("testuser", "testpass") .WithTcpServer("www.baltavista.com", 8883) .WithCleanSession(true) .Build()) .Build(); _mqttClient = new MqttFactory().CreateManagedMqttClient(); await _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("test1").Build()); await _mqttClient.StartAsync(options); _mqttClient.UseApplicationMessageReceivedHandler(e => { _hubContext.Clients.All.SendAsync("ReceiveMessage", $"({DateTime.Now}):{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); }); }