@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/dist/index.js ADDED
@@ -0,0 +1,809 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __returnValue = (v) => v;
3
+ function __exportSetter(name, newValue) {
4
+ this[name] = __returnValue.bind(null, newValue);
5
+ }
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true,
11
+ configurable: true,
12
+ set: __exportSetter.bind(all, name)
13
+ });
14
+ };
15
+ var __esm = (fn, res, err) => () => {
16
+ if (fn)
17
+ try {
18
+ res = fn(fn = 0);
19
+ } catch (e) {
20
+ err = [e];
21
+ }
22
+ if (err)
23
+ throw err[0];
24
+ return res;
25
+ };
26
+
27
+ // src/constants.ts
28
+ var exports_constants = {};
29
+ __export(exports_constants, {
30
+ BRIGHTNESS_MAX: () => BRIGHTNESS_MAX,
31
+ BRIGHTNESS_MIN: () => BRIGHTNESS_MIN,
32
+ BT_TIMEOUT: () => BT_TIMEOUT,
33
+ COMMAND_DELAY: () => COMMAND_DELAY,
34
+ DEVICE_NAME_UUID: () => DEVICE_NAME_UUID,
35
+ PACKET_LENGTH: () => PACKET_LENGTH,
36
+ READ_CHARACTERISTIC_UUID: () => READ_CHARACTERISTIC_UUID,
37
+ SERVICE_UUID: () => SERVICE_UUID,
38
+ WRITE_CHARACTERISTIC_UUID: () => WRITE_CHARACTERISTIC_UUID
39
+ });
40
+ var BT_TIMEOUT = 15000, COMMAND_DELAY = 300, BRIGHTNESS_MIN = 0, BRIGHTNESS_MAX = 255, DEVICE_NAME_UUID = "00002a00-0000-1000-8000-00805f9b34fb", SERVICE_UUID = "00010203-0405-0607-0809-0a0b0c0d1910", WRITE_CHARACTERISTIC_UUID = "00010203-0405-0607-0809-0a0b0c0d2b11", READ_CHARACTERISTIC_UUID = "00010203-0405-0607-0809-0a0b0c0d2b10", PACKET_LENGTH = 20;
41
+
42
+ // src/transports/noble.ts
43
+ function toNobleUuid(uuid) {
44
+ const flat = uuid.replaceAll("-", "").toLowerCase();
45
+ return flat.startsWith("0000") && flat.endsWith(BASE_UUID_SUFFIX) ? flat.slice(4, 8) : flat;
46
+ }
47
+ function normalizeAddress(address) {
48
+ return address.replace(/[^0-9a-f]/gi, "").toLowerCase();
49
+ }
50
+ async function discoverLights(options = {}) {
51
+ const noble = options.noble ?? (await import("@stoprocent/noble")).default;
52
+ await noble.waitForPoweredOnAsync(BT_TIMEOUT);
53
+ const found = new Map;
54
+ const onDiscover = (p) => {
55
+ const name = p.advertisement.localName;
56
+ if (name && GOVEE_NAME.test(name)) {
57
+ found.set(p.id, { address: p.address || p.id, name, rssi: p.rssi });
58
+ }
59
+ };
60
+ noble.on("discover", onDiscover);
61
+ try {
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
+ class NobleTransport {
72
+ #address;
73
+ #timeout;
74
+ #noble;
75
+ #peripheral;
76
+ #write;
77
+ #read;
78
+ #listener;
79
+ #onDisconnect;
80
+ constructor(address, options = {}) {
81
+ this.#address = normalizeAddress(address);
82
+ this.#timeout = options.timeout ?? BT_TIMEOUT;
83
+ this.#noble = options.noble;
84
+ }
85
+ async connect() {
86
+ this.#noble ??= (await import("@stoprocent/noble")).default;
87
+ await this.#noble.waitForPoweredOnAsync(this.#timeout);
88
+ const peripheral = await this.#find(this.#noble);
89
+ for (let attempt = 1;; attempt++) {
90
+ try {
91
+ await this.#open(peripheral);
92
+ break;
93
+ } catch (error) {
94
+ await peripheral.disconnectAsync().catch(() => {});
95
+ if (attempt >= CONNECT_ATTEMPTS)
96
+ throw error;
97
+ await sleep(500);
98
+ }
99
+ }
100
+ this.#peripheral = peripheral;
101
+ peripheral.once("disconnect", () => {
102
+ if (this.#peripheral !== peripheral)
103
+ return;
104
+ this.#peripheral = this.#write = this.#read = undefined;
105
+ this.#onDisconnect?.();
106
+ });
107
+ return await this.#readName(peripheral) ?? peripheral.advertisement.localName;
108
+ }
109
+ async#open(peripheral) {
110
+ await peripheral.connectAsync();
111
+ await sleep(CONNECT_SETTLE_DELAY);
112
+ const writeUuid = toNobleUuid(WRITE_CHARACTERISTIC_UUID);
113
+ const readUuid = toNobleUuid(READ_CHARACTERISTIC_UUID);
114
+ const { characteristics } = await peripheral.discoverSomeServicesAndCharacteristicsAsync([toNobleUuid(SERVICE_UUID)], [writeUuid, readUuid]);
115
+ this.#write = characteristics.find((c) => c.uuid === writeUuid);
116
+ this.#read = characteristics.find((c) => c.uuid === readUuid);
117
+ if (!this.#write || !this.#read) {
118
+ throw new Error(`${this.#address} does not expose the Govee control characteristics`);
119
+ }
120
+ }
121
+ async disconnect() {
122
+ const peripheral = this.#peripheral;
123
+ this.#peripheral = this.#write = this.#read = undefined;
124
+ await peripheral?.disconnectAsync();
125
+ }
126
+ async write(data) {
127
+ const characteristic = this.#require(this.#write);
128
+ const withoutResponse = !characteristic.properties.includes("write");
129
+ await characteristic.writeAsync(Buffer.from(data), withoutResponse);
130
+ }
131
+ async subscribe(listener) {
132
+ const characteristic = this.#require(this.#read);
133
+ if (this.#listener)
134
+ characteristic.off("data", this.#listener);
135
+ this.#listener = (data) => listener(new Uint8Array(data));
136
+ characteristic.on("data", this.#listener);
137
+ await characteristic.subscribeAsync();
138
+ }
139
+ async unsubscribe() {
140
+ const characteristic = this.#read;
141
+ if (!characteristic)
142
+ return;
143
+ if (this.#listener)
144
+ characteristic.off("data", this.#listener);
145
+ this.#listener = undefined;
146
+ await characteristic.unsubscribeAsync();
147
+ }
148
+ onDisconnect(listener) {
149
+ this.#onDisconnect = listener;
150
+ }
151
+ #require(characteristic) {
152
+ if (!characteristic)
153
+ throw new Error("Not connected");
154
+ return characteristic;
155
+ }
156
+ #find(noble) {
157
+ const matches = (p) => normalizeAddress(p.address ?? "") === this.#address || normalizeAddress(p.id) === this.#address;
158
+ return new Promise((resolve, reject) => {
159
+ const finish = (error, peripheral) => {
160
+ clearTimeout(timer);
161
+ noble.off("discover", onDiscover);
162
+ noble.stopScanningAsync().catch(() => {});
163
+ if (peripheral)
164
+ resolve(peripheral);
165
+ else
166
+ reject(error);
167
+ };
168
+ const onDiscover = (peripheral) => {
169
+ if (matches(peripheral))
170
+ finish(undefined, peripheral);
171
+ };
172
+ const timer = setTimeout(() => finish(new Error(`Could not find device ${this.#address}`)), this.#timeout);
173
+ noble.on("discover", onDiscover);
174
+ noble.startScanningAsync([], false).catch((error) => finish(error));
175
+ });
176
+ }
177
+ async#readName(peripheral) {
178
+ try {
179
+ const { characteristics } = await peripheral.discoverSomeServicesAndCharacteristicsAsync(["1800"], [toNobleUuid(DEVICE_NAME_UUID)]);
180
+ const raw = await characteristics[0]?.readAsync();
181
+ return raw ? new TextDecoder().decode(raw).replace(/\0+$/, "") : undefined;
182
+ } catch {
183
+ return;
184
+ }
185
+ }
186
+ }
187
+ var BASE_UUID_SUFFIX = "00001000800000805f9b34fb", CONNECT_ATTEMPTS = 3, CONNECT_SETTLE_DELAY = 750, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), GOVEE_NAME;
188
+ var init_noble = __esm(() => {
189
+ GOVEE_NAME = /^(GBK|ihoment|Govee|Minger)_H\d{3,4}/i;
190
+ });
191
+
192
+ // src/cloud.ts
193
+ var CLOUD_BASE_URL = "https://openapi.api.govee.com";
194
+
195
+ class GoveeApiError extends Error {
196
+ status;
197
+ body;
198
+ constructor(message, status, body) {
199
+ super(message);
200
+ this.status = status;
201
+ this.body = body;
202
+ this.name = "GoveeApiError";
203
+ }
204
+ }
205
+ var Capabilities = {
206
+ power: { type: "devices.capabilities.on_off", instance: "powerSwitch" },
207
+ brightness: { type: "devices.capabilities.range", instance: "brightness" },
208
+ colorRgb: { type: "devices.capabilities.color_setting", instance: "colorRgb" },
209
+ colorTemperature: { type: "devices.capabilities.color_setting", instance: "colorTemperatureK" },
210
+ segmentColor: {
211
+ type: "devices.capabilities.segment_color_setting",
212
+ instance: "segmentedColorRgb"
213
+ },
214
+ segmentBrightness: {
215
+ type: "devices.capabilities.segment_color_setting",
216
+ instance: "segmentedBrightness"
217
+ },
218
+ online: { type: "devices.capabilities.online", instance: "online" }
219
+ };
220
+ var rgbToInt = ([r, g, b]) => (r & 255) << 16 | (g & 255) << 8 | b & 255;
221
+ var intToRgb = (value) => [
222
+ value >> 16 & 255,
223
+ value >> 8 & 255,
224
+ value & 255
225
+ ];
226
+
227
+ class GoveeCloud {
228
+ #apiKey;
229
+ #baseUrl;
230
+ #fetch;
231
+ constructor(apiKey, options = {}) {
232
+ if (!apiKey)
233
+ throw new TypeError("A Govee API key is required");
234
+ this.#apiKey = apiKey;
235
+ this.#baseUrl = options.baseUrl ?? CLOUD_BASE_URL;
236
+ this.#fetch = options.fetch ?? fetch;
237
+ }
238
+ async listDevices() {
239
+ const body = await this.#request("GET", "/router/api/v1/user/devices");
240
+ return body.data.map((info) => new CloudDevice(this, info));
241
+ }
242
+ async getDevice(idOrName) {
243
+ const devices = await this.listDevices();
244
+ const needle = idOrName.toLowerCase();
245
+ const found = devices.find((d) => d.id.toLowerCase() === needle || d.name.toLowerCase() === needle);
246
+ if (!found)
247
+ throw new GoveeApiError(`No device named or with id "${idOrName}"`, 404);
248
+ return found;
249
+ }
250
+ async getState(sku, device) {
251
+ const body = await this.#request("POST", "/router/api/v1/device/state", { requestId: crypto.randomUUID(), payload: { sku, device } });
252
+ return parseState(body.payload.capabilities);
253
+ }
254
+ async control(sku, device, capability) {
255
+ await this.#request("POST", "/router/api/v1/device/control", {
256
+ requestId: crypto.randomUUID(),
257
+ payload: { sku, device, capability }
258
+ });
259
+ }
260
+ async getScenes(sku, device) {
261
+ return this.#scenes("/router/api/v1/device/scenes", sku, device);
262
+ }
263
+ async getDiyScenes(sku, device) {
264
+ return this.#scenes("/router/api/v1/device/diy-scenes", sku, device);
265
+ }
266
+ async#scenes(path, sku, device) {
267
+ const body = await this.#request("POST", path, {
268
+ requestId: crypto.randomUUID(),
269
+ payload: { sku, device }
270
+ });
271
+ return body.payload.capabilities.flatMap((capability) => (capability.parameters?.options ?? []).map((option) => ({
272
+ name: option.name,
273
+ type: capability.type,
274
+ instance: capability.instance,
275
+ value: option.value
276
+ })));
277
+ }
278
+ async#request(method, path, body) {
279
+ const response = await this.#fetch(this.#baseUrl + path, {
280
+ method,
281
+ headers: { "Content-Type": "application/json", "Govee-API-Key": this.#apiKey },
282
+ body: body === undefined ? undefined : JSON.stringify(body)
283
+ });
284
+ const text = await response.text();
285
+ let json;
286
+ try {
287
+ json = text ? JSON.parse(text) : undefined;
288
+ } catch {}
289
+ const code = json?.code ?? response.status;
290
+ if (!response.ok || code !== 200) {
291
+ const status = response.ok ? code : response.status;
292
+ const message = json?.message ?? json?.msg ?? (text || response.statusText);
293
+ const hint = status === 401 ? " (check your API key)" : status === 429 ? " (rate limited, slow down)" : "";
294
+ throw new GoveeApiError(`Govee API ${method} ${path} failed: ${status} ${message}${hint}`, status, json ?? text);
295
+ }
296
+ return json;
297
+ }
298
+ }
299
+ function parseState(capabilities) {
300
+ const value = (instance) => {
301
+ const v = capabilities.find((c) => c.instance === instance)?.state.value;
302
+ return v === "" || v === null ? undefined : v;
303
+ };
304
+ const number = (instance) => {
305
+ const v = value(instance);
306
+ return typeof v === "number" ? v : undefined;
307
+ };
308
+ const online = value("online");
309
+ const power = number("powerSwitch");
310
+ const color = number("colorRgb");
311
+ return {
312
+ online: typeof online === "boolean" ? online : undefined,
313
+ power: power === undefined ? undefined : power === 1,
314
+ brightness: number("brightness"),
315
+ rgb: color === undefined ? undefined : intToRgb(color),
316
+ colorTemperature: number("colorTemperatureK") || undefined,
317
+ capabilities
318
+ };
319
+ }
320
+
321
+ class CloudDevice {
322
+ sku;
323
+ id;
324
+ name;
325
+ type;
326
+ capabilities;
327
+ #cloud;
328
+ constructor(cloud, info) {
329
+ this.#cloud = cloud;
330
+ this.sku = info.sku;
331
+ this.id = info.device;
332
+ this.name = info.deviceName || info.sku;
333
+ this.type = info.type;
334
+ this.capabilities = info.capabilities ?? [];
335
+ }
336
+ capability(instance) {
337
+ return this.capabilities.find((c) => c.instance === instance);
338
+ }
339
+ supports(instance) {
340
+ return this.capability(instance) !== undefined;
341
+ }
342
+ get isGroup() {
343
+ return /group$/i.test(this.sku);
344
+ }
345
+ getState() {
346
+ if (this.isGroup) {
347
+ return Promise.reject(new GoveeApiError(`${this.name} is a group; groups have no readable state`, 400));
348
+ }
349
+ return this.#cloud.getState(this.sku, this.id);
350
+ }
351
+ control(type, instance, value) {
352
+ return this.#cloud.control(this.sku, this.id, { type, instance, value });
353
+ }
354
+ setPower(on) {
355
+ return this.#send(Capabilities.power, on ? 1 : 0);
356
+ }
357
+ turnOn() {
358
+ return this.setPower(true);
359
+ }
360
+ turnOff() {
361
+ return this.setPower(false);
362
+ }
363
+ setBrightness(percent) {
364
+ const { min, max } = this.capability("brightness")?.parameters?.range ?? { min: 1, max: 100 };
365
+ return this.#send(Capabilities.brightness, clampInt(percent, min, max, "Brightness"));
366
+ }
367
+ setColor(rgb) {
368
+ for (const channel of rgb)
369
+ clampInt(channel, 0, 255, "Color channel", true);
370
+ return this.#send(Capabilities.colorRgb, rgbToInt(rgb));
371
+ }
372
+ setColorTemperature(kelvin) {
373
+ const { min, max } = this.capability("colorTemperatureK")?.parameters?.range ?? {
374
+ min: 2000,
375
+ max: 9000
376
+ };
377
+ return this.#send(Capabilities.colorTemperature, clampInt(kelvin, min, max, "Color temperature"));
378
+ }
379
+ setSegmentColor(segments, rgb) {
380
+ return this.#send(Capabilities.segmentColor, { segment: segments, rgb: rgbToInt(rgb) });
381
+ }
382
+ setSegmentBrightness(segments, percent) {
383
+ return this.#send(Capabilities.segmentBrightness, {
384
+ segment: segments,
385
+ brightness: clampInt(percent, 0, 100, "Brightness")
386
+ });
387
+ }
388
+ async getScenes() {
389
+ return this.supports("lightScene") ? this.#cloud.getScenes(this.sku, this.id) : [];
390
+ }
391
+ async getDiyScenes() {
392
+ return this.supports("diyScene") ? this.#cloud.getDiyScenes(this.sku, this.id) : [];
393
+ }
394
+ async getAllScenes() {
395
+ const [scenes, diy] = await Promise.all([this.getScenes(), this.getDiyScenes()]);
396
+ return [...scenes, ...diy];
397
+ }
398
+ setScene(scene) {
399
+ return this.control(scene.type, scene.instance, scene.value);
400
+ }
401
+ #send(capability, value) {
402
+ if (!this.supports(capability.instance)) {
403
+ return Promise.reject(new GoveeApiError(`${this.name} (${this.sku}) does not support ${capability.instance}`, 400));
404
+ }
405
+ return this.control(capability.type, capability.instance, value);
406
+ }
407
+ }
408
+ function clampInt(value, min, max, label, strict = false) {
409
+ if (!Number.isFinite(value))
410
+ throw new TypeError(`${label} must be a number`);
411
+ const rounded = Math.round(value);
412
+ if (strict && (rounded < min || rounded > max)) {
413
+ throw new RangeError(`${label} must be between ${min} and ${max}`);
414
+ }
415
+ return Math.min(max, Math.max(min, rounded));
416
+ }
417
+ // src/colors.ts
418
+ var COLORS = {
419
+ white: [255, 255, 255],
420
+ warm_white: [255, 166, 87],
421
+ cool_white: [255, 254, 250],
422
+ black: [0, 0, 0],
423
+ red: [255, 0, 0],
424
+ dark_red: [139, 0, 0],
425
+ light_red: [255, 69, 69],
426
+ green: [0, 255, 0],
427
+ dark_green: [0, 100, 0],
428
+ light_green: [144, 238, 144],
429
+ blue: [0, 0, 255],
430
+ dark_blue: [0, 0, 139],
431
+ light_blue: [173, 216, 230],
432
+ yellow: [255, 255, 0],
433
+ dark_yellow: [184, 134, 11],
434
+ light_yellow: [255, 255, 153],
435
+ orange: [255, 165, 0],
436
+ dark_orange: [255, 140, 0],
437
+ light_orange: [255, 179, 71],
438
+ purple: [128, 0, 128],
439
+ dark_purple: [75, 0, 130],
440
+ light_purple: [218, 112, 214],
441
+ pink: [255, 182, 193],
442
+ dark_pink: [255, 20, 147],
443
+ light_pink: [255, 182, 193],
444
+ brown: [165, 42, 42],
445
+ dark_brown: [139, 69, 19],
446
+ light_brown: [205, 133, 63]
447
+ };
448
+ var COLOR_NAMES = Object.keys(COLORS);
449
+ function isColorName(name) {
450
+ return Object.hasOwn(COLORS, name.toLowerCase());
451
+ }
452
+ function colorNameToRgb(name) {
453
+ const key = name.toLowerCase();
454
+ return isColorName(key) ? COLORS[key] : undefined;
455
+ }
456
+ function rgbToColorName(rgb) {
457
+ let closest = "black";
458
+ let min = Infinity;
459
+ for (const name of COLOR_NAMES) {
460
+ const [r, g, b] = COLORS[name];
461
+ const d = Math.hypot(rgb[0] - r, rgb[1] - g, rgb[2] - b);
462
+ if (d < min) {
463
+ min = d;
464
+ closest = name;
465
+ }
466
+ }
467
+ return closest;
468
+ }
469
+ // src/protocol.ts
470
+ function checksum(bytes) {
471
+ let result = 0;
472
+ for (let i = 0;i < bytes.length; i++)
473
+ result ^= bytes[i] ?? 0;
474
+ return result;
475
+ }
476
+ function buildPacket(payload) {
477
+ if (payload.length > PACKET_LENGTH - 1) {
478
+ throw new RangeError(`Payload must be at most ${PACKET_LENGTH - 1} bytes`);
479
+ }
480
+ const packet = new Uint8Array(PACKET_LENGTH);
481
+ packet.set(payload);
482
+ packet[PACKET_LENGTH - 1] = checksum(packet.subarray(0, PACKET_LENGTH - 1));
483
+ return packet;
484
+ }
485
+ function assertByte(value, label, min = 0, max = 255) {
486
+ if (!Number.isInteger(value))
487
+ throw new TypeError(`${label} must be an integer`);
488
+ if (value < min || value > max) {
489
+ throw new RangeError(`${label} must be between ${min} and ${max}`);
490
+ }
491
+ }
492
+ var COLOR_MODES = ["legacy", "manual", "manual-0b", "segments"];
493
+ var Commands = {
494
+ turnOn: () => buildPacket([51, 1, 1]),
495
+ turnOff: () => buildPacket([51, 1, 0]),
496
+ setBrightness(brightness) {
497
+ assertByte(brightness, "Brightness", BRIGHTNESS_MIN, BRIGHTNESS_MAX);
498
+ return buildPacket([51, 4, brightness]);
499
+ },
500
+ setColor([r, g, b], mode = "legacy") {
501
+ assertByte(r, "Red");
502
+ assertByte(g, "Green");
503
+ assertByte(b, "Blue");
504
+ switch (mode) {
505
+ case "legacy":
506
+ return buildPacket([51, 5, 2, r, g, b, 0, 255, 174, 84]);
507
+ case "manual":
508
+ return buildPacket([51, 5, 13, r, g, b]);
509
+ case "manual-0b":
510
+ return buildPacket([51, 5, 11, r, g, b]);
511
+ case "segments":
512
+ return buildPacket([51, 5, 21, 1, r, g, b, 0, 0, 0, 0, 0, 255, 255]);
513
+ }
514
+ },
515
+ getPower: () => buildPacket([170, 1]),
516
+ getBrightness: () => buildPacket([170, 4]),
517
+ getColor: () => buildPacket([170, 5, 1])
518
+ };
519
+ var MODE_BYTES = {
520
+ 2: "legacy",
521
+ 13: "manual",
522
+ 11: "manual-0b",
523
+ 21: "segments"
524
+ };
525
+ var KNOWN_MODEL_COLOR_MODES = {
526
+ H613B: "legacy",
527
+ H613C: "manual"
528
+ };
529
+ function modelFromName(name) {
530
+ return name?.match(/H\d{3,4}[A-Z]?/i)?.[0].toUpperCase();
531
+ }
532
+ function parseResponse(data) {
533
+ if (data[0] === 170 && data.length >= 6) {
534
+ switch (data[1]) {
535
+ case 1:
536
+ return { type: "power", power: data[2] === 1 };
537
+ case 4:
538
+ return { type: "brightness", brightness: data[2] ?? 0 };
539
+ case 5:
540
+ return {
541
+ type: "color",
542
+ rgb: [data[3] ?? 0, data[4] ?? 0, data[5] ?? 0],
543
+ mode: MODE_BYTES[data[2] ?? 0]
544
+ };
545
+ }
546
+ }
547
+ return { type: "unknown", data };
548
+ }
549
+ function toHex(data) {
550
+ return Array.from(data, (b) => b.toString(16).padStart(2, "0")).join("");
551
+ }
552
+
553
+ // src/controller.ts
554
+ var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
555
+
556
+ class GoveeController {
557
+ address;
558
+ name;
559
+ power;
560
+ brightness;
561
+ rgb;
562
+ colorName;
563
+ #transport;
564
+ #connected = false;
565
+ #queue = Promise.resolve();
566
+ #waiters = new Set;
567
+ #timeout;
568
+ #commandDelay;
569
+ #responseTimeout;
570
+ #colorMode;
571
+ #logger;
572
+ constructor(address, options = {}) {
573
+ if (typeof address !== "string")
574
+ throw new TypeError("address must be a string");
575
+ this.address = address;
576
+ this.#transport = options.transport;
577
+ this.#timeout = options.timeout ?? BT_TIMEOUT;
578
+ this.#commandDelay = options.commandDelay ?? COMMAND_DELAY;
579
+ this.#responseTimeout = options.responseTimeout ?? 3000;
580
+ this.#colorMode = options.colorMode;
581
+ this.#logger = options.logger;
582
+ }
583
+ get connected() {
584
+ return this.#connected;
585
+ }
586
+ get colorMode() {
587
+ return this.#colorMode;
588
+ }
589
+ async connect() {
590
+ if (this.#connected)
591
+ return this;
592
+ if (!this.#transport) {
593
+ await Promise.resolve().then(() => init_noble());
594
+ this.#transport = new NobleTransport(this.address, { timeout: this.#timeout });
595
+ }
596
+ this.#transport.onDisconnect?.(() => {
597
+ if (!this.#connected)
598
+ return;
599
+ this.#connected = false;
600
+ this.#log(`Lost connection to ${this.address}`);
601
+ });
602
+ this.name = await this.#transport.connect();
603
+ try {
604
+ await this.#transport.subscribe((data) => this.#handleNotification(data));
605
+ } catch (error) {
606
+ await this.#transport.disconnect().catch(() => {});
607
+ throw error;
608
+ }
609
+ this.#connected = true;
610
+ this.#log(`Connected to ${this.name ?? "device"} (${this.address})`);
611
+ return this;
612
+ }
613
+ async disconnect() {
614
+ if (!this.#connected || !this.#transport)
615
+ return;
616
+ this.#connected = false;
617
+ await this.#queue;
618
+ await this.#transport.unsubscribe().catch(() => {});
619
+ await this.#transport.disconnect();
620
+ this.#log(`Disconnected from ${this.address}`);
621
+ }
622
+ async[Symbol.asyncDispose]() {
623
+ await this.disconnect();
624
+ }
625
+ async getPower() {
626
+ return (await this.#query("power", Commands.getPower())).power;
627
+ }
628
+ async getBrightness() {
629
+ return (await this.#query("brightness", Commands.getBrightness())).brightness;
630
+ }
631
+ async getRgb() {
632
+ return (await this.#query("color", Commands.getColor())).rgb;
633
+ }
634
+ async turnOn({ smooth = false } = {}) {
635
+ this.#log("Turning on");
636
+ if (smooth) {
637
+ for (let i = 0;i < 255; i += 50) {
638
+ await this.setBrightness(i);
639
+ await sleep2(150);
640
+ }
641
+ }
642
+ await this.#send(Commands.turnOn());
643
+ this.power = true;
644
+ }
645
+ async turnOff({ smooth = false } = {}) {
646
+ this.#log("Turning off");
647
+ if (smooth) {
648
+ for (let i = 255;i > 0; i -= 50) {
649
+ await this.setBrightness(i);
650
+ await sleep2(150);
651
+ }
652
+ }
653
+ await this.#send(Commands.turnOff());
654
+ this.power = false;
655
+ }
656
+ async setBrightness(brightness) {
657
+ this.#log(`Setting brightness to ${brightness}`);
658
+ await this.#send(Commands.setBrightness(brightness));
659
+ this.brightness = brightness;
660
+ }
661
+ async setColor(color) {
662
+ const rgb = toRgb(color);
663
+ this.#log(`Setting color to ${rgb.join(", ")}`);
664
+ const mode = await this.#detectColorMode();
665
+ await this.#send(Commands.setColor(rgb, mode));
666
+ this.rgb = rgb;
667
+ this.colorName = rgbToColorName(rgb);
668
+ }
669
+ async#detectColorMode() {
670
+ if (this.#colorMode)
671
+ return this.#colorMode;
672
+ const model = modelFromName(this.name);
673
+ let mode = model ? KNOWN_MODEL_COLOR_MODES[model] : undefined;
674
+ if (!mode) {
675
+ mode = await this.#query("color", Commands.getColor()).then((response) => response.mode, () => {
676
+ return;
677
+ });
678
+ }
679
+ this.#colorMode = mode ?? "legacy";
680
+ this.#log(`Using color mode "${this.#colorMode}"`);
681
+ return this.#colorMode;
682
+ }
683
+ #log(message) {
684
+ this.#logger?.(message);
685
+ }
686
+ #requireTransport() {
687
+ if (!this.#connected || !this.#transport) {
688
+ throw new Error("Not connected, call connect() first");
689
+ }
690
+ return this.#transport;
691
+ }
692
+ #enqueue(operation) {
693
+ const run = this.#queue.then(operation);
694
+ this.#queue = run.catch(() => {});
695
+ return run;
696
+ }
697
+ async#send(packet) {
698
+ const transport = this.#requireTransport();
699
+ await this.#enqueue(async () => {
700
+ this.#log(`Sending: ${toHex(packet)}`);
701
+ await transport.write(packet);
702
+ await sleep2(this.#commandDelay);
703
+ });
704
+ }
705
+ async#query(type, packet) {
706
+ const transport = this.#requireTransport();
707
+ return this.#enqueue(async () => {
708
+ const response = this.#waitFor(type);
709
+ this.#log(`Sending: ${toHex(packet)}`);
710
+ try {
711
+ await transport.write(packet);
712
+ } catch (error) {
713
+ response.cancel();
714
+ throw error;
715
+ }
716
+ return await response.promise;
717
+ });
718
+ }
719
+ #waitFor(type) {
720
+ let timer;
721
+ let waiter;
722
+ const promise = new Promise((resolve, reject) => {
723
+ const entry = { type, resolve };
724
+ waiter = entry;
725
+ this.#waiters.add(entry);
726
+ timer = setTimeout(() => {
727
+ this.#waiters.delete(entry);
728
+ reject(new Error(`Timed out waiting for ${type} status from ${this.address}`));
729
+ }, this.#responseTimeout);
730
+ }).finally(() => clearTimeout(timer));
731
+ const cancel = () => {
732
+ clearTimeout(timer);
733
+ if (waiter)
734
+ this.#waiters.delete(waiter);
735
+ };
736
+ return { promise, cancel };
737
+ }
738
+ #handleNotification(data) {
739
+ this.#log(`Received: ${toHex(data)}`);
740
+ const response = parseResponse(data);
741
+ switch (response.type) {
742
+ case "power":
743
+ this.power = response.power;
744
+ break;
745
+ case "brightness":
746
+ this.brightness = response.brightness;
747
+ break;
748
+ case "color":
749
+ this.rgb = response.rgb;
750
+ this.colorName = rgbToColorName(response.rgb);
751
+ break;
752
+ case "unknown":
753
+ this.#log(`Unknown response: ${toHex(data)}`);
754
+ return;
755
+ }
756
+ for (const waiter of this.#waiters) {
757
+ if (waiter.type === response.type) {
758
+ this.#waiters.delete(waiter);
759
+ waiter.resolve(response);
760
+ }
761
+ }
762
+ }
763
+ }
764
+ function toRgb(color) {
765
+ if (typeof color === "string") {
766
+ const rgb = colorNameToRgb(color);
767
+ if (!rgb) {
768
+ throw new RangeError(`Invalid color name, valid values are: ${COLOR_NAMES.join(", ")}`);
769
+ }
770
+ return rgb;
771
+ }
772
+ if (Array.isArray(color) && color.length === 3)
773
+ return [color[0], color[1], color[2]];
774
+ if (typeof color === "object" && color !== null && "r" in color) {
775
+ return [color.r, color.g, color.b];
776
+ }
777
+ throw new TypeError("Invalid color, expected a color name, [r, g, b] or { r, g, b }");
778
+ }
779
+
780
+ // src/index.ts
781
+ init_noble();
782
+ export {
783
+ CLOUD_BASE_URL,
784
+ COLORS,
785
+ COLOR_MODES,
786
+ COLOR_NAMES,
787
+ Capabilities,
788
+ CloudDevice,
789
+ Commands,
790
+ exports_constants as Constants,
791
+ GoveeApiError,
792
+ GoveeCloud,
793
+ GoveeController,
794
+ KNOWN_MODEL_COLOR_MODES,
795
+ NobleTransport,
796
+ buildPacket,
797
+ checksum,
798
+ colorNameToRgb,
799
+ discoverLights,
800
+ intToRgb,
801
+ isColorName,
802
+ modelFromName,
803
+ parseResponse,
804
+ rgbToColorName,
805
+ rgbToInt,
806
+ toHex
807
+ };
808
+
809
+ //# debugId=768A71AA4072507564756E2164756E21