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 ToggleStateAsync(string deviceId, string deviceModel, bool on) => SendCommandAsync(deviceId, deviceModel, "turn", on ? "on" : "off"); public Task SetBrightnessAsync(string deviceId, string deviceModel, int value) => SendCommandAsync(deviceId, deviceModel, "brightness", value); public Task SetColorAsync(string deviceId, string deviceModel, RgbColor color) => SendCommandAsync(deviceId, deviceModel, "color", color); public Task SetColorTempAsync(string deviceId, string deviceModel, int value) => SendCommandAsync(deviceId, deviceModel, "colorTem", value); public Task GetDevicesResponseAsync() => _HttpClient.GetFromJsonAsync($"{_GoveeApiAddress}/devices"); public Task GetDeviceStateAsync(string deviceId, string deviceModel) => _HttpClient.GetFromJsonAsync($"{_GoveeApiAddress}/devices/state?device={deviceId}&model={deviceModel}"); private Task SendCommandAsync(string deviceId, string deviceModel, string command, object commandObject) { Task 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; } }