periph 1.5.0 → 1.5.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.
Files changed (79) hide show
  1. package/README.md +19 -0
  2. package/examples/color/as7262/complete.js +60 -0
  3. package/examples/color/as7262/demo.js +65 -0
  4. package/examples/color/as7262/minimal.js +23 -0
  5. package/examples/environmental/aht10/complete.js +37 -0
  6. package/examples/environmental/aht10/demo.js +43 -0
  7. package/examples/environmental/aht10/minimal.js +12 -0
  8. package/examples/environmental/aht20/complete.js +41 -0
  9. package/examples/environmental/aht20/demo.js +49 -0
  10. package/examples/environmental/aht20/minimal.js +12 -0
  11. package/examples/environmental/am2320/complete.js +34 -0
  12. package/examples/environmental/am2320/demo.js +46 -0
  13. package/examples/environmental/am2320/minimal.js +21 -0
  14. package/examples/humidity/hdc1008/complete.js +39 -0
  15. package/examples/humidity/hdc1008/demo.js +46 -0
  16. package/examples/humidity/hdc1008/minimal.js +22 -0
  17. package/examples/humidity/hdc1080/complete.js +34 -0
  18. package/examples/humidity/hdc1080/demo.js +46 -0
  19. package/examples/humidity/hdc1080/minimal.js +22 -0
  20. package/examples/humidity/hs30xx/complete.js +43 -0
  21. package/examples/humidity/hs30xx/demo.js +40 -0
  22. package/examples/humidity/hs30xx/minimal.js +21 -0
  23. package/examples/humidity/hs40xx/complete.js +54 -0
  24. package/examples/humidity/hs40xx/demo.js +38 -0
  25. package/examples/humidity/hs40xx/minimal.js +21 -0
  26. package/examples/io_expander/tca9554/complete.js +63 -0
  27. package/examples/io_expander/tca9554/demo.js +58 -0
  28. package/examples/io_expander/tca9554/minimal.js +20 -0
  29. package/examples/led/ht16k33/complete.js +45 -0
  30. package/examples/led/ht16k33/demo.js +54 -0
  31. package/examples/led/ht16k33/minimal.js +24 -0
  32. package/examples/led/is31fl3731/complete.js +60 -0
  33. package/examples/led/is31fl3731/demo.js +72 -0
  34. package/examples/led/is31fl3731/minimal.js +26 -0
  35. package/examples/led/pca9685/complete.js +43 -0
  36. package/examples/led/pca9685/demo.js +77 -0
  37. package/examples/led/pca9685/minimal.js +24 -0
  38. package/examples/power/ina260/complete.js +38 -0
  39. package/examples/power/ina260/demo.js +32 -0
  40. package/examples/power/ina260/minimal.js +11 -0
  41. package/examples/power/lc709203f/complete.js +57 -0
  42. package/examples/power/lc709203f/demo.js +34 -0
  43. package/examples/power/lc709203f/minimal.js +11 -0
  44. package/examples/power/lm25066/complete.js +54 -0
  45. package/examples/power/lm25066/demo.js +41 -0
  46. package/examples/power/lm25066/minimal.js +12 -0
  47. package/examples/power/ltc4151/complete.js +40 -0
  48. package/examples/power/ltc4151/demo.js +49 -0
  49. package/examples/power/ltc4151/minimal.js +11 -0
  50. package/examples/power/max17048/complete.js +68 -0
  51. package/examples/power/max17048/demo.js +56 -0
  52. package/examples/power/max17048/minimal.js +19 -0
  53. package/examples/pressure/lps22hb/complete.js +43 -0
  54. package/examples/pressure/lps22hb/demo.js +43 -0
  55. package/examples/pressure/lps22hb/minimal.js +19 -0
  56. package/examples/pressure/mpl115a2/complete.js +25 -0
  57. package/examples/pressure/mpl115a2/demo.js +30 -0
  58. package/examples/pressure/mpl115a2/minimal.js +20 -0
  59. package/package.json +1 -1
  60. package/src/chips/color/as7262.js +419 -0
  61. package/src/chips/environmental/aht10.js +186 -0
  62. package/src/chips/environmental/aht20.js +226 -0
  63. package/src/chips/environmental/am2320.js +237 -0
  64. package/src/chips/humidity/hdc1008.js +262 -0
  65. package/src/chips/humidity/hdc1080.js +208 -0
  66. package/src/chips/humidity/hs30xx.js +254 -0
  67. package/src/chips/humidity/hs40xx.js +382 -0
  68. package/src/chips/io_expander/tca9554.js +407 -0
  69. package/src/chips/led/ht16k33.js +273 -0
  70. package/src/chips/led/is31fl3731.js +501 -0
  71. package/src/chips/led/pca9685.js +350 -0
  72. package/src/chips/power/ina260.js +229 -0
  73. package/src/chips/power/lc709203f.js +376 -0
  74. package/src/chips/power/lm25066.js +370 -0
  75. package/src/chips/power/ltc4151.js +297 -0
  76. package/src/chips/power/max17048.js +302 -0
  77. package/src/chips/pressure/lps22hb.js +257 -0
  78. package/src/chips/pressure/mpl115a2.js +171 -0
  79. package/src/discovery/registry.js +56 -14
@@ -0,0 +1,419 @@
1
+ 'use strict';
2
+
3
+ const _HW_STATUS = 0x00;
4
+ const _HW_WRITE = 0x01;
5
+ const _HW_READ = 0x02;
6
+ const _TX_VALID = 0x02;
7
+ const _RX_VALID = 0x01;
8
+
9
+ const _REG_HW_VERSION = 0x00;
10
+ const _REG_FW_VERSION = 0x02;
11
+ const _REG_CONTROL = 0x04;
12
+ const _REG_INT_T = 0x05;
13
+ const _REG_TEMP = 0x06;
14
+ const _REG_LED = 0x07;
15
+ const _REG_RAW = 0x08;
16
+ const _REG_CAL = 0x14;
17
+
18
+ const _CTRL_RST = 0x80;
19
+ const _CTRL_INT = 0x40;
20
+ const _CTRL_DATA_RDY = 0x02;
21
+
22
+ const _INT_T_DEFAULT = 0x3B;
23
+ const _GAIN_DEFAULT = 2;
24
+ const _STEP_MS = 2.8;
25
+ const _TIMEOUT_MS = 1000;
26
+ const _CHANNELS = ['violet', 'blue', 'green', 'yellow', 'orange', 'red'];
27
+ const _GAINS = [1.0, 3.7, 16.0, 64.0];
28
+ const _DRV_CURRENTS = [12.5, 25.0, 50.0, 100.0];
29
+ const _IND_CURRENTS = [1.0, 2.0, 4.0, 8.0];
30
+
31
+ const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32
+
33
+ function _nearest(options, value) {
34
+ if (value > options[options.length - 1]) {
35
+ throw new RangeError('current above maximum ' + options[options.length - 1] + ' mA');
36
+ }
37
+ let best = 0;
38
+ options.forEach((o, i) => { if (Math.abs(o - value) < Math.abs(options[best] - value)) best = i; });
39
+ return best;
40
+ }
41
+
42
+ /**
43
+ * AS7262 6-channel visible spectral sensor — minimal interface.
44
+ *
45
+ * The AS7262 (ams OSRAM) measures violet (450 nm), blue (500 nm), green (550 nm), yellow (570 nm),
46
+ * orange (600 nm) and red (650 nm). Every sensor register is a *virtual register* reached through
47
+ * three hardware registers (STATUS 0x00, WRITE 0x01, READ 0x02); this class implements the handshake.
48
+ *
49
+ * `init()` soft-resets the chip and configures the Minimal defaults: gain 16x, integration time 0x3B
50
+ * (165.2 ms), one-shot bank mode 3, both LED outputs off, INT pin disabled. `read()` runs one one-shot
51
+ * conversion. Call `await sensor.init()` once before use.
52
+ */
53
+ class AS7262Minimal {
54
+ /**
55
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - Register-capable I²C connection pointing at the device (address 0x49).
56
+ */
57
+ constructor(connection) {
58
+ this._conn = connection;
59
+ }
60
+
61
+ async _status() {
62
+ return (await this._conn.readReg(_HW_STATUS, 1))[0];
63
+ }
64
+
65
+ async _waitStatus(mask, want, timeoutMs = 2000) {
66
+ const deadline = Date.now() + timeoutMs;
67
+ for (;;) {
68
+ if (((await this._status()) & mask) === want) return;
69
+ if (Date.now() >= deadline) throw new Error('AS7262 virtual-register handshake time-out');
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Read one virtual register through the STATUS/WRITE/READ handshake.
75
+ * @param {number} reg - Virtual register address (0x00-0x2B).
76
+ * @returns {Promise<number>} The register byte.
77
+ */
78
+ async readVirtual(reg) {
79
+ await this._waitStatus(_TX_VALID, 0);
80
+ if ((await this._status()) & _RX_VALID) await this._conn.readReg(_HW_READ, 1);
81
+ await this._conn.writeReg(_HW_WRITE, reg & 0x7F);
82
+ await this._waitStatus(_RX_VALID, _RX_VALID);
83
+ return (await this._conn.readReg(_HW_READ, 1))[0];
84
+ }
85
+
86
+ /**
87
+ * Write one virtual register through the STATUS/WRITE handshake.
88
+ * @param {number} reg - Virtual register address (0x04, 0x05 or 0x07 are writable).
89
+ * @param {number} value - Byte to write (0-255).
90
+ * @returns {Promise<void>}
91
+ */
92
+ async writeVirtual(reg, value) {
93
+ await this._waitStatus(_TX_VALID, 0);
94
+ await this._conn.writeReg(_HW_WRITE, (reg & 0x7F) | 0x80);
95
+ await this._waitStatus(_TX_VALID, 0);
96
+ await this._conn.writeReg(_HW_WRITE, value & 0xFF);
97
+ }
98
+
99
+ async _waitBoot() {
100
+ const deadline = Date.now() + 2000;
101
+ for (;;) {
102
+ try {
103
+ if ((await this.readVirtual(_REG_HW_VERSION)) === 0x40) return;
104
+ } catch (e) { /* retry */ }
105
+ if (Date.now() >= deadline) throw new Error('AS7262 not found (HW_VERSION != 0x40)');
106
+ await _sleep(10);
107
+ }
108
+ }
109
+
110
+ async _reset() {
111
+ await this.writeVirtual(_REG_CONTROL, _CTRL_RST);
112
+ const deadline = Date.now() + _TIMEOUT_MS;
113
+ for (;;) {
114
+ await _sleep(10);
115
+ try {
116
+ if (!((await this.readVirtual(_REG_CONTROL)) & _CTRL_RST)) return;
117
+ } catch (e) { /* retry */ }
118
+ if (Date.now() >= deadline) throw new Error('AS7262 reset time-out');
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Wait for the chip to boot, soft-reset it and write the Minimal defaults.
124
+ * @returns {Promise<void>}
125
+ */
126
+ async init() {
127
+ await this._waitBoot();
128
+ await this._reset();
129
+ await this.writeVirtual(_REG_INT_T, _INT_T_DEFAULT);
130
+ await this.writeVirtual(_REG_LED, 0x00);
131
+ await this.writeVirtual(_REG_CONTROL, _GAIN_DEFAULT << 4);
132
+ }
133
+
134
+ async _startOneShot() {
135
+ const ctrl = await this.readVirtual(_REG_CONTROL);
136
+ await this.writeVirtual(_REG_CONTROL, (ctrl & 0x70) | (3 << 2));
137
+ }
138
+
139
+ async _waitData() {
140
+ const intMs = (await this.readVirtual(_REG_INT_T)) * _STEP_MS;
141
+ const deadline = Date.now() + 2 * intMs + _TIMEOUT_MS;
142
+ for (;;) {
143
+ if ((await this.readVirtual(_REG_CONTROL)) & _CTRL_DATA_RDY) return;
144
+ if (Date.now() >= deadline) throw new Error('AS7262 conversion time-out');
145
+ await _sleep(5);
146
+ }
147
+ }
148
+
149
+ async _readCalibrated() {
150
+ const data = Buffer.alloc(24);
151
+ for (let i = 0; i < 24; i++) data[i] = await this.readVirtual(_REG_CAL + i);
152
+ const out = {};
153
+ _CHANNELS.forEach((name, i) => { out[name] = data.readFloatBE(4 * i); });
154
+ return out;
155
+ }
156
+
157
+ /**
158
+ * Run one one-shot conversion and return the six calibrated channels.
159
+ * @returns {Promise<{violet: number, blue: number, green: number, yellow: number, orange: number, red: number}>}
160
+ */
161
+ async read() {
162
+ await this._startOneShot();
163
+ await this._waitData();
164
+ return this._readCalibrated();
165
+ }
166
+
167
+ /**
168
+ * Read the device temperature.
169
+ * @returns {Promise<number>} Temperature in °C.
170
+ */
171
+ async temperature() {
172
+ return this.readVirtual(_REG_TEMP);
173
+ }
174
+ }
175
+
176
+ /**
177
+ * AS7262 full interface — raw counts, gain, integration time, bank modes, LEDs, interrupt.
178
+ * Extends AS7262Minimal; call `await sensor.init()` once before use.
179
+ */
180
+ class AS7262Full extends AS7262Minimal {
181
+ /**
182
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - Register-capable I²C connection pointing at the device (address 0x49).
183
+ */
184
+ constructor(connection) {
185
+ super(connection);
186
+ this._callback = null;
187
+ this._intPin = null;
188
+ this._edgeHandler = null;
189
+ this._pollTimer = null;
190
+ }
191
+
192
+ async _readRawRegs() {
193
+ const data = [];
194
+ for (let i = 0; i < 12; i++) data.push(await this.readVirtual(_REG_RAW + i));
195
+ const out = {};
196
+ _CHANNELS.forEach((name, i) => { out[name] = (data[2 * i] << 8) | data[2 * i + 1]; });
197
+ return out;
198
+ }
199
+
200
+ /**
201
+ * Run one one-shot conversion and return the raw 16-bit counts.
202
+ * @returns {Promise<{violet: number, blue: number, green: number, yellow: number, orange: number, red: number}>}
203
+ */
204
+ async readRaw() {
205
+ await this._startOneShot();
206
+ await this._waitData();
207
+ return this._readRawRegs();
208
+ }
209
+
210
+ /** Start a one-shot conversion without waiting for it (BANK = 3). */
211
+ async measure() {
212
+ await this._startOneShot();
213
+ }
214
+
215
+ /**
216
+ * @returns {Promise<boolean>} True if a conversion result is waiting (CONTROL_SETUP.DATA_RDY).
217
+ */
218
+ async dataReady() {
219
+ return Boolean((await this.readVirtual(_REG_CONTROL)) & _CTRL_DATA_RDY);
220
+ }
221
+
222
+ /**
223
+ * Read the last calibrated results without starting a conversion.
224
+ * @returns {Promise<object>} `{violet, ..., red}` floats.
225
+ */
226
+ async readCalibrated() {
227
+ return this._readCalibrated();
228
+ }
229
+
230
+ /**
231
+ * Read the last raw counts without starting a conversion.
232
+ * @returns {Promise<object>} `{violet, ..., red}` integers.
233
+ */
234
+ async readRawLast() {
235
+ return this._readRawRegs();
236
+ }
237
+
238
+ /**
239
+ * Read one channel of the last conversion.
240
+ * @param {number} index - Channel 0-5 (V, B, G, Y, O, R).
241
+ * @param {boolean} [calibrated=true] - True for the calibrated float, false for the raw count.
242
+ * @returns {Promise<number>}
243
+ */
244
+ async readChannel(index, calibrated = true) {
245
+ if (!(index >= 0 && index <= 5)) throw new RangeError('channel index must be 0-5');
246
+ if (calibrated) {
247
+ const buf = Buffer.alloc(4);
248
+ for (let i = 0; i < 4; i++) buf[i] = await this.readVirtual(_REG_CAL + 4 * index + i);
249
+ return buf.readFloatBE(0);
250
+ }
251
+ const base = _REG_RAW + 2 * index;
252
+ return ((await this.readVirtual(base)) << 8) | (await this.readVirtual(base + 1));
253
+ }
254
+
255
+ async _updateControl(mask, bits) {
256
+ const ctrl = await this.readVirtual(_REG_CONTROL);
257
+ await this.writeVirtual(_REG_CONTROL, (ctrl & 0x7C & ~mask) | bits);
258
+ }
259
+
260
+ /**
261
+ * Set the analog gain.
262
+ * @param {number} gain - 0-3 (index), or the gain 1, 3.7, 16 or 64 (1 means 1x).
263
+ */
264
+ async setGain(gain) {
265
+ let index;
266
+ if (_GAINS.includes(gain)) index = _GAINS.indexOf(gain);
267
+ else if (gain === 0 || gain === 2 || gain === 3) index = gain;
268
+ else throw new RangeError('gain must be 0-3 or one of 1, 3.7, 16, 64');
269
+ await this._updateControl(0x30, index << 4);
270
+ }
271
+
272
+ /** @returns {Promise<number>} The analog gain multiplier (1, 3.7, 16 or 64). */
273
+ async getGain() {
274
+ return _GAINS[((await this.readVirtual(_REG_CONTROL)) >> 4) & 0x03];
275
+ }
276
+
277
+ /**
278
+ * Set the integration time per bank.
279
+ * @param {number} ms - 2.8-714 ms (rounded to a multiple of 2.8 ms).
280
+ */
281
+ async setIntegrationTime(ms) {
282
+ const n = Math.round(ms / _STEP_MS);
283
+ if (n < 1 || n > 255) throw new RangeError('integration time must be 2.8-714 ms');
284
+ await this.writeVirtual(_REG_INT_T, n);
285
+ }
286
+
287
+ /** @returns {Promise<number>} The integration time per bank in milliseconds. */
288
+ async getIntegrationTime() {
289
+ return (await this.readVirtual(_REG_INT_T)) * _STEP_MS;
290
+ }
291
+
292
+ /**
293
+ * Set the bank mode.
294
+ * @param {number} mode - 0 (V,B,G,Y continuous), 1 (G,Y,O,R continuous), 2 (all six continuous) or 3 (all six, one-shot).
295
+ */
296
+ async setMode(mode) {
297
+ if (!(mode >= 0 && mode <= 3)) throw new RangeError('mode must be 0-3');
298
+ await this._updateControl(0x0C, mode << 2);
299
+ }
300
+
301
+ /** @returns {Promise<number>} The bank mode (0-3). */
302
+ async getMode() {
303
+ return ((await this.readVirtual(_REG_CONTROL)) >> 2) & 0x03;
304
+ }
305
+
306
+ /**
307
+ * Switch to continuous conversions.
308
+ * @param {number} [mode=2] - Bank mode 0, 1 or 2.
309
+ */
310
+ async setContinuous(mode = 2) {
311
+ if (![0, 1, 2].includes(mode)) throw new RangeError('continuous mode must be 0, 1 or 2');
312
+ await this.setMode(mode);
313
+ }
314
+
315
+ /** @param {boolean} enabled - Enable or disable the INT pin output (CONTROL_SETUP.INT). */
316
+ async setInterrupt(enabled) {
317
+ await this._updateControl(_CTRL_INT, enabled ? _CTRL_INT : 0);
318
+ }
319
+
320
+ /**
321
+ * Control the driver LED output.
322
+ * @param {boolean} on - True to enable the output.
323
+ * @param {number} [currentMa=12.5] - Current limit; nearest of 12.5, 25, 50, 100 mA.
324
+ */
325
+ async setLed(on, currentMa = 12.5) {
326
+ const index = _nearest(_DRV_CURRENTS, currentMa);
327
+ const led = (await this.readVirtual(_REG_LED)) & 0x07;
328
+ await this.writeVirtual(_REG_LED, led | (index << 4) | (on ? 0x08 : 0));
329
+ }
330
+
331
+ /**
332
+ * Control the indicator LED output.
333
+ * @param {boolean} on - True to enable the output.
334
+ * @param {number} [currentMa=1] - Current limit; nearest of 1, 2, 4, 8 mA.
335
+ */
336
+ async setIndicatorLed(on, currentMa = 1) {
337
+ const index = _nearest(_IND_CURRENTS, currentMa);
338
+ const led = (await this.readVirtual(_REG_LED)) & 0x38;
339
+ await this.writeVirtual(_REG_LED, led | (index << 1) | (on ? 0x01 : 0));
340
+ }
341
+
342
+ /** Soft-reset the chip (all registers return to their defaults). */
343
+ async softReset() {
344
+ await this._reset();
345
+ }
346
+
347
+ /** @returns {Promise<number[]>} `[device_type, hardware_version]` — expect `[0x40, 0x3E]`. */
348
+ async hardwareVersion() {
349
+ return [await this.readVirtual(_REG_HW_VERSION), await this.readVirtual(_REG_HW_VERSION + 1)];
350
+ }
351
+
352
+ /** @returns {Promise<number[]>} The firmware version as `[major, minor, sub]`. */
353
+ async firmwareVersion() {
354
+ const r2 = await this.readVirtual(_REG_FW_VERSION);
355
+ const r3 = await this.readVirtual(_REG_FW_VERSION + 1);
356
+ return [r3 >> 4, ((r3 & 0x0F) << 2) | (r2 >> 6), r2 & 0x3F];
357
+ }
358
+
359
+ /** @returns {Promise<number>} The device type byte (virtual register 0x00, expect 0x40). */
360
+ async deviceType() {
361
+ return this.readVirtual(_REG_HW_VERSION);
362
+ }
363
+
364
+ /**
365
+ * Read CONTROL_SETUP (releases INT) and return DATA_RDY.
366
+ * @returns {Promise<number>} 1 if data is ready, else 0.
367
+ */
368
+ async pollInterrupt() {
369
+ return (await this.readVirtual(_REG_CONTROL)) & _CTRL_DATA_RDY ? 1 : 0;
370
+ }
371
+
372
+ async _dispatch() {
373
+ const cb = this._callback;
374
+ if (!cb) return;
375
+ try {
376
+ const status = await this.pollInterrupt();
377
+ if (status) cb(status);
378
+ } catch (e) { /* ignore */ }
379
+ }
380
+
381
+ /**
382
+ * Enable the INT output and call `callback(status)` on data ready. Subscribes to the falling
383
+ * edge of the INT pin (`intPin` or `connection.intPin`); otherwise polls every integration time.
384
+ * @param {function(number): void} callback - Called with 1 when data is ready.
385
+ * @param {object} [intPin] - Optional InputPin; defaults to `connection.intPin`.
386
+ */
387
+ async onInterrupt(callback, intPin = null) {
388
+ this._callback = callback;
389
+ await this.setInterrupt(true);
390
+ const pin = intPin || this._conn.intPin;
391
+ if (pin) {
392
+ this._intPin = pin;
393
+ this._edgeHandler = () => this._dispatch();
394
+ await pin.onEdge(this._edgeHandler, 'falling');
395
+ } else {
396
+ const periodMs = Math.max(await this.getIntegrationTime(), 10);
397
+ let busy = false;
398
+ this._pollTimer = setInterval(async () => {
399
+ if (busy) return;
400
+ busy = true;
401
+ try { await this._dispatch(); } finally { busy = false; }
402
+ }, periodMs);
403
+ }
404
+ }
405
+
406
+ /** Unsubscribe from the INT pin (or stop the polling task) and disable the INT output. */
407
+ async offInterrupt() {
408
+ this._callback = null;
409
+ if (this._intPin && this._edgeHandler) await this._intPin.offEdge(this._edgeHandler);
410
+ this._intPin = null;
411
+ this._edgeHandler = null;
412
+ if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
413
+ await this.setInterrupt(false);
414
+ }
415
+ }
416
+
417
+ AS7262Minimal.CHANNELS = _CHANNELS;
418
+
419
+ module.exports = { AS7262Minimal, AS7262Full };
@@ -0,0 +1,186 @@
1
+ 'use strict';
2
+
3
+ const _CMD_INIT = Buffer.from([0xE1, 0x08, 0x00]);
4
+ const _CMD_TRIGGER = Buffer.from([0xAC, 0x33, 0x00]);
5
+ const _CMD_SOFT_RESET = Buffer.from([0xBA]);
6
+
7
+ const _STATUS_BUSY = 0x80;
8
+ const _STATUS_CAL = 0x08;
9
+
10
+ function _sleep(ms) {
11
+ const end = Date.now() + ms;
12
+ while (Date.now() < end) {}
13
+ }
14
+
15
+ function _decodeRaw(data) {
16
+ return {
17
+ rawRh: (data[1] << 12) | (data[2] << 4) | (data[3] >> 4),
18
+ rawT: ((data[3] & 0x0F) << 16) | (data[4] << 8) | data[5],
19
+ };
20
+ }
21
+
22
+ /**
23
+ * AHT10 temperature and humidity sensor — minimal interface.
24
+ *
25
+ * Provides temperature and humidity readings with no configuration beyond
26
+ * the connection. Handles power-on wait, initialization (0xE1 calibration
27
+ * enable), calibration check and measurement triggering automatically.
28
+ *
29
+ * Default configuration (baked in at construction):
30
+ * - One-shot measurement triggered on every read() call
31
+ * - 80 ms wait after trigger, then BUSY polling (10 ms steps, 200 ms guard)
32
+ * - No CRC (the AHT10 does not send one)
33
+ *
34
+ * Constructor caveat: JS constructors cannot be async, so the init sequence
35
+ * runs unawaited. Every measurement awaits it first, so errors (e.g. sensor
36
+ * not calibrated after one retry) surface as a rejected promise from the
37
+ * first read()/isCalibrated() call.
38
+ */
39
+ class AHT10Minimal {
40
+ /**
41
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C connection pointing at the device (address 0x38).
42
+ */
43
+ constructor(connection) {
44
+ this._conn = connection;
45
+ this._ready = this._init();
46
+ this._ready.catch(() => {});
47
+ }
48
+
49
+ async _initialize() {
50
+ await this._conn.write(_CMD_INIT);
51
+ _sleep(10);
52
+ }
53
+
54
+ async _init() {
55
+ _sleep(40);
56
+ await this._initialize();
57
+ if (!((await this._readStatus()) & _STATUS_CAL)) {
58
+ await this._conn.write(_CMD_SOFT_RESET);
59
+ _sleep(20);
60
+ await this._initialize();
61
+ if (!((await this._readStatus()) & _STATUS_CAL)) {
62
+ throw new Error('AHT10 not calibrated after init');
63
+ }
64
+ }
65
+ }
66
+
67
+ async _readStatus() {
68
+ return (await this._conn.read(1))[0];
69
+ }
70
+
71
+ async _measure() {
72
+ await this._ready;
73
+ await this._conn.write(_CMD_TRIGGER);
74
+ _sleep(80); // conversion takes > 75 ms
75
+ for (let waited = 0; ; waited += 10) {
76
+ const data = await this._conn.read(6);
77
+ if (!(data[0] & _STATUS_BUSY)) return data;
78
+ if (waited >= 200) throw new Error('AHT10 measurement timeout');
79
+ _sleep(10);
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Trigger a measurement and return temperature and humidity.
85
+ *
86
+ * Sends the trigger command, waits 80 ms, polls BUSY, reads 6 bytes and
87
+ * decodes the raw 20-bit values into physical units.
88
+ *
89
+ * @returns {Promise<{ temperature_c: number, humidity_pct: number }>}
90
+ * temperature_c: Temperature in degrees Celsius (-50 to 150 °C).
91
+ * humidity_pct: Relative humidity in percent (0 to 100 %RH).
92
+ */
93
+ async read() {
94
+ const { rawRh, rawT } = _decodeRaw(await this._measure());
95
+ return {
96
+ temperature_c: (rawT / 1048576.0) * 200.0 - 50.0,
97
+ humidity_pct: Math.min(Math.max((rawRh / 1048576.0) * 100.0, 0.0), 100.0),
98
+ };
99
+ }
100
+ }
101
+
102
+ /**
103
+ * AHT10 full interface — extends AHT10Minimal with raw values, status and dew point.
104
+ */
105
+ class AHT10Full extends AHT10Minimal {
106
+ /**
107
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C connection pointing at the device (address 0x38).
108
+ */
109
+ constructor(connection) {
110
+ super(connection);
111
+ }
112
+
113
+ /**
114
+ * Trigger a measurement and return temperature only.
115
+ * @returns {Promise<number>} Temperature in degrees Celsius (-50 to 150 °C).
116
+ */
117
+ async readTemperature() {
118
+ return (await this.read()).temperature_c;
119
+ }
120
+
121
+ /**
122
+ * Trigger a measurement and return humidity only.
123
+ * @returns {Promise<number>} Relative humidity in percent (0 to 100 %RH).
124
+ */
125
+ async readHumidity() {
126
+ return (await this.read()).humidity_pct;
127
+ }
128
+
129
+ /**
130
+ * Trigger a measurement and return the raw 20-bit values.
131
+ * @returns {Promise<{ raw_humidity: number, raw_temperature: number }>} Each 0 to 1048575.
132
+ */
133
+ async readRaw() {
134
+ const { rawRh, rawT } = _decodeRaw(await this._measure());
135
+ return { raw_humidity: rawRh, raw_temperature: rawT };
136
+ }
137
+
138
+ /**
139
+ * Read the status byte.
140
+ * @returns {Promise<number>} Status byte (bit 7 BUSY, bits 6:5 MODE, bit 3 CAL).
141
+ */
142
+ async readStatus() {
143
+ await this._ready;
144
+ return this._readStatus();
145
+ }
146
+
147
+ /**
148
+ * Check if the calibration bit is set in the status byte.
149
+ * @returns {Promise<boolean>} True if the sensor reports calibration enabled.
150
+ */
151
+ async isCalibrated() {
152
+ return !!((await this.readStatus()) & _STATUS_CAL);
153
+ }
154
+
155
+ /**
156
+ * Check if the busy bit is set in the status byte.
157
+ * @returns {Promise<boolean>} True if a measurement is in progress.
158
+ */
159
+ async isBusy() {
160
+ return !!((await this.readStatus()) & _STATUS_BUSY);
161
+ }
162
+
163
+ /**
164
+ * Send the soft reset command, wait 20 ms, and re-run the init command.
165
+ * @returns {Promise<void>}
166
+ */
167
+ async softReset() {
168
+ await this._ready;
169
+ await this._conn.write(_CMD_SOFT_RESET);
170
+ _sleep(20);
171
+ await this._initialize();
172
+ }
173
+
174
+ /**
175
+ * Trigger a measurement and return the dew point (Magnus formula).
176
+ * @returns {Promise<number>} Dew point in degrees Celsius; -50 if humidity is 0 %RH.
177
+ */
178
+ async dewPoint() {
179
+ const { temperature_c: t, humidity_pct: rh } = await this.read();
180
+ if (rh <= 0) return -50.0;
181
+ const gamma = Math.log(rh / 100.0) + (17.62 * t) / (243.12 + t);
182
+ return (243.12 * gamma) / (17.62 - gamma);
183
+ }
184
+ }
185
+
186
+ module.exports = { AHT10Minimal, AHT10Full };