Files
HomeAssistant/ShowerMonitor.Manager/ShowerMonitorEntityService.cs
T
2026-06-28 14:22:13 +03:00

224 lines
8.2 KiB
C#

using System.Globalization;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
using ShowerMonitor.Models;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
using static ShowerMonitor.Models.ShowerMonitorConsts;
namespace ShowerMonitorManager;
public sealed class ShowerMonitorEntityService(
IEntityManager entityManager,
ILogger<ShowerMonitorEntityService> logger) : IShowerMonitorEntityService
{
private static readonly string[] CleanableEntityIds =
[
ActiveEntityId,
StateEntityId,
DifferentialEntityId,
HumidityRateEntityId,
LastShowerDurationEntityId,
LastShowerTimeEntityId,
TodaySessionCountEntityId,
CleanupButtonEntityId
];
private static object CreateDeviceBlock() => new
{
identifiers = new[] { DeviceIdentifier },
name = DeviceName,
model = DeviceName,
manufacturer = DeviceManufacturer
};
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var entities = GetAllEntities();
var createTasks = entities.Select(async entity =>
{
try
{
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
}
});
await Task.WhenAll(createTasks).ConfigureAwait(false);
}
public async Task UpdateEntitiesAsync(ShowerMonitorUpdateContext ctx, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var timestamp = DateTime.UtcNow.ToString("O");
var isActive = ctx.State is ShowerState.Active or ShowerState.Suspected;
var updateTasks = new[]
{
SetEntityStateSafe(ActiveEntityId, isActive ? "on" : "off"),
SetEntityStateSafe(StateEntityId, ctx.State.ToString().ToLowerInvariant()),
UpdateDifferentialAsync(ctx.Differential, timestamp),
UpdateHumidityRateAsync(ctx.HumidityRate, timestamp),
UpdateTodaySessionCountAsync(ctx.TodaySessionCount, timestamp),
UpdateLastShowerAsync(ctx.LastCompletedSession, timestamp)
};
await Task.WhenAll(updateTasks).ConfigureAwait(false);
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var removeTasks = CleanableEntityIds.Select(entityManager.RemoveEntity);
await Task.WhenAll(removeTasks).ConfigureAwait(false);
logger.LogInformation("ShowerMonitor entities cleaned up successfully");
}
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up ShowerMonitor entities");
throw;
}
}
private static ICollection<ShowerMonitorEntity> GetAllEntities()
{
var device = CreateDeviceBlock();
return
[
new ShowerMonitorEntity("binary_sensor", "showermonitor_active", "Shower active")
{
AdditionalConfig = new { icon = "mdi:shower-head", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_state", "Shower detection state")
{
AdditionalConfig = new { icon = "mdi:state-machine", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_differential_humidity", "Bathroom differential humidity")
{
AdditionalConfig = new { unit_of_measurement = "%", icon = "mdi:water-percent", device_class = "humidity", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_humidity_rate", "Humidity rate of change")
{
AdditionalConfig = new { unit_of_measurement = "%/min", icon = "mdi:chart-line", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_today_session_count", "Showers today")
{
AdditionalConfig = new { icon = "mdi:counter", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_last_shower_duration", "Last shower duration")
{
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_last_shower_time", "Last shower time")
{
AdditionalConfig = new { icon = "mdi:clock-outline", device }
},
new ShowerMonitorEntity("button", "showermonitor_cleanup", "Cleanup all entities")
{
AdditionalConfig = new { icon = "mdi:delete-sweep", device }
}
];
}
private async Task UpdateDifferentialAsync(double differential, string timestamp)
{
await SetEntityStateSafe(DifferentialEntityId, Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(DifferentialEntityId, new
{
unit_of_measurement = "%",
friendly_name = "Bathroom differential humidity",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task UpdateHumidityRateAsync(double rate, string timestamp)
{
await SetEntityStateSafe(HumidityRateEntityId, Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(HumidityRateEntityId, new
{
unit_of_measurement = "%/min",
friendly_name = "Humidity rate of change",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task UpdateTodaySessionCountAsync(int count, string timestamp)
{
await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(TodaySessionCountEntityId, new
{
friendly_name = "Showers today",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task UpdateLastShowerAsync(ShowerSession? session, string timestamp)
{
if (session is null)
{
return;
}
var durationSeconds = (int)session.Duration.TotalSeconds;
await SetEntityStateSafe(LastShowerDurationEntityId, durationSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(LastShowerDurationEntityId, new
{
formatted = FormatDuration(session.Duration),
peak_humidity = session.PeakHumidity,
friendly_name = "Last shower duration",
last_updated = timestamp
}).ConfigureAwait(false);
await SetEntityStateSafe(LastShowerTimeEntityId, session.StartTime.ToString("yyyy-MM-dd HH:mm:ss")).ConfigureAwait(false);
await SetEntityAttributesSafe(LastShowerTimeEntityId, new
{
friendly_name = "Last shower time",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task SetEntityStateSafe(string entityId, string state)
{
try
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
}
}
private async Task SetEntityAttributesSafe(string entityId, object attributes)
{
try
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
}
}
private static string FormatDuration(TimeSpan ts)
{
var totalMinutes = (int)ts.TotalMinutes;
var seconds = ts.Seconds;
return $"{totalMinutes}m {seconds}s";
}
}