Files
govee-csharp-connector/GoveeCSharpConnector/Services/GoveeApiService.cs

65 lines
2.6 KiB
C#

using GoveeCSharpConnector.Interfaces;
using GoveeCSharpConnector.Objects;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
namespace GoveeCSharpConnector.Services;
public class GoveeApiService : IGoveeApiService {
private string _APIKey = string.Empty;
private readonly HttpClient _HttpClient = new();
private const string _GoveeApiAddress = "https://developer-api.govee.com/v1";
public string GetApiKey() =>
_APIKey;
public void SetApiKey(string apiKey) {
_APIKey = apiKey;
_HttpClient.DefaultRequestHeaders.Add("Govee-API-Key", _APIKey);
}
public void RemoveApiKey() {
_APIKey = string.Empty;
_ = _HttpClient.DefaultRequestHeaders.Remove("Govee-Api-Key");
}
private readonly JsonSerializerOptions _JsonOptions = new() {
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
public Task<HttpResponseMessage> ToggleStateAsync(string deviceId, string deviceModel, bool on) =>
SendCommandAsync(deviceId, deviceModel, "turn", on ? "on" : "off");
public Task<HttpResponseMessage> SetBrightnessAsync(string deviceId, string deviceModel, int value) =>
SendCommandAsync(deviceId, deviceModel, "brightness", value);
public Task<HttpResponseMessage> SetColorAsync(string deviceId, string deviceModel, RgbColor color) =>
SendCommandAsync(deviceId, deviceModel, "color", color);
public Task<HttpResponseMessage> SetColorTempAsync(string deviceId, string deviceModel, int value) =>
SendCommandAsync(deviceId, deviceModel, "colorTem", value);
public Task<GoveeResponse> GetDevicesResponseAsync() =>
_HttpClient.GetFromJsonAsync<GoveeResponse>($"{_GoveeApiAddress}/devices");
public Task<GoveeApiState> GetDeviceStateAsync(string deviceId, string deviceModel) =>
_HttpClient.GetFromJsonAsync<GoveeApiState>($"{_GoveeApiAddress}/devices/state?device={deviceId}&model={deviceModel}");
private Task<HttpResponseMessage> SendCommandAsync(string deviceId, string deviceModel, string command, object commandObject) {
Task<HttpResponseMessage> result;
GoveeApiCommand commandRequest = new() {
Device = deviceId,
Model = deviceModel,
Cmd = new Command() {
Name = command,
Value = commandObject
}
};
StringContent httpContent = new(JsonSerializer.Serialize(commandRequest, _JsonOptions), Encoding.UTF8, "application/json");
result = _HttpClient.PutAsync($"{_GoveeApiAddress}/devices/control", httpContent);
return result;
}
}