diff --git a/.gitignore b/.gitignore index 3e7dc38..227db7a 100644 --- a/.gitignore +++ b/.gitignore @@ -108,3 +108,6 @@ ServiceFabricBackup/ # Sensitive / local config (uncomment if you use appsettings.local.json etc.) # appsettings.*.local.json # *.local.json + +# Cursor MCP config (contains secrets) +.cursor/mcp.json diff --git a/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj b/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj new file mode 100644 index 0000000..92c8040 --- /dev/null +++ b/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj @@ -0,0 +1,34 @@ + + + + net10.0 + enable + enable + false + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs b/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs new file mode 100644 index 0000000..17eb02e --- /dev/null +++ b/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs @@ -0,0 +1,143 @@ +using FluentAssertions; +using Microsoft.Extensions.Logging; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using BatteryMonitor.Models; +using BatteryMonitorManager; + +namespace BatteryMonitor.Manager.Tests; + +public class BatteryNotificationServiceTests +{ + private readonly Mock _haContextMock; + private readonly Mock> _loggerMock; + + public BatteryNotificationServiceTests() + { + _haContextMock = new Mock(); + _loggerMock = new Mock>(); + } + + private BatteryNotificationService CreateSut() + { + return new BatteryNotificationService(_haContextMock.Object, _loggerMock.Object); + } + + #region NotifyLowBattery + + [Fact] + public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate() + { + var devices = new List + { + new() { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", BatteryLevel = 3 }, + new() { EntityId = "sensor.bedroom_battery", FriendlyName = "Bedroom Battery", BatteryLevel = 1 } + }; + + var sut = CreateSut(); + sut.NotifyLowBattery(devices); + + _haContextMock.Verify(h => h.CallService( + BatteryMonitorConsts.PersistentNotificationDomain, + BatteryMonitorConsts.PersistentNotificationCreateService, + It.IsAny(), + It.IsAny()), Times.Once); + } + + [Fact] + public void NotifyLowBattery_WithEmptyList_ShouldNotCallService() + { + var devices = new List(); + + var sut = CreateSut(); + sut.NotifyLowBattery(devices); + + _haContextMock.Verify(h => h.CallService( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny()), Times.Never); + } + + #endregion + + #region DismissNotification + + [Fact] + public void DismissNotification_ShouldCallPersistentNotificationDismiss() + { + var sut = CreateSut(); + sut.DismissNotification(); + + _haContextMock.Verify(h => h.CallService( + BatteryMonitorConsts.PersistentNotificationDomain, + BatteryMonitorConsts.PersistentNotificationDismissService, + It.IsAny(), + It.IsAny()), Times.Once); + } + + #endregion + + #region BuildNotificationMessage + + [Fact] + public void BuildNotificationMessage_ShouldOrderByBatteryLevel() + { + var devices = new List + { + new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 4 }, + new() { EntityId = "sensor.b", FriendlyName = "Device B", BatteryLevel = 1 }, + new() { EntityId = "sensor.c", FriendlyName = "Device C", BatteryLevel = 3 } + }; + + var message = BatteryNotificationService.BuildNotificationMessage(devices); + + var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); + lines[1].Should().Contain("Device B"); + lines[2].Should().Contain("Device C"); + lines[3].Should().Contain("Device A"); + } + + [Fact] + public void BuildNotificationMessage_ShouldContainTitle() + { + var devices = new List + { + new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 2 } + }; + + var message = BatteryNotificationService.BuildNotificationMessage(devices); + + message.Should().Contain("low battery"); + } + + [Fact] + public void BuildNotificationMessage_ShouldContainDeviceNameAndLevel() + { + var devices = new List + { + new() { EntityId = "sensor.a", FriendlyName = "Bathroom Battery", BatteryLevel = 3 } + }; + + var message = BatteryNotificationService.BuildNotificationMessage(devices); + + message.Should().Contain("Bathroom Battery"); + message.Should().Contain("3%"); + } + + [Fact] + public void BuildNotificationMessage_WithSingleDevice_ShouldFormatCorrectly() + { + var devices = new List + { + new() { EntityId = "sensor.a", FriendlyName = "Test Device", BatteryLevel = 1 } + }; + + var message = BatteryNotificationService.BuildNotificationMessage(devices); + + message.Should().Contain("- **Test Device**: 1%"); + } + + #endregion +} diff --git a/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs b/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs new file mode 100644 index 0000000..d9566c2 --- /dev/null +++ b/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs @@ -0,0 +1,322 @@ +using System.Text.Json; +using FluentAssertions; +using Microsoft.Extensions.Logging; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using BatteryMonitorManager; +using BatteryMonitor.Models; + +namespace BatteryMonitor.Manager.Tests; + +public class BatterySensorDiscoveryServiceTests +{ + private readonly Mock _haContextMock; + private readonly Mock> _loggerMock; + + public BatterySensorDiscoveryServiceTests() + { + _haContextMock = new Mock(); + _loggerMock = new Mock>(); + } + + private BatterySensorDiscoveryService CreateSut() + { + return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object); + } + + private void SetupEntities(params (string entityId, string? deviceClass, string? state, string? friendlyName)[] entities) + { + var entityList = new List(); + + foreach (var (entityId, deviceClass, state, friendlyName) in entities) + { + var attributes = new Dictionary(); + if (deviceClass is not null) + { + attributes["device_class"] = deviceClass; + } + + if (friendlyName is not null) + { + attributes["friendly_name"] = friendlyName; + } + + var attributesJson = JsonSerializer.SerializeToElement(attributes); + var entityState = new EntityState { AttributesJson = attributesJson, State = state }; + + _haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState); + + var entity = new Entity(_haContextMock.Object, entityId); + entityList.Add(entity); + } + + _haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList); + } + + #region Discovery + + [Fact] + public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "3", "Bathroom Battery"), + ("sensor.bedroom_battery", "battery", "80", "Bedroom Battery"), + ("sensor.boiler_temp_battery", "battery", "2", "Boiler Temp Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(2); + result.Should().Contain(s => s.EntityId == "sensor.bathroom_battery"); + result.Should().Contain(s => s.EntityId == "sensor.boiler_temp_battery"); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldExcludePhoneDevices() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"), + ("sensor.erikas_iphone_battery_level", "battery", "1", "Erika's iPhone Battery"), + ("sensor.home_phone_battery_state", "battery", "3", "Home Phone Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(1); + result.First().EntityId.Should().Be("sensor.bathroom_battery"); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldExcludeWatchDevices() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"), + ("sensor.marius_watch_battery_level", "battery", "1", "Marius Watch Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(1); + result.First().EntityId.Should().Be("sensor.bathroom_battery"); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldExcludeGalaxyDevices() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"), + ("sensor.sm_s936b_battery_level", "battery", "1", "Galaxy S24 Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(1); + result.First().EntityId.Should().Be("sensor.bathroom_battery"); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldIgnoreNonSensorDomain() + { + SetupEntities( + ("binary_sensor.bathroom_battery", "battery", "2", "Bathroom Battery"), + ("sensor.bedroom_battery", "battery", "3", "Bedroom Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(1); + result.First().EntityId.Should().Be("sensor.bedroom_battery"); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldIgnoreNonBatteryDeviceClass() + { + SetupEntities( + ("sensor.bathroom_temperature", "temperature", "2", "Bathroom Temperature"), + ("sensor.bedroom_battery", "battery", "3", "Bedroom Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(1); + result.First().EntityId.Should().Be("sensor.bedroom_battery"); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldSkipUnavailableState() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "unavailable", "Bathroom Battery"), + ("sensor.bedroom_battery", "battery", "3", "Bedroom Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(1); + result.First().EntityId.Should().Be("sensor.bedroom_battery"); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldSkipUnknownState() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "unknown", "Bathroom Battery"), + ("sensor.bedroom_battery", "battery", "3", "Bedroom Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(1); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldSkipNonParsableState() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "not_a_number", "Bathroom Battery"), + ("sensor.bedroom_battery", "battery", "3", "Bedroom Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(1); + result.First().EntityId.Should().Be("sensor.bedroom_battery"); + } + + [Fact] + public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty() + { + SetupEntities( + ("sensor.temperature", "temperature", "22", "Temperature"), + ("switch.some_switch", null, "on", "Switch") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().BeEmpty(); + } + + [Fact] + public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "50", "Bathroom Battery"), + ("sensor.bedroom_battery", "battery", "80", "Bedroom Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().BeEmpty(); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldRespectCustomThreshold() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "15", "Bathroom Battery"), + ("sensor.bedroom_battery", "battery", "25", "Bedroom Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(20); + + result.Should().HaveCount(1); + result.First().EntityId.Should().Be("sensor.bathroom_battery"); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldPopulateFriendlyName() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "2", "Bathroom Battery") + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(1); + result.First().FriendlyName.Should().Be("Bathroom Battery"); + result.First().BatteryLevel.Should().Be(2); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldUseEntityIdWhenNoFriendlyName() + { + SetupEntities( + ("sensor.bathroom_battery", "battery", "2", null) + ); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().HaveCount(1); + result.First().FriendlyName.Should().Be("sensor.bathroom_battery"); + } + + #endregion + + #region IsBatterySensor + + [Fact] + public void IsBatterySensor_WithBatteryDeviceClass_ShouldReturnTrue() + { + SetupEntities(("sensor.bathroom_battery", "battery", "50", "Bathroom Battery")); + var entity = new Entity(_haContextMock.Object, "sensor.bathroom_battery"); + + BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeTrue(); + } + + [Fact] + public void IsBatterySensor_WithNonSensorDomain_ShouldReturnFalse() + { + SetupEntities(("binary_sensor.bathroom_battery", "battery", "50", "Bathroom Battery")); + var entity = new Entity(_haContextMock.Object, "binary_sensor.bathroom_battery"); + + BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse(); + } + + [Fact] + public void IsBatterySensor_WithNonBatteryDeviceClass_ShouldReturnFalse() + { + SetupEntities(("sensor.bathroom_temperature", "temperature", "22", "Bathroom Temperature")); + var entity = new Entity(_haContextMock.Object, "sensor.bathroom_temperature"); + + BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse(); + } + + #endregion + + #region IsExcludedDevice + + [Theory] + [InlineData("sensor.erikas_iphone_battery_level", true)] + [InlineData("sensor.home_phone_battery_state", true)] + [InlineData("sensor.marius_watch_battery_level", true)] + [InlineData("sensor.sm_s936b_battery_level", true)] + [InlineData("sensor.sm_a536b_battery_level", true)] + [InlineData("sensor.pixel_8_battery_level", true)] + [InlineData("sensor.oneplus_battery_level", true)] + [InlineData("sensor.ipad_battery_level", true)] + [InlineData("sensor.galaxy_s24_battery", true)] + [InlineData("sensor.bathroom_battery", false)] + [InlineData("sensor.boiler_temp_battery", false)] + [InlineData("sensor.aquarium_leak_sensor_battery", false)] + public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected) + { + BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected); + } + + #endregion +} diff --git a/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj b/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj new file mode 100644 index 0000000..da25952 --- /dev/null +++ b/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + enable + enable + BatteryMonitorManager + + + + + <_Parameter1>BatteryMonitor.Manager.Tests + + + + + + + + + + + + + + + diff --git a/BatteryMonitor.Manager/BatteryMonitorInit.cs b/BatteryMonitor.Manager/BatteryMonitorInit.cs new file mode 100644 index 0000000..08013b7 --- /dev/null +++ b/BatteryMonitor.Manager/BatteryMonitorInit.cs @@ -0,0 +1,98 @@ +using System.Reactive.Concurrency; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NetDaemon.AppModel; +using NetDaemon.Extensions.Scheduler; +using BatteryMonitorManager.Interface; +using BatteryMonitorManager.Models; + +namespace BatteryMonitorManager; + +[NetDaemonApp] +public sealed class BatteryMonitorInit : IBatteryMonitorInit +{ + private readonly ILogger _logger; + private readonly IScheduler _scheduler; + private readonly IBatterySensorDiscoveryService _discoveryService; + private readonly IBatteryNotificationService _notificationService; + private readonly BatteryMonitorOptions _options; + + public BatteryMonitorInit( + ILogger logger, + IScheduler scheduler, + IBatterySensorDiscoveryService discoveryService, + IBatteryNotificationService notificationService, + IOptions options) + { + _logger = logger; + _scheduler = scheduler; + _discoveryService = discoveryService; + _notificationService = notificationService; + _options = options.Value; + + _ = InitializeAndScheduleAsync(); + } + + private async Task InitializeAndScheduleAsync() + { + try + { + await InitializeAsync(); + ScheduleDailyCheck(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during BatteryMonitor initialization and scheduling"); + } + } + + public async Task InitializeAsync() + { + try + { + await Task.Delay(TimeSpan.FromSeconds(3)); + + CheckAndNotify(); + + _logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error initializing BatteryMonitor"); + throw; + } + } + + private void ScheduleDailyCheck() + { + _scheduler.ScheduleCron(BatteryMonitor.Models.BatteryMonitorConsts.DailyCheckCron, () => + { + try + { + _logger.LogInformation("Running scheduled daily battery check"); + CheckAndNotify(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during scheduled battery check"); + } + }); + + _logger.LogInformation("Scheduled daily battery check at 08:00"); + } + + internal void CheckAndNotify() + { + var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent); + + if (lowBatteryDevices.Count > 0) + { + _notificationService.NotifyLowBattery(lowBatteryDevices); + } + else + { + _notificationService.DismissNotification(); + _logger.LogDebug("No low battery devices found"); + } + } +} diff --git a/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs b/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs new file mode 100644 index 0000000..aa1e2d2 --- /dev/null +++ b/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs @@ -0,0 +1,29 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NetDaemon.AppModel; +using BatteryMonitorManager.Interface; +using BatteryMonitorManager.Models; + +namespace BatteryMonitorManager; + +public static class BatteryMonitorServiceRegistration +{ + public static IServiceCollection AddBatteryMonitor(this IServiceCollection services, IConfiguration configuration) + { + var options = configuration + .GetSection(BatteryMonitorOptions.SectionName) + .Get() ?? new BatteryMonitorOptions(); + + if (!options.Enabled) + { + return services; + } + + services + .AddNetDaemonApp() + .AddScoped() + .AddScoped(); + + return services; + } +} diff --git a/BatteryMonitor.Manager/BatteryNotificationService.cs b/BatteryMonitor.Manager/BatteryNotificationService.cs new file mode 100644 index 0000000..558255e --- /dev/null +++ b/BatteryMonitor.Manager/BatteryNotificationService.cs @@ -0,0 +1,72 @@ +using System.Text; +using Microsoft.Extensions.Logging; +using NetDaemon.HassModel; +using BatteryMonitor.Models; +using BatteryMonitorManager.Interface; + +namespace BatteryMonitorManager; + +public sealed class BatteryNotificationService : IBatteryNotificationService +{ + private readonly IHaContext _haContext; + private readonly ILogger _logger; + + public BatteryNotificationService( + IHaContext haContext, + ILogger logger) + { + _haContext = haContext; + _logger = logger; + } + + public void NotifyLowBattery(IReadOnlyList lowBatteryDevices) + { + if (lowBatteryDevices.Count == 0) + { + return; + } + + var message = BuildNotificationMessage(lowBatteryDevices); + + _haContext.CallService( + BatteryMonitorConsts.PersistentNotificationDomain, + BatteryMonitorConsts.PersistentNotificationCreateService, + data: new + { + title = BatteryMonitorConsts.NotificationTitle, + message, + notification_id = BatteryMonitorConsts.NotificationId + }); + + _logger.LogInformation( + "Sent low battery notification for {Count} device(s)", + lowBatteryDevices.Count); + } + + public void DismissNotification() + { + _haContext.CallService( + BatteryMonitorConsts.PersistentNotificationDomain, + BatteryMonitorConsts.PersistentNotificationDismissService, + data: new + { + notification_id = BatteryMonitorConsts.NotificationId + }); + + _logger.LogDebug("Dismissed low battery notification"); + } + + internal static string BuildNotificationMessage(IReadOnlyList devices) + { + var sb = new StringBuilder(); + sb.AppendLine("The following devices have low battery:"); + sb.AppendLine(); + + foreach (var device in devices.OrderBy(d => d.BatteryLevel)) + { + sb.AppendLine($"- **{device.FriendlyName}**: {device.BatteryLevel:F0}%"); + } + + return sb.ToString().TrimEnd(); + } +} diff --git a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs new file mode 100644 index 0000000..9d1553c --- /dev/null +++ b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs @@ -0,0 +1,105 @@ +using System.Globalization; +using System.Text.Json; +using Microsoft.Extensions.Logging; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using BatteryMonitor.Models; +using BatteryMonitorManager.Interface; + +namespace BatteryMonitorManager; + +public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryService +{ + private readonly IHaContext _haContext; + private readonly ILogger _logger; + + public BatterySensorDiscoveryService( + IHaContext haContext, + ILogger logger) + { + _haContext = haContext; + _logger = logger; + } + + public IReadOnlyList DiscoverLowBatterySensors(int thresholdPercent) + { + var allEntities = _haContext.GetAllEntities(); + + var lowBatterySensors = allEntities + .Where(IsBatterySensor) + .Where(e => !IsExcludedDevice(e.EntityId)) + .Select(e => TryCreateSensorInfo(e, thresholdPercent)) + .Where(info => info is not null) + .ToList(); + + _logger.LogInformation( + "Battery check: found {Count} sensors below {Threshold}%", + lowBatterySensors.Count, thresholdPercent); + + return lowBatterySensors!; + } + + internal static bool IsBatterySensor(Entity entity) + { + if (!entity.EntityId.StartsWith(BatteryMonitorConsts.SensorDomainPrefix, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + var deviceClass = GetJsonStringProperty(entity.EntityState?.AttributesJson, "device_class"); + + return string.Equals(deviceClass, BatteryMonitorConsts.BatteryDeviceClass, StringComparison.OrdinalIgnoreCase); + } + + internal static bool IsExcludedDevice(string entityId) + { + var lowerEntityId = entityId.ToLowerInvariant(); + + return BatteryMonitorConsts.ExcludedKeywords + .Any(keyword => lowerEntityId.Contains(keyword, StringComparison.OrdinalIgnoreCase)); + } + + private BatterySensorInfo? TryCreateSensorInfo(Entity entity, int thresholdPercent) + { + var state = entity.EntityState?.State; + + if (state is null or "unavailable" or "unknown") + { + _logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, state ?? "null"); + return null; + } + + if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel)) + { + _logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, state); + return null; + } + + if (batteryLevel >= thresholdPercent) + { + return null; + } + + var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") + ?? entity.EntityId; + + return new BatterySensorInfo + { + EntityId = entity.EntityId, + FriendlyName = friendlyName, + BatteryLevel = batteryLevel + }; + } + + internal static string? GetJsonStringProperty(JsonElement? element, string propertyName) + { + if (element is null) + { + return null; + } + + return element.Value.TryGetProperty(propertyName, out var value) + ? value.GetString() + : null; + } +} diff --git a/BatteryMonitor.Manager/Interface/IBatteryMonitorInit.cs b/BatteryMonitor.Manager/Interface/IBatteryMonitorInit.cs new file mode 100644 index 0000000..14678e4 --- /dev/null +++ b/BatteryMonitor.Manager/Interface/IBatteryMonitorInit.cs @@ -0,0 +1,6 @@ +namespace BatteryMonitorManager.Interface; + +public interface IBatteryMonitorInit +{ + Task InitializeAsync(); +} diff --git a/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs b/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs new file mode 100644 index 0000000..0b6ff0d --- /dev/null +++ b/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs @@ -0,0 +1,10 @@ +using BatteryMonitor.Models; + +namespace BatteryMonitorManager.Interface; + +public interface IBatteryNotificationService +{ + void NotifyLowBattery(IReadOnlyList lowBatteryDevices); + + void DismissNotification(); +} diff --git a/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs b/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs new file mode 100644 index 0000000..66e1f60 --- /dev/null +++ b/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs @@ -0,0 +1,8 @@ +using BatteryMonitor.Models; + +namespace BatteryMonitorManager.Interface; + +public interface IBatterySensorDiscoveryService +{ + IReadOnlyList DiscoverLowBatterySensors(int thresholdPercent); +} diff --git a/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs b/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs new file mode 100644 index 0000000..66ab3ca --- /dev/null +++ b/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs @@ -0,0 +1,12 @@ +using BatteryMonitor.Models; + +namespace BatteryMonitorManager.Models; + +public sealed class BatteryMonitorOptions +{ + public const string SectionName = "BatteryMonitor"; + + public bool Enabled { get; set; } + + public int BatteryThresholdPercent { get; set; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent; +} diff --git a/BatteryMonitor.Models/BatteryMonitor.Models.csproj b/BatteryMonitor.Models/BatteryMonitor.Models.csproj new file mode 100644 index 0000000..570ba3f --- /dev/null +++ b/BatteryMonitor.Models/BatteryMonitor.Models.csproj @@ -0,0 +1,10 @@ + + + + net10.0 + enable + enable + BatteryMonitor.Models + + + diff --git a/BatteryMonitor.Models/BatteryMonitorConsts.cs b/BatteryMonitor.Models/BatteryMonitorConsts.cs new file mode 100644 index 0000000..0fb47e4 --- /dev/null +++ b/BatteryMonitor.Models/BatteryMonitorConsts.cs @@ -0,0 +1,35 @@ +namespace BatteryMonitor.Models; + +public static class BatteryMonitorConsts +{ + public const int DefaultBatteryThresholdPercent = 5; + + public const string BatteryDeviceClass = "battery"; + + public const string SensorDomainPrefix = "sensor."; + + public const string NotificationId = "battery_monitor_low_battery"; + + public const string NotificationTitle = "Low Battery Alert"; + + public const string PersistentNotificationDomain = "persistent_notification"; + + public const string PersistentNotificationCreateService = "create"; + + public const string PersistentNotificationDismissService = "dismiss"; + + public const string DailyCheckCron = "0 8 * * *"; + + public static readonly string[] ExcludedKeywords = + [ + "iphone", + "phone", + "watch", + "galaxy", + "sm_s", + "sm_a", + "pixel", + "oneplus", + "ipad" + ]; +} diff --git a/BatteryMonitor.Models/BatterySensorInfo.cs b/BatteryMonitor.Models/BatterySensorInfo.cs new file mode 100644 index 0000000..fede27b --- /dev/null +++ b/BatteryMonitor.Models/BatterySensorInfo.cs @@ -0,0 +1,10 @@ +namespace BatteryMonitor.Models; + +public sealed class BatterySensorInfo +{ + public required string EntityId { get; init; } + + public required string FriendlyName { get; init; } + + public required double BatteryLevel { get; init; } +} diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs index c295c48..c9aead4 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs @@ -10,8 +10,8 @@ public class BoilerMonitorConfigTests { var config = new BoilerMonitorConfig { - BoilerPowerEntityId = "sensor.power", - BoilerSwitchEntityId = "switch.boiler", + BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", + BoilerSwitchEntityId = "switch.sonoff_1002230e32", PollIntervalSeconds = 30, HeatingPowerThresholdWatts = 5.0 }; @@ -25,7 +25,7 @@ public class BoilerMonitorConfigTests var config = new BoilerMonitorConfig { BoilerPowerEntityId = null, - BoilerSwitchEntityId = "switch.boiler", + BoilerSwitchEntityId = "switch.sonoff_1002230e32", PollIntervalSeconds = 30, HeatingPowerThresholdWatts = 5.0 }; @@ -38,7 +38,7 @@ public class BoilerMonitorConfigTests { var config = new BoilerMonitorConfig { - BoilerPowerEntityId = "sensor.power", + BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", BoilerSwitchEntityId = null, PollIntervalSeconds = 30, HeatingPowerThresholdWatts = 5.0 @@ -52,8 +52,8 @@ public class BoilerMonitorConfigTests { var config = new BoilerMonitorConfig { - BoilerPowerEntityId = "sensor.power", - BoilerSwitchEntityId = "switch.boiler", + BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", + BoilerSwitchEntityId = "switch.sonoff_1002230e32", PollIntervalSeconds = null, HeatingPowerThresholdWatts = 5.0 }; @@ -66,8 +66,8 @@ public class BoilerMonitorConfigTests { var config = new BoilerMonitorConfig { - BoilerPowerEntityId = "sensor.power", - BoilerSwitchEntityId = "switch.boiler", + BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", + BoilerSwitchEntityId = "switch.sonoff_1002230e32", PollIntervalSeconds = 30, HeatingPowerThresholdWatts = null }; @@ -81,7 +81,7 @@ public class BoilerMonitorConfigTests var config = new BoilerMonitorConfig { BoilerPowerEntityId = " ", - BoilerSwitchEntityId = "switch.boiler", + BoilerSwitchEntityId = "switch.sonoff_1002230e32", PollIntervalSeconds = 30, HeatingPowerThresholdWatts = 5.0 }; @@ -94,8 +94,8 @@ public class BoilerMonitorConfigTests { var config = new BoilerMonitorConfig { - BoilerPowerEntityId = "sensor.power", - BoilerSwitchEntityId = "switch.boiler", + BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", + BoilerSwitchEntityId = "switch.sonoff_1002230e32", PollIntervalSeconds = 0, HeatingPowerThresholdWatts = 5.0 }; @@ -108,8 +108,8 @@ public class BoilerMonitorConfigTests { var config = new BoilerMonitorConfig { - BoilerPowerEntityId = "sensor.power", - BoilerSwitchEntityId = "switch.boiler", + BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", + BoilerSwitchEntityId = "switch.sonoff_1002230e32", PollIntervalSeconds = 30, HeatingPowerThresholdWatts = 0.0 }; @@ -122,8 +122,8 @@ public class BoilerMonitorConfigTests { var config = new BoilerMonitorConfig { - BoilerPowerEntityId = "sensor.power", - BoilerSwitchEntityId = "switch.boiler", + BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", + BoilerSwitchEntityId = "switch.sonoff_1002230e32", PollIntervalSeconds = -1, HeatingPowerThresholdWatts = 5.0 }; diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs index 7f3a88a..5df0bce 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs @@ -48,8 +48,8 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues() { // Arrange - SetupEntityState(TodayRuntimeEntityId, "3600"); - SetupEntityState(SessionCountEntityId, "5"); + SetupEntityState(TodayRuntimeEntityId, "7200"); + SetupEntityState(SessionCountEntityId, "3"); SetupEntityState(SkipPriceCapEntityId, "ON"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -58,8 +58,8 @@ public class BoilerMonitorEntityServiceTests // Assert result.Should().NotBeNull(); - result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(3600)); - result.SessionCount.Should().Be(5); + result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(7200)); + result.SessionCount.Should().Be(3); result.SkipPriceCapState.Should().Be("ON"); result.BudgetOverrideState.Should().Be("OFF"); } @@ -87,7 +87,7 @@ public class BoilerMonitorEntityServiceTests { // Arrange SetupEntityState(TodayRuntimeEntityId, "unavailable"); - SetupEntityState(SessionCountEntityId, "5"); + SetupEntityState(SessionCountEntityId, "3"); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -103,7 +103,7 @@ public class BoilerMonitorEntityServiceTests { // Arrange SetupEntityState(TodayRuntimeEntityId, "unknown"); - SetupEntityState(SessionCountEntityId, "3"); + SetupEntityState(SessionCountEntityId, "2"); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -118,7 +118,7 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WhenSessionCountIsUnavailable_ShouldReturnNull() { // Arrange - SetupEntityState(TodayRuntimeEntityId, "1800"); + SetupEntityState(TodayRuntimeEntityId, "3600"); SetupEntityState(SessionCountEntityId, "unavailable"); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -135,7 +135,7 @@ public class BoilerMonitorEntityServiceTests { // Arrange SetupEntityState(TodayRuntimeEntityId, null); - SetupEntityState(SessionCountEntityId, "3"); + SetupEntityState(SessionCountEntityId, "2"); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -150,7 +150,7 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WhenSessionCountEntityDoesNotExist_ShouldReturnNull() { // Arrange - SetupEntityState(TodayRuntimeEntityId, "1800"); + SetupEntityState(TodayRuntimeEntityId, "3600"); SetupEntityState(SessionCountEntityId, null); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -167,7 +167,7 @@ public class BoilerMonitorEntityServiceTests { // Arrange SetupEntityState(TodayRuntimeEntityId, "not_a_number"); - SetupEntityState(SessionCountEntityId, "3"); + SetupEntityState(SessionCountEntityId, "2"); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -182,7 +182,7 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WhenSessionCountIsNonNumeric_ShouldReturnNull() { // Arrange - SetupEntityState(TodayRuntimeEntityId, "1800"); + SetupEntityState(TodayRuntimeEntityId, "3600"); SetupEntityState(SessionCountEntityId, "abc"); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -199,7 +199,7 @@ public class BoilerMonitorEntityServiceTests { // Arrange SetupEntityState(TodayRuntimeEntityId, "-100"); - SetupEntityState(SessionCountEntityId, "3"); + SetupEntityState(SessionCountEntityId, "2"); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -214,7 +214,7 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WhenSessionCountIsNegative_ShouldReturnNull() { // Arrange - SetupEntityState(TodayRuntimeEntityId, "1800"); + SetupEntityState(TodayRuntimeEntityId, "3600"); SetupEntityState(SessionCountEntityId, "-1"); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -230,8 +230,8 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WhenSwitchEntitiesAreNull_ShouldStillReturnWithNullSwitchStates() { // Arrange - SetupEntityState(TodayRuntimeEntityId, "900"); - SetupEntityState(SessionCountEntityId, "2"); + SetupEntityState(TodayRuntimeEntityId, "1800"); + SetupEntityState(SessionCountEntityId, "1"); SetupEntityState(SkipPriceCapEntityId, null); SetupEntityState(BudgetOverrideEntityId, null); @@ -240,8 +240,8 @@ public class BoilerMonitorEntityServiceTests // Assert result.Should().NotBeNull(); - result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(900)); - result.SessionCount.Should().Be(2); + result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800)); + result.SessionCount.Should().Be(1); result.SkipPriceCapState.Should().BeNull(); result.BudgetOverrideState.Should().BeNull(); } @@ -253,7 +253,7 @@ public class BoilerMonitorEntityServiceTests { // Arrange SetupEntityState(TodayRuntimeEntityId, state); - SetupEntityState(SessionCountEntityId, "3"); + SetupEntityState(SessionCountEntityId, "2"); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -268,8 +268,8 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WithDecimalRuntime_ShouldParseCorrectly() { // Arrange - SetupEntityState(TodayRuntimeEntityId, "1800.5"); - SetupEntityState(SessionCountEntityId, "2"); + SetupEntityState(TodayRuntimeEntityId, "134.66"); + SetupEntityState(SessionCountEntityId, "1"); SetupEntityState(SkipPriceCapEntityId, "OFF"); SetupEntityState(BudgetOverrideEntityId, "OFF"); @@ -278,7 +278,8 @@ public class BoilerMonitorEntityServiceTests // Assert result.Should().NotBeNull(); - result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800.5)); + result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(134.66)); + result.SessionCount.Should().Be(1); } #endregion diff --git a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs index 1657a59..d7401d3 100644 --- a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs @@ -71,7 +71,7 @@ public class WaterReadyServiceTests var sut = CreateSut(); // Act - var result = sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); // Assert result.Should().BeFalse(); @@ -202,7 +202,7 @@ public class WaterReadyServiceTests sut.NotifyTurnedOn(); // Act — high power during grace period is still "not ready" (heating) - var result = sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); // Assert result.Should().BeFalse(); @@ -420,7 +420,7 @@ public class WaterReadyServiceTests var sut = CreateSut(); // Act — water is not ready (high power), no cooldown should be triggered - sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); // Assert sut.IsInCooldown.Should().BeFalse(); diff --git a/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj b/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj index 6f5297d..ea89ee3 100644 --- a/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj +++ b/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj @@ -20,8 +20,8 @@ - - + + diff --git a/BoilerMonitor.Models/BoilerMonitor.Models.csproj b/BoilerMonitor.Models/BoilerMonitor.Models.csproj index cb7cd05..cd6e963 100644 --- a/BoilerMonitor.Models/BoilerMonitor.Models.csproj +++ b/BoilerMonitor.Models/BoilerMonitor.Models.csproj @@ -12,7 +12,7 @@ - + diff --git a/HomeAssistant.Entities/EntityGeneration/HomeAssistantGenerated.cs b/HomeAssistant.Entities/EntityGeneration/HomeAssistantGenerated.cs index e7eab1c..ff2591e 100644 --- a/HomeAssistant.Entities/EntityGeneration/HomeAssistantGenerated.cs +++ b/HomeAssistant.Entities/EntityGeneration/HomeAssistantGenerated.cs @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------ // -// Generated using NetDaemon CodeGenerator nd-codegen v26.3.0.0 -// At: 2026-03-01T17:23:03.1325697+02:00 +// Generated using NetDaemon CodeGenerator nd-codegen v26.11.0.0 +// At: 2026-03-31T22:16:06.7505553+03:00 // // *** Make sure the version of the codegen tool and your nugets NetDaemon.* have the same version.*** // You can use following command to keep it up to date with the latest version: @@ -60,6 +60,7 @@ public static class GeneratedExtensions serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); + serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); @@ -91,6 +92,7 @@ public static class GeneratedExtensions serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); + serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); @@ -114,11 +116,11 @@ public static class GeneratedExtensions serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); + serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); - serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddTransient(); @@ -164,6 +166,7 @@ public class GeneratedEntityFactory : IEntityFactory "sensor" => new SensorEntity(haContext, entityId), "sun" => new SunEntity(haContext, entityId), "switch" => new SwitchEntity(haContext, entityId), + "text" => new TextEntity(haContext, entityId), "tts" => new TtsEntity(haContext, entityId), "update" => new UpdateEntity(haContext, entityId), "weather" => new WeatherEntity(haContext, entityId), @@ -221,6 +224,8 @@ public interface IEntities SwitchEntities Switch { get; } + TextEntities Text { get; } + TtsEntities Tts { get; } UpdateEntities Update { get; } @@ -261,6 +266,7 @@ public partial class Entities : IEntities public SensorEntities Sensor => new(_haContext); public SunEntities Sun => new(_haContext); public SwitchEntities Switch => new(_haContext); + public TextEntities Text => new(_haContext); public TtsEntities Tts => new(_haContext); public UpdateEntities Update => new(_haContext); public WeatherEntities Weather => new(_haContext); @@ -291,8 +297,9 @@ public partial class MediaPlayerEntities /// Enumerates all media_player entities currently registered (at runtime) in Home Assistant as MediaPlayerEntity public IEnumerable EnumerateAll() => _haContext.GetAllEntities().Where(e => e.EntityId.StartsWith("media_player.")).Select(e => new MediaPlayerEntity(e)); - ///123PrasauNenuplysk (QE75Q77DATXXH) public MediaPlayerEntity _123prasaunenuplyskQe75q77datxxh => new(_haContext, "media_player.123prasaunenuplysk_qe75q77datxxh"); + ///123PrasauNenuplysk (QE75Q77DATXXH) + public MediaPlayerEntity _123prasaunenuplyskQe75q77datxxh2 => new(_haContext, "media_player.123prasaunenuplysk_qe75q77datxxh_2"); } public partial class AutomationEntities @@ -341,8 +348,12 @@ public partial class BinarySensorEntities /// Enumerates all binary_sensor entities currently registered (at runtime) in Home Assistant as BinarySensorEntity public IEnumerable EnumerateAll() => _haContext.GetAllEntities().Where(e => e.EntityId.StartsWith("binary_sensor.")).Select(e => new BinarySensorEntity(e)); + ///Aquarium leak sensor + public BinarySensorEntity AquariumLeakSensor => new(_haContext, "binary_sensor.aquarium_leak_sensor"); ///Boiler Moisture public BinarySensorEntity BoilerMoisture => new(_haContext, "binary_sensor.boiler_moisture"); + ///Boiler Monitor Budget exhausted + public BinarySensorEntity BoilermonitorBudgetExhausted => new(_haContext, "binary_sensor.boilermonitor_budget_exhausted"); ///Low Storage public BinarySensorEntity LowStorage => new(_haContext, "binary_sensor.low_storage"); ///Marius Watch Is charging @@ -379,14 +390,18 @@ public partial class ButtonEntities public IEnumerable EnumerateAll() => _haContext.GetAllEntities().Where(e => e.EntityId.StartsWith("button.")).Select(e => new ButtonEntity(e)); ///Boiler Moisture Identify public ButtonEntity BoilerMoistureIdentify => new(_haContext, "button.boiler_moisture_identify"); - ///Boiler Temp Identify + ///Boiler room Temp Identify public ButtonEntity BoilerTempIdentify => new(_haContext, "button.boiler_temp_identify"); + ///Boiler Monitor Cleanup all entities + public ButtonEntity BoilermonitorCleanup => new(_haContext, "button.boilermonitor_cleanup"); ///Home Assistant Reload public ButtonEntity HomeassistantReload => new(_haContext, "button.homeassistant_reload"); ///Home Assistant Restart public ButtonEntity HomeassistantRestart => new(_haContext, "button.homeassistant_restart"); ///Repairs Ignore all public ButtonEntity IgnoreAllIssues => new(_haContext, "button.ignore_all_issues"); + ///Rediscover power sensors + public ButtonEntity PowermonitorRediscoverSensors => new(_haContext, "button.powermonitor_rediscover_sensors"); ///Repairs Unignore all public ButtonEntity UnignoreAllIssues => new(_haContext, "button.unignore_all_issues"); } @@ -519,8 +534,10 @@ public partial class InputBooleanEntities public InputBooleanEntity BoilerBoostMode => new(_haContext, "input_boolean.boiler_boost_mode"); ///Christmas lights public InputBooleanEntity ChristmasLights => new(_haContext, "input_boolean.christmas_lights"); - ///dev_netdaemon_nord_pool_manager_nord_pool_init - public InputBooleanEntity DevNetdaemonNordPoolManagerNordPoolInit => new(_haContext, "input_boolean.dev_netdaemon_nord_pool_manager_nord_pool_init"); + ///netdaemon_boiler_monitor_manager_boiler_monitor_init + public InputBooleanEntity NetdaemonBoilerMonitorManagerBoilerMonitorInit => new(_haContext, "input_boolean.netdaemon_boiler_monitor_manager_boiler_monitor_init"); + ///netdaemon_nord_pool_manager_nord_pool_init + public InputBooleanEntity NetdaemonNordPoolManagerNordPoolInit => new(_haContext, "input_boolean.netdaemon_nord_pool_manager_nord_pool_init"); } public partial class InputDatetimeEntities @@ -535,8 +552,6 @@ public partial class InputDatetimeEntities public IEnumerable EnumerateAll() => _haContext.GetAllEntities().Where(e => e.EntityId.StartsWith("input_datetime.")).Select(e => new InputDatetimeEntity(e)); ///Boiler Ready By public InputDatetimeEntity BoilerReadyBy => new(_haContext, "input_datetime.boiler_ready_by"); - ///input_datetime.price_alert_time_marius - public InputDatetimeEntity InputDatetimePriceAlertTimeMarius => new(_haContext, "input_datetime.input_datetime_price_alert_time_marius"); } public partial class InputNumberEntities @@ -565,18 +580,46 @@ public partial class NumberEntities /// Enumerates all number entities currently registered (at runtime) in Home Assistant as NumberEntity public IEnumerable EnumerateAll() => _haContext.GetAllEntities().Where(e => e.EntityId.StartsWith("number.")).Select(e => new NumberEntity(e)); - ///Boiler Temp Comfort humidity max + ///Bathroom Comfort humidity max + public NumberEntity BathroomComfortHumidityMax => new(_haContext, "number.bathroom_comfort_humidity_max"); + ///Bathroom Comfort humidity min + public NumberEntity BathroomComfortHumidityMin => new(_haContext, "number.bathroom_comfort_humidity_min"); + ///Bathroom Comfort temperature max + public NumberEntity BathroomComfortTemperatureMax => new(_haContext, "number.bathroom_comfort_temperature_max"); + ///Bathroom Comfort temperature min + public NumberEntity BathroomComfortTemperatureMin => new(_haContext, "number.bathroom_comfort_temperature_min"); + ///Bedroom Comfort humidity max + public NumberEntity BedroomComfortHumidityMax => new(_haContext, "number.bedroom_comfort_humidity_max"); + ///Bedroom Comfort humidity min + public NumberEntity BedroomComfortHumidityMin => new(_haContext, "number.bedroom_comfort_humidity_min"); + ///Bedroom Comfort temperature max + public NumberEntity BedroomComfortTemperatureMax => new(_haContext, "number.bedroom_comfort_temperature_max"); + ///Bedroom Comfort temperature min + public NumberEntity BedroomComfortTemperatureMin => new(_haContext, "number.bedroom_comfort_temperature_min"); + ///Boiler room Temp Comfort humidity max public NumberEntity BoilerTempComfortHumidityMax => new(_haContext, "number.boiler_temp_comfort_humidity_max"); - ///Boiler Temp Comfort humidity min + ///Boiler room Temp Comfort humidity min public NumberEntity BoilerTempComfortHumidityMin => new(_haContext, "number.boiler_temp_comfort_humidity_min"); - ///Boiler Temp Comfort temperature max + ///Boiler room Temp Comfort temperature max public NumberEntity BoilerTempComfortTemperatureMax => new(_haContext, "number.boiler_temp_comfort_temperature_max"); - ///Boiler Temp Comfort temperature min + ///Boiler room Temp Comfort temperature min public NumberEntity BoilerTempComfortTemperatureMin => new(_haContext, "number.boiler_temp_comfort_temperature_min"); - ///Boiler Temp Humidity offset + ///Boiler room Temp Humidity offset public NumberEntity BoilerTempHumidityOffset => new(_haContext, "number.boiler_temp_humidity_offset"); - ///Boiler Temp Temperature offset + ///Boiler room Temp Temperature offset public NumberEntity BoilerTempTemperatureOffset => new(_haContext, "number.boiler_temp_temperature_offset"); + ///Boiler Monitor Heating power threshold (watts) + public NumberEntity BoilermonitorConfigHeatingThreshold => new(_haContext, "number.boilermonitor_config_heating_threshold"); + ///Boiler Monitor Poll interval (seconds) + public NumberEntity BoilermonitorConfigPollInterval => new(_haContext, "number.boilermonitor_config_poll_interval"); + ///Main Home Comfort humidity max + public NumberEntity MainHomeComfortHumidityMax => new(_haContext, "number.main_home_comfort_humidity_max"); + ///Main Home Comfort humidity min + public NumberEntity MainHomeComfortHumidityMin => new(_haContext, "number.main_home_comfort_humidity_min"); + ///Main Home Comfort temperature max + public NumberEntity MainHomeComfortTemperatureMax => new(_haContext, "number.main_home_comfort_temperature_max"); + ///Main Home Comfort temperature min + public NumberEntity MainHomeComfortTemperatureMin => new(_haContext, "number.main_home_comfort_temperature_min"); } public partial class PersonEntities @@ -607,8 +650,9 @@ public partial class RemoteEntities /// Enumerates all remote entities currently registered (at runtime) in Home Assistant as RemoteEntity public IEnumerable EnumerateAll() => _haContext.GetAllEntities().Where(e => e.EntityId.StartsWith("remote.")).Select(e => new RemoteEntity(e)); - ///123PrasauNenuplysk (QE75Q77DATXXH) public RemoteEntity _123prasaunenuplyskQe75q77datxxh => new(_haContext, "remote.123prasaunenuplysk_qe75q77datxxh"); + ///123PrasauNenuplysk (QE75Q77DATXXH) + public RemoteEntity _123prasaunenuplyskQe75q77datxxh2 => new(_haContext, "remote.123prasaunenuplysk_qe75q77datxxh_2"); } public partial class ScriptEntities @@ -637,31 +681,63 @@ public partial class SelectEntities /// Enumerates all select entities currently registered (at runtime) in Home Assistant as SelectEntity public IEnumerable EnumerateAll() => _haContext.GetAllEntities().Where(e => e.EntityId.StartsWith("select.")).Select(e => new SelectEntity(e)); - ///Akvariumas Start-up behavior + ///Akvariumas Power-on behavior public SelectEntity AkvariumasStartUpBehavior => new(_haContext, "select.akvariumas_start_up_behavior"); - ///3D print Start-up behavior + ///3D print Power-on behavior public SelectEntity BalkonyLapsStartUpBehavior => new(_haContext, "select.balkony_laps_start_up_behavior"); - ///Boiler Temp Display unit + ///Bathroom Display unit + public SelectEntity BathroomDisplayUnit => new(_haContext, "select.bathroom_display_unit"); + ///Bedroom Display unit + public SelectEntity BedroomDisplayUnit => new(_haContext, "select.bedroom_display_unit"); + ///Boiler room Temp Display unit public SelectEntity BoilerTempDisplayUnit => new(_haContext, "select.boiler_temp_display_unit"); - ///Dishwasher Start-up behavior + ///Dishwasher Power-on behavior public SelectEntity DishwasherStartUpBehavior => new(_haContext, "select.dishwasher_start_up_behavior"); - ///Exhaust Fan Start-up behavior + ///Exhaust Fan Power-on behavior public SelectEntity ExhaustFanStartUpBehavior => new(_haContext, "select.exhaust_fan_start_up_behavior"); - ///Fridge Start-up behavior + ///Fridge Power-on behavior public SelectEntity FridgeStartUpBehavior => new(_haContext, "select.fridge_start_up_behavior"); - ///Heating Relay Far Start-up behavior + ///Heating Relay Far Power-on behavior public SelectEntity HeatingStartUpBehavior => new(_haContext, "select.heating_start_up_behavior"); - ///Heating Relay Bathroom Start-up behavior + ///Heating Relay Bathroom Power-on behavior public SelectEntity HeatingStartUpBehavior2 => new(_haContext, "select.heating_start_up_behavior_2"); - ///Heating Relay Middle Start-up behavior + ///Heating Relay Middle Power-on behavior public SelectEntity HeatingStartUpBehavior3 => new(_haContext, "select.heating_start_up_behavior_3"); - ///LED power Start-up behavior + ///Main Home Display unit + public SelectEntity MainHomeDisplayUnit => new(_haContext, "select.main_home_display_unit"); + ///Induction Startup + public SelectEntity Sonoff10018909cbStartup => new(_haContext, "select.sonoff_10018909cb_startup"); + ///AC + public SelectEntity Sonoff100215c5341 => new(_haContext, "select.sonoff_100215c534_1"); + ///Lamp + public SelectEntity Sonoff100222f7be1 => new(_haContext, "select.sonoff_100222f7be_1"); + ///Christmas tree + public SelectEntity Sonoff100222ff361 => new(_haContext, "select.sonoff_100222ff36_1"); + ///Stair lamps + public SelectEntity Sonoff100222ff631 => new(_haContext, "select.sonoff_100222ff63_1"); + ///Po laiptais + public SelectEntity Sonoff1002230a481 => new(_haContext, "select.sonoff_1002230a48_1"); + ///Boiler + public SelectEntity Sonoff1002230e321 => new(_haContext, "select.sonoff_1002230e32_1"); + ///Washer + public SelectEntity Sonoff100255ead81 => new(_haContext, "select.sonoff_100255ead8_1"); + ///Dryer + public SelectEntity Sonoff100255f06c1 => new(_haContext, "select.sonoff_100255f06c_1"); + ///Cat Christmas lamps + public SelectEntity Sonoff100255f7381 => new(_haContext, "select.sonoff_100255f738_1"); + ///Dehumidifier + public SelectEntity Sonoff10025606e61 => new(_haContext, "select.sonoff_10025606e6_1"); + ///Salt Lamp + public SelectEntity Sonoff10025609ce1 => new(_haContext, "select.sonoff_10025609ce_1"); + ///Home meter + public SelectEntity Sonoff100267d63f1 => new(_haContext, "select.sonoff_100267d63f_1"); + ///LED power Power-on behavior public SelectEntity SonoffS60zbtpfStartUpBehavior => new(_haContext, "select.sonoff_s60zbtpf_start_up_behavior"); - ///Air Purifirier Start-up behavior + ///Air Purifirier Power-on behavior public SelectEntity SonoffS60zbtpfStartUpBehavior2 => new(_haContext, "select.sonoff_s60zbtpf_start_up_behavior_2"); - ///Network Infra Start-up behavior + ///Network Infra Power-on behavior public SelectEntity TempStartUpBehavior => new(_haContext, "select.temp_start_up_behavior"); - ///TV Start-up behavior + ///TV Power-on behavior public SelectEntity TvStartUpBehavior => new(_haContext, "select.tv_start_up_behavior"); ///Washing room Display unit public SelectEntity WashingRoomDisplayUnit => new(_haContext, "select.washing_room_display_unit"); @@ -703,6 +779,12 @@ public partial class SensorEntities public SensorEntity BinarySensors => new(_haContext, "sensor.binary_sensors"); ///Boiler running public SensorEntity BoilerRunning => new(_haContext, "sensor.boiler_running"); + ///Boiler Monitor Heating sessions today + public SensorEntity BoilermonitorSessionCount => new(_haContext, "sensor.boilermonitor_session_count"); + ///Boiler Monitor Boiler Monitor status + public SensorEntity BoilermonitorStatus => new(_haContext, "sensor.boilermonitor_status"); + ///Boiler Monitor Boiler water ready + public SensorEntity BoilermonitorWaterReady => new(_haContext, "sensor.boilermonitor_water_ready"); ///Home Assistant Buttons public SensorEntity Buttons => new(_haContext, "sensor.buttons"); ///Home Assistant Calendars @@ -801,17 +883,15 @@ public partial class SensorEntities public SensorEntity NordPoolLtLastUpdated => new(_haContext, "sensor.nord_pool_lt_last_updated"); ///Boiler water ready public SensorEntity NordpoolBoilerWaterReady => new(_haContext, "sensor.nordpool_boiler_water_ready"); - ///NordPool cheapest boiler intervals + ///NordPool NordPool cheapest boiler intervals public SensorEntity NordpoolCheapestIntervals => new(_haContext, "sensor.nordpool_cheapest_intervals"); - ///NordPool price last pull date - public SensorEntity NordpoolLastPullDate => new(_haContext, "sensor.nordpool_last_pull_date"); - ///NordPool last update time + ///NordPool NordPool last update time public SensorEntity NordpoolLastUpdateTime => new(_haContext, "sensor.nordpool_last_update_time"); - ///NordPool price alerts - public SensorEntity NordpoolPriceAlerts => new(_haContext, "sensor.nordpool_price_alerts"); - ///NordPool today prices + ///NordPool NordPool today prices public SensorEntity NordpoolTodayPrices => new(_haContext, "sensor.nordpool_today_prices"); - ///NordPool tomorrow prices + ///NordPool NordPool today and tomorrow prices + public SensorEntity NordpoolTodayTomorrowPrices => new(_haContext, "sensor.nordpool_today_tomorrow_prices"); + ///NordPool NordPool tomorrow prices public SensorEntity NordpoolTomorrowPrices => new(_haContext, "sensor.nordpool_tomorrow_prices"); ///Home Assistant Numbers public SensorEntity Numbers => new(_haContext, "sensor.numbers"); @@ -849,6 +929,8 @@ public partial class SensorEntities public SensorEntity SmS936bSim1 => new(_haContext, "sensor.sm_s936b_sim_1"); ///Marius Phone Wi-Fi connection public SensorEntity SmS936bWiFiConnection => new(_haContext, "sensor.sm_s936b_wi_fi_connection"); + ///Main Device Connection + public SensorEntity Sonoff1002479627Connection => new(_haContext, "sensor.sonoff_1002479627_connection"); ///Home Assistant Speech-to-text public SensorEntity Stt => new(_haContext, "sensor.stt"); ///Sun Next dawn @@ -891,30 +973,48 @@ public partial class SensorEntities public NumericSensorEntity AkvariumasPower => new(_haContext, "sensor.akvariumas_power"); ///Akvariumas Voltage public NumericSensorEntity AkvariumasVoltage => new(_haContext, "sensor.akvariumas_voltage"); + ///Aquarium leak sensor Battery + public NumericSensorEntity AquariumLeakSensorBattery => new(_haContext, "sensor.aquarium_leak_sensor_battery"); ///3D print Power public NumericSensorEntity BalkonyLapsPower => new(_haContext, "sensor.balkony_laps_power"); ///3D print Voltage public NumericSensorEntity BalkonyLapsVoltage => new(_haContext, "sensor.balkony_laps_voltage"); + ///Bathroom Battery + public NumericSensorEntity BathroomBattery => new(_haContext, "sensor.bathroom_battery"); + ///Bathroom Humidity + public NumericSensorEntity BathroomHumidity => new(_haContext, "sensor.bathroom_humidity"); + ///Bathroom Temperature + public NumericSensorEntity BathroomTemperature => new(_haContext, "sensor.bathroom_temperature"); + ///Bedroom Battery + public NumericSensorEntity BedroomBattery => new(_haContext, "sensor.bedroom_battery"); + ///Bedroom Humidity + public NumericSensorEntity BedroomHumidity => new(_haContext, "sensor.bedroom_humidity"); + ///Bedroom Temperature + public NumericSensorEntity BedroomTemperature => new(_haContext, "sensor.bedroom_temperature"); ///Boiler Moisture Battery public NumericSensorEntity BoilerMoistureBattery => new(_haContext, "sensor.boiler_moisture_battery"); ///Boiler run time public NumericSensorEntity BoilerRunTime => new(_haContext, "sensor.boiler_run_time"); - ///Boiler Temp Battery + ///Boiler room Temp Battery public NumericSensorEntity BoilerTempBattery => new(_haContext, "sensor.boiler_temp_battery"); - ///Boiler Temp Humidity + ///Boiler room Temp Humidity public NumericSensorEntity BoilerTempHumidity => new(_haContext, "sensor.boiler_temp_humidity"); - ///Boiler Temp Temperature + ///Boiler room Temp Temperature public NumericSensorEntity BoilerTempTemperature => new(_haContext, "sensor.boiler_temp_temperature"); + ///Boiler Monitor Budget usage + public NumericSensorEntity BoilermonitorBudgetPercentage => new(_haContext, "sensor.boilermonitor_budget_percentage"); + ///Boiler Monitor Remaining budget time + public NumericSensorEntity BoilermonitorRemainingTime => new(_haContext, "sensor.boilermonitor_remaining_time"); + ///Boiler Monitor Today runtime + public NumericSensorEntity BoilermonitorTodayRuntime => new(_haContext, "sensor.boilermonitor_today_runtime"); ///Cat Area Temp Battery public NumericSensorEntity CatAreaTempBattery => new(_haContext, "sensor.cat_area_temp_battery"); ///Cat Area Temp Humidity public NumericSensorEntity CatAreaTempHumidity => new(_haContext, "sensor.cat_area_temp_humidity"); ///Cat Area Temp Temperature public NumericSensorEntity CatAreaTempTemperature => new(_haContext, "sensor.cat_area_temp_temperature"); - ///Christmas lights power usage - public NumericSensorEntity ChristmasLightsPowerUsage => new(_haContext, "sensor.christmas_lights_power_usage"); - ///Daily power usage - public NumericSensorEntity DailyPowerUsage => new(_haContext, "sensor.daily_power_usage"); + ///Current SetPoint + public NumericSensorEntity CurrentSetpoint => new(_haContext, "sensor.current_setpoint"); ///Dehumidifier running time public NumericSensorEntity DehumidifierRunningTime => new(_haContext, "sensor.dehumidifier_running_time"); ///Dishwasher Power @@ -939,6 +1039,12 @@ public partial class SensorEntities public NumericSensorEntity KaunasNoreikiskesLithuaniaPressure => new(_haContext, "sensor.kaunas_noreikiskes_lithuania_pressure"); ///Kaunas Noreikiskes, Lithuania Temperature public NumericSensorEntity KaunasNoreikiskesLithuaniaTemperature => new(_haContext, "sensor.kaunas_noreikiskes_lithuania_temperature"); + ///Main Home Battery + public NumericSensorEntity MainHomeBattery => new(_haContext, "sensor.main_home_battery"); + ///Main Home Humidity + public NumericSensorEntity MainHomeHumidity => new(_haContext, "sensor.main_home_humidity"); + ///Main Home Temperature + public NumericSensorEntity MainHomeTemperature => new(_haContext, "sensor.main_home_temperature"); ///Marius Watch Battery level public NumericSensorEntity MariusWatchBatteryLevel => new(_haContext, "sensor.marius_watch_battery_level"); ///Marius Watch Battery temperature @@ -963,7 +1069,7 @@ public partial class SensorEntities public NumericSensorEntity NordPoolLtHighestPrice => new(_haContext, "sensor.nord_pool_lt_highest_price"); ///Nord Pool LT Lowest price public NumericSensorEntity NordPoolLtLowestPrice => new(_haContext, "sensor.nord_pool_lt_lowest_price"); - ///NordPool current price + ///NordPool NordPool current price public NumericSensorEntity NordpoolCurrentPrice => new(_haContext, "sensor.nordpool_current_price"); ///Nordpool price public NumericSensorEntity NordpoolPrice => new(_haContext, "sensor.nordpool_price"); @@ -1009,42 +1115,108 @@ public partial class SensorEntities public NumericSensorEntity Sonoff10018909cbPower => new(_haContext, "sensor.sonoff_10018909cb_power"); ///Induction Voltage public NumericSensorEntity Sonoff10018909cbVoltage => new(_haContext, "sensor.sonoff_10018909cb_voltage"); + ///AC Energy Day Supply + public NumericSensorEntity Sonoff100215c534EnergyDaySupply => new(_haContext, "sensor.sonoff_100215c534_energy_day_supply"); + ///AC Energy Month Supply + public NumericSensorEntity Sonoff100215c534EnergyMonthSupply => new(_haContext, "sensor.sonoff_100215c534_energy_month_supply"); ///AC Power public NumericSensorEntity Sonoff100215c534Power => new(_haContext, "sensor.sonoff_100215c534_power"); + ///AC Power Supply + public NumericSensorEntity Sonoff100215c534PowerSupply => new(_haContext, "sensor.sonoff_100215c534_power_supply"); ///AC Voltage public NumericSensorEntity Sonoff100215c534Voltage => new(_haContext, "sensor.sonoff_100215c534_voltage"); + ///Lamp Energy Day Supply + public NumericSensorEntity Sonoff100222f7beEnergyDaySupply => new(_haContext, "sensor.sonoff_100222f7be_energy_day_supply"); + ///Lamp Energy Month Supply + public NumericSensorEntity Sonoff100222f7beEnergyMonthSupply => new(_haContext, "sensor.sonoff_100222f7be_energy_month_supply"); ///Lamp Power public NumericSensorEntity Sonoff100222f7bePower => new(_haContext, "sensor.sonoff_100222f7be_power"); + ///Lamp Power Supply + public NumericSensorEntity Sonoff100222f7bePowerSupply => new(_haContext, "sensor.sonoff_100222f7be_power_supply"); + ///Christmas tree Energy Day Supply + public NumericSensorEntity Sonoff100222ff36EnergyDaySupply => new(_haContext, "sensor.sonoff_100222ff36_energy_day_supply"); + ///Christmas tree Energy Month Supply + public NumericSensorEntity Sonoff100222ff36EnergyMonthSupply => new(_haContext, "sensor.sonoff_100222ff36_energy_month_supply"); ///Christmas tree Power public NumericSensorEntity Sonoff100222ff36Power => new(_haContext, "sensor.sonoff_100222ff36_power"); + ///Christmas tree Power Supply + public NumericSensorEntity Sonoff100222ff36PowerSupply => new(_haContext, "sensor.sonoff_100222ff36_power_supply"); ///Christmas tree Voltage public NumericSensorEntity Sonoff100222ff36Voltage => new(_haContext, "sensor.sonoff_100222ff36_voltage"); + ///Stair lamps Energy Day Supply + public NumericSensorEntity Sonoff100222ff63EnergyDaySupply => new(_haContext, "sensor.sonoff_100222ff63_energy_day_supply"); + ///Stair lamps Energy Month Supply + public NumericSensorEntity Sonoff100222ff63EnergyMonthSupply => new(_haContext, "sensor.sonoff_100222ff63_energy_month_supply"); ///Stair lamps Power public NumericSensorEntity Sonoff100222ff63Power => new(_haContext, "sensor.sonoff_100222ff63_power"); + ///Stair lamps Power Supply + public NumericSensorEntity Sonoff100222ff63PowerSupply => new(_haContext, "sensor.sonoff_100222ff63_power_supply"); + ///Po laiptais Energy Day Supply + public NumericSensorEntity Sonoff1002230a48EnergyDaySupply => new(_haContext, "sensor.sonoff_1002230a48_energy_day_supply"); + ///Po laiptais Energy Month Supply + public NumericSensorEntity Sonoff1002230a48EnergyMonthSupply => new(_haContext, "sensor.sonoff_1002230a48_energy_month_supply"); ///Po laiptais Power public NumericSensorEntity Sonoff1002230a48Power => new(_haContext, "sensor.sonoff_1002230a48_power"); + ///Po laiptais Power Supply + public NumericSensorEntity Sonoff1002230a48PowerSupply => new(_haContext, "sensor.sonoff_1002230a48_power_supply"); ///Po laiptais Voltage public NumericSensorEntity Sonoff1002230a48Voltage => new(_haContext, "sensor.sonoff_1002230a48_voltage"); + ///Boiler Energy Day Supply + public NumericSensorEntity Sonoff1002230e32EnergyDaySupply => new(_haContext, "sensor.sonoff_1002230e32_energy_day_supply"); + ///Boiler Energy Month Supply + public NumericSensorEntity Sonoff1002230e32EnergyMonthSupply => new(_haContext, "sensor.sonoff_1002230e32_energy_month_supply"); ///Boiler Power public NumericSensorEntity Sonoff1002230e32Power => new(_haContext, "sensor.sonoff_1002230e32_power"); + ///Boiler Power Supply + public NumericSensorEntity Sonoff1002230e32PowerSupply => new(_haContext, "sensor.sonoff_1002230e32_power_supply"); ///Boiler Voltage public NumericSensorEntity Sonoff1002230e32Voltage => new(_haContext, "sensor.sonoff_1002230e32_voltage"); + ///Washer Energy Day Supply + public NumericSensorEntity Sonoff100255ead8EnergyDaySupply => new(_haContext, "sensor.sonoff_100255ead8_energy_day_supply"); + ///Washer Energy Month Supply + public NumericSensorEntity Sonoff100255ead8EnergyMonthSupply => new(_haContext, "sensor.sonoff_100255ead8_energy_month_supply"); ///Washer Power public NumericSensorEntity Sonoff100255ead8Power => new(_haContext, "sensor.sonoff_100255ead8_power"); + ///Washer Power Supply + public NumericSensorEntity Sonoff100255ead8PowerSupply => new(_haContext, "sensor.sonoff_100255ead8_power_supply"); ///Washer Voltage public NumericSensorEntity Sonoff100255ead8Voltage => new(_haContext, "sensor.sonoff_100255ead8_voltage"); + ///Dryer Energy Day Supply + public NumericSensorEntity Sonoff100255f06cEnergyDaySupply => new(_haContext, "sensor.sonoff_100255f06c_energy_day_supply"); + ///Dryer Energy Month Supply + public NumericSensorEntity Sonoff100255f06cEnergyMonthSupply => new(_haContext, "sensor.sonoff_100255f06c_energy_month_supply"); ///Dryer Power public NumericSensorEntity Sonoff100255f06cPower => new(_haContext, "sensor.sonoff_100255f06c_power"); + ///Dryer Power Supply + public NumericSensorEntity Sonoff100255f06cPowerSupply => new(_haContext, "sensor.sonoff_100255f06c_power_supply"); ///Dryer Voltage public NumericSensorEntity Sonoff100255f06cVoltage => new(_haContext, "sensor.sonoff_100255f06c_voltage"); + ///Cat Christmas lamps Energy Day Supply + public NumericSensorEntity Sonoff100255f738EnergyDaySupply => new(_haContext, "sensor.sonoff_100255f738_energy_day_supply"); + ///Cat Christmas lamps Energy Month Supply + public NumericSensorEntity Sonoff100255f738EnergyMonthSupply => new(_haContext, "sensor.sonoff_100255f738_energy_month_supply"); ///Cat Christmas lamps Power public NumericSensorEntity Sonoff100255f738Power => new(_haContext, "sensor.sonoff_100255f738_power"); + ///Cat Christmas lamps Power Supply + public NumericSensorEntity Sonoff100255f738PowerSupply => new(_haContext, "sensor.sonoff_100255f738_power_supply"); + ///Dehumidifier Energy Day Supply + public NumericSensorEntity Sonoff10025606e6EnergyDaySupply => new(_haContext, "sensor.sonoff_10025606e6_energy_day_supply"); + ///Dehumidifier Energy Month Supply + public NumericSensorEntity Sonoff10025606e6EnergyMonthSupply => new(_haContext, "sensor.sonoff_10025606e6_energy_month_supply"); ///Dehumidifier Power public NumericSensorEntity Sonoff10025606e6Power => new(_haContext, "sensor.sonoff_10025606e6_power"); + ///Dehumidifier Power Supply + public NumericSensorEntity Sonoff10025606e6PowerSupply => new(_haContext, "sensor.sonoff_10025606e6_power_supply"); ///Dehumidifier Voltage public NumericSensorEntity Sonoff10025606e6Voltage => new(_haContext, "sensor.sonoff_10025606e6_voltage"); + ///Salt Lamp Energy Day Supply + public NumericSensorEntity Sonoff10025609ceEnergyDaySupply => new(_haContext, "sensor.sonoff_10025609ce_energy_day_supply"); + ///Salt Lamp Energy Month Supply + public NumericSensorEntity Sonoff10025609ceEnergyMonthSupply => new(_haContext, "sensor.sonoff_10025609ce_energy_month_supply"); ///Salt Lamp Power public NumericSensorEntity Sonoff10025609cePower => new(_haContext, "sensor.sonoff_10025609ce_power"); + ///Salt Lamp Power Supply + public NumericSensorEntity Sonoff10025609cePowerSupply => new(_haContext, "sensor.sonoff_10025609ce_power_supply"); ///Salt Lamp Voltage public NumericSensorEntity Sonoff10025609ceVoltage => new(_haContext, "sensor.sonoff_10025609ce_voltage"); ///Home meter Current @@ -1053,36 +1225,24 @@ public partial class SensorEntities public NumericSensorEntity Sonoff100267d63fEnergy => new(_haContext, "sensor.sonoff_100267d63f_energy"); ///Home meter Energy Day public NumericSensorEntity Sonoff100267d63fEnergyDay => new(_haContext, "sensor.sonoff_100267d63f_energy_day"); + ///Home meter Energy Day Supply + public NumericSensorEntity Sonoff100267d63fEnergyDaySupply => new(_haContext, "sensor.sonoff_100267d63f_energy_day_supply"); ///Home meter Energy Month public NumericSensorEntity Sonoff100267d63fEnergyMonth => new(_haContext, "sensor.sonoff_100267d63f_energy_month"); + ///Home meter Energy Month Supply + public NumericSensorEntity Sonoff100267d63fEnergyMonthSupply => new(_haContext, "sensor.sonoff_100267d63f_energy_month_supply"); ///Total Home Power Usage public NumericSensorEntity Sonoff100267d63fPower => new(_haContext, "sensor.sonoff_100267d63f_power"); + ///Home meter Power Supply + public NumericSensorEntity Sonoff100267d63fPowerSupply => new(_haContext, "sensor.sonoff_100267d63f_power_supply"); ///Home meter Voltage public NumericSensorEntity Sonoff100267d63fVoltage => new(_haContext, "sensor.sonoff_100267d63f_voltage"); - ///Main Home Battery - public NumericSensorEntity SonoffA4800e66a0Battery => new(_haContext, "sensor.sonoff_a4800e66a0_battery"); - ///Main Home Humidity - public NumericSensorEntity SonoffA4800e66a0Humidity => new(_haContext, "sensor.sonoff_a4800e66a0_humidity"); - ///Main Home Temperature - public NumericSensorEntity SonoffA4800e66a0Temperature => new(_haContext, "sensor.sonoff_a4800e66a0_temperature"); ///Outside Battery public NumericSensorEntity SonoffA4800f07b4Battery => new(_haContext, "sensor.sonoff_a4800f07b4_battery"); ///Outside Humidity public NumericSensorEntity SonoffA4800f07b4Humidity => new(_haContext, "sensor.sonoff_a4800f07b4_humidity"); ///Outside Temperature public NumericSensorEntity SonoffA4800f07b4Temperature => new(_haContext, "sensor.sonoff_a4800f07b4_temperature"); - ///Bedroom Battery - public NumericSensorEntity SonoffA4800f07ddBattery => new(_haContext, "sensor.sonoff_a4800f07dd_battery"); - ///Bedroom Humidity - public NumericSensorEntity SonoffA4800f07ddHumidity => new(_haContext, "sensor.sonoff_a4800f07dd_humidity"); - ///Bedroom Temperature - public NumericSensorEntity SonoffA4800f07ddTemperature => new(_haContext, "sensor.sonoff_a4800f07dd_temperature"); - ///Bathroom Battery - public NumericSensorEntity SonoffA4800f07dfBattery => new(_haContext, "sensor.sonoff_a4800f07df_battery"); - ///Bathroom Humidity - public NumericSensorEntity SonoffA4800f07dfHumidity => new(_haContext, "sensor.sonoff_a4800f07df_humidity"); - ///Bathroom Temperature - public NumericSensorEntity SonoffA4800f07dfTemperature => new(_haContext, "sensor.sonoff_a4800f07df_temperature"); ///LED power Power public NumericSensorEntity SonoffS60zbtpfPower => new(_haContext, "sensor.sonoff_s60zbtpf_power"); ///Air Purifirier Power @@ -1103,12 +1263,6 @@ public partial class SensorEntities public NumericSensorEntity TvPower => new(_haContext, "sensor.tv_power"); ///TV Voltage public NumericSensorEntity TvVoltage => new(_haContext, "sensor.tv_voltage"); - ///Voltage min - public NumericSensorEntity VoltageMin => new(_haContext, "sensor.voltage_min"); - ///Voltage min 99% - public NumericSensorEntity VoltageMin99 => new(_haContext, "sensor.voltage_min_99"); - ///Voltage min standard deviation - public NumericSensorEntity VoltageMinStandardDeviation => new(_haContext, "sensor.voltage_min_standard_deviation"); ///Washing room Battery public NumericSensorEntity WashingRoomBattery => new(_haContext, "sensor.washing_room_battery"); ///Washing room Humidity @@ -1119,12 +1273,16 @@ public partial class SensorEntities public NumericSensorEntity WellbeingAirPurifier2Eco2 => new(_haContext, "sensor.wellbeing_air_purifier_2_eco2"); ///Fresh 360 filter Life public NumericSensorEntity WellbeingAirPurifier2Filterlife => new(_haContext, "sensor.wellbeing_air_purifier_2_filterlife"); + ///Humidity + public NumericSensorEntity WellbeingAirPurifier2Humidity => new(_haContext, "sensor.wellbeing_air_purifier_2_humidity"); ///PM1 public NumericSensorEntity WellbeingAirPurifier2Pm1 => new(_haContext, "sensor.wellbeing_air_purifier_2_pm1"); ///PM10 public NumericSensorEntity WellbeingAirPurifier2Pm10 => new(_haContext, "sensor.wellbeing_air_purifier_2_pm10"); ///PM2.5 public NumericSensorEntity WellbeingAirPurifier2Pm25 => new(_haContext, "sensor.wellbeing_air_purifier_2_pm2_5"); + ///Temperature + public NumericSensorEntity WellbeingAirPurifier2Temp => new(_haContext, "sensor.wellbeing_air_purifier_2_temp"); ///TVOC public NumericSensorEntity WellbeingAirPurifier2Tvoc => new(_haContext, "sensor.wellbeing_air_purifier_2_tvoc"); ///Mode @@ -1155,10 +1313,16 @@ public partial class SwitchEntities /// Enumerates all switch entities currently registered (at runtime) in Home Assistant as SwitchEntity public IEnumerable EnumerateAll() => _haContext.GetAllEntities().Where(e => e.EntityId.StartsWith("switch.")).Select(e => new SwitchEntity(e)); + ///AC On/Off + public SwitchEntity AcOnOff => new(_haContext, "switch.ac_on_off"); ///Akvariumas public SwitchEntity Akvariumas => new(_haContext, "switch.akvariumas"); ///3D print public SwitchEntity BalkonyLaps => new(_haContext, "switch.balkony_laps"); + ///Boiler Monitor Override budget enforcement + public SwitchEntity BoilermonitorBudgetOverride => new(_haContext, "switch.boilermonitor_budget_override"); + ///Boiler Monitor Skip price cap, heat until ready + public SwitchEntity BoilermonitorSkipPriceCap => new(_haContext, "switch.boilermonitor_skip_price_cap"); ///Dishwasher public SwitchEntity Dishwasher => new(_haContext, "switch.dishwasher"); ///Exhaust Fan @@ -1171,6 +1335,8 @@ public partial class SwitchEntities public SwitchEntity Heating2 => new(_haContext, "switch.heating_2"); ///Heating Relay Middle public SwitchEntity Heating3 => new(_haContext, "switch.heating_3"); + ///Skip price cap, heat until ready + public SwitchEntity NordpoolBoilerSkipPriceCap => new(_haContext, "switch.nordpool_boiler_skip_price_cap"); ///Induction public SwitchEntity Sonoff10018909cb => new(_haContext, "switch.sonoff_10018909cb"); ///AC @@ -1211,6 +1377,22 @@ public partial class SwitchEntities public SwitchEntity WellbeingAirPurifier2Uilight => new(_haContext, "switch.wellbeing_air_purifier_2_uilight"); } +public partial class TextEntities +{ + private readonly IHaContext _haContext; + public TextEntities(IHaContext haContext) + { + _haContext = haContext; + } + + /// Enumerates all text entities currently registered (at runtime) in Home Assistant as TextEntity + public IEnumerable EnumerateAll() => _haContext.GetAllEntities().Where(e => e.EntityId.StartsWith("text.")).Select(e => new TextEntity(e)); + ///Boiler Monitor Boiler power entity ID + public TextEntity BoilermonitorConfigPowerEntityId => new(_haContext, "text.boilermonitor_config_power_entity_id"); + ///Boiler Monitor Boiler switch entity ID + public TextEntity BoilermonitorConfigSwitchEntityId => new(_haContext, "text.boilermonitor_config_switch_entity_id"); +} + public partial class TtsEntities { private readonly IHaContext _haContext; @@ -1241,16 +1423,20 @@ public partial class UpdateEntities public UpdateEntity AkvariumasFirmware => new(_haContext, "update.akvariumas_firmware"); ///apexcharts-card update public UpdateEntity ApexchartsCardUpdate => new(_haContext, "update.apexcharts_card_update"); + ///Aquarium leak sensor Firmware + public UpdateEntity AquariumLeakSensorFirmware => new(_haContext, "update.aquarium_leak_sensor_firmware"); ///3D print Firmware public UpdateEntity BalkonyLapsFirmware => new(_haContext, "update.balkony_laps_firmware"); + ///Bathroom Firmware + public UpdateEntity BathroomFirmware => new(_haContext, "update.bathroom_firmware"); + ///Bedroom Firmware + public UpdateEntity BedroomFirmware => new(_haContext, "update.bedroom_firmware"); ///Boiler Moisture Firmware public UpdateEntity BoilerMoistureFirmware => new(_haContext, "update.boiler_moisture_firmware"); - ///Boiler Temp Firmware + ///Boiler room Temp Firmware public UpdateEntity BoilerTempFirmware => new(_haContext, "update.boiler_temp_firmware"); ///Cat Area Temp Firmware public UpdateEntity CatAreaTempFirmware => new(_haContext, "update.cat_area_temp_firmware"); - ///Dynamic Energy Cost update - public UpdateEntity DynamicEnergyCostUpdate => new(_haContext, "update.dynamic_energy_cost_update"); ///Dishwasher Firmware public UpdateEntity DishwasherFirmware => new(_haContext, "update.dishwasher_firmware"); ///Electrolux Wellbeing update @@ -1279,6 +1465,8 @@ public partial class UpdateEntities public UpdateEntity LetSEncryptUpdate => new(_haContext, "update.let_s_encrypt_update"); ///Local Tuya update public UpdateEntity LocalTuyaUpdate => new(_haContext, "update.local_tuya_update"); + ///Main Home Firmware + public UpdateEntity MainHomeFirmware => new(_haContext, "update.main_home_firmware"); ///mini-graph-card update public UpdateEntity MiniGraphCardUpdate => new(_haContext, "update.mini_graph_card_update"); ///Modern Circular Gauge update @@ -1512,6 +1700,9 @@ public partial record MediaPlayerAttributes [JsonPropertyName("sound_mode_raw")] public string? SoundModeRaw { get; init; } + + [JsonPropertyName("restored")] + public bool? Restored { get; init; } } public partial record AutomationEntity : Entity, AutomationAttributes>, IAutomationEntityCore @@ -1920,9 +2111,6 @@ public partial record InputDatetimeAttributes [JsonPropertyName("friendly_name")] public string? FriendlyName { get; init; } - - [JsonPropertyName("icon")] - public string? Icon { get; init; } } public partial record InputNumberEntity : NumericEntity, InputNumberAttributes>, IInputNumberEntityCore @@ -1991,8 +2179,14 @@ public partial record NumberAttributes [JsonPropertyName("unit_of_measurement")] public string? UnitOfMeasurement { get; init; } + [JsonPropertyName("icon")] + public string? Icon { get; init; } + [JsonPropertyName("friendly_name")] public string? FriendlyName { get; init; } + + [JsonPropertyName("device_class")] + public string? DeviceClass { get; init; } } public partial record PersonEntity : Entity, PersonAttributes>, IPersonEntityCore @@ -2054,6 +2248,9 @@ public partial record RemoteAttributes [JsonPropertyName("supported_features")] public double? SupportedFeatures { get; init; } + + [JsonPropertyName("restored")] + public bool? Restored { get; init; } } public partial record ScriptEntity : Entity, ScriptAttributes>, IScriptEntityCore @@ -2124,6 +2321,9 @@ public partial record SensorAttributes [JsonPropertyName("device_class")] public string? DeviceClass { get; init; } + [JsonPropertyName("icon")] + public string? Icon { get; init; } + [JsonPropertyName("options")] public IReadOnlyList? Options { get; init; } @@ -2133,9 +2333,6 @@ public partial record SensorAttributes [JsonPropertyName("unknown")] public double? Unknown { get; init; } - [JsonPropertyName("icon")] - public string? Icon { get; init; } - [JsonPropertyName("administrative_area")] public string? AdministrativeArea_0 { get; init; } @@ -2269,11 +2466,14 @@ public partial record SensorAttributes public string? Attribution { get; init; } [JsonPropertyName("prices")] - public IReadOnlyList? Prices { get; init; } + public IReadOnlyList>? Prices { get; init; } [JsonPropertyName("last_updated")] public string? LastUpdated { get; init; } + [JsonPropertyName("prices_count")] + public double? PricesCount { get; init; } + [JsonPropertyName("intervals")] public IReadOnlyList? Intervals { get; init; } @@ -2286,6 +2486,9 @@ public partial record SensorAttributes [JsonPropertyName("configured_price_cap")] public double? ConfiguredPriceCap { get; init; } + [JsonPropertyName("skip_price_cap")] + public bool? SkipPriceCap { get; init; } + [JsonPropertyName("configured_ready_by")] public string? ConfiguredReadyBy { get; init; } @@ -2306,15 +2509,6 @@ public partial record SensorAttributes [JsonPropertyName("power_threshold_watts")] public double? PowerThresholdWatts { get; init; } - - [JsonPropertyName("active_rules")] - public double? ActiveRules { get; init; } - - [JsonPropertyName("thresholds")] - public IReadOnlyList? Thresholds { get; init; } - - [JsonPropertyName("last_notified")] - public IReadOnlyList? LastNotified { get; init; } } public partial record NumericSensorEntity : NumericEntity, NumericSensorAttributes>, ISensorEntityCore @@ -2339,23 +2533,14 @@ public partial record NumericSensorAttributes [JsonPropertyName("friendly_name")] public string? FriendlyName { get; init; } - [JsonPropertyName("age_coverage_ratio")] - public double? AgeCoverageRatio { get; init; } - - [JsonPropertyName("source_value_valid")] - public bool? SourceValueValid { get; init; } + [JsonPropertyName("device_class")] + public string? DeviceClass { get; init; } [JsonPropertyName("icon")] public string? Icon { get; init; } - [JsonPropertyName("device_class")] - public string? DeviceClass { get; init; } - - [JsonPropertyName("entity_id")] - public IReadOnlyList? EntityId { get; init; } - - [JsonPropertyName("min_entity_id")] - public string? MinEntityId { get; init; } + [JsonPropertyName("raw_state")] + public double? RawState { get; init; } [JsonPropertyName("light")] public double? Light { get; init; } @@ -2390,30 +2575,21 @@ public partial record NumericSensorAttributes [JsonPropertyName("accuracy")] public string? Accuracy { get; init; } - [JsonPropertyName("last_period")] - public string? LastPeriod { get; init; } - - [JsonPropertyName("last_valid_state")] - public string? LastValidState { get; init; } - - [JsonPropertyName("last_reset")] - public string? LastReset { get; init; } - - [JsonPropertyName("next_reset")] - public string? NextReset { get; init; } + [JsonPropertyName("entity_id")] + public IReadOnlyList? EntityId { get; init; } [JsonPropertyName("attribution")] public string? Attribution { get; init; } + [JsonPropertyName("source")] + public string? Source { get; init; } + [JsonPropertyName("integration")] public string? Integration { get; init; } [JsonPropertyName("capabilities")] public IReadOnlyList? Capabilities { get; init; } - [JsonPropertyName("source")] - public string? Source { get; init; } - [JsonPropertyName("last_updated")] public string? LastUpdated { get; init; } @@ -2426,11 +2602,23 @@ public partial record NumericSensorAttributes [JsonPropertyName("current_quarter_index")] public double? CurrentQuarterIndex { get; init; } + [JsonPropertyName("formatted")] + public string? Formatted { get; init; } + + [JsonPropertyName("budget_hours")] + public double? BudgetHours { get; init; } + [JsonPropertyName("measurement_type")] public string? MeasurementType { get; init; } [JsonPropertyName("battery_voltage")] public double? BatteryVoltage { get; init; } + + [JsonPropertyName("restored")] + public bool? Restored { get; init; } + + [JsonPropertyName("supported_features")] + public double? SupportedFeatures { get; init; } } public partial record SunEntity : Entity, SunAttributes>, ISunEntityCore @@ -2493,6 +2681,12 @@ public partial record SwitchAttributes [JsonPropertyName("friendly_name")] public string? FriendlyName { get; init; } + [JsonPropertyName("current")] + public bool? Current { get; init; } + + [JsonPropertyName("raw_state")] + public bool? RawState { get; init; } + [JsonPropertyName("integration")] public string? Integration { get; init; } @@ -2501,6 +2695,44 @@ public partial record SwitchAttributes [JsonPropertyName("device_class")] public string? DeviceClass { get; init; } + + [JsonPropertyName("assumed_state")] + public bool? AssumedState { get; init; } + + [JsonPropertyName("icon")] + public string? Icon { get; init; } +} + +public partial record TextEntity : Entity, TextAttributes> +{ + public TextEntity(IHaContext haContext, string entityId) : base(haContext, entityId) + { + } + + public TextEntity(IEntityCore entity) : base(entity) + { + } +} + +public partial record TextAttributes +{ + [JsonPropertyName("mode")] + public string? Mode { get; init; } + + [JsonPropertyName("min")] + public double? Min { get; init; } + + [JsonPropertyName("max")] + public double? Max { get; init; } + + [JsonPropertyName("pattern")] + public object? Pattern { get; init; } + + [JsonPropertyName("icon")] + public string? Icon { get; init; } + + [JsonPropertyName("friendly_name")] + public string? FriendlyName { get; init; } } public partial record TtsEntity : Entity, TtsAttributes> @@ -2730,6 +2962,8 @@ public interface IServices LightServices Light { get; } + LocaltuyaServices Localtuya { get; } + LockServices Lock { get; } LogbookServices Logbook { get; } @@ -2776,6 +3010,8 @@ public interface IServices TemplateServices Template { get; } + TextServices Text { get; } + TimeServices Time { get; } TimerServices Timer { get; } @@ -2784,8 +3020,6 @@ public interface IServices UpdateServices Update { get; } - UtilityMeterServices UtilityMeter { get; } - VacuumServices Vacuum { get; } ValveServices Valve { get; } @@ -2833,6 +3067,7 @@ public partial class Services : IServices public InputSelectServices InputSelect => new(_haContext); public InputTextServices InputText => new(_haContext); public LightServices Light => new(_haContext); + public LocaltuyaServices Localtuya => new(_haContext); public LockServices Lock => new(_haContext); public LogbookServices Logbook => new(_haContext); public LoggerServices Logger => new(_haContext); @@ -2856,11 +3091,11 @@ public partial class Services : IServices public SpookServices Spook => new(_haContext); public SwitchServices Switch => new(_haContext); public TemplateServices Template => new(_haContext); + public TextServices Text => new(_haContext); public TimeServices Time => new(_haContext); public TimerServices Timer => new(_haContext); public TtsServices Tts => new(_haContext); public UpdateServices Update => new(_haContext); - public UtilityMeterServices UtilityMeter => new(_haContext); public VacuumServices Vacuum => new(_haContext); public ValveServices Valve => new(_haContext); public WeatherServices Weather => new(_haContext); @@ -5779,14 +6014,13 @@ public partial class LightServices /// /// eg: [300, 70] /// eg: [0.52, 0.43] - /// /// /// /// eg: relax /// - public void Toggle(ServiceTarget target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, object? colorTemp = null, long? brightness = null, object? white = null, string? profile = null, object? flash = null) + public void Toggle(ServiceTarget target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, long? brightness = null, object? white = null, string? profile = null, object? flash = null) { - _haContext.CallService("light", "toggle", target, new LightToggleParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, ColorTemp = colorTemp, Brightness = brightness, White = white, Profile = profile, Flash = flash }); + _haContext.CallService("light", "toggle", target, new LightToggleParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, Brightness = brightness, White = white, Profile = profile, Flash = flash }); } ///The target for this service call @@ -5819,15 +6053,14 @@ public partial class LightServices /// /// eg: [300, 70] /// eg: [0.52, 0.43] - /// /// /// /// /// eg: relax /// - public void TurnOn(ServiceTarget target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, long? brightnessStepPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, object? colorTemp = null, long? brightness = null, long? brightnessStep = null, object? white = null, string? profile = null, object? flash = null) + public void TurnOn(ServiceTarget target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, long? brightnessStepPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, long? brightness = null, long? brightnessStep = null, object? white = null, string? profile = null, object? flash = null) { - _haContext.CallService("light", "turn_on", target, new LightTurnOnParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, BrightnessStepPct = brightnessStepPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, ColorTemp = colorTemp, Brightness = brightness, BrightnessStep = brightnessStep, White = white, Profile = profile, Flash = flash }); + _haContext.CallService("light", "turn_on", target, new LightTurnOnParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, BrightnessStepPct = brightnessStepPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, Brightness = brightness, BrightnessStep = brightnessStep, White = white, Profile = profile, Flash = flash }); } } @@ -5868,9 +6101,6 @@ public partial record LightToggleParameters [JsonPropertyName("xy_color")] public object? XyColor { get; init; } - [JsonPropertyName("color_temp")] - public object? ColorTemp { get; init; } - [JsonPropertyName("brightness")] public long? Brightness { get; init; } @@ -5934,9 +6164,6 @@ public partial record LightTurnOnParameters [JsonPropertyName("xy_color")] public object? XyColor { get; init; } - [JsonPropertyName("color_temp")] - public object? ColorTemp { get; init; } - [JsonPropertyName("brightness")] public long? Brightness { get; init; } @@ -5954,6 +6181,51 @@ public partial record LightTurnOnParameters public object? Flash { get; init; } } +public partial class LocaltuyaServices +{ + private readonly IHaContext _haContext; + public LocaltuyaServices(IHaContext haContext) + { + _haContext = haContext; + } + + ///Reload localtuya and reconnect to all devices. + public void Reload(object? data = null) + { + _haContext.CallService("localtuya", "reload", null, data); + } + + ///Change the value of a datapoint (DP) + public void SetDp(LocaltuyaSetDpParameters data) + { + _haContext.CallService("localtuya", "set_dp", null, data); + } + + ///Change the value of a datapoint (DP) + ///Device ID of device to change datapoint value for eg: 11100118278aab4de001 + ///Datapoint index eg: 1 + ///New value to set eg: False + public void SetDp(object? deviceId = null, object? dp = null, object? value = null) + { + _haContext.CallService("localtuya", "set_dp", null, new LocaltuyaSetDpParameters { DeviceId = deviceId, Dp = dp, Value = value }); + } +} + +public partial record LocaltuyaSetDpParameters +{ + ///Device ID of device to change datapoint value for eg: 11100118278aab4de001 + [JsonPropertyName("device_id")] + public object? DeviceId { get; init; } + + ///Datapoint index eg: 1 + [JsonPropertyName("dp")] + public object? Dp { get; init; } + + ///New value to set eg: False + [JsonPropertyName("value")] + public object? Value { get; init; } +} + public partial class LockServices { private readonly IHaContext _haContext; @@ -7930,6 +8202,34 @@ public partial class TemplateServices } } +public partial class TextServices +{ + private readonly IHaContext _haContext; + public TextServices(IHaContext haContext) + { + _haContext = haContext; + } + + ///The target for this service call + public void SetValue(ServiceTarget target, TextSetValueParameters data) + { + _haContext.CallService("text", "set_value", target, data); + } + + /// eg: Hello world! + public void SetValue(ServiceTarget target, string value) + { + _haContext.CallService("text", "set_value", target, new TextSetValueParameters { Value = value }); + } +} + +public partial record TextSetValueParameters +{ + /// eg: Hello world! + [JsonPropertyName("value")] + public string? Value { get; init; } +} + public partial class TimeServices { private readonly IHaContext _haContext; @@ -8182,40 +8482,6 @@ public partial record UpdateInstallParameters public bool? Backup { get; init; } } -public partial class UtilityMeterServices -{ - private readonly IHaContext _haContext; - public UtilityMeterServices(IHaContext haContext) - { - _haContext = haContext; - } - - ///The target for this service call - public void Calibrate(ServiceTarget target, UtilityMeterCalibrateParameters data) - { - _haContext.CallService("utility_meter", "calibrate", target, data); - } - - /// eg: 100 - public void Calibrate(ServiceTarget target, string value) - { - _haContext.CallService("utility_meter", "calibrate", target, new UtilityMeterCalibrateParameters { Value = value }); - } - - ///The target for this service call - public void Reset(ServiceTarget target, object? data = null) - { - _haContext.CallService("utility_meter", "reset", target, data); - } -} - -public partial record UtilityMeterCalibrateParameters -{ - /// eg: 100 - [JsonPropertyName("value")] - public string? Value { get; init; } -} - public partial class VacuumServices { private readonly IHaContext _haContext; @@ -8224,6 +8490,18 @@ public partial class VacuumServices _haContext = haContext; } + ///The target for this service call + public void CleanArea(ServiceTarget target, VacuumCleanAreaParameters data) + { + _haContext.CallService("vacuum", "clean_area", target, data); + } + + /// + public void CleanArea(ServiceTarget target, IEnumerable cleaningAreaId) + { + _haContext.CallService("vacuum", "clean_area", target, new VacuumCleanAreaParameters { CleaningAreaId = cleaningAreaId }); + } + ///The target for this service call public void CleanSpot(ServiceTarget target, object? data = null) { @@ -8286,6 +8564,12 @@ public partial class VacuumServices } } +public partial record VacuumCleanAreaParameters +{ + [JsonPropertyName("cleaning_area_id")] + public IEnumerable? CleaningAreaId { get; init; } +} + public partial record VacuumSendCommandParameters { /// eg: set_dnd_timer @@ -12794,14 +13078,13 @@ public static class LightEntityExtensionMethods /// /// eg: [300, 70] /// eg: [0.52, 0.43] - /// /// /// /// eg: relax /// - public static void Toggle(this ILightEntityCore target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, object? colorTemp = null, long? brightness = null, object? white = null, string? profile = null, object? flash = null) + public static void Toggle(this ILightEntityCore target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, long? brightness = null, object? white = null, string? profile = null, object? flash = null) { - target.CallService("toggle", new LightToggleParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, ColorTemp = colorTemp, Brightness = brightness, White = white, Profile = profile, Flash = flash }); + target.CallService("toggle", new LightToggleParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, Brightness = brightness, White = white, Profile = profile, Flash = flash }); } ///The IEnumerable<ILightEntityCore> to call this service for @@ -12815,14 +13098,13 @@ public static class LightEntityExtensionMethods /// /// eg: [300, 70] /// eg: [0.52, 0.43] - /// /// /// /// eg: relax /// - public static void Toggle(this IEnumerable target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, object? colorTemp = null, long? brightness = null, object? white = null, string? profile = null, object? flash = null) + public static void Toggle(this IEnumerable target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, long? brightness = null, object? white = null, string? profile = null, object? flash = null) { - target.CallService("toggle", new LightToggleParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, ColorTemp = colorTemp, Brightness = brightness, White = white, Profile = profile, Flash = flash }); + target.CallService("toggle", new LightToggleParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, Brightness = brightness, White = white, Profile = profile, Flash = flash }); } public static void TurnOff(this ILightEntityCore target, LightTurnOffParameters data) @@ -12873,15 +13155,14 @@ public static class LightEntityExtensionMethods /// /// eg: [300, 70] /// eg: [0.52, 0.43] - /// /// /// /// /// eg: relax /// - public static void TurnOn(this ILightEntityCore target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, long? brightnessStepPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, object? colorTemp = null, long? brightness = null, long? brightnessStep = null, object? white = null, string? profile = null, object? flash = null) + public static void TurnOn(this ILightEntityCore target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, long? brightnessStepPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, long? brightness = null, long? brightnessStep = null, object? white = null, string? profile = null, object? flash = null) { - target.CallService("turn_on", new LightTurnOnParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, BrightnessStepPct = brightnessStepPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, ColorTemp = colorTemp, Brightness = brightness, BrightnessStep = brightnessStep, White = white, Profile = profile, Flash = flash }); + target.CallService("turn_on", new LightTurnOnParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, BrightnessStepPct = brightnessStepPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, Brightness = brightness, BrightnessStep = brightnessStep, White = white, Profile = profile, Flash = flash }); } ///The IEnumerable<ILightEntityCore> to call this service for @@ -12896,15 +13177,14 @@ public static class LightEntityExtensionMethods /// /// eg: [300, 70] /// eg: [0.52, 0.43] - /// /// /// /// /// eg: relax /// - public static void TurnOn(this IEnumerable target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, long? brightnessStepPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, object? colorTemp = null, long? brightness = null, long? brightnessStep = null, object? white = null, string? profile = null, object? flash = null) + public static void TurnOn(this IEnumerable target, long? transition = null, IReadOnlyCollection? rgbColor = null, object? colorTempKelvin = null, long? brightnessPct = null, long? brightnessStepPct = null, string? effect = null, object? rgbwColor = null, object? rgbwwColor = null, object? colorName = null, object? hsColor = null, object? xyColor = null, long? brightness = null, long? brightnessStep = null, object? white = null, string? profile = null, object? flash = null) { - target.CallService("turn_on", new LightTurnOnParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, BrightnessStepPct = brightnessStepPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, ColorTemp = colorTemp, Brightness = brightness, BrightnessStep = brightnessStep, White = white, Profile = profile, Flash = flash }); + target.CallService("turn_on", new LightTurnOnParameters { Transition = transition, RgbColor = rgbColor, ColorTempKelvin = colorTempKelvin, BrightnessPct = brightnessPct, BrightnessStepPct = brightnessStepPct, Effect = effect, RgbwColor = rgbwColor, RgbwwColor = rgbwwColor, ColorName = colorName, HsColor = hsColor, XyColor = xyColor, Brightness = brightness, BrightnessStep = brightnessStep, White = white, Profile = profile, Flash = flash }); } } @@ -13778,6 +14058,33 @@ public static class SwitchEntityExtensionMethods } } +public static class TextEntityExtensionMethods +{ + public static void SetValue(this TextEntity target, TextSetValueParameters data) + { + target.CallService("set_value", data); + } + + public static void SetValue(this IEnumerable target, TextSetValueParameters data) + { + target.CallService("set_value", data); + } + + ///The TextEntity to call this service for + /// eg: Hello world! + public static void SetValue(this TextEntity target, string value) + { + target.CallService("set_value", new TextSetValueParameters { Value = value }); + } + + ///The IEnumerable<TextEntity> to call this service for + /// eg: Hello world! + public static void SetValue(this IEnumerable target, string value) + { + target.CallService("set_value", new TextSetValueParameters { Value = value }); + } +} + public static class TtsEntityExtensionMethods { public static void Speak(this TtsEntity target, TtsSpeakParameters data) @@ -13862,43 +14169,6 @@ public static class UpdateEntityExtensionMethods } } -public static class UtilityMeterEntityExtensionMethods -{ - public static void Calibrate(this ISensorEntityCore target, UtilityMeterCalibrateParameters data) - { - target.CallService("calibrate", data); - } - - public static void Calibrate(this IEnumerable target, UtilityMeterCalibrateParameters data) - { - target.CallService("calibrate", data); - } - - ///The ISensorEntityCore to call this service for - /// eg: 100 - public static void Calibrate(this ISensorEntityCore target, string value) - { - target.CallService("calibrate", new UtilityMeterCalibrateParameters { Value = value }); - } - - ///The IEnumerable<ISensorEntityCore> to call this service for - /// eg: 100 - public static void Calibrate(this IEnumerable target, string value) - { - target.CallService("calibrate", new UtilityMeterCalibrateParameters { Value = value }); - } - - public static void Reset(this ISelectEntityCore target, object? data = null) - { - target.CallService("reset", data); - } - - public static void Reset(this IEnumerable target, object? data = null) - { - target.CallService("reset", data); - } -} - public static class WeatherEntityExtensionMethods { public static Task GetForecastsAsync(this IWeatherEntityCore target, WeatherGetForecastsParameters data) diff --git a/HomeAssistant.Entities/HomeAssistant.Entities.csproj b/HomeAssistant.Entities/HomeAssistant.Entities.csproj index f76e1f0..e4c528e 100644 --- a/HomeAssistant.Entities/HomeAssistant.Entities.csproj +++ b/HomeAssistant.Entities/HomeAssistant.Entities.csproj @@ -1,4 +1,4 @@ - + net10.0 @@ -7,14 +7,14 @@ - - - - - - - - + + + + + + + + diff --git a/HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs b/HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs new file mode 100644 index 0000000..e56b966 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs @@ -0,0 +1,69 @@ +using BoilerMonitor.Models; +using LightMonitor.Models; +using NordPool.Models; +using ShowerMonitor.Models; + +namespace HomeAssistant.HistoryReplay.Configuration; + +public static class ReplayEntityMap +{ + public static IReadOnlyList GetNordPoolEntities() => + [ + "sensor.nordpool_kwh_lt_eur_3_10_0", + NordPoolConsts.CurrentPriceEntityId, + BoilerMonitorConsts.BoilerDailyHoursEntityId, + BoilerMonitorConsts.BoilerPriceCapEntityId, + BoilerMonitorConsts.BoilerReadyByEntityId, + BoilerMonitorConsts.SkipPriceCapEntityId + ]; + + public static IReadOnlyList GetBoilerEntities(string boilerPowerEntityId, string boilerSwitchEntityId) => + [ + boilerPowerEntityId, + boilerSwitchEntityId, + "sensor.nordpool_cheapest_intervals", + BoilerMonitorConsts.SkipPriceCapEntityId, + BoilerMonitorConsts.BudgetOverrideEntityId, + BoilerMonitorConsts.BoilerDailyHoursEntityId + ]; + + public static IReadOnlyList GetShowerEntities(string bathroomHumidityEntityId, string mainHomeHumidityEntityId) => + [ + bathroomHumidityEntityId, + mainHomeHumidityEntityId + ]; + + public static IReadOnlyList GetPowerEntities(string mainMeterEntityId) => + [ + mainMeterEntityId, + NordPoolConsts.CurrentPriceEntityId + ]; + + public static IReadOnlyList GetLightEntities(string sunEntityId, string lightEntityId, string[] personEntityIds) + { + var entities = new List { sunEntityId, lightEntityId }; + entities.AddRange(personEntityIds); + return entities; + } + + public static IReadOnlyList GetAllEntities( + string boilerPowerEntityId, + string boilerSwitchEntityId, + string bathroomHumidityEntityId, + string mainHomeHumidityEntityId, + string mainMeterEntityId, + string sunEntityId, + string lightEntityId, + string[] personEntityIds) + { + var all = new HashSet(); + + foreach (var e in GetNordPoolEntities()) all.Add(e); + foreach (var e in GetBoilerEntities(boilerPowerEntityId, boilerSwitchEntityId)) all.Add(e); + foreach (var e in GetShowerEntities(bathroomHumidityEntityId, mainHomeHumidityEntityId)) all.Add(e); + foreach (var e in GetPowerEntities(mainMeterEntityId)) all.Add(e); + foreach (var e in GetLightEntities(sunEntityId, lightEntityId, personEntityIds)) all.Add(e); + + return [.. all]; + } +} diff --git a/HomeAssistant.HistoryReplay/Configuration/ReplayOptions.cs b/HomeAssistant.HistoryReplay/Configuration/ReplayOptions.cs new file mode 100644 index 0000000..ff2a7a2 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Configuration/ReplayOptions.cs @@ -0,0 +1,19 @@ +namespace HomeAssistant.HistoryReplay.Configuration; + +public sealed class ReplayOptions +{ + public const string SectionName = "Replay"; + + public DateTimeOffset StartTime { get; set; } = DateTimeOffset.UtcNow.AddDays(-1); + public DateTimeOffset EndTime { get; set; } = DateTimeOffset.UtcNow; + public ReplayMonitorFlags Monitors { get; set; } = new(); +} + +public sealed class ReplayMonitorFlags +{ + public bool NordPool { get; set; } = true; + public bool Boiler { get; set; } = true; + public bool Shower { get; set; } = true; + public bool Power { get; set; } = true; + public bool Light { get; set; } = true; +} diff --git a/HomeAssistant.HistoryReplay/HistoryData/HistoryStateEntry.cs b/HomeAssistant.HistoryReplay/HistoryData/HistoryStateEntry.cs new file mode 100644 index 0000000..e750663 --- /dev/null +++ b/HomeAssistant.HistoryReplay/HistoryData/HistoryStateEntry.cs @@ -0,0 +1,9 @@ +namespace HomeAssistant.HistoryReplay.HistoryData; + +public sealed class HistoryStateEntry +{ + public required string EntityId { get; init; } + public required string? State { get; init; } + public required DateTimeOffset LastChanged { get; init; } + public IReadOnlyDictionary? Attributes { get; init; } +} diff --git a/HomeAssistant.HistoryReplay/HistoryData/HistoryTimeline.cs b/HomeAssistant.HistoryReplay/HistoryData/HistoryTimeline.cs new file mode 100644 index 0000000..420afb4 --- /dev/null +++ b/HomeAssistant.HistoryReplay/HistoryData/HistoryTimeline.cs @@ -0,0 +1,65 @@ +namespace HomeAssistant.HistoryReplay.HistoryData; + +public sealed class HistoryTimeline +{ + private readonly Dictionary> _entityTimelines = new(StringComparer.OrdinalIgnoreCase); + + public void AddEntries(string entityId, IEnumerable entries) + { + if (!_entityTimelines.TryGetValue(entityId, out var list)) + { + list = []; + _entityTimelines[entityId] = list; + } + + list.AddRange(entries); + list.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged)); + } + + public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp) + { + if (!_entityTimelines.TryGetValue(entityId, out var entries) || entries.Count == 0) + { + return null; + } + + HistoryStateEntry? best = null; + foreach (var entry in entries) + { + if (entry.LastChanged <= timestamp) + { + best = entry; + } + else + { + break; + } + } + + return best; + } + + public IReadOnlyList GetAllTimestamps() + { + var timestamps = new SortedSet(); + + foreach (var entries in _entityTimelines.Values) + { + foreach (var entry in entries) + { + timestamps.Add(entry.LastChanged); + } + } + + return [.. timestamps]; + } + + public IReadOnlyList GetEntityIds() => [.. _entityTimelines.Keys]; + + public IReadOnlyList GetEntityHistory(string entityId) + { + return _entityTimelines.TryGetValue(entityId, out var entries) ? entries : []; + } + + public int TotalEntryCount => _entityTimelines.Values.Sum(e => e.Count); +} diff --git a/HomeAssistant.HistoryReplay/HistoryData/HomeAssistantHistoryProvider.cs b/HomeAssistant.HistoryReplay/HistoryData/HomeAssistantHistoryProvider.cs new file mode 100644 index 0000000..ce03853 --- /dev/null +++ b/HomeAssistant.HistoryReplay/HistoryData/HomeAssistantHistoryProvider.cs @@ -0,0 +1,168 @@ +using System.Globalization; +using System.Text.Json; +using HomeAssistant.HistoryReplay.HomeAssistantClient; +using Microsoft.Extensions.Logging; + +namespace HomeAssistant.HistoryReplay.HistoryData; + +public sealed class HomeAssistantHistoryProvider( + IHomeAssistantApiClient client, + ILogger logger) : IHistoryDataProvider +{ + private const int MaxEntitiesPerRequest = 10; + + public async Task FetchHistoryAsync( + IReadOnlyList entityIds, + DateTimeOffset startTime, + DateTimeOffset endTime, + CancellationToken cancellationToken = default) + { + var timeline = new HistoryTimeline(); + var batches = ChunkEntities(entityIds, MaxEntitiesPerRequest); + + var tasks = batches.Select(batch => FetchBatchAsync(batch, startTime, endTime, cancellationToken)); + var results = await Task.WhenAll(tasks).ConfigureAwait(false); + + foreach (var batchTimeline in results) + { + foreach (var entityId in batchTimeline.GetEntityIds()) + { + timeline.AddEntries(entityId, batchTimeline.GetEntityHistory(entityId)); + } + } + + logger.LogInformation( + "Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})", + entityIds.Count, timeline.TotalEntryCount, startTime, endTime); + + return timeline; + } + + private async Task FetchBatchAsync( + IReadOnlyList entityIds, + DateTimeOffset startTime, + DateTimeOffset endTime, + CancellationToken cancellationToken) + { + var timeline = new HistoryTimeline(); + var entityIdsString = string.Join(",", entityIds); + + logger.LogDebug("Fetching history batch for: {Entities}", entityIdsString); + + try + { + var result = await client.GetHistoryAsync( + entityIdsString, startTime, endTime, minimalResponse: false, cancellationToken) + .ConfigureAwait(false); + + ParseHistoryResponse(result, timeline); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to fetch history for entities: {Entities}", entityIdsString); + } + + return timeline; + } + + private void ParseHistoryResponse(JsonElement response, HistoryTimeline timeline) + { + if (response.ValueKind != JsonValueKind.Array) + { + return; + } + + foreach (var entityArray in response.EnumerateArray()) + { + if (entityArray.ValueKind != JsonValueKind.Array) + { + continue; + } + + foreach (var stateObj in entityArray.EnumerateArray()) + { + var entry = ParseStateEntry(stateObj); + if (entry is not null) + { + timeline.AddEntries(entry.EntityId, [entry]); + } + } + } + } + + private HistoryStateEntry? ParseStateEntry(JsonElement stateObj) + { + if (!stateObj.TryGetProperty("entity_id", out var entityIdProp)) + { + return null; + } + + var entityId = entityIdProp.GetString(); + if (string.IsNullOrEmpty(entityId)) + { + return null; + } + + var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null; + + DateTimeOffset lastChanged; + if (stateObj.TryGetProperty("last_changed", out var lastChangedProp)) + { + if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out lastChanged)) + { + return null; + } + } + else + { + return null; + } + + Dictionary? attributes = null; + if (stateObj.TryGetProperty("attributes", out var attrProp) && attrProp.ValueKind == JsonValueKind.Object) + { + attributes = ParseAttributes(attrProp); + } + + return new HistoryStateEntry + { + EntityId = entityId, + State = state, + LastChanged = lastChanged, + Attributes = attributes + }; + } + + private static Dictionary ParseAttributes(JsonElement attrElement) + { + var attributes = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var prop in attrElement.EnumerateObject()) + { + attributes[prop.Name] = prop.Value.ValueKind switch + { + JsonValueKind.String => prop.Value.GetString() ?? string.Empty, + JsonValueKind.Number => prop.Value.GetDouble(), + JsonValueKind.True => true, + JsonValueKind.False => false, + _ => prop.Value.GetRawText() + }; + } + + return attributes; + } + + private static IReadOnlyList> ChunkEntities(IReadOnlyList entities, int chunkSize) + { + var chunks = new List>(); + + for (var i = 0; i < entities.Count; i += chunkSize) + { + var chunk = entities.Skip(i).Take(chunkSize).ToList(); + chunks.Add(chunk); + } + + return chunks; + } +} diff --git a/HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs b/HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs new file mode 100644 index 0000000..a901b03 --- /dev/null +++ b/HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs @@ -0,0 +1,10 @@ +namespace HomeAssistant.HistoryReplay.HistoryData; + +public interface IHistoryDataProvider +{ + Task FetchHistoryAsync( + IReadOnlyList entityIds, + DateTimeOffset startTime, + DateTimeOffset endTime, + CancellationToken cancellationToken = default); +} diff --git a/HomeAssistant.HistoryReplay/HomeAssistant.HistoryReplay.csproj b/HomeAssistant.HistoryReplay/HomeAssistant.HistoryReplay.csproj new file mode 100644 index 0000000..0caf4b2 --- /dev/null +++ b/HomeAssistant.HistoryReplay/HomeAssistant.HistoryReplay.csproj @@ -0,0 +1,45 @@ + + + + Exe + net10.0 + 14.0 + enable + enable + HomeAssistant.HistoryReplay + + + + + Always + + + Always + Never + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs b/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs new file mode 100644 index 0000000..2b30f42 --- /dev/null +++ b/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs @@ -0,0 +1,50 @@ +using System.Net.Http.Headers; +using System.Text.Json; +using Microsoft.Extensions.Options; + +namespace HomeAssistant.HistoryReplay.HomeAssistantClient; + +public sealed class HomeAssistantApiClient : IHomeAssistantApiClient +{ + private readonly HttpClient _httpClient; + + public HomeAssistantApiClient(HttpClient httpClient, IOptions settings) + { + _httpClient = httpClient; + _httpClient.BaseAddress = settings.Value.BaseUrl; + _httpClient.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", settings.Value.Token); + _httpClient.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue("application/json")); + _httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds); + } + + public async Task GetHistoryAsync( + string entityIds, + DateTimeOffset? startTime = null, + DateTimeOffset? endTime = null, + bool minimalResponse = true, + CancellationToken cancellationToken = default) + { + var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1); + var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}"; + + if (endTime.HasValue) + path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}"; + + if (minimalResponse) + path += "&minimal_response"; + + return await GetJsonAsync(path, cancellationToken).ConfigureAwait(false); + } + + private async Task GetJsonAsync(string path, CancellationToken cancellationToken) + { + var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); + return doc.RootElement.Clone(); + } +} diff --git a/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs b/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs new file mode 100644 index 0000000..2e99ba5 --- /dev/null +++ b/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs @@ -0,0 +1,15 @@ +namespace HomeAssistant.HistoryReplay.HomeAssistantClient; + +public sealed class HomeAssistantSettings +{ + public const string SectionName = "HomeAssistant"; + public const int DefaultPort = 8123; + public const int DefaultTimeoutSeconds = 30; + + public string Host { get; set; } = string.Empty; + public int Port { get; set; } = DefaultPort; + public string Token { get; set; } = string.Empty; + public bool Ssl { get; set; } + + public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri; +} diff --git a/HomeAssistant.HistoryReplay/HomeAssistantClient/IHomeAssistantApiClient.cs b/HomeAssistant.HistoryReplay/HomeAssistantClient/IHomeAssistantApiClient.cs new file mode 100644 index 0000000..b1c9579 --- /dev/null +++ b/HomeAssistant.HistoryReplay/HomeAssistantClient/IHomeAssistantApiClient.cs @@ -0,0 +1,13 @@ +using System.Text.Json; + +namespace HomeAssistant.HistoryReplay.HomeAssistantClient; + +public interface IHomeAssistantApiClient +{ + Task GetHistoryAsync( + string entityIds, + DateTimeOffset? startTime = null, + DateTimeOffset? endTime = null, + bool minimalResponse = true, + CancellationToken cancellationToken = default); +} diff --git a/HomeAssistant.HistoryReplay/Program.cs b/HomeAssistant.HistoryReplay/Program.cs new file mode 100644 index 0000000..0f88476 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Program.cs @@ -0,0 +1,191 @@ +using BoilerMonitorManager; +using BoilerMonitorManager.Interface; +using BoilerMonitorManager.Models; +using HomeAssistant.Entities.Interfaces; +using HomeAssistant.HistoryReplay.Configuration; +using HomeAssistant.HistoryReplay.HistoryData; +using HomeAssistant.HistoryReplay.Replay; +using HomeAssistant.HistoryReplay.Reporting; +using HomeAssistant.HistoryReplay.Runners; +using HomeAssistant.HistoryReplay.HomeAssistantClient; +using LightMonitorManager.Models; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NordPoolManager; +using NordPoolManager.Interface; +using PowerMonitorManager; +using PowerMonitorManager.Interface; +using PowerMonitorManager.Models; +using Serilog; +using ShowerMonitorManager; +using ShowerMonitorManager.Interface; +using ShowerMonitorManager.Models; + +Log.Logger = new LoggerConfiguration() + .MinimumLevel.Information() + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .CreateLogger(); + +try +{ + Log.Information("Starting Home Assistant History Replay"); + + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json", optional: false) + .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true) + .AddEnvironmentVariables() + .Build(); + + var services = new ServiceCollection(); + + services.AddLogging(builder => + { + builder.ClearProviders(); + builder.AddSerilog(dispose: true); + }); + + services.Configure(configuration.GetSection(HomeAssistantSettings.SectionName)); + services.Configure(configuration.GetSection(ReplayOptions.SectionName)); + services.Configure(configuration.GetSection(BoilerMonitorOptions.SectionName)); + services.Configure(configuration.GetSection(ShowerMonitorOptions.SectionName)); + services.Configure(configuration.GetSection(PowerMonitorOptions.SectionName)); + services.Configure(configuration.GetSection(LightMonitorOptions.SectionName)); + + services.AddHttpClient(); + services.AddSingleton(); + + var replayOptions = configuration.GetSection(ReplayOptions.SectionName).Get() ?? new ReplayOptions(); + + var replayTimeline = new ReplayTimeline(); + var replayTimeProvider = new ReplayTimeProvider(replayOptions.StartTime); + + services.AddSingleton(replayTimeline); + services.AddSingleton(replayTimeProvider); + services.AddSingleton(replayTimeProvider); + + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + var showerOptions = configuration.GetSection(ShowerMonitorOptions.SectionName).Get() ?? new ShowerMonitorOptions(); + services.AddSingleton(_ => new HumidityRateCalculator(showerOptions.RateWindowSize)); + services.AddSingleton(); + + services.AddSingleton(); + + var provider = services.BuildServiceProvider(); + + var historyProvider = provider.GetRequiredService(); + var logger = provider.GetRequiredService>(); + + var boilerOpts = provider.GetRequiredService>().Value; + var showerOpts = provider.GetRequiredService>().Value; + var powerOpts = provider.GetRequiredService>().Value; + var lightOpts = provider.GetRequiredService>().Value; + + logger.LogInformation("Replay period: {Start} to {End}", replayOptions.StartTime, replayOptions.EndTime); + + var allEntityIds = ReplayEntityMap.GetAllEntities( + boilerPowerEntityId: "sensor.boiler_power", + boilerSwitchEntityId: "switch.boiler", + bathroomHumidityEntityId: showerOpts.BathroomHumidityEntityId, + mainHomeHumidityEntityId: showerOpts.MainHomeHumidityEntityId, + mainMeterEntityId: powerOpts.MainMeterEntityId, + sunEntityId: lightOpts.SunEntityId, + lightEntityId: lightOpts.LightEntityId, + personEntityIds: lightOpts.PersonEntityIds); + + logger.LogInformation("Fetching history for {Count} entities...", allEntityIds.Count); + + var timeline = await historyProvider.FetchHistoryAsync( + allEntityIds, replayOptions.StartTime, replayOptions.EndTime); + + var replayHaContext = new ReplayHaContext( + timeline, + replayTimeProvider, + replayTimeline, + provider.GetRequiredService>()); + + var fanControlService = new ExhaustFanControlService( + replayHaContext, + provider.GetRequiredService>(), + provider.GetRequiredService>()); + + var runners = new List(); + + if (replayOptions.Monitors.NordPool) + { + runners.Add(new NordPoolReplayRunner( + timeline, replayTimeProvider, replayTimeline, + provider.GetRequiredService(), + provider.GetRequiredService>(), + provider.GetRequiredService>())); + } + + if (replayOptions.Monitors.Boiler) + { + runners.Add(new BoilerReplayRunner( + timeline, replayTimeProvider, replayTimeline, + provider.GetRequiredService(), + provider.GetRequiredService(), + provider.GetRequiredService(), + provider.GetRequiredService>(), + provider.GetRequiredService>(), + provider.GetRequiredService>())); + } + + if (replayOptions.Monitors.Shower) + { + runners.Add(new ShowerReplayRunner( + timeline, replayTimeProvider, replayTimeline, + provider.GetRequiredService(), + fanControlService, + provider.GetRequiredService>(), + provider.GetRequiredService>(), + provider.GetRequiredService>())); + } + + if (replayOptions.Monitors.Power) + { + runners.Add(new PowerReplayRunner( + timeline, replayTimeProvider, replayTimeline, + provider.GetRequiredService(), + provider.GetRequiredService(), + provider.GetRequiredService>(), + provider.GetRequiredService>(), + provider.GetRequiredService>())); + } + + if (replayOptions.Monitors.Light) + { + runners.Add(new LightReplayRunner( + timeline, replayTimeProvider, replayTimeline, + provider.GetRequiredService>(), + provider.GetRequiredService>(), + provider.GetRequiredService>())); + } + + logger.LogInformation("Running {Count} monitor replay(s) in parallel...", runners.Count); + + var replayTasks = runners.Select(r => Task.Run(() => r.RunAsync())); + await Task.WhenAll(replayTasks); + + var renderer = provider.GetRequiredService(); + renderer.Render(replayTimeline, replayOptions); +} +catch (Exception ex) +{ + Log.Fatal(ex, "History replay failed"); +} +finally +{ + await Log.CloseAndFlushAsync(); +} diff --git a/HomeAssistant.HistoryReplay/Replay/NoOpEntityManager.cs b/HomeAssistant.HistoryReplay/Replay/NoOpEntityManager.cs new file mode 100644 index 0000000..4d71e51 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Replay/NoOpEntityManager.cs @@ -0,0 +1,38 @@ +using HomeAssistant.Entities.Interfaces; +using HomeAssistant.Models; +using Microsoft.Extensions.Logging; + +namespace HomeAssistant.HistoryReplay.Replay; + +public sealed class NoOpEntityManager(ILogger logger) : IEntityManager +{ + public Task CreateEntitiesAsync(ICollection entities) + { + logger.LogDebug("[REPLAY] Would create {Count} entities", entities.Count); + return Task.CompletedTask; + } + + public Task CreateEntityAsync(EntityCreateModel createModel) + { + logger.LogDebug("[REPLAY] Would create entity: {EntityId}", createModel.EntityId); + return Task.CompletedTask; + } + + public Task SetEntityState(string entityId, string state) + { + logger.LogDebug("[REPLAY] Would set state for {EntityId}: {State}", entityId, state); + return Task.CompletedTask; + } + + public Task SetEntityAttributes(string entityId, object attributes) + { + logger.LogDebug("[REPLAY] Would set attributes for {EntityId}", entityId); + return Task.CompletedTask; + } + + public Task RemoveEntity(string entityId) + { + logger.LogDebug("[REPLAY] Would remove entity: {EntityId}", entityId); + return Task.CompletedTask; + } +} diff --git a/HomeAssistant.HistoryReplay/Replay/ReplayHaContext.cs b/HomeAssistant.HistoryReplay/Replay/ReplayHaContext.cs new file mode 100644 index 0000000..5d79762 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Replay/ReplayHaContext.cs @@ -0,0 +1,98 @@ +using System.Reactive.Linq; +using System.Text.Json; +using HomeAssistant.HistoryReplay.HistoryData; +using HomeAssistant.HistoryReplay.Reporting; +using Microsoft.Extensions.Logging; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; + +namespace HomeAssistant.HistoryReplay.Replay; + +public sealed class ReplayHaContext : IHaContext +{ + private readonly HistoryTimeline _timeline; + private readonly ReplayTimeProvider _timeProvider; + private readonly ReplayTimeline _replayTimeline; + private readonly ILogger _logger; + + public ReplayHaContext( + HistoryTimeline timeline, + ReplayTimeProvider timeProvider, + ReplayTimeline replayTimeline, + ILogger logger) + { + _timeline = timeline; + _timeProvider = timeProvider; + _replayTimeline = replayTimeline; + _logger = logger; + } + + public EntityState? GetState(string entityId) + { + var currentTime = _timeProvider.GetUtcNow(); + var entry = _timeline.GetStateAt(entityId, currentTime); + + if (entry is null) + { + return null; + } + + JsonElement? attributesJson = null; + if (entry.Attributes is { Count: > 0 }) + { + attributesJson = JsonSerializer.SerializeToElement(entry.Attributes); + } + + return new EntityState + { + State = entry.State, + AttributesJson = attributesJson + }; + } + + public IReadOnlyList GetAllEntities() + { + return _timeline.GetEntityIds() + .Select(id => new Entity(this, id)) + .ToList(); + } + + public void CallService(string domain, string service, ServiceTarget? target = null, object? data = null) + { + var currentTime = _timeProvider.GetUtcNow(); + var targetDescription = target?.EntityIds is not null + ? string.Join(", ", target.EntityIds) + : "no target"; + + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = "ServiceCall", + EventType = ReplayEventType.ServiceCall, + Message = $"Would call {domain}.{service} on {targetDescription}", + Details = data is not null ? JsonSerializer.Serialize(data) : null + }); + + _logger.LogDebug("[REPLAY] {Domain}.{Service} → {Target}", domain, service, targetDescription); + } + + public void SendEvent(string eventType, object? data = null) + { + _logger.LogDebug("[REPLAY] Would send event: {EventType}", eventType); + } + + public IObservable StateAllChanges() => Observable.Empty(); + + public IObservable Events => Observable.Empty(); + + public Task CallServiceWithResponseAsync( + string domain, string service, ServiceTarget? target = null, object? data = null) + { + CallService(domain, service, target, data); + return Task.FromResult(null); + } + + public Area? GetAreaFromEntityId(string entityId) => null; + + public EntityRegistration? GetEntityRegistration(string entityId) => null; +} diff --git a/HomeAssistant.HistoryReplay/Replay/ReplayTimeProvider.cs b/HomeAssistant.HistoryReplay/Replay/ReplayTimeProvider.cs new file mode 100644 index 0000000..6847249 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Replay/ReplayTimeProvider.cs @@ -0,0 +1,40 @@ +namespace HomeAssistant.HistoryReplay.Replay; + +public sealed class ReplayTimeProvider : TimeProvider +{ + private readonly Lock _lock = new(); + private DateTimeOffset _currentUtcTime; + private readonly TimeZoneInfo _localTimeZone; + + public ReplayTimeProvider(DateTimeOffset initialTime) + { + _currentUtcTime = initialTime.ToUniversalTime(); + _localTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); + } + + public override DateTimeOffset GetUtcNow() + { + lock (_lock) + { + return _currentUtcTime; + } + } + + public override TimeZoneInfo LocalTimeZone => _localTimeZone; + + public void AdvanceTo(DateTimeOffset utcTime) + { + lock (_lock) + { + _currentUtcTime = utcTime.ToUniversalTime(); + } + } + + public void AdvanceBy(TimeSpan duration) + { + lock (_lock) + { + _currentUtcTime += duration; + } + } +} diff --git a/HomeAssistant.HistoryReplay/Reporting/ConsoleReportRenderer.cs b/HomeAssistant.HistoryReplay/Reporting/ConsoleReportRenderer.cs new file mode 100644 index 0000000..7227fb1 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Reporting/ConsoleReportRenderer.cs @@ -0,0 +1,146 @@ +using HomeAssistant.HistoryReplay.Configuration; + +namespace HomeAssistant.HistoryReplay.Reporting; + +public sealed class ConsoleReportRenderer +{ + private const string Separator = "═══════════════════════════════════════════════════════════"; + private const string SectionSeparator = "── {0} ──────────────────────────────────────────────"; + private const string TimeFormat = "HH:mm:ss"; + + public void Render(ReplayTimeline timeline, ReplayOptions options) + { + Console.WriteLine(); + WriteColored(Separator, ConsoleColor.DarkCyan); + WriteColored($" REPLAY: {options.StartTime:yyyy-MM-dd HH:mm} → {options.EndTime:yyyy-MM-dd HH:mm}", ConsoleColor.White); + WriteColored(Separator, ConsoleColor.DarkCyan); + Console.WriteLine(); + + var monitors = timeline.GetMonitors() + .Where(m => !string.Equals(m, "ServiceCall", StringComparison.OrdinalIgnoreCase)) + .ToList(); + + foreach (var monitor in monitors) + { + RenderMonitorSection(monitor, timeline.GetEventsByMonitor(monitor)); + } + + RenderServiceCallSection(timeline.GetEventsByMonitor("ServiceCall")); + RenderSummary(timeline); + } + + private static void RenderMonitorSection(string monitor, IReadOnlyList events) + { + Console.WriteLine(); + WriteColored(string.Format(SectionSeparator, monitor), ConsoleColor.Yellow); + + if (events.Count == 0) + { + WriteColored(" No events recorded", ConsoleColor.DarkGray); + return; + } + + foreach (var evt in events) + { + var color = GetEventColor(evt.EventType); + var prefix = GetEventPrefix(evt.EventType); + var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat); + + WriteColored($" {timestamp} {prefix}{evt.Message}", color); + + if (!string.IsNullOrEmpty(evt.Details)) + { + WriteColored($" {evt.Details}", ConsoleColor.DarkGray); + } + } + + WriteSectionSummary(events); + } + + private static void RenderServiceCallSection(IReadOnlyList events) + { + if (events.Count == 0) + { + return; + } + + Console.WriteLine(); + WriteColored(string.Format(SectionSeparator, "Service Calls"), ConsoleColor.Magenta); + + foreach (var evt in events) + { + var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat); + WriteColored($" {timestamp} → {evt.Message}", ConsoleColor.DarkMagenta); + } + + WriteColored($"\n Total: {events.Count} service call(s) would have been made", ConsoleColor.DarkGray); + } + + private static void RenderSummary(ReplayTimeline timeline) + { + var allEvents = timeline.GetAllEvents(); + + Console.WriteLine(); + WriteColored(Separator, ConsoleColor.DarkCyan); + WriteColored(" REPLAY SUMMARY", ConsoleColor.White); + WriteColored(Separator, ConsoleColor.DarkCyan); + + var decisions = allEvents.Count(e => e.EventType == ReplayEventType.Decision); + var serviceCalls = allEvents.Count(e => e.EventType == ReplayEventType.ServiceCall); + var warnings = allEvents.Count(e => e.EventType == ReplayEventType.Warning); + var anomalies = allEvents.Count(e => e.EventType == ReplayEventType.Anomaly); + + WriteColored($" Total events: {allEvents.Count}", ConsoleColor.Gray); + WriteColored($" Decisions: {decisions}", ConsoleColor.Cyan); + WriteColored($" Service calls: {serviceCalls}", ConsoleColor.Magenta); + WriteColored($" Warnings: {warnings}", ConsoleColor.DarkYellow); + WriteColored($" Anomalies: {anomalies}", ConsoleColor.Red); + Console.WriteLine(); + } + + private static void WriteSectionSummary(IReadOnlyList events) + { + var decisions = events.Count(e => e.EventType == ReplayEventType.Decision); + var warnings = events.Count(e => e.EventType == ReplayEventType.Warning); + var stateChanges = events.Count(e => e.EventType == ReplayEventType.StateChange); + + var parts = new List(); + if (decisions > 0) parts.Add($"{decisions} decision(s)"); + if (stateChanges > 0) parts.Add($"{stateChanges} state change(s)"); + if (warnings > 0) parts.Add($"{warnings} warning(s)"); + + if (parts.Count > 0) + { + WriteColored($"\n Summary: {string.Join(", ", parts)}", ConsoleColor.DarkGray); + } + } + + private static ConsoleColor GetEventColor(ReplayEventType eventType) => + eventType switch + { + ReplayEventType.Decision => ConsoleColor.Green, + ReplayEventType.StateChange => ConsoleColor.Cyan, + ReplayEventType.Warning => ConsoleColor.DarkYellow, + ReplayEventType.ServiceCall => ConsoleColor.Magenta, + ReplayEventType.Anomaly => ConsoleColor.Red, + _ => ConsoleColor.Gray + }; + + private static string GetEventPrefix(ReplayEventType eventType) => + eventType switch + { + ReplayEventType.Decision => "→ ", + ReplayEventType.Warning => "⚠ ", + ReplayEventType.Anomaly => "⚠ ANOMALY: ", + ReplayEventType.ServiceCall => "⤷ ", + _ => "" + }; + + private static void WriteColored(string text, ConsoleColor color) + { + var previousColor = Console.ForegroundColor; + Console.ForegroundColor = color; + Console.WriteLine(text); + Console.ForegroundColor = previousColor; + } +} diff --git a/HomeAssistant.HistoryReplay/Reporting/ReplayEvent.cs b/HomeAssistant.HistoryReplay/Reporting/ReplayEvent.cs new file mode 100644 index 0000000..463e2f0 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Reporting/ReplayEvent.cs @@ -0,0 +1,20 @@ +namespace HomeAssistant.HistoryReplay.Reporting; + +public sealed class ReplayEvent +{ + public required DateTimeOffset Timestamp { get; init; } + public required string Monitor { get; init; } + public required ReplayEventType EventType { get; init; } + public required string Message { get; init; } + public string? Details { get; init; } +} + +public enum ReplayEventType +{ + Info, + Decision, + StateChange, + Warning, + ServiceCall, + Anomaly +} diff --git a/HomeAssistant.HistoryReplay/Reporting/ReplayTimeline.cs b/HomeAssistant.HistoryReplay/Reporting/ReplayTimeline.cs new file mode 100644 index 0000000..0ed9d83 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Reporting/ReplayTimeline.cs @@ -0,0 +1,25 @@ +using System.Collections.Concurrent; + +namespace HomeAssistant.HistoryReplay.Reporting; + +public sealed class ReplayTimeline +{ + private readonly ConcurrentBag _events = []; + + public void AddEvent(ReplayEvent replayEvent) + { + _events.Add(replayEvent); + } + + public IReadOnlyList GetEventsByMonitor(string monitor) => + _events + .Where(e => string.Equals(e.Monitor, monitor, StringComparison.OrdinalIgnoreCase)) + .OrderBy(e => e.Timestamp) + .ToList(); + + public IReadOnlyList GetAllEvents() => + _events.OrderBy(e => e.Timestamp).ToList(); + + public IReadOnlyList GetMonitors() => + _events.Select(e => e.Monitor).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToList(); +} diff --git a/HomeAssistant.HistoryReplay/Runners/BoilerReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/BoilerReplayRunner.cs new file mode 100644 index 0000000..0ed3c5e --- /dev/null +++ b/HomeAssistant.HistoryReplay/Runners/BoilerReplayRunner.cs @@ -0,0 +1,210 @@ +using System.Globalization; +using BoilerMonitor.Models; +using BoilerMonitor.Models.Enums; +using BoilerMonitorManager.Interface; +using HomeAssistant.HistoryReplay.Configuration; +using HomeAssistant.HistoryReplay.HistoryData; +using HomeAssistant.HistoryReplay.Replay; +using HomeAssistant.HistoryReplay.Reporting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using BoilerMonitorManager.Models; + +namespace HomeAssistant.HistoryReplay.Runners; + +public sealed class BoilerReplayRunner : IMonitorReplayRunner +{ + private readonly HistoryTimeline _timeline; + private readonly ReplayTimeProvider _timeProvider; + private readonly ReplayTimeline _replayTimeline; + private readonly IBoilerControlService _boilerControlService; + private readonly IBoilerRunTimeTracker _tracker; + private readonly IWaterReadyService _waterReadyService; + private readonly ILogger _logger; + private readonly ReplayOptions _replayOptions; + private readonly BoilerMonitorOptions _boilerOptions; + + public string MonitorName => "Boiler"; + + public BoilerReplayRunner( + HistoryTimeline timeline, + ReplayTimeProvider timeProvider, + ReplayTimeline replayTimeline, + IBoilerControlService boilerControlService, + IBoilerRunTimeTracker tracker, + IWaterReadyService waterReadyService, + ILogger logger, + IOptions replayOptions, + IOptions boilerOptions) + { + _timeline = timeline; + _timeProvider = timeProvider; + _replayTimeline = replayTimeline; + _boilerControlService = boilerControlService; + _tracker = tracker; + _waterReadyService = waterReadyService; + _logger = logger; + _replayOptions = replayOptions.Value; + _boilerOptions = boilerOptions.Value; + } + + public Task RunAsync(CancellationToken cancellationToken = default) + { + _logger.LogInformation("Starting Boiler replay"); + + var currentTime = _replayOptions.StartTime; + var pollInterval = TimeSpan.FromSeconds(BoilerMonitorConsts.DefaultPollIntervalSeconds); + var heatingThreshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts; + BoilerAction? lastAction = null; + var lastWaterReady = false; + + var boilerPowerEntityId = ReadConfigEntityState( + BoilerMonitorConsts.ConfigPowerEntityId, _replayOptions.StartTime); + var boilerSwitchEntityId = ReadConfigEntityState( + BoilerMonitorConsts.ConfigSwitchEntityId, _replayOptions.StartTime); + + if (string.IsNullOrEmpty(boilerPowerEntityId) || string.IsNullOrEmpty(boilerSwitchEntityId)) + { + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = MonitorName, + EventType = ReplayEventType.Warning, + Message = "Boiler not configured (missing power/switch entity IDs), skipping replay" + }); + return Task.CompletedTask; + } + + var configThresholdState = ReadConfigEntityState( + BoilerMonitorConsts.ConfigHeatingThresholdEntityId, _replayOptions.StartTime); + if (!string.IsNullOrEmpty(configThresholdState) && + double.TryParse(configThresholdState, CultureInfo.InvariantCulture, out var configuredThreshold)) + { + heatingThreshold = configuredThreshold; + } + + while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested) + { + _timeProvider.AdvanceTo(currentTime); + + var powerEntry = _timeline.GetStateAt(boilerPowerEntityId, currentTime); + var switchEntry = _timeline.GetStateAt(boilerSwitchEntityId, currentTime); + var cheapEntry = _timeline.GetStateAt("sensor.nordpool_cheapest_intervals", currentTime); + var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, currentTime); + var budgetOverrideEntry = _timeline.GetStateAt(BoilerMonitorConsts.BudgetOverrideEntityId, currentTime); + var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, currentTime); + + var boilerPowerWatts = ParseDouble(powerEntry?.State); + var boilerSwitchState = switchEntry?.State; + var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= heatingThreshold; + + _tracker.RecordPollResult(isHeating, pollInterval); + + var isNowCheap = ReadAttributeBool(cheapEntry, "is_now_cheap"); + var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase); + var budgetOverride = string.Equals(budgetOverrideEntry?.State, "on", StringComparison.OrdinalIgnoreCase); + var dailyHours = ParseDouble(dailyHoursEntry?.State) ?? 1.0; + + var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, heatingThreshold); + + if (!lastWaterReady && waterReady) + { + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = MonitorName, + EventType = ReplayEventType.StateChange, + Message = $"Water ready detected (power: {boilerPowerWatts:F1}W, threshold: {heatingThreshold}W)" + }); + } + lastWaterReady = waterReady; + + var snapshot = _tracker.GetSnapshot(); + var budgetTimeSpan = TimeSpan.FromHours(dailyHours); + var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan; + var budgetPercentage = budgetTimeSpan.TotalSeconds > 0 + ? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0 + : 0.0; + + var effectiveIsNowCheap = isNowCheap || skipPriceCap; + var action = _boilerControlService.DetermineAction( + effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride); + + if (action != BoilerAction.NoChange && action != lastAction) + { + var actionMessage = action switch + { + BoilerAction.TurnOn => $"TURN ON (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)", + BoilerAction.TurnOff => $"TURN OFF (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)", + _ => action.ToString() + }; + + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = MonitorName, + EventType = ReplayEventType.Decision, + Message = actionMessage, + Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}" + }); + + if (action == BoilerAction.TurnOn) + { + _waterReadyService.NotifyTurnedOn(); + } + } + + lastAction = action; + currentTime = currentTime.Add(pollInterval); + } + + var finalSnapshot = _tracker.GetSnapshot(); + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = _replayOptions.EndTime, + Monitor = MonitorName, + EventType = ReplayEventType.Info, + Message = $"Final: {finalSnapshot.AccumulatedRunTime:hh\\:mm\\:ss} total runtime, {finalSnapshot.SessionCount} session(s)" + }); + + _logger.LogInformation("Boiler replay complete"); + return Task.CompletedTask; + } + + private string? ReadConfigEntityState(string entityId, DateTimeOffset timestamp) + { + var entry = _timeline.GetStateAt(entityId, timestamp); + return entry?.State; + } + + private static bool ReadAttributeBool(HistoryStateEntry? entry, string attributeName) + { + if (entry?.Attributes is null) + { + return false; + } + + if (!entry.Attributes.TryGetValue(attributeName, out var value)) + { + return false; + } + + return value switch + { + bool b => b, + string s => bool.TryParse(s, out var parsed) && parsed, + double d => d != 0, + _ => false + }; + } + + private static double? ParseDouble(string? value) + { + if (value is null or "unavailable" or "unknown") + { + return null; + } + + return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null; + } +} diff --git a/HomeAssistant.HistoryReplay/Runners/IMonitorReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/IMonitorReplayRunner.cs new file mode 100644 index 0000000..c757120 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Runners/IMonitorReplayRunner.cs @@ -0,0 +1,7 @@ +namespace HomeAssistant.HistoryReplay.Runners; + +public interface IMonitorReplayRunner +{ + string MonitorName { get; } + Task RunAsync(CancellationToken cancellationToken = default); +} diff --git a/HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs new file mode 100644 index 0000000..307c3c2 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs @@ -0,0 +1,175 @@ +using HomeAssistant.HistoryReplay.Configuration; +using HomeAssistant.HistoryReplay.HistoryData; +using HomeAssistant.HistoryReplay.Replay; +using HomeAssistant.HistoryReplay.Reporting; +using LightMonitor.Models; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using LightMonitorManager.Models; + +namespace HomeAssistant.HistoryReplay.Runners; + +public sealed class LightReplayRunner : IMonitorReplayRunner +{ + private readonly HistoryTimeline _timeline; + private readonly ReplayTimeProvider _timeProvider; + private readonly ReplayTimeline _replayTimeline; + private readonly ILogger _logger; + private readonly ReplayOptions _replayOptions; + private readonly LightMonitorOptions _lightOptions; + + public string MonitorName => "Light"; + + public LightReplayRunner( + HistoryTimeline timeline, + ReplayTimeProvider timeProvider, + ReplayTimeline replayTimeline, + ILogger logger, + IOptions replayOptions, + IOptions lightOptions) + { + _timeline = timeline; + _timeProvider = timeProvider; + _replayTimeline = replayTimeline; + _logger = logger; + _replayOptions = replayOptions.Value; + _lightOptions = lightOptions.Value; + } + + public Task RunAsync(CancellationToken cancellationToken = default) + { + _logger.LogInformation("Starting Light replay"); + + ReplaySunEvents(cancellationToken); + ReplayPersonArrivals(cancellationToken); + + _logger.LogInformation("Light replay complete"); + return Task.CompletedTask; + } + + private void ReplaySunEvents(CancellationToken cancellationToken) + { + var sunHistory = _timeline.GetEntityHistory(_lightOptions.SunEntityId); + string? previousSunState = null; + + foreach (var entry in sunHistory) + { + if (cancellationToken.IsCancellationRequested) break; + + if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime) + { + continue; + } + + if (string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase) && + !string.Equals(previousSunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) + { + _timeProvider.AdvanceTo(entry.LastChanged); + + var anyoneHome = IsAnyoneHome(entry.LastChanged); + var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State; + var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase); + + if (anyoneHome && !lightAlreadyOn) + { + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = entry.LastChanged, + Monitor = MonitorName, + EventType = ReplayEventType.Decision, + Message = "TURN ON light (sun below horizon + someone home)" + }); + } + else if (!anyoneHome) + { + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = entry.LastChanged, + Monitor = MonitorName, + EventType = ReplayEventType.Info, + Message = "Sun below horizon but nobody home — light stays off" + }); + } + else + { + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = entry.LastChanged, + Monitor = MonitorName, + EventType = ReplayEventType.Info, + Message = "Sun below horizon but light already on" + }); + } + } + + previousSunState = entry.State; + } + } + + private void ReplayPersonArrivals(CancellationToken cancellationToken) + { + foreach (var personEntityId in _lightOptions.PersonEntityIds) + { + var personHistory = _timeline.GetEntityHistory(personEntityId); + string? previousState = null; + + foreach (var entry in personHistory) + { + if (cancellationToken.IsCancellationRequested) break; + + if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime) + { + continue; + } + + if (string.Equals(entry.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase) && + !string.Equals(previousState, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) + { + _timeProvider.AdvanceTo(entry.LastChanged); + + var sunEntry = _timeline.GetStateAt(_lightOptions.SunEntityId, entry.LastChanged); + var isDark = string.Equals(sunEntry?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase); + var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State; + var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase); + + if (isDark && !lightAlreadyOn) + { + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = entry.LastChanged, + Monitor = MonitorName, + EventType = ReplayEventType.Decision, + Message = $"TURN ON light ({personEntityId} arrived home + dark outside)" + }); + } + else if (isDark) + { + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = entry.LastChanged, + Monitor = MonitorName, + EventType = ReplayEventType.Info, + Message = $"{personEntityId} arrived home (dark) but light already on" + }); + } + } + + previousState = entry.State; + } + } + } + + private bool IsAnyoneHome(DateTimeOffset timestamp) + { + foreach (var personEntityId in _lightOptions.PersonEntityIds) + { + var entry = _timeline.GetStateAt(personEntityId, timestamp); + if (string.Equals(entry?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + + return false; + } +} diff --git a/HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs new file mode 100644 index 0000000..52c9bb5 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs @@ -0,0 +1,171 @@ +using System.Globalization; +using BoilerMonitor.Models; +using HomeAssistant.HistoryReplay.Configuration; +using HomeAssistant.HistoryReplay.HistoryData; +using HomeAssistant.HistoryReplay.Replay; +using HomeAssistant.HistoryReplay.Reporting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NordPool.Models; +using NordPoolManager.Interface; + +namespace HomeAssistant.HistoryReplay.Runners; + +public sealed class NordPoolReplayRunner : IMonitorReplayRunner +{ + private readonly HistoryTimeline _timeline; + private readonly ReplayTimeProvider _timeProvider; + private readonly ReplayTimeline _replayTimeline; + private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; + private readonly ILogger _logger; + private readonly ReplayOptions _options; + + public string MonitorName => "NordPool"; + + public NordPoolReplayRunner( + HistoryTimeline timeline, + ReplayTimeProvider timeProvider, + ReplayTimeline replayTimeline, + ICheapestIntervalsFinder cheapestIntervalsFinder, + ILogger logger, + IOptions options) + { + _timeline = timeline; + _timeProvider = timeProvider; + _replayTimeline = replayTimeline; + _cheapestIntervalsFinder = cheapestIntervalsFinder; + _logger = logger; + _options = options.Value; + } + + public Task RunAsync(CancellationToken cancellationToken = default) + { + _logger.LogInformation("Starting NordPool replay"); + + var currentTime = _options.StartTime; + var interval = TimeSpan.FromMinutes(NordPoolConsts.MinutesPerInterval); + double? lastReportedPrice = null; + + while (currentTime <= _options.EndTime && !cancellationToken.IsCancellationRequested) + { + _timeProvider.AdvanceTo(currentTime); + + var priceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime); + if (priceEntry?.State is not null && + double.TryParse(priceEntry.State, CultureInfo.InvariantCulture, out var currentPrice)) + { + if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.001) + { + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = MonitorName, + EventType = ReplayEventType.Info, + Message = $"Price: {currentPrice:F2} ct/kWh" + }); + lastReportedPrice = currentPrice; + } + } + + var boilerConfig = ReadBoilerConfig(currentTime); + if (boilerConfig is not null) + { + var prices = BuildNordPoolPriceFromHistory(currentTime); + if (prices.Prices is { Count: > 0 }) + { + var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap; + var effectiveIntervalCount = boilerConfig.SkipPriceCap + ? NordPoolConsts.MaxDailyIntervals + : boilerConfig.IntervalCount; + + var cheapest = _cheapestIntervalsFinder.FindCheapestIntervals( + prices, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline); + + var isNowCheap = _cheapestIntervalsFinder.IsCurrentIntervalCheap( + cheapest, currentTime.LocalDateTime); + + if (isNowCheap) + { + var currentInterval = cheapest.FirstOrDefault(i => + currentTime.LocalDateTime >= i.Start && currentTime.LocalDateTime < i.End); + + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = MonitorName, + EventType = ReplayEventType.Decision, + Message = $"CHEAP interval active (rank #{currentInterval?.Rank}, price: {currentInterval?.Price:F2} ct/kWh)", + Details = $"Total cheap intervals: {cheapest.Count}" + }); + } + } + } + + currentTime = currentTime.Add(interval); + } + + _logger.LogInformation("NordPool replay complete"); + return Task.CompletedTask; + } + + private BoilerConfig? ReadBoilerConfig(DateTimeOffset timestamp) + { + var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, timestamp); + var priceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerPriceCapEntityId, timestamp); + var readyByEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerReadyByEntityId, timestamp); + var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, timestamp); + + if (dailyHoursEntry?.State is null || priceCapEntry?.State is null || readyByEntry?.State is null) + { + return null; + } + + if (!double.TryParse(dailyHoursEntry.State, CultureInfo.InvariantCulture, out var dailyHours) || + !double.TryParse(priceCapEntry.State, CultureInfo.InvariantCulture, out var priceCap)) + { + return null; + } + + var intervalCount = (int)(dailyHours * NordPoolConsts.IntervalsPerHour); + + if (!TimeSpan.TryParse(readyByEntry.State, CultureInfo.InvariantCulture, out var readyByTime)) + { + return null; + } + + var deadline = timestamp.LocalDateTime.Date.Add(readyByTime); + if (deadline < timestamp.LocalDateTime) + { + deadline = deadline.AddDays(1); + } + + var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase); + + return new BoilerConfig + { + IntervalCount = intervalCount, + PriceCap = priceCap, + Deadline = deadline, + SkipPriceCap = skipPriceCap + }; + } + + private NordPoolPrice BuildNordPoolPriceFromHistory(DateTimeOffset timestamp) + { + var nordPoolSensorEntries = _timeline.GetEntityHistory("sensor.nordpool_kwh_lt_eur_3_10_0"); + var todayDate = timestamp.LocalDateTime.Date; + + var todayPrices = nordPoolSensorEntries + .Where(e => e.LastChanged.LocalDateTime.Date == todayDate) + .Where(e => e.State is not null && double.TryParse(e.State, CultureInfo.InvariantCulture, out _)) + .Select(e => new NordPoolDayPrice + { + Start = e.LastChanged.LocalDateTime, + End = e.LastChanged.LocalDateTime.AddMinutes(NordPoolConsts.MinutesPerInterval), + Price = double.Parse(e.State!, CultureInfo.InvariantCulture) + }) + .ToList(); + + return new NordPoolPrice { Prices = todayPrices }; + } +} diff --git a/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs new file mode 100644 index 0000000..f871b38 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs @@ -0,0 +1,158 @@ +using System.Globalization; +using HomeAssistant.HistoryReplay.Configuration; +using HomeAssistant.HistoryReplay.HistoryData; +using HomeAssistant.HistoryReplay.Replay; +using HomeAssistant.HistoryReplay.Reporting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NordPool.Models; +using PowerMonitorManager.Interface; +using PowerMonitorManager.Models; +using PowerMonitorManager.Models.Consts; + +namespace HomeAssistant.HistoryReplay.Runners; + +public sealed class PowerReplayRunner : IMonitorReplayRunner +{ + private readonly HistoryTimeline _timeline; + private readonly ReplayTimeProvider _timeProvider; + private readonly ReplayTimeline _replayTimeline; + private readonly IOtherPowerCalculationService _calculationService; + private readonly IPowerCostCalculationService _costService; + private readonly ILogger _logger; + private readonly ReplayOptions _replayOptions; + private readonly PowerMonitorOptions _powerOptions; + + public string MonitorName => "Power"; + + public PowerReplayRunner( + HistoryTimeline timeline, + ReplayTimeProvider timeProvider, + ReplayTimeline replayTimeline, + IOtherPowerCalculationService calculationService, + IPowerCostCalculationService costService, + ILogger logger, + IOptions replayOptions, + IOptions powerOptions) + { + _timeline = timeline; + _timeProvider = timeProvider; + _replayTimeline = replayTimeline; + _calculationService = calculationService; + _costService = costService; + _logger = logger; + _replayOptions = replayOptions.Value; + _powerOptions = powerOptions.Value; + } + + public Task RunAsync(CancellationToken cancellationToken = default) + { + _logger.LogInformation("Starting Power replay"); + + var currentTime = _replayOptions.StartTime; + var pollInterval = TimeSpan.FromSeconds(_powerOptions.PollIntervalSeconds); + DateTime? anomalyStartTime = null; + + while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested) + { + _timeProvider.AdvanceTo(currentTime); + + var mainMeterEntry = _timeline.GetStateAt(_powerOptions.MainMeterEntityId, currentTime); + var totalPower = ParseDouble(mainMeterEntry?.State); + + if (!totalPower.HasValue) + { + currentTime = currentTime.Add(pollInterval); + continue; + } + + var deviceReadings = DiscoverAndReadDevicePower(currentTime); + var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings); + + var nordPoolPriceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime); + var nordPoolPrice = ParseDouble(nordPoolPriceEntry?.State) ?? 0; + + _costService.RecordCosts(calculation, nordPoolPrice, _powerOptions.PollIntervalSeconds, currentTime.LocalDateTime); + + var isAnomaly = calculation.SmoothedOtherPowerWatts > _powerOptions.AnomalyThresholdWatts; + if (isAnomaly && anomalyStartTime is null) + { + anomalyStartTime = currentTime.LocalDateTime; + + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = MonitorName, + EventType = ReplayEventType.Anomaly, + Message = $"Other power {calculation.SmoothedOtherPowerWatts:F0}W exceeds threshold {_powerOptions.AnomalyThresholdWatts}W", + Details = $"Total: {calculation.TotalPowerWatts:F0}W, Known: {calculation.KnownDevicesSumWatts:F0}W" + }); + } + else if (!isAnomaly && anomalyStartTime is not null) + { + var duration = currentTime.LocalDateTime - anomalyStartTime.Value; + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = MonitorName, + EventType = ReplayEventType.Info, + Message = $"Anomaly resolved after {duration:mm\\:ss}" + }); + anomalyStartTime = null; + } + + currentTime = currentTime.Add(pollInterval); + } + + var totalCost = _costService.GetTotalCostSnapshot(); + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = _replayOptions.EndTime, + Monitor = MonitorName, + EventType = ReplayEventType.Info, + Message = $"Final: Total daily cost {totalCost.CostDaily:F4} EUR" + }); + + _logger.LogInformation("Power replay complete"); + return Task.CompletedTask; + } + + private IReadOnlyDictionary DiscoverAndReadDevicePower(DateTimeOffset timestamp) + { + var readings = new Dictionary(); + + var allEntities = _timeline.GetEntityIds(); + foreach (var entityId in allEntities) + { + if (!entityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase) || + !entityId.EndsWith("_power", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + if (string.Equals(entityId, _powerOptions.MainMeterEntityId, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + var entry = _timeline.GetStateAt(entityId, timestamp); + var value = ParseDouble(entry?.State); + if (value.HasValue) + { + readings[entityId] = value.Value; + } + } + + return readings; + } + + private static double? ParseDouble(string? value) + { + if (value is null or "unavailable" or "unknown") + { + return null; + } + + return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null; + } +} diff --git a/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs new file mode 100644 index 0000000..b489bba --- /dev/null +++ b/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs @@ -0,0 +1,126 @@ +using System.Globalization; +using HomeAssistant.HistoryReplay.Configuration; +using HomeAssistant.HistoryReplay.HistoryData; +using HomeAssistant.HistoryReplay.Replay; +using HomeAssistant.HistoryReplay.Reporting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using ShowerMonitor.Models.Enums; +using ShowerMonitorManager.Interface; +using ShowerMonitorManager.Models; + +namespace HomeAssistant.HistoryReplay.Runners; + +public sealed class ShowerReplayRunner : IMonitorReplayRunner +{ + private readonly HistoryTimeline _timeline; + private readonly ReplayTimeProvider _timeProvider; + private readonly ReplayTimeline _replayTimeline; + private readonly IShowerDetectionService _detectionService; + private readonly IExhaustFanControlService _fanControlService; + private readonly ILogger _logger; + private readonly ReplayOptions _replayOptions; + private readonly ShowerMonitorOptions _showerOptions; + + public string MonitorName => "Shower"; + + public ShowerReplayRunner( + HistoryTimeline timeline, + ReplayTimeProvider timeProvider, + ReplayTimeline replayTimeline, + IShowerDetectionService detectionService, + IExhaustFanControlService fanControlService, + ILogger logger, + IOptions replayOptions, + IOptions showerOptions) + { + _timeline = timeline; + _timeProvider = timeProvider; + _replayTimeline = replayTimeline; + _detectionService = detectionService; + _fanControlService = fanControlService; + _logger = logger; + _replayOptions = replayOptions.Value; + _showerOptions = showerOptions.Value; + } + + public Task RunAsync(CancellationToken cancellationToken = default) + { + _logger.LogInformation("Starting Shower replay"); + + var currentTime = _replayOptions.StartTime; + var pollInterval = TimeSpan.FromSeconds(_showerOptions.PollIntervalSeconds); + var previousState = ShowerState.Idle; + + while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested) + { + _timeProvider.AdvanceTo(currentTime); + + var bathroomEntry = _timeline.GetStateAt(_showerOptions.BathroomHumidityEntityId, currentTime); + var homeEntry = _timeline.GetStateAt(_showerOptions.MainHomeHumidityEntityId, currentTime); + + var bathroomHumidity = ParseDouble(bathroomEntry?.State); + var homeHumidity = ParseDouble(homeEntry?.State); + + if (bathroomHumidity.HasValue && homeHumidity.HasValue) + { + var state = _detectionService.Evaluate(bathroomHumidity.Value, homeHumidity.Value, currentTime); + var differential = bathroomHumidity.Value - homeHumidity.Value; + + _fanControlService.Evaluate(state, currentTime); + + if (state != previousState) + { + var eventType = state switch + { + ShowerState.Active => ReplayEventType.Decision, + ShowerState.Completed => ReplayEventType.StateChange, + _ => ReplayEventType.Info + }; + + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = MonitorName, + EventType = eventType, + Message = $"State: {previousState} → {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)", + Details = GetStateChangeDetails(state) + }); + + previousState = state; + } + } + + currentTime = currentTime.Add(pollInterval); + } + + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = _replayOptions.EndTime, + Monitor = MonitorName, + EventType = ReplayEventType.Info, + Message = $"Final: {_detectionService.TodaySessionCount} session(s) detected" + }); + + _logger.LogInformation("Shower replay complete"); + return Task.CompletedTask; + } + + private string? GetStateChangeDetails(ShowerState state) => + state switch + { + ShowerState.Completed when _detectionService.LastCompletedSession is not null => + $"Duration: {_detectionService.LastCompletedSession.Duration:mm\\:ss}, Peak humidity: {_detectionService.LastCompletedSession.PeakHumidity:F1}%", + _ => null + }; + + private static double? ParseDouble(string? value) + { + if (value is null or "unavailable" or "unknown") + { + return null; + } + + return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null; + } +} diff --git a/HomeAssistant.HistoryReplay/appsettings.json b/HomeAssistant.HistoryReplay/appsettings.json new file mode 100644 index 0000000..4ec67a5 --- /dev/null +++ b/HomeAssistant.HistoryReplay/appsettings.json @@ -0,0 +1,57 @@ +{ + "HomeAssistant": { + "Host": "homeassistant.local", + "Port": 8123, + "Token": "", + "Ssl": false + }, + "Replay": { + "StartTime": "2026-03-30T00:00:00+02:00", + "EndTime": "2026-03-31T00:00:00+02:00", + "Monitors": { + "NordPool": true, + "Boiler": true, + "Shower": true, + "Power": false, + "Light": true + } + }, + "BoilerMonitor": { + "Enabled": true, + "CleanupEntitiesOnStartup": false + }, + "ShowerMonitor": { + "Enabled": true, + "CleanupEntitiesOnStartup": false, + "BathroomHumidityEntityId": "sensor.bathroom_humidity", + "MainHomeHumidityEntityId": "sensor.main_home_humidity", + "BathroomTemperatureEntityId": "sensor.bathroom_temperature", + "ExhaustFanEntityId": "switch.exhaust_fan", + "PollIntervalSeconds": 30, + "SpikeRateThreshold": 4.0, + "MinDifferentialHumidity": 8.0, + "PeakHumidityThreshold": 58.0, + "ConfirmationWindowMinutes": 2, + "RecoveryDifferentialThreshold": 5.0, + "MaxShowerDurationMinutes": 60, + "FanRunAfterShowerMinutes": 10, + "RateWindowSize": 5 + }, + "LightMonitor": { + "Enabled": true, + "LightEntityId": "light.sonoff_1002214d40", + "SunEntityId": "sun.sun", + "PersonEntityIds": ["person.marius", "person.erika", "person.home_phone"] + }, + "PowerMonitor": { + "Enabled": false, + "MainMeterEntityId": "sensor.sonoff_100267d63f_power", + "PollIntervalSeconds": 1, + "SmoothingWindowSize": 10, + "AnomalyThresholdWatts": 500, + "ExcludedSensorPatterns": [ + "sensor.nordpool_*", + "sensor.powermonitor_*" + ] + } +} diff --git a/HomeAssistant.McpServer/HomeAssistant.McpServer.csproj b/HomeAssistant.McpServer/HomeAssistant.McpServer.csproj new file mode 100644 index 0000000..8e302aa --- /dev/null +++ b/HomeAssistant.McpServer/HomeAssistant.McpServer.csproj @@ -0,0 +1,18 @@ + + + + Exe + net10.0 + 14.0 + enable + enable + HomeAssistant.McpServer + + + + + + + + + diff --git a/HomeAssistant.McpServer/Program.cs b/HomeAssistant.McpServer/Program.cs new file mode 100644 index 0000000..cddc8f5 --- /dev/null +++ b/HomeAssistant.McpServer/Program.cs @@ -0,0 +1,25 @@ +using HomeAssistant.McpServer.Services; +using HomeAssistant.McpServer.Settings; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using ModelContextProtocol.Server; + +var builder = Host.CreateApplicationBuilder(args); + +builder.Logging.AddConsole(options => +{ + options.LogToStandardErrorThreshold = LogLevel.Trace; +}); + +builder.Services + .Configure( + builder.Configuration.GetSection(HomeAssistantSettings.SectionName)) + .AddHttpClient(); + +builder.Services + .AddMcpServer() + .WithStdioServerTransport() + .WithToolsFromAssembly(); + +await builder.Build().RunAsync(); diff --git a/HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs b/HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs new file mode 100644 index 0000000..c574ecc --- /dev/null +++ b/HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs @@ -0,0 +1,107 @@ +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using HomeAssistant.McpServer.Settings; +using Microsoft.Extensions.Options; + +namespace HomeAssistant.McpServer.Services; + +public sealed class HomeAssistantApiClient : IHomeAssistantApiClient +{ + private readonly HttpClient _httpClient; + + public HomeAssistantApiClient(HttpClient httpClient, IOptions settings) + { + _httpClient = httpClient; + _httpClient.BaseAddress = settings.Value.BaseUrl; + _httpClient.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", settings.Value.Token); + _httpClient.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue("application/json")); + _httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds); + } + + public Task GetApiStatusAsync(CancellationToken cancellationToken = default) => + GetJsonAsync("/api/", cancellationToken); + + public Task GetConfigAsync(CancellationToken cancellationToken = default) => + GetJsonAsync("/api/config", cancellationToken); + + public Task GetAllStatesAsync(CancellationToken cancellationToken = default) => + GetJsonAsync("/api/states", cancellationToken); + + public Task GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default) => + GetJsonAsync($"/api/states/{Uri.EscapeDataString(entityId)}", cancellationToken); + + public Task GetServicesAsync(CancellationToken cancellationToken = default) => + GetJsonAsync("/api/services", cancellationToken); + + public Task GetHistoryAsync( + string entityIds, + DateTimeOffset? startTime = null, + DateTimeOffset? endTime = null, + bool minimalResponse = true, + CancellationToken cancellationToken = default) + { + var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1); + var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}"; + + if (endTime.HasValue) + path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}"; + + if (minimalResponse) + path += "&minimal_response"; + + return GetJsonAsync(path, cancellationToken); + } + + public Task GetLogbookAsync( + string? entityId = null, + DateTimeOffset? startTime = null, + DateTimeOffset? endTime = null, + CancellationToken cancellationToken = default) + { + var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1); + var path = $"/api/logbook/{start:O}"; + + var queryParts = new List(); + if (!string.IsNullOrWhiteSpace(entityId)) + queryParts.Add($"entity={Uri.EscapeDataString(entityId)}"); + if (endTime.HasValue) + queryParts.Add($"end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}"); + + if (queryParts.Count > 0) + path += "?" + string.Join("&", queryParts); + + return GetJsonAsync(path, cancellationToken); + } + + public async Task CallServiceAsync( + string domain, + string service, + JsonElement? serviceData = null, + CancellationToken cancellationToken = default) + { + var url = $"/api/services/{Uri.EscapeDataString(domain)}/{Uri.EscapeDataString(service)}"; + var content = serviceData.HasValue + ? JsonContent.Create(serviceData.Value) + : JsonContent.Create(new { }); + + var response = await _httpClient.PostAsync(url, content, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); + return doc.RootElement.Clone(); + } + + private async Task GetJsonAsync(string path, CancellationToken cancellationToken) + { + var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); + return doc.RootElement.Clone(); + } +} diff --git a/HomeAssistant.McpServer/Services/IHomeAssistantApiClient.cs b/HomeAssistant.McpServer/Services/IHomeAssistantApiClient.cs new file mode 100644 index 0000000..e8abb1f --- /dev/null +++ b/HomeAssistant.McpServer/Services/IHomeAssistantApiClient.cs @@ -0,0 +1,31 @@ +using System.Text.Json; + +namespace HomeAssistant.McpServer.Services; + +public interface IHomeAssistantApiClient +{ + Task GetApiStatusAsync(CancellationToken cancellationToken = default); + Task GetConfigAsync(CancellationToken cancellationToken = default); + Task GetAllStatesAsync(CancellationToken cancellationToken = default); + Task GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default); + Task GetServicesAsync(CancellationToken cancellationToken = default); + + Task GetHistoryAsync( + string entityIds, + DateTimeOffset? startTime = null, + DateTimeOffset? endTime = null, + bool minimalResponse = true, + CancellationToken cancellationToken = default); + + Task GetLogbookAsync( + string? entityId = null, + DateTimeOffset? startTime = null, + DateTimeOffset? endTime = null, + CancellationToken cancellationToken = default); + + Task CallServiceAsync( + string domain, + string service, + JsonElement? serviceData = null, + CancellationToken cancellationToken = default); +} diff --git a/HomeAssistant.McpServer/Settings/HomeAssistantSettings.cs b/HomeAssistant.McpServer/Settings/HomeAssistantSettings.cs new file mode 100644 index 0000000..b41ca09 --- /dev/null +++ b/HomeAssistant.McpServer/Settings/HomeAssistantSettings.cs @@ -0,0 +1,15 @@ +namespace HomeAssistant.McpServer.Settings; + +public sealed class HomeAssistantSettings +{ + public const string SectionName = "HomeAssistant"; + public const int DefaultPort = 8123; + public const int DefaultTimeoutSeconds = 30; + + public string Host { get; set; } = string.Empty; + public int Port { get; set; } = DefaultPort; + public string Token { get; set; } = string.Empty; + public bool Ssl { get; set; } + + public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri; +} diff --git a/HomeAssistant.McpServer/Tools/EntityStateTools.cs b/HomeAssistant.McpServer/Tools/EntityStateTools.cs new file mode 100644 index 0000000..9cac3e7 --- /dev/null +++ b/HomeAssistant.McpServer/Tools/EntityStateTools.cs @@ -0,0 +1,98 @@ +using System.ComponentModel; +using System.Text.Json; +using HomeAssistant.McpServer.Services; +using ModelContextProtocol.Server; + +namespace HomeAssistant.McpServer.Tools; + +[McpServerToolType] +public sealed class EntityStateTools +{ + private readonly IHomeAssistantApiClient _client; + + public EntityStateTools(IHomeAssistantApiClient client) + { + _client = client; + } + + [McpServerTool, Description( + "Get the current state and attributes of a single Home Assistant entity. " + + "Provide the full entity_id, e.g. 'sensor.nordpool_kwh_lt_eur_3_10_0' or 'switch.boiler'.")] + public async Task GetEntityState( + [Description("Full entity ID, e.g. 'sensor.temperature' or 'light.living_room'")] string entityId, + CancellationToken cancellationToken = default) + { + var result = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false); + return FormatJson(result); + } + + [McpServerTool, Description( + "Get the current states of all Home Assistant entities. " + + "Optionally filter by domain (e.g. 'sensor', 'switch', 'climate', 'light'). " + + "Returns entity_id, state, and key attributes for each entity.")] + public async Task GetAllStates( + [Description("Optional domain filter, e.g. 'sensor', 'switch', 'climate'. Leave empty for all.")] string? domain = null, + CancellationToken cancellationToken = default) + { + var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false); + + if (string.IsNullOrWhiteSpace(domain)) + return FormatJson(allStates); + + var filtered = allStates.EnumerateArray() + .Where(e => e.TryGetProperty("entity_id", out var eid) && + eid.GetString()?.StartsWith(domain + ".", StringComparison.OrdinalIgnoreCase) == true) + .ToList(); + + return JsonSerializer.Serialize(filtered, SerializerOptions); + } + + [McpServerTool, Description( + "Search Home Assistant entities by partial match on entity_id or friendly_name. " + + "Useful for discovering entities related to a topic (e.g. 'nordpool', 'boiler', 'temperature').")] + public async Task SearchEntities( + [Description("Search term to match against entity_id or friendly_name")] string query, + CancellationToken cancellationToken = default) + { + var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false); + + var matches = allStates.EnumerateArray() + .Where(e => MatchesQuery(e, query)) + .Select(e => new + { + entity_id = e.GetProperty("entity_id").GetString(), + state = e.GetProperty("state").GetString(), + friendly_name = e.TryGetProperty("attributes", out var attrs) && + attrs.TryGetProperty("friendly_name", out var fn) + ? fn.GetString() + : null + }) + .ToList(); + + return JsonSerializer.Serialize(matches, SerializerOptions); + } + + private static bool MatchesQuery(JsonElement entity, string query) + { + var q = query.ToUpperInvariant(); + + if (entity.TryGetProperty("entity_id", out var eid) && + (eid.GetString()?.ToUpperInvariant().Contains(q) ?? false)) + return true; + + if (entity.TryGetProperty("attributes", out var attrs) && + attrs.TryGetProperty("friendly_name", out var fn) && + (fn.GetString()?.ToUpperInvariant().Contains(q) ?? false)) + return true; + + return false; + } + + private static string FormatJson(JsonElement element) => + JsonSerializer.Serialize(element, SerializerOptions); + + private static readonly JsonSerializerOptions SerializerOptions = new() + { + WriteIndented = true + }; +} diff --git a/HomeAssistant.McpServer/Tools/HistoryTools.cs b/HomeAssistant.McpServer/Tools/HistoryTools.cs new file mode 100644 index 0000000..e934a94 --- /dev/null +++ b/HomeAssistant.McpServer/Tools/HistoryTools.cs @@ -0,0 +1,46 @@ +using System.ComponentModel; +using System.Text.Json; +using HomeAssistant.McpServer.Services; +using ModelContextProtocol.Server; + +namespace HomeAssistant.McpServer.Tools; + +[McpServerToolType] +public sealed class HistoryTools +{ + private readonly IHomeAssistantApiClient _client; + + public HistoryTools(IHomeAssistantApiClient client) + { + _client = client; + } + + [McpServerTool, Description( + "Get state history for one or more Home Assistant entities over a time period. " + + "Returns timestamped state changes. Useful for debugging sensor readings, switch toggling, price changes, etc.")] + public async Task GetEntityHistory( + [Description("Comma-separated entity IDs, e.g. 'sensor.temperature,sensor.humidity'")] string entityIds, + [Description("Start time in ISO 8601 format. Defaults to 24 hours ago. Example: '2026-03-30T00:00:00'")] string? startTime = null, + [Description("End time in ISO 8601 format. Defaults to now. Example: '2026-03-31T00:00:00'")] string? endTime = null, + [Description("If true, returns minimal data (state + last_changed only). Defaults to true.")] bool minimalResponse = true, + CancellationToken cancellationToken = default) + { + DateTimeOffset? start = string.IsNullOrWhiteSpace(startTime) + ? null + : DateTimeOffset.Parse(startTime); + + DateTimeOffset? end = string.IsNullOrWhiteSpace(endTime) + ? null + : DateTimeOffset.Parse(endTime); + + var result = await _client.GetHistoryAsync(entityIds, start, end, minimalResponse, cancellationToken) + .ConfigureAwait(false); + + return JsonSerializer.Serialize(result, SerializerOptions); + } + + private static readonly JsonSerializerOptions SerializerOptions = new() + { + WriteIndented = true + }; +} diff --git a/HomeAssistant.McpServer/Tools/LogbookTools.cs b/HomeAssistant.McpServer/Tools/LogbookTools.cs new file mode 100644 index 0000000..fb2b0c3 --- /dev/null +++ b/HomeAssistant.McpServer/Tools/LogbookTools.cs @@ -0,0 +1,45 @@ +using System.ComponentModel; +using System.Text.Json; +using HomeAssistant.McpServer.Services; +using ModelContextProtocol.Server; + +namespace HomeAssistant.McpServer.Tools; + +[McpServerToolType] +public sealed class LogbookTools +{ + private readonly IHomeAssistantApiClient _client; + + public LogbookTools(IHomeAssistantApiClient client) + { + _client = client; + } + + [McpServerTool, Description( + "Get Home Assistant logbook entries. Shows state changes and events for entities. " + + "Useful for understanding what happened and when. Filter by entity and/or time range.")] + public async Task GetLogbook( + [Description("Optional entity ID to filter, e.g. 'switch.boiler'. Leave empty for all.")] string? entityId = null, + [Description("Start time in ISO 8601 format. Defaults to 24 hours ago.")] string? startTime = null, + [Description("End time in ISO 8601 format. Defaults to now.")] string? endTime = null, + CancellationToken cancellationToken = default) + { + DateTimeOffset? start = string.IsNullOrWhiteSpace(startTime) + ? null + : DateTimeOffset.Parse(startTime); + + DateTimeOffset? end = string.IsNullOrWhiteSpace(endTime) + ? null + : DateTimeOffset.Parse(endTime); + + var result = await _client.GetLogbookAsync(entityId, start, end, cancellationToken) + .ConfigureAwait(false); + + return JsonSerializer.Serialize(result, SerializerOptions); + } + + private static readonly JsonSerializerOptions SerializerOptions = new() + { + WriteIndented = true + }; +} diff --git a/HomeAssistant.McpServer/Tools/ServiceTools.cs b/HomeAssistant.McpServer/Tools/ServiceTools.cs new file mode 100644 index 0000000..4b47642 --- /dev/null +++ b/HomeAssistant.McpServer/Tools/ServiceTools.cs @@ -0,0 +1,75 @@ +using System.ComponentModel; +using System.Text.Json; +using HomeAssistant.McpServer.Services; +using ModelContextProtocol.Server; + +namespace HomeAssistant.McpServer.Tools; + +[McpServerToolType] +public sealed class ServiceTools +{ + private readonly IHomeAssistantApiClient _client; + + public ServiceTools(IHomeAssistantApiClient client) + { + _client = client; + } + + [McpServerTool, Description( + "List available Home Assistant services. Optionally filter by domain (e.g. 'light', 'climate', 'switch'). " + + "Each service shows its domain and available service names.")] + public async Task ListServices( + [Description("Optional domain filter, e.g. 'light', 'climate'. Leave empty for all.")] string? domain = null, + CancellationToken cancellationToken = default) + { + var allServices = await _client.GetServicesAsync(cancellationToken).ConfigureAwait(false); + + if (string.IsNullOrWhiteSpace(domain)) + return FormatJson(allServices); + + var filtered = allServices.EnumerateArray() + .Where(s => s.TryGetProperty("domain", out var d) && + string.Equals(d.GetString(), domain, StringComparison.OrdinalIgnoreCase)) + .ToList(); + + return JsonSerializer.Serialize(filtered, SerializerOptions); + } + + [McpServerTool, Description( + "Call a Home Assistant service. Examples: domain='light', service='turn_on', entityId='light.living_room'. " + + "For services requiring extra data, pass it as a JSON string in serviceData.")] + public async Task CallService( + [Description("Service domain, e.g. 'light', 'climate', 'switch', 'input_boolean'")] string domain, + [Description("Service name, e.g. 'turn_on', 'turn_off', 'set_temperature'")] string service, + [Description("Optional target entity ID, e.g. 'light.living_room'")] string? entityId = null, + [Description("Optional JSON service data, e.g. '{\"brightness\": 255}' or '{\"temperature\": 22}'")] string? serviceData = null, + CancellationToken cancellationToken = default) + { + JsonElement? data = null; + + if (!string.IsNullOrWhiteSpace(serviceData) || !string.IsNullOrWhiteSpace(entityId)) + { + var dataDict = string.IsNullOrWhiteSpace(serviceData) + ? new Dictionary() + : JsonSerializer.Deserialize>(serviceData) ?? []; + + if (!string.IsNullOrWhiteSpace(entityId)) + dataDict["entity_id"] = entityId; + + data = JsonSerializer.SerializeToElement(dataDict); + } + + var result = await _client.CallServiceAsync(domain, service, data, cancellationToken) + .ConfigureAwait(false); + + return FormatJson(result); + } + + private static string FormatJson(JsonElement element) => + JsonSerializer.Serialize(element, SerializerOptions); + + private static readonly JsonSerializerOptions SerializerOptions = new() + { + WriteIndented = true + }; +} diff --git a/HomeAssistant.McpServer/Tools/SystemTools.cs b/HomeAssistant.McpServer/Tools/SystemTools.cs new file mode 100644 index 0000000..4acd222 --- /dev/null +++ b/HomeAssistant.McpServer/Tools/SystemTools.cs @@ -0,0 +1,52 @@ +using System.ComponentModel; +using System.Text.Json; +using HomeAssistant.McpServer.Services; +using ModelContextProtocol.Server; + +namespace HomeAssistant.McpServer.Tools; + +[McpServerToolType] +public sealed class SystemTools +{ + private readonly IHomeAssistantApiClient _client; + + public SystemTools(IHomeAssistantApiClient client) + { + _client = client; + } + + [McpServerTool, Description( + "Get Home Assistant configuration including version, location, components, and unit system. " + + "Useful for understanding the HA environment.")] + public async Task GetHaConfig(CancellationToken cancellationToken = default) + { + var result = await _client.GetConfigAsync(cancellationToken).ConfigureAwait(false); + return JsonSerializer.Serialize(result, SerializerOptions); + } + + [McpServerTool, Description( + "Check if the Home Assistant API is reachable and responding. " + + "Returns the API status message or an error description.")] + public async Task CheckApi(CancellationToken cancellationToken = default) + { + try + { + var result = await _client.GetApiStatusAsync(cancellationToken).ConfigureAwait(false); + return JsonSerializer.Serialize(result, SerializerOptions); + } + catch (HttpRequestException ex) + { + return JsonSerializer.Serialize(new { status = "error", message = ex.Message }, SerializerOptions); + } + catch (TaskCanceledException) + { + return JsonSerializer.Serialize( + new { status = "error", message = "Request timed out - HA may be unreachable" }, SerializerOptions); + } + } + + private static readonly JsonSerializerOptions SerializerOptions = new() + { + WriteIndented = true + }; +} diff --git a/HomeAssistant.Models/HomeAssistant.Models.csproj b/HomeAssistant.Models/HomeAssistant.Models.csproj index a2611d5..797aa7e 100644 --- a/HomeAssistant.Models/HomeAssistant.Models.csproj +++ b/HomeAssistant.Models/HomeAssistant.Models.csproj @@ -1,4 +1,4 @@ - + net10.0 @@ -7,7 +7,7 @@ - + diff --git a/HomeAssistant.Server/.config/dotnet-tools.json b/HomeAssistant.Server/.config/dotnet-tools.json index be3eb89..56cd7da 100644 --- a/HomeAssistant.Server/.config/dotnet-tools.json +++ b/HomeAssistant.Server/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "netdaemon.hassmodel.codegen": { - "version": "26.3.0", + "version": "26.11.0", "commands": [ "nd-codegen" ], diff --git a/HomeAssistant.Server/HomeAssistant.Server.csproj b/HomeAssistant.Server/HomeAssistant.Server.csproj index 5f24375..6eeb889 100644 --- a/HomeAssistant.Server/HomeAssistant.Server.csproj +++ b/HomeAssistant.Server/HomeAssistant.Server.csproj @@ -34,13 +34,13 @@ - - - - - - - + + + + + + + @@ -52,5 +52,11 @@ + + + + + + diff --git a/HomeAssistant.Server/NetDaemonCodegen/EntityMetaData.json b/HomeAssistant.Server/NetDaemonCodegen/EntityMetaData.json new file mode 100644 index 0000000..5e517d7 --- /dev/null +++ b/HomeAssistant.Server/NetDaemonCodegen/EntityMetaData.json @@ -0,0 +1,4130 @@ +{ + "domains": [ + { + "domain": "light", + "entities": [ + { + "id": "light.sonoff_1002214d40", + "friendlyName": "Edge LED", + "cSharpName": "Sonoff1002214d40" + } + ], + "attributes": [ + { + "jsonName": "supported_color_modes", + "cSharpName": "SupportedColorModes", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "supported_features", + "cSharpName": "SupportedFeatures", + "clrType": "System.Double" + }, + { + "jsonName": "color_mode", + "cSharpName": "ColorMode", + "clrType": "System.String" + }, + { + "jsonName": "min_color_temp_kelvin", + "cSharpName": "MinColorTempKelvin", + "clrType": "System.Double" + }, + { + "jsonName": "max_color_temp_kelvin", + "cSharpName": "MaxColorTempKelvin", + "clrType": "System.Double" + }, + { + "jsonName": "min_mireds", + "cSharpName": "MinMireds", + "clrType": "System.Double" + }, + { + "jsonName": "max_mireds", + "cSharpName": "MaxMireds", + "clrType": "System.Double" + }, + { + "jsonName": "brightness", + "cSharpName": "Brightness", + "clrType": "System.Double" + }, + { + "jsonName": "color_temp_kelvin", + "cSharpName": "ColorTempKelvin", + "clrType": "System.Double" + }, + { + "jsonName": "color_temp", + "cSharpName": "ColorTemp", + "clrType": "System.Double" + }, + { + "jsonName": "hs_color", + "cSharpName": "HsColor", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.Double]" + }, + { + "jsonName": "rgb_color", + "cSharpName": "RgbColor", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.Double]" + }, + { + "jsonName": "xy_color", + "cSharpName": "XyColor", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.Double]" + }, + { + "jsonName": "entity_id", + "cSharpName": "EntityId", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "effect_list", + "cSharpName": "EffectList", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "color", + "cSharpName": "Color", + "clrType": "System.Object" + }, + { + "jsonName": "effect", + "cSharpName": "Effect", + "clrType": null + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "media_player", + "entities": [ + { + "id": "media_player.123prasaunenuplysk_qe75q77datxxh", + "friendlyName": null, + "cSharpName": "_123prasaunenuplyskQe75q77datxxh" + }, + { + "id": "media_player.123prasaunenuplysk_qe75q77datxxh_2", + "friendlyName": "123PrasauNenuplysk (QE75Q77DATXXH)", + "cSharpName": "_123prasaunenuplyskQe75q77datxxh2" + } + ], + "attributes": [ + { + "jsonName": "app_id", + "cSharpName": "AppId", + "clrType": "System.String" + }, + { + "jsonName": "app_name", + "cSharpName": "AppName", + "clrType": "System.String" + }, + { + "jsonName": "device_class", + "cSharpName": "DeviceClass", + "clrType": "System.String" + }, + { + "jsonName": "entity_picture_local", + "cSharpName": "EntityPictureLocal", + "clrType": "System.String" + }, + { + "jsonName": "entity_picture", + "cSharpName": "EntityPicture", + "clrType": "System.String" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "supported_features", + "cSharpName": "SupportedFeatures", + "clrType": "System.Double" + }, + { + "jsonName": "volume_level", + "cSharpName": "VolumeLevel", + "clrType": "System.Double" + }, + { + "jsonName": "is_volume_muted", + "cSharpName": "IsVolumeMuted", + "clrType": "System.Boolean" + }, + { + "jsonName": "media_content_id", + "cSharpName": "MediaContentId", + "clrType": "System.String" + }, + { + "jsonName": "media_content_type", + "cSharpName": "MediaContentType", + "clrType": "System.String" + }, + { + "jsonName": "media_duration", + "cSharpName": "MediaDuration", + "clrType": "System.Double" + }, + { + "jsonName": "media_position", + "cSharpName": "MediaPosition", + "clrType": "System.Double" + }, + { + "jsonName": "media_position_updated_at", + "cSharpName": "MediaPositionUpdatedAt", + "clrType": "System.String" + }, + { + "jsonName": "media_title", + "cSharpName": "MediaTitle", + "clrType": "System.String" + }, + { + "jsonName": "media_album_name", + "cSharpName": "MediaAlbumName", + "clrType": "System.String" + }, + { + "jsonName": "media_image_url", + "cSharpName": "MediaImageUrl", + "clrType": "System.String" + }, + { + "jsonName": "media_artist", + "cSharpName": "MediaArtist", + "clrType": "System.String" + }, + { + "jsonName": "sound_mode_list", + "cSharpName": "SoundModeList", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "media_track", + "cSharpName": "MediaTrack", + "clrType": "System.Object" + }, + { + "jsonName": "shuffle", + "cSharpName": "Shuffle", + "clrType": "System.Boolean" + }, + { + "jsonName": "repeat", + "cSharpName": "Repeat", + "clrType": "System.String" + }, + { + "jsonName": "source_list", + "cSharpName": "SourceList", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "source", + "cSharpName": "Source", + "clrType": "System.String" + }, + { + "jsonName": "adb_response", + "cSharpName": "AdbResponse", + "clrType": "System.Object" + }, + { + "jsonName": "hdmi_input", + "cSharpName": "HdmiInput", + "clrType": "System.Object" + }, + { + "jsonName": "sound_mode", + "cSharpName": "SoundMode", + "clrType": "System.String" + }, + { + "jsonName": "sound_mode_raw", + "cSharpName": "SoundModeRaw", + "clrType": "System.String" + }, + { + "jsonName": "restored", + "cSharpName": "Restored", + "clrType": "System.Boolean" + } + ] + }, + { + "domain": "automation", + "entities": [ + { + "id": "automation.ac_cool_on", + "friendlyName": "AC cool on", + "cSharpName": "AcCoolOn" + }, + { + "id": "automation.ac_tun_off", + "friendlyName": "AC tun off", + "cSharpName": "AcTunOff" + }, + { + "id": "automation.auto_turn_off_boiler", + "friendlyName": "Auto turn off boiler", + "cSharpName": "AutoTurnOffBoiler" + }, + { + "id": "automation.boiler_turn_on_counter", + "friendlyName": "Boiler turn on counter", + "cSharpName": "BoilerTurnOnCounter" + }, + { + "id": "automation.christmas_lights_sync", + "friendlyName": "Christmas lights sync", + "cSharpName": "ChristmasLightsSync" + }, + { + "id": "automation.christmas_lights_sync_v2", + "friendlyName": "Christmas lights sync v2", + "cSharpName": "ChristmasLightsSyncV2" + }, + { + "id": "automation.dehumidifier_on_off_counter", + "friendlyName": "Dehumidifier on counter", + "cSharpName": "DehumidifierOnOffCounter" + }, + { + "id": "automation.lamp_sync_off", + "friendlyName": "Lamp sync off", + "cSharpName": "LampSyncOff" + }, + { + "id": "automation.lamp_sync_on", + "friendlyName": "Lamp sync on", + "cSharpName": "LampSyncOn" + }, + { + "id": "automation.turn_of_dehumidifier", + "friendlyName": "Turn off dehumidifier", + "cSharpName": "TurnOfDehumidifier" + }, + { + "id": "automation.turn_off_all_lights", + "friendlyName": "Turn Off all lights", + "cSharpName": "TurnOffAllLights" + }, + { + "id": "automation.turnon_dehumidifier_then_not_at_home", + "friendlyName": "TurnOn Dehumidifier then not at home", + "cSharpName": "TurnonDehumidifierThenNotAtHome" + } + ], + "attributes": [ + { + "jsonName": "id", + "cSharpName": "Id", + "clrType": "System.String" + }, + { + "jsonName": "last_triggered", + "cSharpName": "LastTriggered", + "clrType": "System.String" + }, + { + "jsonName": "mode", + "cSharpName": "Mode", + "clrType": "System.String" + }, + { + "jsonName": "current", + "cSharpName": "Current", + "clrType": "System.Double" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "binary_sensor", + "entities": [ + { + "id": "binary_sensor.aquarium_leak_sensor", + "friendlyName": "Aquarium leak sensor", + "cSharpName": "AquariumLeakSensor" + }, + { + "id": "binary_sensor.boiler_moisture", + "friendlyName": "Boiler Moisture", + "cSharpName": "BoilerMoisture" + }, + { + "id": "binary_sensor.boilermonitor_budget_exhausted", + "friendlyName": "Boiler Monitor Budget exhausted", + "cSharpName": "BoilermonitorBudgetExhausted" + }, + { + "id": "binary_sensor.low_storage", + "friendlyName": "Low Storage", + "cSharpName": "LowStorage" + }, + { + "id": "binary_sensor.marius_watch_is_charging", + "friendlyName": "Marius Watch Is charging", + "cSharpName": "MariusWatchIsCharging" + }, + { + "id": "binary_sensor.marius_watch_on_body_sensor", + "friendlyName": "Marius Watch On body sensor", + "cSharpName": "MariusWatchOnBodySensor" + }, + { + "id": "binary_sensor.sm_s936b_is_charging", + "friendlyName": "Marius Phone Is charging", + "cSharpName": "SmS936bIsCharging" + }, + { + "id": "binary_sensor.sm_s936b_mobile_data", + "friendlyName": "Marius Phone Mobile data", + "cSharpName": "SmS936bMobileData" + }, + { + "id": "binary_sensor.sm_s936b_wi_fi_state", + "friendlyName": "Marius Phone Wi-Fi state", + "cSharpName": "SmS936bWiFiState" + }, + { + "id": "binary_sensor.wellbeing_air_purifier_2_connectionstate", + "friendlyName": "Connection State", + "cSharpName": "WellbeingAirPurifier2Connectionstate" + }, + { + "id": "binary_sensor.wellbeing_air_purifier_2_ionizer", + "friendlyName": "Ionizer", + "cSharpName": "WellbeingAirPurifier2Ionizer" + }, + { + "id": "binary_sensor.wellbeing_air_purifier_2_safetylock", + "friendlyName": "Safety Lock", + "cSharpName": "WellbeingAirPurifier2Safetylock" + }, + { + "id": "binary_sensor.wellbeing_air_purifier_2_status", + "friendlyName": "Status", + "cSharpName": "WellbeingAirPurifier2Status" + }, + { + "id": "binary_sensor.wellbeing_air_purifier_2_uilight", + "friendlyName": "UI Light", + "cSharpName": "WellbeingAirPurifier2Uilight" + } + ], + "attributes": [ + { + "jsonName": "entity_id", + "cSharpName": "EntityId", + "clrType": "System.String" + }, + { + "jsonName": "hysteresis", + "cSharpName": "Hysteresis", + "clrType": "System.Double" + }, + { + "jsonName": "lower", + "cSharpName": "Lower", + "clrType": "System.Double" + }, + { + "jsonName": "position", + "cSharpName": "Position", + "clrType": "System.String" + }, + { + "jsonName": "sensor_value", + "cSharpName": "SensorValue", + "clrType": "System.Double" + }, + { + "jsonName": "type", + "cSharpName": "Type", + "clrType": "System.String" + }, + { + "jsonName": "upper", + "cSharpName": "Upper", + "clrType": "System.Double" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "device_class", + "cSharpName": "DeviceClass", + "clrType": "System.String" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + }, + { + "jsonName": "integration", + "cSharpName": "Integration", + "clrType": "System.String" + }, + { + "jsonName": "capabilities", + "cSharpName": "Capabilities", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + } + ] + }, + { + "domain": "button", + "entities": [ + { + "id": "button.boiler_moisture_identify", + "friendlyName": "Boiler Moisture Identify", + "cSharpName": "BoilerMoistureIdentify" + }, + { + "id": "button.boiler_temp_identify", + "friendlyName": "Boiler room Temp Identify", + "cSharpName": "BoilerTempIdentify" + }, + { + "id": "button.boilermonitor_cleanup", + "friendlyName": "Boiler Monitor Cleanup all entities", + "cSharpName": "BoilermonitorCleanup" + }, + { + "id": "button.homeassistant_reload", + "friendlyName": "Home Assistant Reload", + "cSharpName": "HomeassistantReload" + }, + { + "id": "button.homeassistant_restart", + "friendlyName": "Home Assistant Restart", + "cSharpName": "HomeassistantRestart" + }, + { + "id": "button.ignore_all_issues", + "friendlyName": "Repairs Ignore all", + "cSharpName": "IgnoreAllIssues" + }, + { + "id": "button.powermonitor_rediscover_sensors", + "friendlyName": "Rediscover power sensors", + "cSharpName": "PowermonitorRediscoverSensors" + }, + { + "id": "button.unignore_all_issues", + "friendlyName": "Repairs Unignore all", + "cSharpName": "UnignoreAllIssues" + } + ], + "attributes": [ + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "device_class", + "cSharpName": "DeviceClass", + "clrType": "System.String" + } + ] + }, + { + "domain": "climate", + "entities": [ + { + "id": "climate.air_conditioner", + "friendlyName": "AC", + "cSharpName": "AirConditioner" + }, + { + "id": "climate.bathroom_thermostat", + "friendlyName": "Bathroom Thermostat", + "cSharpName": "BathroomThermostat" + }, + { + "id": "climate.main_home_termostat", + "friendlyName": "Main Home Termostat", + "cSharpName": "MainHomeTermostat" + }, + { + "id": "climate.windows_termostat", + "friendlyName": "Windows Termostat", + "cSharpName": "WindowsTermostat" + } + ], + "attributes": [ + { + "jsonName": "hvac_modes", + "cSharpName": "HvacModes", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "min_temp", + "cSharpName": "MinTemp", + "clrType": "System.Double" + }, + { + "jsonName": "max_temp", + "cSharpName": "MaxTemp", + "clrType": "System.Double" + }, + { + "jsonName": "target_temp_step", + "cSharpName": "TargetTempStep", + "clrType": "System.Double" + }, + { + "jsonName": "current_temperature", + "cSharpName": "CurrentTemperature", + "clrType": "System.Double" + }, + { + "jsonName": "temperature", + "cSharpName": "Temperature", + "clrType": "System.Double" + }, + { + "jsonName": "hvac_action", + "cSharpName": "HvacAction", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "supported_features", + "cSharpName": "SupportedFeatures", + "clrType": "System.Double" + }, + { + "jsonName": "current_humidity", + "cSharpName": "CurrentHumidity", + "clrType": "System.Double" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + } + ] + }, + { + "domain": "conversation", + "entities": [ + { + "id": "conversation.home_assistant", + "friendlyName": "Home Assistant", + "cSharpName": "HomeAssistant" + } + ], + "attributes": [ + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "supported_features", + "cSharpName": "SupportedFeatures", + "clrType": "System.Double" + } + ] + }, + { + "domain": "counter", + "entities": [ + { + "id": "counter.ac_on_off_counter", + "friendlyName": "AC on/off counter", + "cSharpName": "AcOnOffCounter" + }, + { + "id": "counter.boiler_turn_on_count", + "friendlyName": "Boiler turn on count", + "cSharpName": "BoilerTurnOnCount" + }, + { + "id": "counter.dehumidifier_on_off_counter", + "friendlyName": "Dehumidifier on counter", + "cSharpName": "DehumidifierOnOffCounter" + } + ], + "attributes": [ + { + "jsonName": "editable", + "cSharpName": "Editable", + "clrType": "System.Boolean" + }, + { + "jsonName": "initial", + "cSharpName": "Initial", + "clrType": "System.Double" + }, + { + "jsonName": "step", + "cSharpName": "Step", + "clrType": "System.Double" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "device_tracker", + "entities": [ + { + "id": "device_tracker.erika_s_iphone", + "friendlyName": "Erika\u0027s iPhone", + "cSharpName": "ErikaSIphone" + }, + { + "id": "device_tracker.home_phone", + "friendlyName": "Home Phone", + "cSharpName": "HomePhone" + }, + { + "id": "device_tracker.sm_s936b", + "friendlyName": "Marius Phone", + "cSharpName": "SmS936b" + } + ], + "attributes": [ + { + "jsonName": "source_type", + "cSharpName": "SourceType", + "clrType": "System.String" + }, + { + "jsonName": "latitude", + "cSharpName": "Latitude", + "clrType": "System.Double" + }, + { + "jsonName": "longitude", + "cSharpName": "Longitude", + "clrType": "System.Double" + }, + { + "jsonName": "gps_accuracy", + "cSharpName": "GpsAccuracy", + "clrType": "System.Double" + }, + { + "jsonName": "altitude", + "cSharpName": "Altitude", + "clrType": "System.Double" + }, + { + "jsonName": "course", + "cSharpName": "Course", + "clrType": "System.Double" + }, + { + "jsonName": "speed", + "cSharpName": "Speed", + "clrType": "System.Double" + }, + { + "jsonName": "vertical_accuracy", + "cSharpName": "VerticalAccuracy", + "clrType": "System.Double" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "battery_level", + "cSharpName": "BatteryLevel", + "clrType": "System.Double" + } + ] + }, + { + "domain": "event", + "entities": [ + { + "id": "event.repair", + "friendlyName": "Repairs", + "cSharpName": "Repair" + } + ], + "attributes": [ + { + "jsonName": "event_types", + "cSharpName": "EventTypes", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "event_type", + "cSharpName": "EventType", + "clrType": "System.String" + }, + { + "jsonName": "domain", + "cSharpName": "Domain", + "clrType": "System.String" + }, + { + "jsonName": "issue_id", + "cSharpName": "IssueId", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "fan", + "entities": [ + { + "id": "fan.wellbeing_air_purifier_2_fanspeed", + "friendlyName": "Fan Speed", + "cSharpName": "WellbeingAirPurifier2Fanspeed" + } + ], + "attributes": [ + { + "jsonName": "preset_modes", + "cSharpName": "PresetModes", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "percentage", + "cSharpName": "Percentage", + "clrType": "System.Double" + }, + { + "jsonName": "percentage_step", + "cSharpName": "PercentageStep", + "clrType": "System.Double" + }, + { + "jsonName": "preset_mode", + "cSharpName": "PresetMode", + "clrType": "System.String" + }, + { + "jsonName": "integration", + "cSharpName": "Integration", + "clrType": "System.String" + }, + { + "jsonName": "capabilities", + "cSharpName": "Capabilities", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "supported_features", + "cSharpName": "SupportedFeatures", + "clrType": "System.Double" + } + ] + }, + { + "domain": "humidifier", + "entities": [ + { + "id": "humidifier.auto_dehumidifier", + "friendlyName": "Auto Dehumidifier", + "cSharpName": "AutoDehumidifier" + } + ], + "attributes": [ + { + "jsonName": "min_humidity", + "cSharpName": "MinHumidity", + "clrType": "System.Double" + }, + { + "jsonName": "max_humidity", + "cSharpName": "MaxHumidity", + "clrType": "System.Double" + }, + { + "jsonName": "action", + "cSharpName": "Action", + "clrType": "System.String" + }, + { + "jsonName": "current_humidity", + "cSharpName": "CurrentHumidity", + "clrType": "System.Double" + }, + { + "jsonName": "humidity", + "cSharpName": "Humidity", + "clrType": "System.Double" + }, + { + "jsonName": "device_class", + "cSharpName": "DeviceClass", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "supported_features", + "cSharpName": "SupportedFeatures", + "clrType": "System.Double" + } + ] + }, + { + "domain": "input_boolean", + "entities": [ + { + "id": "input_boolean.ac_on_off", + "friendlyName": "AC on/off", + "cSharpName": "AcOnOff" + }, + { + "id": "input_boolean.boiler_boost_mode", + "friendlyName": "Boiler Boost Mode", + "cSharpName": "BoilerBoostMode" + }, + { + "id": "input_boolean.christmas_lights", + "friendlyName": "Christmas lights ", + "cSharpName": "ChristmasLights" + }, + { + "id": "input_boolean.netdaemon_boiler_monitor_manager_boiler_monitor_init", + "friendlyName": "netdaemon_boiler_monitor_manager_boiler_monitor_init", + "cSharpName": "NetdaemonBoilerMonitorManagerBoilerMonitorInit" + }, + { + "id": "input_boolean.netdaemon_nord_pool_manager_nord_pool_init", + "friendlyName": "netdaemon_nord_pool_manager_nord_pool_init", + "cSharpName": "NetdaemonNordPoolManagerNordPoolInit" + } + ], + "attributes": [ + { + "jsonName": "editable", + "cSharpName": "Editable", + "clrType": "System.Boolean" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "input_datetime", + "entities": [ + { + "id": "input_datetime.boiler_ready_by", + "friendlyName": "Boiler Ready By", + "cSharpName": "BoilerReadyBy" + } + ], + "attributes": [ + { + "jsonName": "has_date", + "cSharpName": "HasDate", + "clrType": "System.Boolean" + }, + { + "jsonName": "has_time", + "cSharpName": "HasTime", + "clrType": "System.Boolean" + }, + { + "jsonName": "editable", + "cSharpName": "Editable", + "clrType": "System.Boolean" + }, + { + "jsonName": "hour", + "cSharpName": "Hour", + "clrType": "System.Double" + }, + { + "jsonName": "minute", + "cSharpName": "Minute", + "clrType": "System.Double" + }, + { + "jsonName": "second", + "cSharpName": "Second", + "clrType": "System.Double" + }, + { + "jsonName": "timestamp", + "cSharpName": "Timestamp", + "clrType": "System.Double" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "input_number", + "isNumeric": true, + "entities": [ + { + "id": "input_number.boiler_daily_hours", + "friendlyName": "Boiler Daily Hours", + "cSharpName": "BoilerDailyHours" + }, + { + "id": "input_number.boiler_price_cap", + "friendlyName": "Boiler price cap", + "cSharpName": "BoilerPriceCap" + } + ], + "attributes": [ + { + "jsonName": "initial", + "cSharpName": "Initial", + "clrType": null + }, + { + "jsonName": "editable", + "cSharpName": "Editable", + "clrType": "System.Boolean" + }, + { + "jsonName": "min", + "cSharpName": "Min", + "clrType": "System.Double" + }, + { + "jsonName": "max", + "cSharpName": "Max", + "clrType": "System.Double" + }, + { + "jsonName": "step", + "cSharpName": "Step", + "clrType": "System.Double" + }, + { + "jsonName": "mode", + "cSharpName": "Mode", + "clrType": "System.String" + }, + { + "jsonName": "unit_of_measurement", + "cSharpName": "UnitOfMeasurement", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "number", + "isNumeric": true, + "entities": [ + { + "id": "number.bathroom_comfort_humidity_max", + "friendlyName": "Bathroom Comfort humidity max", + "cSharpName": "BathroomComfortHumidityMax" + }, + { + "id": "number.bathroom_comfort_humidity_min", + "friendlyName": "Bathroom Comfort humidity min", + "cSharpName": "BathroomComfortHumidityMin" + }, + { + "id": "number.bathroom_comfort_temperature_max", + "friendlyName": "Bathroom Comfort temperature max", + "cSharpName": "BathroomComfortTemperatureMax" + }, + { + "id": "number.bathroom_comfort_temperature_min", + "friendlyName": "Bathroom Comfort temperature min", + "cSharpName": "BathroomComfortTemperatureMin" + }, + { + "id": "number.bedroom_comfort_humidity_max", + "friendlyName": "Bedroom Comfort humidity max", + "cSharpName": "BedroomComfortHumidityMax" + }, + { + "id": "number.bedroom_comfort_humidity_min", + "friendlyName": "Bedroom Comfort humidity min", + "cSharpName": "BedroomComfortHumidityMin" + }, + { + "id": "number.bedroom_comfort_temperature_max", + "friendlyName": "Bedroom Comfort temperature max", + "cSharpName": "BedroomComfortTemperatureMax" + }, + { + "id": "number.bedroom_comfort_temperature_min", + "friendlyName": "Bedroom Comfort temperature min", + "cSharpName": "BedroomComfortTemperatureMin" + }, + { + "id": "number.boiler_temp_comfort_humidity_max", + "friendlyName": "Boiler room Temp Comfort humidity max", + "cSharpName": "BoilerTempComfortHumidityMax" + }, + { + "id": "number.boiler_temp_comfort_humidity_min", + "friendlyName": "Boiler room Temp Comfort humidity min", + "cSharpName": "BoilerTempComfortHumidityMin" + }, + { + "id": "number.boiler_temp_comfort_temperature_max", + "friendlyName": "Boiler room Temp Comfort temperature max", + "cSharpName": "BoilerTempComfortTemperatureMax" + }, + { + "id": "number.boiler_temp_comfort_temperature_min", + "friendlyName": "Boiler room Temp Comfort temperature min", + "cSharpName": "BoilerTempComfortTemperatureMin" + }, + { + "id": "number.boiler_temp_humidity_offset", + "friendlyName": "Boiler room Temp Humidity offset", + "cSharpName": "BoilerTempHumidityOffset" + }, + { + "id": "number.boiler_temp_temperature_offset", + "friendlyName": "Boiler room Temp Temperature offset", + "cSharpName": "BoilerTempTemperatureOffset" + }, + { + "id": "number.boilermonitor_config_heating_threshold", + "friendlyName": "Boiler Monitor Heating power threshold (watts)", + "cSharpName": "BoilermonitorConfigHeatingThreshold" + }, + { + "id": "number.boilermonitor_config_poll_interval", + "friendlyName": "Boiler Monitor Poll interval (seconds)", + "cSharpName": "BoilermonitorConfigPollInterval" + }, + { + "id": "number.main_home_comfort_humidity_max", + "friendlyName": "Main Home Comfort humidity max", + "cSharpName": "MainHomeComfortHumidityMax" + }, + { + "id": "number.main_home_comfort_humidity_min", + "friendlyName": "Main Home Comfort humidity min", + "cSharpName": "MainHomeComfortHumidityMin" + }, + { + "id": "number.main_home_comfort_temperature_max", + "friendlyName": "Main Home Comfort temperature max", + "cSharpName": "MainHomeComfortTemperatureMax" + }, + { + "id": "number.main_home_comfort_temperature_min", + "friendlyName": "Main Home Comfort temperature min", + "cSharpName": "MainHomeComfortTemperatureMin" + } + ], + "attributes": [ + { + "jsonName": "min", + "cSharpName": "Min", + "clrType": "System.Double" + }, + { + "jsonName": "max", + "cSharpName": "Max", + "clrType": "System.Double" + }, + { + "jsonName": "step", + "cSharpName": "Step", + "clrType": "System.Double" + }, + { + "jsonName": "mode", + "cSharpName": "Mode", + "clrType": "System.String" + }, + { + "jsonName": "unit_of_measurement", + "cSharpName": "UnitOfMeasurement", + "clrType": "System.String" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "device_class", + "cSharpName": "DeviceClass", + "clrType": "System.String" + } + ] + }, + { + "domain": "person", + "entities": [ + { + "id": "person.erika", + "friendlyName": "Erika", + "cSharpName": "Erika" + }, + { + "id": "person.home_phone", + "friendlyName": "Home Phone", + "cSharpName": "HomePhone" + }, + { + "id": "person.marius", + "friendlyName": "Marius", + "cSharpName": "Marius" + } + ], + "attributes": [ + { + "jsonName": "editable", + "cSharpName": "Editable", + "clrType": "System.Boolean" + }, + { + "jsonName": "id", + "cSharpName": "Id", + "clrType": "System.String" + }, + { + "jsonName": "device_trackers", + "cSharpName": "DeviceTrackers", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "latitude", + "cSharpName": "Latitude", + "clrType": "System.Double" + }, + { + "jsonName": "longitude", + "cSharpName": "Longitude", + "clrType": "System.Double" + }, + { + "jsonName": "gps_accuracy", + "cSharpName": "GpsAccuracy", + "clrType": "System.Double" + }, + { + "jsonName": "source", + "cSharpName": "Source", + "clrType": "System.String" + }, + { + "jsonName": "user_id", + "cSharpName": "UserId", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "remote", + "entities": [ + { + "id": "remote.123prasaunenuplysk_qe75q77datxxh", + "friendlyName": null, + "cSharpName": "_123prasaunenuplyskQe75q77datxxh" + }, + { + "id": "remote.123prasaunenuplysk_qe75q77datxxh_2", + "friendlyName": "123PrasauNenuplysk (QE75Q77DATXXH)", + "cSharpName": "_123prasaunenuplyskQe75q77datxxh2" + } + ], + "attributes": [ + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "supported_features", + "cSharpName": "SupportedFeatures", + "clrType": "System.Double" + }, + { + "jsonName": "restored", + "cSharpName": "Restored", + "clrType": "System.Boolean" + } + ] + }, + { + "domain": "script", + "entities": [ + { + "id": "script.system_purge_device_history", + "friendlyName": "System: Purge Device History", + "cSharpName": "SystemPurgeDeviceHistory" + }, + { + "id": "script.updatenordpoolprices", + "friendlyName": "Update NordPool Prices", + "cSharpName": "Updatenordpoolprices" + } + ], + "attributes": [ + { + "jsonName": "last_triggered", + "cSharpName": "LastTriggered", + "clrType": "System.String" + }, + { + "jsonName": "mode", + "cSharpName": "Mode", + "clrType": "System.String" + }, + { + "jsonName": "current", + "cSharpName": "Current", + "clrType": "System.Double" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + } + ] + }, + { + "domain": "select", + "entities": [ + { + "id": "select.akvariumas_start_up_behavior", + "friendlyName": "Akvariumas Power-on behavior", + "cSharpName": "AkvariumasStartUpBehavior" + }, + { + "id": "select.balkony_laps_start_up_behavior", + "friendlyName": "3D print Power-on behavior", + "cSharpName": "BalkonyLapsStartUpBehavior" + }, + { + "id": "select.bathroom_display_unit", + "friendlyName": "Bathroom Display unit", + "cSharpName": "BathroomDisplayUnit" + }, + { + "id": "select.bedroom_display_unit", + "friendlyName": "Bedroom Display unit", + "cSharpName": "BedroomDisplayUnit" + }, + { + "id": "select.boiler_temp_display_unit", + "friendlyName": "Boiler room Temp Display unit", + "cSharpName": "BoilerTempDisplayUnit" + }, + { + "id": "select.dishwasher_start_up_behavior", + "friendlyName": "Dishwasher Power-on behavior", + "cSharpName": "DishwasherStartUpBehavior" + }, + { + "id": "select.exhaust_fan_start_up_behavior", + "friendlyName": "Exhaust Fan Power-on behavior", + "cSharpName": "ExhaustFanStartUpBehavior" + }, + { + "id": "select.fridge_start_up_behavior", + "friendlyName": "Fridge Power-on behavior", + "cSharpName": "FridgeStartUpBehavior" + }, + { + "id": "select.heating_start_up_behavior", + "friendlyName": "Heating Relay Far Power-on behavior", + "cSharpName": "HeatingStartUpBehavior" + }, + { + "id": "select.heating_start_up_behavior_2", + "friendlyName": "Heating Relay Bathroom Power-on behavior", + "cSharpName": "HeatingStartUpBehavior2" + }, + { + "id": "select.heating_start_up_behavior_3", + "friendlyName": "Heating Relay Middle Power-on behavior", + "cSharpName": "HeatingStartUpBehavior3" + }, + { + "id": "select.main_home_display_unit", + "friendlyName": "Main Home Display unit", + "cSharpName": "MainHomeDisplayUnit" + }, + { + "id": "select.sonoff_10018909cb_startup", + "friendlyName": "Induction Startup", + "cSharpName": "Sonoff10018909cbStartup" + }, + { + "id": "select.sonoff_100215c534_1", + "friendlyName": "AC", + "cSharpName": "Sonoff100215c5341" + }, + { + "id": "select.sonoff_100222f7be_1", + "friendlyName": "Lamp", + "cSharpName": "Sonoff100222f7be1" + }, + { + "id": "select.sonoff_100222ff36_1", + "friendlyName": "Christmas tree", + "cSharpName": "Sonoff100222ff361" + }, + { + "id": "select.sonoff_100222ff63_1", + "friendlyName": "Stair lamps", + "cSharpName": "Sonoff100222ff631" + }, + { + "id": "select.sonoff_1002230a48_1", + "friendlyName": "Po laiptais", + "cSharpName": "Sonoff1002230a481" + }, + { + "id": "select.sonoff_1002230e32_1", + "friendlyName": "Boiler", + "cSharpName": "Sonoff1002230e321" + }, + { + "id": "select.sonoff_100255ead8_1", + "friendlyName": "Washer", + "cSharpName": "Sonoff100255ead81" + }, + { + "id": "select.sonoff_100255f06c_1", + "friendlyName": "Dryer", + "cSharpName": "Sonoff100255f06c1" + }, + { + "id": "select.sonoff_100255f738_1", + "friendlyName": "Cat Christmas lamps", + "cSharpName": "Sonoff100255f7381" + }, + { + "id": "select.sonoff_10025606e6_1", + "friendlyName": "Dehumidifier", + "cSharpName": "Sonoff10025606e61" + }, + { + "id": "select.sonoff_10025609ce_1", + "friendlyName": "Salt Lamp", + "cSharpName": "Sonoff10025609ce1" + }, + { + "id": "select.sonoff_100267d63f_1", + "friendlyName": "Home meter", + "cSharpName": "Sonoff100267d63f1" + }, + { + "id": "select.sonoff_s60zbtpf_start_up_behavior", + "friendlyName": "LED power Power-on behavior", + "cSharpName": "SonoffS60zbtpfStartUpBehavior" + }, + { + "id": "select.sonoff_s60zbtpf_start_up_behavior_2", + "friendlyName": "Air Purifirier Power-on behavior", + "cSharpName": "SonoffS60zbtpfStartUpBehavior2" + }, + { + "id": "select.temp_start_up_behavior", + "friendlyName": "Network Infra Power-on behavior", + "cSharpName": "TempStartUpBehavior" + }, + { + "id": "select.tv_start_up_behavior", + "friendlyName": "TV Power-on behavior", + "cSharpName": "TvStartUpBehavior" + }, + { + "id": "select.washing_room_display_unit", + "friendlyName": "Washing room Display unit", + "cSharpName": "WashingRoomDisplayUnit" + } + ], + "attributes": [ + { + "jsonName": "options", + "cSharpName": "Options", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "sensor", + "entities": [ + { + "id": "sensor.ac_status", + "friendlyName": "AC status", + "cSharpName": "AcStatus" + }, + { + "id": "sensor.air_purified_status", + "friendlyName": "Air Purified Status", + "cSharpName": "AirPurifiedStatus" + }, + { + "id": "sensor.air_quality", + "friendlyName": "Home Assistant Air quality", + "cSharpName": "AirQuality" + }, + { + "id": "sensor.akvariumas_status", + "friendlyName": "Akvariumas Status", + "cSharpName": "AkvariumasStatus" + }, + { + "id": "sensor.alarm_control_panels", + "friendlyName": "Home Assistant Alarm control panels", + "cSharpName": "AlarmControlPanels" + }, + { + "id": "sensor.areas", + "friendlyName": "Home Assistant Areas", + "cSharpName": "Areas" + }, + { + "id": "sensor.automations", + "friendlyName": "Home Assistant Automations", + "cSharpName": "Automations" + }, + { + "id": "sensor.backup_last_attempted_automatic_backup", + "friendlyName": "Backup Last attempted automatic backup", + "cSharpName": "BackupLastAttemptedAutomaticBackup" + }, + { + "id": "sensor.backup_last_successful_automatic_backup", + "friendlyName": "Backup Last successful automatic backup", + "cSharpName": "BackupLastSuccessfulAutomaticBackup" + }, + { + "id": "sensor.binary_sensors", + "friendlyName": "Home Assistant Binary sensors", + "cSharpName": "BinarySensors" + }, + { + "id": "sensor.boiler_running", + "friendlyName": "Boiler running", + "cSharpName": "BoilerRunning" + }, + { + "id": "sensor.boilermonitor_session_count", + "friendlyName": "Boiler Monitor Heating sessions today", + "cSharpName": "BoilermonitorSessionCount" + }, + { + "id": "sensor.boilermonitor_status", + "friendlyName": "Boiler Monitor Boiler Monitor status", + "cSharpName": "BoilermonitorStatus" + }, + { + "id": "sensor.boilermonitor_water_ready", + "friendlyName": "Boiler Monitor Boiler water ready", + "cSharpName": "BoilermonitorWaterReady" + }, + { + "id": "sensor.buttons", + "friendlyName": "Home Assistant Buttons", + "cSharpName": "Buttons" + }, + { + "id": "sensor.calendars", + "friendlyName": "Home Assistant Calendars", + "cSharpName": "Calendars" + }, + { + "id": "sensor.cameras", + "friendlyName": "Home Assistant Cameras", + "cSharpName": "Cameras" + }, + { + "id": "sensor.climate", + "friendlyName": "Home Assistant Climate", + "cSharpName": "Climate" + }, + { + "id": "sensor.covers", + "friendlyName": "Home Assistant Covers", + "cSharpName": "Covers" + }, + { + "id": "sensor.custom_integrations", + "friendlyName": "Home Assistant Custom integrations", + "cSharpName": "CustomIntegrations" + }, + { + "id": "sensor.dates", + "friendlyName": "Home Assistant Dates", + "cSharpName": "Dates" + }, + { + "id": "sensor.datetimes", + "friendlyName": "Home Assistant Date/times", + "cSharpName": "Datetimes" + }, + { + "id": "sensor.dehumidifier_status", + "friendlyName": "Dehumidifier status", + "cSharpName": "DehumidifierStatus" + }, + { + "id": "sensor.device_trackers", + "friendlyName": "Home Assistant Device trackers", + "cSharpName": "DeviceTrackers" + }, + { + "id": "sensor.devices", + "friendlyName": "Home Assistant Devices", + "cSharpName": "Devices" + }, + { + "id": "sensor.dishwasher_status", + "friendlyName": "Dishwasher status", + "cSharpName": "DishwasherStatus" + }, + { + "id": "sensor.dryer_status", + "friendlyName": "Dryer Status", + "cSharpName": "DryerStatus" + }, + { + "id": "sensor.entities", + "friendlyName": "Home Assistant Entities", + "cSharpName": "Entities" + }, + { + "id": "sensor.erika_s_iphone_battery_state", + "friendlyName": "Erika\u0027s iPhone Battery State", + "cSharpName": "ErikaSIphoneBatteryState" + }, + { + "id": "sensor.erika_s_iphone_connection_type", + "friendlyName": "Erika\u0027s iPhone Connection Type", + "cSharpName": "ErikaSIphoneConnectionType" + }, + { + "id": "sensor.erika_s_iphone_geocoded_location", + "friendlyName": "Erika\u0027s iPhone Geocoded Location", + "cSharpName": "ErikaSIphoneGeocodedLocation" + }, + { + "id": "sensor.erika_s_iphone_ssid", + "friendlyName": "Erika\u0027s iPhone SSID", + "cSharpName": "ErikaSIphoneSsid" + }, + { + "id": "sensor.fans", + "friendlyName": "Home Assistant Fans", + "cSharpName": "Fans" + }, + { + "id": "sensor.home_assistant_operating_system_newest_version", + "friendlyName": "Home Assistant Operating System Newest version", + "cSharpName": "HomeAssistantOperatingSystemNewestVersion" + }, + { + "id": "sensor.home_assistant_operating_system_version", + "friendlyName": "Home Assistant Operating System Version", + "cSharpName": "HomeAssistantOperatingSystemVersion" + }, + { + "id": "sensor.home_phone_battery_state", + "friendlyName": "Home Phone Battery state", + "cSharpName": "HomePhoneBatteryState" + }, + { + "id": "sensor.home_phone_charger_type", + "friendlyName": "Home Phone Charger type", + "cSharpName": "HomePhoneChargerType" + }, + { + "id": "sensor.humidifiers", + "friendlyName": "Home Assistant Humidifiers", + "cSharpName": "Humidifiers" + }, + { + "id": "sensor.images", + "friendlyName": "Home Assistant Images", + "cSharpName": "Images" + }, + { + "id": "sensor.input_booleans", + "friendlyName": "Home Assistant Input booleans", + "cSharpName": "InputBooleans" + }, + { + "id": "sensor.input_buttons", + "friendlyName": "Home Assistant Input buttons", + "cSharpName": "InputButtons" + }, + { + "id": "sensor.input_datetimes", + "friendlyName": "Home Assistant Input date/times", + "cSharpName": "InputDatetimes" + }, + { + "id": "sensor.input_numbers", + "friendlyName": "Home Assistant Input numbers", + "cSharpName": "InputNumbers" + }, + { + "id": "sensor.input_selects", + "friendlyName": "Home Assistant Input selects", + "cSharpName": "InputSelects" + }, + { + "id": "sensor.input_texts", + "friendlyName": "Home Assistant Input texts", + "cSharpName": "InputTexts" + }, + { + "id": "sensor.integrations", + "friendlyName": "Home Assistant Integrations", + "cSharpName": "Integrations" + }, + { + "id": "sensor.kaunas_noreikiskes_lithuania_air_quality_index", + "friendlyName": "Kaunas Noreikiskes, Lithuania Air quality index", + "cSharpName": "KaunasNoreikiskesLithuaniaAirQualityIndex" + }, + { + "id": "sensor.kaunas_noreikiskes_lithuania_carbon_monoxide", + "friendlyName": "Kaunas Noreikiskes, Lithuania Carbon monoxide", + "cSharpName": "KaunasNoreikiskesLithuaniaCarbonMonoxide" + }, + { + "id": "sensor.kaunas_noreikiskes_lithuania_dominant_pollutant", + "friendlyName": "Kaunas Noreikiskes, Lithuania Dominant pollutant", + "cSharpName": "KaunasNoreikiskesLithuaniaDominantPollutant" + }, + { + "id": "sensor.kaunas_noreikiskes_lithuania_ozone", + "friendlyName": "Kaunas Noreikiskes, Lithuania Ozone", + "cSharpName": "KaunasNoreikiskesLithuaniaOzone" + }, + { + "id": "sensor.kaunas_noreikiskes_lithuania_pm10", + "friendlyName": "Kaunas Noreikiskes, Lithuania PM10", + "cSharpName": "KaunasNoreikiskesLithuaniaPm10" + }, + { + "id": "sensor.kaunas_noreikiskes_lithuania_pm2_5", + "friendlyName": "Kaunas Noreikiskes, Lithuania PM2.5", + "cSharpName": "KaunasNoreikiskesLithuaniaPm25" + }, + { + "id": "sensor.kaunas_noreikiskes_lithuania_sulphur_dioxide", + "friendlyName": "Kaunas Noreikiskes, Lithuania Sulphur dioxide", + "cSharpName": "KaunasNoreikiskesLithuaniaSulphurDioxide" + }, + { + "id": "sensor.lights", + "friendlyName": "Home Assistant Lights", + "cSharpName": "Lights" + }, + { + "id": "sensor.locks", + "friendlyName": "Home Assistant Locks", + "cSharpName": "Locks" + }, + { + "id": "sensor.marius_watch_activity_state", + "friendlyName": "Marius Watch Activity state", + "cSharpName": "MariusWatchActivityState" + }, + { + "id": "sensor.marius_watch_battery_health", + "friendlyName": "Marius Watch Battery health", + "cSharpName": "MariusWatchBatteryHealth" + }, + { + "id": "sensor.marius_watch_battery_state", + "friendlyName": "Marius Watch Battery state", + "cSharpName": "MariusWatchBatteryState" + }, + { + "id": "sensor.marius_watch_charger_type", + "friendlyName": "Marius Watch Charger type", + "cSharpName": "MariusWatchChargerType" + }, + { + "id": "sensor.marius_watch_network_type", + "friendlyName": "Marius Watch Network type", + "cSharpName": "MariusWatchNetworkType" + }, + { + "id": "sensor.media_players", + "friendlyName": "Home Assistant Media players", + "cSharpName": "MediaPlayers" + }, + { + "id": "sensor.nord_pool_lt_last_updated", + "friendlyName": "Nord Pool LT Last updated", + "cSharpName": "NordPoolLtLastUpdated" + }, + { + "id": "sensor.nordpool_boiler_water_ready", + "friendlyName": "Boiler water ready", + "cSharpName": "NordpoolBoilerWaterReady" + }, + { + "id": "sensor.nordpool_cheapest_intervals", + "friendlyName": "NordPool NordPool cheapest boiler intervals", + "cSharpName": "NordpoolCheapestIntervals" + }, + { + "id": "sensor.nordpool_last_update_time", + "friendlyName": "NordPool NordPool last update time", + "cSharpName": "NordpoolLastUpdateTime" + }, + { + "id": "sensor.nordpool_today_prices", + "friendlyName": "NordPool NordPool today prices", + "cSharpName": "NordpoolTodayPrices" + }, + { + "id": "sensor.nordpool_today_tomorrow_prices", + "friendlyName": "NordPool NordPool today and tomorrow prices", + "cSharpName": "NordpoolTodayTomorrowPrices" + }, + { + "id": "sensor.nordpool_tomorrow_prices", + "friendlyName": "NordPool NordPool tomorrow prices", + "cSharpName": "NordpoolTomorrowPrices" + }, + { + "id": "sensor.numbers", + "friendlyName": "Home Assistant Numbers", + "cSharpName": "Numbers" + }, + { + "id": "sensor.persistent_notifications", + "friendlyName": "Home Assistant Persistent notifications", + "cSharpName": "PersistentNotifications" + }, + { + "id": "sensor.persons", + "friendlyName": "Home Assistant Persons", + "cSharpName": "Persons" + }, + { + "id": "sensor.remotes", + "friendlyName": "Home Assistant Remotes", + "cSharpName": "Remotes" + }, + { + "id": "sensor.scenes", + "friendlyName": "Home Assistant Scenes", + "cSharpName": "Scenes" + }, + { + "id": "sensor.scripts", + "friendlyName": "Home Assistant Scripts", + "cSharpName": "Scripts" + }, + { + "id": "sensor.selects", + "friendlyName": "Home Assistant Selects", + "cSharpName": "Selects" + }, + { + "id": "sensor.sensors", + "friendlyName": "Home Assistant Sensors", + "cSharpName": "Sensors" + }, + { + "id": "sensor.sirens", + "friendlyName": "Home Assistant Sirens", + "cSharpName": "Sirens" + }, + { + "id": "sensor.system_monitor_last_boot", + "friendlyName": "System Monitor Last boot", + "cSharpName": "SystemMonitorLastBoot" + }, + { + "id": "sensor.sm_s936b_battery_health", + "friendlyName": "Marius Phone Battery health", + "cSharpName": "SmS936bBatteryHealth" + }, + { + "id": "sensor.sm_s936b_battery_state", + "friendlyName": "Marius Phone Battery state", + "cSharpName": "SmS936bBatteryState" + }, + { + "id": "sensor.sm_s936b_detected_activity", + "friendlyName": "Marius Phone Detected activity", + "cSharpName": "SmS936bDetectedActivity" + }, + { + "id": "sensor.sm_s936b_geocoded_location", + "friendlyName": "Marius Phone Geocoded location", + "cSharpName": "SmS936bGeocodedLocation" + }, + { + "id": "sensor.sm_s936b_network_type", + "friendlyName": "Marius Phone Network type", + "cSharpName": "SmS936bNetworkType" + }, + { + "id": "sensor.sm_s936b_phone_state", + "friendlyName": "Marius Phone Phone state", + "cSharpName": "SmS936bPhoneState" + }, + { + "id": "sensor.sm_s936b_sim_1", + "friendlyName": "Marius Phone SIM 1", + "cSharpName": "SmS936bSim1" + }, + { + "id": "sensor.sm_s936b_wi_fi_connection", + "friendlyName": "Marius Phone Wi-Fi connection", + "cSharpName": "SmS936bWiFiConnection" + }, + { + "id": "sensor.sonoff_1002479627_connection", + "friendlyName": "Main Device Connection", + "cSharpName": "Sonoff1002479627Connection" + }, + { + "id": "sensor.stt", + "friendlyName": "Home Assistant Speech-to-text", + "cSharpName": "Stt" + }, + { + "id": "sensor.sun_next_dawn", + "friendlyName": "Sun Next dawn", + "cSharpName": "SunNextDawn" + }, + { + "id": "sensor.sun_next_dusk", + "friendlyName": "Sun Next dusk", + "cSharpName": "SunNextDusk" + }, + { + "id": "sensor.sun_next_midnight", + "friendlyName": "Sun Next midnight", + "cSharpName": "SunNextMidnight" + }, + { + "id": "sensor.sun_next_noon", + "friendlyName": "Sun Next noon", + "cSharpName": "SunNextNoon" + }, + { + "id": "sensor.sun_next_rising", + "friendlyName": "Sun Next rising", + "cSharpName": "SunNextRising" + }, + { + "id": "sensor.sun_next_setting", + "friendlyName": "Sun Next setting", + "cSharpName": "SunNextSetting" + }, + { + "id": "sensor.suns", + "friendlyName": "Home Assistant Suns", + "cSharpName": "Suns" + }, + { + "id": "sensor.switches", + "friendlyName": "Home Assistant Switches", + "cSharpName": "Switches" + }, + { + "id": "sensor.texts", + "friendlyName": "Home Assistant Texts", + "cSharpName": "Texts" + }, + { + "id": "sensor.times", + "friendlyName": "Home Assistant Times", + "cSharpName": "Times" + }, + { + "id": "sensor.tts", + "friendlyName": "Home Assistant Text-to-speech", + "cSharpName": "Tts" + }, + { + "id": "sensor.update", + "friendlyName": "Home Assistant Update", + "cSharpName": "Update" + }, + { + "id": "sensor.vacuums", + "friendlyName": "Home Assistant Vacuums", + "cSharpName": "Vacuums" + }, + { + "id": "sensor.washer_status", + "friendlyName": "Washer Status", + "cSharpName": "WasherStatus" + }, + { + "id": "sensor.water_heaters", + "friendlyName": "Home Assistant Water heaters", + "cSharpName": "WaterHeaters" + }, + { + "id": "sensor.weather", + "friendlyName": "Home Assistant Weather", + "cSharpName": "Weather" + }, + { + "id": "sensor.zones", + "friendlyName": "Home Assistant Zones", + "cSharpName": "Zones" + } + ], + "attributes": [ + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "device_class", + "cSharpName": "DeviceClass", + "clrType": "System.String" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + }, + { + "jsonName": "options", + "cSharpName": "Options", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "still", + "cSharpName": "Still", + "clrType": "System.Double" + }, + { + "jsonName": "unknown", + "cSharpName": "Unknown", + "clrType": "System.Double" + }, + { + "jsonName": "administrative_area", + "cSharpName": "AdministrativeArea_0", + "clrType": "System.String" + }, + { + "jsonName": "Administrative Area", + "cSharpName": "AdministrativeArea_1", + "clrType": "System.String" + }, + { + "jsonName": "country", + "cSharpName": "Country_0", + "clrType": "System.String" + }, + { + "jsonName": "Country", + "cSharpName": "Country_1", + "clrType": "System.String" + }, + { + "jsonName": "iso_country_code", + "cSharpName": "IsoCountryCode", + "clrType": "System.String" + }, + { + "jsonName": "locality", + "cSharpName": "Locality_0", + "clrType": "System.String" + }, + { + "jsonName": "Locality", + "cSharpName": "Locality_1", + "clrType": "System.String" + }, + { + "jsonName": "location", + "cSharpName": "Location_0", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.Double]" + }, + { + "jsonName": "Location", + "cSharpName": "Location_1", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.Double]" + }, + { + "jsonName": "name", + "cSharpName": "Name_0", + "clrType": "System.String" + }, + { + "jsonName": "Name", + "cSharpName": "Name_1", + "clrType": "System.String" + }, + { + "jsonName": "phone", + "cSharpName": "Phone", + "clrType": "System.String" + }, + { + "jsonName": "postal_code", + "cSharpName": "PostalCode_0", + "clrType": "System.String" + }, + { + "jsonName": "Postal Code", + "cSharpName": "PostalCode_1", + "clrType": "System.String" + }, + { + "jsonName": "premises", + "cSharpName": "Premises", + "clrType": "System.String" + }, + { + "jsonName": "sub_administrative_area", + "cSharpName": "SubAdministrativeArea_0", + "clrType": "System.String" + }, + { + "jsonName": "Sub Administrative Area", + "cSharpName": "SubAdministrativeArea_1", + "clrType": "System.String" + }, + { + "jsonName": "sub_locality", + "cSharpName": "SubLocality_0", + "clrType": "System.String" + }, + { + "jsonName": "Sub Locality", + "cSharpName": "SubLocality_1", + "clrType": "System.String" + }, + { + "jsonName": "sub_thoroughfare", + "cSharpName": "SubThoroughfare_0", + "clrType": "System.String" + }, + { + "jsonName": "Sub Thoroughfare", + "cSharpName": "SubThoroughfare_1", + "clrType": "System.String" + }, + { + "jsonName": "thoroughfare", + "cSharpName": "Thoroughfare_0", + "clrType": "System.String" + }, + { + "jsonName": "Thoroughfare", + "cSharpName": "Thoroughfare_1", + "clrType": "System.String" + }, + { + "jsonName": "url", + "cSharpName": "Url", + "clrType": "System.String" + }, + { + "jsonName": "is_hidden", + "cSharpName": "IsHidden", + "clrType": "System.Boolean" + }, + { + "jsonName": "metered", + "cSharpName": "Metered", + "clrType": "System.Boolean" + }, + { + "jsonName": "carrier id", + "cSharpName": "Carrierid", + "clrType": "System.Double" + }, + { + "jsonName": "carrier name", + "cSharpName": "Carriername", + "clrType": "System.String" + }, + { + "jsonName": "data roaming", + "cSharpName": "Dataroaming", + "clrType": "System.String" + }, + { + "jsonName": "is opportunistic", + "cSharpName": "Isopportunistic", + "clrType": "System.Boolean" + }, + { + "jsonName": "iso country code", + "cSharpName": "Isocountrycode", + "clrType": "System.String" + }, + { + "jsonName": "mcc", + "cSharpName": "Mcc", + "clrType": "System.String" + }, + { + "jsonName": "mnc", + "cSharpName": "Mnc", + "clrType": "System.String" + }, + { + "jsonName": "Low Power Mode", + "cSharpName": "LowPowerMode", + "clrType": "System.Boolean" + }, + { + "jsonName": "Areas Of Interest", + "cSharpName": "AreasOfInterest", + "clrType": "System.String" + }, + { + "jsonName": "Inland Water", + "cSharpName": "InlandWater", + "clrType": "System.String" + }, + { + "jsonName": "ISO Country Code", + "cSharpName": "ISOCountryCode", + "clrType": "System.String" + }, + { + "jsonName": "Ocean", + "cSharpName": "Ocean", + "clrType": "System.String" + }, + { + "jsonName": "Time Zone", + "cSharpName": "TimeZone", + "clrType": "System.String" + }, + { + "jsonName": "Zones", + "cSharpName": "Zones", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "exercise_type", + "cSharpName": "ExerciseType", + "clrType": "System.String" + }, + { + "jsonName": "time", + "cSharpName": "Time", + "clrType": "System.String" + }, + { + "jsonName": "state_class", + "cSharpName": "StateClass", + "clrType": "System.String" + }, + { + "jsonName": "attribution", + "cSharpName": "Attribution", + "clrType": "System.String" + }, + { + "jsonName": "prices", + "cSharpName": "Prices", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.Collections.Generic.IReadOnlyList\u00601[System.Double]]" + }, + { + "jsonName": "last_updated", + "cSharpName": "LastUpdated", + "clrType": "System.String" + }, + { + "jsonName": "prices_count", + "cSharpName": "PricesCount", + "clrType": "System.Double" + }, + { + "jsonName": "intervals", + "cSharpName": "Intervals", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.Object]" + }, + { + "jsonName": "configured_hours", + "cSharpName": "ConfiguredHours", + "clrType": "System.Double" + }, + { + "jsonName": "configured_interval_count", + "cSharpName": "ConfiguredIntervalCount", + "clrType": "System.Double" + }, + { + "jsonName": "configured_price_cap", + "cSharpName": "ConfiguredPriceCap", + "clrType": "System.Double" + }, + { + "jsonName": "skip_price_cap", + "cSharpName": "SkipPriceCap", + "clrType": "System.Boolean" + }, + { + "jsonName": "configured_ready_by", + "cSharpName": "ConfiguredReadyBy", + "clrType": "System.String" + }, + { + "jsonName": "total_heating_minutes", + "cSharpName": "TotalHeatingMinutes", + "clrType": "System.Double" + }, + { + "jsonName": "is_now_cheap", + "cSharpName": "IsNowCheap", + "clrType": "System.Boolean" + }, + { + "jsonName": "next_cheap_interval", + "cSharpName": "NextCheapInterval", + "clrType": null + }, + { + "jsonName": "boiler_switch_state", + "cSharpName": "BoilerSwitchState", + "clrType": "System.String" + }, + { + "jsonName": "boiler_power_watts", + "cSharpName": "BoilerPowerWatts", + "clrType": "System.Double" + }, + { + "jsonName": "power_threshold_watts", + "cSharpName": "PowerThresholdWatts", + "clrType": "System.Double" + } + ] + }, + { + "domain": "sensor", + "isNumeric": true, + "entities": [ + { + "id": "sensor.active_issues", + "friendlyName": "Repairs Active", + "cSharpName": "ActiveIssues" + }, + { + "id": "sensor.akvariumas_power", + "friendlyName": "Akvariumas Power", + "cSharpName": "AkvariumasPower" + }, + { + "id": "sensor.akvariumas_voltage", + "friendlyName": "Akvariumas Voltage", + "cSharpName": "AkvariumasVoltage" + }, + { + "id": "sensor.aquarium_leak_sensor_battery", + "friendlyName": "Aquarium leak sensor Battery", + "cSharpName": "AquariumLeakSensorBattery" + }, + { + "id": "sensor.balkony_laps_power", + "friendlyName": "3D print Power", + "cSharpName": "BalkonyLapsPower" + }, + { + "id": "sensor.balkony_laps_voltage", + "friendlyName": "3D print Voltage", + "cSharpName": "BalkonyLapsVoltage" + }, + { + "id": "sensor.bathroom_battery", + "friendlyName": "Bathroom Battery", + "cSharpName": "BathroomBattery" + }, + { + "id": "sensor.bathroom_humidity", + "friendlyName": "Bathroom Humidity", + "cSharpName": "BathroomHumidity" + }, + { + "id": "sensor.bathroom_temperature", + "friendlyName": "Bathroom Temperature", + "cSharpName": "BathroomTemperature" + }, + { + "id": "sensor.bedroom_battery", + "friendlyName": "Bedroom Battery", + "cSharpName": "BedroomBattery" + }, + { + "id": "sensor.bedroom_humidity", + "friendlyName": "Bedroom Humidity", + "cSharpName": "BedroomHumidity" + }, + { + "id": "sensor.bedroom_temperature", + "friendlyName": "Bedroom Temperature", + "cSharpName": "BedroomTemperature" + }, + { + "id": "sensor.boiler_moisture_battery", + "friendlyName": "Boiler Moisture Battery", + "cSharpName": "BoilerMoistureBattery" + }, + { + "id": "sensor.boiler_run_time", + "friendlyName": "Boiler run time", + "cSharpName": "BoilerRunTime" + }, + { + "id": "sensor.boiler_temp_battery", + "friendlyName": "Boiler room Temp Battery", + "cSharpName": "BoilerTempBattery" + }, + { + "id": "sensor.boiler_temp_humidity", + "friendlyName": "Boiler room Temp Humidity", + "cSharpName": "BoilerTempHumidity" + }, + { + "id": "sensor.boiler_temp_temperature", + "friendlyName": "Boiler room Temp Temperature", + "cSharpName": "BoilerTempTemperature" + }, + { + "id": "sensor.boilermonitor_budget_percentage", + "friendlyName": "Boiler Monitor Budget usage", + "cSharpName": "BoilermonitorBudgetPercentage" + }, + { + "id": "sensor.boilermonitor_remaining_time", + "friendlyName": "Boiler Monitor Remaining budget time", + "cSharpName": "BoilermonitorRemainingTime" + }, + { + "id": "sensor.boilermonitor_today_runtime", + "friendlyName": "Boiler Monitor Today runtime", + "cSharpName": "BoilermonitorTodayRuntime" + }, + { + "id": "sensor.cat_area_temp_battery", + "friendlyName": "Cat Area Temp Battery", + "cSharpName": "CatAreaTempBattery" + }, + { + "id": "sensor.cat_area_temp_humidity", + "friendlyName": "Cat Area Temp Humidity", + "cSharpName": "CatAreaTempHumidity" + }, + { + "id": "sensor.cat_area_temp_temperature", + "friendlyName": "Cat Area Temp Temperature", + "cSharpName": "CatAreaTempTemperature" + }, + { + "id": "sensor.current_setpoint", + "friendlyName": "Current SetPoint", + "cSharpName": "CurrentSetpoint" + }, + { + "id": "sensor.dehumidifier_running_time", + "friendlyName": "Dehumidifier running time", + "cSharpName": "DehumidifierRunningTime" + }, + { + "id": "sensor.dishwasher_power", + "friendlyName": "Dishwasher Power", + "cSharpName": "DishwasherPower" + }, + { + "id": "sensor.dishwasher_voltage", + "friendlyName": "Dishwasher Voltage", + "cSharpName": "DishwasherVoltage" + }, + { + "id": "sensor.erika_s_iphone_battery_level", + "friendlyName": "Erika\u0027s iPhone Battery Level", + "cSharpName": "ErikaSIphoneBatteryLevel" + }, + { + "id": "sensor.fridge_power", + "friendlyName": "Fridge Power", + "cSharpName": "FridgePower" + }, + { + "id": "sensor.fridge_voltage", + "friendlyName": "Fridge Voltage", + "cSharpName": "FridgeVoltage" + }, + { + "id": "sensor.home_phone_battery_level", + "friendlyName": "Home Phone Battery level", + "cSharpName": "HomePhoneBatteryLevel" + }, + { + "id": "sensor.ignored_issues", + "friendlyName": "Repairs Ignored", + "cSharpName": "IgnoredIssues" + }, + { + "id": "sensor.issues", + "friendlyName": "Repairs Total", + "cSharpName": "Issues" + }, + { + "id": "sensor.kaunas_noreikiskes_lithuania_humidity", + "friendlyName": "Kaunas Noreikiskes, Lithuania Humidity", + "cSharpName": "KaunasNoreikiskesLithuaniaHumidity" + }, + { + "id": "sensor.kaunas_noreikiskes_lithuania_pressure", + "friendlyName": "Kaunas Noreikiskes, Lithuania Pressure", + "cSharpName": "KaunasNoreikiskesLithuaniaPressure" + }, + { + "id": "sensor.kaunas_noreikiskes_lithuania_temperature", + "friendlyName": "Kaunas Noreikiskes, Lithuania Temperature", + "cSharpName": "KaunasNoreikiskesLithuaniaTemperature" + }, + { + "id": "sensor.main_home_battery", + "friendlyName": "Main Home Battery", + "cSharpName": "MainHomeBattery" + }, + { + "id": "sensor.main_home_humidity", + "friendlyName": "Main Home Humidity", + "cSharpName": "MainHomeHumidity" + }, + { + "id": "sensor.main_home_temperature", + "friendlyName": "Main Home Temperature", + "cSharpName": "MainHomeTemperature" + }, + { + "id": "sensor.marius_watch_battery_level", + "friendlyName": "Marius Watch Battery level", + "cSharpName": "MariusWatchBatteryLevel" + }, + { + "id": "sensor.marius_watch_battery_temperature", + "friendlyName": "Marius Watch Battery temperature", + "cSharpName": "MariusWatchBatteryTemperature" + }, + { + "id": "sensor.marius_watch_daily_steps", + "friendlyName": "Marius Watch Daily steps", + "cSharpName": "MariusWatchDailySteps" + }, + { + "id": "sensor.marius_watch_heart_rate", + "friendlyName": "Marius Watch Heart rate", + "cSharpName": "MariusWatchHeartRate" + }, + { + "id": "sensor.marius_watch_light_sensor", + "friendlyName": "Marius Watch Light sensor", + "cSharpName": "MariusWatchLightSensor" + }, + { + "id": "sensor.marius_watch_steps_sensor", + "friendlyName": "Marius Watch Steps sensor", + "cSharpName": "MariusWatchStepsSensor" + }, + { + "id": "sensor.netdaemon_v6_net_10_cpu_percent", + "friendlyName": "NetDaemon V6 (.NET 10) CPU percent", + "cSharpName": "NetdaemonV6Net10CpuPercent" + }, + { + "id": "sensor.netdaemon_v6_net_10_memory_percent", + "friendlyName": "NetDaemon V6 (.NET 10) Memory percent", + "cSharpName": "NetdaemonV6Net10MemoryPercent" + }, + { + "id": "sensor.nord_pool_lt_current_price", + "friendlyName": "Nord Pool LT Current price", + "cSharpName": "NordPoolLtCurrentPrice" + }, + { + "id": "sensor.nord_pool_lt_daily_average", + "friendlyName": "Nord Pool LT Daily average", + "cSharpName": "NordPoolLtDailyAverage" + }, + { + "id": "sensor.nord_pool_lt_highest_price", + "friendlyName": "Nord Pool LT Highest price", + "cSharpName": "NordPoolLtHighestPrice" + }, + { + "id": "sensor.nord_pool_lt_lowest_price", + "friendlyName": "Nord Pool LT Lowest price", + "cSharpName": "NordPoolLtLowestPrice" + }, + { + "id": "sensor.nordpool_current_price", + "friendlyName": "NordPool NordPool current price", + "cSharpName": "NordpoolCurrentPrice" + }, + { + "id": "sensor.nordpool_price", + "friendlyName": "Nordpool price", + "cSharpName": "NordpoolPrice" + }, + { + "id": "sensor.system_monitor_disk_free", + "friendlyName": "System Monitor Disk free /", + "cSharpName": "SystemMonitorDiskFree" + }, + { + "id": "sensor.system_monitor_disk_usage", + "friendlyName": "System Monitor Disk usage /", + "cSharpName": "SystemMonitorDiskUsage" + }, + { + "id": "sensor.system_monitor_disk_use", + "friendlyName": "System Monitor Disk use /", + "cSharpName": "SystemMonitorDiskUse" + }, + { + "id": "sensor.system_monitor_memory_usage", + "friendlyName": "System Monitor Memory usage", + "cSharpName": "SystemMonitorMemoryUsage" + }, + { + "id": "sensor.system_monitor_network_in_end0", + "friendlyName": "System Monitor Network in end0", + "cSharpName": "SystemMonitorNetworkInEnd0" + }, + { + "id": "sensor.system_monitor_network_throughput_in_end0", + "friendlyName": "System Monitor Network throughput in end0", + "cSharpName": "SystemMonitorNetworkThroughputInEnd0" + }, + { + "id": "sensor.system_monitor_processor_temperature", + "friendlyName": "System Monitor Processor temperature", + "cSharpName": "SystemMonitorProcessorTemperature" + }, + { + "id": "sensor.system_monitor_processor_use", + "friendlyName": "System Monitor Processor use", + "cSharpName": "SystemMonitorProcessorUse" + }, + { + "id": "sensor.system_monitor_swap_usage", + "friendlyName": "System Monitor Swap usage", + "cSharpName": "SystemMonitorSwapUsage" + }, + { + "id": "sensor.sm_s936b_battery_level", + "friendlyName": "Marius Phone Battery level", + "cSharpName": "SmS936bBatteryLevel" + }, + { + "id": "sensor.sm_s936b_battery_power", + "friendlyName": "Marius Phone Battery power", + "cSharpName": "SmS936bBatteryPower" + }, + { + "id": "sensor.sm_s936b_battery_temperature", + "friendlyName": "Marius Phone Battery temperature", + "cSharpName": "SmS936bBatteryTemperature" + }, + { + "id": "sensor.sm_s936b_light_sensor", + "friendlyName": "Marius Phone Light sensor", + "cSharpName": "SmS936bLightSensor" + }, + { + "id": "sensor.sm_s936b_pressure_sensor", + "friendlyName": "Marius Phone Pressure sensor", + "cSharpName": "SmS936bPressureSensor" + }, + { + "id": "sensor.sm_s936b_remaining_charge_time", + "friendlyName": "Marius Phone Remaining charge time", + "cSharpName": "SmS936bRemainingChargeTime" + }, + { + "id": "sensor.sm_s936b_signal_strength_sim_1", + "friendlyName": "Marius Phone Signal strength (SIM 1)", + "cSharpName": "SmS936bSignalStrengthSim1" + }, + { + "id": "sensor.sm_s936b_sleep_confidence", + "friendlyName": "Marius Phone Sleep confidence", + "cSharpName": "SmS936bSleepConfidence" + }, + { + "id": "sensor.sm_s936b_sleep_segment", + "friendlyName": "Marius Phone Sleep segment", + "cSharpName": "SmS936bSleepSegment" + }, + { + "id": "sensor.sm_s936b_steps_sensor", + "friendlyName": "Marius Phone Steps sensor", + "cSharpName": "SmS936bStepsSensor" + }, + { + "id": "sensor.sonoff_10018909cb_power", + "friendlyName": "Induction Power", + "cSharpName": "Sonoff10018909cbPower" + }, + { + "id": "sensor.sonoff_10018909cb_voltage", + "friendlyName": "Induction Voltage", + "cSharpName": "Sonoff10018909cbVoltage" + }, + { + "id": "sensor.sonoff_100215c534_energy_day_supply", + "friendlyName": "AC Energy Day Supply", + "cSharpName": "Sonoff100215c534EnergyDaySupply" + }, + { + "id": "sensor.sonoff_100215c534_energy_month_supply", + "friendlyName": "AC Energy Month Supply", + "cSharpName": "Sonoff100215c534EnergyMonthSupply" + }, + { + "id": "sensor.sonoff_100215c534_power", + "friendlyName": "AC Power", + "cSharpName": "Sonoff100215c534Power" + }, + { + "id": "sensor.sonoff_100215c534_power_supply", + "friendlyName": "AC Power Supply", + "cSharpName": "Sonoff100215c534PowerSupply" + }, + { + "id": "sensor.sonoff_100215c534_voltage", + "friendlyName": "AC Voltage", + "cSharpName": "Sonoff100215c534Voltage" + }, + { + "id": "sensor.sonoff_100222f7be_energy_day_supply", + "friendlyName": "Lamp Energy Day Supply", + "cSharpName": "Sonoff100222f7beEnergyDaySupply" + }, + { + "id": "sensor.sonoff_100222f7be_energy_month_supply", + "friendlyName": "Lamp Energy Month Supply", + "cSharpName": "Sonoff100222f7beEnergyMonthSupply" + }, + { + "id": "sensor.sonoff_100222f7be_power", + "friendlyName": "Lamp Power", + "cSharpName": "Sonoff100222f7bePower" + }, + { + "id": "sensor.sonoff_100222f7be_power_supply", + "friendlyName": "Lamp Power Supply", + "cSharpName": "Sonoff100222f7bePowerSupply" + }, + { + "id": "sensor.sonoff_100222ff36_energy_day_supply", + "friendlyName": "Christmas tree Energy Day Supply", + "cSharpName": "Sonoff100222ff36EnergyDaySupply" + }, + { + "id": "sensor.sonoff_100222ff36_energy_month_supply", + "friendlyName": "Christmas tree Energy Month Supply", + "cSharpName": "Sonoff100222ff36EnergyMonthSupply" + }, + { + "id": "sensor.sonoff_100222ff36_power", + "friendlyName": "Christmas tree Power", + "cSharpName": "Sonoff100222ff36Power" + }, + { + "id": "sensor.sonoff_100222ff36_power_supply", + "friendlyName": "Christmas tree Power Supply", + "cSharpName": "Sonoff100222ff36PowerSupply" + }, + { + "id": "sensor.sonoff_100222ff36_voltage", + "friendlyName": "Christmas tree Voltage", + "cSharpName": "Sonoff100222ff36Voltage" + }, + { + "id": "sensor.sonoff_100222ff63_energy_day_supply", + "friendlyName": "Stair lamps Energy Day Supply", + "cSharpName": "Sonoff100222ff63EnergyDaySupply" + }, + { + "id": "sensor.sonoff_100222ff63_energy_month_supply", + "friendlyName": "Stair lamps Energy Month Supply", + "cSharpName": "Sonoff100222ff63EnergyMonthSupply" + }, + { + "id": "sensor.sonoff_100222ff63_power", + "friendlyName": "Stair lamps Power", + "cSharpName": "Sonoff100222ff63Power" + }, + { + "id": "sensor.sonoff_100222ff63_power_supply", + "friendlyName": "Stair lamps Power Supply", + "cSharpName": "Sonoff100222ff63PowerSupply" + }, + { + "id": "sensor.sonoff_1002230a48_energy_day_supply", + "friendlyName": "Po laiptais Energy Day Supply", + "cSharpName": "Sonoff1002230a48EnergyDaySupply" + }, + { + "id": "sensor.sonoff_1002230a48_energy_month_supply", + "friendlyName": "Po laiptais Energy Month Supply", + "cSharpName": "Sonoff1002230a48EnergyMonthSupply" + }, + { + "id": "sensor.sonoff_1002230a48_power", + "friendlyName": "Po laiptais Power", + "cSharpName": "Sonoff1002230a48Power" + }, + { + "id": "sensor.sonoff_1002230a48_power_supply", + "friendlyName": "Po laiptais Power Supply", + "cSharpName": "Sonoff1002230a48PowerSupply" + }, + { + "id": "sensor.sonoff_1002230a48_voltage", + "friendlyName": "Po laiptais Voltage", + "cSharpName": "Sonoff1002230a48Voltage" + }, + { + "id": "sensor.sonoff_1002230e32_energy_day_supply", + "friendlyName": "Boiler Energy Day Supply", + "cSharpName": "Sonoff1002230e32EnergyDaySupply" + }, + { + "id": "sensor.sonoff_1002230e32_energy_month_supply", + "friendlyName": "Boiler Energy Month Supply", + "cSharpName": "Sonoff1002230e32EnergyMonthSupply" + }, + { + "id": "sensor.sonoff_1002230e32_power", + "friendlyName": "Boiler Power", + "cSharpName": "Sonoff1002230e32Power" + }, + { + "id": "sensor.sonoff_1002230e32_power_supply", + "friendlyName": "Boiler Power Supply", + "cSharpName": "Sonoff1002230e32PowerSupply" + }, + { + "id": "sensor.sonoff_1002230e32_voltage", + "friendlyName": "Boiler Voltage", + "cSharpName": "Sonoff1002230e32Voltage" + }, + { + "id": "sensor.sonoff_100255ead8_energy_day_supply", + "friendlyName": "Washer Energy Day Supply", + "cSharpName": "Sonoff100255ead8EnergyDaySupply" + }, + { + "id": "sensor.sonoff_100255ead8_energy_month_supply", + "friendlyName": "Washer Energy Month Supply", + "cSharpName": "Sonoff100255ead8EnergyMonthSupply" + }, + { + "id": "sensor.sonoff_100255ead8_power", + "friendlyName": "Washer Power", + "cSharpName": "Sonoff100255ead8Power" + }, + { + "id": "sensor.sonoff_100255ead8_power_supply", + "friendlyName": "Washer Power Supply", + "cSharpName": "Sonoff100255ead8PowerSupply" + }, + { + "id": "sensor.sonoff_100255ead8_voltage", + "friendlyName": "Washer Voltage", + "cSharpName": "Sonoff100255ead8Voltage" + }, + { + "id": "sensor.sonoff_100255f06c_energy_day_supply", + "friendlyName": "Dryer Energy Day Supply", + "cSharpName": "Sonoff100255f06cEnergyDaySupply" + }, + { + "id": "sensor.sonoff_100255f06c_energy_month_supply", + "friendlyName": "Dryer Energy Month Supply", + "cSharpName": "Sonoff100255f06cEnergyMonthSupply" + }, + { + "id": "sensor.sonoff_100255f06c_power", + "friendlyName": "Dryer Power", + "cSharpName": "Sonoff100255f06cPower" + }, + { + "id": "sensor.sonoff_100255f06c_power_supply", + "friendlyName": "Dryer Power Supply", + "cSharpName": "Sonoff100255f06cPowerSupply" + }, + { + "id": "sensor.sonoff_100255f06c_voltage", + "friendlyName": "Dryer Voltage", + "cSharpName": "Sonoff100255f06cVoltage" + }, + { + "id": "sensor.sonoff_100255f738_energy_day_supply", + "friendlyName": "Cat Christmas lamps Energy Day Supply", + "cSharpName": "Sonoff100255f738EnergyDaySupply" + }, + { + "id": "sensor.sonoff_100255f738_energy_month_supply", + "friendlyName": "Cat Christmas lamps Energy Month Supply", + "cSharpName": "Sonoff100255f738EnergyMonthSupply" + }, + { + "id": "sensor.sonoff_100255f738_power", + "friendlyName": "Cat Christmas lamps Power", + "cSharpName": "Sonoff100255f738Power" + }, + { + "id": "sensor.sonoff_100255f738_power_supply", + "friendlyName": "Cat Christmas lamps Power Supply", + "cSharpName": "Sonoff100255f738PowerSupply" + }, + { + "id": "sensor.sonoff_10025606e6_energy_day_supply", + "friendlyName": "Dehumidifier Energy Day Supply", + "cSharpName": "Sonoff10025606e6EnergyDaySupply" + }, + { + "id": "sensor.sonoff_10025606e6_energy_month_supply", + "friendlyName": "Dehumidifier Energy Month Supply", + "cSharpName": "Sonoff10025606e6EnergyMonthSupply" + }, + { + "id": "sensor.sonoff_10025606e6_power", + "friendlyName": "Dehumidifier Power", + "cSharpName": "Sonoff10025606e6Power" + }, + { + "id": "sensor.sonoff_10025606e6_power_supply", + "friendlyName": "Dehumidifier Power Supply", + "cSharpName": "Sonoff10025606e6PowerSupply" + }, + { + "id": "sensor.sonoff_10025606e6_voltage", + "friendlyName": "Dehumidifier Voltage", + "cSharpName": "Sonoff10025606e6Voltage" + }, + { + "id": "sensor.sonoff_10025609ce_energy_day_supply", + "friendlyName": "Salt Lamp Energy Day Supply", + "cSharpName": "Sonoff10025609ceEnergyDaySupply" + }, + { + "id": "sensor.sonoff_10025609ce_energy_month_supply", + "friendlyName": "Salt Lamp Energy Month Supply", + "cSharpName": "Sonoff10025609ceEnergyMonthSupply" + }, + { + "id": "sensor.sonoff_10025609ce_power", + "friendlyName": "Salt Lamp Power", + "cSharpName": "Sonoff10025609cePower" + }, + { + "id": "sensor.sonoff_10025609ce_power_supply", + "friendlyName": "Salt Lamp Power Supply", + "cSharpName": "Sonoff10025609cePowerSupply" + }, + { + "id": "sensor.sonoff_10025609ce_voltage", + "friendlyName": "Salt Lamp Voltage", + "cSharpName": "Sonoff10025609ceVoltage" + }, + { + "id": "sensor.sonoff_100267d63f_current", + "friendlyName": "Home meter Current", + "cSharpName": "Sonoff100267d63fCurrent" + }, + { + "id": "sensor.sonoff_100267d63f_energy", + "friendlyName": "Home meter Energy", + "cSharpName": "Sonoff100267d63fEnergy" + }, + { + "id": "sensor.sonoff_100267d63f_energy_day", + "friendlyName": "Home meter Energy Day", + "cSharpName": "Sonoff100267d63fEnergyDay" + }, + { + "id": "sensor.sonoff_100267d63f_energy_day_supply", + "friendlyName": "Home meter Energy Day Supply", + "cSharpName": "Sonoff100267d63fEnergyDaySupply" + }, + { + "id": "sensor.sonoff_100267d63f_energy_month", + "friendlyName": "Home meter Energy Month", + "cSharpName": "Sonoff100267d63fEnergyMonth" + }, + { + "id": "sensor.sonoff_100267d63f_energy_month_supply", + "friendlyName": "Home meter Energy Month Supply", + "cSharpName": "Sonoff100267d63fEnergyMonthSupply" + }, + { + "id": "sensor.sonoff_100267d63f_power", + "friendlyName": "Total Home Power Usage", + "cSharpName": "Sonoff100267d63fPower" + }, + { + "id": "sensor.sonoff_100267d63f_power_supply", + "friendlyName": "Home meter Power Supply", + "cSharpName": "Sonoff100267d63fPowerSupply" + }, + { + "id": "sensor.sonoff_100267d63f_voltage", + "friendlyName": "Home meter Voltage", + "cSharpName": "Sonoff100267d63fVoltage" + }, + { + "id": "sensor.sonoff_a4800f07b4_battery", + "friendlyName": "Outside Battery", + "cSharpName": "SonoffA4800f07b4Battery" + }, + { + "id": "sensor.sonoff_a4800f07b4_humidity", + "friendlyName": "Outside Humidity", + "cSharpName": "SonoffA4800f07b4Humidity" + }, + { + "id": "sensor.sonoff_a4800f07b4_temperature", + "friendlyName": "Outside Temperature", + "cSharpName": "SonoffA4800f07b4Temperature" + }, + { + "id": "sensor.sonoff_s60zbtpf_power", + "friendlyName": "LED power Power", + "cSharpName": "SonoffS60zbtpfPower" + }, + { + "id": "sensor.sonoff_s60zbtpf_power_2", + "friendlyName": "Air Purifirier Power", + "cSharpName": "SonoffS60zbtpfPower2" + }, + { + "id": "sensor.sonoff_s60zbtpf_voltage", + "friendlyName": "LED power Voltage", + "cSharpName": "SonoffS60zbtpfVoltage" + }, + { + "id": "sensor.sonoff_s60zbtpf_voltage_2", + "friendlyName": "Air Purifirier Voltage", + "cSharpName": "SonoffS60zbtpfVoltage2" + }, + { + "id": "sensor.temp_power", + "friendlyName": "Network Infra Power", + "cSharpName": "TempPower" + }, + { + "id": "sensor.temp_voltage", + "friendlyName": "Network Infra Voltage", + "cSharpName": "TempVoltage" + }, + { + "id": "sensor.total_kwh", + "friendlyName": "Total KWH", + "cSharpName": "TotalKwh" + }, + { + "id": "sensor.total_power", + "friendlyName": "Total sensors", + "cSharpName": "TotalPower" + }, + { + "id": "sensor.tv_power", + "friendlyName": "TV Power", + "cSharpName": "TvPower" + }, + { + "id": "sensor.tv_voltage", + "friendlyName": "TV Voltage", + "cSharpName": "TvVoltage" + }, + { + "id": "sensor.washing_room_battery", + "friendlyName": "Washing room Battery", + "cSharpName": "WashingRoomBattery" + }, + { + "id": "sensor.washing_room_humidity", + "friendlyName": "Washing room Humidity", + "cSharpName": "WashingRoomHumidity" + }, + { + "id": "sensor.washing_room_temperature", + "friendlyName": "Washing room Temperature", + "cSharpName": "WashingRoomTemperature" + }, + { + "id": "sensor.wellbeing_air_purifier_2_eco2", + "friendlyName": "eCO2", + "cSharpName": "WellbeingAirPurifier2Eco2" + }, + { + "id": "sensor.wellbeing_air_purifier_2_filterlife", + "friendlyName": "Fresh 360 filter Life", + "cSharpName": "WellbeingAirPurifier2Filterlife" + }, + { + "id": "sensor.wellbeing_air_purifier_2_humidity", + "friendlyName": "Humidity", + "cSharpName": "WellbeingAirPurifier2Humidity" + }, + { + "id": "sensor.wellbeing_air_purifier_2_pm1", + "friendlyName": "PM1", + "cSharpName": "WellbeingAirPurifier2Pm1" + }, + { + "id": "sensor.wellbeing_air_purifier_2_pm10", + "friendlyName": "PM10", + "cSharpName": "WellbeingAirPurifier2Pm10" + }, + { + "id": "sensor.wellbeing_air_purifier_2_pm2_5", + "friendlyName": "PM2.5", + "cSharpName": "WellbeingAirPurifier2Pm25" + }, + { + "id": "sensor.wellbeing_air_purifier_2_temp", + "friendlyName": "Temperature", + "cSharpName": "WellbeingAirPurifier2Temp" + }, + { + "id": "sensor.wellbeing_air_purifier_2_tvoc", + "friendlyName": "TVOC", + "cSharpName": "WellbeingAirPurifier2Tvoc" + }, + { + "id": "sensor.wellbeing_air_purifier_2_workmode", + "friendlyName": "Mode", + "cSharpName": "WellbeingAirPurifier2Workmode" + } + ], + "attributes": [ + { + "jsonName": "state_class", + "cSharpName": "StateClass", + "clrType": "System.String" + }, + { + "jsonName": "unit_of_measurement", + "cSharpName": "UnitOfMeasurement", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "device_class", + "cSharpName": "DeviceClass", + "clrType": "System.String" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + }, + { + "jsonName": "raw_state", + "cSharpName": "RawState", + "clrType": "System.Double" + }, + { + "jsonName": "light", + "cSharpName": "Light", + "clrType": "System.Double" + }, + { + "jsonName": "motion", + "cSharpName": "Motion", + "clrType": "System.Double" + }, + { + "jsonName": "timestamp", + "cSharpName": "Timestamp", + "clrType": "System.Double" + }, + { + "jsonName": "end", + "cSharpName": "End", + "clrType": "System.Object" + }, + { + "jsonName": "start", + "cSharpName": "Start", + "clrType": "System.Object" + }, + { + "jsonName": "status", + "cSharpName": "Status", + "clrType": "System.String" + }, + { + "jsonName": "current", + "cSharpName": "Current", + "clrType": "System.Double" + }, + { + "jsonName": "voltage", + "cSharpName": "Voltage", + "clrType": "System.Double" + }, + { + "jsonName": "asu", + "cSharpName": "Asu", + "clrType": "System.Double" + }, + { + "jsonName": "quality", + "cSharpName": "Quality", + "clrType": "System.String" + }, + { + "jsonName": "accuracy", + "cSharpName": "Accuracy", + "clrType": "System.String" + }, + { + "jsonName": "entity_id", + "cSharpName": "EntityId", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "attribution", + "cSharpName": "Attribution", + "clrType": "System.String" + }, + { + "jsonName": "source", + "cSharpName": "Source", + "clrType": "System.String" + }, + { + "jsonName": "integration", + "cSharpName": "Integration", + "clrType": "System.String" + }, + { + "jsonName": "capabilities", + "cSharpName": "Capabilities", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "last_updated", + "cSharpName": "LastUpdated", + "clrType": "System.String" + }, + { + "jsonName": "last_api_fetch", + "cSharpName": "LastApiFetch", + "clrType": "System.String" + }, + { + "jsonName": "using_cached_data", + "cSharpName": "UsingCachedData", + "clrType": "System.Boolean" + }, + { + "jsonName": "current_quarter_index", + "cSharpName": "CurrentQuarterIndex", + "clrType": "System.Double" + }, + { + "jsonName": "formatted", + "cSharpName": "Formatted", + "clrType": "System.String" + }, + { + "jsonName": "budget_hours", + "cSharpName": "BudgetHours", + "clrType": "System.Double" + }, + { + "jsonName": "measurement_type", + "cSharpName": "MeasurementType", + "clrType": "System.String" + }, + { + "jsonName": "battery_voltage", + "cSharpName": "BatteryVoltage", + "clrType": "System.Double" + }, + { + "jsonName": "restored", + "cSharpName": "Restored", + "clrType": "System.Boolean" + }, + { + "jsonName": "supported_features", + "cSharpName": "SupportedFeatures", + "clrType": "System.Double" + } + ] + }, + { + "domain": "sun", + "entities": [ + { + "id": "sun.sun", + "friendlyName": "Sun", + "cSharpName": "Sun" + } + ], + "attributes": [ + { + "jsonName": "next_dawn", + "cSharpName": "NextDawn", + "clrType": "System.String" + }, + { + "jsonName": "next_dusk", + "cSharpName": "NextDusk", + "clrType": "System.String" + }, + { + "jsonName": "next_midnight", + "cSharpName": "NextMidnight", + "clrType": "System.String" + }, + { + "jsonName": "next_noon", + "cSharpName": "NextNoon", + "clrType": "System.String" + }, + { + "jsonName": "next_rising", + "cSharpName": "NextRising", + "clrType": "System.String" + }, + { + "jsonName": "next_setting", + "cSharpName": "NextSetting", + "clrType": "System.String" + }, + { + "jsonName": "elevation", + "cSharpName": "Elevation", + "clrType": "System.Double" + }, + { + "jsonName": "azimuth", + "cSharpName": "Azimuth", + "clrType": "System.Double" + }, + { + "jsonName": "rising", + "cSharpName": "Rising", + "clrType": "System.Boolean" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "switch", + "entities": [ + { + "id": "switch.ac_on_off", + "friendlyName": "AC On/Off", + "cSharpName": "AcOnOff" + }, + { + "id": "switch.akvariumas", + "friendlyName": "Akvariumas", + "cSharpName": "Akvariumas" + }, + { + "id": "switch.balkony_laps", + "friendlyName": "3D print", + "cSharpName": "BalkonyLaps" + }, + { + "id": "switch.boilermonitor_budget_override", + "friendlyName": "Boiler Monitor Override budget enforcement", + "cSharpName": "BoilermonitorBudgetOverride" + }, + { + "id": "switch.boilermonitor_skip_price_cap", + "friendlyName": "Boiler Monitor Skip price cap, heat until ready", + "cSharpName": "BoilermonitorSkipPriceCap" + }, + { + "id": "switch.dishwasher", + "friendlyName": "Dishwasher", + "cSharpName": "Dishwasher" + }, + { + "id": "switch.exhaust_fan", + "friendlyName": "Exhaust Fan", + "cSharpName": "ExhaustFan" + }, + { + "id": "switch.fridge", + "friendlyName": "Fridge", + "cSharpName": "Fridge" + }, + { + "id": "switch.heating", + "friendlyName": "Heating Relay Far", + "cSharpName": "Heating" + }, + { + "id": "switch.heating_2", + "friendlyName": "Heating Relay Bathroom", + "cSharpName": "Heating2" + }, + { + "id": "switch.heating_3", + "friendlyName": "Heating Relay Middle", + "cSharpName": "Heating3" + }, + { + "id": "switch.nordpool_boiler_skip_price_cap", + "friendlyName": "Skip price cap, heat until ready", + "cSharpName": "NordpoolBoilerSkipPriceCap" + }, + { + "id": "switch.sonoff_10018909cb", + "friendlyName": "Induction", + "cSharpName": "Sonoff10018909cb" + }, + { + "id": "switch.sonoff_100215c534", + "friendlyName": "AC", + "cSharpName": "Sonoff100215c534" + }, + { + "id": "switch.sonoff_100222f7be", + "friendlyName": "Plant Lamp", + "cSharpName": "Sonoff100222f7be" + }, + { + "id": "switch.sonoff_100222ff36", + "friendlyName": "Christmas tree", + "cSharpName": "Sonoff100222ff36" + }, + { + "id": "switch.sonoff_100222ff63", + "friendlyName": "Stair lamps", + "cSharpName": "Sonoff100222ff63" + }, + { + "id": "switch.sonoff_1002230a48", + "friendlyName": "Po laiptais", + "cSharpName": "Sonoff1002230a48" + }, + { + "id": "switch.sonoff_1002230e32", + "friendlyName": "Boiler", + "cSharpName": "Sonoff1002230e32" + }, + { + "id": "switch.sonoff_100255ead8", + "friendlyName": "Washer", + "cSharpName": "Sonoff100255ead8" + }, + { + "id": "switch.sonoff_100255f06c", + "friendlyName": "Dryer", + "cSharpName": "Sonoff100255f06c" + }, + { + "id": "switch.sonoff_100255f738", + "friendlyName": "Cat Christmas lamps", + "cSharpName": "Sonoff100255f738" + }, + { + "id": "switch.sonoff_10025606e6", + "friendlyName": "Dehumidifier", + "cSharpName": "Sonoff10025606e6" + }, + { + "id": "switch.sonoff_10025609ce", + "friendlyName": "Salt Lamp", + "cSharpName": "Sonoff10025609ce" + }, + { + "id": "switch.sonoff_s60zbtpf", + "friendlyName": "LED power", + "cSharpName": "SonoffS60zbtpf" + }, + { + "id": "switch.sonoff_s60zbtpf_2", + "friendlyName": "Air Purifirier", + "cSharpName": "SonoffS60zbtpf2" + }, + { + "id": "switch.temp", + "friendlyName": "Network Infra", + "cSharpName": "Temp" + }, + { + "id": "switch.tv", + "friendlyName": "TV", + "cSharpName": "Tv" + }, + { + "id": "switch.wellbeing_air_purifier_2_ionizer", + "friendlyName": "Ionizer", + "cSharpName": "WellbeingAirPurifier2Ionizer" + }, + { + "id": "switch.wellbeing_air_purifier_2_safetylock", + "friendlyName": "Safety Lock", + "cSharpName": "WellbeingAirPurifier2Safetylock" + }, + { + "id": "switch.wellbeing_air_purifier_2_uilight", + "friendlyName": "UI Light", + "cSharpName": "WellbeingAirPurifier2Uilight" + } + ], + "attributes": [ + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "current", + "cSharpName": "Current", + "clrType": "System.Boolean" + }, + { + "jsonName": "raw_state", + "cSharpName": "RawState", + "clrType": "System.Boolean" + }, + { + "jsonName": "integration", + "cSharpName": "Integration", + "clrType": "System.String" + }, + { + "jsonName": "capabilities", + "cSharpName": "Capabilities", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "device_class", + "cSharpName": "DeviceClass", + "clrType": "System.String" + }, + { + "jsonName": "assumed_state", + "cSharpName": "AssumedState", + "clrType": "System.Boolean" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + } + ] + }, + { + "domain": "text", + "entities": [ + { + "id": "text.boilermonitor_config_power_entity_id", + "friendlyName": "Boiler Monitor Boiler power entity ID", + "cSharpName": "BoilermonitorConfigPowerEntityId" + }, + { + "id": "text.boilermonitor_config_switch_entity_id", + "friendlyName": "Boiler Monitor Boiler switch entity ID", + "cSharpName": "BoilermonitorConfigSwitchEntityId" + } + ], + "attributes": [ + { + "jsonName": "mode", + "cSharpName": "Mode", + "clrType": "System.String" + }, + { + "jsonName": "min", + "cSharpName": "Min", + "clrType": "System.Double" + }, + { + "jsonName": "max", + "cSharpName": "Max", + "clrType": "System.Double" + }, + { + "jsonName": "pattern", + "cSharpName": "Pattern", + "clrType": null + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "tts", + "entities": [ + { + "id": "tts.google_translate_en_com", + "friendlyName": "Google Translate en com", + "cSharpName": "GoogleTranslateEnCom" + } + ], + "attributes": [ + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + }, + { + "domain": "update", + "entities": [ + { + "id": "update.advanced_ssh_web_terminal_update", + "friendlyName": "Advanced SSH \u0026 Web Terminal Update", + "cSharpName": "AdvancedSshWebTerminalUpdate" + }, + { + "id": "update.akvariumas_firmware", + "friendlyName": "Akvariumas Firmware", + "cSharpName": "AkvariumasFirmware" + }, + { + "id": "update.apexcharts_card_update", + "friendlyName": "apexcharts-card update", + "cSharpName": "ApexchartsCardUpdate" + }, + { + "id": "update.aquarium_leak_sensor_firmware", + "friendlyName": "Aquarium leak sensor Firmware", + "cSharpName": "AquariumLeakSensorFirmware" + }, + { + "id": "update.balkony_laps_firmware", + "friendlyName": "3D print Firmware", + "cSharpName": "BalkonyLapsFirmware" + }, + { + "id": "update.bathroom_firmware", + "friendlyName": "Bathroom Firmware", + "cSharpName": "BathroomFirmware" + }, + { + "id": "update.bedroom_firmware", + "friendlyName": "Bedroom Firmware", + "cSharpName": "BedroomFirmware" + }, + { + "id": "update.boiler_moisture_firmware", + "friendlyName": "Boiler Moisture Firmware", + "cSharpName": "BoilerMoistureFirmware" + }, + { + "id": "update.boiler_temp_firmware", + "friendlyName": "Boiler room Temp Firmware", + "cSharpName": "BoilerTempFirmware" + }, + { + "id": "update.cat_area_temp_firmware", + "friendlyName": "Cat Area Temp Firmware", + "cSharpName": "CatAreaTempFirmware" + }, + { + "id": "update.dishwasher_firmware", + "friendlyName": "Dishwasher Firmware", + "cSharpName": "DishwasherFirmware" + }, + { + "id": "update.electrolux_wellbeing_update", + "friendlyName": "Electrolux Wellbeing update", + "cSharpName": "ElectroluxWellbeingUpdate" + }, + { + "id": "update.exhaust_fan_firmware", + "friendlyName": "Exhaust Fan Firmware", + "cSharpName": "ExhaustFanFirmware" + }, + { + "id": "update.fridge_firmware", + "friendlyName": "Fridge Firmware", + "cSharpName": "FridgeFirmware" + }, + { + "id": "update.get_hacs_update", + "friendlyName": "Get HACS Update", + "cSharpName": "GetHacsUpdate" + }, + { + "id": "update.hacs_update", + "friendlyName": "HACS update", + "cSharpName": "HacsUpdate" + }, + { + "id": "update.heating_firmware", + "friendlyName": "Heating Relay Far Firmware", + "cSharpName": "HeatingFirmware" + }, + { + "id": "update.heating_firmware_2", + "friendlyName": "Heating Relay Bathroom Firmware", + "cSharpName": "HeatingFirmware2" + }, + { + "id": "update.heating_firmware_3", + "friendlyName": "Heating Relay Middle Firmware", + "cSharpName": "HeatingFirmware3" + }, + { + "id": "update.home_assistant_core_update", + "friendlyName": "Home Assistant Core Update", + "cSharpName": "HomeAssistantCoreUpdate" + }, + { + "id": "update.home_assistant_operating_system_update", + "friendlyName": "Home Assistant Operating System Update", + "cSharpName": "HomeAssistantOperatingSystemUpdate" + }, + { + "id": "update.home_assistant_supervisor_update", + "friendlyName": "Home Assistant Supervisor Update", + "cSharpName": "HomeAssistantSupervisorUpdate" + }, + { + "id": "update.let_s_encrypt_update", + "friendlyName": "Let\u0027s Encrypt Update", + "cSharpName": "LetSEncryptUpdate" + }, + { + "id": "update.local_tuya_update", + "friendlyName": "Local Tuya update", + "cSharpName": "LocalTuyaUpdate" + }, + { + "id": "update.main_home_firmware", + "friendlyName": "Main Home Firmware", + "cSharpName": "MainHomeFirmware" + }, + { + "id": "update.mini_graph_card_update", + "friendlyName": "mini-graph-card update", + "cSharpName": "MiniGraphCardUpdate" + }, + { + "id": "update.modern_circular_gauge_update", + "friendlyName": "Modern Circular Gauge update", + "cSharpName": "ModernCircularGaugeUpdate" + }, + { + "id": "update.mosquitto_broker_update", + "friendlyName": "Mosquitto broker Update", + "cSharpName": "MosquittoBrokerUpdate" + }, + { + "id": "update.netdaemon_v6_net_10_update", + "friendlyName": "NetDaemon V6 (.NET 10) Update", + "cSharpName": "NetdaemonV6Net10Update" + }, + { + "id": "update.nginx_proxy_manager_update", + "friendlyName": "Nginx Proxy Manager Update", + "cSharpName": "NginxProxyManagerUpdate" + }, + { + "id": "update.samba_share_update", + "friendlyName": "Samba share Update", + "cSharpName": "SambaShareUpdate" + }, + { + "id": "update.sonoff_lan_update", + "friendlyName": "Sonoff LAN update", + "cSharpName": "SonoffLanUpdate" + }, + { + "id": "update.sonoff_s60zbtpf_firmware", + "friendlyName": "LED power Firmware", + "cSharpName": "SonoffS60zbtpfFirmware" + }, + { + "id": "update.sonoff_s60zbtpf_firmware_2", + "friendlyName": "Air Purifirier Firmware", + "cSharpName": "SonoffS60zbtpfFirmware2" + }, + { + "id": "update.spook_your_homie_update", + "friendlyName": "Spook \uD83D\uDC7B Your homie update", + "cSharpName": "SpookYourHomieUpdate" + }, + { + "id": "update.studio_code_server_update", + "friendlyName": "Studio Code Server Update", + "cSharpName": "StudioCodeServerUpdate" + }, + { + "id": "update.temp_firmware", + "friendlyName": "Network Infra Firmware", + "cSharpName": "TempFirmware" + }, + { + "id": "update.tibber_graph_update", + "friendlyName": "Tibber Graph update", + "cSharpName": "TibberGraphUpdate" + }, + { + "id": "update.tv_firmware", + "friendlyName": "TV Firmware", + "cSharpName": "TvFirmware" + }, + { + "id": "update.unifi_network_application_update", + "friendlyName": "UniFi Network Application Update", + "cSharpName": "UnifiNetworkApplicationUpdate" + }, + { + "id": "update.vaultwarden_bitwarden_update", + "friendlyName": "Vaultwarden Update", + "cSharpName": "VaultwardenBitwardenUpdate" + }, + { + "id": "update.washing_room_firmware", + "friendlyName": "Washing room Firmware", + "cSharpName": "WashingRoomFirmware" + }, + { + "id": "update.zha_toolkit_service_for_advanced_zigbee_usage_update", + "friendlyName": "\uD83E\uDDF0 ZHA Toolkit - Service for advanced Zigbee Usage update", + "cSharpName": "ZhaToolkitServiceForAdvancedZigbeeUsageUpdate" + } + ], + "attributes": [ + { + "jsonName": "auto_update", + "cSharpName": "AutoUpdate", + "clrType": "System.Boolean" + }, + { + "jsonName": "display_precision", + "cSharpName": "DisplayPrecision", + "clrType": "System.Double" + }, + { + "jsonName": "installed_version", + "cSharpName": "InstalledVersion", + "clrType": "System.String" + }, + { + "jsonName": "in_progress", + "cSharpName": "InProgress", + "clrType": "System.Boolean" + }, + { + "jsonName": "latest_version", + "cSharpName": "LatestVersion", + "clrType": "System.String" + }, + { + "jsonName": "release_summary", + "cSharpName": "ReleaseSummary", + "clrType": null + }, + { + "jsonName": "release_url", + "cSharpName": "ReleaseUrl", + "clrType": "System.String" + }, + { + "jsonName": "skipped_version", + "cSharpName": "SkippedVersion", + "clrType": null + }, + { + "jsonName": "title", + "cSharpName": "Title", + "clrType": "System.String" + }, + { + "jsonName": "update_percentage", + "cSharpName": "UpdatePercentage", + "clrType": null + }, + { + "jsonName": "entity_picture", + "cSharpName": "EntityPicture", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "supported_features", + "cSharpName": "SupportedFeatures", + "clrType": "System.Double" + }, + { + "jsonName": "device_class", + "cSharpName": "DeviceClass", + "clrType": "System.String" + } + ] + }, + { + "domain": "weather", + "entities": [ + { + "id": "weather.kaunas_zaliakalnis", + "friendlyName": "Kaunas (\u017Daliakalnis)", + "cSharpName": "KaunasZaliakalnis" + } + ], + "attributes": [ + { + "jsonName": "temperature", + "cSharpName": "Temperature", + "clrType": "System.Double" + }, + { + "jsonName": "apparent_temperature", + "cSharpName": "ApparentTemperature", + "clrType": "System.Double" + }, + { + "jsonName": "temperature_unit", + "cSharpName": "TemperatureUnit", + "clrType": "System.String" + }, + { + "jsonName": "humidity", + "cSharpName": "Humidity", + "clrType": "System.Double" + }, + { + "jsonName": "cloud_coverage", + "cSharpName": "CloudCoverage", + "clrType": "System.Double" + }, + { + "jsonName": "pressure", + "cSharpName": "Pressure", + "clrType": "System.Double" + }, + { + "jsonName": "pressure_unit", + "cSharpName": "PressureUnit", + "clrType": "System.String" + }, + { + "jsonName": "wind_bearing", + "cSharpName": "WindBearing", + "clrType": "System.Double" + }, + { + "jsonName": "wind_gust_speed", + "cSharpName": "WindGustSpeed", + "clrType": "System.Double" + }, + { + "jsonName": "wind_speed", + "cSharpName": "WindSpeed", + "clrType": "System.Double" + }, + { + "jsonName": "wind_speed_unit", + "cSharpName": "WindSpeedUnit", + "clrType": "System.String" + }, + { + "jsonName": "visibility_unit", + "cSharpName": "VisibilityUnit", + "clrType": "System.String" + }, + { + "jsonName": "precipitation_unit", + "cSharpName": "PrecipitationUnit", + "clrType": "System.String" + }, + { + "jsonName": "attribution", + "cSharpName": "Attribution", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + }, + { + "jsonName": "supported_features", + "cSharpName": "SupportedFeatures", + "clrType": "System.Double" + } + ] + }, + { + "domain": "zone", + "entities": [ + { + "id": "zone.home", + "friendlyName": "Home", + "cSharpName": "Home" + } + ], + "attributes": [ + { + "jsonName": "latitude", + "cSharpName": "Latitude", + "clrType": "System.Double" + }, + { + "jsonName": "longitude", + "cSharpName": "Longitude", + "clrType": "System.Double" + }, + { + "jsonName": "radius", + "cSharpName": "Radius", + "clrType": "System.Double" + }, + { + "jsonName": "passive", + "cSharpName": "Passive", + "clrType": "System.Boolean" + }, + { + "jsonName": "persons", + "cSharpName": "Persons", + "clrType": "System.Collections.Generic.IReadOnlyList\u00601[System.String]" + }, + { + "jsonName": "editable", + "cSharpName": "Editable", + "clrType": "System.Boolean" + }, + { + "jsonName": "icon", + "cSharpName": "Icon", + "clrType": "System.String" + }, + { + "jsonName": "friendly_name", + "cSharpName": "FriendlyName", + "clrType": "System.String" + } + ] + } + ] +} \ No newline at end of file diff --git a/HomeAssistant.Server/NetDaemonCodegen/ServicesMetaData.json b/HomeAssistant.Server/NetDaemonCodegen/ServicesMetaData.json new file mode 100644 index 0000000..64a5278 --- /dev/null +++ b/HomeAssistant.Server/NetDaemonCodegen/ServicesMetaData.json @@ -0,0 +1,12173 @@ +{ + "homeassistant": { + "save_persistent_states": { + "fields": {} + }, + "turn_off": { + "fields": {}, + "target": {} + }, + "turn_on": { + "fields": {}, + "target": {} + }, + "toggle": { + "fields": {}, + "target": {} + }, + "stop": { + "fields": {} + }, + "check_config": { + "fields": {} + }, + "update_entity": { + "fields": { + "entity_id": { + "required": true, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "reload_core_config": { + "fields": {} + }, + "set_location": { + "fields": { + "latitude": { + "required": true, + "example": 32.87336, + "selector": { + "number": { + "mode": "box", + "min": -90.0, + "max": 90.0, + "step": "any" + } + } + }, + "longitude": { + "required": true, + "example": 117.22743, + "selector": { + "number": { + "mode": "box", + "min": -180.0, + "max": 180.0, + "step": "any" + } + } + }, + "elevation": { + "required": false, + "example": 120, + "selector": { + "number": { + "mode": "box", + "step": "any" + } + } + } + } + }, + "reload_custom_templates": { + "fields": {} + }, + "reload_config_entry": { + "fields": { + "entry_id": { + "advanced": true, + "required": false, + "example": "8955375327824e14ba89e4b29cc3ec9a", + "selector": { + "config_entry": {} + } + } + }, + "target": {} + }, + "reload_all": { + "fields": {} + }, + "create_label": { + "name": "Create a label \uD83D\uDC7B", + "description": "Creates a new label on the fly.", + "fields": { + "name": { + "name": "Name", + "description": "The name of the label to create.", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "description": { + "name": "Description", + "description": "Description for the label.", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "icon": { + "name": "Icon", + "description": "Icon to use for the label.", + "required": false, + "selector": { + "icon": { + "placeholder": "mdi:tag" + } + } + }, + "color": { + "name": "Color", + "description": "Color to use for the label. Can be a color name from the list, or a hex color code (like #FF0000).", + "selector": { + "select": { + "options": [ + { + "label": "Primary theme color", + "value": "primary" + }, + { + "label": "Accent theme color", + "value": "accent" + }, + { + "label": "Disabled theme color", + "value": "disabled" + }, + { + "label": "Red", + "value": "red" + }, + { + "label": "Pink", + "value": "pink" + }, + { + "label": "Purple", + "value": "purple" + }, + { + "label": "Deep purple", + "value": "deep_purple" + }, + { + "label": "Indigo", + "value": "indigo" + }, + { + "label": "Blue", + "value": "blue" + }, + { + "label": "Light blue", + "value": "light_blue" + }, + { + "label": "Cyan", + "value": "cyan" + }, + { + "label": "Teal", + "value": "teal" + }, + { + "label": "Green", + "value": "green" + }, + { + "label": "Light green", + "value": "light_green" + }, + { + "label": "Lime", + "value": "lime" + }, + { + "label": "Yellow", + "value": "yellow" + }, + { + "label": "Orange", + "value": "orange" + }, + { + "label": "Deep orange", + "value": "deep_orange" + }, + { + "label": "Brown", + "value": "brown" + }, + { + "label": "Grey", + "value": "grey" + }, + { + "label": "Blue grey", + "value": "blue_grey" + }, + { + "label": "Black", + "value": "black" + }, + { + "label": "White", + "value": "white" + } + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + } + }, + "disable_entity": { + "name": "Disable an entity \uD83D\uDC7B", + "description": "Disables an entity (or entities) on the fly.", + "fields": { + "entity_id": { + "name": "Entity", + "description": "The entity/entities to disable.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "add_label_to_device": { + "name": "Add a label to a device \uD83D\uDC7B", + "description": "Adds a label to a device. If multiple labels or multiple devices are provided, all combinations will be added.", + "fields": { + "label_id": { + "name": "Label ID", + "description": "The ID(s) of the label(s) to add the device(s).", + "required": true, + "selector": { + "label": { + "multiple": true + } + } + }, + "device_id": { + "name": "Device ID", + "description": "The ID(s) of the device(s) to add the label(s) to.", + "required": true, + "selector": { + "device": { + "multiple": true + } + } + } + } + }, + "remove_label_from_area": { + "name": "Remove a label from an area \uD83D\uDC7B", + "description": "Removes a label to an area. If multiple labels or multiple areas are provided, all combinations will be removed.", + "fields": { + "label_id": { + "name": "Label ID", + "description": "The ID(s) of the label(s) to remove from the area(s).", + "required": true, + "selector": { + "label": { + "multiple": true + } + } + }, + "area_id": { + "name": "Area ID", + "description": "The ID(s) of the area(s) to remove the label(s) from.", + "required": true, + "selector": { + "area": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "set_area_aliases": { + "name": "Sets aliases for an area \uD83D\uDC7B", + "description": "Sets aliases for an area. Overwrite and removed any existing aliases, fully replacing them with the new ones.", + "fields": { + "area_id": { + "name": "Area ID", + "description": "The ID of the area to set the aliases for.", + "required": true, + "selector": { + "area": { + "multiple": false, + "reorder": false + } + } + }, + "aliases": { + "name": "Aliases", + "description": "The aliases to set for the area.", + "required": true, + "selector": { + "object": { + "multiple": false + } + } + } + } + }, + "set_floor_aliases": { + "name": "Sets aliases for a floor \uD83D\uDC7B", + "description": "Sets aliases for a floor. Overwrite and removed any existing aliases, fully replacing them with the new ones.", + "fields": { + "floor_id": { + "name": "Floor ID", + "description": "The ID of the floor to set the aliases for.", + "required": true, + "selector": { + "floor": { + "multiple": false + } + } + }, + "aliases": { + "name": "Aliases", + "description": "The aliases to set for the floor.", + "required": true, + "selector": { + "object": { + "multiple": false + } + } + } + } + }, + "add_area_to_floor": { + "name": "Add an area to a floor \uD83D\uDC7B", + "description": "Adds an area to a floor. Please note, if the area is already on a floor, it will be removed from the previous floor.", + "fields": { + "floor_id": { + "name": "Floor ID", + "description": "The ID of the floor to add the area on.", + "required": true, + "selector": { + "floor": { + "multiple": false + } + } + }, + "area_id": { + "name": "Area ID", + "description": "The ID of the area(s) to add to the floor.", + "required": true, + "selector": { + "area": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "remove_alias_from_floor": { + "name": "Remove an alias from a floor \uD83D\uDC7B", + "description": "Removes an alias from a floor.", + "fields": { + "floor_id": { + "name": "Floor ID", + "description": "The ID of the floor to remove the alias from.", + "required": true, + "selector": { + "floor": { + "multiple": false + } + } + }, + "alias": { + "name": "Alias", + "description": "The alias (or list of aliasses) to remove from the floor.", + "required": true, + "selector": { + "object": { + "multiple": false + } + } + } + } + }, + "add_entity_to_area": { + "name": "Add an entity to an area \uD83D\uDC7B", + "description": "Adds an entity to an area. Please note, if the enity is already in an area, it will be removed from the previous area. This will override the area the device, that provides this entity, is in.", + "fields": { + "area_id": { + "name": "Area ID", + "description": "The ID of the area to add the entity to.", + "required": true, + "selector": { + "area": { + "multiple": false, + "reorder": false + } + } + }, + "entity_id": { + "name": "Entity ID", + "description": "The ID of the entity (or entities) to add to the area.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "remove_entity_from_area": { + "name": "Remove an entity from an area \uD83D\uDC7B", + "description": "Removes an entity from an area. As an entity can only be in one area, this call doesn\u0027t need to specify the area. Please note, the entity will still be in the area of the device that provides it after this call.", + "fields": { + "entity_id": { + "name": "Entity ID", + "description": "The ID of the entity (or entities) to remove the area from.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "remove_device_from_area": { + "name": "Remove a device from an area \uD83D\uDC7B", + "description": "Removes a device from an area. As a device can only be in one area, this call doesn\u0027t need to specify the area.", + "fields": { + "device_id": { + "name": "Device ID", + "description": "The ID of the device to remove the area from.", + "required": true, + "selector": { + "device": { + "multiple": true + } + } + } + } + }, + "add_alias_to_floor": { + "name": "Add an alias to a floor \uD83D\uDC7B", + "description": "Adds an alias to a floor.", + "fields": { + "floor_id": { + "name": "Floor ID", + "description": "The ID of the floor to add the alias to.", + "required": true, + "selector": { + "floor": { + "multiple": false + } + } + }, + "alias": { + "name": "Alias", + "description": "The alias (or list of aliasses) to add to the floor.", + "required": true, + "selector": { + "object": { + "multiple": false + } + } + } + } + }, + "hide_entity": { + "name": "Hide an entity \uD83D\uDC7B", + "description": "Hides an entity (or entities) on the fly.", + "fields": { + "entity_id": { + "name": "Entity", + "description": "The entity/entities to hide.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "add_label_to_entity": { + "name": "Add a label to an entity \uD83D\uDC7B", + "description": "Adds a label to an entity. If multiple labels or multiple entities are provided, all combinations will be added.", + "fields": { + "label_id": { + "name": "Label ID", + "description": "The ID(s) of the label(s) to add the entity/entities.", + "required": true, + "selector": { + "label": { + "multiple": true + } + } + }, + "entity_id": { + "name": "Entity ID", + "description": "The ID(s) of the entity/entities to add the label(s) to.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "remove_label_from_device": { + "name": "Remove a label from a device \uD83D\uDC7B", + "description": "Removes a label from a device. If multiple labels or multiple devices are provided, all combinations will be removed.", + "fields": { + "label_id": { + "name": "Label ID", + "description": "The ID(s) of the label(s) to remove from the device(s).", + "required": true, + "selector": { + "label": { + "multiple": true + } + } + }, + "device_id": { + "name": "Device ID", + "description": "The ID(s) of the device(s) to remove the label(s) from.", + "required": true, + "selector": { + "device": { + "multiple": true + } + } + } + } + }, + "remove_alias_from_area": { + "name": "Remove an alias from an area \uD83D\uDC7B", + "description": "Removes an alias from an area.", + "fields": { + "area_id": { + "name": "Area ID", + "description": "The ID of the area to remove the alias from.", + "required": true, + "selector": { + "area": { + "multiple": false, + "reorder": false + } + } + }, + "alias": { + "name": "Alias", + "description": "The alias (or list of aliasses) to remove from the area.", + "required": true, + "selector": { + "object": { + "multiple": false + } + } + } + } + }, + "add_alias_to_area": { + "name": "Add an alias to an area \uD83D\uDC7B", + "description": "Adds an alias to an area.", + "fields": { + "area_id": { + "name": "Area ID", + "description": "The ID of the area to add the alias to.", + "required": true, + "selector": { + "area": { + "multiple": false, + "reorder": false + } + } + }, + "alias": { + "name": "Alias", + "description": "The alias (or list of aliasses) to add to the area.", + "required": true, + "selector": { + "object": { + "multiple": false + } + } + } + } + }, + "disable_config_entry": { + "name": "Disable an integration \uD83D\uDC7B", + "description": "Disables an integration configuration entry.", + "fields": { + "config_entry_id": { + "name": "Config entry", + "description": "The integration configuration entry to disable.", + "required": true, + "selector": { + "config_entry": {} + } + } + } + }, + "create_floor": { + "name": "Create a floor \uD83D\uDC7B", + "description": "Creates a new floor on the fly.", + "fields": { + "name": { + "name": "Name", + "description": "The name of the floor to create.", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "icon": { + "name": "Icon", + "description": "Icon to use for the floor.", + "required": false, + "selector": { + "icon": { + "placeholder": "mdi:texture-box" + } + } + }, + "level": { + "name": "Level", + "description": "The level the floor is on in your home.", + "required": false, + "selector": { + "number": { + "step": 1.0, + "mode": "box" + } + } + }, + "aliases": { + "name": "Aliases", + "description": "A list of aliases for the floor. This is useful if you want to use the floor in a different language or different nickname.", + "selector": { + "object": { + "multiple": false + } + } + } + } + }, + "create_area": { + "name": "Create an area \uD83D\uDC7B", + "description": "Creates a new area on the fly.", + "fields": { + "name": { + "name": "Name", + "description": "The name of the area to create.", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "icon": { + "name": "Icon", + "description": "Icon to use for the area.", + "required": false, + "selector": { + "icon": { + "placeholder": "mdi:texture-box" + } + } + }, + "aliases": { + "name": "Aliases", + "description": "A list of aliases for the area. This is useful if you want to use the area in a different language or different nickname.", + "selector": { + "object": { + "multiple": false + } + } + } + } + }, + "enable_config_entry": { + "name": "Enable an integration \uD83D\uDC7B", + "description": "Enables an integration configuration entry.", + "fields": { + "config_entry_id": { + "name": "Config entry", + "description": "The integration configuration entry to enable.", + "required": true, + "selector": { + "config_entry": {} + } + } + } + }, + "update_entity_id": { + "name": "Update an entity\u0027s ID \uD83D\uDC7B", + "description": "Updates an entity\u0027s ID on the fly.", + "fields": { + "entity_id": { + "name": "Entity", + "description": "The entity/entities to update.", + "required": true, + "selector": { + "entity": { + "multiple": false, + "reorder": false + } + } + }, + "new_entity_id": { + "name": "New Entity ID", + "description": "The new ID for the entity", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "delete_label": { + "name": "Delete a label \uD83D\uDC7B", + "description": "Deletes a label on the fly.", + "fields": { + "label_id": { + "name": "Label ID", + "description": "The ID of the label to delete.", + "required": true, + "selector": { + "label": { + "multiple": false + } + } + } + } + }, + "remove_area_from_floor": { + "name": "Remove an area from a floor \uD83D\uDC7B", + "description": "Removes an area from a floor. As an area can only be on one floor, this call doesn\u0027t need to specify the floor.", + "fields": { + "area_id": { + "name": "Area ID", + "description": "The ID of the area to remove the floor from.", + "required": true, + "selector": { + "area": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "add_label_to_area": { + "name": "Add a label to an area \uD83D\uDC7B", + "description": "Adds a label to an area. If multiple labels or multiple areas are provided, all combinations will be added.", + "fields": { + "label_id": { + "name": "Label ID", + "description": "The ID(s) of the label(s) to add the area(s).", + "required": true, + "selector": { + "label": { + "multiple": true + } + } + }, + "area_id": { + "name": "Area ID", + "description": "The ID(s) of the area(s) to add the label(s) to.", + "required": true, + "selector": { + "area": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "delete_all_orphaned_entities": { + "name": "Delete all orphaned entities \uD83D\uDC7B", + "description": "Deletes all orphaned entities that no longer have an integration that claim/provide them. Please note, if the integration was just removed, it might need a restart for Home Assistant to realize they are orphaned.\n**WARNING** Entities might have been marked orphaned because an integration is offline or not working since Home Assistant started. Calling this action will delete those entities as well.", + "fields": {} + }, + "ignore_all_discovered": { + "name": "Ignore all currently discovered devices \uD83D\uDC7B", + "description": "Ignore all currently discovered devices that are shown on the integrations dashboard. This will not ignore devices that are discovered after this.", + "fields": { + "domain": { + "name": "Integration domain", + "description": "The integration domain to ignore all discovered devices for. If not provided, all domains will be considered to be ignored.", + "required": false, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "list_orphaned_database_entities": { + "name": "List all orphaned database entities \uD83D\uDC7B", + "description": "Lists all orphaned database entities unclaimed by any integration.", + "fields": {}, + "response": { + "optional": false + } + }, + "unhide_entity": { + "name": "Unhide an entity \uD83D\uDC7B", + "description": "Unhides an entity (or entities) on the fly.", + "fields": { + "entity_id": { + "name": "Entity", + "description": "The entity/entities to unhide.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "rename_entity": { + "name": "Rename an entity \uD83D\uDC7B", + "description": "Renames an entity (or entities) on the fly.", + "fields": { + "entity_id": { + "name": "Entity", + "description": "The entity/entities to rename.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + }, + "name": { + "name": "Name", + "description": "The new name for the entity/entities.", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "disable_device": { + "name": "Disable a device \uD83D\uDC7B", + "description": "Disables a device on the fly.", + "fields": { + "device_id": { + "name": "Device", + "description": "The device(s) to disable.", + "required": true, + "selector": { + "device": { + "multiple": true + } + } + } + } + }, + "disable_polling": { + "name": "Disable polling for updates \uD83D\uDC7B", + "description": "Disables polling for updates for an integration configuration entry.", + "fields": { + "config_entry_id": { + "name": "Config entry", + "description": "The integration configuration entry to disable polling for.", + "required": true, + "selector": { + "config_entry": {} + } + } + } + }, + "delete_area": { + "name": "Delete an area \uD83D\uDC7B", + "description": "Deletes a new area on the fly.", + "fields": { + "area_id": { + "name": "Area ID", + "description": "The ID of the area to delete.", + "required": true, + "selector": { + "area": { + "multiple": false, + "reorder": false + } + } + } + } + }, + "delete_floor": { + "name": "Delete a floor \uD83D\uDC7B", + "description": "Deletes a floor on the fly.", + "fields": { + "floor_id": { + "name": "Floor ID", + "description": "The ID of the floor to delete.", + "required": true, + "selector": { + "floor": { + "multiple": false + } + } + } + } + }, + "enable_device": { + "name": "Enable a device \uD83D\uDC7B", + "description": "Enables a device on the fly.", + "fields": { + "device_id": { + "name": "Device", + "description": "The device(s) to enable.", + "required": true, + "selector": { + "device": { + "multiple": true + } + } + } + } + }, + "enable_polling": { + "name": "Enable polling for updates \uD83D\uDC7B", + "description": "Enables polling for updates for an integration configuration entry.", + "fields": { + "config_entry_id": { + "name": "Config entry", + "description": "The integration configuration entry to enable polling for.", + "required": true, + "selector": { + "config_entry": {} + } + } + } + }, + "enable_entity": { + "name": "Enable an entity \uD83D\uDC7B", + "description": "Enables an entity (or entities) on the fly.", + "fields": { + "entity_id": { + "name": "Entity", + "description": "The entity/entities to enable.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "remove_label_from_entity": { + "name": "Remove a label from an entity \uD83D\uDC7B", + "description": "Removes a label from an entity. If multiple labels or multiple entities are provided, all combinations will be removed.", + "fields": { + "label_id": { + "name": "Label ID", + "description": "The ID(s) of the label(s) to remove from the entity/entities.", + "required": true, + "selector": { + "label": { + "multiple": true + } + } + }, + "entity_id": { + "name": "Entity ID", + "description": "The ID(s) of the entity/entities to remove the label(s) from.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "restart": { + "name": "Restart \uD83D\uDC7B", + "description": "Restart the Home Assistant action.", + "fields": { + "safe_mode": { + "name": "Safe mode", + "description": "If the restart should be done in safe mode. This will disable all custom integrations and frontend modules.", + "required": false, + "selector": { + "boolean": {} + } + }, + "force": { + "name": "Force restart", + "description": "Force the restart. WARNING! This will not gracefully shutdown Home Assistant, it will skip configuration checks and ignore running database migrations. Only use this if you know what you are doing.", + "required": false, + "selector": { + "boolean": {} + } + } + } + }, + "add_device_to_area": { + "name": "Add a device to an area \uD83D\uDC7B", + "description": "Adds an device to an area. Please note, if the device is already in an area, it will be removed from the previous area.", + "fields": { + "area_id": { + "name": "Area ID", + "description": "The ID of the area to add the device to.", + "required": true, + "selector": { + "area": { + "multiple": false, + "reorder": false + } + } + }, + "device_id": { + "name": "Device ID", + "description": "The ID of the device(s) to add to the area.", + "required": true, + "selector": { + "device": { + "multiple": true + } + } + } + } + } + }, + "persistent_notification": { + "create": { + "fields": { + "message": { + "required": true, + "example": "Please check your configuration.yaml.", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "title": { + "example": "Test notification", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "notification_id": { + "example": 1234, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "dismiss": { + "fields": { + "notification_id": { + "required": true, + "example": 1234, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "dismiss_all": { + "fields": {} + } + }, + "system_log": { + "clear": { + "fields": {} + }, + "write": { + "fields": { + "message": { + "required": true, + "example": "Something went wrong", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "level": { + "default": "error", + "selector": { + "select": { + "options": [ + "debug", + "info", + "warning", + "error", + "critical" + ], + "translation_key": "level", + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "logger": { + "example": "mycomponent.myplatform", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + } + }, + "logger": { + "set_default_level": { + "fields": { + "level": { + "selector": { + "select": { + "options": [ + "debug", + "info", + "warning", + "error", + "fatal", + "critical" + ], + "translation_key": "level", + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + } + }, + "set_level": { + "fields": {} + } + }, + "frontend": { + "set_theme": { + "fields": { + "name": { + "required": false, + "example": "default", + "selector": { + "theme": { + "include_default": true + } + } + }, + "name_dark": { + "required": false, + "example": "default", + "selector": { + "theme": { + "include_default": true + } + } + } + } + }, + "reload_themes": { + "fields": {} + } + }, + "recorder": { + "purge": { + "fields": { + "keep_days": { + "selector": { + "number": { + "min": 0.0, + "max": 365.0, + "unit_of_measurement": "days", + "step": 1.0, + "mode": "slider" + } + } + }, + "repack": { + "default": false, + "selector": { + "boolean": {} + } + }, + "apply_filter": { + "default": false, + "selector": { + "boolean": {} + } + } + } + }, + "purge_entities": { + "fields": { + "entity_id": { + "required": false, + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + }, + "domains": { + "example": "sun", + "required": false, + "selector": { + "object": { + "multiple": false + } + } + }, + "entity_globs": { + "example": "domain*.object_id*", + "required": false, + "selector": { + "object": { + "multiple": false + } + } + }, + "keep_days": { + "default": 0, + "selector": { + "number": { + "min": 0.0, + "max": 365.0, + "unit_of_measurement": "days", + "step": 1.0, + "mode": "slider" + } + } + } + } + }, + "enable": { + "fields": {} + }, + "disable": { + "fields": {} + }, + "get_statistics": { + "fields": { + "start_time": { + "required": true, + "example": "2025-01-01 00:00:00", + "selector": { + "datetime": {} + } + }, + "end_time": { + "required": false, + "example": "2025-01-02 00:00:00", + "selector": { + "datetime": {} + } + }, + "statistic_ids": { + "required": true, + "example": [ + "sensor.energy_consumption", + "sensor.temperature" + ], + "selector": { + "statistic": { + "multiple": true + } + } + }, + "period": { + "required": true, + "example": "hour", + "selector": { + "select": { + "options": [ + "5minute", + "hour", + "day", + "week", + "month", + "year" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "types": { + "required": true, + "example": [ + "mean", + "sum" + ], + "selector": { + "select": { + "options": [ + "change", + "last_reset", + "max", + "mean", + "min", + "state", + "sum" + ], + "multiple": true, + "custom_value": false, + "sort": false + } + } + }, + "units": { + "required": false, + "example": { + "energy": "kWh", + "temperature": "\u00B0C" + }, + "selector": { + "object": { + "multiple": false + } + } + } + }, + "response": { + "optional": false + } + }, + "import_statistics": { + "name": "Import statistics \uD83D\uDC7B", + "description": "Import long-term statistics.", + "fields": { + "statistic_id": { + "name": "Statistics ID", + "description": "The statistics ID (entity ID) to import for.", + "required": true, + "selector": { + "entity": { + "multiple": false, + "reorder": false + } + } + }, + "name": { + "name": "Name", + "description": "The name of the statistics.", + "required": false, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "source": { + "name": "Source", + "description": "The source of the statistics data.", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "unit_of_measurement": { + "name": "Unit of measurement", + "description": "The unit of measurement of the statistics.", + "required": false, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "has_mean": { + "name": "Has a mean", + "description": "If the statistics has a mean value.", + "required": true, + "selector": { + "boolean": {} + } + }, + "has_sum": { + "name": "Has a sum", + "description": "If the statistics has a sum value.", + "required": true, + "selector": { + "boolean": {} + } + }, + "stats": { + "name": "Statistics", + "description": "A list of mappings/dictionaries with statistics to import. The dictionaries must contain a \u0022start\u0022 key with a datetime string other valid options are \u0022mean\u0022, \u0022sum\u0022, \u0022min\u0022, \u0022max\u0022, \u0022last_reset\u0022, and \u0022state\u0022. All of those are optional and either an integer or a float, except for \u0022last_reset\u0022 which is a datetime string.", + "required": true, + "selector": { + "object": { + "multiple": false + } + } + } + } + } + }, + "hassio": { + "addon_start": { + "fields": { + "addon": { + "required": true, + "example": "core_ssh", + "selector": { + "addon": {} + } + } + } + }, + "addon_stop": { + "fields": { + "addon": { + "required": true, + "example": "core_ssh", + "selector": { + "addon": {} + } + } + } + }, + "addon_restart": { + "fields": { + "addon": { + "required": true, + "example": "core_ssh", + "selector": { + "addon": {} + } + } + } + }, + "addon_stdin": { + "fields": { + "addon": { + "required": true, + "example": "core_ssh", + "selector": { + "addon": {} + } + } + } + }, + "app_start": { + "fields": { + "app": { + "required": true, + "example": "core_ssh", + "selector": { + "app": {} + } + } + } + }, + "app_stop": { + "fields": { + "app": { + "required": true, + "example": "core_ssh", + "selector": { + "app": {} + } + } + } + }, + "app_restart": { + "fields": { + "app": { + "required": true, + "example": "core_ssh", + "selector": { + "app": {} + } + } + } + }, + "app_stdin": { + "fields": { + "app": { + "required": true, + "example": "core_ssh", + "selector": { + "app": {} + } + }, + "input": { + "required": true, + "selector": { + "object": { + "multiple": false + } + } + } + } + }, + "host_shutdown": { + "fields": {} + }, + "host_reboot": { + "fields": {} + }, + "backup_full": { + "fields": { + "name": { + "example": "Backup 1", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "password": { + "example": "password", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "compressed": { + "default": true, + "selector": { + "boolean": {} + } + }, + "location": { + "example": "my_backup_mount", + "selector": { + "backup_location": {} + } + }, + "homeassistant_exclude_database": { + "default": false, + "selector": { + "boolean": {} + } + } + } + }, + "backup_partial": { + "fields": { + "homeassistant": { + "selector": { + "boolean": {} + } + }, + "homeassistant_exclude_database": { + "default": false, + "selector": { + "boolean": {} + } + }, + "apps": { + "example": [ + "core_ssh", + "core_samba", + "core_mosquitto" + ], + "selector": { + "object": { + "multiple": false + } + } + }, + "addons": { + "example": [ + "core_ssh", + "core_samba", + "core_mosquitto" + ], + "selector": { + "object": { + "multiple": false + } + } + }, + "folders": { + "example": [ + "homeassistant", + "share" + ], + "selector": { + "object": { + "multiple": false + } + } + }, + "name": { + "example": "Partial backup 1", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "password": { + "example": "password", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "compressed": { + "default": true, + "selector": { + "boolean": {} + } + }, + "location": { + "example": "my_backup_mount", + "selector": { + "backup_location": {} + } + } + } + }, + "restore_full": { + "fields": { + "slug": { + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "password": { + "example": "password", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "restore_partial": { + "fields": { + "slug": { + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "homeassistant": { + "selector": { + "boolean": {} + } + }, + "folders": { + "example": [ + "homeassistant", + "share" + ], + "selector": { + "object": { + "multiple": false + } + } + }, + "apps": { + "example": [ + "core_ssh", + "core_samba", + "core_mosquitto" + ], + "selector": { + "object": { + "multiple": false + } + } + }, + "addons": { + "example": [ + "core_ssh", + "core_samba", + "core_mosquitto" + ], + "selector": { + "object": { + "multiple": false + } + } + }, + "password": { + "example": "password", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + } + }, + "ffmpeg": { + "start": { + "fields": { + "entity_id": { + "selector": { + "entity": { + "integration": "ffmpeg", + "domain": [ + "binary_sensor" + ], + "multiple": false, + "reorder": false + } + } + } + } + }, + "stop": { + "fields": { + "entity_id": { + "selector": { + "entity": { + "integration": "ffmpeg", + "domain": [ + "binary_sensor" + ], + "multiple": false, + "reorder": false + } + } + } + } + }, + "restart": { + "fields": { + "entity_id": { + "selector": { + "entity": { + "integration": "ffmpeg", + "domain": [ + "binary_sensor" + ], + "multiple": false, + "reorder": false + } + } + } + } + } + }, + "switch": { + "turn_off": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "switch" + ] + } + ] + } + }, + "turn_on": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "switch" + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "switch" + ] + } + ] + } + } + }, + "update": { + "install": { + "fields": { + "version": { + "required": false, + "example": "1.0.0", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "backup": { + "filter": { + "supported_features": [ + 8 + ] + }, + "required": false, + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "update" + ] + } + ] + } + }, + "skip": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "update" + ] + } + ] + } + }, + "clear_skipped": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "update" + ] + } + ] + } + } + }, + "backup": { + "create_automatic": { + "fields": {} + } + }, + "conversation": { + "process": { + "fields": { + "text": { + "example": "Turn all lights on", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "language": { + "example": "NL", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "agent_id": { + "example": "homeassistant", + "selector": { + "conversation_agent": {} + } + }, + "conversation_id": { + "example": "my_conversation_1", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "response": { + "optional": true + } + }, + "reload": { + "fields": { + "language": { + "example": "NL", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "agent_id": { + "example": "homeassistant", + "selector": { + "conversation_agent": {} + } + } + } + } + }, + "tts": { + "speak": { + "fields": { + "media_player_entity_id": { + "required": true, + "selector": { + "entity": { + "domain": [ + "media_player" + ], + "multiple": false, + "reorder": false + } + } + }, + "message": { + "example": "My name is hanna", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "cache": { + "default": true, + "selector": { + "boolean": {} + } + }, + "language": { + "example": "ru", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "options": { + "advanced": true, + "example": "platform specific", + "selector": { + "object": { + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "tts" + ] + } + ] + } + }, + "clear_cache": { + "fields": {} + }, + "cloud_say": { + "name": "Say a TTS message with cloud", + "description": "Say something using text-to-speech on a media player with cloud.", + "fields": { + "entity_id": { + "required": true, + "selector": { + "entity": { + "domain": "media_player" + } + } + }, + "message": { + "example": "My name is hanna", + "required": true, + "selector": { + "text": null + } + }, + "cache": { + "default": false, + "selector": { + "boolean": null + } + }, + "language": { + "example": "ru", + "selector": { + "text": null + } + }, + "options": { + "advanced": true, + "example": "platform specific", + "selector": { + "object": null + } + } + } + } + }, + "cloud": { + "remote_connect": { + "fields": {} + }, + "remote_disconnect": { + "fields": {} + } + }, + "number": { + "set_value": { + "fields": { + "value": { + "example": 42, + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "number" + ] + } + ] + } + }, + "min": { + "name": "Set minimum value \uD83D\uDC7B", + "description": "Set a number entity to its minimum value.", + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "number" + ] + } + ] + } + }, + "decrement": { + "name": "Decrease value \uD83D\uDC7B", + "description": "Decrease a number entity value by a certain amount.", + "fields": { + "amount": { + "name": "Amount", + "description": "The amount to decrease the number with. If not provided, the step of the number entity will be used.", + "required": false, + "selector": { + "number": { + "step": 1.0, + "mode": "box" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "number" + ] + } + ] + } + }, + "increment": { + "name": "Increase value \uD83D\uDC7B", + "description": "Increase a number entity value by a certain amount.", + "fields": { + "amount": { + "name": "Amount", + "description": "The amount to increase the number with. If not provided, the step of the number entity will be used.", + "required": false, + "selector": { + "number": { + "step": 1.0, + "mode": "box" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "number" + ] + } + ] + } + }, + "max": { + "name": "Set maximum value \uD83D\uDC7B", + "description": "Set a number entity to its maximum value.", + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "number" + ] + } + ] + } + } + }, + "camera": { + "enable_motion_detection": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "camera" + ] + } + ] + } + }, + "disable_motion_detection": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "camera" + ] + } + ] + } + }, + "turn_off": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "camera" + ] + } + ] + } + }, + "turn_on": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "camera" + ] + } + ] + } + }, + "snapshot": { + "fields": { + "filename": { + "required": true, + "example": "/tmp/snapshot_{{ entity_id.name }}.jpg", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "camera" + ] + } + ] + } + }, + "play_stream": { + "fields": { + "media_player": { + "required": true, + "selector": { + "entity": { + "domain": [ + "media_player" + ], + "multiple": false, + "reorder": false + } + } + }, + "format": { + "default": "hls", + "selector": { + "select": { + "options": [ + "hls" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "camera" + ] + } + ] + } + }, + "record": { + "fields": { + "filename": { + "required": true, + "example": "/tmp/snapshot_{{ entity_id.name }}.mp4", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "duration": { + "default": 30, + "selector": { + "number": { + "min": 1.0, + "max": 3600.0, + "unit_of_measurement": "seconds", + "step": 1.0, + "mode": "slider" + } + } + }, + "lookback": { + "default": 0, + "selector": { + "number": { + "min": 0.0, + "max": 300.0, + "unit_of_measurement": "seconds", + "step": 1.0, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "camera" + ] + } + ] + } + } + }, + "select": { + "select_first": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "select" + ] + } + ] + } + }, + "select_last": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "select" + ] + } + ] + } + }, + "select_next": { + "fields": { + "cycle": { + "default": true, + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "select" + ] + } + ] + } + }, + "select_option": { + "fields": { + "option": { + "required": true, + "example": "\u0022Item A\u0022", + "selector": { + "state": { + "hide_states": [ + "unavailable", + "unknown" + ], + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "select" + ] + } + ] + } + }, + "select_previous": { + "fields": { + "cycle": { + "default": true, + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "select" + ] + } + ] + } + }, + "random": { + "name": "Select random option \uD83D\uDC7B", + "description": "Select an random option for a select entity.", + "fields": { + "options": { + "name": "Options", + "description": "Limits the options to select from. If not provided, all options will be considered.", + "required": false, + "selector": { + "object": { + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "select" + ] + } + ] + } + } + }, + "scene": { + "reload": { + "fields": {} + }, + "apply": { + "fields": { + "entities": { + "required": true, + "example": "light.kitchen: \u0022on\u0022\nlight.ceiling:\n state: \u0022on\u0022\n brightness: 80\n", + "selector": { + "object": { + "multiple": false + } + } + }, + "transition": { + "selector": { + "number": { + "min": 0.0, + "max": 300.0, + "unit_of_measurement": "seconds", + "step": 1.0, + "mode": "slider" + } + } + } + } + }, + "create": { + "fields": { + "scene_id": { + "required": true, + "example": "all_lights", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "entities": { + "advanced": true, + "example": "light.tv_back_light: \u0022on\u0022\nlight.ceiling:\n state: \u0022on\u0022\n brightness: 200\n", + "selector": { + "object": { + "multiple": false + } + } + }, + "snapshot_entities": { + "example": "- light.ceiling\n- light.kitchen\n", + "selector": { + "entity": { + "multiple": true, + "reorder": false + } + } + } + } + }, + "delete": { + "fields": {}, + "target": { + "entity": [ + { + "integration": "homeassistant", + "domain": [ + "scene" + ] + } + ] + } + }, + "turn_on": { + "fields": { + "transition": { + "selector": { + "number": { + "min": 0.0, + "max": 300.0, + "unit_of_measurement": "seconds", + "step": 1.0, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "scene" + ] + } + ] + } + } + }, + "zone": { + "reload": { + "fields": {} + }, + "delete": { + "name": "Delete a zone \uD83D\uDC7B", + "description": "Delete a zone. This works only with zones created and managed via the UI. Zones created and managed in YAML cannot be managed by Spook.", + "fields": { + "entity_id": { + "name": "Entity ID", + "description": "The ID of the entity (or entities) to remove.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "filter": [ + { + "domain": [ + "zone" + ] + } + ], + "reorder": false + } + } + } + } + }, + "update": { + "name": "Update a zone \uD83D\uDC7B", + "description": "Update properties of a zone on the fly.", + "fields": { + "entity_id": { + "name": "Entity ID", + "description": "The ID of the entity (or entities) to update.", + "required": true, + "selector": { + "entity": { + "filter": [ + { + "domain": [ + "zone" + ] + } + ], + "multiple": false, + "reorder": false + } + } + }, + "name": { + "name": "Name", + "description": "Name of the zone", + "required": false, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "icon": { + "name": "Icon", + "description": "Icon to use for the zone", + "required": false, + "selector": { + "icon": { + "placeholder": "mdi:map-marker" + } + } + }, + "latitude": { + "name": "Latitude", + "description": "Latitude of the zone", + "required": false, + "selector": { + "number": { + "min": -90.0, + "max": 90.0, + "step": "any", + "mode": "box", + "unit_of_measurement": "\u00B0" + } + } + }, + "longitude": { + "name": "Longitude", + "description": "Longitude of the zone", + "required": false, + "selector": { + "number": { + "min": -180.0, + "max": 180.0, + "step": "any", + "mode": "box", + "unit_of_measurement": "\u00B0" + } + } + }, + "radius": { + "name": "Radius", + "description": "Radius of the zone", + "required": false, + "default": 100, + "selector": { + "number": { + "min": 0.0, + "max": 999999999999.0, + "step": "any", + "unit_of_measurement": "m", + "mode": "box" + } + } + } + } + }, + "create": { + "name": "Create a zone \uD83D\uDC7B", + "description": "Create a new zone in Home Assistant on the fly.", + "fields": { + "name": { + "name": "Name", + "description": "Name of the zone", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "icon": { + "name": "Icon", + "description": "Icon to use for the zone", + "required": false, + "selector": { + "icon": { + "placeholder": "mdi:map-marker" + } + } + }, + "latitude": { + "name": "Latitude", + "description": "Latitude of the zone", + "required": true, + "selector": { + "number": { + "min": -90.0, + "max": 90.0, + "step": "any", + "mode": "box", + "unit_of_measurement": "\u00B0" + } + } + }, + "longitude": { + "name": "Longitude", + "description": "Longitude of the zone", + "required": true, + "selector": { + "number": { + "min": -180.0, + "max": 180.0, + "step": "any", + "mode": "box", + "unit_of_measurement": "\u00B0" + } + } + }, + "radius": { + "name": "Radius", + "description": "Radius of the zone", + "required": false, + "default": 100, + "selector": { + "number": { + "min": 0.0, + "max": 999999999999.0, + "unit_of_measurement": "m", + "mode": "box", + "step": 1.0 + } + } + } + } + } + }, + "input_select": { + "reload": { + "fields": {} + }, + "select_first": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "input_select" + ] + } + ] + } + }, + "select_last": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "input_select" + ] + } + ] + } + }, + "select_next": { + "fields": { + "cycle": { + "default": true, + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "input_select" + ] + } + ] + } + }, + "select_option": { + "fields": { + "option": { + "required": true, + "example": "\u0022Item A\u0022", + "selector": { + "state": { + "hide_states": [ + "unavailable", + "unknown" + ], + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "input_select" + ] + } + ] + } + }, + "select_previous": { + "fields": { + "cycle": { + "default": true, + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "input_select" + ] + } + ] + } + }, + "set_options": { + "fields": { + "options": { + "required": true, + "example": "[\u0022Item A\u0022, \u0022Item B\u0022, \u0022Item C\u0022]", + "selector": { + "text": { + "multiple": true, + "multiline": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "input_select" + ] + } + ] + } + }, + "shuffle": { + "name": "Shuffle options \uD83D\uDC7B", + "description": "Shuffles the list of selectable options for an \u0060input_select\u0060 entity. This is not persistent and will be undone once reloaded or Home Assistant restarts.", + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "input_select" + ] + } + ] + } + }, + "sort": { + "name": "Sort options \uD83D\uDC7B", + "description": "Sorts the list of selectable options for an \u0060input_select\u0060 entity. This is not persistent and will be undone once reloaded or Home Assistant restarts.", + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "input_select" + ] + } + ] + } + }, + "random": { + "name": "Select random option \uD83D\uDC7B", + "description": "Select an random option for an input_select entity.", + "fields": { + "options": { + "name": "Options", + "description": "Limits the options to select from. If not provided, all options will be considered.", + "required": false, + "selector": { + "object": { + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "input_select" + ] + } + ] + } + } + }, + "timer": { + "reload": { + "fields": {} + }, + "start": { + "fields": { + "duration": { + "example": "00:01:00 or 60", + "selector": { + "duration": { + "enable_second": true + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "timer" + ] + } + ] + } + }, + "pause": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "timer" + ] + } + ] + } + }, + "cancel": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "timer" + ] + } + ] + } + }, + "finish": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "timer" + ] + } + ] + } + }, + "change": { + "fields": { + "duration": { + "default": 0, + "required": true, + "example": "00:01:00, 60 or -60", + "selector": { + "duration": { + "allow_negative": true, + "enable_second": true + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "timer" + ] + } + ] + } + }, + "set_duration": { + "name": "Set duration \uD83D\uDC7B", + "description": "Set duration for an existing timer.", + "fields": { + "duration": { + "name": "Duration", + "description": "New duration for the timer, as a timedelta string.", + "required": true, + "example": "00:01:00, 60", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "timer" + ] + } + ] + } + } + }, + "script": { + "updatenordpoolprices": { + "name": "Update NordPool Prices", + "description": "", + "fields": {}, + "response": { + "optional": true + } + }, + "system_purge_device_history": { + "name": "System: Purge Device History", + "description": "", + "fields": { + "device_id": { + "name": "Device", + "description": "The device to purge all history from.", + "required": true, + "selector": { + "device": { + "multiple": true + } + }, + "advanced": false + } + }, + "response": { + "optional": true + } + }, + "reload": { + "fields": {} + }, + "turn_on": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "script" + ] + } + ] + } + }, + "turn_off": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "script" + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "script" + ] + } + ] + } + } + }, + "logbook": { + "log": { + "fields": { + "name": { + "required": true, + "example": "Kitchen", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "message": { + "required": true, + "example": "is being used", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "entity_id": { + "selector": { + "entity": { + "multiple": false, + "reorder": false + } + } + }, + "domain": { + "example": "light", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + } + }, + "person": { + "reload": { + "fields": {} + }, + "add_device_tracker": { + "name": "Add a device tracker \uD83D\uDC7B", + "description": "Add a device tracker to a person.", + "fields": { + "entity_id": { + "name": "Person", + "description": "The person entity ID to add the device tracker to.", + "required": true, + "selector": { + "entity": { + "filter": [ + { + "domain": [ + "person" + ] + } + ], + "multiple": false, + "reorder": false + } + } + }, + "device_tracker": { + "name": "Device tracker", + "description": "The device tracker entity ID to add to the person.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "filter": [ + { + "domain": [ + "device_tracker" + ] + } + ], + "reorder": false + } + } + } + } + }, + "remove_device_tracker": { + "name": "Remove a device tracker \uD83D\uDC7B", + "description": "Remove a device tracker from a person.", + "fields": { + "entity_id": { + "name": "Person", + "description": "The person entity ID to remove the device tracker from.", + "required": true, + "selector": { + "entity": { + "filter": [ + { + "domain": [ + "person" + ] + } + ], + "multiple": false, + "reorder": false + } + } + }, + "device_tracker": { + "name": "Device tracker", + "description": "The device tracker entity ID to remove from the person.", + "required": true, + "selector": { + "entity": { + "multiple": true, + "filter": [ + { + "domain": [ + "device_tracker" + ] + } + ], + "reorder": false + } + } + } + } + } + }, + "input_boolean": { + "reload": { + "fields": {} + }, + "turn_on": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "input_boolean" + ] + } + ] + } + }, + "turn_off": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "input_boolean" + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "input_boolean" + ] + } + ] + } + } + }, + "input_number": { + "reload": { + "fields": {} + }, + "set_value": { + "fields": { + "value": { + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 9.223372036854776e+18, + "step": 0.001, + "mode": "box" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "input_number" + ] + } + ] + } + }, + "min": { + "name": "Set minimum value \uD83D\uDC7B", + "description": "Set an input number entity to its minimum value.", + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "input_number" + ] + } + ] + } + }, + "decrement": { + "name": "Decrease value \uD83D\uDC7B", + "description": "Decrease an input number entity value by a certain amount.", + "fields": { + "amount": { + "name": "Amount", + "description": "The amount to decrease the input number with. If not provided, the step of the number entity will be used.", + "required": false, + "selector": { + "number": { + "step": 1.0, + "mode": "box" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "input_number" + ] + } + ] + } + }, + "increment": { + "name": "Increase value \uD83D\uDC7B", + "description": "Increase an input number entity value by a certain amount.", + "fields": { + "amount": { + "name": "Amount", + "description": "The amount to increase the input number with. If not provided, the step of the number entity will be used.", + "required": false, + "selector": { + "number": { + "step": 1.0, + "mode": "box" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "input_number" + ] + } + ] + } + }, + "max": { + "name": "Set maximum value \uD83D\uDC7B", + "description": "Set an input number entity to its maximum value.", + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "input_number" + ] + } + ] + } + } + }, + "input_button": { + "reload": { + "fields": {} + }, + "press": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "input_button" + ] + } + ] + } + } + }, + "counter": { + "increment": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "counter" + ] + } + ] + } + }, + "decrement": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "counter" + ] + } + ] + } + }, + "reset": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "counter" + ] + } + ] + } + }, + "set_value": { + "fields": { + "value": { + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 9.223372036854776e+18, + "mode": "box", + "step": 1.0 + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "counter" + ] + } + ] + } + } + }, + "mqtt": { + "publish": { + "fields": { + "topic": { + "required": true, + "example": "/homeassistant/hello", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "payload": { + "example": "The temperature is {{ states(\u0027sensor.temperature\u0027) }}", + "selector": { + "template": {} + } + }, + "evaluate_payload": { + "advanced": true, + "default": false, + "selector": { + "boolean": {} + } + }, + "qos": { + "advanced": true, + "default": 0, + "selector": { + "select": { + "options": [ + "0", + "1", + "2" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "retain": { + "default": false, + "selector": { + "boolean": {} + } + } + } + }, + "dump": { + "fields": { + "topic": { + "example": "OpenZWave/#", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "duration": { + "default": 5, + "selector": { + "number": { + "min": 1.0, + "max": 300.0, + "unit_of_measurement": "seconds", + "step": 1.0, + "mode": "slider" + } + } + } + } + }, + "reload": { + "fields": {} + } + }, + "input_text": { + "reload": { + "fields": {} + }, + "set_value": { + "fields": { + "value": { + "required": true, + "example": "This is an example text", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "input_text" + ] + } + ] + } + } + }, + "file": { + "read_file": { + "fields": { + "file_name": { + "example": "www/my_file.json", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "file_encoding": { + "example": "JSON", + "selector": { + "select": { + "options": [ + "JSON", + "YAML" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + }, + "response": { + "optional": false + } + } + }, + "schedule": { + "reload": { + "fields": {} + }, + "get_schedule": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "schedule" + ] + } + ] + }, + "response": { + "optional": false + } + } + }, + "sonoff": { + "send_command": { + "fields": { + "device": { + "name": "Device", + "description": "Device ID to send command to.", + "example": "1000123456" + }, + "cmd": { + "name": "Command", + "description": "A single command to send.", + "example": "switch" + } + }, + "description": "Sends a command to a device.", + "name": "Send Command" + } + }, + "template": { + "reload": { + "fields": {} + } + }, + "alarm_control_panel": { + "alarm_disarm": { + "fields": { + "code": { + "example": "1234", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "alarm_control_panel" + ] + } + ] + } + }, + "alarm_arm_home": { + "fields": { + "code": { + "example": "1234", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "alarm_control_panel" + ], + "supported_features": [ + 1 + ] + } + ] + } + }, + "alarm_arm_away": { + "fields": { + "code": { + "example": "1234", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "alarm_control_panel" + ], + "supported_features": [ + 2 + ] + } + ] + } + }, + "alarm_arm_night": { + "fields": { + "code": { + "example": "1234", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "alarm_control_panel" + ], + "supported_features": [ + 4 + ] + } + ] + } + }, + "alarm_arm_vacation": { + "fields": { + "code": { + "example": "1234", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "alarm_control_panel" + ], + "supported_features": [ + 32 + ] + } + ] + } + }, + "alarm_arm_custom_bypass": { + "fields": { + "code": { + "example": "1234", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "alarm_control_panel" + ], + "supported_features": [ + 16 + ] + } + ] + } + }, + "alarm_trigger": { + "fields": { + "code": { + "example": "1234", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "alarm_control_panel" + ], + "supported_features": [ + 8 + ] + } + ] + } + } + }, + "button": { + "press": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "button" + ] + } + ] + } + } + }, + "climate": { + "turn_on": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "climate" + ], + "supported_features": [ + 256 + ] + } + ] + } + }, + "turn_off": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "climate" + ], + "supported_features": [ + 128 + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "climate" + ], + "supported_features": [ + 128, + 256 + ] + } + ] + } + }, + "set_hvac_mode": { + "fields": { + "hvac_mode": { + "selector": { + "state": { + "hide_states": [ + "unavailable", + "unknown" + ], + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "climate" + ] + } + ] + } + }, + "set_preset_mode": { + "fields": { + "preset_mode": { + "required": true, + "example": "away", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "climate" + ], + "supported_features": [ + 16 + ] + } + ] + } + }, + "set_temperature": { + "fields": { + "temperature": { + "filter": { + "supported_features": [ + 1 + ] + }, + "selector": { + "number": { + "min": 0.0, + "max": 250.0, + "step": 0.1, + "mode": "box" + } + } + }, + "target_temp_high": { + "filter": { + "supported_features": [ + 2 + ] + }, + "advanced": true, + "selector": { + "number": { + "min": 0.0, + "max": 250.0, + "step": 0.1, + "mode": "box" + } + } + }, + "target_temp_low": { + "filter": { + "supported_features": [ + 2 + ] + }, + "advanced": true, + "selector": { + "number": { + "min": 0.0, + "max": 250.0, + "step": 0.1, + "mode": "box" + } + } + }, + "hvac_mode": { + "selector": { + "select": { + "options": [ + "off", + "auto", + "cool", + "dry", + "fan_only", + "heat_cool", + "heat" + ], + "translation_key": "hvac_mode", + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "climate" + ], + "supported_features": [ + 1, + 2 + ] + } + ] + } + }, + "set_humidity": { + "fields": { + "humidity": { + "required": true, + "selector": { + "number": { + "min": 30.0, + "max": 99.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "climate" + ], + "supported_features": [ + 4 + ] + } + ] + } + }, + "set_fan_mode": { + "fields": { + "fan_mode": { + "required": true, + "example": "low", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "climate" + ], + "supported_features": [ + 8 + ] + } + ] + } + }, + "set_swing_mode": { + "fields": { + "swing_mode": { + "required": true, + "example": "on", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "climate" + ], + "supported_features": [ + 32 + ] + } + ] + } + }, + "set_swing_horizontal_mode": { + "fields": { + "swing_horizontal_mode": { + "required": true, + "example": "on", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "climate" + ], + "supported_features": [ + 512 + ] + } + ] + } + } + }, + "cover": { + "open_cover": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "cover" + ], + "supported_features": [ + 1 + ] + } + ] + } + }, + "close_cover": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "cover" + ], + "supported_features": [ + 2 + ] + } + ] + } + }, + "set_cover_position": { + "fields": { + "position": { + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "cover" + ], + "supported_features": [ + 4 + ] + } + ] + } + }, + "stop_cover": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "cover" + ], + "supported_features": [ + 8 + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "cover" + ], + "supported_features": [ + 3 + ] + } + ] + } + }, + "open_cover_tilt": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "cover" + ], + "supported_features": [ + 16 + ] + } + ] + } + }, + "close_cover_tilt": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "cover" + ], + "supported_features": [ + 32 + ] + } + ] + } + }, + "stop_cover_tilt": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "cover" + ], + "supported_features": [ + 64 + ] + } + ] + } + }, + "set_cover_tilt_position": { + "fields": { + "tilt_position": { + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "cover" + ], + "supported_features": [ + 128 + ] + } + ] + } + }, + "toggle_cover_tilt": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "cover" + ], + "supported_features": [ + 48 + ] + } + ] + } + } + }, + "fan": { + "turn_on": { + "fields": { + "percentage": { + "filter": { + "supported_features": [ + 1 + ] + }, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + }, + "preset_mode": { + "example": "auto", + "filter": { + "supported_features": [ + 8 + ] + }, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "fan" + ], + "supported_features": [ + 32 + ] + } + ] + } + }, + "turn_off": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "fan" + ], + "supported_features": [ + 16 + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "fan" + ] + } + ] + } + }, + "increase_speed": { + "fields": { + "percentage_step": { + "advanced": true, + "required": false, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "fan" + ], + "supported_features": [ + 1 + ] + } + ] + } + }, + "decrease_speed": { + "fields": { + "percentage_step": { + "advanced": true, + "required": false, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "fan" + ], + "supported_features": [ + 1 + ] + } + ] + } + }, + "oscillate": { + "fields": { + "oscillating": { + "required": true, + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "fan" + ], + "supported_features": [ + 2 + ] + } + ] + } + }, + "set_direction": { + "fields": { + "direction": { + "required": true, + "selector": { + "select": { + "options": [ + "forward", + "reverse" + ], + "translation_key": "direction", + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "fan" + ], + "supported_features": [ + 4 + ] + } + ] + } + }, + "set_percentage": { + "fields": { + "percentage": { + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "fan" + ], + "supported_features": [ + 1 + ] + } + ] + } + }, + "set_preset_mode": { + "fields": { + "preset_mode": { + "required": true, + "example": "auto", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "fan" + ], + "supported_features": [ + 8 + ] + } + ] + } + } + }, + "light": { + "turn_on": { + "fields": { + "transition": { + "filter": { + "supported_features": [ + 32 + ] + }, + "selector": { + "number": { + "min": 0.0, + "max": 300.0, + "unit_of_measurement": "seconds", + "step": 1.0, + "mode": "slider" + } + } + }, + "rgb_color": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "example": "[255, 100, 100]", + "selector": { + "color_rgb": {} + } + }, + "color_temp_kelvin": { + "filter": { + "attribute": { + "supported_color_modes": [ + "color_temp", + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "selector": { + "color_temp": { + "unit": "kelvin", + "min": 2000, + "max": 6500 + } + } + }, + "brightness_pct": { + "filter": { + "attribute": { + "supported_color_modes": [ + "brightness", + "color_temp", + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + }, + "brightness_step_pct": { + "filter": { + "attribute": { + "supported_color_modes": [ + "brightness", + "color_temp", + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "selector": { + "number": { + "min": -100.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + }, + "effect": { + "filter": { + "supported_features": [ + 4 + ] + }, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "advanced_fields": { + "collapsed": true, + "fields": { + "rgbw_color": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "example": "[255, 100, 100, 50]", + "selector": { + "object": { + "multiple": false + } + } + }, + "rgbww_color": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "example": "[255, 100, 100, 50, 70]", + "selector": { + "object": { + "multiple": false + } + } + }, + "color_name": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "selector": { + "select": { + "translation_key": "color_name", + "options": [ + "homeassistant", + "aliceblue", + "antiquewhite", + "aqua", + "aquamarine", + "azure", + "beige", + "bisque", + "blanchedalmond", + "blue", + "blueviolet", + "brown", + "burlywood", + "cadetblue", + "chartreuse", + "chocolate", + "coral", + "cornflowerblue", + "cornsilk", + "crimson", + "cyan", + "darkblue", + "darkcyan", + "darkgoldenrod", + "darkgray", + "darkgreen", + "darkgrey", + "darkkhaki", + "darkmagenta", + "darkolivegreen", + "darkorange", + "darkorchid", + "darkred", + "darksalmon", + "darkseagreen", + "darkslateblue", + "darkslategray", + "darkslategrey", + "darkturquoise", + "darkviolet", + "deeppink", + "deepskyblue", + "dimgray", + "dimgrey", + "dodgerblue", + "firebrick", + "floralwhite", + "forestgreen", + "fuchsia", + "gainsboro", + "ghostwhite", + "gold", + "goldenrod", + "gray", + "green", + "greenyellow", + "grey", + "honeydew", + "hotpink", + "indianred", + "indigo", + "ivory", + "khaki", + "lavender", + "lavenderblush", + "lawngreen", + "lemonchiffon", + "lightblue", + "lightcoral", + "lightcyan", + "lightgoldenrodyellow", + "lightgray", + "lightgreen", + "lightgrey", + "lightpink", + "lightsalmon", + "lightseagreen", + "lightskyblue", + "lightslategray", + "lightslategrey", + "lightsteelblue", + "lightyellow", + "lime", + "limegreen", + "linen", + "magenta", + "maroon", + "mediumaquamarine", + "mediumblue", + "mediumorchid", + "mediumpurple", + "mediumseagreen", + "mediumslateblue", + "mediumspringgreen", + "mediumturquoise", + "mediumvioletred", + "midnightblue", + "mintcream", + "mistyrose", + "moccasin", + "navajowhite", + "navy", + "navyblue", + "oldlace", + "olive", + "olivedrab", + "orange", + "orangered", + "orchid", + "palegoldenrod", + "palegreen", + "paleturquoise", + "palevioletred", + "papayawhip", + "peachpuff", + "peru", + "pink", + "plum", + "powderblue", + "purple", + "red", + "rosybrown", + "royalblue", + "saddlebrown", + "salmon", + "sandybrown", + "seagreen", + "seashell", + "sienna", + "silver", + "skyblue", + "slateblue", + "slategray", + "slategrey", + "snow", + "springgreen", + "steelblue", + "tan", + "teal", + "thistle", + "tomato", + "turquoise", + "violet", + "wheat", + "white", + "whitesmoke", + "yellow", + "yellowgreen" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "hs_color": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "example": "[300, 70]", + "selector": { + "object": { + "multiple": false + } + } + }, + "xy_color": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "example": "[0.52, 0.43]", + "selector": { + "object": { + "multiple": false + } + } + }, + "brightness": { + "filter": { + "attribute": { + "supported_color_modes": [ + "brightness", + "color_temp", + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "brightness_step": { + "filter": { + "attribute": { + "supported_color_modes": [ + "brightness", + "color_temp", + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "selector": { + "number": { + "min": -225.0, + "max": 255.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "white": { + "filter": { + "attribute": { + "supported_color_modes": [ + "white" + ] + } + }, + "selector": { + "constant": { + "value": true, + "label": "Enabled" + } + } + }, + "profile": { + "example": "relax", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "flash": { + "filter": { + "supported_features": [ + 8 + ] + }, + "selector": { + "select": { + "translation_key": "flash", + "options": [ + "long", + "short" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "light" + ] + } + ] + } + }, + "turn_off": { + "fields": { + "transition": { + "filter": { + "supported_features": [ + 32 + ] + }, + "selector": { + "number": { + "min": 0.0, + "max": 300.0, + "unit_of_measurement": "seconds", + "step": 1.0, + "mode": "slider" + } + } + }, + "advanced_fields": { + "collapsed": true, + "fields": { + "flash": { + "filter": { + "supported_features": [ + 8 + ] + }, + "selector": { + "select": { + "translation_key": "flash", + "options": [ + "long", + "short" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "light" + ] + } + ] + } + }, + "toggle": { + "fields": { + "transition": { + "filter": { + "supported_features": [ + 32 + ] + }, + "selector": { + "number": { + "min": 0.0, + "max": 300.0, + "unit_of_measurement": "seconds", + "step": 1.0, + "mode": "slider" + } + } + }, + "rgb_color": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "example": "[255, 100, 100]", + "selector": { + "color_rgb": {} + } + }, + "color_temp_kelvin": { + "filter": { + "attribute": { + "supported_color_modes": [ + "color_temp", + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "selector": { + "color_temp": { + "unit": "kelvin", + "min": 2000, + "max": 6500 + } + } + }, + "brightness_pct": { + "filter": { + "attribute": { + "supported_color_modes": [ + "brightness", + "color_temp", + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + }, + "effect": { + "filter": { + "supported_features": [ + 4 + ] + }, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "advanced_fields": { + "collapsed": true, + "fields": { + "rgbw_color": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "example": "[255, 100, 100, 50]", + "selector": { + "object": { + "multiple": false + } + } + }, + "rgbww_color": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "example": "[255, 100, 100, 50, 70]", + "selector": { + "object": { + "multiple": false + } + } + }, + "color_name": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "selector": { + "select": { + "translation_key": "color_name", + "options": [ + "homeassistant", + "aliceblue", + "antiquewhite", + "aqua", + "aquamarine", + "azure", + "beige", + "bisque", + "blanchedalmond", + "blue", + "blueviolet", + "brown", + "burlywood", + "cadetblue", + "chartreuse", + "chocolate", + "coral", + "cornflowerblue", + "cornsilk", + "crimson", + "cyan", + "darkblue", + "darkcyan", + "darkgoldenrod", + "darkgray", + "darkgreen", + "darkgrey", + "darkkhaki", + "darkmagenta", + "darkolivegreen", + "darkorange", + "darkorchid", + "darkred", + "darksalmon", + "darkseagreen", + "darkslateblue", + "darkslategray", + "darkslategrey", + "darkturquoise", + "darkviolet", + "deeppink", + "deepskyblue", + "dimgray", + "dimgrey", + "dodgerblue", + "firebrick", + "floralwhite", + "forestgreen", + "fuchsia", + "gainsboro", + "ghostwhite", + "gold", + "goldenrod", + "gray", + "green", + "greenyellow", + "grey", + "honeydew", + "hotpink", + "indianred", + "indigo", + "ivory", + "khaki", + "lavender", + "lavenderblush", + "lawngreen", + "lemonchiffon", + "lightblue", + "lightcoral", + "lightcyan", + "lightgoldenrodyellow", + "lightgray", + "lightgreen", + "lightgrey", + "lightpink", + "lightsalmon", + "lightseagreen", + "lightskyblue", + "lightslategray", + "lightslategrey", + "lightsteelblue", + "lightyellow", + "lime", + "limegreen", + "linen", + "magenta", + "maroon", + "mediumaquamarine", + "mediumblue", + "mediumorchid", + "mediumpurple", + "mediumseagreen", + "mediumslateblue", + "mediumspringgreen", + "mediumturquoise", + "mediumvioletred", + "midnightblue", + "mintcream", + "mistyrose", + "moccasin", + "navajowhite", + "navy", + "navyblue", + "oldlace", + "olive", + "olivedrab", + "orange", + "orangered", + "orchid", + "palegoldenrod", + "palegreen", + "paleturquoise", + "palevioletred", + "papayawhip", + "peachpuff", + "peru", + "pink", + "plum", + "powderblue", + "purple", + "red", + "rosybrown", + "royalblue", + "saddlebrown", + "salmon", + "sandybrown", + "seagreen", + "seashell", + "sienna", + "silver", + "skyblue", + "slateblue", + "slategray", + "slategrey", + "snow", + "springgreen", + "steelblue", + "tan", + "teal", + "thistle", + "tomato", + "turquoise", + "violet", + "wheat", + "white", + "whitesmoke", + "yellow", + "yellowgreen" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "hs_color": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "example": "[300, 70]", + "selector": { + "object": { + "multiple": false + } + } + }, + "xy_color": { + "filter": { + "attribute": { + "supported_color_modes": [ + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "example": "[0.52, 0.43]", + "selector": { + "object": { + "multiple": false + } + } + }, + "brightness": { + "filter": { + "attribute": { + "supported_color_modes": [ + "brightness", + "color_temp", + "hs", + "xy", + "rgb", + "rgbw", + "rgbww" + ] + } + }, + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "white": { + "filter": { + "attribute": { + "supported_color_modes": [ + "white" + ] + } + }, + "selector": { + "constant": { + "value": true, + "label": "Enabled" + } + } + }, + "profile": { + "example": "relax", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "flash": { + "filter": { + "supported_features": [ + 8 + ] + }, + "selector": { + "select": { + "translation_key": "flash", + "options": [ + "long", + "short" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "light" + ] + } + ] + } + } + }, + "media_player": { + "turn_on": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 128 + ] + } + ] + } + }, + "turn_off": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 256 + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 384 + ] + } + ] + } + }, + "volume_up": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 4, + 1024 + ] + } + ] + } + }, + "volume_down": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 4, + 1024 + ] + } + ] + } + }, + "media_play_pause": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 16385 + ] + } + ] + } + }, + "media_play": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 16384 + ] + } + ] + } + }, + "media_pause": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 1 + ] + } + ] + } + }, + "media_stop": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 4096 + ] + } + ] + } + }, + "media_next_track": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 32 + ] + } + ] + } + }, + "media_previous_track": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 16 + ] + } + ] + } + }, + "clear_playlist": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 8192 + ] + } + ] + } + }, + "volume_set": { + "fields": { + "volume_level": { + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 1.0, + "step": 0.01, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 4 + ] + } + ] + } + }, + "volume_mute": { + "fields": { + "is_volume_muted": { + "required": true, + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 8 + ] + } + ] + } + }, + "media_seek": { + "fields": { + "seek_position": { + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 9.223372036854776e+18, + "step": 0.01, + "mode": "box" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 2 + ] + } + ] + } + }, + "join": { + "fields": { + "group_members": { + "required": true, + "example": "- media_player.multiroom_player2\n- media_player.multiroom_player3\n", + "selector": { + "entity": { + "multiple": true, + "domain": [ + "media_player" + ], + "reorder": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 524288 + ] + } + ] + } + }, + "select_source": { + "fields": { + "source": { + "required": true, + "example": "video1", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 2048 + ] + } + ] + } + }, + "select_sound_mode": { + "fields": { + "sound_mode": { + "example": "Music", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 65536 + ] + } + ] + } + }, + "play_media": { + "fields": { + "media": { + "required": true, + "selector": { + "media": { + "multiple": false + } + }, + "example": "{\u0022media_content_id\u0022: \u0022https://home-assistant.io/images/cast/splash.png\u0022, \u0022media_content_type\u0022: \u0022music\u0022}" + }, + "enqueue": { + "filter": { + "supported_features": [ + 2097152 + ] + }, + "required": false, + "selector": { + "select": { + "options": [ + "play", + "next", + "add", + "replace" + ], + "translation_key": "enqueue", + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "announce": { + "filter": { + "supported_features": [ + 1048576 + ] + }, + "required": false, + "example": "true", + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 512 + ] + } + ] + } + }, + "browse_media": { + "fields": { + "media_content_type": { + "required": false, + "example": "music", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "media_content_id": { + "required": false, + "example": "A:ALBUMARTIST/Beatles", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 131072 + ] + } + ] + }, + "response": { + "optional": false + } + }, + "search_media": { + "fields": { + "search_query": { + "required": true, + "example": "Beatles", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "media_content_type": { + "required": false, + "example": "music", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "media_content_id": { + "required": false, + "example": "A:ALBUMARTIST/Beatles", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "media_filter_classes": { + "required": false, + "example": [ + "album", + "artist" + ], + "selector": { + "text": { + "multiple": true, + "multiline": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 4194304 + ] + } + ] + }, + "response": { + "optional": false + } + }, + "shuffle_set": { + "fields": { + "shuffle": { + "required": true, + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 32768 + ] + } + ] + } + }, + "unjoin": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 524288 + ] + } + ] + } + }, + "repeat_set": { + "fields": { + "repeat": { + "required": true, + "selector": { + "select": { + "options": [ + "off", + "all", + "one" + ], + "translation_key": "repeat", + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "media_player" + ], + "supported_features": [ + 262144 + ] + } + ] + } + } + }, + "remote": { + "turn_off": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "remote" + ] + } + ] + } + }, + "turn_on": { + "fields": { + "activity": { + "example": "BedroomTV", + "filter": { + "supported_features": [ + 4 + ] + }, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "remote" + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "remote" + ] + } + ] + } + }, + "send_command": { + "fields": { + "device": { + "example": "32756745", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "command": { + "required": true, + "example": "Play", + "selector": { + "object": { + "multiple": false + } + } + }, + "num_repeats": { + "default": 1, + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "delay_secs": { + "default": 0.4, + "selector": { + "number": { + "min": 0.0, + "max": 60.0, + "step": 0.1, + "unit_of_measurement": "seconds", + "mode": "slider" + } + } + }, + "hold_secs": { + "default": 0, + "selector": { + "number": { + "min": 0.0, + "max": 60.0, + "step": 0.1, + "unit_of_measurement": "seconds", + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "remote" + ] + } + ] + } + }, + "learn_command": { + "fields": { + "device": { + "example": "television", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "command": { + "example": "Turn on", + "selector": { + "object": { + "multiple": false + } + } + }, + "command_type": { + "default": "ir", + "selector": { + "select": { + "options": [ + "ir", + "rf" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "alternative": { + "selector": { + "boolean": {} + } + }, + "timeout": { + "selector": { + "number": { + "min": 0.0, + "max": 60.0, + "step": 5.0, + "unit_of_measurement": "seconds", + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "remote" + ] + } + ] + } + }, + "delete_command": { + "fields": { + "device": { + "example": "television", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "command": { + "required": true, + "example": "Mute", + "selector": { + "object": { + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "remote" + ] + } + ] + } + } + }, + "nordpool": { + "get_prices_for_date": { + "fields": { + "config_entry": { + "required": true, + "selector": { + "config_entry": { + "integration": "nordpool" + } + } + }, + "date": { + "required": true, + "selector": { + "date": {} + } + }, + "areas": { + "selector": { + "select": { + "options": [ + "EE", + "LT", + "LV", + "AT", + "BE", + "FR", + "GER", + "NL", + "PL", + "DK1", + "DK2", + "FI", + "NO1", + "NO2", + "NO3", + "NO4", + "NO5", + "SE1", + "SE2", + "SE3", + "SE4", + "SYS" + ], + "mode": "dropdown", + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "currency": { + "selector": { + "select": { + "options": [ + "DKK", + "EUR", + "NOK", + "PLN", + "SEK" + ], + "mode": "dropdown", + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + }, + "response": { + "optional": false + } + }, + "get_price_indices_for_date": { + "fields": { + "config_entry": { + "required": true, + "selector": { + "config_entry": { + "integration": "nordpool" + } + } + }, + "date": { + "required": true, + "selector": { + "date": {} + } + }, + "areas": { + "selector": { + "select": { + "options": [ + "EE", + "LT", + "LV", + "AT", + "BE", + "FR", + "GER", + "NL", + "PL", + "DK1", + "DK2", + "FI", + "NO1", + "NO2", + "NO3", + "NO4", + "NO5", + "SE1", + "SE2", + "SE3", + "SE4", + "SYS" + ], + "mode": "dropdown", + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "currency": { + "selector": { + "select": { + "options": [ + "DKK", + "EUR", + "NOK", + "PLN", + "SEK" + ], + "mode": "dropdown", + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "resolution": { + "selector": { + "select": { + "options": [ + "15", + "30", + "60" + ], + "mode": "dropdown", + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + }, + "response": { + "optional": false + } + } + }, + "localtuya": { + "reload": { + "fields": {}, + "description": "Reload localtuya and reconnect to all devices." + }, + "set_dp": { + "fields": { + "device_id": { + "description": "Device ID of device to change datapoint value for", + "example": "11100118278aab4de001" + }, + "dp": { + "description": "Datapoint index", + "example": 1 + }, + "value": { + "description": "New value to set", + "example": false + } + }, + "description": "Change the value of a datapoint (DP)" + } + }, + "input_datetime": { + "reload": { + "fields": {} + }, + "set_datetime": { + "fields": { + "date": { + "example": "\u00222019-04-20\u0022", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "time": { + "example": "\u002205:04:20\u0022", + "selector": { + "time": {} + } + }, + "datetime": { + "example": "\u00222019-04-20 05:04:20\u0022", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "timestamp": { + "selector": { + "number": { + "min": 0.0, + "max": 9.223372036854776e+18, + "mode": "box", + "step": 1.0 + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "input_datetime" + ] + } + ] + } + } + }, + "weather": { + "get_forecasts": { + "fields": { + "type": { + "required": true, + "selector": { + "select": { + "options": [ + "daily", + "hourly", + "twice_daily" + ], + "translation_key": "forecast_type", + "custom_value": false, + "sort": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "weather" + ], + "supported_features": [ + 1, + 2, + 4 + ] + } + ] + }, + "response": { + "optional": false + } + } + }, + "notify": { + "send_message": { + "fields": { + "message": { + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "title": { + "required": false, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + }, + "filter": { + "supported_features": [ + 1 + ] + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "notify" + ] + } + ] + } + }, + "persistent_notification": { + "fields": { + "message": { + "required": true, + "example": "The garage door has been open for 10 minutes.", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "title": { + "example": "Your Garage Door Friend", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "data": { + "example": "platform specific", + "selector": { + "object": { + "multiple": false + } + } + } + } + }, + "mobile_app_marius_phone": { + "name": "Send a notification via mobile_app_marius_phone", + "description": "Sends a notification message using the mobile_app_marius_phone integration.", + "fields": { + "message": { + "required": true, + "example": "The garage door has been open for 10 minutes.", + "selector": { + "text": null + } + }, + "title": { + "example": "Your Garage Door Friend", + "selector": { + "text": null + } + }, + "target": { + "example": "platform specific", + "selector": { + "object": null + } + }, + "data": { + "example": "platform specific", + "selector": { + "object": null + } + } + } + }, + "mobile_app_erika_s_iphone": { + "name": "Send a notification via mobile_app_erika_s_iphone", + "description": "Sends a notification message using the mobile_app_erika_s_iphone integration.", + "fields": { + "message": { + "required": true, + "example": "The garage door has been open for 10 minutes.", + "selector": { + "text": null + } + }, + "title": { + "example": "Your Garage Door Friend", + "selector": { + "text": null + } + }, + "target": { + "example": "platform specific", + "selector": { + "object": null + } + }, + "data": { + "example": "platform specific", + "selector": { + "object": null + } + } + } + }, + "mobile_app_marius_watch": { + "name": "Send a notification via mobile_app_marius_watch", + "description": "Sends a notification message using the mobile_app_marius_watch integration.", + "fields": { + "message": { + "required": true, + "example": "The garage door has been open for 10 minutes.", + "selector": { + "text": null + } + }, + "title": { + "example": "Your Garage Door Friend", + "selector": { + "text": null + } + }, + "target": { + "example": "platform specific", + "selector": { + "object": null + } + }, + "data": { + "example": "platform specific", + "selector": { + "object": null + } + } + } + }, + "mobile_app_home_phone": { + "name": "Send a notification via mobile_app_home_phone", + "description": "Sends a notification message using the mobile_app_home_phone integration.", + "fields": { + "message": { + "required": true, + "example": "The garage door has been open for 10 minutes.", + "selector": { + "text": null + } + }, + "title": { + "example": "Your Garage Door Friend", + "selector": { + "text": null + } + }, + "target": { + "example": "platform specific", + "selector": { + "object": null + } + }, + "data": { + "example": "platform specific", + "selector": { + "object": null + } + } + } + }, + "notify": { + "name": "Send a notification with notify", + "description": "Sends a notification message using the notify service.", + "fields": { + "message": { + "required": true, + "example": "The garage door has been open for 10 minutes.", + "selector": { + "text": null + } + }, + "title": { + "example": "Your Garage Door Friend", + "selector": { + "text": null + } + }, + "target": { + "example": "platform specific", + "selector": { + "object": null + } + }, + "data": { + "example": "platform specific", + "selector": { + "object": null + } + } + } + } + }, + "device_tracker": { + "see": { + "fields": { + "mac": { + "example": "FF:FF:FF:FF:FF:FF", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "dev_id": { + "example": "phonedave", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "host_name": { + "example": "Dave", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "location_name": { + "example": "home", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "gps": { + "example": "[51.509802, -0.086692]", + "selector": { + "object": { + "multiple": false + } + } + }, + "gps_accuracy": { + "selector": { + "number": { + "min": 0.0, + "mode": "box", + "unit_of_measurement": "m", + "step": 1.0 + } + } + }, + "battery": { + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + } + } + } + }, + "humidifier": { + "turn_on": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "humidifier" + ] + } + ] + } + }, + "turn_off": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "humidifier" + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "humidifier" + ] + } + ] + } + }, + "set_mode": { + "fields": { + "mode": { + "required": true, + "example": "away", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "humidifier" + ], + "supported_features": [ + 1 + ] + } + ] + } + }, + "set_humidity": { + "fields": { + "humidity": { + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "humidifier" + ] + } + ] + } + } + }, + "siren": { + "turn_on": { + "fields": { + "tone": { + "example": "fire", + "filter": { + "supported_features": [ + 4 + ] + }, + "required": false, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "volume_level": { + "example": 0.5, + "filter": { + "supported_features": [ + 8 + ] + }, + "required": false, + "selector": { + "number": { + "min": 0.0, + "max": 1.0, + "step": 0.05, + "mode": "slider" + } + } + }, + "duration": { + "example": 15, + "filter": { + "supported_features": [ + 16 + ] + }, + "required": false, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "siren" + ], + "supported_features": [ + 1 + ] + } + ] + } + }, + "turn_off": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "siren" + ], + "supported_features": [ + 2 + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "siren" + ], + "supported_features": [ + 3 + ] + } + ] + } + } + }, + "vacuum": { + "start": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "vacuum" + ], + "supported_features": [ + 8192 + ] + } + ] + } + }, + "pause": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "vacuum" + ], + "supported_features": [ + 4 + ] + } + ] + } + }, + "return_to_base": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "vacuum" + ], + "supported_features": [ + 16 + ] + } + ] + } + }, + "clean_spot": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "vacuum" + ] + } + ] + } + }, + "clean_area": { + "fields": { + "cleaning_area_id": { + "required": true, + "selector": { + "area": { + "multiple": true, + "reorder": true + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "vacuum" + ], + "supported_features": [ + 16384 + ] + } + ] + } + }, + "locate": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "vacuum" + ], + "supported_features": [ + 512 + ] + } + ] + } + }, + "stop": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "vacuum" + ], + "supported_features": [ + 8 + ] + } + ] + } + }, + "set_fan_speed": { + "fields": { + "fan_speed": { + "required": true, + "example": "low", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "vacuum" + ] + } + ] + } + }, + "send_command": { + "fields": { + "command": { + "required": true, + "example": "set_dnd_timer", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "params": { + "example": "{ \u0022key\u0022: \u0022value\u0022 }", + "selector": { + "object": { + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "vacuum" + ] + } + ] + } + } + }, + "valve": { + "open_valve": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "valve" + ], + "supported_features": [ + 1 + ] + } + ] + } + }, + "close_valve": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "valve" + ], + "supported_features": [ + 2 + ] + } + ] + } + }, + "set_valve_position": { + "fields": { + "position": { + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "unit_of_measurement": "%", + "step": 1.0, + "mode": "slider" + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "valve" + ], + "supported_features": [ + 4 + ] + } + ] + } + }, + "stop_valve": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "valve" + ], + "supported_features": [ + 8 + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "valve" + ], + "supported_features": [ + 3 + ] + } + ] + } + } + }, + "text": { + "set_value": { + "fields": { + "value": { + "required": true, + "example": "Hello world!", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "text" + ] + } + ] + } + } + }, + "repairs": { + "ignore_all": { + "name": "Ignore all issues \uD83D\uDC7B", + "description": "Ignore all issues currently raised in Home Assistant Repairs.", + "fields": {} + }, + "unignore_all": { + "name": "Unignore all issues \uD83D\uDC7B", + "description": "Unignore all issues currently raised in Home Assistant Repairs.", + "fields": {} + }, + "remove": { + "name": "Remove issue \uD83D\uDC7B", + "description": "Removes a manually created Home Assistant repairs issue. This action can only remove issues created with the \u0060repairs_create\u0060 action.", + "fields": { + "issue_id": { + "name": "Issue ID", + "description": "The issue ID to remove.", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "create": { + "name": "Create issue \uD83D\uDC7B", + "description": "Manually create and raise a issue in Home Assistant repairs.", + "fields": { + "title": { + "name": "Title", + "description": "The title of the issue.", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "description": { + "name": "Description", + "description": "The description of the issue. Supports Markdown.", + "required": true, + "selector": { + "text": { + "multiline": true, + "multiple": false + } + } + }, + "issue_id": { + "name": "Issue ID", + "description": "The issue can have an identifier, which allows you to cancel it later with that ID if needed. It also prevent duplicate issues to be created. If not provided, a random ID will be generated.", + "required": false, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "domain": { + "name": "Domain", + "description": "This field can be used to set the domain of the issue. For example, by default (if not set), it will use \u0022spook\u0022. This causes Spook to be shown in the logo/image of the issue. If you set it to \u0022homeassistant\u0022, the Home Assistant logo will be used, or use \u0022hue\u0022, \u0022zwave_js\u0022, \u0022mqtt\u0022, etc. to use the logo of that integration.", + "required": false, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "severity": { + "name": "Severity", + "description": "The severity of the issue. This will be used to determine the priority of the issue. If not set, \u0022warning\u0022 will be used", + "required": false, + "selector": { + "select": { + "options": [ + { + "label": "Warning", + "value": "warning" + }, + { + "label": "Error", + "value": "error" + }, + { + "label": "Critical", + "value": "critical" + } + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "persistent": { + "name": "Persistent", + "description": "If the issue should be persistent, which means it will survive restarts of Home Assistant. By default, issues are not persistent.", + "required": false, + "selector": { + "boolean": {} + } + } + } + } + }, + "blueprint": { + "import": { + "name": "Import blueprint \uD83D\uDC7B", + "description": "Import a blueprint.", + "fields": { + "url": { + "name": "URL", + "description": "The URL to import the blueprint from.", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + } + }, + "spook": { + "boo": { + "fields": {}, + "description": "Calling this action spooks Home Assistant. Performing this action will always fail.", + "name": "Boo! \uD83D\uDC7B" + }, + "random_fail": { + "fields": {}, + "description": "Performing this action will randomly fail.", + "name": "Random fail \uD83D\uDC7B" + } + }, + "time": { + "set_value": { + "fields": { + "time": { + "required": true, + "example": "22:15", + "selector": { + "time": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "time" + ] + } + ] + } + } + }, + "automation": { + "trigger": { + "fields": { + "skip_condition": { + "default": true, + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "automation" + ] + } + ] + } + }, + "toggle": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "automation" + ] + } + ] + } + }, + "turn_on": { + "fields": {}, + "target": { + "entity": [ + { + "domain": [ + "automation" + ] + } + ] + } + }, + "turn_off": { + "fields": { + "stop_actions": { + "default": true, + "selector": { + "boolean": {} + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "automation" + ] + } + ] + } + }, + "reload": { + "fields": {} + } + }, + "zha": { + "permit": { + "fields": { + "duration": { + "default": 60, + "selector": { + "number": { + "min": 0.0, + "max": 254.0, + "unit_of_measurement": "seconds", + "step": 1.0, + "mode": "slider" + } + } + }, + "ieee": { + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "source_ieee": { + "example": "00:0a:bf:00:01:10:23:35", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "install_code": { + "example": "1234-5678-1234-5678-AABB-CCDD-AABB-CCDD-EEFF", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "qr_code": { + "example": "Z:000D6FFFFED4163B$I:52797BF4A5084DAA8E1712B61741CA024051", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "remove": { + "fields": { + "ieee": { + "required": true, + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "set_zigbee_cluster_attribute": { + "fields": { + "ieee": { + "required": true, + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "endpoint_id": { + "required": true, + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster_id": { + "required": true, + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "cluster_type": { + "default": "in", + "selector": { + "select": { + "options": [ + "in", + "out" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "attribute": { + "required": true, + "example": 0, + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "value": { + "required": true, + "example": 1, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "manufacturer": { + "example": 252, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "issue_zigbee_cluster_command": { + "fields": { + "ieee": { + "required": true, + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "endpoint_id": { + "required": true, + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "cluster_id": { + "required": true, + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "cluster_type": { + "default": "in", + "selector": { + "select": { + "options": [ + "in", + "out" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "command": { + "required": true, + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "command_type": { + "required": true, + "selector": { + "select": { + "options": [ + "client", + "server" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "args": { + "example": "[arg1, arg2, argN]", + "selector": { + "object": { + "multiple": false + } + } + }, + "params": { + "selector": { + "object": { + "multiple": false + } + } + }, + "manufacturer": { + "example": 252, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "issue_zigbee_group_command": { + "fields": { + "group": { + "required": true, + "example": 546, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "cluster_id": { + "required": true, + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "cluster_type": { + "default": "in", + "selector": { + "select": { + "options": [ + "in", + "out" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "command": { + "required": true, + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "step": 1.0, + "mode": "slider" + } + } + }, + "args": { + "example": "[arg1, arg2, argN]", + "selector": { + "object": { + "multiple": false + } + } + }, + "manufacturer": { + "example": 252, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + } + }, + "warning_device_squawk": { + "fields": { + "ieee": { + "required": true, + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "mode": { + "default": 0, + "selector": { + "number": { + "min": 0.0, + "max": 1.0, + "mode": "box", + "step": 1.0 + } + } + }, + "strobe": { + "default": 1, + "selector": { + "number": { + "min": 0.0, + "max": 1.0, + "mode": "box", + "step": 1.0 + } + } + }, + "level": { + "default": 2, + "selector": { + "number": { + "min": 0.0, + "max": 3.0, + "mode": "box", + "step": 1.0 + } + } + } + } + }, + "warning_device_warn": { + "fields": { + "ieee": { + "required": true, + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "mode": { + "default": 3, + "selector": { + "number": { + "min": 0.0, + "max": 6.0, + "mode": "box", + "step": 1.0 + } + } + }, + "strobe": { + "default": 1, + "selector": { + "number": { + "min": 0.0, + "max": 1.0, + "mode": "box", + "step": 1.0 + } + } + }, + "level": { + "default": 2, + "selector": { + "number": { + "min": 0.0, + "max": 3.0, + "mode": "box", + "step": 1.0 + } + } + }, + "duration": { + "default": 5, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "unit_of_measurement": "seconds", + "step": 1.0, + "mode": "slider" + } + } + }, + "duty_cycle": { + "default": 0, + "selector": { + "number": { + "min": 0.0, + "max": 100.0, + "step": 10.0, + "mode": "slider" + } + } + }, + "intensity": { + "default": 2, + "selector": { + "number": { + "min": 0.0, + "max": 3.0, + "mode": "box", + "step": 1.0 + } + } + } + } + }, + "set_lock_user_code": { + "fields": { + "code_slot": { + "required": true, + "example": 1, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "user_code": { + "required": true, + "example": 1234, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "lock" + ], + "integration": "zha" + } + ] + } + }, + "enable_lock_user_code": { + "fields": { + "code_slot": { + "required": true, + "example": 1, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "lock" + ], + "integration": "zha" + } + ] + } + }, + "disable_lock_user_code": { + "fields": { + "code_slot": { + "required": true, + "example": 1, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "lock" + ], + "integration": "zha" + } + ] + } + }, + "clear_lock_user_code": { + "fields": { + "code_slot": { + "required": true, + "example": 1, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "lock" + ], + "integration": "zha" + } + ] + } + } + }, + "lock": { + "unlock": { + "fields": { + "code": { + "example": 1234, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "lock" + ] + } + ] + } + }, + "lock": { + "fields": { + "code": { + "example": 1234, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "lock" + ] + } + ] + } + }, + "open": { + "fields": { + "code": { + "example": 1234, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "target": { + "entity": [ + { + "domain": [ + "lock" + ], + "supported_features": [ + 1 + ] + } + ] + } + } + }, + "zha_toolkit": { + "execute": { + "fields": { + "command": { + "name": "Command name", + "description": "Command name", + "example": "scan_device", + "required": true, + "selector": { + "select": { + "options": [ + "add_group", + "add_to_group", + "all_routes_and_neighbours", + "attr_read", + "attr_write", + "backup", + "bind_group", + "bind_ieee", + "binds_get", + "binds_remove_all", + "conf_report", + "conf_report_read", + "ezsp_add_key", + "ezsp_backup", + "ezsp_clear_keys", + "ezsp_get_config_value", + "ezsp_get_ieee_by_nwk", + "ezsp_get_keys", + "ezsp_get_policy", + "ezsp_get_token", + "ezsp_get_value", + "ezsp_set_channel", + "ezsp_start_mfg", + "get_groups", + "get_routes_and_neighbours", + "get_zll_groups", + "handle_join", + "ieee_ping", + "leave", + "misc_reinitialize", + "misc_settime", + "ota_notify", + "rejoin", + "remove_all_groups", + "remove_from_group", + "remove_group", + "scan_device", + "tuya_magic", + "unbind_coordinator", + "unbind_group", + "zcl_cmd", + "zdo_flood_parent_annce", + "zdo_join_with_code", + "zdo_scan_now", + "zdo_update_nwk_id", + "znp_backup", + "znp_nvram_backup", + "znp_nvram_reset", + "znp_nvram_restore", + "znp_restore" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "command_data": { + "name": "Command data", + "description": "data for the command (specific command. Example, second IEEE address for binding)", + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "manf": { + "name": "Manufacturer Id", + "description": "Manufacturer id (0 = No manufacturer id, empty=possibly automatic)", + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cmd": { + "name": "Command Id", + "description": "Command Id (zcl_cmd)", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "target endpoint", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "dst_endpoint": { + "name": "Destination Endpoint", + "description": "destination endpoint", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster": { + "name": "Target Cluster", + "description": "target cluster", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "attribute": { + "name": "Attribute Id or Name", + "description": "target attribute id (or name, accepted in most cases)", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "attr_type": { + "name": "Attribute Type", + "description": "Attribute type (to write, ...)", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "attr_val": { + "name": "Attribute Value", + "description": "Attribute value to write", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "min_interval": { + "name": "Minimum Report Interval", + "description": "Minimum report interval (seconds)", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "max_interval": { + "name": "Maximum Report Interval", + "description": "Maximum report interval (seconds)", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "reportable_change": { + "name": "Minimum Reportable Change", + "description": "Minimum change before reporting", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "dir": { + "name": "Direction", + "description": "Direction indicator, according to command", + "selector": { + "number": { + "min": 0.0, + "max": 1.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "state_id": { + "name": "State Id", + "description": "When defined, name of state to write the read attribute value to", + "example": "sensor.example", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "state_attr": { + "name": "State Attribute", + "description": "When defined, attribute in state_id to write the read attribute value to. Write to state value when missing (and state_id is defined)", + "example": "other_attr", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "state_value_template": { + "name": "State Value Template", + "description": "When defined, the read attribute is converted using this template before writing it to the state.", + "example": "value / 100", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "force_update": { + "name": "Force Update", + "description": "Force an update event when the state is written When not set or false, if the state value is unchanged, the update may not trigger an automation.\n", + "example": true, + "selector": { + "boolean": {} + } + }, + "use_cache": { + "name": "Use Cache", + "description": "Use zigpy attribute cache to get the value of an attribute. (Does not send a zigbee packet to read the attribute). Can also be 0, 1 or 2, where 2 has a special meaning with attr_write where it falls back to an actual read when the value is not in cache.\n", + "example": true, + "selector": { + "boolean": {} + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "allow_create": { + "name": "Allow Create", + "description": "Allow state creation (given by state_id) if it does not exist", + "selector": { + "boolean": {} + } + }, + "read_before_write": { + "name": "Read Before Write", + "description": "Read attribute before writing it (used with attr_write). When the read value matches the value to write, no write is done. Defaults to True.", + "selector": { + "boolean": {} + } + }, + "read_after_write": { + "name": "Read After Write", + "description": "Read attribute after writing. Can be used to ensure the values match. Defaults to True", + "selector": { + "boolean": {} + } + }, + "write_if_equal": { + "name": "Write If Equal", + "description": "Force writing the attribute even if the read attribute already matches. Defaults to False", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + }, + "csvout": { + "name": "CSV Filename", + "description": "Filename of CSV to write read data to. Written to \u0027csv\u0027 directory", + "example": "../web/mycsv.csv", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "csvlabel": { + "name": "CSV Label", + "description": "Label to use for read value (in CSV file)", + "example": "SecretAttributeName", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "description": "Execute ZHA Toolkit service (Examine the documentation or code to know which parameters are needed)", + "name": "Execute any zha toolkit service", + "response": { + "optional": true + } + }, + "add_group": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "endpoint to get information for (all endpoints when not set)", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "command_data": { + "name": "Group Id", + "description": "Group id to add", + "example": 2, + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + } + }, + "description": "Add group to endpoint groups list of device. May be equivalent to \u0060add_to_group\u0060", + "name": "Add Group", + "response": { + "optional": true + } + }, + "add_to_group": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "endpoint to remove group from (or all EP if not set)", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "command_data": { + "name": "Removed Group Id", + "description": "Group id to remove", + "example": 2, + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + } + }, + "description": "Add device to group", + "name": "Add device to group", + "response": { + "optional": true + } + }, + "all_routes_and_neighbours": { + "fields": { + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Scan for all routes and neighbours, results saved to config/scans/...", + "name": "Scan all Routes and Neighbours", + "response": { + "optional": true + } + }, + "attr_read": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "manf": { + "name": "Manufacturer Id", + "description": "Manufacturer id (0 = No manufacturer id, empty=possibly automatic)", + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "target endpoint", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster": { + "name": "Target Cluster", + "description": "target cluster", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "attribute": { + "name": "Attribute Id or Name", + "description": "target attribute id (or name, accepted in most cases)", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "state_id": { + "name": "State Id", + "description": "When defined, name of state to write the read attribute value to", + "example": "sensor.example", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "state_attr": { + "name": "State Attribute", + "description": "When defined, attribute in state_id to write the read attribute value to. Write to state value when missing (and state_id is defined)", + "example": "other_attr", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "state_value_template": { + "name": "State Value Template", + "description": "When defined, the read attribute is converted using this template before writing it to the state.", + "example": "value / 100", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "force_update": { + "name": "Force Update", + "description": "Force an update event when the state is written When not set or false, if the state value is unchanged, the update may not trigger an automation.\n", + "example": true, + "selector": { + "boolean": {} + } + }, + "use_cache": { + "name": "Use Cache", + "description": "Use zigpy attribute cache to get the value of an attribute. (Does not send a zigbee packet to read the attribute). Can also be 0, 1 or 2, where 2 has a special meaning where it falls back to an actual read when the value is not in cache.\n", + "example": true, + "selector": { + "boolean": {} + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "allow_create": { + "name": "Allow Create", + "description": "Allow state creation (given by state_id) if it does not exist", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + }, + "csvout": { + "name": "CSV Filename", + "description": "Filename of CSV to write read data to. Written to \u0027csv\u0027 directory", + "example": "../web/mycsv.csv", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "csvlabel": { + "name": "CSV Label", + "description": "Label to use for read value (in CSV file)", + "example": "SecretAttributeName", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "description": "Read Attribute", + "name": "Read Attribute", + "response": { + "optional": true + } + }, + "attr_write": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "manf": { + "name": "Manufacturer Id", + "description": "Manufacturer id (0 = No manufacturer id, empty=possibly automatic)", + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "target endpoint", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster": { + "name": "Target Cluster", + "description": "target cluster", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "attribute": { + "name": "Attribute Id or Name", + "description": "target attribute id (or name, accepted in most cases)", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "attr_type": { + "name": "Attribute Type", + "description": "Attribute type (to write, ...)", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "attr_val": { + "name": "Attribute Value", + "description": "Attribute value to write", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "use_cache": { + "name": "Use Cache", + "description": "Use zigpy attribute cache to get the value of an attribute. (Does not send a zigbee packet to read the attribute). Can also be 0, 1 or 2, where 2 has a special meaning where it falls back to an actual read (when reading before a write) when the value is not in cache.\n", + "example": true, + "selector": { + "boolean": {} + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "state_id": { + "name": "State Id", + "description": "When defined, name of state to write the read attribute value to", + "example": "sensor.example", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "state_attr": { + "name": "State Attribute", + "description": "When defined, attribute in state_id to write the read attribute value to. Write to state value when missing (and state_id is defined)", + "example": "other_attr", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "allow_create": { + "name": "Allow Create", + "description": "Allow state creation (given by state_id) if it does not exist", + "selector": { + "boolean": {} + } + }, + "read_before_write": { + "name": "Read Before Write", + "description": "Read attribute before writing it (used with attr_write). When the read value matches the value to write, no write is done. Defaults to True.", + "selector": { + "boolean": {} + } + }, + "read_after_write": { + "name": "Read After Write", + "description": "Read attribute after writing. Can be used to ensure the values match. Defaults to True", + "selector": { + "boolean": {} + } + }, + "write_if_equal": { + "name": "Write If Equal", + "description": "Force writing the attribute even if the read attribute already matches. Defaults to False", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + }, + "csvout": { + "name": "CSV Filename", + "description": "Filename of CSV to write read data to. Written to \u0027csv\u0027 directory", + "example": "../web/mycsv.csv", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "csvlabel": { + "name": "CSV Label", + "description": "Label to use for read value (in CSV file)", + "example": "SecretAttributeName", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "description": "Write Attribute", + "name": "Write Attribute", + "response": { + "optional": true + } + }, + "backup": { + "fields": { + "command_data": { + "name": "Backup File Suffix", + "description": "Suffix for backup file", + "example": "_bathroom_added", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Backup coordinator data (znp, bellows/ezsp)", + "name": "Backup Coordinator Data", + "response": { + "optional": true + } + }, + "bind_group": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "command_data": { + "name": "Target Binding Group", + "description": "Target group for binding", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "Target endpoint (when missing: all endpoints)", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster": { + "name": "Target Cluster", + "description": "Target cluster (when missing: all internally defined cluster)", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Bind clusters from ieee device to command_data device", + "name": "Bind Clusters From Device to Device", + "response": { + "optional": true + } + }, + "bind_ieee": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "command_data": { + "name": "Bind To Device Reference", + "description": "Binding target (Entity name, device name, or IEEE address of the node to execute command). By default: coordinator", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": false, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "Target endpoint (when missing: all endpoints)", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "dst_endpoint": { + "name": "Destination Endpoint", + "description": "Destination endpoint (when missing: first EP with matching cluster)", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster": { + "name": "Target Cluster", + "description": "Target cluster (or all internally defined ones)", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Bind clusters from ieee device to command_data device", + "name": "Bind Cluster", + "response": { + "optional": true + } + }, + "binds_get": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Get binding table from device.", + "name": "Get Binding Table", + "response": { + "optional": true + } + }, + "binds_remove_all": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "command_data": { + "name": "Remove Bindings with This Device", + "description": "When provided, remove only bindings towards this device (Entity name, device name, or IEEE address of the binding destination)", + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "When provided, remove only bindings for this endpoint or list of endpoints (single value or list. Example: 20 or [20, 30]) Otherwise: removes bindings for all endpoints", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster": { + "name": "Target Cluster", + "description": "When provided, remove only bindings for this cluster or list of clusters (single value or list. Example: 0x0200 or [0x200, 0x300]) Otherwise: removes bindings for all clusters", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Remove (Unbind) all bindings from device", + "name": "Remove All Bindings from Device", + "response": { + "optional": true + } + }, + "conf_report": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command\u0022", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "target endpoint", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster": { + "name": "Target Cluster", + "description": "target cluster", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "attribute": { + "name": "Attribute Id or Name", + "description": "target attribute id (or name, accepted in most cases)", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "min_interval": { + "name": "Minimum Report Interval", + "description": "Minimum report interval (seconds)", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "max_interval": { + "name": "Maximum Report Interval", + "description": "Maximum report interval (seconds)", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "reportable_change": { + "name": "Minimum Reportable Change", + "description": "Minimum change before reporting", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "manf": { + "name": "Manufacturer Id", + "description": "Manufacturer id (0 = No manufacturer id, empty=possibly automatic)", + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Configure attribute reporting. You can set a high value for tries (100 or more) for sleepy devices.\u0022", + "name": "Configure Attribute Reporting", + "response": { + "optional": true + } + }, + "conf_report_read": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command\u0022", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "target endpoint", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster": { + "name": "Target Cluster", + "description": "target cluster", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "attribute": { + "name": "Attribute Id or Name", + "description": "target attribute id (or name, accepted in most cases), can be a list", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "manf": { + "name": "Manufacturer Id", + "description": "Manufacturer id (0 = No manufacturer id, empty=possibly automatic)", + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Read attribute report configuration You can set a high value for tries (100 or more) for sleepy devices.\u0022", + "name": "Read Report Configuration", + "response": { + "optional": true + } + }, + "ezsp_add_key": { + "fields": {}, + "response": { + "optional": true + } + }, + "ezsp_backup": { + "fields": { + "command_data": { + "name": "Backup File Suffix", + "description": "Suffix for backup file", + "example": "_bathroom_added", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Backup coordinator data (bellows/ezsp)", + "name": "Backup Ezsp Coordinator", + "response": { + "optional": true + } + }, + "ezsp_clear_keys": { + "fields": {}, + "response": { + "optional": true + } + }, + "ezsp_get_config_value": { + "fields": {}, + "response": { + "optional": true + } + }, + "ezsp_get_ieee_by_nwk": { + "fields": {}, + "response": { + "optional": true + } + }, + "ezsp_get_keys": { + "fields": {}, + "response": { + "optional": true + } + }, + "ezsp_get_policy": { + "fields": {}, + "response": { + "optional": true + } + }, + "ezsp_get_token": { + "fields": {}, + "response": { + "optional": true + } + }, + "ezsp_get_value": { + "fields": {}, + "response": { + "optional": true + } + }, + "ezsp_set_channel": { + "fields": {}, + "response": { + "optional": true + } + }, + "ezsp_start_mfg": { + "fields": {}, + "response": { + "optional": true + } + }, + "get_groups": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "endpoint to get information for (all endpoints when not set)", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + } + }, + "description": "Get groups set on the endpoints of the device", + "name": "Get Groups Set On Endpoint", + "response": { + "optional": true + } + }, + "get_routes_and_neighbours": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Scan for all routes and neighbours, results saved to config/scans/...", + "name": "Scan Device\u0027s Routes and Neighbours", + "response": { + "optional": true + } + }, + "get_zll_groups": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + } + }, + "description": "Get groups for zll_cluster (if present)", + "name": "Get Groups for ZLL Cluster", + "response": { + "optional": true + } + }, + "ha_set_state": { + "fields": { + "attr_val": { + "name": "Attribute Value", + "description": "value to write to the state (or use in the template)", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "state_id": { + "name": "state_id", + "description": "Name of state to write the read attribute value to", + "example": "sensor.example", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "state_attr": { + "name": "State Attribute", + "description": "When defined, attribute in state_id to write the read attribute value to. Write to state value when missing (and state_id is defined)", + "example": "other_attr", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "state_value_template": { + "name": "State Value Template", + "description": "When defined, used as a template expression. For example \u0022value \u002B 10\u0022 will be internally interpreted as \u0022{{ value \u002B 10 }}\u0022 where \u0027value\u0027 is substituted with the value for \u0027attr_val\u0027", + "example": "value \u002B 10", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "allow_create": { + "name": "Allow Create", + "description": "Allow state creation (given by state_id) if it does not exist", + "selector": { + "boolean": {} + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "csvout": { + "name": "CSV Filename", + "description": "Filename of CSV to write the update state information to. Written to \u0027csv\u0027 directory.", + "example": "../web/mystatecsv.csv", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "csvlabel": { + "name": "CSV Label", + "description": "Label to designate value written (in CSV file)", + "example": "Updated from zha_toolkit.ha_set_state", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "description": "Set/update a Home Assistant state", + "name": "Set/Update Home Assistant State", + "response": { + "optional": true + } + }, + "zha_devices": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Optional Entity name, device name, or IEEE address of the device to provide details for. Defaults to all devices", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": false, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "command_data": { + "name": "Selected Fields", + "description": "Selected Fields", + "example": [ + "ieee", + "lqi", + "name" + ], + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "csvout": { + "name": "CSV Filename", + "description": "Filename of CSV to write read data to. Written to \u0027csv\u0027 directory (can be relative as in example).", + "example": "../web/mycsv.csv", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "csvlabel": { + "name": "CSV Sort Column", + "description": "Column to sort table by", + "example": "lqi", + "selector": { + "select": { + "options": [ + "ieee", + "nwk", + "manufacturer", + "model", + "name", + "quirk_applied", + "quirk_class", + "manufacturer_code", + "power_source", + "lqi", + "rssi", + "last_seen", + "available", + "device_type", + "user_given_name", + "device_reg_id", + "area_id" + ], + "custom_value": false, + "sort": false, + "multiple": false + } + } + }, + "json_out": { + "name": "JSON Filename", + "description": "Filename of JSON to write read data to. Written to \u0027/config/json\u0027 directory", + "required": false, + "example": "zha_devices.json", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "json_timestamp": { + "name": "JSON Timestamp", + "description": "Add timestamp to Filename of JSON file. Defaults to False.", + "required": false, + "example": true, + "selector": { + "boolean": {} + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + } + }, + "description": "Export device information (Response, CSV File, JSON File, Event)", + "name": "Get/Export Device Information", + "response": { + "optional": true + } + }, + "handle_join": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "command_data": { + "name": "Short Network Address", + "description": "Short network address of the device (optional, if known in ZHA)", + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + } + }, + "description": "Handle join (ZHA should re-interrogate the device as on new join)", + "name": "Handle Join", + "response": { + "optional": true + } + }, + "ieee_ping": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Ping: Requests IEEE address (using the known NWK Address)", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Ping device", + "name": "Ping Device", + "response": { + "optional": true + } + }, + "leave": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to leave the network", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Send a Leave request to the device", + "name": "Send Leave Request", + "response": { + "optional": true + } + }, + "misc_reinitialize": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command\u0022", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + } + }, + "description": "Reinitialize device", + "name": "Reinitialize Device", + "response": { + "optional": true + } + }, + "misc_settime": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "target endpoint", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "read_before_write": { + "name": "Read Before Write", + "description": "Read attributes before writing them", + "selector": { + "boolean": {} + } + }, + "read_after_write": { + "name": "Read After Write", + "description": "Read attribute after writing. Can be used to ensure the values match. Defaults to True", + "selector": { + "boolean": {} + } + }, + "csvout": { + "name": "CSV Filename", + "description": "Filename of CSV to write read data to. Written to \u0027csv\u0027 directory", + "example": "../web/mycsv.csv", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + } + }, + "description": "Set Time Cluster attributes (Time, DST - except TimeStatus)", + "name": "Set Time", + "response": { + "optional": true + } + }, + "ota_notify": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "entity.name_of_zigbee_device", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "download": { + "name": "Enable Firmware Download", + "description": "When True, download FW from KKoenk\u0027s list that possibly matches devices.", + "selector": { + "boolean": {} + } + }, + "path": { + "name": "Firmware Directory", + "description": "Path to write ota image(s) to (defaults to zha:zigpy_config:ota:otau_directory value or /config/zigpy_ota)", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "ota_notify_success", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "ota_notify_fail", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the images were updated and the device notified (either success or failure).", + "example": "ota_notify_done", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Notify a device that an update is available, after triggering ota image providers to fetch new images.", + "name": "Trigger Device\u0027s Firmware Update", + "response": { + "optional": true + } + }, + "rejoin": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to request rejoin", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "command_data": { + "name": "Node to send the Rejoin", + "description": "Node used to accept the rejoin (Entity name, device name, or IEEE address of the node)", + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Send a rejoin request to the device (=leave with rejoin)", + "name": "Send Rejoin Request", + "response": { + "optional": true + } + }, + "register_services": { + "fields": {}, + "description": "Reregister zha-toolkit services Useful during development when they are updated in __init__.py", + "name": "Register Services", + "response": { + "optional": true + } + }, + "remove_all_groups": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "endpoint to remove group from (all endpoints when not set)", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + } + }, + "description": "Remove all groups from (selected) endpoints on device", + "name": "Remove All Groups from Endpoint", + "response": { + "optional": true + } + }, + "remove_from_group": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "endpoint to remove group from (or all EP if not set)", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "command_data": { + "name": "Group Id", + "description": "Group id to remove", + "example": 2, + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + } + }, + "description": "Remove device endpoints from group", + "name": "Remove Endpoints from Group", + "response": { + "optional": true + } + }, + "remove_group": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "endpoint to remove group from (or all EP if not set)", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "command_data": { + "name": "Group Id", + "description": "Group id to remove", + "example": 2, + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + } + }, + "description": "Remove group from endpoint groups list of device. May be equivalent to \u0060remove_from_group\u0060", + "name": "Remove Group from Endpoint", + "response": { + "optional": true + } + }, + "scan_device": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "Target endpoint, or list of endpoints", + "example": 1, + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times a zigbee packet is repeated when no response", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Scan device (result written to file in /config/scans)", + "name": "Scan Device", + "response": { + "optional": true + } + }, + "tuya_magic": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Do Tuya magic spell (= make most Tuya devices work normally)", + "name": "Cast Tuya Magic Spell", + "response": { + "optional": true + } + }, + "unbind_coordinator": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to execute command", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "When provided, remove only bindings for this endpoint or list of endpoints (single value or list. Example: 20 or [20, 30]) Otherwise: removes bindings for all endpoints", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster": { + "name": "Target Cluster", + "description": "When provided, remove only bindings for this cluster or list of clusters (single value or list. Example: 0x0200 or [0x200, 0x300]) Otherwise: removes bindings for all clusters", + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Remove (Unbind) all bindings from device to the coordinator (your HA Instance)", + "name": "Remove Bindings to Coordinator", + "response": { + "optional": true + } + }, + "unbind_group": { + "fields": {}, + "response": { + "optional": true + } + }, + "zcl_cmd": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to send\\ command to", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "manf": { + "name": "Manufacturer Id", + "description": "Manufacturer id (0 = No manufacturer id, empty=possibly automatic)", + "selector": { + "number": { + "min": 1.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "endpoint": { + "name": "Target Endpoint", + "description": "target endpoint", + "selector": { + "number": { + "min": 1.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cluster": { + "name": "Target Cluster", + "description": "target cluster", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 65535.0, + "mode": "box", + "step": 1.0 + } + } + }, + "cmd": { + "name": "Command Id", + "description": "Command Id to execute", + "required": true, + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "args": { + "name": "Command Arguments", + "description": "Arguments for command when needed (as per zigpy\u0027s definition corresponding to Zigbee Library Cluster (ZCL) specification)", + "example": [ + 1, + "abcd", + 3 + ], + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "kwargs": { + "name": "Command Keyword Arguments", + "description": "Keyword arguments for command", + "example": { + "code": "cool_code" + }, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "tries": { + "name": "Tries", + "description": "Number of times the zigbee packet should be attempted", + "selector": { + "number": { + "min": 0.0, + "max": 255.0, + "mode": "box", + "step": 1.0 + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Send cluster command", + "name": "Send Cluster Command", + "response": { + "optional": true + } + }, + "zdo_flood_parent_annce": { + "fields": {}, + "response": { + "optional": true + } + }, + "zdo_join_with_code": { + "fields": { + "ieee": { + "name": "Device Reference", + "description": "Entity name, device name, or IEEE address of the node to request rejoin", + "example": "00:0d:6f:00:05:7d:2d:34", + "required": true, + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "command_data": { + "name": "Device accepting the Join", + "description": "Node used to accept the rejoin (Entity name, device name, or IEEE address of the node)", + "example": "00:0d:6f:00:05:7d:2d:34", + "selector": { + "entity": { + "integration": "zha", + "multiple": false, + "reorder": false + } + } + }, + "code": { + "name": "Code", + "description": "The code the device needs to present", + "example": "01234567", + "required": true, + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Allow a device to join with a code (bellows radio type only)", + "name": "Allow a device to join with a code", + "response": { + "optional": true + } + }, + "zdo_scan_now": { + "fields": {}, + "response": { + "optional": true + } + }, + "zdo_update_nwk_id": { + "fields": {}, + "response": { + "optional": true + } + }, + "znp_backup": { + "fields": { + "command_data": { + "name": "Backup File Suffix", + "description": "Suffix for backup file", + "example": "_bathroom_added", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_success": { + "name": "Success Event Name", + "description": "Event name in case of success", + "example": "my_read_success_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_fail": { + "name": "Fail Event Name", + "description": "Event name in case of failure", + "example": "my_read_fail_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "event_done": { + "name": "Done Event Name", + "description": "Event name when the service call did all its work (either success or failure). Has event data with relevant attributes.", + "example": "my_read_done_trigger_event", + "selector": { + "text": { + "multiline": false, + "multiple": false + } + } + }, + "fail_exception": { + "name": "Exception When Failure", + "description": "Throw exception when success==False, useful to stop scripts, automations", + "selector": { + "boolean": {} + } + }, + "expect_reply": { + "name": "Expect Reply", + "description": "Wait for/expect a reply (not used yet)", + "selector": { + "boolean": {} + } + } + }, + "description": "Backup coordinator data (znp, bellows/ezsp)", + "name": "Backup ZNP Coordinator", + "response": { + "optional": true + } + }, + "znp_nvram_backup": { + "fields": {}, + "response": { + "optional": true + } + }, + "znp_nvram_reset": { + "fields": {}, + "response": { + "optional": true + } + }, + "znp_nvram_restore": { + "fields": {}, + "response": { + "optional": true + } + }, + "znp_restore": { + "fields": {}, + "response": { + "optional": true + } + } + } +} \ No newline at end of file diff --git a/HomeAssistant.Server/appsettings.json b/HomeAssistant.Server/appsettings.json index 49722cf..773d9a2 100644 --- a/HomeAssistant.Server/appsettings.json +++ b/HomeAssistant.Server/appsettings.json @@ -6,7 +6,10 @@ "System.Net.Http.HttpClient": "Warning", "NordPoolManager": "Information", "PowerMonitorManager": "Information", - "BoilerMonitorManager": "Information" + "BoilerMonitorManager": "Information", + "ShowerMonitorManager": "Information", + "LightMonitorManager": "Information", + "BatteryMonitorManager": "Information" } }, "WriteTo": [ @@ -34,6 +37,33 @@ "Enabled": true, "CleanupEntitiesOnStartup": false }, + "ShowerMonitor": { + "Enabled": true, + "CleanupEntitiesOnStartup": false, + "BathroomHumidityEntityId": "sensor.bathroom_humidity", + "MainHomeHumidityEntityId": "sensor.main_home_humidity", + "BathroomTemperatureEntityId": "sensor.bathroom_temperature", + "ExhaustFanEntityId": "switch.exhaust_fan", + "PollIntervalSeconds": 30, + "SpikeRateThreshold": 4.0, + "MinDifferentialHumidity": 8.0, + "PeakHumidityThreshold": 58.0, + "ConfirmationWindowMinutes": 2, + "RecoveryDifferentialThreshold": 5.0, + "MaxShowerDurationMinutes": 60, + "FanRunAfterShowerMinutes": 10, + "RateWindowSize": 5 + }, + "LightMonitor": { + "Enabled": true, + "LightEntityId": "light.sonoff_1002214d40", + "SunEntityId": "sun.sun", + "PersonEntityIds": ["person.marius", "person.erika", "person.home_phone"] + }, + "BatteryMonitor": { + "Enabled": true, + "BatteryThresholdPercent": 5 + }, "PowerMonitor": { "Enabled": false, "MainMeterEntityId": "sensor.sonoff_100267d63f_power", diff --git a/HomeAssistant.Server/program.cs b/HomeAssistant.Server/program.cs index 9887b6d..565c88b 100644 --- a/HomeAssistant.Server/program.cs +++ b/HomeAssistant.Server/program.cs @@ -19,6 +19,12 @@ using NordPoolManager.Interface; using NordPoolManager.Models; using PowerMonitorManager; using PowerMonitorManager.Models; +using ShowerMonitorManager; +using ShowerMonitorManager.Models; +using LightMonitorManager; +using LightMonitorManager.Models; +using BatteryMonitorManager; +using BatteryMonitorManager.Models; #pragma warning disable CA1812 @@ -53,6 +59,12 @@ try .AddPowerMonitor(context.Configuration) .Configure(context.Configuration.GetSection(BoilerMonitorOptions.SectionName)) .AddBoilerMonitor(context.Configuration) + .Configure(context.Configuration.GetSection(ShowerMonitorOptions.SectionName)) + .AddShowerMonitor(context.Configuration) + .Configure(context.Configuration.GetSection(LightMonitorOptions.SectionName)) + .AddLightMonitor(context.Configuration) + .Configure(context.Configuration.GetSection(BatteryMonitorOptions.SectionName)) + .AddBatteryMonitor(context.Configuration) ) .Build() .RunAsync() diff --git a/HomeAssistantSDK.sln b/HomeAssistantSDK.sln index 5858ef8..1fbb38c 100644 --- a/HomeAssistantSDK.sln +++ b/HomeAssistantSDK.sln @@ -30,6 +30,28 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Testing", "Testing", "{95E9 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Models", "Models", "{48492269-2B47-43FE-BC14-A901054EE5AE}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.McpServer", "HomeAssistant.McpServer\HomeAssistant.McpServer.csproj", "{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Models", "ShowerMonitor.Models\ShowerMonitor.Models.csproj", "{DAD0BDF9-2A6D-48AD-B714-38D237E97285}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Manager", "ShowerMonitor.Manager\ShowerMonitor.Manager.csproj", "{8D05B406-B94B-4D6B-8221-831485AF6702}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Manager.Tests", "ShowerMonitor.Manager.Tests\ShowerMonitor.Manager.Tests.csproj", "{A9DFB47D-7736-428C-9459-22AFC5CF3A38}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Models", "LightMonitor.Models\LightMonitor.Models.csproj", "{B14E51EB-7D5C-44FA-8674-4B4796459978}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager", "LightMonitor.Manager\LightMonitor.Manager.csproj", "{9165EDEF-2FE2-4578-849B-B4D4089416DA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager.Tests", "LightMonitor.Manager.Tests\LightMonitor.Manager.Tests.csproj", "{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.HistoryReplay", "HomeAssistant.HistoryReplay\HomeAssistant.HistoryReplay.csproj", "{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Models", "BatteryMonitor.Models\BatteryMonitor.Models.csproj", "{2D27B621-7B92-4014-8FDF-6AD376C97612}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager", "BatteryMonitor.Manager\BatteryMonitor.Manager.csproj", "{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager.Tests", "BatteryMonitor.Manager.Tests\BatteryMonitor.Manager.Tests.csproj", "{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -196,17 +218,151 @@ Global {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x64.Build.0 = Release|Any CPU {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.ActiveCfg = Release|Any CPU {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.Build.0 = Release|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x64.ActiveCfg = Debug|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x64.Build.0 = Debug|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x86.ActiveCfg = Debug|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x86.Build.0 = Debug|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|Any CPU.Build.0 = Release|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x64.ActiveCfg = Release|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x64.Build.0 = Release|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x86.ActiveCfg = Release|Any CPU + {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x86.Build.0 = Release|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x64.ActiveCfg = Debug|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x64.Build.0 = Debug|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x86.ActiveCfg = Debug|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x86.Build.0 = Debug|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|Any CPU.Build.0 = Release|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x64.ActiveCfg = Release|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x64.Build.0 = Release|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x86.ActiveCfg = Release|Any CPU + {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x86.Build.0 = Release|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x64.ActiveCfg = Debug|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x64.Build.0 = Debug|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x86.ActiveCfg = Debug|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x86.Build.0 = Debug|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Release|Any CPU.Build.0 = Release|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x64.ActiveCfg = Release|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x64.Build.0 = Release|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x86.ActiveCfg = Release|Any CPU + {8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x86.Build.0 = Release|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x64.ActiveCfg = Debug|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x64.Build.0 = Debug|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x86.ActiveCfg = Debug|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x86.Build.0 = Debug|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|Any CPU.Build.0 = Release|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x64.ActiveCfg = Release|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x64.Build.0 = Release|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x86.ActiveCfg = Release|Any CPU + {A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x86.Build.0 = Release|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x64.ActiveCfg = Debug|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x64.Build.0 = Debug|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x86.ActiveCfg = Debug|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x86.Build.0 = Debug|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|Any CPU.Build.0 = Release|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x64.ActiveCfg = Release|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x64.Build.0 = Release|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x86.ActiveCfg = Release|Any CPU + {B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x86.Build.0 = Release|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x64.ActiveCfg = Debug|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x64.Build.0 = Debug|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x86.ActiveCfg = Debug|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x86.Build.0 = Debug|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|Any CPU.Build.0 = Release|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x64.ActiveCfg = Release|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x64.Build.0 = Release|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x86.ActiveCfg = Release|Any CPU + {9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x86.Build.0 = Release|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x64.ActiveCfg = Debug|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x64.Build.0 = Debug|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x86.ActiveCfg = Debug|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x86.Build.0 = Debug|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|Any CPU.Build.0 = Release|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x64.ActiveCfg = Release|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x64.Build.0 = Release|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.ActiveCfg = Release|Any CPU + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.Build.0 = Release|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x64.ActiveCfg = Debug|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x64.Build.0 = Debug|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x86.ActiveCfg = Debug|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x86.Build.0 = Debug|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|Any CPU.Build.0 = Release|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x64.ActiveCfg = Release|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x64.Build.0 = Release|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x86.ActiveCfg = Release|Any CPU + {EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x86.Build.0 = Release|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.ActiveCfg = Debug|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.Build.0 = Debug|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x86.ActiveCfg = Debug|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x86.Build.0 = Debug|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|Any CPU.Build.0 = Release|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x64.ActiveCfg = Release|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x64.Build.0 = Release|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x86.ActiveCfg = Release|Any CPU + {2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x86.Build.0 = Release|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x64.ActiveCfg = Debug|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x64.Build.0 = Debug|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x86.ActiveCfg = Debug|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x86.Build.0 = Debug|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|Any CPU.Build.0 = Release|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x64.ActiveCfg = Release|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x64.Build.0 = Release|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x86.ActiveCfg = Release|Any CPU + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x86.Build.0 = Release|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x64.ActiveCfg = Debug|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x64.Build.0 = Debug|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x86.ActiveCfg = Debug|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x86.Build.0 = Debug|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|Any CPU.Build.0 = Release|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x64.ActiveCfg = Release|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x64.Build.0 = Release|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x86.ActiveCfg = Release|Any CPU + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C} = {95E98121-7DA4-4085-A8E3-B0430628452F} - {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C} = {95E98121-7DA4-4085-A8E3-B0430628452F} - {1F613F65-5F3C-41E6-B86B-774301D80E42} = {95E98121-7DA4-4085-A8E3-B0430628452F} - {D1FDF2F0-E8D2-4F00-95CA-1759047EA205} = {48492269-2B47-43FE-BC14-A901054EE5AE} {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {D1FDF2F0-E8D2-4F00-95CA-1759047EA205} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C} = {95E98121-7DA4-4085-A8E3-B0430628452F} {2C0E9D45-3E34-4A60-A6B5-1E89B935419D} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {1F613F65-5F3C-41E6-B86B-774301D80E42} = {95E98121-7DA4-4085-A8E3-B0430628452F} {72331F53-884D-42A1-8EEA-8CC83FFAB623} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C} = {95E98121-7DA4-4085-A8E3-B0430628452F} + {B14E51EB-7D5C-44FA-8674-4B4796459978} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {B8303C3E-785C-48F0-8F40-D4A9E9D50C92} = {95E98121-7DA4-4085-A8E3-B0430628452F} EndGlobalSection EndGlobal diff --git a/LightMonitor.Manager.Tests/LightControlServiceTests.cs b/LightMonitor.Manager.Tests/LightControlServiceTests.cs new file mode 100644 index 0000000..8afde48 --- /dev/null +++ b/LightMonitor.Manager.Tests/LightControlServiceTests.cs @@ -0,0 +1,117 @@ +using FluentAssertions; +using LightMonitor.Models; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using LightMonitorManager; +using LightMonitorManager.Models; + +namespace LightMonitor.Manager.Tests; + +public class LightControlServiceTests +{ + private const string LightEntityId = "light.sonoff_1002214d40"; + private const string SunEntityId = "sun.sun"; + + private readonly LightMonitorOptions _defaultOptions = new() + { + LightEntityId = LightEntityId, + SunEntityId = SunEntityId + }; + + private readonly Mock _haContextMock = new(); + + private LightControlService CreateService(LightMonitorOptions? options = null) + { + return new LightControlService( + _haContextMock.Object, + Mock.Of>(), + Options.Create(options ?? _defaultOptions)); + } + + [Fact] + public void TurnOnLight_WhenDarkAndLightIsOff_ShouldTurnOnLight() + { + _haContextMock.Setup(x => x.GetState(SunEntityId)) + .Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon }); + _haContextMock.Setup(x => x.GetState(LightEntityId)) + .Returns(new EntityState { State = "off" }); + + var service = CreateService(); + service.TurnOnLight(); + + _haContextMock.Verify(x => x.CallService("light", "turn_on", + It.IsAny(), It.IsAny()), Times.Once); + } + + [Fact] + public void TurnOnLight_WhenDarkAndLightIsAlreadyOn_ShouldNotCallService() + { + _haContextMock.Setup(x => x.GetState(SunEntityId)) + .Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon }); + _haContextMock.Setup(x => x.GetState(LightEntityId)) + .Returns(new EntityState { State = "on" }); + + var service = CreateService(); + service.TurnOnLight(); + + _haContextMock.Verify(x => x.CallService("light", "turn_on", + It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public void TurnOnLight_WhenSunIsAboveHorizon_ShouldNotTurnOnLight() + { + _haContextMock.Setup(x => x.GetState(SunEntityId)) + .Returns(new EntityState { State = LightMonitorConsts.SunAboveHorizon }); + + var service = CreateService(); + service.TurnOnLight(); + + _haContextMock.Verify(x => x.CallService("light", "turn_on", + It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public void TurnOnLight_WhenSunStateIsNull_ShouldNotTurnOnLight() + { + _haContextMock.Setup(x => x.GetState(SunEntityId)) + .Returns((EntityState?)null); + + var service = CreateService(); + service.TurnOnLight(); + + _haContextMock.Verify(x => x.CallService("light", "turn_on", + It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public void TurnOnLight_WhenSunStateIsUnavailable_ShouldNotTurnOnLight() + { + _haContextMock.Setup(x => x.GetState(SunEntityId)) + .Returns(new EntityState { State = "unavailable" }); + + var service = CreateService(); + service.TurnOnLight(); + + _haContextMock.Verify(x => x.CallService("light", "turn_on", + It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public void TurnOnLight_WhenLightStateIsNull_ShouldTurnOnLight() + { + _haContextMock.Setup(x => x.GetState(SunEntityId)) + .Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon }); + _haContextMock.Setup(x => x.GetState(LightEntityId)) + .Returns((EntityState?)null); + + var service = CreateService(); + service.TurnOnLight(); + + _haContextMock.Verify(x => x.CallService("light", "turn_on", + It.IsAny(), It.IsAny()), Times.Once); + } +} diff --git a/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj b/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj new file mode 100644 index 0000000..81dc668 --- /dev/null +++ b/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj @@ -0,0 +1,34 @@ + + + + net10.0 + enable + enable + false + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/LightMonitor.Manager.Tests/PresenceServiceTests.cs b/LightMonitor.Manager.Tests/PresenceServiceTests.cs new file mode 100644 index 0000000..7fc7c4b --- /dev/null +++ b/LightMonitor.Manager.Tests/PresenceServiceTests.cs @@ -0,0 +1,146 @@ +using FluentAssertions; +using LightMonitor.Models; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using LightMonitorManager; +using LightMonitorManager.Models; + +namespace LightMonitor.Manager.Tests; + +public class PresenceServiceTests +{ + private readonly Mock _haContextMock = new(); + + private readonly LightMonitorOptions _defaultOptions = new() + { + PersonEntityIds = ["person.marius", "person.erika", "person.home_phone"] + }; + + private PresenceService CreateService(LightMonitorOptions? options = null) + { + return new PresenceService( + _haContextMock.Object, + Mock.Of>(), + Options.Create(options ?? _defaultOptions)); + } + + [Fact] + public void IsAnyoneHome_WhenOnePersonIsHome_ShouldReturnTrue() + { + _haContextMock.Setup(x => x.GetState("person.marius")) + .Returns(new EntityState { State = "home" }); + _haContextMock.Setup(x => x.GetState("person.erika")) + .Returns(new EntityState { State = "not_home" }); + _haContextMock.Setup(x => x.GetState("person.home_phone")) + .Returns(new EntityState { State = "not_home" }); + + var service = CreateService(); + + service.IsAnyoneHome().Should().BeTrue(); + } + + [Fact] + public void IsAnyoneHome_WhenAllPersonsAreHome_ShouldReturnTrue() + { + _haContextMock.Setup(x => x.GetState("person.marius")) + .Returns(new EntityState { State = "home" }); + _haContextMock.Setup(x => x.GetState("person.erika")) + .Returns(new EntityState { State = "home" }); + _haContextMock.Setup(x => x.GetState("person.home_phone")) + .Returns(new EntityState { State = "home" }); + + var service = CreateService(); + + service.IsAnyoneHome().Should().BeTrue(); + } + + [Fact] + public void IsAnyoneHome_WhenNoPersonIsHome_ShouldReturnFalse() + { + _haContextMock.Setup(x => x.GetState("person.marius")) + .Returns(new EntityState { State = "not_home" }); + _haContextMock.Setup(x => x.GetState("person.erika")) + .Returns(new EntityState { State = "not_home" }); + _haContextMock.Setup(x => x.GetState("person.home_phone")) + .Returns(new EntityState { State = "not_home" }); + + var service = CreateService(); + + service.IsAnyoneHome().Should().BeFalse(); + } + + [Fact] + public void IsAnyoneHome_WhenStateIsUnavailable_ShouldSkipAndReturnFalse() + { + _haContextMock.Setup(x => x.GetState("person.marius")) + .Returns(new EntityState { State = "unavailable" }); + _haContextMock.Setup(x => x.GetState("person.erika")) + .Returns(new EntityState { State = "unknown" }); + _haContextMock.Setup(x => x.GetState("person.home_phone")) + .Returns((EntityState?)null); + + var service = CreateService(); + + service.IsAnyoneHome().Should().BeFalse(); + } + + [Fact] + public void IsAnyoneHome_WhenStateIsNull_ShouldSkipAndReturnFalse() + { + _haContextMock.Setup(x => x.GetState("person.marius")) + .Returns((EntityState?)null); + _haContextMock.Setup(x => x.GetState("person.erika")) + .Returns((EntityState?)null); + _haContextMock.Setup(x => x.GetState("person.home_phone")) + .Returns((EntityState?)null); + + var service = CreateService(); + + service.IsAnyoneHome().Should().BeFalse(); + } + + [Fact] + public void IsAnyoneHome_WhenMixedStatesWithOneHome_ShouldReturnTrue() + { + _haContextMock.Setup(x => x.GetState("person.marius")) + .Returns(new EntityState { State = "unavailable" }); + _haContextMock.Setup(x => x.GetState("person.erika")) + .Returns(new EntityState { State = "home" }); + _haContextMock.Setup(x => x.GetState("person.home_phone")) + .Returns((EntityState?)null); + + var service = CreateService(); + + service.IsAnyoneHome().Should().BeTrue(); + } + + [Theory] + [InlineData("HOME")] + [InlineData("Home")] + [InlineData("home")] + public void IsAnyoneHome_CaseInsensitiveHomeState_ShouldReturnTrue(string homeState) + { + _haContextMock.Setup(x => x.GetState("person.marius")) + .Returns(new EntityState { State = homeState }); + _haContextMock.Setup(x => x.GetState("person.erika")) + .Returns(new EntityState { State = "not_home" }); + _haContextMock.Setup(x => x.GetState("person.home_phone")) + .Returns(new EntityState { State = "not_home" }); + + var service = CreateService(); + + service.IsAnyoneHome().Should().BeTrue(); + } + + [Fact] + public void IsAnyoneHome_WithEmptyPersonList_ShouldReturnFalse() + { + var options = new LightMonitorOptions { PersonEntityIds = [] }; + var service = CreateService(options); + + service.IsAnyoneHome().Should().BeFalse(); + } +} diff --git a/LightMonitor.Manager/Interface/ILightControlService.cs b/LightMonitor.Manager/Interface/ILightControlService.cs new file mode 100644 index 0000000..7a3e62d --- /dev/null +++ b/LightMonitor.Manager/Interface/ILightControlService.cs @@ -0,0 +1,6 @@ +namespace LightMonitorManager.Interface; + +public interface ILightControlService +{ + void TurnOnLight(); +} diff --git a/LightMonitor.Manager/Interface/ILightMonitorInit.cs b/LightMonitor.Manager/Interface/ILightMonitorInit.cs new file mode 100644 index 0000000..badbe4d --- /dev/null +++ b/LightMonitor.Manager/Interface/ILightMonitorInit.cs @@ -0,0 +1,6 @@ +namespace LightMonitorManager.Interface; + +public interface ILightMonitorInit +{ + Task InitializeAsync(); +} diff --git a/LightMonitor.Manager/Interface/IPresenceService.cs b/LightMonitor.Manager/Interface/IPresenceService.cs new file mode 100644 index 0000000..3efdffd --- /dev/null +++ b/LightMonitor.Manager/Interface/IPresenceService.cs @@ -0,0 +1,6 @@ +namespace LightMonitorManager.Interface; + +public interface IPresenceService +{ + bool IsAnyoneHome(); +} diff --git a/LightMonitor.Manager/LightControlService.cs b/LightMonitor.Manager/LightControlService.cs new file mode 100644 index 0000000..caa5471 --- /dev/null +++ b/LightMonitor.Manager/LightControlService.cs @@ -0,0 +1,48 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using LightMonitor.Models; +using LightMonitorManager.Interface; +using LightMonitorManager.Models; + +namespace LightMonitorManager; + +public sealed class LightControlService : ILightControlService +{ + private readonly IHaContext _haContext; + private readonly ILogger _logger; + private readonly LightMonitorOptions _options; + + public LightControlService( + IHaContext haContext, + ILogger logger, + IOptions options) + { + _haContext = haContext; + _logger = logger; + _options = options.Value; + } + + public void TurnOnLight() + { + var sunState = _haContext.GetState(_options.SunEntityId)?.State; + + if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) + { + _logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState); + return; + } + + var lightState = _haContext.GetState(_options.LightEntityId)?.State; + + if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase)) + { + _logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId); + return; + } + + _haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId)); + _logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId); + } +} diff --git a/LightMonitor.Manager/LightMonitor.Manager.csproj b/LightMonitor.Manager/LightMonitor.Manager.csproj new file mode 100644 index 0000000..660f934 --- /dev/null +++ b/LightMonitor.Manager/LightMonitor.Manager.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + enable + enable + LightMonitorManager + + + + + <_Parameter1>LightMonitor.Manager.Tests + + + + + + + + + + + + + + diff --git a/LightMonitor.Manager/LightMonitorInit.cs b/LightMonitor.Manager/LightMonitorInit.cs new file mode 100644 index 0000000..c296016 --- /dev/null +++ b/LightMonitor.Manager/LightMonitorInit.cs @@ -0,0 +1,105 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NetDaemon.AppModel; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using LightMonitor.Models; +using LightMonitorManager.Interface; +using LightMonitorManager.Models; + +namespace LightMonitorManager; + +[NetDaemonApp] +public sealed class LightMonitorInit : ILightMonitorInit +{ + private readonly IHaContext _haContext; + private readonly ILogger _logger; + private readonly IPresenceService _presenceService; + private readonly ILightControlService _lightControlService; + private readonly LightMonitorOptions _options; + + public LightMonitorInit( + IHaContext haContext, + ILogger logger, + IPresenceService presenceService, + ILightControlService lightControlService, + IOptions options) + { + _haContext = haContext; + _logger = logger; + _presenceService = presenceService; + _lightControlService = lightControlService; + _options = options.Value; + + _ = InitializeAsync(); + } + + public Task InitializeAsync() + { + try + { + SubscribeToSunStateChanges(); + SubscribeToPersonStateChanges(); + _logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons", _options.PersonEntityIds.Length); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during LightMonitor initialization"); + } + + return Task.CompletedTask; + } + + private void SubscribeToSunStateChanges() + { + var sunEntity = new Entity(_haContext, _options.SunEntityId); + sunEntity.StateChanges() + .Subscribe(e => + { + try + { + if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + _logger.LogInformation("Sun went below horizon, checking if anyone is home"); + + if (_presenceService.IsAnyoneHome()) + { + _lightControlService.TurnOnLight(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Error handling sun state change"); + } + }); + } + + private void SubscribeToPersonStateChanges() + { + foreach (var personEntityId in _options.PersonEntityIds) + { + var personEntity = new Entity(_haContext, personEntityId); + personEntity.StateChanges() + .Subscribe(e => + { + try + { + if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + _logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", personEntityId); + _lightControlService.TurnOnLight(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error handling person state change for {EntityId}", personEntityId); + } + }); + } + } +} diff --git a/LightMonitor.Manager/LightMonitorServiceRegistration.cs b/LightMonitor.Manager/LightMonitorServiceRegistration.cs new file mode 100644 index 0000000..1f4a875 --- /dev/null +++ b/LightMonitor.Manager/LightMonitorServiceRegistration.cs @@ -0,0 +1,29 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NetDaemon.AppModel; +using LightMonitorManager.Interface; +using LightMonitorManager.Models; + +namespace LightMonitorManager; + +public static class LightMonitorServiceRegistration +{ + public static IServiceCollection AddLightMonitor(this IServiceCollection services, IConfiguration configuration) + { + var options = configuration + .GetSection(LightMonitorOptions.SectionName) + .Get() ?? new LightMonitorOptions(); + + if (!options.Enabled) + { + return services; + } + + services + .AddNetDaemonApp() + .AddScoped() + .AddScoped(); + + return services; + } +} diff --git a/LightMonitor.Manager/Models/LightMonitorOptions.cs b/LightMonitor.Manager/Models/LightMonitorOptions.cs new file mode 100644 index 0000000..829a41a --- /dev/null +++ b/LightMonitor.Manager/Models/LightMonitorOptions.cs @@ -0,0 +1,13 @@ +using static LightMonitor.Models.LightMonitorConsts; + +namespace LightMonitorManager.Models; + +public sealed class LightMonitorOptions +{ + public const string SectionName = "LightMonitor"; + + public bool Enabled { get; set; } + public string LightEntityId { get; set; } = DefaultLightEntityId; + public string SunEntityId { get; set; } = DefaultSunEntityId; + public string[] PersonEntityIds { get; set; } = DefaultPersonEntityIds; +} diff --git a/LightMonitor.Manager/PresenceService.cs b/LightMonitor.Manager/PresenceService.cs new file mode 100644 index 0000000..c0da4ce --- /dev/null +++ b/LightMonitor.Manager/PresenceService.cs @@ -0,0 +1,48 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NetDaemon.HassModel; +using LightMonitor.Models; +using LightMonitorManager.Interface; +using LightMonitorManager.Models; + +namespace LightMonitorManager; + +public sealed class PresenceService : IPresenceService +{ + private readonly IHaContext _haContext; + private readonly ILogger _logger; + private readonly LightMonitorOptions _options; + + public PresenceService( + IHaContext haContext, + ILogger logger, + IOptions options) + { + _haContext = haContext; + _logger = logger; + _options = options.Value; + } + + public bool IsAnyoneHome() + { + foreach (var personEntityId in _options.PersonEntityIds) + { + var state = _haContext.GetState(personEntityId); + + if (state?.State is null or "unavailable" or "unknown") + { + _logger.LogDebug("Person entity {EntityId} state unavailable", personEntityId); + continue; + } + + if (string.Equals(state.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) + { + _logger.LogDebug("Person {EntityId} is home", personEntityId); + return true; + } + } + + _logger.LogDebug("No person is currently home"); + return false; + } +} diff --git a/LightMonitor.Models/LightMonitor.Models.csproj b/LightMonitor.Models/LightMonitor.Models.csproj new file mode 100644 index 0000000..6b50cba --- /dev/null +++ b/LightMonitor.Models/LightMonitor.Models.csproj @@ -0,0 +1,18 @@ + + + + net10.0 + enable + enable + LightMonitor.Models + + + + + + + + + + + diff --git a/LightMonitor.Models/LightMonitorConsts.cs b/LightMonitor.Models/LightMonitorConsts.cs new file mode 100644 index 0000000..508f3ea --- /dev/null +++ b/LightMonitor.Models/LightMonitorConsts.cs @@ -0,0 +1,19 @@ +namespace LightMonitor.Models; + +public static class LightMonitorConsts +{ + public const string DefaultLightEntityId = "light.sonoff_1002214d40"; + public const string DefaultSunEntityId = "sun.sun"; + + public static readonly string[] DefaultPersonEntityIds = + [ + "person.marius", + "person.erika", + "person.home_phone" + ]; + + public const string SunBelowHorizon = "below_horizon"; + public const string SunAboveHorizon = "above_horizon"; + public const string PersonHomeState = "home"; + public const string LightOnState = "on"; +} diff --git a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs index 3b5885c..3a3e36a 100644 --- a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs +++ b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs @@ -30,7 +30,7 @@ public class CheapestIntervalsFinderTests { Start = start, End = start.AddMinutes(15), - Price = 5.0 + i * 0.5 + Price = 4.93 + i * 0.22 }); } @@ -61,7 +61,7 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); var prices = CreatePricesForDay(dayStart); var deadline = dayStart.AddDays(1); @@ -77,8 +77,8 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 15.0, 2.0, 8.0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); + var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92, 5.63, 13.26); var deadline = dayStart.AddDays(1); // Act @@ -87,9 +87,9 @@ public class CheapestIntervalsFinderTests // Assert result.Should().HaveCount(3); var sortedByRank = result.OrderBy(r => r.Rank).ToList(); - sortedByRank[0].Price.Should().Be(1.0); - sortedByRank[1].Price.Should().Be(2.0); - sortedByRank[2].Price.Should().Be(3.0); + sortedByRank[0].Price.Should().Be(4.93); + sortedByRank[1].Price.Should().Be(5.63); + sortedByRank[2].Price.Should().Be(6.20); } [Fact] @@ -97,17 +97,17 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 10.0, 5.0, 1.0, 8.0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); + var prices = CreatePricesWithValues(dayStart, 17.91, 8.96, 4.93, 13.26); var deadline = dayStart.AddDays(1); // Act var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline); // Assert - var cheapest = result.Single(r => r.Price == 1.0); + var cheapest = result.Single(r => r.Price == 4.93); cheapest.Rank.Should().Be(1); - var secondCheapest = result.Single(r => r.Price == 5.0); + var secondCheapest = result.Single(r => r.Price == 8.96); secondCheapest.Rank.Should().Be(2); } @@ -116,8 +116,8 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); + var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96); var deadline = dayStart.AddDays(1); // Act @@ -132,8 +132,8 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 0.5, 0.1, 0.2); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); + var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 2.50, 1.80, 3.20); var deadline = dayStart.AddMinutes(75); // 1h15m = covers intervals 0-4 (end of interval 4 = 75min) // Act @@ -149,33 +149,33 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 15.0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); + var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92); var deadline = dayStart.AddDays(1); // Act - var result = sut.FindCheapestIntervals(prices, 10, 6.0, deadline); + var result = sut.FindCheapestIntervals(prices, 10, 10.0, deadline); // Assert result.Should().HaveCount(3); - result.Should().OnlyContain(r => r.Price <= 6.0); + result.Should().OnlyContain(r => r.Price <= 10.0); } [Fact] public void FindCheapestIntervals_WithMaxPriceCap_ShouldIncludeAllIntervalsBeforeDeadline() { - // Arrange: prices 10, 3, 7, 1, 5, 15 - with cap 6.0 only 3 would qualify; with double.MaxValue all qualify + // Arrange: realistic ct/kWh samples — with double.MaxValue all six intervals qualify var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 15.0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); + var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92); var deadline = dayStart.AddDays(1); // Act var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline); - // Assert: all 6 intervals are eligible, we take 4 cheapest: 1, 3, 5, 7 + // Assert: all 6 intervals are eligible, we take 4 cheapest by price result.Should().HaveCount(4); - result.Select(r => r.Price).OrderBy(p => p).Should().ContainInOrder(1.0, 3.0, 5.0, 7.0); + result.Select(r => r.Price).OrderBy(p => p).Should().ContainInOrder(4.93, 6.20, 8.96, 12.50); } [Fact] @@ -183,16 +183,16 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 0.5); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); + var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 2.50); var deadline = dayStart.AddMinutes(75); // Act - var result = sut.FindCheapestIntervals(prices, 10, 6.0, deadline); + var result = sut.FindCheapestIntervals(prices, 2, 10.0, deadline); // Assert - result.Should().HaveCount(3); - result.Should().OnlyContain(r => r.End <= deadline && r.Price <= 6.0); + result.Should().HaveCount(2); + result.Should().OnlyContain(r => r.End <= deadline && r.Price <= 10.0); } [Fact] @@ -230,7 +230,7 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); var prices = CreatePricesForDay(dayStart); var deadline = dayStart.AddDays(1); @@ -246,7 +246,7 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); var prices = CreatePricesForDay(dayStart); var deadline = dayStart.AddDays(1); @@ -262,8 +262,8 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 3.0, 5.0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); + var prices = CreatePricesWithValues(dayStart, 6.20, 8.96); var deadline = dayStart.AddDays(1); // Act @@ -278,12 +278,12 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 10.0, 20.0, 15.0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); + var prices = CreatePricesWithValues(dayStart, 17.91, 24.92, 22.44); var deadline = dayStart.AddDays(1); // Act - var result = sut.FindCheapestIntervals(prices, 4, 5.0, deadline); + var result = sut.FindCheapestIntervals(prices, 4, 10.0, deadline); // Assert result.Should().BeEmpty(); @@ -294,9 +294,9 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 12, 0, 0); - var prices = CreatePricesWithValues(dayStart, 1.0, 2.0, 3.0); - var deadline = new DateTime(2026, 2, 26, 10, 0, 0); + var dayStart = new DateTime(2026, 3, 31, 12, 0, 0); + var prices = CreatePricesWithValues(dayStart, 4.93, 5.63, 6.20); + var deadline = new DateTime(2026, 3, 31, 10, 0, 0); // Act var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline); @@ -310,8 +310,8 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 5.0, 5.0, 5.0, 5.0, 5.0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); + var prices = CreatePricesWithValues(dayStart, 12.50, 12.50, 12.50, 12.50, 12.50); var deadline = dayStart.AddDays(1); // Act @@ -319,7 +319,7 @@ public class CheapestIntervalsFinderTests // Assert result.Should().HaveCount(3); - result.Should().OnlyContain(r => r.Price == 5.0); + result.Should().OnlyContain(r => r.Price == 12.50); } [Fact] @@ -327,16 +327,16 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 2, 26, 0, 0, 0); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); var prices = new NordPoolPrice { Prices = new List { - new() { Start = dayStart, End = dayStart.AddMinutes(15), Price = 5.0 }, + new() { Start = dayStart, End = dayStart.AddMinutes(15), Price = 8.96 }, new() { Start = dayStart.AddMinutes(15), End = dayStart.AddMinutes(30), Price = null }, - new() { Start = dayStart.AddMinutes(30), End = dayStart.AddMinutes(45), Price = 3.0 }, - new() { Start = null, End = dayStart.AddMinutes(60), Price = 1.0 }, - new() { Start = dayStart.AddMinutes(60), End = null, Price = 2.0 } + new() { Start = dayStart.AddMinutes(30), End = dayStart.AddMinutes(45), Price = 6.20 }, + new() { Start = null, End = dayStart.AddMinutes(60), Price = 4.93 }, + new() { Start = dayStart.AddMinutes(60), End = null, Price = 5.63 } } }; var deadline = dayStart.AddDays(1); @@ -357,10 +357,10 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var now = new DateTime(2026, 2, 26, 10, 7, 0); + var now = new DateTime(2026, 3, 31, 10, 7, 0); var intervals = new List { - new() { Start = new DateTime(2026, 2, 26, 10, 0, 0), End = new DateTime(2026, 2, 26, 10, 15, 0), Price = 5.0, Rank = 1 } + new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 } }; // Act @@ -375,10 +375,10 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var now = new DateTime(2026, 2, 26, 10, 0, 0); + var now = new DateTime(2026, 3, 31, 10, 0, 0); var intervals = new List { - new() { Start = new DateTime(2026, 2, 26, 10, 0, 0), End = new DateTime(2026, 2, 26, 10, 15, 0), Price = 5.0, Rank = 1 } + new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 } }; // Act @@ -393,10 +393,10 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var now = new DateTime(2026, 2, 26, 10, 15, 0); + var now = new DateTime(2026, 3, 31, 10, 15, 0); var intervals = new List { - new() { Start = new DateTime(2026, 2, 26, 10, 0, 0), End = new DateTime(2026, 2, 26, 10, 15, 0), Price = 5.0, Rank = 1 } + new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 } }; // Act @@ -411,11 +411,11 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var now = new DateTime(2026, 2, 26, 12, 0, 0); + var now = new DateTime(2026, 3, 31, 12, 0, 0); var intervals = new List { - new() { Start = new DateTime(2026, 2, 26, 10, 0, 0), End = new DateTime(2026, 2, 26, 10, 15, 0), Price = 5.0, Rank = 1 }, - new() { Start = new DateTime(2026, 2, 26, 14, 0, 0), End = new DateTime(2026, 2, 26, 14, 15, 0), Price = 3.0, Rank = 2 } + new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 }, + new() { Start = new DateTime(2026, 3, 31, 14, 0, 0), End = new DateTime(2026, 3, 31, 14, 15, 0), Price = 6.20, Rank = 2 } }; // Act diff --git a/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs b/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs index a603720..1a2f7ee 100644 --- a/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs +++ b/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs @@ -9,7 +9,7 @@ public class CompactNordPoolDayPriceTests { private const int IntervalDurationSeconds = MinutesPerInterval * 60; - private static readonly DateTime TestStart = new(2026, 3, 19, 10, 0, 0, DateTimeKind.Utc); + private static readonly DateTime TestStart = new(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc); private static readonly DateTime TestEnd = TestStart.AddMinutes(MinutesPerInterval); private static readonly long TestStartEpoch = new DateTimeOffset(TestStart).ToUnixTimeSeconds(); private static readonly long TestEndEpoch = new DateTimeOffset(TestEnd).ToUnixTimeSeconds(); @@ -17,19 +17,19 @@ public class CompactNordPoolDayPriceTests [Fact] public void FromDayPrice_ShouldConvertDateTimesToUnixEpochSeconds() { - var dayPrice = new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = 12.35 }; + var dayPrice = new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = 17.91 }; var result = CompactNordPoolDayPrice.FromDayPrice(dayPrice); result.Start.Should().Be(TestStartEpoch); result.End.Should().Be(TestEndEpoch); - result.Price.Should().Be(12.35); + result.Price.Should().Be(17.91); } [Fact] public void FromDayPrice_WhenStartIsNull_ShouldUseZeroEpoch() { - var dayPrice = new NordPoolDayPrice { Start = null, End = TestEnd, Price = 5.0 }; + var dayPrice = new NordPoolDayPrice { Start = null, End = TestEnd, Price = 8.96 }; var result = CompactNordPoolDayPrice.FromDayPrice(dayPrice); @@ -40,7 +40,7 @@ public class CompactNordPoolDayPriceTests [Fact] public void FromDayPrice_WhenEndIsNull_ShouldUseZeroEpoch() { - var dayPrice = new NordPoolDayPrice { Start = TestStart, End = null, Price = 5.0 }; + var dayPrice = new NordPoolDayPrice { Start = TestStart, End = null, Price = 8.96 }; var result = CompactNordPoolDayPrice.FromDayPrice(dayPrice); @@ -51,9 +51,9 @@ public class CompactNordPoolDayPriceTests [Fact] public void FromDayPrice_WhenDateTimeKindIsLocal_ShouldConvertToUtcWithoutThrowing() { - var localStart = new DateTime(2026, 3, 19, 12, 0, 0, DateTimeKind.Local); - var localEnd = new DateTime(2026, 3, 19, 12, 15, 0, DateTimeKind.Local); - var dayPrice = new NordPoolDayPrice { Start = localStart, End = localEnd, Price = 10.0 }; + var localStart = new DateTime(2026, 3, 31, 12, 0, 0, DateTimeKind.Local); + var localEnd = new DateTime(2026, 3, 31, 12, 15, 0, DateTimeKind.Local); + var dayPrice = new NordPoolDayPrice { Start = localStart, End = localEnd, Price = 12.50 }; var act = () => CompactNordPoolDayPrice.FromDayPrice(dayPrice); @@ -66,9 +66,9 @@ public class CompactNordPoolDayPriceTests [Fact] public void FromDayPrice_WhenDateTimeKindIsUnspecified_ShouldConvertWithoutThrowing() { - var unspecifiedStart = new DateTime(2026, 3, 19, 12, 0, 0, DateTimeKind.Unspecified); - var unspecifiedEnd = new DateTime(2026, 3, 19, 12, 15, 0, DateTimeKind.Unspecified); - var dayPrice = new NordPoolDayPrice { Start = unspecifiedStart, End = unspecifiedEnd, Price = 10.0 }; + var unspecifiedStart = new DateTime(2026, 3, 31, 12, 0, 0, DateTimeKind.Unspecified); + var unspecifiedEnd = new DateTime(2026, 3, 31, 12, 15, 0, DateTimeKind.Unspecified); + var dayPrice = new NordPoolDayPrice { Start = unspecifiedStart, End = unspecifiedEnd, Price = 12.50 }; var act = () => CompactNordPoolDayPrice.FromDayPrice(dayPrice); @@ -92,12 +92,12 @@ public class CompactNordPoolDayPriceTests { Start = TestStartEpoch, End = TestEndEpoch, - Price = 12.35 + Price = 17.91 }; var json = JsonSerializer.Serialize(compact); - json.Should().Be($"[{TestStartEpoch},{TestEndEpoch},12.35]"); + json.Should().Be($"[{TestStartEpoch},{TestEndEpoch},17.91]"); } [Fact] @@ -122,7 +122,7 @@ public class CompactNordPoolDayPriceTests { Start = TestStartEpoch, End = TestEndEpoch, - Price = 12.35 + Price = 17.91 }; var json = JsonSerializer.Serialize(original); @@ -138,13 +138,13 @@ public class CompactNordPoolDayPriceTests { var prices = new List { - new() { Start = TestStartEpoch, End = TestEndEpoch, Price = 10.0 }, - new() { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 11.0 } + new() { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 }, + new() { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 } }; var json = JsonSerializer.Serialize(prices); - json.Should().Be($"[[{TestStartEpoch},{TestEndEpoch},10],[{TestEndEpoch},{TestEndEpoch + IntervalDurationSeconds},11]]"); + json.Should().Be($"[[{TestStartEpoch},{TestEndEpoch},12.5],[{TestEndEpoch},{TestEndEpoch + IntervalDurationSeconds},13.26]]"); } [Fact] @@ -184,16 +184,16 @@ public class CompactNordPoolDayPriceTests { var prices = new List { - new() { Start = TestStart, End = TestEnd, Price = 10.0 }, - new() { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 11.0 } + new() { Start = TestStart, End = TestEnd, Price = 12.50 }, + new() { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 } }; var result = prices.ToCompact(); result.Should().HaveCount(2); result[0].Start.Should().Be(TestStartEpoch); - result[0].Price.Should().Be(10.0); - result[1].Price.Should().Be(11.0); + result[0].Price.Should().Be(12.50); + result[1].Price.Should().Be(13.26); } [Fact] @@ -220,7 +220,7 @@ public class CompactNordPoolDayPriceTests public void SerializedSize_WithMaxEntries_ShouldBeUnderHaAttributeLimit() { const int haAttributeByteLimitBytes = 16_384; - var dayStart = new DateTime(2026, 3, 19, 0, 0, 0, DateTimeKind.Utc); + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); var prices = new List(); for (var i = 0; i < MaxExpectedPriceEntries; i++) @@ -230,7 +230,7 @@ public class CompactNordPoolDayPriceTests { Start = start, End = start.AddMinutes(MinutesPerInterval), - Price = 10.0 + i * 0.01 + Price = 4.93 + i * 0.22 }); } diff --git a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs index 34dfa81..e82e87d 100644 --- a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs @@ -318,7 +318,7 @@ public class NordPoolEntityServiceTests #region UpdateEntitiesAsync private static EntityUpdateContext CreateDefaultContext( - double currentPrice = 12.5, + double currentPrice = 17.91, NordPoolPrice? todayPrice = null, NordPoolPrice? tomorrowPrice = null) { @@ -331,18 +331,18 @@ public class NordPoolEntityServiceTests UsingCachedData = false, TodayNordPoolPrice = todayPrice ?? new NordPoolPrice { - Prices = new List { new() { Price = 10.0 } } + Prices = new List { new() { Price = 12.50 } } }, TomorrowNordPoolPrice = tomorrowPrice ?? new NordPoolPrice { - Prices = new List { new() { Price = 20.0 } } + Prices = new List { new() { Price = 18.71 } } }, CheapestIntervals = [], - ConfiguredHours = 1.0, + ConfiguredHours = 2.0, ConfiguredIntervalCount = 4, - ConfiguredPriceCap = 100.0, + ConfiguredPriceCap = 25.0, SkipPriceCap = false, - ConfiguredReadyBy = "06:00", + ConfiguredReadyBy = "18:00", IsNowCheap = false, NextCheapIntervalStart = null }; @@ -364,7 +364,7 @@ public class NordPoolEntityServiceTests // Assert _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "12.50"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "17.91"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "1"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "1"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => s.Contains('-') && s.Contains(':'))), Times.Once); @@ -421,21 +421,21 @@ public class NordPoolEntityServiceTests public async Task UpdateEntitiesAsync_WithTodayAndTomorrowPrices_ShouldUpdateCombinedSensor() { // Arrange - var todayStart = new DateTime(2025, 3, 16, 6, 0, 0, DateTimeKind.Utc); - var tomorrowStart = new DateTime(2025, 3, 17, 6, 0, 0, DateTimeKind.Utc); + var todayStart = new DateTime(2026, 3, 31, 6, 0, 0, DateTimeKind.Utc); + var tomorrowStart = new DateTime(2026, 4, 1, 6, 0, 0, DateTimeKind.Utc); var todayPrice = new NordPoolPrice { Prices = [ - new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 15.0 }, - new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 10.0 } + new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 }, + new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 12.50 } ] }; var tomorrowPrice = new NordPoolPrice { Prices = [ - new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 20.0 } + new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 } ] }; var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice); @@ -467,7 +467,7 @@ public class NordPoolEntityServiceTests // Arrange var todayPrice = new NordPoolPrice { - Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddMinutes(15), Price = 12.0 }] + Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddMinutes(15), Price = 17.91 }] }; var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] }); @@ -496,7 +496,7 @@ public class NordPoolEntityServiceTests // Arrange var tomorrowPrice = new NordPoolPrice { - Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow.AddDays(1), End = DateTime.UtcNow.AddDays(1).AddMinutes(15), Price = 18.0 }] + Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow.AddDays(1), End = DateTime.UtcNow.AddDays(1).AddMinutes(15), Price = 18.71 }] }; var context = CreateDefaultContext(todayPrice: new NordPoolPrice { Prices = [] }, tomorrowPrice: tomorrowPrice); @@ -527,9 +527,9 @@ public class NordPoolEntityServiceTests { Prices = [new NordPoolDayPrice { - Start = new DateTime(2026, 3, 19, 10, 0, 0, DateTimeKind.Utc), - End = new DateTime(2026, 3, 19, 10, 15, 0, DateTimeKind.Utc), - Price = 12.0 + Start = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc), + End = new DateTime(2026, 3, 31, 10, 15, 0, DateTimeKind.Utc), + Price = 17.91 }] }; var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] }); @@ -555,21 +555,21 @@ public class NordPoolEntityServiceTests // Arrange const int intervalsPerDay = 96; const int haAttributeByteLimitBytes = 16_384; - var todayStart = new DateTime(2026, 3, 19, 0, 0, 0, DateTimeKind.Utc); - var tomorrowStart = new DateTime(2026, 3, 20, 0, 0, 0, DateTimeKind.Utc); + var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); + var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc); var todayPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice { Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), - Price = 5.0 + i * 0.1 + Price = 4.93 + i * 0.22 }).ToList(); var tomorrowPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice { Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), - Price = 8.0 + i * 0.1 + Price = 5.50 + i * 0.22 }).ToList(); object? capturedAttributes = null; diff --git a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs index 53413f7..37f7916 100644 --- a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs @@ -40,7 +40,7 @@ public class NordPoolPriceServiceTests public void GetTimeQuarterIndex_ShouldReturnCorrectIndex(int hour, int minute, int expectedIndex) { // Arrange - var testDate = new DateTime(2026, 2, 3, hour, minute, 0, DateTimeKind.Utc); + var testDate = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc); // Act var result = NordPoolPriceService.GetTimeQuarterIndex(testDate); @@ -58,7 +58,7 @@ public class NordPoolPriceServiceTests public void GetTimeQuarterIndex_ShouldHandleAllHoursCorrectly(int hour, int minute, int expectedIndex) { // Arrange - var testDate = new DateTime(2026, 2, 3, hour, minute, 0, DateTimeKind.Utc); + var testDate = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc); // Act var result = NordPoolPriceService.GetTimeQuarterIndex(testDate); @@ -71,7 +71,7 @@ public class NordPoolPriceServiceTests public void GetTimeQuarterIndex_AtExactMidnight_ShouldReturnIndex4() { // Arrange - var testDate = new DateTime(2026, 2, 3, 0, 0, 0, DateTimeKind.Utc); + var testDate = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); // Act var result = NordPoolPriceService.GetTimeQuarterIndex(testDate); @@ -84,7 +84,7 @@ public class NordPoolPriceServiceTests public void GetTimeQuarterIndex_AtEndOfDay_ShouldReturnIndex95() { // Arrange - var testDate = new DateTime(2026, 2, 3, 22, 45, 0, DateTimeKind.Utc); + var testDate = new DateTime(2026, 3, 31, 22, 45, 0, DateTimeKind.Utc); // Act var result = NordPoolPriceService.GetTimeQuarterIndex(testDate); @@ -97,8 +97,8 @@ public class NordPoolPriceServiceTests public void GetTimeQuarterIndex_WithSeconds_ShouldIgnoreSeconds() { // Arrange - var withoutSeconds = new DateTime(2026, 2, 3, 12, 0, 0, DateTimeKind.Utc); - var withSeconds = new DateTime(2026, 2, 3, 12, 0, 59, DateTimeKind.Utc); + var withoutSeconds = new DateTime(2026, 3, 31, 12, 0, 0, DateTimeKind.Utc); + var withSeconds = new DateTime(2026, 3, 31, 12, 0, 59, DateTimeKind.Utc); // Act var result1 = NordPoolPriceService.GetTimeQuarterIndex(withoutSeconds); @@ -117,7 +117,7 @@ public class NordPoolPriceServiceTests { for (var minute = 0; minute < 60; minute += 15) { - var date = new DateTime(2026, 2, 3, hour, minute, 0, DateTimeKind.Utc); + var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc); var index = NordPoolPriceService.GetTimeQuarterIndex(date); indices.Add(index); } @@ -285,9 +285,9 @@ public class NordPoolPriceServiceTests { Prices = new List { - new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 100.0 }, - new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 200.0 }, - new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 150.0 } + new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }, + new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 }, + new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 } } }; @@ -297,9 +297,9 @@ public class NordPoolPriceServiceTests // Assert result.Should().NotBeNull(); result.Prices.Should().HaveCount(3); - result.Prices![0].Price.Should().BeApproximately(12.1, 0.01); - result.Prices![1].Price.Should().BeApproximately(24.2, 0.01); - result.Prices![2].Price.Should().BeApproximately(18.15, 0.01); + result.Prices![0].Price.Should().BeApproximately(9.80, 0.01); + result.Prices![1].Price.Should().BeApproximately(17.91, 0.01); + result.Prices![2].Price.Should().BeApproximately(26.02, 0.01); } [Fact] @@ -310,9 +310,9 @@ public class NordPoolPriceServiceTests { Prices = new List { - new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 100.0 }, + new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }, new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }, - new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 150.0 } + new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 } } }; @@ -344,14 +344,14 @@ public class NordPoolPriceServiceTests public void AdjustedNordPoolPrice_ShouldPreserveDateTimes() { // Arrange - var startTime = new DateTime(2026, 2, 3, 10, 0, 0, DateTimeKind.Utc); - var endTime = new DateTime(2026, 2, 3, 11, 0, 0, DateTimeKind.Utc); + var startTime = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc); + var endTime = new DateTime(2026, 3, 31, 11, 0, 0, DateTimeKind.Utc); var inputPrice = new NordPoolPrice { Prices = new List { - new() { Start = startTime, End = endTime, Price = 100.0 } + new() { Start = startTime, End = endTime, Price = 81.0 } } }; @@ -408,7 +408,7 @@ public class NordPoolPriceServiceTests { Prices = new List { - new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 100.0 } + new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 } } }; @@ -416,7 +416,7 @@ public class NordPoolPriceServiceTests var result = _sut.AdjustedNordPoolPrice(inputPrice); // Assert - inputPrice.Prices[0].Price.Should().Be(100.0); + inputPrice.Prices[0].Price.Should().Be(81.0); result.Prices.Should().NotBeSameAs(inputPrice.Prices); } @@ -437,7 +437,7 @@ public class NordPoolPriceServiceTests { Start = now.AddMinutes(i * 15), End = now.AddMinutes((i + 1) * 15), - Price = 10.0 + i + Price = 5.0 + i * 0.22 }); } @@ -494,17 +494,17 @@ public class NordPoolPriceServiceTests var prices = new List(); for (var i = 0; i < 96; i++) - prices.Add(new NordPoolDayPrice { Price = 42.0 + i }); + prices.Add(new NordPoolDayPrice { Price = 4.0 + i * 0.23 }); _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.DayQuartersIndex = expectedIndex; - _sut.CurrentPrice = 99.99; + _sut.CurrentPrice = 17.91; // Act var result = _sut.UpdateCurrentPrice(); // Assert - result.Should().Be(99.99); + result.Should().Be(17.91); } [Fact] @@ -516,14 +516,14 @@ public class NordPoolPriceServiceTests prices.Add(new NordPoolDayPrice { Price = null }); _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; - _sut.CurrentPrice = 55.0; + _sut.CurrentPrice = 17.91; _sut.DayQuartersIndex = -1; // Act var result = _sut.UpdateCurrentPrice(); // Assert - result.Should().Be(55.0); + result.Should().Be(17.91); } [Fact] @@ -532,7 +532,7 @@ public class NordPoolPriceServiceTests // Arrange var prices = new List(); for (var i = 0; i < 96; i++) - prices.Add(new NordPoolDayPrice { Price = 10.0 + i }); + prices.Add(new NordPoolDayPrice { Price = 5.0 + i * 0.22 }); _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.DayQuartersIndex = -1; @@ -566,7 +566,7 @@ public class NordPoolPriceServiceTests _sut.LastFetchedDate = today.AddDays(-1); _sut.TodayNordPoolPrice = new NordPoolPrice { - Prices = new List { new() { Price = 10.0 } } + Prices = new List { new() { Price = 12.50 } } }; // Act @@ -585,7 +585,7 @@ public class NordPoolPriceServiceTests _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = null }; _sut.TomorrowNordPoolPrice = new NordPoolPrice { - Prices = new List { new() { Price = 10.0 } } + Prices = new List { new() { Price = 12.50 } } }; // Act @@ -604,7 +604,7 @@ public class NordPoolPriceServiceTests _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = new List() }; _sut.TomorrowNordPoolPrice = new NordPoolPrice { - Prices = new List { new() { Price = 10.0 } } + Prices = new List { new() { Price = 12.50 } } }; // Act @@ -622,11 +622,11 @@ public class NordPoolPriceServiceTests _sut.LastFetchedDate = today; _sut.TodayNordPoolPrice = new NordPoolPrice { - Prices = new List { new() { Price = 10.0 } } + Prices = new List { new() { Price = 12.50 } } }; _sut.TomorrowNordPoolPrice = new NordPoolPrice { - Prices = new List { new() { Price = 20.0 } } + Prices = new List { new() { Price = 18.71 } } }; // Act diff --git a/NordPool.Manager/NordPool.Manager.csproj b/NordPool.Manager/NordPool.Manager.csproj index d312c73..71d81e5 100644 --- a/NordPool.Manager/NordPool.Manager.csproj +++ b/NordPool.Manager/NordPool.Manager.csproj @@ -21,8 +21,8 @@ - - + + diff --git a/NordPool.Models/NordPool.Models.csproj b/NordPool.Models/NordPool.Models.csproj index da34f94..92fdafe 100644 --- a/NordPool.Models/NordPool.Models.csproj +++ b/NordPool.Models/NordPool.Models.csproj @@ -1,4 +1,4 @@ - + net10.0 @@ -7,7 +7,7 @@ - + diff --git a/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs b/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs index 822c06d..dba782a 100644 --- a/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs +++ b/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs @@ -24,15 +24,15 @@ public class OtherPowerCalculationServiceTests var sut = CreateSut(smoothingWindowSize: 1); var devices = new Dictionary { - ["sensor.device_a_power"] = 500, - ["sensor.device_b_power"] = 300 + ["sensor.sonoff_100215c534_power"] = 8.55, + ["sensor.sonoff_10018909cb_power"] = 36.93 }; - var result = sut.Calculate(1000, devices); + var result = sut.Calculate(341.97, devices); - result.TotalPowerWatts.Should().Be(1000); - result.KnownDevicesSumWatts.Should().Be(800); - result.RawOtherPowerWatts.Should().Be(200); + result.TotalPowerWatts.Should().Be(341.97); + result.KnownDevicesSumWatts.Should().BeApproximately(45.48, 0.01); + result.RawOtherPowerWatts.Should().BeApproximately(296.49, 0.01); result.DataQuality.Should().Be("ok"); } @@ -42,11 +42,11 @@ public class OtherPowerCalculationServiceTests var sut = CreateSut(smoothingWindowSize: 1); var devices = new Dictionary { - ["sensor.device_a_power"] = 800, - ["sensor.device_b_power"] = 500 + ["sensor.sonoff_100215c534_power"] = 200.0, + ["sensor.sonoff_10018909cb_power"] = 180.0 }; - var result = sut.Calculate(1000, devices); + var result = sut.Calculate(341.97, devices); result.RawOtherPowerWatts.Should().Be(0); result.SmoothedOtherPowerWatts.Should().Be(0); @@ -59,9 +59,9 @@ public class OtherPowerCalculationServiceTests var sut = CreateSut(smoothingWindowSize: 1); var devices = new Dictionary(); - var result = sut.Calculate(1500, devices); + var result = sut.Calculate(341.97, devices); - result.RawOtherPowerWatts.Should().Be(1500); + result.RawOtherPowerWatts.Should().Be(341.97); result.KnownDevicesSumWatts.Should().Be(0); } @@ -71,15 +71,15 @@ public class OtherPowerCalculationServiceTests var sut = CreateSut(smoothingWindowSize: 1); var devices = new Dictionary { - ["sensor.a"] = 100, - ["sensor.b"] = 200 + ["sensor.sonoff_100215c534_power"] = 8.55, + ["sensor.sonoff_10018909cb_power"] = 36.93 }; - var result = sut.Calculate(500, devices); + var result = sut.Calculate(341.97, devices); result.DevicePowerReadings.Should().HaveCount(2); - result.DevicePowerReadings["sensor.a"].Should().Be(100); - result.DevicePowerReadings["sensor.b"].Should().Be(200); + result.DevicePowerReadings["sensor.sonoff_100215c534_power"].Should().Be(8.55); + result.DevicePowerReadings["sensor.sonoff_10018909cb_power"].Should().Be(36.93); } #endregion @@ -92,12 +92,12 @@ public class OtherPowerCalculationServiceTests var sut = CreateSut(smoothingWindowSize: 4); var devices = new Dictionary(); - var result1 = sut.Calculate(1000, devices); - result1.SmoothedOtherPowerWatts.Should().BeApproximately(1000, 0.1); + var result1 = sut.Calculate(341.97, devices); + result1.SmoothedOtherPowerWatts.Should().BeApproximately(341.97, 0.1); - var result2 = sut.Calculate(500, devices); - result2.SmoothedOtherPowerWatts.Should().BeLessThan(1000); - result2.SmoothedOtherPowerWatts.Should().BeGreaterThan(500); + var result2 = sut.Calculate(115.0, devices); + result2.SmoothedOtherPowerWatts.Should().BeLessThan(341.97); + result2.SmoothedOtherPowerWatts.Should().BeGreaterThan(115.0); } [Fact] @@ -109,10 +109,10 @@ public class OtherPowerCalculationServiceTests PowerCalculationResult? result = null; for (var i = 0; i < 50; i++) { - result = sut.Calculate(300, devices); + result = sut.Calculate(200.0, devices); } - result!.SmoothedOtherPowerWatts.Should().BeApproximately(300, 0.1); + result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1); } #endregion @@ -124,13 +124,13 @@ public class OtherPowerCalculationServiceTests { var sut = CreateSut(smoothingWindowSize: 10); var devices = new Dictionary(); - sut.Calculate(1000, devices); - sut.Calculate(1000, devices); + sut.Calculate(341.97, devices); + sut.Calculate(341.97, devices); sut.Reset(); - var result = sut.Calculate(100, devices); + var result = sut.Calculate(115.0, devices); - result.SmoothedOtherPowerWatts.Should().BeApproximately(100, 0.1); + result.SmoothedOtherPowerWatts.Should().BeApproximately(115.0, 0.1); } #endregion diff --git a/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs b/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs index df28ec7..4c78d9e 100644 --- a/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs @@ -9,15 +9,19 @@ public class PowerCostCalculationServiceTests { private readonly PowerCostCalculationService _sut = new(); + private const double DefaultTotalWatts = 341.97; + private const double DefaultSmoothedOtherWatts = 131.04; + private const double DefaultPricePerKwh = 0.1791; + private static PowerCalculationResult CreateResult( - double totalWatts = 1000, - double smoothedOtherWatts = 200, + double totalWatts = DefaultTotalWatts, + double smoothedOtherWatts = DefaultSmoothedOtherWatts, Dictionary? deviceReadings = null) { var readings = deviceReadings ?? new Dictionary { - ["sensor.device_a_power"] = 500, - ["sensor.device_b_power"] = 300 + ["sensor.sonoff_100215c534_power"] = 101.0, + ["sensor.sonoff_10018909cb_power"] = 109.93 }; return new PowerCalculationResult @@ -37,12 +41,12 @@ public class PowerCostCalculationServiceTests public void CalculateCostIncrement_ShouldComputeCorrectCost() { var cost = PowerCostCalculationService.CalculateCostIncrement( - powerWatts: 1000, - pricePerKwh: 0.10, + powerWatts: 341.97, + pricePerKwh: 0.1791, pollIntervalSeconds: PowerMonitorConsts.DefaultPollIntervalSeconds); - var expected = (1000.0 / PowerMonitorConsts.WattsPerKilowatt) - * 0.10 + var expected = (341.97 / PowerMonitorConsts.WattsPerKilowatt) + * 0.1791 * ((double)PowerMonitorConsts.DefaultPollIntervalSeconds / PowerMonitorConsts.SecondsPerHour); cost.Should().BeApproximately(expected, 0.000001); } @@ -50,14 +54,14 @@ public class PowerCostCalculationServiceTests [Fact] public void CalculateCostIncrement_WithZeroPower_ShouldReturnZero() { - var cost = PowerCostCalculationService.CalculateCostIncrement(0, 0.10, 15); + var cost = PowerCostCalculationService.CalculateCostIncrement(0, DefaultPricePerKwh, 15); cost.Should().Be(0); } [Fact] public void CalculateCostIncrement_WithZeroPrice_ShouldReturnZero() { - var cost = PowerCostCalculationService.CalculateCostIncrement(1000, 0, 15); + var cost = PowerCostCalculationService.CalculateCostIncrement(341.97, 0, 15); cost.Should().Be(0); } @@ -71,7 +75,7 @@ public class PowerCostCalculationServiceTests var now = new DateTime(2026, 3, 17, 10, 0, 0); var result = CreateResult(); - _sut.RecordCosts(result, 0.10, 15, now); + _sut.RecordCosts(result, DefaultPricePerKwh, 15, now); var totalSnapshot = _sut.GetTotalCostSnapshot(); totalSnapshot.CostDaily.Should().BeGreaterThan(0); @@ -86,22 +90,22 @@ public class PowerCostCalculationServiceTests var now = new DateTime(2026, 3, 17, 10, 0, 0); var result = CreateResult(); - _sut.RecordCosts(result, 0.10, 15, now); + _sut.RecordCosts(result, DefaultPricePerKwh, 15, now); - var deviceA = _sut.GetDeviceCostSnapshot("sensor.device_a_power"); - deviceA.CostDaily.Should().BeGreaterThan(0); + var ac = _sut.GetDeviceCostSnapshot("sensor.sonoff_100215c534_power"); + ac.CostDaily.Should().BeGreaterThan(0); - var deviceB = _sut.GetDeviceCostSnapshot("sensor.device_b_power"); - deviceB.CostDaily.Should().BeGreaterThan(0); + var induction = _sut.GetDeviceCostSnapshot("sensor.sonoff_10018909cb_power"); + induction.CostDaily.Should().BeGreaterThan(0); } [Fact] public void RecordCosts_TotalCostShouldBeHigherThanOtherCost() { var now = new DateTime(2026, 3, 17, 10, 0, 0); - var result = CreateResult(totalWatts: 1000, smoothedOtherWatts: 200); + var result = CreateResult(totalWatts: DefaultTotalWatts, smoothedOtherWatts: DefaultSmoothedOtherWatts); - _sut.RecordCosts(result, 0.10, 15, now); + _sut.RecordCosts(result, DefaultPricePerKwh, 15, now); var total = _sut.GetTotalCostSnapshot(); var other = _sut.GetOtherCostSnapshot(); @@ -114,10 +118,10 @@ public class PowerCostCalculationServiceTests var now = new DateTime(2026, 3, 17, 10, 0, 0); var result = CreateResult(); - _sut.RecordCosts(result, 0.10, 15, now); + _sut.RecordCosts(result, DefaultPricePerKwh, 15, now); var firstCost = _sut.GetTotalCostSnapshot().CostDaily; - _sut.RecordCosts(result, 0.10, 15, now.AddSeconds(15)); + _sut.RecordCosts(result, DefaultPricePerKwh, 15, now.AddSeconds(15)); var secondCost = _sut.GetTotalCostSnapshot().CostDaily; secondCost.Should().BeApproximately(firstCost * 2, 0.000001); @@ -129,19 +133,19 @@ public class PowerCostCalculationServiceTests var now = new DateTime(2026, 3, 17, 10, 0, 0); var result1 = CreateResult(deviceReadings: new Dictionary { - ["sensor.device_a_power"] = 500 + ["sensor.sonoff_100215c534_power"] = 101.0 }); - _sut.RecordCosts(result1, 0.10, 15, now); + _sut.RecordCosts(result1, DefaultPricePerKwh, 15, now); _sut.GetAllDeviceCostSnapshots().Should().HaveCount(1); var result2 = CreateResult(deviceReadings: new Dictionary { - ["sensor.device_a_power"] = 500, - ["sensor.device_b_power"] = 300 + ["sensor.sonoff_100215c534_power"] = 101.0, + ["sensor.sonoff_10018909cb_power"] = 109.93 }); - _sut.RecordCosts(result2, 0.10, 15, now.AddSeconds(15)); + _sut.RecordCosts(result2, DefaultPricePerKwh, 15, now.AddSeconds(15)); _sut.GetAllDeviceCostSnapshots().Should().HaveCount(2); } @@ -155,9 +159,9 @@ public class PowerCostCalculationServiceTests var now = new DateTime(2026, 3, 17, 10, 0, 0); var result = CreateResult(); - _sut.RecordCosts(result, 0.15, 15, now); + _sut.RecordCosts(result, 0.2492, 15, now); - _sut.LastKnownPrice.Should().Be(0.15); + _sut.LastKnownPrice.Should().Be(0.2492); _sut.PriceSource.Should().Be("live"); } @@ -167,19 +171,19 @@ public class PowerCostCalculationServiceTests var now = new DateTime(2026, 3, 17, 10, 0, 0); var result = CreateResult(); - _sut.RecordCosts(result, 0.10, 15, now); + _sut.RecordCosts(result, DefaultPricePerKwh, 15, now); _sut.RecordCosts(result, 0, 15, now.AddSeconds(15)); - _sut.LastKnownPrice.Should().Be(0.10); + _sut.LastKnownPrice.Should().Be(DefaultPricePerKwh); _sut.PriceSource.Should().Be("live"); } [Fact] public void SetPrice_ShouldUpdatePriceAndMarkAsStale() { - _sut.SetPrice(0.20); + _sut.SetPrice(0.1891); - _sut.LastKnownPrice.Should().Be(0.20); + _sut.LastKnownPrice.Should().Be(0.1891); _sut.PriceSource.Should().Be("stale"); } @@ -229,7 +233,7 @@ public class PowerCostCalculationServiceTests public async Task RecordCosts_ConcurrentAccess_ShouldNotLoseData() { var now = new DateTime(2026, 3, 17, 10, 0, 0); - var result = CreateResult(totalWatts: 1000, smoothedOtherWatts: 200); + var result = CreateResult(totalWatts: DefaultTotalWatts, smoothedOtherWatts: DefaultSmoothedOtherWatts); const int callsPerThread = 100; const int threadCount = 10; @@ -238,7 +242,7 @@ public class PowerCostCalculationServiceTests { for (var i = 0; i < callsPerThread; i++) { - _sut.RecordCosts(result, 0.10, 15, now.AddSeconds(1)); + _sut.RecordCosts(result, DefaultPricePerKwh, 15, now.AddSeconds(1)); } })) .ToArray(); diff --git a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs index e655bca..7f69e57 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs @@ -146,8 +146,8 @@ public class PowerMonitorEntityServiceTests var sensors = new List { - new() { EntityId = "sensor.device_a_power", FriendlyName = "Device A", DeviceName = "device_a" }, - new() { EntityId = "sensor.device_b_power", FriendlyName = "Device B", DeviceName = "device_b" } + new() { EntityId = "sensor.sonoff_100215c534_power", FriendlyName = "AC Power", DeviceName = "sonoff_100215c534" }, + new() { EntityId = "sensor.sonoff_10018909cb_power", FriendlyName = "Induction Power", DeviceName = "sonoff_10018909cb" } }; await _sut.CreateDeviceEntitiesAsync(sensors); @@ -238,10 +238,10 @@ public class PowerMonitorEntityServiceTests await _sut.UpdateEntitiesAsync(context); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_15min", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_1h", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_daily", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_monthly", It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_15min", It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_1h", It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_daily", It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_monthly", It.IsAny()), Times.Once); } [Fact] @@ -293,31 +293,41 @@ public class PowerMonitorEntityServiceTests { Calculation = new PowerCalculationResult { - TotalPowerWatts = 1000, - KnownDevicesSumWatts = 800, - RawOtherPowerWatts = 200, - SmoothedOtherPowerWatts = 195, + TotalPowerWatts = 341.97, + KnownDevicesSumWatts = 210.93, + RawOtherPowerWatts = 131.04, + SmoothedOtherPowerWatts = 128.5, DataQuality = "ok", DevicePowerReadings = new Dictionary { - ["sensor.device_a_power"] = 500, - ["sensor.device_b_power"] = 300 + ["sensor.sonoff_100215c534_power"] = 8.55, + ["sensor.sonoff_10018909cb_power"] = 36.93, + ["sensor.tv_power"] = 101.0, + ["sensor.akvariumas_power"] = 21.0, + ["sensor.sonoff_1002230a48_power"] = 20.06, + ["sensor.temp_power"] = 14.0, + ["sensor.balkony_laps_power"] = 9.39 } }, - CurrentNordPoolPrice = 0.10, + CurrentNordPoolPrice = 0.1791, PriceUnit = "EUR/kWh", PriceSource = "live", DeviceCosts = new Dictionary { - ["sensor.device_a_power"] = new() { Cost15Min = 0.01, Cost1Hour = 0.04, CostDaily = 0.50, CostMonthly = 15.0 }, - ["sensor.device_b_power"] = new() { Cost15Min = 0.005, Cost1Hour = 0.02, CostDaily = 0.30, CostMonthly = 9.0 } + ["sensor.sonoff_100215c534_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.004, CostDaily = 0.03, CostMonthly = 0.9 }, + ["sensor.sonoff_10018909cb_power"] = new() { Cost15Min = 0.002, Cost1Hour = 0.009, CostDaily = 0.11, CostMonthly = 3.3 }, + ["sensor.tv_power"] = new() { Cost15Min = 0.006, Cost1Hour = 0.024, CostDaily = 0.30, CostMonthly = 9.0 }, + ["sensor.akvariumas_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.005, CostDaily = 0.06, CostMonthly = 1.8 }, + ["sensor.sonoff_1002230a48_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.005, CostDaily = 0.06, CostMonthly = 1.8 }, + ["sensor.temp_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.003, CostDaily = 0.04, CostMonthly = 1.2 }, + ["sensor.balkony_laps_power"] = new() { Cost15Min = 0.0005, Cost1Hour = 0.002, CostDaily = 0.03, CostMonthly = 0.9 } }, TotalCost = new CostSnapshot { Cost15Min = 0.02, Cost1Hour = 0.08, CostDaily = 1.00, CostMonthly = 30.0 }, - OtherCost = new CostSnapshot { Cost15Min = 0.005, Cost1Hour = 0.02, CostDaily = 0.20, CostMonthly = 6.0 }, + OtherCost = new CostSnapshot { Cost15Min = 0.008, Cost1Hour = 0.031, CostDaily = 0.38, CostMonthly = 11.4 }, IsAnomaly = isAnomaly, AnomalyDuration = TimeSpan.Zero, - AnomalyThresholdWatts = 500, - TrackedSensorCount = 2, + AnomalyThresholdWatts = 1000, + TrackedSensorCount = 7, DegradedSensors = [], SystemStatus = "ok" }; diff --git a/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs b/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs index 8a0f407..64b622a 100644 --- a/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs @@ -22,7 +22,7 @@ public class PowerSensorDiscoveryServiceTests } private PowerSensorDiscoveryService CreateSut( - string mainMeterEntityId = "sensor.p1_meter_power", + string mainMeterEntityId = "sensor.sonoff_100267d63f_power", string[]? excludedPatterns = null) { var options = Options.Create(new PowerMonitorOptions @@ -73,9 +73,9 @@ public class PowerSensorDiscoveryServiceTests public void DiscoverDeviceSensors_ShouldFindPowerSensors() { SetupEntities( - ("sensor.p1_meter_power", "power", "W", "P1 Meter"), - ("sensor.sonoff_power", "power", "W", "Sonoff Power"), - ("sensor.zigbee_power", "power", "W", "Zigbee Power"), + ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), + ("sensor.sonoff_100215c534_power", "power", "W", "AC Power"), + ("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"), ("sensor.temperature", "temperature", "°C", "Temperature") ); @@ -83,31 +83,31 @@ public class PowerSensorDiscoveryServiceTests var result = sut.DiscoverDeviceSensors(); result.Should().HaveCount(2); - result.Should().Contain(s => s.EntityId == "sensor.sonoff_power"); - result.Should().Contain(s => s.EntityId == "sensor.zigbee_power"); + result.Should().Contain(s => s.EntityId == "sensor.sonoff_100215c534_power"); + result.Should().Contain(s => s.EntityId == "sensor.sonoff_10018909cb_power"); } [Fact] public void DiscoverDeviceSensors_ShouldExcludeMainMeter() { SetupEntities( - ("sensor.p1_meter_power", "power", "W", "P1 Meter"), - ("sensor.device_power", "power", "W", "Device") + ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), + ("sensor.tv_power", "power", "W", "TV Power") ); var sut = CreateSut(); var result = sut.DiscoverDeviceSensors(); result.Should().HaveCount(1); - result.Should().NotContain(s => s.EntityId == "sensor.p1_meter_power"); + result.Should().NotContain(s => s.EntityId == "sensor.sonoff_100267d63f_power"); } [Fact] public void DiscoverDeviceSensors_ShouldApplyExclusionPatterns() { SetupEntities( - ("sensor.p1_meter_power", "power", "W", "P1"), - ("sensor.device_power", "power", "W", "Device"), + ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), + ("sensor.tv_power", "power", "W", "TV Power"), ("sensor.nordpool_some_power", "power", "W", "NordPool"), ("sensor.powermonitor_other_power", "power", "W", "PowerMonitor") ); @@ -116,21 +116,22 @@ public class PowerSensorDiscoveryServiceTests var result = sut.DiscoverDeviceSensors(); result.Should().HaveCount(1); - result.Should().Contain(s => s.EntityId == "sensor.device_power"); + result.Should().Contain(s => s.EntityId == "sensor.tv_power"); } [Fact] public void DiscoverDeviceSensors_ShouldHandleKilowattUnit() { SetupEntities( - ("sensor.p1_meter_power", "power", "W", "P1"), - ("sensor.device_kw", "power", "kW", "Device kW") + ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), + ("sensor.sonoff_1002230e32_power", "power", "kW", "Boiler Power") ); var sut = CreateSut(); var result = sut.DiscoverDeviceSensors(); result.Should().HaveCount(1); + result.First().EntityId.Should().Be("sensor.sonoff_1002230e32_power"); result.First().UnitOfMeasurement.Should().Be("kW"); } @@ -152,8 +153,8 @@ public class PowerSensorDiscoveryServiceTests public void DiscoverDeviceSensors_ShouldUpdateCurrentDeviceSensors() { SetupEntities( - ("sensor.p1_meter_power", "power", "W", "P1"), - ("sensor.device_power", "power", "W", "Device") + ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), + ("sensor.akvariumas_power", "power", "W", "Akvariumas Power") ); var sut = CreateSut(); @@ -168,8 +169,8 @@ public class PowerSensorDiscoveryServiceTests public void DiscoverDeviceSensors_ReDiscovery_ShouldReplacePreviousList() { SetupEntities( - ("sensor.p1_meter_power", "power", "W", "P1"), - ("sensor.device_a_power", "power", "W", "Device A") + ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), + ("sensor.sonoff_100215c534_power", "power", "W", "AC Power") ); var sut = CreateSut(); @@ -177,9 +178,9 @@ public class PowerSensorDiscoveryServiceTests sut.CurrentDeviceSensors.Should().HaveCount(1); SetupEntities( - ("sensor.p1_meter_power", "power", "W", "P1"), - ("sensor.device_a_power", "power", "W", "Device A"), - ("sensor.device_b_power", "power", "W", "Device B") + ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), + ("sensor.sonoff_100215c534_power", "power", "W", "AC Power"), + ("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power") ); sut.DiscoverDeviceSensors(); @@ -192,8 +193,9 @@ public class PowerSensorDiscoveryServiceTests [Theory] [InlineData("sensor.sonoff_1002230e32_power", "sonoff_1002230e32")] - [InlineData("sensor.zigbee_device_power", "zigbee_device")] - [InlineData("sensor.some_sensor", "some_sensor")] + [InlineData("sensor.sonoff_100215c534_power", "sonoff_100215c534")] + [InlineData("sensor.tv_power", "tv")] + [InlineData("sensor.temp_power", "temp")] [InlineData("sensor.power", "power")] public void ExtractDeviceName_ShouldStripDomainAndPowerSuffix(string entityId, string expected) { @@ -206,9 +208,9 @@ public class PowerSensorDiscoveryServiceTests [Theory] [InlineData("sensor.nordpool_*", "sensor.nordpool_current_price", true)] - [InlineData("sensor.nordpool_*", "sensor.device_power", false)] + [InlineData("sensor.nordpool_*", "sensor.tv_power", false)] [InlineData("sensor.powermonitor_*", "sensor.powermonitor_other_power", true)] - [InlineData("*_power", "sensor.sonoff_power", true)] + [InlineData("*_power", "sensor.sonoff_100215c534_power", true)] public void GlobToRegex_ShouldMatchCorrectly(string glob, string input, bool expected) { var regex = PowerSensorDiscoveryService.GlobToRegex(glob); @@ -222,8 +224,8 @@ public class PowerSensorDiscoveryServiceTests [Fact] public void IsPowerSensor_WithPowerDeviceClassAndWattUnit_ShouldReturnTrue() { - SetupEntities(("sensor.test_power", "power", "W", "Test")); - var entity = new Entity(_haContextMock.Object, "sensor.test_power"); + SetupEntities(("sensor.sonoff_100215c534_power", "power", "W", "AC Power")); + var entity = new Entity(_haContextMock.Object, "sensor.sonoff_100215c534_power"); var sut = CreateSut(); sut.IsPowerSensor(entity).Should().BeTrue(); @@ -232,8 +234,8 @@ public class PowerSensorDiscoveryServiceTests [Fact] public void IsPowerSensor_WithNonSensorDomain_ShouldReturnFalse() { - SetupEntities(("switch.test_power", "power", "W", "Test")); - var entity = new Entity(_haContextMock.Object, "switch.test_power"); + SetupEntities(("switch.sonoff_100215c534_power", "power", "W", "AC Power")); + var entity = new Entity(_haContextMock.Object, "switch.sonoff_100215c534_power"); var sut = CreateSut(); sut.IsPowerSensor(entity).Should().BeFalse(); @@ -242,8 +244,8 @@ public class PowerSensorDiscoveryServiceTests [Fact] public void IsPowerSensor_WithTemperatureDeviceClass_ShouldReturnFalse() { - SetupEntities(("sensor.test_temp", "temperature", "°C", "Test")); - var entity = new Entity(_haContextMock.Object, "sensor.test_temp"); + SetupEntities(("sensor.sonoff_100215c534_temp", "temperature", "°C", "AC Temp")); + var entity = new Entity(_haContextMock.Object, "sensor.sonoff_100215c534_temp"); var sut = CreateSut(); sut.IsPowerSensor(entity).Should().BeFalse(); diff --git a/PowerMonitor.Manager/PowerMonitor.Manager.csproj b/PowerMonitor.Manager/PowerMonitor.Manager.csproj index aa4d7c5..6d79ea3 100644 --- a/PowerMonitor.Manager/PowerMonitor.Manager.csproj +++ b/PowerMonitor.Manager/PowerMonitor.Manager.csproj @@ -20,8 +20,8 @@ - - + + diff --git a/PowerMonitor.Models/PowerMonitor.Models.csproj b/PowerMonitor.Models/PowerMonitor.Models.csproj index 52df77e..babb160 100644 --- a/PowerMonitor.Models/PowerMonitor.Models.csproj +++ b/PowerMonitor.Models/PowerMonitor.Models.csproj @@ -12,7 +12,7 @@ - + diff --git a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs new file mode 100644 index 0000000..9c7116a --- /dev/null +++ b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs @@ -0,0 +1,116 @@ +using FluentAssertions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using ShowerMonitor.Models.Enums; +using ShowerMonitorManager; +using ShowerMonitorManager.Models; + +namespace ShowerMonitor.Manager.Tests; + +public class ExhaustFanControlServiceTests +{ + private const string FanEntityId = "switch.exhaust_fan"; + + private readonly ShowerMonitorOptions _defaultOptions = new() + { + ExhaustFanEntityId = FanEntityId, + FanRunAfterShowerMinutes = 10 + }; + + private readonly Mock _haContextMock = new(); + + private ExhaustFanControlService CreateService(ShowerMonitorOptions? options = null) + { + return new ExhaustFanControlService( + Mock.Of>(), + Options.Create(options ?? _defaultOptions)); + } + + [Fact] + public void Evaluate_WhenActive_TurnsFanOn() + { + var entityState = new EntityState { State = "off" }; + _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); + + var service = CreateService(); + service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow, _haContextMock.Object); + + _haContextMock.Verify(x => x.CallService("switch", "turn_on", + It.IsAny(), It.IsAny()), Times.Once); + } + + [Fact] + public void Evaluate_WhenActiveAndFanAlreadyOn_DoesNotCallAgain() + { + var entityState = new EntityState { State = "on" }; + _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); + + var service = CreateService(); + service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow, _haContextMock.Object); + + _haContextMock.Verify(x => x.CallService("switch", "turn_on", + It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public void Evaluate_AfterShowerEndsAndRunPeriodElapsed_TurnsFanOff() + { + var entityState = new EntityState { State = "off" }; + _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); + + var service = CreateService(); + var now = DateTimeOffset.UtcNow; + + service.Evaluate(ShowerState.Active, now, _haContextMock.Object); + service.Evaluate(ShowerState.Completed, now.AddMinutes(5), _haContextMock.Object); + service.Evaluate(ShowerState.Idle, now.AddMinutes(16), _haContextMock.Object); + + _haContextMock.Verify(x => x.CallService("switch", "turn_off", + It.IsAny(), It.IsAny()), Times.Once); + } + + [Fact] + public void Evaluate_AfterShowerEndsButRunPeriodNotElapsed_KeepsFanOn() + { + var entityState = new EntityState { State = "off" }; + _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); + + var service = CreateService(); + var now = DateTimeOffset.UtcNow; + + service.Evaluate(ShowerState.Active, now, _haContextMock.Object); + service.Evaluate(ShowerState.Completed, now.AddMinutes(5), _haContextMock.Object); + service.Evaluate(ShowerState.Idle, now.AddMinutes(8), _haContextMock.Object); + + _haContextMock.Verify(x => x.CallService("switch", "turn_off", + It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public void Reset_WhenFanWasTurnedOnByUs_TurnsFanOff() + { + var entityState = new EntityState { State = "off" }; + _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); + + var service = CreateService(); + service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow, _haContextMock.Object); + + service.Reset(_haContextMock.Object); + + _haContextMock.Verify(x => x.CallService("switch", "turn_off", + It.IsAny(), It.IsAny()), Times.Once); + } + + [Fact] + public void Reset_WhenFanWasNotTurnedOnByUs_DoesNotTurnFanOff() + { + var service = CreateService(); + service.Reset(_haContextMock.Object); + + _haContextMock.Verify(x => x.CallService("switch", "turn_off", + It.IsAny(), It.IsAny()), Times.Never); + } +} diff --git a/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs b/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs new file mode 100644 index 0000000..222de91 --- /dev/null +++ b/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs @@ -0,0 +1,105 @@ +using FluentAssertions; +using ShowerMonitorManager; + +namespace ShowerMonitor.Manager.Tests; + +public class HumidityRateCalculatorTests +{ + private const int DefaultWindowSize = 5; + + [Fact] + public void GetRatePerMinute_WithNoReadings_ReturnsZero() + { + var calculator = new HumidityRateCalculator(DefaultWindowSize); + + calculator.GetRatePerMinute().Should().Be(0.0); + } + + [Fact] + public void GetRatePerMinute_WithSingleReading_ReturnsZero() + { + var calculator = new HumidityRateCalculator(DefaultWindowSize); + calculator.RecordReading(52.9, DateTimeOffset.UtcNow); + + calculator.GetRatePerMinute().Should().Be(0.0); + } + + [Fact] + public void GetRatePerMinute_WithRisingHumidity_ReturnsPositiveRate() + { + var calculator = new HumidityRateCalculator(DefaultWindowSize); + var baseTime = DateTimeOffset.UtcNow; + + calculator.RecordReading(52.9, baseTime); + calculator.RecordReading(62.9, baseTime.AddMinutes(1)); + + calculator.GetRatePerMinute().Should().BeApproximately(10.0, 0.01); + } + + [Fact] + public void GetRatePerMinute_WithFallingHumidity_ReturnsNegativeRate() + { + var calculator = new HumidityRateCalculator(DefaultWindowSize); + var baseTime = DateTimeOffset.UtcNow; + + calculator.RecordReading(62.9, baseTime); + calculator.RecordReading(52.9, baseTime.AddMinutes(2)); + + calculator.GetRatePerMinute().Should().BeApproximately(-5.0, 0.01); + } + + [Fact] + public void GetRatePerMinute_ExceedingWindowSize_DropsStalestReading() + { + var calculator = new HumidityRateCalculator(3); + var baseTime = DateTimeOffset.UtcNow; + + calculator.RecordReading(52.9, baseTime); + calculator.RecordReading(57.9, baseTime.AddMinutes(1)); + calculator.RecordReading(62.9, baseTime.AddMinutes(2)); + calculator.RecordReading(64.9, baseTime.AddMinutes(3)); + + var rate = calculator.GetRatePerMinute(); + rate.Should().BeApproximately(3.5, 0.01); + } + + [Fact] + public void GetRatePerMinute_WithSameTimestamp_ReturnsZero() + { + var calculator = new HumidityRateCalculator(DefaultWindowSize); + var sameTime = DateTimeOffset.UtcNow; + + calculator.RecordReading(52.9, sameTime); + calculator.RecordReading(62.9, sameTime); + + calculator.GetRatePerMinute().Should().Be(0.0); + } + + [Fact] + public void Reset_ClearsAllReadings() + { + var calculator = new HumidityRateCalculator(DefaultWindowSize); + var baseTime = DateTimeOffset.UtcNow; + + calculator.RecordReading(52.9, baseTime); + calculator.RecordReading(62.9, baseTime.AddMinutes(1)); + + calculator.Reset(); + + calculator.GetRatePerMinute().Should().Be(0.0); + } + + [Fact] + public void GetRatePerMinute_SimulatesShowerSpike_DetectsHighRate() + { + var calculator = new HumidityRateCalculator(DefaultWindowSize); + var baseTime = DateTimeOffset.UtcNow; + + calculator.RecordReading(52.9, baseTime); + calculator.RecordReading(59.9, baseTime.AddSeconds(30)); + calculator.RecordReading(64.9, baseTime.AddSeconds(60)); + + var rate = calculator.GetRatePerMinute(); + rate.Should().BeGreaterThan(4.0); + } +} diff --git a/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs b/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs new file mode 100644 index 0000000..2690d87 --- /dev/null +++ b/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs @@ -0,0 +1,170 @@ +using FluentAssertions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using ShowerMonitor.Models.Enums; +using ShowerMonitorManager; +using ShowerMonitorManager.Interface; +using ShowerMonitorManager.Models; + +namespace ShowerMonitor.Manager.Tests; + +public class ShowerDetectionServiceTests +{ + private readonly ShowerMonitorOptions _defaultOptions = new() + { + SpikeRateThreshold = 4.0, + MinDifferentialHumidity = 8.0, + PeakHumidityThreshold = 58.0, + ConfirmationWindowMinutes = 2, + RecoveryDifferentialThreshold = 5.0, + MaxShowerDurationMinutes = 60, + RateWindowSize = 5 + }; + + private ShowerDetectionService CreateService( + IHumidityRateCalculator? rateCalculator = null, + ShowerMonitorOptions? options = null) + { + var opts = options ?? _defaultOptions; + var calculator = rateCalculator ?? new HumidityRateCalculator(opts.RateWindowSize); + + return new ShowerDetectionService( + calculator, + Mock.Of>(), + Options.Create(opts)); + } + + [Fact] + public void InitialState_IsIdle() + { + var service = CreateService(); + service.CurrentState.Should().Be(ShowerState.Idle); + } + + [Fact] + public void Evaluate_WithNoSpike_RemainsIdle() + { + var service = CreateService(); + var baseTime = DateTimeOffset.UtcNow; + + service.Evaluate(52.9, 50.5, baseTime); + service.Evaluate(53.2, 50.5, baseTime.AddSeconds(30)); + + service.CurrentState.Should().Be(ShowerState.Idle); + } + + [Fact] + public void Evaluate_WithShowerSpike_TransitionsToSuspected() + { + var service = CreateService(); + var baseTime = DateTimeOffset.UtcNow; + + service.Evaluate(52.9, 50.5, baseTime); + service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); + var state = service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); + + state.Should().Be(ShowerState.Suspected); + } + + [Fact] + public void Evaluate_WithSustainedSpike_TransitionsToActive() + { + var service = CreateService(); + var baseTime = DateTimeOffset.UtcNow; + + service.Evaluate(52.9, 50.5, baseTime); + service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); + service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); + + var state = service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3)); + + state.Should().Be(ShowerState.Active); + } + + [Fact] + public void Evaluate_FullShowerCycle_CompletesSession() + { + var service = CreateService(); + var baseTime = DateTimeOffset.UtcNow; + + service.Evaluate(52.9, 50.5, baseTime); + service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); + service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); + service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3)); + + service.CurrentState.Should().Be(ShowerState.Active); + + service.Evaluate(61.0, 50.0, baseTime.AddMinutes(10)); + service.Evaluate(56.0, 50.5, baseTime.AddMinutes(15)); + + service.Evaluate(53.5, 50.5, baseTime.AddMinutes(20)); + + service.TodaySessionCount.Should().BeGreaterThanOrEqualTo(1); + service.LastCompletedSession.Should().NotBeNull(); + } + + [Fact] + public void Evaluate_SuspectedThenDrops_ReturnsToIdle() + { + var service = CreateService(); + var baseTime = DateTimeOffset.UtcNow; + + service.Evaluate(52.9, 50.5, baseTime); + service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); + service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); + + service.CurrentState.Should().Be(ShowerState.Suspected); + + service.Evaluate(57.0, 50.0, baseTime.AddMinutes(2)); + service.Evaluate(54.0, 50.0, baseTime.AddMinutes(3)); + service.Evaluate(52.5, 50.5, baseTime.AddMinutes(4)); + service.Evaluate(52.0, 50.5, baseTime.AddMinutes(5)); + + service.CurrentState.Should().Be(ShowerState.Idle); + } + + [Fact] + public void ResetDailyCounters_ClearsSessionCount() + { + var service = CreateService(); + var baseTime = DateTimeOffset.UtcNow; + + service.Evaluate(52.9, 50.5, baseTime); + service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); + service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); + service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3)); + service.Evaluate(56.0, 50.5, baseTime.AddMinutes(15)); + service.Evaluate(53.5, 50.5, baseTime.AddMinutes(20)); + + service.ResetDailyCounters(); + + service.TodaySessionCount.Should().Be(0); + service.LastCompletedSession.Should().BeNull(); + } + + [Fact] + public void Evaluate_BackToBackShowers_CountsAsTwoSessions() + { + var service = CreateService(); + var baseTime = DateTimeOffset.UtcNow; + + service.Evaluate(52.9, 50.5, baseTime); + service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); + service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); + service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3)); + service.Evaluate(56.0, 50.5, baseTime.AddMinutes(10)); + service.Evaluate(53.5, 50.5, baseTime.AddMinutes(15)); + + var firstCount = service.TodaySessionCount; + + service.Evaluate(52.9, 50.5, baseTime.AddMinutes(20)); + service.Evaluate(58.5, 49.5, baseTime.AddMinutes(20).AddSeconds(30)); + service.Evaluate(66.0, 49.5, baseTime.AddMinutes(21)); + service.Evaluate(68.0, 49.5, baseTime.AddMinutes(23)); + service.Evaluate(56.0, 50.5, baseTime.AddMinutes(30)); + service.Evaluate(53.5, 50.5, baseTime.AddMinutes(35)); + + service.TodaySessionCount.Should().BeGreaterThan(firstCount); + } +} diff --git a/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj b/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj new file mode 100644 index 0000000..00bf47d --- /dev/null +++ b/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj @@ -0,0 +1,35 @@ + + + + net10.0 + enable + enable + false + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/ShowerMonitor.Manager/ExhaustFanControlService.cs b/ShowerMonitor.Manager/ExhaustFanControlService.cs new file mode 100644 index 0000000..3356d84 --- /dev/null +++ b/ShowerMonitor.Manager/ExhaustFanControlService.cs @@ -0,0 +1,106 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using ShowerMonitor.Models.Enums; +using ShowerMonitorManager.Interface; +using ShowerMonitorManager.Models; + +namespace ShowerMonitorManager; + +public sealed class ExhaustFanControlService : IExhaustFanControlService +{ + private readonly ILogger _logger; + private readonly ShowerMonitorOptions _options; + private readonly Lock _lock = new(); + + private bool _fanTurnedOnByUs; + private DateTimeOffset? _showerEndedAt; + + public ExhaustFanControlService( + ILogger logger, + IOptions options) + { + _logger = logger; + _options = options.Value; + } + + public void Evaluate(ShowerState state, DateTimeOffset timestamp, IHaContext haContext) + { + lock (_lock) + { + switch (state) + { + case ShowerState.Active: + case ShowerState.Suspected: + TurnOnFanIfNeeded(haContext); + _showerEndedAt = null; + break; + + case ShowerState.Declining: + case ShowerState.Completed: + _showerEndedAt ??= timestamp; + EvaluatePostShowerFanOff(timestamp, haContext); + break; + + case ShowerState.Idle: + EvaluatePostShowerFanOff(timestamp, haContext); + break; + } + } + } + + public void Reset(IHaContext haContext) + { + lock (_lock) + { + if (_fanTurnedOnByUs) + { + haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); + _logger.LogInformation("Exhaust fan turned OFF during reset (was turned on by shower detection)"); + } + + _fanTurnedOnByUs = false; + _showerEndedAt = null; + } + } + + private void TurnOnFanIfNeeded(IHaContext haContext) + { + if (_fanTurnedOnByUs) + { + return; + } + + var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State; + if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase)) + { + return; + } + + haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); + _fanTurnedOnByUs = true; + _logger.LogInformation("Exhaust fan turned ON by shower detection"); + } + + private void EvaluatePostShowerFanOff(DateTimeOffset timestamp, IHaContext haContext) + { + if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue) + { + return; + } + + var elapsed = timestamp - _showerEndedAt.Value; + var runAfterDuration = TimeSpan.FromMinutes(_options.FanRunAfterShowerMinutes); + + if (elapsed < runAfterDuration) + { + return; + } + + haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); + _fanTurnedOnByUs = false; + _showerEndedAt = null; + _logger.LogInformation("Exhaust fan turned OFF after post-shower run period ({Duration})", runAfterDuration); + } +} diff --git a/ShowerMonitor.Manager/HumidityRateCalculator.cs b/ShowerMonitor.Manager/HumidityRateCalculator.cs new file mode 100644 index 0000000..fcd23aa --- /dev/null +++ b/ShowerMonitor.Manager/HumidityRateCalculator.cs @@ -0,0 +1,52 @@ +using ShowerMonitorManager.Interface; + +namespace ShowerMonitorManager; + +public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalculator +{ + private readonly Lock _lock = new(); + private readonly Queue<(double Humidity, DateTimeOffset Timestamp)> _readings = new(); + + public void RecordReading(double humidity, DateTimeOffset timestamp) + { + lock (_lock) + { + _readings.Enqueue((humidity, timestamp)); + + while (_readings.Count > windowSize) + { + _readings.Dequeue(); + } + } + } + + public double GetRatePerMinute() + { + lock (_lock) + { + if (_readings.Count < 2) + { + return 0.0; + } + + var oldest = _readings.Peek(); + var newest = _readings.Last(); + var elapsedMinutes = (newest.Timestamp - oldest.Timestamp).TotalMinutes; + + if (elapsedMinutes <= 0) + { + return 0.0; + } + + return (newest.Humidity - oldest.Humidity) / elapsedMinutes; + } + } + + public void Reset() + { + lock (_lock) + { + _readings.Clear(); + } + } +} diff --git a/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs b/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs new file mode 100644 index 0000000..68628ab --- /dev/null +++ b/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs @@ -0,0 +1,10 @@ +using NetDaemon.HassModel; +using ShowerMonitor.Models.Enums; + +namespace ShowerMonitorManager.Interface; + +public interface IExhaustFanControlService +{ + void Evaluate(ShowerState state, DateTimeOffset timestamp, IHaContext haContext); + void Reset(IHaContext haContext); +} diff --git a/ShowerMonitor.Manager/Interface/IHumidityRateCalculator.cs b/ShowerMonitor.Manager/Interface/IHumidityRateCalculator.cs new file mode 100644 index 0000000..97d9ba1 --- /dev/null +++ b/ShowerMonitor.Manager/Interface/IHumidityRateCalculator.cs @@ -0,0 +1,8 @@ +namespace ShowerMonitorManager.Interface; + +public interface IHumidityRateCalculator +{ + void RecordReading(double humidity, DateTimeOffset timestamp); + double GetRatePerMinute(); + void Reset(); +} diff --git a/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs b/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs new file mode 100644 index 0000000..4a8b1b0 --- /dev/null +++ b/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs @@ -0,0 +1,15 @@ +using ShowerMonitor.Models; +using ShowerMonitor.Models.Enums; + +namespace ShowerMonitorManager.Interface; + +public interface IShowerDetectionService +{ + ShowerState CurrentState { get; } + ShowerSession? CurrentSession { get; } + ShowerSession? LastCompletedSession { get; } + int TodaySessionCount { get; } + + ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp); + void ResetDailyCounters(); +} diff --git a/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs b/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs new file mode 100644 index 0000000..8d0c9ae --- /dev/null +++ b/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs @@ -0,0 +1,11 @@ +using ShowerMonitorManager.Models; + +namespace ShowerMonitorManager.Interface; + +public interface IShowerMonitorEntityService +{ + Task CreateEntitiesAsync(CancellationToken cancellationToken = default); + Task UpdateEntitiesAsync(ShowerMonitorUpdateContext context, CancellationToken cancellationToken = default); + Task ResetEntitiesAsync(CancellationToken cancellationToken = default); + Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); +} diff --git a/ShowerMonitor.Manager/Interface/IShowerMonitorInit.cs b/ShowerMonitor.Manager/Interface/IShowerMonitorInit.cs new file mode 100644 index 0000000..fa730a7 --- /dev/null +++ b/ShowerMonitor.Manager/Interface/IShowerMonitorInit.cs @@ -0,0 +1,7 @@ +namespace ShowerMonitorManager.Interface; + +public interface IShowerMonitorInit +{ + Task InitializeAsync(); + Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); +} diff --git a/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs b/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs new file mode 100644 index 0000000..3f5295a --- /dev/null +++ b/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs @@ -0,0 +1,24 @@ +using ShowerMonitor.Models; + +namespace ShowerMonitorManager.Models; + +public sealed class ShowerMonitorOptions +{ + public const string SectionName = "ShowerMonitor"; + + public bool Enabled { get; set; } + public bool CleanupEntitiesOnStartup { get; set; } + public string BathroomHumidityEntityId { get; set; } = ShowerMonitorConsts.BathroomHumidityEntityId; + public string MainHomeHumidityEntityId { get; set; } = ShowerMonitorConsts.MainHomeHumidityEntityId; + public string BathroomTemperatureEntityId { get; set; } = ShowerMonitorConsts.BathroomTemperatureEntityId; + public string ExhaustFanEntityId { get; set; } = ShowerMonitorConsts.ExhaustFanEntityId; + public int PollIntervalSeconds { get; set; } = ShowerMonitorConsts.DefaultPollIntervalSeconds; + public double SpikeRateThreshold { get; set; } = ShowerMonitorConsts.DefaultSpikeRateThreshold; + public double MinDifferentialHumidity { get; set; } = ShowerMonitorConsts.DefaultMinDifferentialHumidity; + public double PeakHumidityThreshold { get; set; } = ShowerMonitorConsts.DefaultPeakHumidityThreshold; + public int ConfirmationWindowMinutes { get; set; } = ShowerMonitorConsts.DefaultConfirmationWindowMinutes; + public double RecoveryDifferentialThreshold { get; set; } = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold; + public int MaxShowerDurationMinutes { get; set; } = (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes; + public int FanRunAfterShowerMinutes { get; set; } = (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes; + public int RateWindowSize { get; set; } = ShowerMonitorConsts.DefaultRateWindowSize; +} diff --git a/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs b/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs new file mode 100644 index 0000000..fb28023 --- /dev/null +++ b/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs @@ -0,0 +1,16 @@ +using ShowerMonitor.Models; +using ShowerMonitor.Models.Enums; + +namespace ShowerMonitorManager.Models; + +public sealed class ShowerMonitorUpdateContext +{ + public required ShowerState State { get; init; } + public required double BathroomHumidity { get; init; } + public required double MainHomeHumidity { get; init; } + public required double Differential { get; init; } + public required double HumidityRate { get; init; } + public required int TodaySessionCount { get; init; } + public ShowerSession? LastCompletedSession { get; init; } + public ShowerSession? CurrentSession { get; init; } +} diff --git a/ShowerMonitor.Manager/ShowerDetectionService.cs b/ShowerMonitor.Manager/ShowerDetectionService.cs new file mode 100644 index 0000000..ebcd3a4 --- /dev/null +++ b/ShowerMonitor.Manager/ShowerDetectionService.cs @@ -0,0 +1,218 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using ShowerMonitor.Models; +using ShowerMonitor.Models.Enums; +using ShowerMonitorManager.Interface; +using ShowerMonitorManager.Models; + +namespace ShowerMonitorManager; + +public sealed class ShowerDetectionService : IShowerDetectionService +{ + private readonly IHumidityRateCalculator _rateCalculator; + private readonly ILogger _logger; + private readonly ShowerMonitorOptions _options; + private readonly Lock _lock = new(); + + private ShowerState _currentState = ShowerState.Idle; + private ShowerSession? _currentSession; + private ShowerSession? _lastCompletedSession; + private int _todaySessionCount; + private DateTimeOffset? _suspectedSince; + + public ShowerDetectionService( + IHumidityRateCalculator rateCalculator, + ILogger logger, + IOptions options) + { + _rateCalculator = rateCalculator; + _logger = logger; + _options = options.Value; + } + + public ShowerState CurrentState + { + get { lock (_lock) { return _currentState; } } + } + + public ShowerSession? CurrentSession + { + get { lock (_lock) { return _currentSession; } } + } + + public ShowerSession? LastCompletedSession + { + get { lock (_lock) { return _lastCompletedSession; } } + } + + public int TodaySessionCount + { + get { lock (_lock) { return _todaySessionCount; } } + } + + public ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp) + { + _rateCalculator.RecordReading(bathroomHumidity, timestamp); + var rate = _rateCalculator.GetRatePerMinute(); + var differential = bathroomHumidity - mainHomeHumidity; + + lock (_lock) + { + var previousState = _currentState; + _currentState = _currentState switch + { + ShowerState.Idle => EvaluateIdle(rate, differential, bathroomHumidity, timestamp), + ShowerState.Suspected => EvaluateSuspected(rate, differential, bathroomHumidity, timestamp), + ShowerState.Active => EvaluateActive(rate, differential, bathroomHumidity, timestamp), + ShowerState.Declining => EvaluateDeclining(differential, timestamp), + ShowerState.Completed => TransitionToIdle(), + _ => _currentState + }; + + if (_currentState != previousState) + { + _logger.LogInformation( + "Shower state transition: {Previous} -> {Current} (humidity={Humidity}%, differential={Diff}%, rate={Rate}%/min)", + previousState, _currentState, bathroomHumidity, Math.Round(differential, 1), Math.Round(rate, 2)); + } + + return _currentState; + } + } + + public void ResetDailyCounters() + { + lock (_lock) + { + _todaySessionCount = 0; + _lastCompletedSession = null; + _logger.LogInformation("Shower monitor daily counters reset"); + } + } + + private ShowerState EvaluateIdle(double rate, double differential, double humidity, DateTimeOffset timestamp) + { + if (rate >= _options.SpikeRateThreshold && differential >= _options.MinDifferentialHumidity) + { + _suspectedSince = timestamp; + _currentSession = new ShowerSession + { + StartTime = timestamp, + PreEventHumidity = humidity - (rate > 0 ? rate : 0), + PeakHumidity = humidity, + PeakTime = timestamp + }; + + _logger.LogInformation("Shower suspected: rate={Rate}%/min, differential={Diff}%", Math.Round(rate, 2), Math.Round(differential, 1)); + return ShowerState.Suspected; + } + + return ShowerState.Idle; + } + + private ShowerState EvaluateSuspected(double rate, double differential, double humidity, DateTimeOffset timestamp) + { + if (_currentSession is not null && humidity > _currentSession.PeakHumidity) + { + _currentSession.PeakHumidity = humidity; + _currentSession.PeakTime = timestamp; + } + + var confirmationWindow = TimeSpan.FromMinutes(_options.ConfirmationWindowMinutes); + if (_suspectedSince.HasValue && (timestamp - _suspectedSince.Value) >= confirmationWindow + && humidity >= _options.PeakHumidityThreshold + && differential >= _options.MinDifferentialHumidity) + { + _logger.LogInformation("Shower confirmed: peak={Peak}%, differential={Diff}%", humidity, Math.Round(differential, 1)); + return ShowerState.Active; + } + + if (rate < 0 && differential < _options.MinDifferentialHumidity) + { + _logger.LogInformation("Shower suspicion cleared: differential dropped below threshold"); + CompleteSessionCleanup(); + return ShowerState.Idle; + } + + return ShowerState.Suspected; + } + + private ShowerState EvaluateActive(double rate, double differential, double humidity, DateTimeOffset timestamp) + { + if (_currentSession is not null && humidity > _currentSession.PeakHumidity) + { + _currentSession.PeakHumidity = humidity; + _currentSession.PeakTime = timestamp; + } + + var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes); + if (_currentSession is not null && _currentSession.Duration >= maxDuration) + { + _logger.LogWarning("Shower exceeded max duration ({MaxDuration}), completing", maxDuration); + return TransitionToDeclining(timestamp); + } + + if (rate < 0 && differential < _options.PeakHumidityThreshold - _options.RecoveryDifferentialThreshold) + { + return TransitionToDeclining(timestamp); + } + + return ShowerState.Active; + } + + private ShowerState EvaluateDeclining(double differential, DateTimeOffset timestamp) + { + if (differential <= _options.RecoveryDifferentialThreshold) + { + CompleteSession(timestamp); + return ShowerState.Completed; + } + + var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes); + if (_currentSession is not null && _currentSession.Duration >= maxDuration) + { + _logger.LogWarning("Shower declining phase exceeded max duration, completing"); + CompleteSession(timestamp); + return ShowerState.Completed; + } + + return ShowerState.Declining; + } + + private ShowerState TransitionToDeclining(DateTimeOffset timestamp) + { + _logger.LogInformation("Shower entering decline phase at {Time}", timestamp); + return ShowerState.Declining; + } + + private ShowerState TransitionToIdle() + { + _rateCalculator.Reset(); + return ShowerState.Idle; + } + + private void CompleteSession(DateTimeOffset endTime) + { + if (_currentSession is null) + { + return; + } + + _currentSession.EndTime = endTime; + _lastCompletedSession = _currentSession; + _todaySessionCount++; + + _logger.LogInformation( + "Shower session completed: duration={Duration}, peak={Peak}%, sessions today={Count}", + _currentSession.Duration, _currentSession.PeakHumidity, _todaySessionCount); + + _currentSession = null; + _suspectedSince = null; + } + + private void CompleteSessionCleanup() + { + _currentSession = null; + _suspectedSince = null; + } +} diff --git a/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj b/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj new file mode 100644 index 0000000..32dc900 --- /dev/null +++ b/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + enable + enable + ShowerMonitorManager + + + + + <_Parameter1>ShowerMonitor.Manager.Tests + + + + + + + + + + + + + + + diff --git a/ShowerMonitor.Manager/ShowerMonitorEntityService.cs b/ShowerMonitor.Manager/ShowerMonitorEntityService.cs new file mode 100644 index 0000000..a6a519c --- /dev/null +++ b/ShowerMonitor.Manager/ShowerMonitorEntityService.cs @@ -0,0 +1,240 @@ +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 logger) : IShowerMonitorEntityService +{ + private static readonly string[] CleanableEntityIds = + [ + ActiveEntityId, + StateEntityId, + DifferentialEntityId, + HumidityRateEntityId, + TodaySessionCountEntityId, + LastShowerDurationEntityId, + LastShowerTimeEntityId, + 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 + { + logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId); + 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 ResetEntitiesAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + logger.LogInformation("Resetting ShowerMonitor entity states to defaults"); + + await Task.WhenAll( + SetEntityStateSafe(ActiveEntityId, "off"), + SetEntityStateSafe(StateEntityId, ShowerState.Idle.ToString().ToLowerInvariant()), + SetEntityStateSafe(DifferentialEntityId, "0"), + SetEntityStateSafe(HumidityRateEntityId, "0"), + SetEntityStateSafe(TodaySessionCountEntityId, "0"), + SetEntityStateSafe(LastShowerDurationEntityId, "0"), + SetEntityStateSafe(LastShowerTimeEntityId, "unknown") + ).ConfigureAwait(false); + } + + public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + try + { + var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId)); + 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 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"; + } +} diff --git a/ShowerMonitor.Manager/ShowerMonitorInit.cs b/ShowerMonitor.Manager/ShowerMonitorInit.cs new file mode 100644 index 0000000..66c81cd --- /dev/null +++ b/ShowerMonitor.Manager/ShowerMonitorInit.cs @@ -0,0 +1,224 @@ +using System.Globalization; +using System.Reactive.Concurrency; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NetDaemon.AppModel; +using NetDaemon.Extensions.Scheduler; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using ShowerMonitor.Models.Enums; +using ShowerMonitorManager.Interface; +using ShowerMonitorManager.Models; +using static ShowerMonitor.Models.ShowerMonitorConsts; + +namespace ShowerMonitorManager; + +[NetDaemonApp] +public sealed class ShowerMonitorInit : IShowerMonitorInit +{ + private readonly ILogger _logger; + private readonly IHaContext _haContext; + private readonly IScheduler _scheduler; + private readonly IShowerDetectionService _detectionService; + private readonly IHumidityRateCalculator _rateCalculator; + private readonly IExhaustFanControlService _fanControlService; + private readonly IShowerMonitorEntityService _entityService; + private readonly ShowerMonitorOptions _options; + + private bool _cleanedUp; + + public ShowerMonitorInit( + IHaContext haContext, + ILogger logger, + IScheduler scheduler, + IShowerDetectionService detectionService, + IHumidityRateCalculator rateCalculator, + IExhaustFanControlService fanControlService, + IShowerMonitorEntityService entityService, + IOptions options) + { + _haContext = haContext; + _logger = logger; + _scheduler = scheduler; + _detectionService = detectionService; + _rateCalculator = rateCalculator; + _fanControlService = fanControlService; + _entityService = entityService; + _options = options.Value; + + _ = InitializeAndScheduleAsync(); + } + + private async Task InitializeAndScheduleAsync() + { + try + { + await InitializeAsync(); + SchedulePeriodicPolling(); + ScheduleMidnightReset(); + SubscribeToCleanupButton(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during ShowerMonitor initialization and scheduling"); + } + } + + public async Task InitializeAsync() + { + try + { + await Task.Delay(TimeSpan.FromSeconds(3)); + + if (_options.CleanupEntitiesOnStartup) + { + await _entityService.CleanupEntitiesAsync(); + } + + await _entityService.CreateEntitiesAsync(); + await _entityService.ResetEntitiesAsync(); + + await Task.Delay(TimeSpan.FromSeconds(2)); + await PollAndUpdateAsync(); + + _logger.LogInformation("ShowerMonitor initialized"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error initializing ShowerMonitor"); + throw; + } + } + + public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) + { + await _entityService.CleanupEntitiesAsync(cancellationToken); + } + + private void SchedulePeriodicPolling() + { + var pollInterval = TimeSpan.FromSeconds(_options.PollIntervalSeconds); + var now = DateTime.Now; + var currentSecondInInterval = (now.Minute * 60 + now.Second) % _options.PollIntervalSeconds; + var secondsUntilNext = _options.PollIntervalSeconds - currentSecondInInterval; + var nextPollTime = now.Add(TimeSpan.FromSeconds(secondsUntilNext)); + + _logger.LogInformation("Scheduling ShowerMonitor polling every {Interval}s, first at {Time}", _options.PollIntervalSeconds, nextPollTime); + + _scheduler.RunEvery(pollInterval, nextPollTime, async void () => + { + try + { + await PollAndUpdateAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during ShowerMonitor poll cycle"); + } + }); + } + + private void ScheduleMidnightReset() + { + _scheduler.ScheduleCron("0 0 * * *", () => + { + try + { + _logger.LogInformation("Midnight reset: clearing shower session counters"); + _detectionService.ResetDailyCounters(); + _ = _entityService.ResetEntitiesAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during midnight reset"); + } + }); + } + + private void SubscribeToCleanupButton() + { + var cleanupButton = new Entity(_haContext, CleanupButtonEntityId); + cleanupButton.StateChanges() + .Subscribe(_ => + { + _logger.LogInformation("Cleanup button pressed, removing all ShowerMonitor entities"); + Task.Run(HandleCleanupAsync); + }); + } + + private async Task HandleCleanupAsync() + { + try + { + await _entityService.CleanupEntitiesAsync(); + _cleanedUp = true; + _detectionService.ResetDailyCounters(); + _fanControlService.Reset(_haContext); + _logger.LogInformation("ShowerMonitor cleanup complete"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during ShowerMonitor cleanup"); + } + } + + private async Task PollAndUpdateAsync() + { + if (_cleanedUp) + { + _logger.LogDebug("ShowerMonitor is cleaned up, skipping poll"); + return; + } + + try + { + var bathroomHumidity = ReadSensorDouble(_options.BathroomHumidityEntityId); + var mainHomeHumidity = ReadSensorDouble(_options.MainHomeHumidityEntityId); + + if (!bathroomHumidity.HasValue || !mainHomeHumidity.HasValue) + { + _logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", bathroomHumidity, mainHomeHumidity); + return; + } + + var timestamp = DateTimeOffset.UtcNow; + var state = _detectionService.Evaluate(bathroomHumidity.Value, mainHomeHumidity.Value, timestamp); + var differential = bathroomHumidity.Value - mainHomeHumidity.Value; + + _fanControlService.Evaluate(state, timestamp, _haContext); + + var context = new ShowerMonitorUpdateContext + { + State = state, + BathroomHumidity = bathroomHumidity.Value, + MainHomeHumidity = mainHomeHumidity.Value, + Differential = differential, + HumidityRate = _rateCalculator.GetRatePerMinute(), + TodaySessionCount = _detectionService.TodaySessionCount, + LastCompletedSession = _detectionService.LastCompletedSession, + CurrentSession = _detectionService.CurrentSession + }; + + await _entityService.UpdateEntitiesAsync(context); + + _logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}", + bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during ShowerMonitor poll"); + } + } + + private double? ReadSensorDouble(string entityId) + { + var state = _haContext.GetState(entityId); + + if (state?.State is null or "unavailable" or "unknown") + { + return null; + } + + return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null; + } +} diff --git a/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs b/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs new file mode 100644 index 0000000..4db6c90 --- /dev/null +++ b/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs @@ -0,0 +1,32 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NetDaemon.AppModel; +using ShowerMonitorManager.Interface; +using ShowerMonitorManager.Models; +using static ShowerMonitor.Models.ShowerMonitorConsts; + +namespace ShowerMonitorManager; + +public static class ShowerMonitorServiceRegistration +{ + public static IServiceCollection AddShowerMonitor(this IServiceCollection services, IConfiguration configuration) + { + var options = configuration + .GetSection(ShowerMonitorOptions.SectionName) + .Get() ?? new ShowerMonitorOptions(); + + if (!options.Enabled) + { + return services; + } + + services + .AddNetDaemonApp() + .AddSingleton(_ => new HumidityRateCalculator(options.RateWindowSize)) + .AddSingleton() + .AddSingleton() + .AddTransient(); + + return services; + } +} diff --git a/ShowerMonitor.Models/Enums/ShowerState.cs b/ShowerMonitor.Models/Enums/ShowerState.cs new file mode 100644 index 0000000..1145495 --- /dev/null +++ b/ShowerMonitor.Models/Enums/ShowerState.cs @@ -0,0 +1,10 @@ +namespace ShowerMonitor.Models.Enums; + +public enum ShowerState +{ + Idle, + Suspected, + Active, + Declining, + Completed +} diff --git a/ShowerMonitor.Models/ShowerMonitor.Models.csproj b/ShowerMonitor.Models/ShowerMonitor.Models.csproj new file mode 100644 index 0000000..2b2ef03 --- /dev/null +++ b/ShowerMonitor.Models/ShowerMonitor.Models.csproj @@ -0,0 +1,18 @@ + + + + net10.0 + enable + enable + ShowerMonitor.Models + + + + + + + + + + + diff --git a/ShowerMonitor.Models/ShowerMonitorConsts.cs b/ShowerMonitor.Models/ShowerMonitorConsts.cs new file mode 100644 index 0000000..85380ad --- /dev/null +++ b/ShowerMonitor.Models/ShowerMonitorConsts.cs @@ -0,0 +1,34 @@ +namespace ShowerMonitor.Models; + +public static class ShowerMonitorConsts +{ + public const int DefaultPollIntervalSeconds = 30; + + public const double DefaultSpikeRateThreshold = 4.0; + public const double DefaultMinDifferentialHumidity = 8.0; + public const double DefaultPeakHumidityThreshold = 58.0; + public const int DefaultConfirmationWindowMinutes = 2; + public const double DefaultRecoveryDifferentialThreshold = 5.0; + public const int DefaultRateWindowSize = 5; + + public static readonly TimeSpan DefaultMaxShowerDuration = TimeSpan.FromMinutes(60); + public static readonly TimeSpan DefaultFanRunAfterShower = TimeSpan.FromMinutes(10); + + public const string BathroomHumidityEntityId = "sensor.bathroom_humidity"; + public const string MainHomeHumidityEntityId = "sensor.main_home_humidity"; + public const string BathroomTemperatureEntityId = "sensor.bathroom_temperature"; + public const string ExhaustFanEntityId = "switch.exhaust_fan"; + + public const string ActiveEntityId = "binary_sensor.showermonitor_active"; + public const string StateEntityId = "sensor.showermonitor_state"; + public const string DifferentialEntityId = "sensor.showermonitor_differential_humidity"; + public const string HumidityRateEntityId = "sensor.showermonitor_humidity_rate"; + public const string TodaySessionCountEntityId = "sensor.showermonitor_today_session_count"; + public const string LastShowerDurationEntityId = "sensor.showermonitor_last_shower_duration"; + public const string LastShowerTimeEntityId = "sensor.showermonitor_last_shower_time"; + public const string CleanupButtonEntityId = "button.showermonitor_cleanup"; + + public const string DeviceIdentifier = "shower_monitor"; + public const string DeviceName = "Shower Monitor"; + public const string DeviceManufacturer = "HomeAssistant App Daemon"; +} diff --git a/ShowerMonitor.Models/ShowerMonitorEntity.cs b/ShowerMonitor.Models/ShowerMonitorEntity.cs new file mode 100644 index 0000000..4edbb3f --- /dev/null +++ b/ShowerMonitor.Models/ShowerMonitorEntity.cs @@ -0,0 +1,25 @@ +using HomeAssistant.Models; +using NetDaemon.Extensions.MqttEntityManager; + +namespace ShowerMonitor.Models; + +public class ShowerMonitorEntity : EntityCreateModel +{ + public string Domain { get; set; } + public string Identifier { get; set; } + public string Name { get; set; } + + public ShowerMonitorEntity(string domain, string identifier, string name) + { + Domain = domain; + Identifier = identifier; + EntityId = $"{Domain}.{Identifier}"; + Name = string.IsNullOrWhiteSpace(name) ? identifier : name; + + Options = new EntityCreationOptions + { + UniqueId = EntityId, + Name = Name + }; + } +} diff --git a/ShowerMonitor.Models/ShowerSession.cs b/ShowerMonitor.Models/ShowerSession.cs new file mode 100644 index 0000000..4516953 --- /dev/null +++ b/ShowerMonitor.Models/ShowerSession.cs @@ -0,0 +1,14 @@ +namespace ShowerMonitor.Models; + +public sealed class ShowerSession +{ + public required DateTimeOffset StartTime { get; init; } + public DateTimeOffset? EndTime { get; set; } + public double PreEventHumidity { get; init; } + public double PeakHumidity { get; set; } + public DateTimeOffset? PeakTime { get; set; } + + public TimeSpan Duration => EndTime.HasValue + ? EndTime.Value - StartTime + : DateTimeOffset.UtcNow - StartTime; +}