Files
gitea_admin f919d6b25b Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
2026-12-01 12:33:31 +02:00

89 lines
3.3 KiB
C#

#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> mqttConfiguration) : IEntityManager
{
/// <summary>
/// Every topic owned by an entity created through <see cref="IMqttEntityManager" />:
/// <c>state</c>, <c>attributes</c>, <c>availability</c>, <c>set</c> and <c>config</c>.
/// The discovery config topic comes last: an empty retained payload on it is what removes the
/// entity from Home Assistant.
/// </summary>
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);
}
/// <summary>
/// Removes the entity from Home Assistant and clears every retained MQTT message it owns at the broker.
/// <para>
/// <see cref="IMqttEntityManager.RemoveAsync" /> 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 <c>mqtt.publish</c> service clears the retained
/// messages and removes the entity for good.
/// </para>
/// </summary>
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}";
}
}