@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/LICENSE +21 -0
- package/README.md +22 -2
- package/dist/cloud.d.ts +165 -0
- package/dist/cloud.d.ts.map +1 -0
- package/dist/colors.d.ts +39 -0
- package/dist/colors.d.ts.map +1 -0
- package/dist/constants.d.ts +15 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/controller.d.ts +60 -0
- package/dist/controller.d.ts.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +809 -0
- package/dist/index.js.map +16 -0
- package/dist/protocol.d.ts +47 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/transport.d.ts +19 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transports/noble.d.ts +32 -0
- package/dist/transports/noble.d.ts.map +1 -0
- package/package.json +43 -4
- package/src/cloud.ts +371 -0
- package/src/colors.ts +70 -0
- package/src/constants.ts +19 -0
- package/src/controller.ts +308 -0
- package/src/index.ts +37 -0
- package/src/protocol.ts +116 -0
- package/src/transport.ts +18 -0
- package/src/transports/noble.ts +210 -0
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { COLOR_NAMES, type ColorName, colorNameToRgb, type RGB, rgbToColorName } from "./colors.ts";
|
|
2
|
+
import { BT_TIMEOUT, COMMAND_DELAY } from "./constants.ts";
|
|
3
|
+
import {
|
|
4
|
+
type ColorMode,
|
|
5
|
+
Commands,
|
|
6
|
+
KNOWN_MODEL_COLOR_MODES,
|
|
7
|
+
modelFromName,
|
|
8
|
+
parseResponse,
|
|
9
|
+
type StatusResponse,
|
|
10
|
+
toHex,
|
|
11
|
+
} from "./protocol.ts";
|
|
12
|
+
import type { GoveeTransport } from "./transport.ts";
|
|
13
|
+
|
|
14
|
+
export type Color = ColorName | RGB | { r: number; g: number; b: number };
|
|
15
|
+
|
|
16
|
+
export interface GoveeControllerOptions {
|
|
17
|
+
/** Custom BLE transport. Defaults to `NobleTransport` (requires `@stoprocent/noble`). */
|
|
18
|
+
transport?: GoveeTransport;
|
|
19
|
+
/** Connection/scan timeout in ms, used by the default transport. Default 15000. */
|
|
20
|
+
timeout?: number;
|
|
21
|
+
/** Delay after each command in ms. Default 300. */
|
|
22
|
+
commandDelay?: number;
|
|
23
|
+
/** How long to wait for a status response in ms. Default 3000. */
|
|
24
|
+
responseTimeout?: number;
|
|
25
|
+
/**
|
|
26
|
+
* How this model encodes color commands, see `ColorMode`. Detected automatically by
|
|
27
|
+
* default: from known model names, then from the device's color status, else `"legacy"`.
|
|
28
|
+
*/
|
|
29
|
+
colorMode?: ColorMode;
|
|
30
|
+
/** Receives debug messages. */
|
|
31
|
+
logger?: (message: string) => void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SmoothOptions {
|
|
35
|
+
/** Ramp the brightness instead of switching instantly. */
|
|
36
|
+
smooth?: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type ResponseType = Exclude<StatusResponse["type"], "unknown">;
|
|
40
|
+
type ResponseOf<T extends ResponseType> = Extract<StatusResponse, { type: T }>;
|
|
41
|
+
|
|
42
|
+
interface Waiter {
|
|
43
|
+
type: ResponseType;
|
|
44
|
+
resolve: (response: StatusResponse) => void;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
48
|
+
|
|
49
|
+
export class GoveeController {
|
|
50
|
+
readonly address: string;
|
|
51
|
+
name: string | undefined;
|
|
52
|
+
|
|
53
|
+
/** Last known state, updated by status queries and successful commands. */
|
|
54
|
+
power: boolean | undefined;
|
|
55
|
+
brightness: number | undefined;
|
|
56
|
+
rgb: RGB | undefined;
|
|
57
|
+
colorName: ColorName | undefined;
|
|
58
|
+
|
|
59
|
+
#transport: GoveeTransport | undefined;
|
|
60
|
+
#connected = false;
|
|
61
|
+
#queue: Promise<unknown> = Promise.resolve();
|
|
62
|
+
#waiters = new Set<Waiter>();
|
|
63
|
+
readonly #timeout: number;
|
|
64
|
+
readonly #commandDelay: number;
|
|
65
|
+
readonly #responseTimeout: number;
|
|
66
|
+
#colorMode: ColorMode | undefined;
|
|
67
|
+
readonly #logger: ((message: string) => void) | undefined;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @param address MAC address of the device (or the noble peripheral id on macOS).
|
|
71
|
+
*/
|
|
72
|
+
constructor(address: string, options: GoveeControllerOptions = {}) {
|
|
73
|
+
if (typeof address !== "string") throw new TypeError("address must be a string");
|
|
74
|
+
this.address = address;
|
|
75
|
+
this.#transport = options.transport;
|
|
76
|
+
this.#timeout = options.timeout ?? BT_TIMEOUT;
|
|
77
|
+
this.#commandDelay = options.commandDelay ?? COMMAND_DELAY;
|
|
78
|
+
this.#responseTimeout = options.responseTimeout ?? 3000;
|
|
79
|
+
this.#colorMode = options.colorMode;
|
|
80
|
+
this.#logger = options.logger;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
get connected(): boolean {
|
|
84
|
+
return this.#connected;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The color command format in use, or `undefined` until it has been detected. */
|
|
88
|
+
get colorMode(): ColorMode | undefined {
|
|
89
|
+
return this.#colorMode;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async connect(): Promise<this> {
|
|
93
|
+
if (this.#connected) return this;
|
|
94
|
+
|
|
95
|
+
if (!this.#transport) {
|
|
96
|
+
const { NobleTransport } = await import("./transports/noble.ts");
|
|
97
|
+
this.#transport = new NobleTransport(this.address, { timeout: this.#timeout });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
this.#transport.onDisconnect?.(() => {
|
|
101
|
+
if (!this.#connected) return;
|
|
102
|
+
this.#connected = false;
|
|
103
|
+
this.#log(`Lost connection to ${this.address}`);
|
|
104
|
+
});
|
|
105
|
+
this.name = await this.#transport.connect();
|
|
106
|
+
try {
|
|
107
|
+
await this.#transport.subscribe((data) => this.#handleNotification(data));
|
|
108
|
+
} catch (error) {
|
|
109
|
+
await this.#transport.disconnect().catch(() => {});
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
this.#connected = true;
|
|
113
|
+
|
|
114
|
+
this.#log(`Connected to ${this.name ?? "device"} (${this.address})`);
|
|
115
|
+
return this;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async disconnect(): Promise<void> {
|
|
119
|
+
if (!this.#connected || !this.#transport) return;
|
|
120
|
+
this.#connected = false;
|
|
121
|
+
await this.#queue;
|
|
122
|
+
await this.#transport.unsubscribe().catch(() => {});
|
|
123
|
+
await this.#transport.disconnect();
|
|
124
|
+
this.#log(`Disconnected from ${this.address}`);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Enables `await using device = await new GoveeController(...).connect()`. */
|
|
128
|
+
async [Symbol.asyncDispose](): Promise<void> {
|
|
129
|
+
await this.disconnect();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async getPower(): Promise<boolean> {
|
|
133
|
+
return (await this.#query("power", Commands.getPower())).power;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async getBrightness(): Promise<number> {
|
|
137
|
+
return (await this.#query("brightness", Commands.getBrightness())).brightness;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async getRgb(): Promise<RGB> {
|
|
141
|
+
return (await this.#query("color", Commands.getColor())).rgb;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async turnOn({ smooth = false }: SmoothOptions = {}): Promise<void> {
|
|
145
|
+
this.#log("Turning on");
|
|
146
|
+
if (smooth) {
|
|
147
|
+
for (let i = 0; i < 255; i += 50) {
|
|
148
|
+
await this.setBrightness(i);
|
|
149
|
+
await sleep(150);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
await this.#send(Commands.turnOn());
|
|
153
|
+
this.power = true;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async turnOff({ smooth = false }: SmoothOptions = {}): Promise<void> {
|
|
157
|
+
this.#log("Turning off");
|
|
158
|
+
if (smooth) {
|
|
159
|
+
for (let i = 255; i > 0; i -= 50) {
|
|
160
|
+
await this.setBrightness(i);
|
|
161
|
+
await sleep(150);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
await this.#send(Commands.turnOff());
|
|
165
|
+
this.power = false;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Sets brightness, 0-255. */
|
|
169
|
+
async setBrightness(brightness: number): Promise<void> {
|
|
170
|
+
this.#log(`Setting brightness to ${brightness}`);
|
|
171
|
+
await this.#send(Commands.setBrightness(brightness));
|
|
172
|
+
this.brightness = brightness;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Sets the color from a name (see `COLOR_NAMES`), an `[r, g, b]` tuple or an `{ r, g, b }` object. */
|
|
176
|
+
async setColor(color: Color): Promise<void> {
|
|
177
|
+
const rgb = toRgb(color);
|
|
178
|
+
this.#log(`Setting color to ${rgb.join(", ")}`);
|
|
179
|
+
const mode = await this.#detectColorMode();
|
|
180
|
+
await this.#send(Commands.setColor(rgb, mode));
|
|
181
|
+
this.rgb = rgb;
|
|
182
|
+
this.colorName = rgbToColorName(rgb);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async #detectColorMode(): Promise<ColorMode> {
|
|
186
|
+
if (this.#colorMode) return this.#colorMode;
|
|
187
|
+
|
|
188
|
+
const model = modelFromName(this.name);
|
|
189
|
+
let mode = model ? KNOWN_MODEL_COLOR_MODES[model] : undefined;
|
|
190
|
+
if (!mode) {
|
|
191
|
+
// The color status reply carries the format byte the device itself uses.
|
|
192
|
+
mode = await this.#query("color", Commands.getColor()).then(
|
|
193
|
+
(response) => response.mode,
|
|
194
|
+
() => undefined,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
this.#colorMode = mode ?? "legacy";
|
|
198
|
+
this.#log(`Using color mode "${this.#colorMode}"`);
|
|
199
|
+
return this.#colorMode;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
#log(message: string): void {
|
|
203
|
+
this.#logger?.(message);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
#requireTransport(): GoveeTransport {
|
|
207
|
+
if (!this.#connected || !this.#transport) {
|
|
208
|
+
throw new Error("Not connected, call connect() first");
|
|
209
|
+
}
|
|
210
|
+
return this.#transport;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Runs operations one at a time so writes never interleave. */
|
|
214
|
+
#enqueue<T>(operation: () => Promise<T>): Promise<T> {
|
|
215
|
+
const run = this.#queue.then(operation);
|
|
216
|
+
this.#queue = run.catch(() => {});
|
|
217
|
+
return run;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async #send(packet: Uint8Array): Promise<void> {
|
|
221
|
+
const transport = this.#requireTransport();
|
|
222
|
+
await this.#enqueue(async () => {
|
|
223
|
+
this.#log(`Sending: ${toHex(packet)}`);
|
|
224
|
+
await transport.write(packet);
|
|
225
|
+
await sleep(this.#commandDelay);
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async #query<T extends ResponseType>(type: T, packet: Uint8Array): Promise<ResponseOf<T>> {
|
|
230
|
+
const transport = this.#requireTransport();
|
|
231
|
+
return this.#enqueue(async () => {
|
|
232
|
+
// Register before writing so a fast response can't be missed.
|
|
233
|
+
const response = this.#waitFor(type);
|
|
234
|
+
this.#log(`Sending: ${toHex(packet)}`);
|
|
235
|
+
try {
|
|
236
|
+
await transport.write(packet);
|
|
237
|
+
} catch (error) {
|
|
238
|
+
response.cancel();
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
return (await response.promise) as ResponseOf<T>;
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
#waitFor(type: ResponseType) {
|
|
246
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
247
|
+
let waiter: Waiter | undefined;
|
|
248
|
+
const promise = new Promise<StatusResponse>((resolve, reject) => {
|
|
249
|
+
const entry: Waiter = { type, resolve };
|
|
250
|
+
waiter = entry;
|
|
251
|
+
this.#waiters.add(entry);
|
|
252
|
+
timer = setTimeout(() => {
|
|
253
|
+
this.#waiters.delete(entry);
|
|
254
|
+
reject(new Error(`Timed out waiting for ${type} status from ${this.address}`));
|
|
255
|
+
}, this.#responseTimeout);
|
|
256
|
+
}).finally(() => clearTimeout(timer));
|
|
257
|
+
|
|
258
|
+
const cancel = () => {
|
|
259
|
+
clearTimeout(timer);
|
|
260
|
+
if (waiter) this.#waiters.delete(waiter);
|
|
261
|
+
// The promise will never settle now; nothing should await it.
|
|
262
|
+
};
|
|
263
|
+
return { promise, cancel };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
#handleNotification(data: Uint8Array): void {
|
|
267
|
+
this.#log(`Received: ${toHex(data)}`);
|
|
268
|
+
const response = parseResponse(data);
|
|
269
|
+
|
|
270
|
+
switch (response.type) {
|
|
271
|
+
case "power":
|
|
272
|
+
this.power = response.power;
|
|
273
|
+
break;
|
|
274
|
+
case "brightness":
|
|
275
|
+
this.brightness = response.brightness;
|
|
276
|
+
break;
|
|
277
|
+
case "color":
|
|
278
|
+
this.rgb = response.rgb;
|
|
279
|
+
this.colorName = rgbToColorName(response.rgb);
|
|
280
|
+
break;
|
|
281
|
+
case "unknown":
|
|
282
|
+
this.#log(`Unknown response: ${toHex(data)}`);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
for (const waiter of this.#waiters) {
|
|
287
|
+
if (waiter.type === response.type) {
|
|
288
|
+
this.#waiters.delete(waiter);
|
|
289
|
+
waiter.resolve(response);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function toRgb(color: Color): RGB {
|
|
296
|
+
if (typeof color === "string") {
|
|
297
|
+
const rgb = colorNameToRgb(color);
|
|
298
|
+
if (!rgb) {
|
|
299
|
+
throw new RangeError(`Invalid color name, valid values are: ${COLOR_NAMES.join(", ")}`);
|
|
300
|
+
}
|
|
301
|
+
return rgb;
|
|
302
|
+
}
|
|
303
|
+
if (Array.isArray(color) && color.length === 3) return [color[0], color[1], color[2]];
|
|
304
|
+
if (typeof color === "object" && color !== null && "r" in color) {
|
|
305
|
+
return [color.r, color.g, color.b];
|
|
306
|
+
}
|
|
307
|
+
throw new TypeError("Invalid color, expected a color name, [r, g, b] or { r, g, b }");
|
|
308
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type {
|
|
2
|
+
Capability,
|
|
3
|
+
CapabilityParameters,
|
|
4
|
+
CapabilityState,
|
|
5
|
+
CloudDeviceInfo,
|
|
6
|
+
CloudDeviceState,
|
|
7
|
+
GoveeCloudOptions,
|
|
8
|
+
Scene,
|
|
9
|
+
} from "./cloud.ts";
|
|
10
|
+
export {
|
|
11
|
+
Capabilities,
|
|
12
|
+
CLOUD_BASE_URL,
|
|
13
|
+
CloudDevice,
|
|
14
|
+
GoveeApiError,
|
|
15
|
+
GoveeCloud,
|
|
16
|
+
intToRgb,
|
|
17
|
+
rgbToInt,
|
|
18
|
+
} from "./cloud.ts";
|
|
19
|
+
export type { ColorName, RGB } from "./colors.ts";
|
|
20
|
+
export { COLOR_NAMES, COLORS, colorNameToRgb, isColorName, rgbToColorName } from "./colors.ts";
|
|
21
|
+
export * as Constants from "./constants.ts";
|
|
22
|
+
export type { Color, GoveeControllerOptions, SmoothOptions } from "./controller.ts";
|
|
23
|
+
export { GoveeController } from "./controller.ts";
|
|
24
|
+
export type { ColorMode, StatusResponse } from "./protocol.ts";
|
|
25
|
+
export {
|
|
26
|
+
buildPacket,
|
|
27
|
+
COLOR_MODES,
|
|
28
|
+
Commands,
|
|
29
|
+
checksum,
|
|
30
|
+
KNOWN_MODEL_COLOR_MODES,
|
|
31
|
+
modelFromName,
|
|
32
|
+
parseResponse,
|
|
33
|
+
toHex,
|
|
34
|
+
} from "./protocol.ts";
|
|
35
|
+
export type { GoveeTransport } from "./transport.ts";
|
|
36
|
+
export type { DiscoveredLight, NobleTransportOptions } from "./transports/noble.ts";
|
|
37
|
+
export { discoverLights, NobleTransport } from "./transports/noble.ts";
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import type { RGB } from "./colors.ts";
|
|
2
|
+
import { BRIGHTNESS_MAX, BRIGHTNESS_MIN, PACKET_LENGTH } from "./constants.ts";
|
|
3
|
+
|
|
4
|
+
/** XOR of all bytes. */
|
|
5
|
+
export function checksum(bytes: ArrayLike<number>): number {
|
|
6
|
+
let result = 0;
|
|
7
|
+
for (let i = 0; i < bytes.length; i++) result ^= bytes[i] ?? 0;
|
|
8
|
+
return result;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Builds a 20-byte packet: the payload, zero-padded, followed by its XOR checksum. */
|
|
12
|
+
export function buildPacket(payload: readonly number[]): Uint8Array {
|
|
13
|
+
if (payload.length > PACKET_LENGTH - 1) {
|
|
14
|
+
throw new RangeError(`Payload must be at most ${PACKET_LENGTH - 1} bytes`);
|
|
15
|
+
}
|
|
16
|
+
const packet = new Uint8Array(PACKET_LENGTH);
|
|
17
|
+
packet.set(payload);
|
|
18
|
+
packet[PACKET_LENGTH - 1] = checksum(packet.subarray(0, PACKET_LENGTH - 1));
|
|
19
|
+
return packet;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function assertByte(value: number, label: string, min = 0, max = 255): void {
|
|
23
|
+
if (!Number.isInteger(value)) throw new TypeError(`${label} must be an integer`);
|
|
24
|
+
if (value < min || value > max) {
|
|
25
|
+
throw new RangeError(`${label} must be between ${min} and ${max}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Govee models differ in how they encode "set color":
|
|
31
|
+
* - `legacy`: `33 05 02 RR GG BB ...` (H613B, the original target)
|
|
32
|
+
* - `manual`: `33 05 0D RR GG BB` (many newer strips)
|
|
33
|
+
* - `manual-0b`: `33 05 0B RR GG BB` (some bulbs/strips)
|
|
34
|
+
* - `segments`: `33 05 15 01 RR GG BB ... FF FF`, sets all segments (RGBIC strips)
|
|
35
|
+
*/
|
|
36
|
+
export type ColorMode = "legacy" | "manual" | "manual-0b" | "segments";
|
|
37
|
+
|
|
38
|
+
export const COLOR_MODES: readonly ColorMode[] = ["legacy", "manual", "manual-0b", "segments"];
|
|
39
|
+
|
|
40
|
+
export const Commands = {
|
|
41
|
+
turnOn: () => buildPacket([0x33, 0x01, 0x01]),
|
|
42
|
+
turnOff: () => buildPacket([0x33, 0x01, 0x00]),
|
|
43
|
+
|
|
44
|
+
setBrightness(brightness: number): Uint8Array {
|
|
45
|
+
assertByte(brightness, "Brightness", BRIGHTNESS_MIN, BRIGHTNESS_MAX);
|
|
46
|
+
return buildPacket([0x33, 0x04, brightness]);
|
|
47
|
+
},
|
|
48
|
+
|
|
49
|
+
setColor([r, g, b]: RGB, mode: ColorMode = "legacy"): Uint8Array {
|
|
50
|
+
assertByte(r, "Red");
|
|
51
|
+
assertByte(g, "Green");
|
|
52
|
+
assertByte(b, "Blue");
|
|
53
|
+
switch (mode) {
|
|
54
|
+
case "legacy":
|
|
55
|
+
return buildPacket([0x33, 0x05, 0x02, r, g, b, 0x00, 0xff, 0xae, 0x54]);
|
|
56
|
+
case "manual":
|
|
57
|
+
return buildPacket([0x33, 0x05, 0x0d, r, g, b]);
|
|
58
|
+
case "manual-0b":
|
|
59
|
+
return buildPacket([0x33, 0x05, 0x0b, r, g, b]);
|
|
60
|
+
case "segments":
|
|
61
|
+
return buildPacket([0x33, 0x05, 0x15, 0x01, r, g, b, 0, 0, 0, 0, 0, 0xff, 0xff]);
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
|
|
65
|
+
getPower: () => buildPacket([0xaa, 0x01]),
|
|
66
|
+
getBrightness: () => buildPacket([0xaa, 0x04]),
|
|
67
|
+
getColor: () => buildPacket([0xaa, 0x05, 0x01]),
|
|
68
|
+
} as const;
|
|
69
|
+
|
|
70
|
+
export type StatusResponse =
|
|
71
|
+
| { type: "power"; power: boolean }
|
|
72
|
+
| { type: "brightness"; brightness: number }
|
|
73
|
+
/** `mode` is the color format the device reported, if it's one we know. */
|
|
74
|
+
| { type: "color"; rgb: RGB; mode: ColorMode | undefined }
|
|
75
|
+
| { type: "unknown"; data: Uint8Array };
|
|
76
|
+
|
|
77
|
+
const MODE_BYTES: Record<number, ColorMode> = {
|
|
78
|
+
2: "legacy",
|
|
79
|
+
13: "manual",
|
|
80
|
+
11: "manual-0b",
|
|
81
|
+
21: "segments",
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/** Color formats of models confirmed on real hardware, keyed by model number. */
|
|
85
|
+
export const KNOWN_MODEL_COLOR_MODES: Readonly<Record<string, ColorMode>> = {
|
|
86
|
+
H613B: "legacy",
|
|
87
|
+
H613C: "manual",
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/** Extracts the model number from an advertised name such as `GBK_H613C_6FB2`. */
|
|
91
|
+
export function modelFromName(name: string | undefined): string | undefined {
|
|
92
|
+
return name?.match(/H\d{3,4}[A-Z]?/i)?.[0].toUpperCase();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Parses a notification received on the read characteristic. */
|
|
96
|
+
export function parseResponse(data: Uint8Array): StatusResponse {
|
|
97
|
+
if (data[0] === 0xaa && data.length >= 6) {
|
|
98
|
+
switch (data[1]) {
|
|
99
|
+
case 0x01:
|
|
100
|
+
return { type: "power", power: data[2] === 0x01 };
|
|
101
|
+
case 0x04:
|
|
102
|
+
return { type: "brightness", brightness: data[2] ?? 0 };
|
|
103
|
+
case 0x05:
|
|
104
|
+
return {
|
|
105
|
+
type: "color",
|
|
106
|
+
rgb: [data[3] ?? 0, data[4] ?? 0, data[5] ?? 0],
|
|
107
|
+
mode: MODE_BYTES[data[2] ?? 0],
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return { type: "unknown", data };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function toHex(data: Uint8Array): string {
|
|
115
|
+
return Array.from(data, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
116
|
+
}
|
package/src/transport.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Low-level Bluetooth link to a single Govee device.
|
|
3
|
+
*
|
|
4
|
+
* Implement this to run the controller on any BLE stack (noble, Web Bluetooth,
|
|
5
|
+
* react-native-ble-plx, ...). The bundled implementation is `NobleTransport`.
|
|
6
|
+
*/
|
|
7
|
+
export interface GoveeTransport {
|
|
8
|
+
/** Connects to the device. Resolves with its advertised/GAP name, if available. */
|
|
9
|
+
connect(): Promise<string | undefined>;
|
|
10
|
+
disconnect(): Promise<void>;
|
|
11
|
+
/** Writes a packet to the Govee write characteristic. */
|
|
12
|
+
write(data: Uint8Array): Promise<void>;
|
|
13
|
+
/** Starts delivering notifications from the Govee read characteristic. */
|
|
14
|
+
subscribe(listener: (data: Uint8Array) => void): Promise<void>;
|
|
15
|
+
unsubscribe(): Promise<void>;
|
|
16
|
+
/** Sets a listener for unexpected disconnects (replaces any previous one). Optional. */
|
|
17
|
+
onDisconnect?(listener: () => void): void;
|
|
18
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import type { Characteristic, Noble, Peripheral } from "@stoprocent/noble";
|
|
2
|
+
import {
|
|
3
|
+
BT_TIMEOUT,
|
|
4
|
+
DEVICE_NAME_UUID,
|
|
5
|
+
READ_CHARACTERISTIC_UUID,
|
|
6
|
+
SERVICE_UUID,
|
|
7
|
+
WRITE_CHARACTERISTIC_UUID,
|
|
8
|
+
} from "../constants.ts";
|
|
9
|
+
import type { GoveeTransport } from "../transport.ts";
|
|
10
|
+
|
|
11
|
+
export interface NobleTransportOptions {
|
|
12
|
+
/** Scan/connect timeout in ms. Default 15000. */
|
|
13
|
+
timeout?: number;
|
|
14
|
+
/** Noble instance to use. Defaults to the shared `@stoprocent/noble` instance. */
|
|
15
|
+
noble?: Noble;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const BASE_UUID_SUFFIX = "00001000800000805f9b34fb";
|
|
19
|
+
const CONNECT_ATTEMPTS = 3;
|
|
20
|
+
const CONNECT_SETTLE_DELAY = 750;
|
|
21
|
+
|
|
22
|
+
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
23
|
+
|
|
24
|
+
/** Noble reports UUIDs lowercase without dashes, and standard 16-bit UUIDs in short form. */
|
|
25
|
+
function toNobleUuid(uuid: string): string {
|
|
26
|
+
const flat = uuid.replaceAll("-", "").toLowerCase();
|
|
27
|
+
return flat.startsWith("0000") && flat.endsWith(BASE_UUID_SUFFIX) ? flat.slice(4, 8) : flat;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Strips separators so `A4:C1:38:35:97:24`, `a4c138359724` and noble ids compare equal. */
|
|
31
|
+
function normalizeAddress(address: string): string {
|
|
32
|
+
return address.replace(/[^0-9a-f]/gi, "").toLowerCase();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface DiscoveredLight {
|
|
36
|
+
/** MAC address, or the noble peripheral id where the platform hides it (macOS). */
|
|
37
|
+
address: string;
|
|
38
|
+
name: string;
|
|
39
|
+
rssi: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const GOVEE_NAME = /^(GBK|ihoment|Govee|Minger)_H\d{3,4}/i;
|
|
43
|
+
|
|
44
|
+
/** Scans for nearby Govee lights, recognised by their advertised name. */
|
|
45
|
+
export async function discoverLights(
|
|
46
|
+
options: { timeout?: number; noble?: Noble } = {},
|
|
47
|
+
): Promise<DiscoveredLight[]> {
|
|
48
|
+
const noble = options.noble ?? (await import("@stoprocent/noble")).default;
|
|
49
|
+
await noble.waitForPoweredOnAsync(BT_TIMEOUT);
|
|
50
|
+
|
|
51
|
+
const found = new Map<string, DiscoveredLight>();
|
|
52
|
+
const onDiscover = (p: Peripheral) => {
|
|
53
|
+
const name = p.advertisement.localName;
|
|
54
|
+
if (name && GOVEE_NAME.test(name)) {
|
|
55
|
+
found.set(p.id, { address: p.address || p.id, name, rssi: p.rssi });
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
noble.on("discover", onDiscover);
|
|
59
|
+
try {
|
|
60
|
+
// With duplicates off, noble reports each peripheral only once per process, so a second
|
|
61
|
+
// scan would find nothing. `found` already de-duplicates.
|
|
62
|
+
await noble.startScanningAsync([], true);
|
|
63
|
+
await new Promise((resolve) => setTimeout(resolve, options.timeout ?? 5000));
|
|
64
|
+
} finally {
|
|
65
|
+
noble.off("discover", onDiscover);
|
|
66
|
+
await noble.stopScanningAsync().catch(() => {});
|
|
67
|
+
}
|
|
68
|
+
return [...found.values()].sort((a, b) => b.rssi - a.rssi);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** BLE transport for Node.js / Bun backed by `@stoprocent/noble` (Windows, macOS, Linux). */
|
|
72
|
+
export class NobleTransport implements GoveeTransport {
|
|
73
|
+
readonly #address: string;
|
|
74
|
+
readonly #timeout: number;
|
|
75
|
+
#noble: Noble | undefined;
|
|
76
|
+
#peripheral: Peripheral | undefined;
|
|
77
|
+
#write: Characteristic | undefined;
|
|
78
|
+
#read: Characteristic | undefined;
|
|
79
|
+
#listener: ((data: Buffer) => void) | undefined;
|
|
80
|
+
#onDisconnect: (() => void) | undefined;
|
|
81
|
+
|
|
82
|
+
/** @param address MAC address, or the noble peripheral id (macOS hides MAC addresses). */
|
|
83
|
+
constructor(address: string, options: NobleTransportOptions = {}) {
|
|
84
|
+
this.#address = normalizeAddress(address);
|
|
85
|
+
this.#timeout = options.timeout ?? BT_TIMEOUT;
|
|
86
|
+
this.#noble = options.noble;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async connect(): Promise<string | undefined> {
|
|
90
|
+
this.#noble ??= (await import("@stoprocent/noble")).default;
|
|
91
|
+
await this.#noble.waitForPoweredOnAsync(this.#timeout);
|
|
92
|
+
|
|
93
|
+
const peripheral = await this.#find(this.#noble);
|
|
94
|
+
|
|
95
|
+
for (let attempt = 1; ; attempt++) {
|
|
96
|
+
try {
|
|
97
|
+
await this.#open(peripheral);
|
|
98
|
+
break;
|
|
99
|
+
} catch (error) {
|
|
100
|
+
await peripheral.disconnectAsync().catch(() => {});
|
|
101
|
+
if (attempt >= CONNECT_ATTEMPTS) throw error;
|
|
102
|
+
await sleep(500);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
this.#peripheral = peripheral;
|
|
107
|
+
peripheral.once("disconnect", () => {
|
|
108
|
+
// Ignore the event for a disconnect() we initiated, or for a stale peripheral.
|
|
109
|
+
if (this.#peripheral !== peripheral) return;
|
|
110
|
+
this.#peripheral = this.#write = this.#read = undefined;
|
|
111
|
+
this.#onDisconnect?.();
|
|
112
|
+
});
|
|
113
|
+
return (await this.#readName(peripheral)) ?? peripheral.advertisement.localName;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async #open(peripheral: Peripheral): Promise<void> {
|
|
117
|
+
await peripheral.connectAsync();
|
|
118
|
+
// On Windows, noble reports "connected" before the GATT session is usable, and discovering
|
|
119
|
+
// services straight away makes the device drop the connection.
|
|
120
|
+
await sleep(CONNECT_SETTLE_DELAY);
|
|
121
|
+
|
|
122
|
+
const writeUuid = toNobleUuid(WRITE_CHARACTERISTIC_UUID);
|
|
123
|
+
const readUuid = toNobleUuid(READ_CHARACTERISTIC_UUID);
|
|
124
|
+
const { characteristics } = await peripheral.discoverSomeServicesAndCharacteristicsAsync(
|
|
125
|
+
[toNobleUuid(SERVICE_UUID)],
|
|
126
|
+
[writeUuid, readUuid],
|
|
127
|
+
);
|
|
128
|
+
this.#write = characteristics.find((c) => c.uuid === writeUuid);
|
|
129
|
+
this.#read = characteristics.find((c) => c.uuid === readUuid);
|
|
130
|
+
if (!this.#write || !this.#read) {
|
|
131
|
+
throw new Error(`${this.#address} does not expose the Govee control characteristics`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async disconnect(): Promise<void> {
|
|
136
|
+
const peripheral = this.#peripheral;
|
|
137
|
+
this.#peripheral = this.#write = this.#read = undefined;
|
|
138
|
+
await peripheral?.disconnectAsync();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async write(data: Uint8Array): Promise<void> {
|
|
142
|
+
const characteristic = this.#require(this.#write);
|
|
143
|
+
const withoutResponse = !characteristic.properties.includes("write");
|
|
144
|
+
await characteristic.writeAsync(Buffer.from(data), withoutResponse);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async subscribe(listener: (data: Uint8Array) => void): Promise<void> {
|
|
148
|
+
const characteristic = this.#require(this.#read);
|
|
149
|
+
if (this.#listener) characteristic.off("data", this.#listener);
|
|
150
|
+
this.#listener = (data) => listener(new Uint8Array(data));
|
|
151
|
+
characteristic.on("data", this.#listener);
|
|
152
|
+
await characteristic.subscribeAsync();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async unsubscribe(): Promise<void> {
|
|
156
|
+
const characteristic = this.#read;
|
|
157
|
+
if (!characteristic) return;
|
|
158
|
+
if (this.#listener) characteristic.off("data", this.#listener);
|
|
159
|
+
this.#listener = undefined;
|
|
160
|
+
await characteristic.unsubscribeAsync();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
onDisconnect(listener: () => void): void {
|
|
164
|
+
this.#onDisconnect = listener;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
#require(characteristic: Characteristic | undefined): Characteristic {
|
|
168
|
+
if (!characteristic) throw new Error("Not connected");
|
|
169
|
+
return characteristic;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
#find(noble: Noble): Promise<Peripheral> {
|
|
173
|
+
const matches = (p: Peripheral) =>
|
|
174
|
+
normalizeAddress(p.address ?? "") === this.#address ||
|
|
175
|
+
normalizeAddress(p.id) === this.#address;
|
|
176
|
+
|
|
177
|
+
return new Promise<Peripheral>((resolve, reject) => {
|
|
178
|
+
const finish = (error: Error | undefined, peripheral?: Peripheral) => {
|
|
179
|
+
clearTimeout(timer);
|
|
180
|
+
noble.off("discover", onDiscover);
|
|
181
|
+
noble.stopScanningAsync().catch(() => {});
|
|
182
|
+
if (peripheral) resolve(peripheral);
|
|
183
|
+
else reject(error);
|
|
184
|
+
};
|
|
185
|
+
const onDiscover = (peripheral: Peripheral) => {
|
|
186
|
+
if (matches(peripheral)) finish(undefined, peripheral);
|
|
187
|
+
};
|
|
188
|
+
const timer = setTimeout(
|
|
189
|
+
() => finish(new Error(`Could not find device ${this.#address}`)),
|
|
190
|
+
this.#timeout,
|
|
191
|
+
);
|
|
192
|
+
noble.on("discover", onDiscover);
|
|
193
|
+
noble.startScanningAsync([], false).catch((error: Error) => finish(error));
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async #readName(peripheral: Peripheral): Promise<string | undefined> {
|
|
198
|
+
try {
|
|
199
|
+
const { characteristics } = await peripheral.discoverSomeServicesAndCharacteristicsAsync(
|
|
200
|
+
["1800"],
|
|
201
|
+
[toNobleUuid(DEVICE_NAME_UUID)],
|
|
202
|
+
);
|
|
203
|
+
const raw = await characteristics[0]?.readAsync();
|
|
204
|
+
return raw ? new TextDecoder().decode(raw).replace(/\0+$/, "") : undefined;
|
|
205
|
+
} catch {
|
|
206
|
+
// Some platforms (notably Windows) don't allow reading the GAP service.
|
|
207
|
+
return undefined;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|