periph 1.5.2 → 1.5.4

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 (53) hide show
  1. package/README.md +12 -0
  2. package/examples/color/isl29125/complete.js +57 -0
  3. package/examples/color/isl29125/demo.js +77 -0
  4. package/examples/color/isl29125/minimal.js +23 -0
  5. package/examples/environmental/bme688/complete.js +48 -0
  6. package/examples/environmental/bme688/demo.js +47 -0
  7. package/examples/environmental/bme688/minimal.js +21 -0
  8. package/examples/humidity/hts221/complete.js +83 -0
  9. package/examples/humidity/hts221/demo.js +94 -0
  10. package/examples/humidity/hts221/minimal.js +22 -0
  11. package/examples/humidity/htu31d/complete.js +50 -0
  12. package/examples/humidity/htu31d/demo.js +65 -0
  13. package/examples/humidity/htu31d/minimal.js +22 -0
  14. package/examples/humidity/shtc3/complete.js +48 -0
  15. package/examples/humidity/shtc3/demo.js +45 -0
  16. package/examples/humidity/shtc3/minimal.js +22 -0
  17. package/examples/led/saa1064/complete.js +51 -0
  18. package/examples/led/saa1064/demo.js +54 -0
  19. package/examples/led/saa1064/minimal.js +23 -0
  20. package/examples/light/apds9250/complete.js +71 -0
  21. package/examples/light/apds9250/demo.js +79 -0
  22. package/examples/light/apds9250/minimal.js +23 -0
  23. package/examples/light/bh1750/complete.js +46 -0
  24. package/examples/light/bh1750/demo.js +52 -0
  25. package/examples/light/bh1750/minimal.js +22 -0
  26. package/examples/light/si1132/complete.js +70 -0
  27. package/examples/light/si1132/demo.js +73 -0
  28. package/examples/light/si1132/minimal.js +22 -0
  29. package/examples/pressure/mpl3115a2/complete.js +49 -0
  30. package/examples/pressure/mpl3115a2/demo.js +48 -0
  31. package/examples/pressure/mpl3115a2/minimal.js +22 -0
  32. package/examples/pressure/ms5607/complete.js +49 -0
  33. package/examples/pressure/ms5607/demo.js +65 -0
  34. package/examples/pressure/ms5607/minimal.js +22 -0
  35. package/examples/pressure/ms5611/complete.js +49 -0
  36. package/examples/pressure/ms5611/demo.js +65 -0
  37. package/examples/pressure/ms5611/minimal.js +22 -0
  38. package/package.json +1 -1
  39. package/src/chips/color/isl29125.js +379 -0
  40. package/src/chips/environmental/bme688.js +573 -0
  41. package/src/chips/humidity/hts221.js +369 -0
  42. package/src/chips/humidity/htu31d.js +242 -0
  43. package/src/chips/humidity/shtc3.js +239 -0
  44. package/src/chips/led/saa1064.js +241 -0
  45. package/src/chips/light/apds9250.js +431 -0
  46. package/src/chips/light/bh1750.js +196 -0
  47. package/src/chips/light/si1132.js +416 -0
  48. package/src/chips/pressure/mpl3115a2.js +459 -0
  49. package/src/chips/pressure/ms5607.js +290 -0
  50. package/src/chips/pressure/ms5611.js +290 -0
  51. package/src/discovery/registry.js +12 -12
  52. package/examples/gpio/.gitkeep +0 -0
  53. package/src/chips/gpio/.gitkeep +0 -0
@@ -0,0 +1,369 @@
1
+ 'use strict';
2
+
3
+ const { toSigned } = require('../../connection/register');
4
+
5
+ const _REG_WHO_AM_I = 0x0F;
6
+ const _REG_AV_CONF = 0x10;
7
+ const _REG_CTRL_REG1 = 0x20;
8
+ const _REG_CTRL_REG2 = 0x21;
9
+ const _REG_CTRL_REG3 = 0x22;
10
+ const _REG_STATUS = 0x27;
11
+ const _REG_HUMIDITY_OUT = 0x28;
12
+ const _REG_CALIB = 0x30;
13
+
14
+ const _AUTO_INC = 0x80;
15
+ const _CTRL_REG1_DEFAULT = 0x84; // PD=1, BDU=1, ODR=00 (one-shot)
16
+ const _CTRL1_PD = 0x80;
17
+ const _CTRL1_BDU = 0x04;
18
+ const _CTRL1_ODR_MASK = 0x03;
19
+ const _CTRL2_BOOT = 0x80;
20
+ const _CTRL2_HEATER = 0x02;
21
+ const _CTRL2_ONE_SHOT = 0x01;
22
+ const _STATUS_BOTH = 0x03;
23
+ const _TIMEOUT_MS = 100;
24
+
25
+ const _TEMP_SAMPLES = [2, 4, 8, 16, 32, 64, 128, 256];
26
+ const _HUM_SAMPLES = [4, 8, 16, 32, 64, 128, 256, 512];
27
+ const _ODR_HZ = [0, 1, 7, 12.5];
28
+
29
+ const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
30
+
31
+ /**
32
+ * HTS221 capacitive relative-humidity and temperature sensor (STMicroelectronics) — minimal interface.
33
+ *
34
+ * `init()` reads the factory calibration (registers 0x30–0x3F) and writes CTRL_REG1 = 0x84 (active,
35
+ * block data update, one-shot). `read()` starts a one-shot conversion, waits for it (timeout 100 ms)
36
+ * and converts the outputs by linear interpolation. The I²C address is fixed at 0x5F. The constructor
37
+ * does not touch the bus.
38
+ */
39
+ class HTS221Minimal {
40
+ /**
41
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - I²C register connection (0x5F).
42
+ */
43
+ constructor(connection) {
44
+ this._conn = connection;
45
+ this._cal = null;
46
+ }
47
+
48
+ /**
49
+ * Read the calibration block and start one-shot mode (CTRL_REG1 = 0x84).
50
+ * @returns {Promise<void>}
51
+ */
52
+ async init() {
53
+ await this._readCalibration();
54
+ await this._writeReg(_REG_CTRL_REG1, _CTRL_REG1_DEFAULT);
55
+ }
56
+
57
+ async _writeReg(reg, value) {
58
+ await this._conn.writeReg(reg, value & 0xFF);
59
+ }
60
+
61
+ async _readReg(reg) {
62
+ return (await this._conn.readReg(reg, 1))[0];
63
+ }
64
+
65
+ async _readBurst(reg, length) {
66
+ return Buffer.from(await this._conn.readReg(reg | _AUTO_INC, length));
67
+ }
68
+
69
+ async _readCalibration() {
70
+ const c = await this._readBurst(_REG_CALIB, 16);
71
+ const t0 = ((c[5] & 0x03) << 8) | c[2];
72
+ const t1 = ((c[5] & 0x0C) << 6) | c[3];
73
+ this._cal = {
74
+ H0_rH: c[0] / 2.0,
75
+ H1_rH: c[1] / 2.0,
76
+ T0_degC: t0 / 8.0,
77
+ T1_degC: t1 / 8.0,
78
+ H0_T0_OUT: toSigned((c[7] << 8) | c[6], 16),
79
+ H1_T0_OUT: toSigned((c[11] << 8) | c[10], 16),
80
+ T0_OUT: toSigned((c[13] << 8) | c[12], 16),
81
+ T1_OUT: toSigned((c[15] << 8) | c[14], 16),
82
+ };
83
+ }
84
+
85
+ _humidityFromRaw(raw) {
86
+ const c = this._cal;
87
+ const span = c.H1_T0_OUT - c.H0_T0_OUT;
88
+ if (span === 0) return 0.0;
89
+ const v = (raw - c.H0_T0_OUT) * (c.H1_rH - c.H0_rH) / span + c.H0_rH;
90
+ return Math.max(0.0, Math.min(100.0, v));
91
+ }
92
+
93
+ _temperatureFromRaw(raw) {
94
+ const c = this._cal;
95
+ const span = c.T1_OUT - c.T0_OUT;
96
+ if (span === 0) return 0.0;
97
+ return (raw - c.T0_OUT) * (c.T1_degC - c.T0_degC) / span + c.T0_degC;
98
+ }
99
+
100
+ async _readRawPair() {
101
+ const d = await this._readBurst(_REG_HUMIDITY_OUT, 4);
102
+ return [toSigned((d[1] << 8) | d[0], 16), toSigned((d[3] << 8) | d[2], 16)];
103
+ }
104
+
105
+ async _oneShotRaw() {
106
+ const ctrl2 = await this._readReg(_REG_CTRL_REG2);
107
+ await this._writeReg(_REG_CTRL_REG2, ctrl2 | _CTRL2_ONE_SHOT);
108
+ let status = 0;
109
+ for (let i = 0; i < _TIMEOUT_MS; i++) {
110
+ status = await this._readReg(_REG_STATUS);
111
+ if ((status & _STATUS_BOTH) === _STATUS_BOTH) return this._readRawPair();
112
+ await _sleep(1);
113
+ }
114
+ throw new Error('HTS221 conversion timeout (STATUS=0x' + status.toString(16) + ')');
115
+ }
116
+
117
+ /**
118
+ * Measure temperature and relative humidity (one-shot).
119
+ * @returns {Promise<{temperature_c: number, humidity_pct: number}>} °C and %rH (humidity clamped to 0–100)
120
+ */
121
+ async read() {
122
+ const [h, t] = await this._oneShotRaw();
123
+ return { temperature_c: this._temperatureFromRaw(t), humidity_pct: this._humidityFromRaw(h) };
124
+ }
125
+ }
126
+
127
+ /**
128
+ * HTS221 full interface — single values, raw outputs, output data rate, averaging, power modes, heater,
129
+ * DRDY pin, calibration access, dew point and data-ready interrupt support.
130
+ *
131
+ * Extends HTS221Minimal.
132
+ */
133
+ class HTS221Full extends HTS221Minimal {
134
+ /** @param {import('../../connection/register_connection').RegisterConnection} connection - I²C register connection (0x5F). */
135
+ constructor(connection) {
136
+ super(connection);
137
+ this._intCallback = null;
138
+ this._intHandler = null;
139
+ this._pollTimer = null;
140
+ }
141
+
142
+ /** @returns {Promise<number>} Relative humidity in %rH (one-shot, clamped to 0–100). */
143
+ async readHumidity() {
144
+ return this._humidityFromRaw((await this._oneShotRaw())[0]);
145
+ }
146
+
147
+ /** @returns {Promise<number>} Temperature in °C (one-shot). */
148
+ async readTemperature() {
149
+ return this._temperatureFromRaw((await this._oneShotRaw())[1]);
150
+ }
151
+
152
+ /** @returns {Promise<number>} Signed 16-bit raw humidity output (one-shot). */
153
+ async readRawHumidity() {
154
+ return (await this._oneShotRaw())[0];
155
+ }
156
+
157
+ /** @returns {Promise<number>} Signed 16-bit raw temperature output (one-shot). */
158
+ async readRawTemperature() {
159
+ return (await this._oneShotRaw())[1];
160
+ }
161
+
162
+ /**
163
+ * Read the latest sample without starting a conversion (continuous output data rate).
164
+ * @returns {Promise<{temperature_c: number, humidity_pct: number}>}
165
+ */
166
+ async readContinuous() {
167
+ const [h, t] = await this._readRawPair();
168
+ return { temperature_c: this._temperatureFromRaw(t), humidity_pct: this._humidityFromRaw(h) };
169
+ }
170
+
171
+ /** @returns {Promise<number>} Dew point in °C from one measurement (Magnus formula). */
172
+ async dewPoint() {
173
+ const m = await this.read();
174
+ const t = m.temperature_c;
175
+ const h = Math.max(m.humidity_pct, 0.01);
176
+ const g = Math.log(h / 100.0) + 17.62 * t / (243.12 + t);
177
+ return 243.12 * g / (17.62 - g);
178
+ }
179
+
180
+ /**
181
+ * Set the output data rate (CTRL_REG1.ODR).
182
+ * @param {number} hz - 0 (one-shot), 1, 7 or 12.5.
183
+ * @throws {Error} For any other value.
184
+ */
185
+ async setOutputDataRate(hz) {
186
+ const code = _ODR_HZ.indexOf(hz);
187
+ if (code < 0) throw new Error('output data rate must be 0, 1, 7 or 12.5 Hz');
188
+ const ctrl1 = await this._readReg(_REG_CTRL_REG1);
189
+ await this._writeReg(_REG_CTRL_REG1, (ctrl1 & ~_CTRL1_ODR_MASK) | code);
190
+ // Clear flags left over from continuous sampling so the next one-shot wait does not return early.
191
+ await this._readRawPair();
192
+ }
193
+
194
+ /** @returns {Promise<number>} Output data rate in Hz (0, 1, 7 or 12.5). */
195
+ async getOutputDataRate() {
196
+ return _ODR_HZ[(await this._readReg(_REG_CTRL_REG1)) & _CTRL1_ODR_MASK];
197
+ }
198
+
199
+ /**
200
+ * Set the internal averaging (AV_CONF).
201
+ * @param {number} temperatureSamples - 2, 4, 8, 16, 32, 64, 128 or 256.
202
+ * @param {number} humiditySamples - 4, 8, 16, 32, 64, 128, 256 or 512.
203
+ * @throws {Error} For any other value.
204
+ */
205
+ async setAveraging(temperatureSamples, humiditySamples) {
206
+ const t = _TEMP_SAMPLES.indexOf(temperatureSamples);
207
+ const h = _HUM_SAMPLES.indexOf(humiditySamples);
208
+ if (t < 0) throw new Error('temperatureSamples must be a power of two, 2..256');
209
+ if (h < 0) throw new Error('humiditySamples must be a power of two, 4..512');
210
+ await this._writeReg(_REG_AV_CONF, (t << 3) | h);
211
+ }
212
+
213
+ /** @returns {Promise<[number, number]>} [temperature samples, humidity samples]. */
214
+ async getAveraging() {
215
+ const v = await this._readReg(_REG_AV_CONF);
216
+ return [_TEMP_SAMPLES[(v >> 3) & 0x07], _HUM_SAMPLES[v & 0x07]];
217
+ }
218
+
219
+ /** @param {boolean} enabled - Block data update (CTRL_REG1.BDU). */
220
+ async setBlockDataUpdate(enabled) {
221
+ let ctrl1 = await this._readReg(_REG_CTRL_REG1);
222
+ ctrl1 = enabled ? (ctrl1 | _CTRL1_BDU) : (ctrl1 & ~_CTRL1_BDU);
223
+ await this._writeReg(_REG_CTRL_REG1, ctrl1);
224
+ }
225
+
226
+ /** Enter power-down mode (CTRL_REG1.PD = 0). */
227
+ async powerDown() {
228
+ await this._writeReg(_REG_CTRL_REG1, (await this._readReg(_REG_CTRL_REG1)) & ~_CTRL1_PD);
229
+ }
230
+
231
+ /** Leave power-down mode (CTRL_REG1.PD = 1). */
232
+ async powerUp() {
233
+ await this._writeReg(_REG_CTRL_REG1, (await this._readReg(_REG_CTRL_REG1)) | _CTRL1_PD);
234
+ }
235
+
236
+ /** @param {boolean} on - Switch the heater on or off (do not measure while heating). */
237
+ async setHeater(on) {
238
+ let ctrl2 = await this._readReg(_REG_CTRL_REG2);
239
+ ctrl2 = on ? (ctrl2 | _CTRL2_HEATER) : (ctrl2 & ~_CTRL2_HEATER);
240
+ await this._writeReg(_REG_CTRL_REG2, ctrl2);
241
+ }
242
+
243
+ /** @returns {Promise<boolean>} True when the heater is on. */
244
+ async isHeaterOn() {
245
+ return ((await this._readReg(_REG_CTRL_REG2)) & _CTRL2_HEATER) !== 0;
246
+ }
247
+
248
+ /**
249
+ * Reload the trimming registers (CTRL_REG2.BOOT), wait for it to clear (timeout 100 ms) and re-read
250
+ * the calibration.
251
+ * @throws {Error} If BOOT does not clear in time.
252
+ */
253
+ async reboot() {
254
+ const ctrl2 = await this._readReg(_REG_CTRL_REG2);
255
+ await this._writeReg(_REG_CTRL_REG2, ctrl2 | _CTRL2_BOOT);
256
+ for (let i = 0; i < _TIMEOUT_MS; i++) {
257
+ if (((await this._readReg(_REG_CTRL_REG2)) & _CTRL2_BOOT) === 0) {
258
+ await this._readCalibration();
259
+ return;
260
+ }
261
+ await _sleep(1);
262
+ }
263
+ throw new Error('HTS221 reboot timeout');
264
+ }
265
+
266
+ /** @returns {Promise<number>} WHO_AM_I register (0xBC). */
267
+ async whoAmI() {
268
+ return this._readReg(_REG_WHO_AM_I);
269
+ }
270
+
271
+ /** @returns {Promise<number>} STATUS_REG (H_DA = 0x02, T_DA = 0x01). */
272
+ async status() {
273
+ return this._readReg(_REG_STATUS);
274
+ }
275
+
276
+ /** @returns {Promise<boolean>} True when H_DA and T_DA are both set. */
277
+ async dataReady() {
278
+ return ((await this.status()) & _STATUS_BOTH) === _STATUS_BOTH;
279
+ }
280
+
281
+ /** @returns {Promise<object>} Decoded calibration: H0_rH, H1_rH, T0_degC, T1_degC, H0_T0_OUT, H1_T0_OUT, T0_OUT, T1_OUT. */
282
+ async readCalibration() {
283
+ return Object.assign({}, this._cal);
284
+ }
285
+
286
+ /**
287
+ * Configure the DRDY output pin (CTRL_REG3).
288
+ * @param {boolean} enabled - Route data-ready to the DRDY pin.
289
+ * @param {boolean} [activeHigh=true] - false selects active-low.
290
+ * @param {boolean} [openDrain=false] - true selects open-drain.
291
+ */
292
+ async configureDrdy(enabled, activeHigh = true, openDrain = false) {
293
+ let v = 0;
294
+ if (!activeHigh) v |= 0x80;
295
+ if (openDrain) v |= 0x40;
296
+ if (enabled) v |= 0x04;
297
+ await this._writeReg(_REG_CTRL_REG3, v);
298
+ }
299
+
300
+ /**
301
+ * Subscribe to data-ready events. Enables DRDY (active high, push-pull) and uses the connection's
302
+ * `intPin` (rising edge); without a pin a polling timer calls `pollInterrupt()` at the output data rate.
303
+ * @param {function(number): void} callback - Called with the STATUS_REG value.
304
+ * @param {object} [intPin] - Optional InputPin wired to DRDY (default: the connection's `intPin`).
305
+ */
306
+ async onInterrupt(callback, intPin = null) {
307
+ await this.offInterrupt();
308
+ await this.configureDrdy(true);
309
+ this._intCallback = callback;
310
+ const pin = intPin || (this._conn ? this._conn.intPin : null);
311
+ if (pin) {
312
+ this._intPin = pin;
313
+ this._intHandler = () => { this._dispatchInt(); };
314
+ await pin.onEdge(this._intHandler, 'rising');
315
+ } else {
316
+ await this._startPollingFallback();
317
+ }
318
+ }
319
+
320
+ /** Unsubscribe from data-ready events and disable the DRDY output. */
321
+ async offInterrupt() {
322
+ const had = this._intCallback !== null || this._pollTimer !== null;
323
+ this._intCallback = null;
324
+ if (this._intPin && this._intHandler) {
325
+ await this._intPin.offEdge(this._intHandler);
326
+ }
327
+ this._intPin = null;
328
+ this._intHandler = null;
329
+ if (this._pollTimer !== null) {
330
+ clearTimeout(this._pollTimer);
331
+ this._pollTimer = null;
332
+ }
333
+ if (had) await this.configureDrdy(false);
334
+ }
335
+
336
+ /** @returns {Promise<number>} STATUS_REG; the flags clear when the output registers are read. */
337
+ async pollInterrupt() {
338
+ return this.status();
339
+ }
340
+
341
+ async _dispatchInt() {
342
+ const callback = this._intCallback;
343
+ if (!callback) return;
344
+ try {
345
+ callback(await this.pollInterrupt());
346
+ } catch (e) {
347
+ // A failing bus read must not kill the event loop.
348
+ }
349
+ }
350
+
351
+ async _startPollingFallback() {
352
+ const tick = async () => {
353
+ if (this._intCallback === null) return;
354
+ try {
355
+ if (await this.dataReady()) await this._dispatchInt();
356
+ const hz = await this.getOutputDataRate();
357
+ this._pollTimer = setTimeout(tick, hz > 0 ? Math.floor(1000 / hz) : 100);
358
+ } catch (e) {
359
+ this._pollTimer = setTimeout(tick, 100);
360
+ }
361
+ };
362
+ this._pollTimer = setTimeout(tick, 0);
363
+ }
364
+ }
365
+
366
+ /** Default 7-bit I²C address (fixed, no address pins). */
367
+ HTS221Minimal.I2C_ADDRESS = 0x5F;
368
+
369
+ module.exports = { HTS221Minimal, HTS221Full };
@@ -0,0 +1,242 @@
1
+ 'use strict';
2
+
3
+ const _CMD_RESET = 0x1E;
4
+ const _CMD_HEATER_ON = 0x04;
5
+ const _CMD_HEATER_OFF = 0x02;
6
+ const _CMD_CONVERT = 0x40;
7
+ const _CMD_READ_TRH = 0x00;
8
+ const _CMD_READ_RH = 0x10;
9
+ const _CMD_READ_DIAG = 0x08;
10
+ const _CMD_READ_SERIAL = 0x0A;
11
+
12
+ // typical conversion times in seconds, indexed by OSR 0..3
13
+ const _T_RH = [0.00111, 0.00214, 0.00421, 0.00834];
14
+ const _T_T = [0.00157, 0.00306, 0.00603, 0.01198];
15
+
16
+ const _DIAG_FLAGS = [
17
+ [7, 'nvm_err'], [6, 'rh_overrun'], [5, 'rh_high_err'], [4, 'rh_low_err'],
18
+ [3, 't_overrun'], [2, 't_high_err'], [1, 't_low_err'], [0, 'heater_on'],
19
+ ];
20
+
21
+ const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
22
+
23
+ /**
24
+ * CRC-8 used by the HTU31D: polynomial 0x31 (x^8 + x^5 + x^4 + 1), init 0x00, no final XOR.
25
+ * @param {Buffer|number[]} data
26
+ * @returns {number}
27
+ */
28
+ function crc8(data) {
29
+ let crc = 0x00;
30
+ for (const byte of data) {
31
+ crc ^= byte;
32
+ for (let i = 0; i < 8; i++) crc = (crc & 0x80) ? ((crc << 1) ^ 0x31) & 0xFF : (crc << 1) & 0xFF;
33
+ }
34
+ return crc;
35
+ }
36
+
37
+ function _toHumidity(code) {
38
+ return Math.min(100.0, Math.max(0.0, 100.0 * code / 65535.0));
39
+ }
40
+
41
+ function _toTemperature(code) {
42
+ return -40.0 + 165.0 * code / 65535.0;
43
+ }
44
+
45
+ /**
46
+ * HTU31D humidity and temperature sensor — minimal interface.
47
+ *
48
+ * Each `read()` starts one conversion at the highest resolution (command 0x5E, OSR 3 for
49
+ * humidity and temperature), waits 25 ms, reads the temperature and humidity words
50
+ * (command 0x00) and verifies both CRC-8 bytes. Humidity is clamped to 0-100 %RH.
51
+ *
52
+ * The device is command driven (no register pointer), so a plain I²C connection is used.
53
+ * The constructor does not touch the bus; `init()` performs the soft reset.
54
+ */
55
+ class HTU31DMinimal {
56
+ /**
57
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C connection pointing at the device (address 0x40 or 0x41).
58
+ */
59
+ constructor(connection) {
60
+ this._conn = connection;
61
+ this._osrRh = 3;
62
+ this._osrT = 3;
63
+ }
64
+
65
+ /** Soft reset (0x1E) and wait 15 ms; heater off, highest resolution. */
66
+ async init() {
67
+ await this._conn.write(Buffer.from([_CMD_RESET]));
68
+ await _sleep(15);
69
+ }
70
+
71
+ _waitMs() {
72
+ if (this._osrRh === 3 && this._osrT === 3) return 25;
73
+ return 1.25 * (_T_RH[this._osrRh] + _T_T[this._osrT]) * 1000.0;
74
+ }
75
+
76
+ async _start() {
77
+ await this._conn.write(Buffer.from([_CMD_CONVERT | (this._osrRh << 3) | (this._osrT << 1)]));
78
+ }
79
+
80
+ async _readWords(command, count) {
81
+ await this._conn.write(Buffer.from([command]));
82
+ const data = Buffer.from(await this._conn.read(3 * count));
83
+ const words = [];
84
+ for (let i = 0; i < count; i++) {
85
+ const chunk = data.subarray(3 * i, 3 * i + 3);
86
+ if (crc8(chunk.subarray(0, 2)) !== chunk[2]) throw new Error('HTU31D CRC mismatch');
87
+ words.push((chunk[0] << 8) | chunk[1]);
88
+ }
89
+ return words;
90
+ }
91
+
92
+ async _measure(command, count) {
93
+ await this._start();
94
+ await _sleep(this._waitMs());
95
+ return this._readWords(command, count);
96
+ }
97
+
98
+ /**
99
+ * Measure temperature and humidity.
100
+ * @returns {Promise<{temperature_c: number, humidity_pct: number}>} °C and %RH (0-100)
101
+ */
102
+ async read() {
103
+ const [t, rh] = await this._measure(_CMD_READ_TRH, 2);
104
+ return { temperature_c: _toTemperature(t), humidity_pct: _toHumidity(rh) };
105
+ }
106
+ }
107
+
108
+ /**
109
+ * HTU31D full interface — oversampling, non-blocking conversion, heater, diagnostics, dew point.
110
+ *
111
+ * Extends HTU31DMinimal with single values, raw codes, separate oversampling settings for
112
+ * humidity and temperature, the on-chip heater, the diagnostic byte, the serial number,
113
+ * soft reset and the dew point.
114
+ */
115
+ class HTU31DFull extends HTU31DMinimal {
116
+ /**
117
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C connection pointing at the device (address 0x40 or 0x41).
118
+ */
119
+ constructor(connection) {
120
+ super(connection);
121
+ }
122
+
123
+ /**
124
+ * Run one humidity measurement (command 0x10 after the conversion).
125
+ * @returns {Promise<number>} Relative humidity in %RH, clamped to 0-100.
126
+ */
127
+ async readHumidity() {
128
+ return _toHumidity((await this._measure(_CMD_READ_RH, 1))[0]);
129
+ }
130
+
131
+ /**
132
+ * Run one temperature measurement (the read stops after the temperature word).
133
+ * @returns {Promise<number>} Temperature in °C.
134
+ */
135
+ async readTemperature() {
136
+ return _toTemperature((await this._measure(_CMD_READ_TRH, 1))[0]);
137
+ }
138
+
139
+ /**
140
+ * Measure temperature and humidity and return the raw codes.
141
+ * @returns {Promise<[number, number]>} [t_raw, rh_raw], both 16-bit unsigned.
142
+ */
143
+ async readRaw() {
144
+ return this._measure(_CMD_READ_TRH, 2);
145
+ }
146
+
147
+ /**
148
+ * Select the oversampling of the following measurements.
149
+ * @param {number} osrRh - Humidity oversampling 0-3.
150
+ * @param {number} osrT - Temperature oversampling 0-3.
151
+ * @throws {RangeError} If either value is not 0-3.
152
+ */
153
+ setResolution(osrRh, osrT) {
154
+ if (![0, 1, 2, 3].includes(osrRh) || ![0, 1, 2, 3].includes(osrT)) throw new RangeError('osr must be 0-3');
155
+ this._osrRh = osrRh;
156
+ this._osrT = osrT;
157
+ }
158
+
159
+ /** @returns {[number, number]} [osrRh, osrT] */
160
+ getResolution() {
161
+ return [this._osrRh, this._osrT];
162
+ }
163
+
164
+ /** @returns {number} Typical conversion time of one measurement at the current oversampling, in seconds. */
165
+ conversionTime() {
166
+ return _T_RH[this._osrRh] + _T_T[this._osrT];
167
+ }
168
+
169
+ /** Write the conversion command only (non-blocking use); wait `conversionTime()` plus margin before `readResult()`. */
170
+ async startConversion() {
171
+ await this._start();
172
+ }
173
+
174
+ /**
175
+ * Read the result of the last conversion (command 0x00).
176
+ * @returns {Promise<{temperature_c: number, humidity_pct: number}>}
177
+ */
178
+ async readResult() {
179
+ const [t, rh] = await this._readWords(_CMD_READ_TRH, 2);
180
+ return { temperature_c: _toTemperature(t), humidity_pct: _toHumidity(rh) };
181
+ }
182
+
183
+ /**
184
+ * Switch the on-chip heater on (0x04) or off (0x02).
185
+ * @param {boolean} on
186
+ */
187
+ async setHeater(on) {
188
+ await this._conn.write(Buffer.from([on ? _CMD_HEATER_ON : _CMD_HEATER_OFF]));
189
+ }
190
+
191
+ /** @returns {Promise<boolean>} True if the diagnostic byte reports the heater on. */
192
+ async isHeaterOn() {
193
+ return ((await this.diagnostic()) & 0x01) !== 0;
194
+ }
195
+
196
+ /** @returns {Promise<number>} The diagnostic byte (command 0x08). */
197
+ async diagnostic() {
198
+ await this._conn.write(Buffer.from([_CMD_READ_DIAG]));
199
+ return Buffer.from(await this._conn.read(1))[0];
200
+ }
201
+
202
+ /** @returns {Promise<Object>} Named boolean diagnostic flags (nvm_err, rh_overrun, rh_high_err, rh_low_err, t_overrun, t_high_err, t_low_err, heater_on). */
203
+ async diagnosticFlags() {
204
+ const value = await this.diagnostic();
205
+ const flags = {};
206
+ for (const [bit, name] of _DIAG_FLAGS) flags[name] = ((value >> bit) & 1) === 1;
207
+ return flags;
208
+ }
209
+
210
+ /**
211
+ * Read the 24-bit serial number (command 0x0A, CRC verified).
212
+ * @returns {Promise<number>}
213
+ */
214
+ async serialNumber() {
215
+ await this._conn.write(Buffer.from([_CMD_READ_SERIAL]));
216
+ const data = Buffer.from(await this._conn.read(4));
217
+ if (crc8(data.subarray(0, 3)) !== data[3]) throw new Error('HTU31D CRC mismatch');
218
+ return (data[0] << 16) | (data[1] << 8) | data[2];
219
+ }
220
+
221
+ /** Soft reset (0x1E) and wait 15 ms; heater off, oversampling back to OSR 3 / 3. */
222
+ async softReset() {
223
+ await this._conn.write(Buffer.from([_CMD_RESET]));
224
+ await _sleep(15);
225
+ this._osrRh = 3;
226
+ this._osrT = 3;
227
+ }
228
+
229
+ /**
230
+ * Run one measurement and compute the dew point (Magnus formula over water).
231
+ * @returns {Promise<number>} Dew point in °C.
232
+ */
233
+ async dewPoint() {
234
+ const m = await this.read();
235
+ const t = m.temperature_c;
236
+ const rh = m.humidity_pct <= 0.0 ? 0.01 : m.humidity_pct;
237
+ const g = Math.log(rh / 100.0) + 17.62 * t / (243.12 + t);
238
+ return 243.12 * g / (17.62 - g);
239
+ }
240
+ }
241
+
242
+ module.exports = { HTU31DMinimal, HTU31DFull, crc8 };