feat: add BatteryMonitor implementation with discovery, notification, and scheduling services

This commit is contained in:
Marius
2026-04-01 10:55:33 +03:00
parent 11c2574235
commit 6e4d684359
114 changed files with 22820 additions and 527 deletions
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>HomeAssistant.McpServer</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
</ItemGroup>
</Project>
+25
View File
@@ -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<HomeAssistantSettings>(
builder.Configuration.GetSection(HomeAssistantSettings.SectionName))
.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
@@ -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<HomeAssistantSettings> 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<JsonElement> GetApiStatusAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/", cancellationToken);
public Task<JsonElement> GetConfigAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/config", cancellationToken);
public Task<JsonElement> GetAllStatesAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/states", cancellationToken);
public Task<JsonElement> GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default) =>
GetJsonAsync($"/api/states/{Uri.EscapeDataString(entityId)}", cancellationToken);
public Task<JsonElement> GetServicesAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/services", cancellationToken);
public Task<JsonElement> 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<JsonElement> 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<string>();
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<JsonElement> 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<JsonElement> 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();
}
}
@@ -0,0 +1,31 @@
using System.Text.Json;
namespace HomeAssistant.McpServer.Services;
public interface IHomeAssistantApiClient
{
Task<JsonElement> GetApiStatusAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetConfigAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetAllStatesAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default);
Task<JsonElement> GetServicesAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default);
Task<JsonElement> GetLogbookAsync(
string? entityId = null,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
CancellationToken cancellationToken = default);
Task<JsonElement> CallServiceAsync(
string domain,
string service,
JsonElement? serviceData = null,
CancellationToken cancellationToken = default);
}
@@ -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;
}
@@ -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<string> 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<string> 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<string> 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
};
}
@@ -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<string> 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
};
}
@@ -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<string> 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
};
}
@@ -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<string> 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<string> 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<string, object>()
: JsonSerializer.Deserialize<Dictionary<string, object>>(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
};
}
@@ -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<string> 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<string> 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
};
}