From 742bdd3d6955aa61cf1df2022526e042fc989405 Mon Sep 17 00:00:00 2001 From: Sleevezipper Date: Fri, 29 Jan 2021 00:22:38 +0100 Subject: [PATCH] wip reworking mqtt topic --- hass-workstation-service/Communication/MQTT/MqttPublisher.cs | 3 ++- hass-workstation-service/Domain/Sensors/AbstractSensor.cs | 4 ++++ hass-workstation-service/Domain/Sensors/DummySensor.cs | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/hass-workstation-service/Communication/MQTT/MqttPublisher.cs b/hass-workstation-service/Communication/MQTT/MqttPublisher.cs index b431d90..3a9e333 100644 --- a/hass-workstation-service/Communication/MQTT/MqttPublisher.cs +++ b/hass-workstation-service/Communication/MQTT/MqttPublisher.cs @@ -95,7 +95,8 @@ namespace hass_workstation_service.Communication this._logger.LogInformation($"Message dropped because mqtt not connected: {message}"); } } - + // TODO: This should take a sensor/command instead of a config. + // Then we can ask the sensor about the topic based on ObjectId instead of referencing Name directly public async Task AnnounceAutoDiscoveryConfig(DiscoveryConfigModel config, string domain, bool clearConfig = false) { if (this._mqttClient.IsConnected) diff --git a/hass-workstation-service/Domain/Sensors/AbstractSensor.cs b/hass-workstation-service/Domain/Sensors/AbstractSensor.cs index 8c5cd50..d78eb6c 100644 --- a/hass-workstation-service/Domain/Sensors/AbstractSensor.cs +++ b/hass-workstation-service/Domain/Sensors/AbstractSensor.cs @@ -1,4 +1,5 @@ using System; +using System.Text.RegularExpressions; using System.Threading.Tasks; using hass_workstation_service.Communication; using MQTTnet; @@ -10,6 +11,9 @@ namespace hass_workstation_service.Domain.Sensors { public Guid Id { get; protected set; } public string Name { get; protected set; } + public string ObjectId { get { + return Regex.Replace(this.Name, "[^a-zA-Z0-9_-]", "_"); + } } /// /// The update interval in seconds. It checks state only if the interval has passed. /// diff --git a/hass-workstation-service/Domain/Sensors/DummySensor.cs b/hass-workstation-service/Domain/Sensors/DummySensor.cs index 3431fb5..66eaaad 100644 --- a/hass-workstation-service/Domain/Sensors/DummySensor.cs +++ b/hass-workstation-service/Domain/Sensors/DummySensor.cs @@ -20,7 +20,7 @@ namespace hass_workstation_service.Domain.Sensors Name = this.Name, Unique_id = this.Id.ToString(), Device = this.Publisher.DeviceConfigModel, - State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", + State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.ObjectId}/state", Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); }