@sdeck/govee 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cloud.ts ADDED
@@ -0,0 +1,371 @@
1
+ import type { RGB } from "./colors.ts";
2
+
3
+ /**
4
+ * Client for Govee's official cloud API (https://developer.govee.com), which reaches every
5
+ * Wi-Fi device on your account from anywhere. Get a key in the Govee Home app:
6
+ * Profile → Settings → Apply for API Key.
7
+ */
8
+
9
+ export const CLOUD_BASE_URL = "https://openapi.api.govee.com";
10
+
11
+ export interface Capability {
12
+ type: string;
13
+ instance: string;
14
+ parameters?: CapabilityParameters;
15
+ }
16
+
17
+ export interface CapabilityParameters {
18
+ dataType?: "ENUM" | "INTEGER" | "STRUCT" | string;
19
+ unit?: string;
20
+ options?: { name: string; value: unknown }[];
21
+ range?: { min: number; max: number; precision?: number };
22
+ fields?: { fieldName: string; dataType: string; required?: boolean; [key: string]: unknown }[];
23
+ }
24
+
25
+ export interface CloudDeviceInfo {
26
+ sku: string;
27
+ /** Device id, e.g. `64:09:C5:32:37:36:2D:13`. */
28
+ device: string;
29
+ deviceName?: string;
30
+ type?: string;
31
+ capabilities: Capability[];
32
+ }
33
+
34
+ export interface CapabilityState {
35
+ type: string;
36
+ instance: string;
37
+ state: { value: unknown };
38
+ }
39
+
40
+ export interface CloudDeviceState {
41
+ /** If false, the other values are the last known state. */
42
+ online: boolean | undefined;
43
+ power: boolean | undefined;
44
+ /** 1-100. */
45
+ brightness: number | undefined;
46
+ rgb: RGB | undefined;
47
+ colorTemperature: number | undefined;
48
+ /** Every capability as returned by the API, including ones without a typed field above. */
49
+ capabilities: CapabilityState[];
50
+ }
51
+
52
+ /** A scene that can be passed to `setScene`. */
53
+ export interface Scene {
54
+ name: string;
55
+ type: string;
56
+ instance: string;
57
+ value: unknown;
58
+ }
59
+
60
+ export class GoveeApiError extends Error {
61
+ constructor(
62
+ message: string,
63
+ /** HTTP status, or the `code` field of the response body. */
64
+ readonly status: number,
65
+ readonly body?: unknown,
66
+ ) {
67
+ super(message);
68
+ this.name = "GoveeApiError";
69
+ }
70
+ }
71
+
72
+ export interface GoveeCloudOptions {
73
+ baseUrl?: string;
74
+ /** Custom fetch, e.g. for proxies or tests. */
75
+ fetch?: typeof fetch;
76
+ }
77
+
78
+ export const Capabilities = {
79
+ power: { type: "devices.capabilities.on_off", instance: "powerSwitch" },
80
+ brightness: { type: "devices.capabilities.range", instance: "brightness" },
81
+ colorRgb: { type: "devices.capabilities.color_setting", instance: "colorRgb" },
82
+ colorTemperature: { type: "devices.capabilities.color_setting", instance: "colorTemperatureK" },
83
+ segmentColor: {
84
+ type: "devices.capabilities.segment_color_setting",
85
+ instance: "segmentedColorRgb",
86
+ },
87
+ segmentBrightness: {
88
+ type: "devices.capabilities.segment_color_setting",
89
+ instance: "segmentedBrightness",
90
+ },
91
+ online: { type: "devices.capabilities.online", instance: "online" },
92
+ } as const;
93
+
94
+ export const rgbToInt = ([r, g, b]: RGB): number =>
95
+ ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
96
+ export const intToRgb = (value: number): RGB => [
97
+ (value >> 16) & 0xff,
98
+ (value >> 8) & 0xff,
99
+ value & 0xff,
100
+ ];
101
+
102
+ export class GoveeCloud {
103
+ readonly #apiKey: string;
104
+ readonly #baseUrl: string;
105
+ readonly #fetch: typeof fetch;
106
+
107
+ constructor(apiKey: string, options: GoveeCloudOptions = {}) {
108
+ if (!apiKey) throw new TypeError("A Govee API key is required");
109
+ this.#apiKey = apiKey;
110
+ this.#baseUrl = options.baseUrl ?? CLOUD_BASE_URL;
111
+ this.#fetch = options.fetch ?? fetch;
112
+ }
113
+
114
+ /** Lists every device on the account, with what each one supports. */
115
+ async listDevices(): Promise<CloudDevice[]> {
116
+ const body = await this.#request<{ data: CloudDeviceInfo[] }>(
117
+ "GET",
118
+ "/router/api/v1/user/devices",
119
+ );
120
+ return body.data.map((info) => new CloudDevice(this, info));
121
+ }
122
+
123
+ /** Finds a device by id or (case-insensitive) name. */
124
+ async getDevice(idOrName: string): Promise<CloudDevice> {
125
+ const devices = await this.listDevices();
126
+ const needle = idOrName.toLowerCase();
127
+ const found = devices.find(
128
+ (d) => d.id.toLowerCase() === needle || d.name.toLowerCase() === needle,
129
+ );
130
+ if (!found) throw new GoveeApiError(`No device named or with id "${idOrName}"`, 404);
131
+ return found;
132
+ }
133
+
134
+ async getState(sku: string, device: string): Promise<CloudDeviceState> {
135
+ const body = await this.#request<{ payload: { capabilities: CapabilityState[] } }>(
136
+ "POST",
137
+ "/router/api/v1/device/state",
138
+ { requestId: crypto.randomUUID(), payload: { sku, device } },
139
+ );
140
+ return parseState(body.payload.capabilities);
141
+ }
142
+
143
+ async control(
144
+ sku: string,
145
+ device: string,
146
+ capability: { type: string; instance: string; value: unknown },
147
+ ): Promise<void> {
148
+ await this.#request("POST", "/router/api/v1/device/control", {
149
+ requestId: crypto.randomUUID(),
150
+ payload: { sku, device, capability },
151
+ });
152
+ }
153
+
154
+ /** Built-in dynamic scenes ("Sunrise", "Aurora", ...). */
155
+ async getScenes(sku: string, device: string): Promise<Scene[]> {
156
+ return this.#scenes("/router/api/v1/device/scenes", sku, device);
157
+ }
158
+
159
+ /** DIY scenes created in the Govee Home app. */
160
+ async getDiyScenes(sku: string, device: string): Promise<Scene[]> {
161
+ return this.#scenes("/router/api/v1/device/diy-scenes", sku, device);
162
+ }
163
+
164
+ async #scenes(path: string, sku: string, device: string): Promise<Scene[]> {
165
+ const body = await this.#request<{ payload: { capabilities: Capability[] } }>("POST", path, {
166
+ requestId: crypto.randomUUID(),
167
+ payload: { sku, device },
168
+ });
169
+ return body.payload.capabilities.flatMap((capability) =>
170
+ (capability.parameters?.options ?? []).map((option) => ({
171
+ name: option.name,
172
+ type: capability.type,
173
+ instance: capability.instance,
174
+ value: option.value,
175
+ })),
176
+ );
177
+ }
178
+
179
+ async #request<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> {
180
+ const response = await this.#fetch(this.#baseUrl + path, {
181
+ method,
182
+ headers: { "Content-Type": "application/json", "Govee-API-Key": this.#apiKey },
183
+ body: body === undefined ? undefined : JSON.stringify(body),
184
+ });
185
+
186
+ const text = await response.text();
187
+ let json: { code?: number; message?: string; msg?: string } | undefined;
188
+ try {
189
+ json = text ? JSON.parse(text) : undefined;
190
+ } catch {
191
+ // Non-JSON error pages are reported with their status below.
192
+ }
193
+
194
+ const code = json?.code ?? response.status;
195
+ if (!response.ok || code !== 200) {
196
+ const status = response.ok ? code : response.status;
197
+ const message = json?.message ?? json?.msg ?? (text || response.statusText);
198
+ const hint =
199
+ status === 401
200
+ ? " (check your API key)"
201
+ : status === 429
202
+ ? " (rate limited, slow down)"
203
+ : "";
204
+ throw new GoveeApiError(
205
+ `Govee API ${method} ${path} failed: ${status} ${message}${hint}`,
206
+ status,
207
+ json ?? text,
208
+ );
209
+ }
210
+ return json as T;
211
+ }
212
+ }
213
+
214
+ function parseState(capabilities: CapabilityState[]): CloudDeviceState {
215
+ const value = (instance: string) => {
216
+ const v = capabilities.find((c) => c.instance === instance)?.state.value;
217
+ return v === "" || v === null ? undefined : v;
218
+ };
219
+ const number = (instance: string) => {
220
+ const v = value(instance);
221
+ return typeof v === "number" ? v : undefined;
222
+ };
223
+
224
+ const online = value("online");
225
+ const power = number("powerSwitch");
226
+ const color = number("colorRgb");
227
+ return {
228
+ online: typeof online === "boolean" ? online : undefined,
229
+ power: power === undefined ? undefined : power === 1,
230
+ brightness: number("brightness"),
231
+ rgb: color === undefined ? undefined : intToRgb(color),
232
+ colorTemperature: number("colorTemperatureK") || undefined,
233
+ capabilities,
234
+ };
235
+ }
236
+
237
+ /** A device on the account, with helpers for the common capabilities. */
238
+ export class CloudDevice {
239
+ readonly sku: string;
240
+ readonly id: string;
241
+ readonly name: string;
242
+ readonly type: string | undefined;
243
+ readonly capabilities: readonly Capability[];
244
+ readonly #cloud: GoveeCloud;
245
+
246
+ constructor(cloud: GoveeCloud, info: CloudDeviceInfo) {
247
+ this.#cloud = cloud;
248
+ this.sku = info.sku;
249
+ this.id = info.device;
250
+ this.name = info.deviceName || info.sku;
251
+ this.type = info.type;
252
+ this.capabilities = info.capabilities ?? [];
253
+ }
254
+
255
+ /** The capability definition for an instance, e.g. `"brightness"`, if the device has it. */
256
+ capability(instance: string): Capability | undefined {
257
+ return this.capabilities.find((c) => c.instance === instance);
258
+ }
259
+
260
+ supports(instance: string): boolean {
261
+ return this.capability(instance) !== undefined;
262
+ }
263
+
264
+ /** Groups made in the Govee app (sku `BaseGroup`, `SameModeGroup`, ...) only support power. */
265
+ get isGroup(): boolean {
266
+ return /group$/i.test(this.sku);
267
+ }
268
+
269
+ getState(): Promise<CloudDeviceState> {
270
+ if (this.isGroup) {
271
+ return Promise.reject(
272
+ new GoveeApiError(`${this.name} is a group; groups have no readable state`, 400),
273
+ );
274
+ }
275
+ return this.#cloud.getState(this.sku, this.id);
276
+ }
277
+
278
+ /** Sends any capability, for features without a dedicated helper. */
279
+ control(type: string, instance: string, value: unknown): Promise<void> {
280
+ return this.#cloud.control(this.sku, this.id, { type, instance, value });
281
+ }
282
+
283
+ setPower(on: boolean): Promise<void> {
284
+ return this.#send(Capabilities.power, on ? 1 : 0);
285
+ }
286
+
287
+ turnOn(): Promise<void> {
288
+ return this.setPower(true);
289
+ }
290
+
291
+ turnOff(): Promise<void> {
292
+ return this.setPower(false);
293
+ }
294
+
295
+ /** Brightness in percent, 1-100. */
296
+ setBrightness(percent: number): Promise<void> {
297
+ const { min, max } = this.capability("brightness")?.parameters?.range ?? { min: 1, max: 100 };
298
+ return this.#send(Capabilities.brightness, clampInt(percent, min, max, "Brightness"));
299
+ }
300
+
301
+ setColor(rgb: RGB): Promise<void> {
302
+ for (const channel of rgb) clampInt(channel, 0, 255, "Color channel", true);
303
+ return this.#send(Capabilities.colorRgb, rgbToInt(rgb));
304
+ }
305
+
306
+ /** Color temperature in Kelvin; the valid range depends on the device (often 2000-9000). */
307
+ setColorTemperature(kelvin: number): Promise<void> {
308
+ const { min, max } = this.capability("colorTemperatureK")?.parameters?.range ?? {
309
+ min: 2000,
310
+ max: 9000,
311
+ };
312
+ return this.#send(
313
+ Capabilities.colorTemperature,
314
+ clampInt(kelvin, min, max, "Color temperature"),
315
+ );
316
+ }
317
+
318
+ /** Colors individual segments of an RGBIC strip. Segment indexes start at 0. */
319
+ setSegmentColor(segments: number[], rgb: RGB): Promise<void> {
320
+ return this.#send(Capabilities.segmentColor, { segment: segments, rgb: rgbToInt(rgb) });
321
+ }
322
+
323
+ setSegmentBrightness(segments: number[], percent: number): Promise<void> {
324
+ return this.#send(Capabilities.segmentBrightness, {
325
+ segment: segments,
326
+ brightness: clampInt(percent, 0, 100, "Brightness"),
327
+ });
328
+ }
329
+
330
+ /** Built-in scenes; empty if the device has none (the API would answer 400). */
331
+ async getScenes(): Promise<Scene[]> {
332
+ return this.supports("lightScene") ? this.#cloud.getScenes(this.sku, this.id) : [];
333
+ }
334
+
335
+ /** DIY scenes made in the Govee Home app; empty if the device doesn't support them. */
336
+ async getDiyScenes(): Promise<Scene[]> {
337
+ return this.supports("diyScene") ? this.#cloud.getDiyScenes(this.sku, this.id) : [];
338
+ }
339
+
340
+ /** Built-in and DIY scenes together. */
341
+ async getAllScenes(): Promise<Scene[]> {
342
+ const [scenes, diy] = await Promise.all([this.getScenes(), this.getDiyScenes()]);
343
+ return [...scenes, ...diy];
344
+ }
345
+
346
+ /** Applies a scene from `getScenes()` / `getDiyScenes()`. */
347
+ setScene(scene: Scene): Promise<void> {
348
+ return this.control(scene.type, scene.instance, scene.value);
349
+ }
350
+
351
+ #send(capability: { type: string; instance: string }, value: unknown): Promise<void> {
352
+ if (!this.supports(capability.instance)) {
353
+ return Promise.reject(
354
+ new GoveeApiError(
355
+ `${this.name} (${this.sku}) does not support ${capability.instance}`,
356
+ 400,
357
+ ),
358
+ );
359
+ }
360
+ return this.control(capability.type, capability.instance, value);
361
+ }
362
+ }
363
+
364
+ function clampInt(value: number, min: number, max: number, label: string, strict = false): number {
365
+ if (!Number.isFinite(value)) throw new TypeError(`${label} must be a number`);
366
+ const rounded = Math.round(value);
367
+ if (strict && (rounded < min || rounded > max)) {
368
+ throw new RangeError(`${label} must be between ${min} and ${max}`);
369
+ }
370
+ return Math.min(max, Math.max(min, rounded));
371
+ }
package/src/colors.ts ADDED
@@ -0,0 +1,70 @@
1
+ export type RGB = readonly [r: number, g: number, b: number];
2
+
3
+ export const COLORS = {
4
+ white: [255, 255, 255],
5
+ warm_white: [255, 166, 87],
6
+ cool_white: [255, 254, 250],
7
+
8
+ black: [0, 0, 0],
9
+
10
+ red: [255, 0, 0],
11
+ dark_red: [139, 0, 0],
12
+ light_red: [255, 69, 69],
13
+
14
+ green: [0, 255, 0],
15
+ dark_green: [0, 100, 0],
16
+ light_green: [144, 238, 144],
17
+
18
+ blue: [0, 0, 255],
19
+ dark_blue: [0, 0, 139],
20
+ light_blue: [173, 216, 230],
21
+
22
+ yellow: [255, 255, 0],
23
+ dark_yellow: [184, 134, 11],
24
+ light_yellow: [255, 255, 153],
25
+
26
+ orange: [255, 165, 0],
27
+ dark_orange: [255, 140, 0],
28
+ light_orange: [255, 179, 71],
29
+
30
+ purple: [128, 0, 128],
31
+ dark_purple: [75, 0, 130],
32
+ light_purple: [218, 112, 214],
33
+
34
+ pink: [255, 182, 193],
35
+ dark_pink: [255, 20, 147],
36
+ light_pink: [255, 182, 193],
37
+
38
+ brown: [165, 42, 42],
39
+ dark_brown: [139, 69, 19],
40
+ light_brown: [205, 133, 63],
41
+ } as const satisfies Record<string, RGB>;
42
+
43
+ export type ColorName = keyof typeof COLORS;
44
+
45
+ export const COLOR_NAMES = Object.keys(COLORS) as ColorName[];
46
+
47
+ export function isColorName(name: string): name is ColorName {
48
+ return Object.hasOwn(COLORS, name.toLowerCase());
49
+ }
50
+
51
+ /** Looks up a named color (case-insensitive). Returns `undefined` for unknown names. */
52
+ export function colorNameToRgb(name: string): RGB | undefined {
53
+ const key = name.toLowerCase();
54
+ return isColorName(key) ? COLORS[key] : undefined;
55
+ }
56
+
57
+ /** Returns the named color closest (by euclidean distance) to the given RGB value. */
58
+ export function rgbToColorName(rgb: RGB): ColorName {
59
+ let closest: ColorName = "black";
60
+ let min = Infinity;
61
+ for (const name of COLOR_NAMES) {
62
+ const [r, g, b] = COLORS[name];
63
+ const d = Math.hypot(rgb[0] - r, rgb[1] - g, rgb[2] - b);
64
+ if (d < min) {
65
+ min = d;
66
+ closest = name;
67
+ }
68
+ }
69
+ return closest;
70
+ }
@@ -0,0 +1,19 @@
1
+ /** Bluetooth connection/scan timeout in milliseconds. */
2
+ export const BT_TIMEOUT = 15_000;
3
+
4
+ /** Delay after each command so the device can keep up, in milliseconds. */
5
+ export const COMMAND_DELAY = 300;
6
+
7
+ export const BRIGHTNESS_MIN = 0;
8
+ export const BRIGHTNESS_MAX = 255;
9
+
10
+ /** Standard GAP "Device Name" characteristic. */
11
+ export const DEVICE_NAME_UUID = "00002a00-0000-1000-8000-00805f9b34fb";
12
+
13
+ /** Govee control service. */
14
+ export const SERVICE_UUID = "00010203-0405-0607-0809-0a0b0c0d1910";
15
+ export const WRITE_CHARACTERISTIC_UUID = "00010203-0405-0607-0809-0a0b0c0d2b11";
16
+ export const READ_CHARACTERISTIC_UUID = "00010203-0405-0607-0809-0a0b0c0d2b10";
17
+
18
+ /** Every Govee packet is exactly 20 bytes: 19 bytes of payload plus an XOR checksum. */
19
+ export const PACKET_LENGTH = 20;