@sdeck/govee 0.4.1 → 0.4.2
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.map
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"sources": ["../src/constants.ts", "../src/transports/noble.ts", "../src/cloud.ts", "../src/colors.ts", "../src/protocol.ts", "../src/controller.ts", "../src/index.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/** Bluetooth connection/scan timeout in milliseconds. */\nexport const BT_TIMEOUT = 15_000;\n\n/** Delay after each command so the device can keep up, in milliseconds. */\nexport const COMMAND_DELAY = 300;\n\nexport const BRIGHTNESS_MIN = 0;\nexport const BRIGHTNESS_MAX = 255;\n\n/** Standard GAP \"Device Name\" characteristic. */\nexport const DEVICE_NAME_UUID = \"00002a00-0000-1000-8000-00805f9b34fb\";\n\n/** Govee control service. */\nexport const SERVICE_UUID = \"00010203-0405-0607-0809-0a0b0c0d1910\";\nexport const WRITE_CHARACTERISTIC_UUID = \"00010203-0405-0607-0809-0a0b0c0d2b11\";\nexport const READ_CHARACTERISTIC_UUID = \"00010203-0405-0607-0809-0a0b0c0d2b10\";\n\n/** Every Govee packet is exactly 20 bytes: 19 bytes of payload plus an XOR checksum. */\nexport const PACKET_LENGTH = 20;\n",
|
|
6
|
-
"import type { Characteristic, Noble, Peripheral } from \"@stoprocent/noble\";\nimport {\n BT_TIMEOUT,\n DEVICE_NAME_UUID,\n READ_CHARACTERISTIC_UUID,\n SERVICE_UUID,\n WRITE_CHARACTERISTIC_UUID,\n} from \"../constants.ts\";\nimport type { GoveeTransport } from \"../transport.ts\";\n\nexport interface NobleTransportOptions {\n /** Scan/connect timeout in ms. Default 15000. */\n timeout?: number;\n /** The light's name, if it is known: saves asking for it. */\n name?: string;\n /** Noble instance to use. Defaults to the shared `@stoprocent/noble` instance. */\n noble?: Noble;\n}\n\nconst BASE_UUID_SUFFIX = \"00001000800000805f9b34fb\";\nconst CONNECT_ATTEMPTS = 2;\nconst CONNECT_SETTLE_DELAY = 750;\nconst STOP_TIMEOUT = 2000;\n/** Noble has no limits of its own: a step the light never answers would hang for good. */\nconst CONNECT_TIMEOUT = 5000;\nconst DISCOVER_TIMEOUT = 6000;\nconst STEP_TIMEOUT = 3000;\nconst SCAN_TIME = 15_000;\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/** `promise`, or an error once it has taken `ms`. */\nfunction within<T>(promise: Promise<T>, ms: number, what: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`The light took too long to ${what}`)), ms);\n });\n return Promise.race([promise, late]).finally(() => clearTimeout(timer));\n}\n\nconst letGo = (peripheral: Peripheral) =>\n within(peripheral.disconnectAsync(), STEP_TIMEOUT, \"disconnect\").catch(() => {});\n\n/** Noble reports UUIDs lowercase without dashes, and standard 16-bit UUIDs in short form. */\nfunction toNobleUuid(uuid: string): string {\n const flat = uuid.replaceAll(\"-\", \"\").toLowerCase();\n return flat.startsWith(\"0000\") && flat.endsWith(BASE_UUID_SUFFIX) ? flat.slice(4, 8) : flat;\n}\n\n/** Strips separators so `A4:C1:38:35:97:24`, `a4c138359724` and noble ids compare equal. */\nfunction normalizeAddress(address: string): string {\n return address.replace(/[^0-9a-f]/gi, \"\").toLowerCase();\n}\n\ninterface Scan {\n users: number;\n /** Starting and stopping, one at a time. */\n turn: Promise<void>;\n}\n\nconst scans = new WeakMap<Noble, Scan>();\n\n/**\n * Listens for advertisements until the returned function is called. Noble has one scan for the\n * whole process, so it runs until its last user is done: connecting to one light doesn't end a\n * search for others.\n */\nasync function listen(noble: Noble, onDiscover: (p: Peripheral) => void): Promise<() => void> {\n const scan = scans.get(noble) ?? { users: 0, turn: Promise.resolve() };\n scans.set(noble, scan);\n const inTurn = (step: () => Promise<void>) => {\n const result = scan.turn.then(step);\n scan.turn = result.catch(() => {});\n return result;\n };\n let done = false;\n const stop = () => {\n if (done) return;\n done = true;\n noble.off(\"discover\", onDiscover);\n void inTurn(async () => {\n scan.users--;\n // A radio that never confirms must not block every later scan.\n if (scan.users === 0) {\n await Promise.race([noble.stopScanningAsync().catch(() => {}), sleep(STOP_TIMEOUT)]);\n }\n });\n };\n\n noble.on(\"discover\", onDiscover);\n try {\n await inTurn(async () => {\n scan.users++;\n // Duplicates on: a light already heard in this scan must be reported to its later users, and\n // the name often comes in a later packet than the first.\n if (scan.users === 1) await noble.startScanningAsync([], true);\n });\n } catch (error) {\n stop();\n throw error;\n }\n return stop;\n}\n\nexport interface DiscoveredLight {\n /** MAC address, or the noble peripheral id where the platform hides it (macOS). */\n address: string;\n name: string;\n rssi: number;\n}\n\nconst GOVEE_NAME = /^(GBK|ihoment|Govee|Minger)_H\\d{3,4}/i;\n\n/**\n * Scans for nearby Govee lights, recognised by their advertised name. A computer's\n * radio can miss a light for 15 seconds at a time, so this listens for `timeout` ms (default 15000),\n * and for as long again while it has found nothing.\n */\nexport async function discoverLights(\n options: { timeout?: number; noble?: Noble } = {},\n): Promise<DiscoveredLight[]> {\n const noble = options.noble ?? (await import(\"@stoprocent/noble\")).default;\n await noble.waitForPoweredOnAsync(BT_TIMEOUT);\n\n const found = new Map<string, DiscoveredLight>();\n const onDiscover = (p: Peripheral) => {\n const name = p.advertisement.localName;\n if (name && GOVEE_NAME.test(name)) {\n found.set(p.id, { address: p.address || p.id, name, rssi: p.rssi });\n }\n };\n const stop = await listen(noble, onDiscover);\n const timeout = options.timeout ?? SCAN_TIME;\n await sleep(timeout);\n for (let i = 0; i < 10 && found.size === 0; i++) await sleep(timeout / 10);\n stop();\n return [...found.values()].sort((a, b) => b.rssi - a.rssi);\n}\n\n/** BLE transport for Node.js / Bun backed by `@stoprocent/noble` (Windows, macOS, Linux). */\nexport class NobleTransport implements GoveeTransport {\n readonly #address: string;\n readonly #timeout: number;\n readonly #name: string | undefined;\n #noble: Noble | undefined;\n #peripheral: Peripheral | undefined;\n #write: Characteristic | undefined;\n #read: Characteristic | undefined;\n #listener: ((data: Buffer) => void) | undefined;\n #onDisconnect: (() => void) | undefined;\n\n /** @param address MAC address, or the noble peripheral id (macOS hides MAC addresses). */\n constructor(address: string, options: NobleTransportOptions = {}) {\n this.#address = normalizeAddress(address);\n this.#timeout = options.timeout ?? BT_TIMEOUT;\n this.#noble = options.noble;\n this.#name = options.name;\n }\n\n async connect(): Promise<string | undefined> {\n this.#noble ??= (await import(\"@stoprocent/noble\")).default;\n await this.#noble.waitForPoweredOnAsync(this.#timeout);\n\n const peripheral =\n (await this.#openKnown(this.#noble)) ??\n (await this.#openFound(await this.#find(this.#noble)));\n\n this.#peripheral = peripheral;\n peripheral.once(\"disconnect\", () => {\n // Ignore the event for a disconnect() we initiated, or for a stale peripheral.\n if (this.#peripheral !== peripheral) return;\n this.#peripheral = this.#write = this.#read = undefined;\n this.#onDisconnect?.();\n });\n return peripheral.advertisement?.localName || this.#name || (await this.#readName(peripheral));\n }\n\n /**\n * Connects by address alone, without waiting to hear the light first: the difference between half a\n * second and many. `undefined` where that does not work.\n */\n async #openKnown(noble: Noble): Promise<Peripheral | undefined> {\n // Elsewhere a connection needs an advertisement, or the address is not the real one.\n if (process.platform !== \"win32\" || this.#address.length !== 12) return undefined;\n let peripheral: Peripheral | undefined;\n try {\n peripheral = await within(noble.connectAsync(this.#address), CONNECT_TIMEOUT, \"connect\");\n await this.#prepare(peripheral);\n return peripheral;\n } catch {\n if (peripheral) await letGo(peripheral);\n return undefined;\n }\n }\n\n async #openFound(peripheral: Peripheral): Promise<Peripheral> {\n for (let attempt = 1; ; attempt++) {\n try {\n await within(peripheral.connectAsync(), CONNECT_TIMEOUT, \"connect\");\n // On Windows, noble reports \"connected\" before the GATT session is usable, and discovering\n // services straight away can make the device drop the connection.\n await sleep(CONNECT_SETTLE_DELAY);\n await this.#prepare(peripheral);\n return peripheral;\n } catch (error) {\n await letGo(peripheral);\n if (attempt >= CONNECT_ATTEMPTS) throw error;\n await sleep(500);\n }\n }\n }\n\n /** Finds what commands are written to and answers read from. */\n async #prepare(peripheral: Peripheral): Promise<void> {\n const writeUuid = toNobleUuid(WRITE_CHARACTERISTIC_UUID);\n const readUuid = toNobleUuid(READ_CHARACTERISTIC_UUID);\n const { characteristics } = await within(\n peripheral.discoverSomeServicesAndCharacteristicsAsync(\n [toNobleUuid(SERVICE_UUID)],\n [writeUuid, readUuid],\n ),\n DISCOVER_TIMEOUT,\n \"answer\",\n );\n this.#write = characteristics.find((c) => c.uuid === writeUuid);\n this.#read = characteristics.find((c) => c.uuid === readUuid);\n if (!this.#write || !this.#read) {\n throw new Error(`${this.#address} does not expose the Govee control characteristics`);\n }\n }\n\n async disconnect(): Promise<void> {\n const peripheral = this.#peripheral;\n this.#peripheral = this.#write = this.#read = undefined;\n if (peripheral) await letGo(peripheral);\n }\n\n async write(data: Uint8Array): Promise<void> {\n const characteristic = this.#require(this.#write);\n const withoutResponse = !characteristic.properties.includes(\"write\");\n await within(\n characteristic.writeAsync(Buffer.from(data), withoutResponse),\n STEP_TIMEOUT,\n \"take the command\",\n );\n }\n\n async subscribe(listener: (data: Uint8Array) => void): Promise<void> {\n const characteristic = this.#require(this.#read);\n if (this.#listener) characteristic.off(\"data\", this.#listener);\n this.#listener = (data) => listener(new Uint8Array(data));\n characteristic.on(\"data\", this.#listener);\n await within(characteristic.subscribeAsync(), STEP_TIMEOUT, \"answer\");\n }\n\n async unsubscribe(): Promise<void> {\n const characteristic = this.#read;\n if (!characteristic) return;\n if (this.#listener) characteristic.off(\"data\", this.#listener);\n this.#listener = undefined;\n await within(characteristic.unsubscribeAsync(), STEP_TIMEOUT, \"disconnect\");\n }\n\n onDisconnect(listener: () => void): void {\n this.#onDisconnect = listener;\n }\n\n #require(characteristic: Characteristic | undefined): Characteristic {\n if (!characteristic) throw new Error(\"Not connected\");\n return characteristic;\n }\n\n async #find(noble: Noble): Promise<Peripheral> {\n const matches = (p: Peripheral) =>\n normalizeAddress(p.address ?? \"\") === this.#address ||\n normalizeAddress(p.id) === this.#address;\n\n const found = Promise.withResolvers<Peripheral>();\n const stop = await listen(noble, (p) => {\n if (matches(p)) found.resolve(p);\n });\n const timer = setTimeout(\n () => found.reject(new Error(`Could not find device ${this.#address}`)),\n this.#timeout,\n );\n try {\n return await found.promise;\n } finally {\n clearTimeout(timer);\n stop();\n }\n }\n\n async #readName(peripheral: Peripheral): Promise<string | undefined> {\n try {\n const read = async () => {\n const { characteristics } = await peripheral.discoverSomeServicesAndCharacteristicsAsync(\n [\"1800\"],\n [toNobleUuid(DEVICE_NAME_UUID)],\n );\n return characteristics[0]?.readAsync();\n };\n const raw = await within(read(), STEP_TIMEOUT, \"say its name\");\n return raw ? new TextDecoder().decode(raw).replace(/\\0+$/, \"\") : undefined;\n } catch {\n // Some platforms (notably Windows) don't allow reading the GAP service.\n return undefined;\n }\n }\n}\n",
|
|
6
|
+
"import type { Characteristic, Noble, Peripheral } from \"@stoprocent/noble\";\nimport {\n BT_TIMEOUT,\n DEVICE_NAME_UUID,\n READ_CHARACTERISTIC_UUID,\n SERVICE_UUID,\n WRITE_CHARACTERISTIC_UUID,\n} from \"../constants.ts\";\nimport type { GoveeTransport } from \"../transport.ts\";\n\nexport interface NobleTransportOptions {\n /** Scan/connect timeout in ms. Default 15000. */\n timeout?: number;\n /** The light's name, if it is known: saves asking for it. */\n name?: string;\n /** Noble instance to use. Defaults to the shared `@stoprocent/noble` instance. */\n noble?: Noble;\n}\n\nconst BASE_UUID_SUFFIX = \"00001000800000805f9b34fb\";\nconst CONNECT_ATTEMPTS = 2;\nconst CONNECT_SETTLE_DELAY = 750;\nconst STOP_TIMEOUT = 2000;\n/** Noble has no limits of its own: a step the light never answers would hang for good. */\nconst CONNECT_TIMEOUT = 5000;\nconst DISCOVER_TIMEOUT = 6000;\nconst STEP_TIMEOUT = 3000;\nconst SCAN_TIME = 15_000;\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/** `promise`, or an error once it has taken `ms`. */\nfunction within<T>(promise: Promise<T>, ms: number, what: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`The light took too long to ${what}`)), ms);\n });\n return Promise.race([promise, late]).finally(() => clearTimeout(timer));\n}\n\nconst letGo = (peripheral: Peripheral) =>\n within(peripheral.disconnectAsync(), STEP_TIMEOUT, \"disconnect\").catch(() => {});\n\n/** Noble reports UUIDs lowercase without dashes, and standard 16-bit UUIDs in short form. */\nfunction toNobleUuid(uuid: string): string {\n const flat = uuid.replaceAll(\"-\", \"\").toLowerCase();\n return flat.startsWith(\"0000\") && flat.endsWith(BASE_UUID_SUFFIX) ? flat.slice(4, 8) : flat;\n}\n\n/** Strips separators so `A4:C1:38:35:97:24`, `a4c138359724` and noble ids compare equal. */\nfunction normalizeAddress(address: string): string {\n return address.replace(/[^0-9a-f]/gi, \"\").toLowerCase();\n}\n\ninterface Scan {\n users: number;\n /** Starting and stopping, one at a time. */\n turn: Promise<void>;\n}\n\nconst scans = new WeakMap<Noble, Scan>();\n\n/**\n * Listens for advertisements until the returned function is called. Noble has one scan for the\n * whole process, so it runs until its last user is done: connecting to one light doesn't end a\n * search for others.\n */\nasync function listen(noble: Noble, onDiscover: (p: Peripheral) => void): Promise<() => void> {\n const scan = scans.get(noble) ?? { users: 0, turn: Promise.resolve() };\n scans.set(noble, scan);\n const inTurn = (step: () => Promise<void>) => {\n const result = scan.turn.then(step);\n scan.turn = result.catch(() => {});\n return result;\n };\n let done = false;\n const stop = () => {\n if (done) return;\n done = true;\n noble.off(\"discover\", onDiscover);\n void inTurn(async () => {\n scan.users--;\n // A radio that never confirms must not block every later scan.\n if (scan.users === 0) {\n await Promise.race([noble.stopScanningAsync().catch(() => {}), sleep(STOP_TIMEOUT)]);\n }\n });\n };\n\n noble.on(\"discover\", onDiscover);\n try {\n await inTurn(async () => {\n scan.users++;\n // Duplicates on: a light already heard in this scan must be reported to its later users, and\n // the name often comes in a later packet than the first.\n if (scan.users === 1) await noble.startScanningAsync([], true);\n });\n } catch (error) {\n stop();\n throw error;\n }\n return stop;\n}\n\nexport interface DiscoveredLight {\n /** MAC address, or the noble peripheral id where the platform hides it (macOS). */\n address: string;\n name: string;\n rssi: number;\n}\n\nconst GOVEE_NAME = /^(GBK|ihoment|Govee|Minger)_H\\d{3,4}/i;\n\n/**\n * Scans for nearby Govee lights, recognized by their advertised name. A computer's\n * radio can miss a light for 15 seconds at a time, so this listens for `timeout` ms (default 15000),\n * and for as long again while it has found nothing.\n */\nexport async function discoverLights(\n options: { timeout?: number; noble?: Noble } = {},\n): Promise<DiscoveredLight[]> {\n const noble = options.noble ?? (await import(\"@stoprocent/noble\")).default;\n await noble.waitForPoweredOnAsync(BT_TIMEOUT);\n\n const found = new Map<string, DiscoveredLight>();\n const onDiscover = (p: Peripheral) => {\n const name = p.advertisement.localName;\n if (name && GOVEE_NAME.test(name)) {\n found.set(p.id, { address: p.address || p.id, name, rssi: p.rssi });\n }\n };\n const stop = await listen(noble, onDiscover);\n const timeout = options.timeout ?? SCAN_TIME;\n await sleep(timeout);\n for (let i = 0; i < 10 && found.size === 0; i++) await sleep(timeout / 10);\n stop();\n return [...found.values()].sort((a, b) => b.rssi - a.rssi);\n}\n\n/** BLE transport for Node.js / Bun backed by `@stoprocent/noble` (Windows, macOS, Linux). */\nexport class NobleTransport implements GoveeTransport {\n readonly #address: string;\n readonly #timeout: number;\n readonly #name: string | undefined;\n #noble: Noble | undefined;\n #peripheral: Peripheral | undefined;\n #write: Characteristic | undefined;\n #read: Characteristic | undefined;\n #listener: ((data: Buffer) => void) | undefined;\n #onDisconnect: (() => void) | undefined;\n\n /** @param address MAC address, or the noble peripheral id (macOS hides MAC addresses). */\n constructor(address: string, options: NobleTransportOptions = {}) {\n this.#address = normalizeAddress(address);\n this.#timeout = options.timeout ?? BT_TIMEOUT;\n this.#noble = options.noble;\n this.#name = options.name;\n }\n\n async connect(): Promise<string | undefined> {\n this.#noble ??= (await import(\"@stoprocent/noble\")).default;\n await this.#noble.waitForPoweredOnAsync(this.#timeout);\n\n const peripheral =\n (await this.#openKnown(this.#noble)) ??\n (await this.#openFound(await this.#find(this.#noble)));\n\n this.#peripheral = peripheral;\n peripheral.once(\"disconnect\", () => {\n // Ignore the event for a disconnect() we initiated, or for a stale peripheral.\n if (this.#peripheral !== peripheral) return;\n this.#peripheral = this.#write = this.#read = undefined;\n this.#onDisconnect?.();\n });\n return peripheral.advertisement?.localName || this.#name || (await this.#readName(peripheral));\n }\n\n /**\n * Connects by address alone, without waiting to hear the light first: the difference between half a\n * second and many. `undefined` where that does not work.\n */\n async #openKnown(noble: Noble): Promise<Peripheral | undefined> {\n // Elsewhere a connection needs an advertisement, or the address is not the real one.\n if (process.platform !== \"win32\" || this.#address.length !== 12) return undefined;\n let peripheral: Peripheral | undefined;\n try {\n peripheral = await within(noble.connectAsync(this.#address), CONNECT_TIMEOUT, \"connect\");\n await this.#prepare(peripheral);\n return peripheral;\n } catch {\n if (peripheral) await letGo(peripheral);\n return undefined;\n }\n }\n\n async #openFound(peripheral: Peripheral): Promise<Peripheral> {\n for (let attempt = 1; ; attempt++) {\n try {\n await within(peripheral.connectAsync(), CONNECT_TIMEOUT, \"connect\");\n // On Windows, noble reports \"connected\" before the GATT session is usable, and discovering\n // services straight away can make the device drop the connection.\n await sleep(CONNECT_SETTLE_DELAY);\n await this.#prepare(peripheral);\n return peripheral;\n } catch (error) {\n await letGo(peripheral);\n if (attempt >= CONNECT_ATTEMPTS) throw error;\n await sleep(500);\n }\n }\n }\n\n /** Finds what commands are written to and answers read from. */\n async #prepare(peripheral: Peripheral): Promise<void> {\n const writeUuid = toNobleUuid(WRITE_CHARACTERISTIC_UUID);\n const readUuid = toNobleUuid(READ_CHARACTERISTIC_UUID);\n const { characteristics } = await within(\n peripheral.discoverSomeServicesAndCharacteristicsAsync(\n [toNobleUuid(SERVICE_UUID)],\n [writeUuid, readUuid],\n ),\n DISCOVER_TIMEOUT,\n \"answer\",\n );\n this.#write = characteristics.find((c) => c.uuid === writeUuid);\n this.#read = characteristics.find((c) => c.uuid === readUuid);\n if (!this.#write || !this.#read) {\n throw new Error(`${this.#address} does not expose the Govee control characteristics`);\n }\n }\n\n async disconnect(): Promise<void> {\n const peripheral = this.#peripheral;\n this.#peripheral = this.#write = this.#read = undefined;\n if (peripheral) await letGo(peripheral);\n }\n\n async write(data: Uint8Array): Promise<void> {\n const characteristic = this.#require(this.#write);\n const withoutResponse = !characteristic.properties.includes(\"write\");\n await within(\n characteristic.writeAsync(Buffer.from(data), withoutResponse),\n STEP_TIMEOUT,\n \"take the command\",\n );\n }\n\n async subscribe(listener: (data: Uint8Array) => void): Promise<void> {\n const characteristic = this.#require(this.#read);\n if (this.#listener) characteristic.off(\"data\", this.#listener);\n this.#listener = (data) => listener(new Uint8Array(data));\n characteristic.on(\"data\", this.#listener);\n await within(characteristic.subscribeAsync(), STEP_TIMEOUT, \"answer\");\n }\n\n async unsubscribe(): Promise<void> {\n const characteristic = this.#read;\n if (!characteristic) return;\n if (this.#listener) characteristic.off(\"data\", this.#listener);\n this.#listener = undefined;\n await within(characteristic.unsubscribeAsync(), STEP_TIMEOUT, \"disconnect\");\n }\n\n onDisconnect(listener: () => void): void {\n this.#onDisconnect = listener;\n }\n\n #require(characteristic: Characteristic | undefined): Characteristic {\n if (!characteristic) throw new Error(\"Not connected\");\n return characteristic;\n }\n\n async #find(noble: Noble): Promise<Peripheral> {\n const matches = (p: Peripheral) =>\n normalizeAddress(p.address ?? \"\") === this.#address ||\n normalizeAddress(p.id) === this.#address;\n\n const found = Promise.withResolvers<Peripheral>();\n const stop = await listen(noble, (p) => {\n if (matches(p)) found.resolve(p);\n });\n const timer = setTimeout(\n () => found.reject(new Error(`Could not find device ${this.#address}`)),\n this.#timeout,\n );\n try {\n return await found.promise;\n } finally {\n clearTimeout(timer);\n stop();\n }\n }\n\n async #readName(peripheral: Peripheral): Promise<string | undefined> {\n try {\n const read = async () => {\n const { characteristics } = await peripheral.discoverSomeServicesAndCharacteristicsAsync(\n [\"1800\"],\n [toNobleUuid(DEVICE_NAME_UUID)],\n );\n return characteristics[0]?.readAsync();\n };\n const raw = await within(read(), STEP_TIMEOUT, \"say its name\");\n return raw ? new TextDecoder().decode(raw).replace(/\\0+$/, \"\") : undefined;\n } catch {\n // Some platforms (notably Windows) don't allow reading the GAP service.\n return undefined;\n }\n }\n}\n",
|
|
7
7
|
"import type { RGB } from \"./colors.ts\";\n\n/**\n * Client for Govee's official cloud API (https://developer.govee.com), which reaches every\n * Wi-Fi device on your account from anywhere. Get a key in the Govee Home app:\n * Profile → Settings → Apply for API Key.\n */\n\nexport const CLOUD_BASE_URL = \"https://openapi.api.govee.com\";\n\nexport interface Capability {\n type: string;\n instance: string;\n parameters?: CapabilityParameters;\n}\n\nexport interface CapabilityParameters {\n dataType?: \"ENUM\" | \"INTEGER\" | \"STRUCT\" | string;\n unit?: string;\n options?: { name: string; value: unknown }[];\n range?: { min: number; max: number; precision?: number };\n fields?: { fieldName: string; dataType: string; required?: boolean; [key: string]: unknown }[];\n}\n\nexport interface CloudDeviceInfo {\n sku: string;\n /** Device id, e.g. `64:09:C5:32:37:36:2D:13`. */\n device: string;\n deviceName?: string;\n type?: string;\n capabilities: Capability[];\n}\n\nexport interface CapabilityState {\n type: string;\n instance: string;\n state: { value: unknown };\n}\n\nexport interface CloudDeviceState {\n /** If false, the other values are the last known state. */\n online: boolean | undefined;\n power: boolean | undefined;\n /** 1-100. */\n brightness: number | undefined;\n rgb: RGB | undefined;\n colorTemperature: number | undefined;\n /** Every capability as returned by the API, including ones without a typed field above. */\n capabilities: CapabilityState[];\n}\n\n/** A scene that can be passed to `setScene`. */\nexport interface Scene {\n name: string;\n type: string;\n instance: string;\n value: unknown;\n}\n\nexport class GoveeApiError extends Error {\n constructor(\n message: string,\n /** HTTP status, or the `code` field of the response body. */\n readonly status: number,\n readonly body?: unknown,\n ) {\n super(message);\n this.name = \"GoveeApiError\";\n }\n}\n\nexport interface GoveeCloudOptions {\n baseUrl?: string;\n /** How long to wait for an answer in ms. Default 10000. */\n timeout?: number;\n /** Custom fetch, e.g. for proxies or tests. */\n fetch?: typeof fetch;\n}\n\nexport const Capabilities = {\n power: { type: \"devices.capabilities.on_off\", instance: \"powerSwitch\" },\n brightness: { type: \"devices.capabilities.range\", instance: \"brightness\" },\n colorRgb: { type: \"devices.capabilities.color_setting\", instance: \"colorRgb\" },\n colorTemperature: { type: \"devices.capabilities.color_setting\", instance: \"colorTemperatureK\" },\n segmentColor: {\n type: \"devices.capabilities.segment_color_setting\",\n instance: \"segmentedColorRgb\",\n },\n segmentBrightness: {\n type: \"devices.capabilities.segment_color_setting\",\n instance: \"segmentedBrightness\",\n },\n online: { type: \"devices.capabilities.online\", instance: \"online\" },\n} as const;\n\nexport const rgbToInt = ([r, g, b]: RGB): number =>\n ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);\nexport const intToRgb = (value: number): RGB => [\n (value >> 16) & 0xff,\n (value >> 8) & 0xff,\n value & 0xff,\n];\n\nexport class GoveeCloud {\n readonly #apiKey: string;\n readonly #baseUrl: string;\n readonly #fetch: typeof fetch;\n readonly #timeout: number;\n\n constructor(apiKey: string, options: GoveeCloudOptions = {}) {\n if (!apiKey) throw new TypeError(\"A Govee API key is required\");\n this.#apiKey = apiKey;\n this.#baseUrl = options.baseUrl ?? CLOUD_BASE_URL;\n this.#fetch = options.fetch ?? fetch;\n this.#timeout = options.timeout ?? 10_000;\n }\n\n /** Lists every device on the account, with what each one supports. */\n async listDevices(): Promise<CloudDevice[]> {\n const body = await this.#request<{ data: CloudDeviceInfo[] }>(\n \"GET\",\n \"/router/api/v1/user/devices\",\n );\n return body.data.map((info) => new CloudDevice(this, info));\n }\n\n /** Finds a device by id or (case-insensitive) name. */\n async getDevice(idOrName: string): Promise<CloudDevice> {\n const devices = await this.listDevices();\n const needle = idOrName.toLowerCase();\n const found = devices.find(\n (d) => d.id.toLowerCase() === needle || d.name.toLowerCase() === needle,\n );\n if (!found) throw new GoveeApiError(`No device named or with id \"${idOrName}\"`, 404);\n return found;\n }\n\n async getState(sku: string, device: string): Promise<CloudDeviceState> {\n const body = await this.#request<{ payload: { capabilities: CapabilityState[] } }>(\n \"POST\",\n \"/router/api/v1/device/state\",\n { requestId: crypto.randomUUID(), payload: { sku, device } },\n );\n return parseState(body.payload.capabilities);\n }\n\n async control(\n sku: string,\n device: string,\n capability: { type: string; instance: string; value: unknown },\n ): Promise<void> {\n await this.#request(\"POST\", \"/router/api/v1/device/control\", {\n requestId: crypto.randomUUID(),\n payload: { sku, device, capability },\n });\n }\n\n /** Built-in dynamic scenes (\"Sunrise\", \"Aurora\", ...). */\n async getScenes(sku: string, device: string): Promise<Scene[]> {\n return this.#scenes(\"/router/api/v1/device/scenes\", sku, device);\n }\n\n /** DIY scenes created in the Govee Home app. */\n async getDiyScenes(sku: string, device: string): Promise<Scene[]> {\n return this.#scenes(\"/router/api/v1/device/diy-scenes\", sku, device);\n }\n\n async #scenes(path: string, sku: string, device: string): Promise<Scene[]> {\n const body = await this.#request<{ payload: { capabilities: Capability[] } }>(\"POST\", path, {\n requestId: crypto.randomUUID(),\n payload: { sku, device },\n });\n return body.payload.capabilities.flatMap((capability) =>\n (capability.parameters?.options ?? []).map((option) => ({\n name: option.name,\n type: capability.type,\n instance: capability.instance,\n value: option.value,\n })),\n );\n }\n\n async #request<T>(method: \"GET\" | \"POST\", path: string, body?: unknown): Promise<T> {\n const response = await this.#fetch(this.#baseUrl + path, {\n method,\n headers: { \"Content-Type\": \"application/json\", \"Govee-API-Key\": this.#apiKey },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: AbortSignal.timeout(this.#timeout),\n }).catch((error: Error) => {\n if (error.name !== \"TimeoutError\") throw error;\n throw new GoveeApiError(`Govee did not answer within ${this.#timeout / 1000} s`, 408);\n });\n\n const text = await response.text();\n let json: { code?: number; message?: string; msg?: string } | undefined;\n try {\n json = text ? JSON.parse(text) : undefined;\n } catch {\n // Non-JSON error pages are reported with their status below.\n }\n\n const code = json?.code ?? response.status;\n if (!response.ok || code !== 200) {\n const status = response.ok ? code : response.status;\n const message = json?.message ?? json?.msg ?? (text || response.statusText);\n const hint =\n status === 401\n ? \" (check your API key)\"\n : status === 429\n ? \" (rate limited, slow down)\"\n : \"\";\n throw new GoveeApiError(\n `Govee API ${method} ${path} failed: ${status} ${message}${hint}`,\n status,\n json ?? text,\n );\n }\n return json as T;\n }\n}\n\nfunction parseState(capabilities: CapabilityState[]): CloudDeviceState {\n const value = (instance: string) => {\n const v = capabilities.find((c) => c.instance === instance)?.state.value;\n return v === \"\" || v === null ? undefined : v;\n };\n const number = (instance: string) => {\n const v = value(instance);\n return typeof v === \"number\" ? v : undefined;\n };\n\n const online = value(\"online\");\n const power = number(\"powerSwitch\");\n const color = number(\"colorRgb\");\n return {\n online: typeof online === \"boolean\" ? online : undefined,\n power: power === undefined ? undefined : power === 1,\n brightness: number(\"brightness\"),\n rgb: color === undefined ? undefined : intToRgb(color),\n colorTemperature: number(\"colorTemperatureK\") || undefined,\n capabilities,\n };\n}\n\n/** A device on the account, with helpers for the common capabilities. */\nexport class CloudDevice {\n readonly sku: string;\n readonly id: string;\n readonly name: string;\n readonly type: string | undefined;\n readonly capabilities: readonly Capability[];\n readonly #cloud: GoveeCloud;\n\n constructor(cloud: GoveeCloud, info: CloudDeviceInfo) {\n this.#cloud = cloud;\n this.sku = info.sku;\n this.id = info.device;\n this.name = info.deviceName || info.sku;\n this.type = info.type;\n this.capabilities = info.capabilities ?? [];\n }\n\n /** The capability definition for an instance, e.g. `\"brightness\"`, if the device has it. */\n capability(instance: string): Capability | undefined {\n return this.capabilities.find((c) => c.instance === instance);\n }\n\n supports(instance: string): boolean {\n return this.capability(instance) !== undefined;\n }\n\n /** Groups made in the Govee app (sku `BaseGroup`, `SameModeGroup`, ...) only support power. */\n get isGroup(): boolean {\n return /group$/i.test(this.sku);\n }\n\n getState(): Promise<CloudDeviceState> {\n if (this.isGroup) {\n return Promise.reject(\n new GoveeApiError(`${this.name} is a group; groups have no readable state`, 400),\n );\n }\n return this.#cloud.getState(this.sku, this.id);\n }\n\n /** Sends any capability, for features without a dedicated helper. */\n control(type: string, instance: string, value: unknown): Promise<void> {\n return this.#cloud.control(this.sku, this.id, { type, instance, value });\n }\n\n setPower(on: boolean): Promise<void> {\n return this.#send(Capabilities.power, on ? 1 : 0);\n }\n\n turnOn(): Promise<void> {\n return this.setPower(true);\n }\n\n turnOff(): Promise<void> {\n return this.setPower(false);\n }\n\n /** Brightness in percent, 1-100. */\n setBrightness(percent: number): Promise<void> {\n const { min, max } = this.capability(\"brightness\")?.parameters?.range ?? { min: 1, max: 100 };\n return this.#send(Capabilities.brightness, clampInt(percent, min, max, \"Brightness\"));\n }\n\n setColor(rgb: RGB): Promise<void> {\n for (const channel of rgb) clampInt(channel, 0, 255, \"Color channel\", true);\n return this.#send(Capabilities.colorRgb, rgbToInt(rgb));\n }\n\n /** Color temperature in Kelvin; the valid range depends on the device (often 2000-9000). */\n setColorTemperature(kelvin: number): Promise<void> {\n const { min, max } = this.capability(\"colorTemperatureK\")?.parameters?.range ?? {\n min: 2000,\n max: 9000,\n };\n return this.#send(\n Capabilities.colorTemperature,\n clampInt(kelvin, min, max, \"Color temperature\"),\n );\n }\n\n /** Colors individual segments of an RGBIC strip. Segment indexes start at 0. */\n setSegmentColor(segments: number[], rgb: RGB): Promise<void> {\n return this.#send(Capabilities.segmentColor, { segment: segments, rgb: rgbToInt(rgb) });\n }\n\n setSegmentBrightness(segments: number[], percent: number): Promise<void> {\n return this.#send(Capabilities.segmentBrightness, {\n segment: segments,\n brightness: clampInt(percent, 0, 100, \"Brightness\"),\n });\n }\n\n /** Built-in scenes; empty if the device has none (the API would answer 400). */\n async getScenes(): Promise<Scene[]> {\n return this.supports(\"lightScene\") ? this.#cloud.getScenes(this.sku, this.id) : [];\n }\n\n /** DIY scenes made in the Govee Home app; empty if the device doesn't support them. */\n async getDiyScenes(): Promise<Scene[]> {\n return this.supports(\"diyScene\") ? this.#cloud.getDiyScenes(this.sku, this.id) : [];\n }\n\n /** Built-in and DIY scenes together. */\n async getAllScenes(): Promise<Scene[]> {\n const [scenes, diy] = await Promise.all([this.getScenes(), this.getDiyScenes()]);\n return [...scenes, ...diy];\n }\n\n /** Applies a scene from `getScenes()` / `getDiyScenes()`. */\n setScene(scene: Scene): Promise<void> {\n return this.control(scene.type, scene.instance, scene.value);\n }\n\n #send(capability: { type: string; instance: string }, value: unknown): Promise<void> {\n if (!this.supports(capability.instance)) {\n return Promise.reject(\n new GoveeApiError(\n `${this.name} (${this.sku}) does not support ${capability.instance}`,\n 400,\n ),\n );\n }\n return this.control(capability.type, capability.instance, value);\n }\n}\n\nfunction clampInt(value: number, min: number, max: number, label: string, strict = false): number {\n if (!Number.isFinite(value)) throw new TypeError(`${label} must be a number`);\n const rounded = Math.round(value);\n if (strict && (rounded < min || rounded > max)) {\n throw new RangeError(`${label} must be between ${min} and ${max}`);\n }\n return Math.min(max, Math.max(min, rounded));\n}\n",
|
|
8
8
|
"export type RGB = readonly [r: number, g: number, b: number];\n\nexport const COLORS = {\n white: [255, 255, 255],\n warm_white: [255, 166, 87],\n cool_white: [255, 254, 250],\n\n black: [0, 0, 0],\n\n red: [255, 0, 0],\n dark_red: [139, 0, 0],\n light_red: [255, 69, 69],\n\n green: [0, 255, 0],\n dark_green: [0, 100, 0],\n light_green: [144, 238, 144],\n\n blue: [0, 0, 255],\n dark_blue: [0, 0, 139],\n light_blue: [173, 216, 230],\n\n yellow: [255, 255, 0],\n dark_yellow: [184, 134, 11],\n light_yellow: [255, 255, 153],\n\n orange: [255, 165, 0],\n dark_orange: [255, 140, 0],\n light_orange: [255, 179, 71],\n\n purple: [128, 0, 128],\n dark_purple: [75, 0, 130],\n light_purple: [218, 112, 214],\n\n pink: [255, 182, 193],\n dark_pink: [255, 20, 147],\n light_pink: [255, 182, 193],\n\n brown: [165, 42, 42],\n dark_brown: [139, 69, 19],\n light_brown: [205, 133, 63],\n} as const satisfies Record<string, RGB>;\n\nexport type ColorName = keyof typeof COLORS;\n\nexport const COLOR_NAMES = Object.keys(COLORS) as ColorName[];\n\nexport function isColorName(name: string): name is ColorName {\n return Object.hasOwn(COLORS, name.toLowerCase());\n}\n\n/** Looks up a named color (case-insensitive). Returns `undefined` for unknown names. */\nexport function colorNameToRgb(name: string): RGB | undefined {\n const key = name.toLowerCase();\n return isColorName(key) ? COLORS[key] : undefined;\n}\n\n/** Returns the named color closest (by euclidean distance) to the given RGB value. */\nexport function rgbToColorName(rgb: RGB): ColorName {\n let closest: ColorName = \"black\";\n let min = Infinity;\n for (const name of COLOR_NAMES) {\n const [r, g, b] = COLORS[name];\n const d = Math.hypot(rgb[0] - r, rgb[1] - g, rgb[2] - b);\n if (d < min) {\n min = d;\n closest = name;\n }\n }\n return closest;\n}\n",
|
|
9
9
|
"import type { RGB } from \"./colors.ts\";\nimport { BRIGHTNESS_MAX, BRIGHTNESS_MIN, PACKET_LENGTH } from \"./constants.ts\";\n\n/** XOR of all bytes. */\nexport function checksum(bytes: ArrayLike<number>): number {\n let result = 0;\n for (let i = 0; i < bytes.length; i++) result ^= bytes[i] ?? 0;\n return result;\n}\n\n/** Builds a 20-byte packet: the payload, zero-padded, followed by its XOR checksum. */\nexport function buildPacket(payload: readonly number[]): Uint8Array {\n if (payload.length > PACKET_LENGTH - 1) {\n throw new RangeError(`Payload must be at most ${PACKET_LENGTH - 1} bytes`);\n }\n const packet = new Uint8Array(PACKET_LENGTH);\n packet.set(payload);\n packet[PACKET_LENGTH - 1] = checksum(packet.subarray(0, PACKET_LENGTH - 1));\n return packet;\n}\n\nfunction assertByte(value: number, label: string, min = 0, max = 255): void {\n if (!Number.isInteger(value)) throw new TypeError(`${label} must be an integer`);\n if (value < min || value > max) {\n throw new RangeError(`${label} must be between ${min} and ${max}`);\n }\n}\n\n/**\n * Govee models differ in how they encode \"set color\":\n * - `legacy`: `33 05 02 RR GG BB ...` (H613B, the original target)\n * - `manual`: `33 05 0D RR GG BB` (many newer strips)\n * - `manual-0b`: `33 05 0B RR GG BB` (some bulbs/strips)\n * - `segments`: `33 05 15 01 RR GG BB ... FF FF`, sets all segments (RGBIC strips)\n */\nexport type ColorMode = \"legacy\" | \"manual\" | \"manual-0b\" | \"segments\";\n\nexport const COLOR_MODES: readonly ColorMode[] = [\"legacy\", \"manual\", \"manual-0b\", \"segments\"];\n\nexport const Commands = {\n turnOn: () => buildPacket([0x33, 0x01, 0x01]),\n turnOff: () => buildPacket([0x33, 0x01, 0x00]),\n\n setBrightness(brightness: number): Uint8Array {\n assertByte(brightness, \"Brightness\", BRIGHTNESS_MIN, BRIGHTNESS_MAX);\n return buildPacket([0x33, 0x04, brightness]);\n },\n\n setColor([r, g, b]: RGB, mode: ColorMode = \"legacy\"): Uint8Array {\n assertByte(r, \"Red\");\n assertByte(g, \"Green\");\n assertByte(b, \"Blue\");\n switch (mode) {\n case \"legacy\":\n return buildPacket([0x33, 0x05, 0x02, r, g, b, 0x00, 0xff, 0xae, 0x54]);\n case \"manual\":\n return buildPacket([0x33, 0x05, 0x0d, r, g, b]);\n case \"manual-0b\":\n return buildPacket([0x33, 0x05, 0x0b, r, g, b]);\n case \"segments\":\n return buildPacket([0x33, 0x05, 0x15, 0x01, r, g, b, 0, 0, 0, 0, 0, 0xff, 0xff]);\n }\n },\n\n getPower: () => buildPacket([0xaa, 0x01]),\n getBrightness: () => buildPacket([0xaa, 0x04]),\n getColor: () => buildPacket([0xaa, 0x05, 0x01]),\n} as const;\n\nexport type StatusResponse =\n | { type: \"power\"; power: boolean }\n | { type: \"brightness\"; brightness: number }\n /** `mode` is the color format the device reported, if it's one we know. */\n | { type: \"color\"; rgb: RGB; mode: ColorMode | undefined }\n | { type: \"unknown\"; data: Uint8Array };\n\nconst MODE_BYTES: Record<number, ColorMode> = {\n 2: \"legacy\",\n 13: \"manual\",\n 11: \"manual-0b\",\n 21: \"segments\",\n};\n\n/** Color formats of models confirmed on real hardware, keyed by model number. */\nexport const KNOWN_MODEL_COLOR_MODES: Readonly<Record<string, ColorMode>> = {\n H613B: \"legacy\",\n H613C: \"manual\",\n};\n\n/** Extracts the model number from an advertised name such as `GBK_H613C_6FB2`. */\nexport function modelFromName(name: string | undefined): string | undefined {\n return name?.match(/H\\d{3,4}[A-Z]?/i)?.[0].toUpperCase();\n}\n\n/** Parses a notification received on the read characteristic. */\nexport function parseResponse(data: Uint8Array): StatusResponse {\n if (data[0] === 0xaa && data.length >= 6) {\n switch (data[1]) {\n case 0x01:\n return { type: \"power\", power: data[2] === 0x01 };\n case 0x04:\n return { type: \"brightness\", brightness: data[2] ?? 0 };\n case 0x05:\n return {\n type: \"color\",\n rgb: [data[3] ?? 0, data[4] ?? 0, data[5] ?? 0],\n mode: MODE_BYTES[data[2] ?? 0],\n };\n }\n }\n return { type: \"unknown\", data };\n}\n\nexport function toHex(data: Uint8Array): string {\n return Array.from(data, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n",
|
|
@@ -15,7 +15,7 @@ export interface DiscoveredLight {
|
|
|
15
15
|
rssi: number;
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
* Scans for nearby Govee lights,
|
|
18
|
+
* Scans for nearby Govee lights, recognized by their advertised name. A computer's
|
|
19
19
|
* radio can miss a light for 15 seconds at a time, so this listens for `timeout` ms (default 15000),
|
|
20
20
|
* and for as long again while it has found nothing.
|
|
21
21
|
*/
|
package/package.json
CHANGED
package/src/transports/noble.ts
CHANGED
|
@@ -112,7 +112,7 @@ export interface DiscoveredLight {
|
|
|
112
112
|
const GOVEE_NAME = /^(GBK|ihoment|Govee|Minger)_H\d{3,4}/i;
|
|
113
113
|
|
|
114
114
|
/**
|
|
115
|
-
* Scans for nearby Govee lights,
|
|
115
|
+
* Scans for nearby Govee lights, recognized by their advertised name. A computer's
|
|
116
116
|
* radio can miss a light for 15 seconds at a time, so this listens for `timeout` ms (default 15000),
|
|
117
117
|
* and for as long again while it has found nothing.
|
|
118
118
|
*/
|