From 03282b81c565f8d04f7b81bdef2011290af3a8fc Mon Sep 17 00:00:00 2001 From: Dreaded_X Date: Fri, 6 Jan 2023 05:40:18 +0100 Subject: [PATCH] Further improved mqtt topic handling --- config/zeus.dev.toml | 2 +- src/config.rs | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/config/zeus.dev.toml b/config/zeus.dev.toml index e931c12..809e44a 100644 --- a/config/zeus.dev.toml +++ b/config/zeus.dev.toml @@ -11,7 +11,7 @@ password="${MQTT_PASSWORD}" topic = "${NTFY_TOPIC}" [presence] -topic = "automation_dev/presence/+" +topic = "automation_dev/presence/+/#" [hue_bridge] ip = "10.0.0.146" diff --git a/src/config.rs b/src/config.rs index 9ad8983..6763d14 100644 --- a/src/config.rs +++ b/src/config.rs @@ -123,9 +123,11 @@ pub struct PresenceDeviceConfig { impl PresenceDeviceConfig { /// Set the mqtt topic to an appropriate value if it is not already set - fn generate_topic(&mut self, identifier: &str, config: &Config) { + fn generate_topic(&mut self, class: &str, identifier: &str, config: &Config) { if self.mqtt.is_none() { - let topic = config.presence.topic.replace('+', identifier).replace('#', identifier); + // @TODO This is not perfect, if the topic is some/+/thing/# this will fail + let offset = config.presence.topic.find('+').or(config.presence.topic.find('#')).unwrap(); + let topic = config.presence.topic[..offset].to_owned() + class + "/" + identifier; trace!("Setting presence mqtt topic: {topic}"); self.mqtt = Some(MqttDeviceConfig { topic }); } @@ -219,7 +221,7 @@ impl Device { Device::ContactSensor { mqtt, mut presence } => { trace!(id = identifier, "ContactSensor [{}]", identifier); if let Some(presence) = &mut presence { - presence.generate_topic(&identifier, &config); + presence.generate_topic("contact", &identifier, &config); } Box::new(ContactSensor::new(identifier, mqtt, presence, client)) },