@sdeck/govee 0.0.0-stage → 0.2.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 +837 -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 +36 -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 +257 -0
|
@@ -0,0 +1,257 @@
|
|
|
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
|
+
const STOP_TIMEOUT = 2000;
|
|
22
|
+
const SCAN_TIME = 15_000;
|
|
23
|
+
|
|
24
|
+
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
25
|
+
|
|
26
|
+
/** Noble reports UUIDs lowercase without dashes, and standard 16-bit UUIDs in short form. */
|
|
27
|
+
function toNobleUuid(uuid: string): string {
|
|
28
|
+
const flat = uuid.replaceAll("-", "").toLowerCase();
|
|
29
|
+
return flat.startsWith("0000") && flat.endsWith(BASE_UUID_SUFFIX) ? flat.slice(4, 8) : flat;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Strips separators so `A4:C1:38:35:97:24`, `a4c138359724` and noble ids compare equal. */
|
|
33
|
+
function normalizeAddress(address: string): string {
|
|
34
|
+
return address.replace(/[^0-9a-f]/gi, "").toLowerCase();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface Scan {
|
|
38
|
+
users: number;
|
|
39
|
+
/** Starting and stopping, one at a time. */
|
|
40
|
+
turn: Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const scans = new WeakMap<Noble, Scan>();
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Listens for advertisements until the returned function is called. Noble has one scan for the
|
|
47
|
+
* whole process, so it runs until its last user is done: connecting to one light doesn't end a
|
|
48
|
+
* search for others.
|
|
49
|
+
*/
|
|
50
|
+
async function listen(noble: Noble, onDiscover: (p: Peripheral) => void): Promise<() => void> {
|
|
51
|
+
const scan = scans.get(noble) ?? { users: 0, turn: Promise.resolve() };
|
|
52
|
+
scans.set(noble, scan);
|
|
53
|
+
const inTurn = (step: () => Promise<void>) => {
|
|
54
|
+
const result = scan.turn.then(step);
|
|
55
|
+
scan.turn = result.catch(() => {});
|
|
56
|
+
return result;
|
|
57
|
+
};
|
|
58
|
+
let done = false;
|
|
59
|
+
const stop = () => {
|
|
60
|
+
if (done) return;
|
|
61
|
+
done = true;
|
|
62
|
+
noble.off("discover", onDiscover);
|
|
63
|
+
void inTurn(async () => {
|
|
64
|
+
scan.users--;
|
|
65
|
+
// A radio that never confirms must not block every later scan.
|
|
66
|
+
if (scan.users === 0) {
|
|
67
|
+
await Promise.race([noble.stopScanningAsync().catch(() => {}), sleep(STOP_TIMEOUT)]);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
noble.on("discover", onDiscover);
|
|
73
|
+
try {
|
|
74
|
+
await inTurn(async () => {
|
|
75
|
+
scan.users++;
|
|
76
|
+
// Duplicates on: a light already heard in this scan must be reported to its later users, and
|
|
77
|
+
// the name often comes in a later packet than the first.
|
|
78
|
+
if (scan.users === 1) await noble.startScanningAsync([], true);
|
|
79
|
+
});
|
|
80
|
+
} catch (error) {
|
|
81
|
+
stop();
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
return stop;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface DiscoveredLight {
|
|
88
|
+
/** MAC address, or the noble peripheral id where the platform hides it (macOS). */
|
|
89
|
+
address: string;
|
|
90
|
+
name: string;
|
|
91
|
+
rssi: number;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const GOVEE_NAME = /^(GBK|ihoment|Govee|Minger)_H\d{3,4}/i;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Scans for nearby Govee lights, recognised by their advertised name. A computer's
|
|
98
|
+
* radio can miss a light for 15 seconds at a time, so this listens for `timeout` ms (default 15000),
|
|
99
|
+
* and for as long again while it has found nothing.
|
|
100
|
+
*/
|
|
101
|
+
export async function discoverLights(
|
|
102
|
+
options: { timeout?: number; noble?: Noble } = {},
|
|
103
|
+
): Promise<DiscoveredLight[]> {
|
|
104
|
+
const noble = options.noble ?? (await import("@stoprocent/noble")).default;
|
|
105
|
+
await noble.waitForPoweredOnAsync(BT_TIMEOUT);
|
|
106
|
+
|
|
107
|
+
const found = new Map<string, DiscoveredLight>();
|
|
108
|
+
const onDiscover = (p: Peripheral) => {
|
|
109
|
+
const name = p.advertisement.localName;
|
|
110
|
+
if (name && GOVEE_NAME.test(name)) {
|
|
111
|
+
found.set(p.id, { address: p.address || p.id, name, rssi: p.rssi });
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const stop = await listen(noble, onDiscover);
|
|
115
|
+
const timeout = options.timeout ?? SCAN_TIME;
|
|
116
|
+
await sleep(timeout);
|
|
117
|
+
for (let i = 0; i < 10 && found.size === 0; i++) await sleep(timeout / 10);
|
|
118
|
+
stop();
|
|
119
|
+
return [...found.values()].sort((a, b) => b.rssi - a.rssi);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** BLE transport for Node.js / Bun backed by `@stoprocent/noble` (Windows, macOS, Linux). */
|
|
123
|
+
export class NobleTransport implements GoveeTransport {
|
|
124
|
+
readonly #address: string;
|
|
125
|
+
readonly #timeout: number;
|
|
126
|
+
#noble: Noble | undefined;
|
|
127
|
+
#peripheral: Peripheral | undefined;
|
|
128
|
+
#write: Characteristic | undefined;
|
|
129
|
+
#read: Characteristic | undefined;
|
|
130
|
+
#listener: ((data: Buffer) => void) | undefined;
|
|
131
|
+
#onDisconnect: (() => void) | undefined;
|
|
132
|
+
|
|
133
|
+
/** @param address MAC address, or the noble peripheral id (macOS hides MAC addresses). */
|
|
134
|
+
constructor(address: string, options: NobleTransportOptions = {}) {
|
|
135
|
+
this.#address = normalizeAddress(address);
|
|
136
|
+
this.#timeout = options.timeout ?? BT_TIMEOUT;
|
|
137
|
+
this.#noble = options.noble;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async connect(): Promise<string | undefined> {
|
|
141
|
+
this.#noble ??= (await import("@stoprocent/noble")).default;
|
|
142
|
+
await this.#noble.waitForPoweredOnAsync(this.#timeout);
|
|
143
|
+
|
|
144
|
+
const peripheral = await this.#find(this.#noble);
|
|
145
|
+
|
|
146
|
+
for (let attempt = 1; ; attempt++) {
|
|
147
|
+
try {
|
|
148
|
+
await this.#open(peripheral);
|
|
149
|
+
break;
|
|
150
|
+
} catch (error) {
|
|
151
|
+
await peripheral.disconnectAsync().catch(() => {});
|
|
152
|
+
if (attempt >= CONNECT_ATTEMPTS) throw error;
|
|
153
|
+
await sleep(500);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
this.#peripheral = peripheral;
|
|
158
|
+
peripheral.once("disconnect", () => {
|
|
159
|
+
// Ignore the event for a disconnect() we initiated, or for a stale peripheral.
|
|
160
|
+
if (this.#peripheral !== peripheral) return;
|
|
161
|
+
this.#peripheral = this.#write = this.#read = undefined;
|
|
162
|
+
this.#onDisconnect?.();
|
|
163
|
+
});
|
|
164
|
+
return (await this.#readName(peripheral)) ?? peripheral.advertisement.localName;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async #open(peripheral: Peripheral): Promise<void> {
|
|
168
|
+
await peripheral.connectAsync();
|
|
169
|
+
// On Windows, noble reports "connected" before the GATT session is usable, and discovering
|
|
170
|
+
// services straight away makes the device drop the connection.
|
|
171
|
+
await sleep(CONNECT_SETTLE_DELAY);
|
|
172
|
+
|
|
173
|
+
const writeUuid = toNobleUuid(WRITE_CHARACTERISTIC_UUID);
|
|
174
|
+
const readUuid = toNobleUuid(READ_CHARACTERISTIC_UUID);
|
|
175
|
+
const { characteristics } = await peripheral.discoverSomeServicesAndCharacteristicsAsync(
|
|
176
|
+
[toNobleUuid(SERVICE_UUID)],
|
|
177
|
+
[writeUuid, readUuid],
|
|
178
|
+
);
|
|
179
|
+
this.#write = characteristics.find((c) => c.uuid === writeUuid);
|
|
180
|
+
this.#read = characteristics.find((c) => c.uuid === readUuid);
|
|
181
|
+
if (!this.#write || !this.#read) {
|
|
182
|
+
throw new Error(`${this.#address} does not expose the Govee control characteristics`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async disconnect(): Promise<void> {
|
|
187
|
+
const peripheral = this.#peripheral;
|
|
188
|
+
this.#peripheral = this.#write = this.#read = undefined;
|
|
189
|
+
await peripheral?.disconnectAsync();
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async write(data: Uint8Array): Promise<void> {
|
|
193
|
+
const characteristic = this.#require(this.#write);
|
|
194
|
+
const withoutResponse = !characteristic.properties.includes("write");
|
|
195
|
+
await characteristic.writeAsync(Buffer.from(data), withoutResponse);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async subscribe(listener: (data: Uint8Array) => void): Promise<void> {
|
|
199
|
+
const characteristic = this.#require(this.#read);
|
|
200
|
+
if (this.#listener) characteristic.off("data", this.#listener);
|
|
201
|
+
this.#listener = (data) => listener(new Uint8Array(data));
|
|
202
|
+
characteristic.on("data", this.#listener);
|
|
203
|
+
await characteristic.subscribeAsync();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async unsubscribe(): Promise<void> {
|
|
207
|
+
const characteristic = this.#read;
|
|
208
|
+
if (!characteristic) return;
|
|
209
|
+
if (this.#listener) characteristic.off("data", this.#listener);
|
|
210
|
+
this.#listener = undefined;
|
|
211
|
+
await characteristic.unsubscribeAsync();
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
onDisconnect(listener: () => void): void {
|
|
215
|
+
this.#onDisconnect = listener;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
#require(characteristic: Characteristic | undefined): Characteristic {
|
|
219
|
+
if (!characteristic) throw new Error("Not connected");
|
|
220
|
+
return characteristic;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async #find(noble: Noble): Promise<Peripheral> {
|
|
224
|
+
const matches = (p: Peripheral) =>
|
|
225
|
+
normalizeAddress(p.address ?? "") === this.#address ||
|
|
226
|
+
normalizeAddress(p.id) === this.#address;
|
|
227
|
+
|
|
228
|
+
const found = Promise.withResolvers<Peripheral>();
|
|
229
|
+
const stop = await listen(noble, (p) => {
|
|
230
|
+
if (matches(p)) found.resolve(p);
|
|
231
|
+
});
|
|
232
|
+
const timer = setTimeout(
|
|
233
|
+
() => found.reject(new Error(`Could not find device ${this.#address}`)),
|
|
234
|
+
this.#timeout,
|
|
235
|
+
);
|
|
236
|
+
try {
|
|
237
|
+
return await found.promise;
|
|
238
|
+
} finally {
|
|
239
|
+
clearTimeout(timer);
|
|
240
|
+
stop();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async #readName(peripheral: Peripheral): Promise<string | undefined> {
|
|
245
|
+
try {
|
|
246
|
+
const { characteristics } = await peripheral.discoverSomeServicesAndCharacteristicsAsync(
|
|
247
|
+
["1800"],
|
|
248
|
+
[toNobleUuid(DEVICE_NAME_UUID)],
|
|
249
|
+
);
|
|
250
|
+
const raw = await characteristics[0]?.readAsync();
|
|
251
|
+
return raw ? new TextDecoder().decode(raw).replace(/\0+$/, "") : undefined;
|
|
252
|
+
} catch {
|
|
253
|
+
// Some platforms (notably Windows) don't allow reading the GAP service.
|
|
254
|
+
return undefined;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|