Files
HomeAssistant/HomeAssistant.Entities/EntityManager.cs
T
gitea_admin 77458383d1 Add braces to single-statement guards and refactor NordPool price fetching
- Expand inline guard, return and logger blocks across the monitor services, init classes and tests
- Have INordPoolPriceService take a per-date fetch delegate and expose ParseAndAdjust, moving the HA fetch call into NordPoolInit so the service can be registered singleton
- Record the NordPool and boiler service lifetimes in AGENTS.md
- Drop the unused persisted-state argument from the boiler test data helper
2026-12-01 11:59:31 +02:00

82 lines
3.2 KiB
C#

using HomeAssistant.Entities.Interfaces;
using HomeAssistant.Models;
using HomeAssistantGenerated;
using Microsoft.Extensions.Options;
using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.HassModel;
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}";
}
}