Files
HomeAssistant/HomeAssistant.Entities/EntityManager.cs
T
gitea_admin 41ac93733e Clear Qodana findings in monitor runtime code
- Guard logger calls with IsEnabled so value-type arguments are not boxed
  when the level is disabled
- Make helper members static, narrow write-only properties to init or
  private get, and delete members no call site reaches
- Flatten nested conditionals and convert if/else chains into switch and
  ternary form
- Drop the unused *MonitorInit interfaces; NetDaemon instantiates the
  concrete app classes
- Drop the unused IConfiguration parameter from AddNordPool and
  AddPowerMonitor, and the unused IEntityManager.CreateEntitiesAsync
- Remove the ignored parameters of the boiler run-time tracker stub
- Pin the NordPool DTO price mapping explicitly so the getter use is
  visible to static analysis
- Fail Qodana on any finding and record the registration changes in
  AGENTS.md
2026-11-29 21:42:47 +02:00

85 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}";
}
}