feat: add BatteryMonitor implementation with discovery, notification, and scheduling services
This commit is contained in:
@@ -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
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user