108 lines
4.4 KiB
C#
108 lines
4.4 KiB
C#
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();
|
|
}
|
|
}
|