#region using HomeAssistant.Entities.Interfaces; using HomeAssistant.Models; using HomeAssistantGenerated; using Microsoft.Extensions.Options; using NetDaemon.Extensions.MqttEntityManager; using NetDaemon.HassModel; #endregion namespace HomeAssistant.Entities; public class EntityManager( IMqttEntityManager entityManager, IHaContext haContext, IOptions mqttConfiguration) : IEntityManager { /// /// Every topic owned by an entity created through : /// state, attributes, availability, set and config. /// The discovery config topic comes last: an empty retained payload on it is what removes the /// entity from Home Assistant. /// private static readonly string[] CleanupTopicSuffixes = ["state", "attributes", "availability", "set", "config"]; public async Task CreateEntityAsync(EntityCreateModel createModel) { if (createModel.EntityId != null) { await entityManager.CreateAsync(createModel.EntityId, createModel.Options, createModel.AdditionalConfig); } } public async Task SetEntityState(string entityId, string state) { await entityManager.SetStateAsync(entityId, state); } public async Task SetEntityAttributes(string entityId, object attributes) { await entityManager.SetAttributesAsync(entityId, attributes); } /// /// Removes the entity from Home Assistant and clears every retained MQTT message it owns at the broker. /// /// publishes the empty discovery payload without the /// retain flag, so Home Assistant forgets the entity but the broker keeps the retained config and /// re-discovers the entity after a Home Assistant restart or MQTT reload. Publishing an empty /// retained payload through Home Assistant's mqtt.publish service clears the retained /// messages and removes the entity for good. /// /// public Task RemoveEntity(string entityId) { var rootTopic = BuildRootTopic(entityId, mqttConfiguration.Value.DiscoveryPrefix); foreach (var suffix in CleanupTopicSuffixes) { haContext.CallService("mqtt", "publish", null, new MqttPublishParameters { Topic = $"{rootTopic}/{suffix}", Payload = string.Empty, Retain = true }); } // IHaContext.CallService is fire-and-forget; the calls are queued in order on the HA websocket. return Task.CompletedTask; } private static string BuildRootTopic(string entityId, string discoveryPrefix) { var separatorIndex = entityId.IndexOf('.'); if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1) { throw new ArgumentException( $"Entity id '{entityId}' is not in the 'domain.object_id' format.", nameof(entityId)); } var domain = entityId[..separatorIndex]; var objectId = entityId[(separatorIndex + 1)..]; return $"{discoveryPrefix}/{domain}/{objectId}"; } }