예제 #1
0
        /// <inheritdoc />
        protected override void Mqtt_MqttMsgPublishReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            var topic   = e.ApplicationMessage.Topic;
            var message = e.ApplicationMessage.ConvertPayloadToString();

            _log.LogInformation("MQTT message received for topic {Topic}: {Message}", topic, message);

            if (topic == TopicRoot + "/REQUEST_SYNC")
            {
                _messageHub.Publish(new RequestSyncEvent());
            }
            else if (_stateCache.TryGetValue(topic, out string currentState))
            {
                if (_stateCache.TryUpdate(topic, message, currentState))
                {
                    // Identify updated devices that handle reportState
                    var devices = _deviceRepository.GetAll()
                                  .Where(device => !device.Disabled)
                                  .Where(device => device.WillReportState)
                                  .Where(device => device.Traits.Any(trait => trait.State.Values.Any(state => state.Topic == topic)))
                                  .ToList();

                    // Trigger reportState
                    _messageHub.Publish(new ReportStateEvent {
                        Devices = devices
                    });
                }
            }
        }
        /// <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 = _deviceRepository.GetAll()
                              .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();
                }
            }
        }