Further improved mqtt topic handling

This commit is contained in:
Dreaded_X 2023-01-06 05:40:18 +01:00
parent 9fd3890c45
commit 03282b81c5
Signed by: Dreaded_X
GPG Key ID: 76BDEC4E165D8AD9
2 changed files with 6 additions and 4 deletions

View File

@ -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"

View File

@ -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))
},