/// <inheritdoc /> protected override void Mqtt_MqttMsgPublishReceived(object sender, MqttApplicationMessageReceivedEventArgs e) { var message = e.ApplicationMessage.ConvertPayloadToString(); _log.LogInformation("MQTT message received for topic " + e.ApplicationMessage.Topic + ": " + message); if (e.ApplicationMessage.Topic == TopicRoot + "REQUEST_SYNC") { // Handle REQUEST_SYNC _googleHomeGraphClient.RequestSyncAsync() .GetAwaiter().GetResult(); } else if (_stateCache.ContainsKey(e.ApplicationMessage.Topic)) { _stateCache[e.ApplicationMessage.Topic] = message; // Identify devices that handle reportState var devices = _deviceConfig.Values .Where(x => x.WillReportState) .Where(x => x.Traits.Any(trait => trait.State.Values.Any(state => state.Topic == e.ApplicationMessage.Topic))) .ToList(); // Send updated to Google Home Graph if (devices.Count() > 0) { _googleHomeGraphClient.SendUpdatesAsync(devices, _stateCache) .GetAwaiter().GetResult(); } } }
/// <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); } } }