public void SubscribeTopic(string topicName) { if (!SubscribedTopics.Contains(topicName)) { SubscribedTopics.Add(topicName); } }
/// <summary> /// Handler for device config change events. /// </summary> /// <param name="changeEvent">The change event to handle.</param> private async void HandleConfigSubscriptionChange(ConfigSubscriptionChangeEvent changeEvent) { // Stop listening to removed topics foreach (var topic in changeEvent.DeletedSubscriptions.Distinct()) { // Check if actually subscribed and remove MQTT subscription if (SubscribedTopics.Contains(topic)) { _log.LogInformation("MQTT unsubscribing to the following topic: {Topic}", topic); await MqttClient.UnsubscribeAsync(new List <string> { topic }); SubscribedTopics.Remove(topic); } // Check that state cache actually contains topic if (_stateCache.ContainsKey(topic)) { if (_stateCache.TryRemove(topic, out string _)) { _log.LogInformation("Successfully removed topic {Topic} from internal state cache", topic); } else { _log.LogWarning("Failed to remove topic {Topic} from internal state cache", topic); } } } // Begin listening to added topics foreach (var topic in changeEvent.AddedSubscriptions.Distinct()) { // Ensure the that state cache doesn't contain topic and add if (!_stateCache.ContainsKey(topic)) { if (_stateCache.TryAdd(topic, string.Empty)) { _log.LogInformation("Successfully added topic {Topic} to internal state cache", topic); } else { _log.LogWarning("Failed to add topic {Topic} to internal state cache", topic); } } // Check if already subscribed and subscribe to MQTT topic if (!SubscribedTopics.Contains(topic)) { _log.LogInformation("MQTT subscribing to the following topic: {Topic}", topic); await MqttClient.SubscribeAsync( new List <MqttTopicFilter> { new MqttTopicFilterBuilder() .WithTopic(topic) .WithAtLeastOnceQoS() .Build() }); SubscribedTopics.Add(topic); } } }