private async Task Subscribe() { var settings = _settings.CurrentSettings; await _client.SubscribeAsync($"{settings.BaseTopic}/#"); await _client.SubscribeAsync($"{settings.HomeAssistantDiscoveryBaseTopic}/#"); }
public async Task SuscribeAync(string topic, int qos = 2) { _logger.LogInformation("o de bi"); await _client.SubscribeAsync(new TopicFilterBuilder() .WithTopic (topic) .WithQualityOfServiceLevel ((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos) .Build()); }
public async Task InitSubscription() { await _mqttClient.SubscribeAsync(GetRequestTopic("+", MqttQualityOfServiceLevel.AtMostOnce), MqttQualityOfServiceLevel.AtMostOnce); await _mqttClient.SubscribeAsync(GetRequestTopic("+", MqttQualityOfServiceLevel.AtLeastOnce), MqttQualityOfServiceLevel.AtLeastOnce); await _mqttClient.SubscribeAsync(GetRequestTopic("+", MqttQualityOfServiceLevel.ExactlyOnce), MqttQualityOfServiceLevel.ExactlyOnce); }
public Task HandleConnectedAsync(MqttClientConnectedEventArgs eventArgs) { Console.WriteLine("connected"); return(_mqttClient.SubscribeAsync( new MqttTopicFilter[] { new MqttTopicFilter() { Topic = "/client", QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce } })); }
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); }
public virtual async Task StartMqttClient() { _logger.Info("Starting MQTT client.."); _managedMqttClient = new MqttFactory().CreateManagedMqttClient(); // This is event is hit when we receive a message from the broker. _managedMqttClient.ApplicationMessageReceived += (s, a) => { var topic = a.ApplicationMessage.Topic; var decodedString = Encoding.UTF8.GetString(a.ApplicationMessage.Payload); _logger.Trace($"Message from topic '{topic}' received."); _logger.Trace($"Decoded Message: {decodedString}"); HandleMqttApplicationMessageReceived(topic, decodedString); }; // This just tells us that a message we sent was received successfully by the broker. _managedMqttClient.ApplicationMessageProcessed += (s, a) => { _logger.Trace("Client Message Processed by Broker", a); if (a.HasSucceeded == false) { // TODO: What to do here? // Add to a file? And retry later? } }; await _managedMqttClient.SubscribeAsync(new List <TopicFilter> { new TopicFilterBuilder().WithTopic(_moduleConfiguration.MqttValuePushTopic).WithAtLeastOnceQoS().Build() }); await _managedMqttClient.StartAsync(GetMqttClientOptions()); }
public async Task Start() { await _mqttClient.SubscribeAsync( new TopicFilterBuilder() .WithTopic($"{_commandTopic}/#") .Build()); }
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) { } }
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); }
public void SubscribeTopic(List <MqttTopicFilter> listTopic) { try { if (!client.IsConnected) { Log.Debug("MQTT客户端尚未连接!"); return; } if (listTopic.Count <= 0) { Log.Debug("订阅主题不能为空!"); return; } // 订阅Topic client.SubscribeAsync(listTopic.ToArray()).Wait(); foreach (MqttTopicFilter mqttTopicFilter in listTopic) { Log.Debug($"topic : [{mqttTopicFilter.Topic}] is subscribed success"); } } catch (Exception ex) { foreach (MqttTopicFilter mqttTopicFilter in listTopic) { Log.Debug($"topic : [{mqttTopicFilter.Topic}] is subscribed fail"); } } }
private async Task SubscribeAsync(String topic, byte qos) { MqttQualityOfServiceLevel mqttQos; switch (qos) { case 0: mqttQos = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce; break; case 1: mqttQos = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce; break; case 2: mqttQos = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce; break; default: throw new Exception("Invalid Qos value (0-2)."); } if (string.IsNullOrEmpty(topic)) { throw new Exception("Topic cannot be empty."); } await MqttClient.SubscribeAsync( new MqttTopicFilterBuilder() .WithTopic(topic) .WithQualityOfServiceLevel(mqttQos) .Build() ); }
/// <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 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(); }
private async void Subscribe(object sender, RoutedEventArgs e) { try { var qos = MqttQualityOfServiceLevel.AtMostOnce; if (SubscribeQoS1.IsChecked == true) { qos = MqttQualityOfServiceLevel.AtLeastOnce; } if (SubscribeQoS2.IsChecked == true) { qos = MqttQualityOfServiceLevel.ExactlyOnce; } var topicFilter = new TopicFilter { Topic = SubscribeTopic.Text, QualityOfServiceLevel = qos }; if (_mqttClient != null) { await _mqttClient.SubscribeAsync(topicFilter); } if (_managedMqttClient != null) { await _managedMqttClient.SubscribeAsync(topicFilter); } } catch (Exception exception) { Trace.Text += exception + Environment.NewLine; } }
public async Task SubscribeAsync(string topic, int qos = 1) { await client.SubscribeAsync(new TopicFilterBuilder() .WithTopic(topic) .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos) .Build()); }
public async void SubcribeTopic(string topic) { await client.SubscribeAsync(new MqttTopicFilter { Topic = topic }); }
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(); }
async void Connected(object sender, MqttClientConnectedEventArgs e) { logger.Debug("Mqqtclient Connected to server"); // Subscribe to a topic await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(MQTTRoot + "/#").Build()); }
public async Task HandleConnectedAsync(MqttClientConnectedEventArgs eventArgs) { System.Console.WriteLine("Agent-Broker connected"); await hubContext.Clients.All.AgentConnectionStatus(true); await mqttClient.SubscribeAsync("#"); }
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); } }
public void Subscribe(string subscription) { if (!ranOnce) { return; } client.SubscribeAsync(new TopicFilterBuilder().WithTopic(subscription).WithExactlyOnceQoS().Build()); }
/// <summary> /// Subscribe to one or more topics. /// </summary> /// <param name="topics">The topics to subscribe to.</param> public async Task SubscribeAsync(TopicFilter[] topics) { if (_managedMqttClient == null) { throw new MqttConnectionException("Connection not open, please use StartAsync first!"); } await _managedMqttClient.SubscribeAsync(topics).ConfigureAwait(false); }
public async Task StartAsync(CancellationToken cancellationToken) { await _mqttClient.StartAsync(_options); await _mqttClient.SubscribeAsync(_zigbeeEvents.BridgeState); await _mqttClient.SubscribeAsync(_zigbeeEvents.BridgeLog); await _mqttClient.SubscribeAsync(_zigbeeEvents.ConnectedDevices); await _mqttClient.SubscribeAsync(_brokerEvents.NewClientConnected); await _mqttClient.SubscribeAsync(_brokerEvents.NewClientDisconnected); using (var scope = _serviceScopeFactory.CreateScope()) { var mediator = scope.ServiceProvider.GetService <IMediator>(); var messages = await mediator.Send(new GetAllMqttSubscriptionMessagesQuery()); if (messages != null) { foreach (var message in messages) { await _mqttClient.SubscribeAsync(message.Topic); } } } }
public static async Task SubscribeAsync(string topic, int qos = 1) { var topicFilter = new MqttTopicFilterBuilder() .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos) .WithTopic(topic) .Build(); await _client.SubscribeAsync(topicFilter); }
public static void Subscribe(string strTopicFormat, params object[] strParams) { Logging.WriteDebugLog("MQTT.Subscribe() {0}", string.Format(strTopicFormat, strParams)); if (_mqtt != null) { _mqtt.SubscribeAsync(string.Format(strTopicFormat, strParams)); } }
public static Task SubscribeAsync(this IManagedMqttClient managedClient, params TopicFilter[] topicFilters) { if (managedClient == null) { throw new ArgumentNullException(nameof(managedClient)); } return(managedClient.SubscribeAsync(topicFilters)); }
public async Task SubscribeAsync(string topic) { await _mqttClient.SubscribeAsync(new List <MqttTopicFilter>() { new MqttTopicFilter() { Topic = topic, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce } }); await Task.Delay(TimeSpan.FromSeconds(1)); }
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 async void ManagedClient_Connected(object sender, MqttClientConnectedEventArgs e) { logger.Log("*** Connected with MQTT server ***"); await managedClient.SubscribeAsync(new TopicFilterBuilder() .WithTopic(MQTT_TOPIC).Build()); managedClient.ApplicationMessageReceived += ManagedClient_ApplicationMessageReceived; }
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)); }