periph 1.5.4 → 1.6.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.
@@ -0,0 +1,534 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * RRH46410 digital gas sensor module for indoor air quality (Renesas).
5
+ *
6
+ * The host sends a request `[command, params…, checksum]` in one I²C write and reads the
7
+ * response `[status, params…, checksum]` in a separate read; `checksum = ~(sum of the other
8
+ * bytes) & 0xFF`. The module stretches the I²C clock (address 0x38).
9
+ */
10
+
11
+ const CMD_GET_PRODUCT_ID = 0x00;
12
+ const CMD_GET_TRACKING_NUMBER = 0x01;
13
+ const CMD_GET_OPERATION_MODE = 0x10;
14
+ const CMD_SET_OPERATION_MODE = 0x11;
15
+ const CMD_SET_HUMIDITY = 0x12;
16
+ const CMD_GET_MEASUREMENT_RESULTS = 0x18;
17
+ const CMD_CONFIG_GPIO = 0x20;
18
+ const CMD_GET_GPIO = 0x21;
19
+ const CMD_SET_GPIO = 0x22;
20
+ const CMD_CLEAR_GPIO = 0x23;
21
+ const CMD_RESET = 0x8F;
22
+
23
+ const MODE_SUSPEND = 0x00;
24
+ const MODE_IAQ_2ND_GEN = 0x01;
25
+ const MODE_ULP = 0x02;
26
+ const MODE_PBAQ = 0x05;
27
+ const MODE_CLEANING = 0x80;
28
+
29
+ const STATUS_NOT_COMPLETE = 0x10;
30
+ const PRODUCT_ID = 0x2310;
31
+
32
+ const _INIT_TIMEOUT_MS = 1000;
33
+ const _POLL_MS = 200;
34
+ const _CLEAN_TIMEOUT_MS = 90000;
35
+
36
+ const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
37
+
38
+ function _checksum(bytes) {
39
+ let sum = 0;
40
+ for (const b of bytes) sum += b;
41
+ return (~sum) & 0xFF;
42
+ }
43
+
44
+ function _period(mode) {
45
+ if (mode === MODE_IAQ_2ND_GEN) return 3.0;
46
+ if (mode === MODE_ULP) return 90.0;
47
+ if (mode === MODE_PBAQ) return 5.0;
48
+ return 0.0;
49
+ }
50
+
51
+ function _warmup(mode) {
52
+ if (mode === MODE_IAQ_2ND_GEN) return 100;
53
+ if (mode === MODE_ULP) return 10;
54
+ if (mode === MODE_PBAQ) return 60;
55
+ return 0;
56
+ }
57
+
58
+ /**
59
+ * RRH46410 protocol or status error.
60
+ * @property {number|null} status - Status byte of the failing response, or null for a
61
+ * checksum / timeout / identity error.
62
+ */
63
+ class RRH46410Error extends Error {
64
+ constructor(message, status = null) {
65
+ super(message);
66
+ this.name = 'RRH46410Error';
67
+ this.status = status;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * RRH46410 indoor air quality sensor (Renesas) — minimal interface.
73
+ *
74
+ * One call returns the IAQ index, TVOC, ethanol equivalent, estimated CO₂ and relative IAQ of
75
+ * the IAQ 2nd Gen algorithm. `init()` retries Get Product ID for up to 1 s, verifies 0x2310
76
+ * and selects the IAQ 2nd Gen mode (one sample every 3 s; the first 100 samples, about
77
+ * 5 minutes, are the warm-up). The module's default humidity (50 %RH) is kept; GPIOs are
78
+ * unused. The constructor does not touch the bus.
79
+ *
80
+ * @param {import('../../connection/base').Connection} connection - Plain I²C connection bound to 0x38.
81
+ */
82
+ class RRH46410Minimal {
83
+ constructor(connection) {
84
+ this._conn = connection;
85
+ this._mode = MODE_SUSPEND;
86
+ this._lastStatus = 0;
87
+ this._lastCounter = null;
88
+ this._samples = 0;
89
+ this._lastResult = null;
90
+ this._busy = Promise.resolve();
91
+ }
92
+
93
+ /**
94
+ * Wait for the module, verify the product ID and start IAQ 2nd Gen mode.
95
+ * @returns {Promise<void>}
96
+ * @throws {RRH46410Error} If the module does not answer within 1 s or the product ID is not 0x2310.
97
+ */
98
+ async init() {
99
+ await this._waitProductId();
100
+ await this._setMode(MODE_IAQ_2ND_GEN);
101
+ }
102
+
103
+ /**
104
+ * Wait for the next sample and return it.
105
+ * @returns {Promise<{iaq: number, tvoc_mg_m3: number, etoh_ppm: number, eco2_ppm: number,
106
+ * relative_iaq: number, sample: number, warmed_up: boolean}>} IAQ index (UBA level
107
+ * 1.0–5.0), TVOC in mg/m³, ethanol equivalent in ppm, estimated CO₂ in ppm, relative IAQ,
108
+ * the sample counter (0–255) and whether the warm-up is over.
109
+ * @throws {RRH46410Error} If no new sample arrives within the sample period plus 2 s, or the
110
+ * module reports an error.
111
+ */
112
+ async read() {
113
+ if (!(await this._waitSample(_period(this._mode) + 2.0))) throw new RRH46410Error('RRH46410 sample timeout');
114
+ return this._lastResult;
115
+ }
116
+
117
+ // --- protocol ----------------------------------------------------------
118
+
119
+ async _transact(command, params = [], responseLen = 0, check = true) {
120
+ const req = [command, ...params];
121
+ req.push(_checksum(req));
122
+ // Serialize request/response pairs (the interrupt poller shares the bus).
123
+ const run = this._busy.then(async () => {
124
+ await this._conn.write(Buffer.from(req));
125
+ return Buffer.from(await this._conn.read(responseLen + 2));
126
+ });
127
+ this._busy = run.catch(() => {});
128
+ const resp = await run;
129
+ let sum = 0;
130
+ for (const b of resp) sum += b;
131
+ if ((sum & 0xFF) !== 0xFF) throw new RRH46410Error(`RRH46410 response checksum error (command 0x${command.toString(16)})`);
132
+ const status = resp[0];
133
+ this._lastStatus = status;
134
+ if (check && status) throw new RRH46410Error(`RRH46410 status 0x${status.toString(16)} (command 0x${command.toString(16)})`, status);
135
+ return { status, data: resp.subarray(1, 1 + responseLen) };
136
+ }
137
+
138
+ async _waitProductId() {
139
+ const deadline = Date.now() + _INIT_TIMEOUT_MS;
140
+ let data;
141
+ for (;;) {
142
+ try {
143
+ data = (await this._transact(CMD_GET_PRODUCT_ID, [], 5)).data;
144
+ break;
145
+ } catch (e) {
146
+ if (Date.now() > deadline) throw new RRH46410Error('RRH46410 not responding');
147
+ await _sleep(50);
148
+ }
149
+ }
150
+ const pid = (data[0] << 8) | data[1];
151
+ if (pid !== PRODUCT_ID) throw new RRH46410Error(`Unexpected RRH46410 product ID 0x${pid.toString(16)}, expected 0x2310`);
152
+ return data;
153
+ }
154
+
155
+ async _setMode(mode) {
156
+ await this._transact(CMD_SET_OPERATION_MODE, [mode]);
157
+ this._mode = mode;
158
+ this._lastCounter = null;
159
+ this._samples = 0;
160
+ }
161
+
162
+ /** Read the raw result; returns the parameter bytes or null before the first sample. */
163
+ async _fetch() {
164
+ const n = this._mode === MODE_PBAQ ? 5 : 9;
165
+ const { status, data } = await this._transact(CMD_GET_MEASUREMENT_RESULTS, [], n, false);
166
+ if (status === STATUS_NOT_COMPLETE) return null;
167
+ if (status) throw new RRH46410Error(`RRH46410 status 0x${status.toString(16)} (command 0x18)`, status);
168
+ return data;
169
+ }
170
+
171
+ _decode(d) {
172
+ const counter = d[0];
173
+ if (this._lastCounter === null) this._samples = counter;
174
+ else this._samples += (counter - this._lastCounter) & 0xFF;
175
+ this._lastCounter = counter;
176
+ const warmed_up = this._samples >= _warmup(this._mode);
177
+ if (this._mode === MODE_PBAQ) {
178
+ return {
179
+ tvoc_mg_m3: ((d[1] << 8) | d[2]) / 1000,
180
+ etoh_ppm: ((d[3] << 8) | d[4]) / 1000,
181
+ sample: counter,
182
+ warmed_up,
183
+ };
184
+ }
185
+ return {
186
+ iaq: d[1] / 10,
187
+ tvoc_mg_m3: ((d[2] << 8) | d[3]) / 100,
188
+ etoh_ppm: ((d[4] << 8) | d[5]) / 100,
189
+ eco2_ppm: (d[6] << 8) | d[7],
190
+ relative_iaq: d[8] * 10,
191
+ sample: counter,
192
+ warmed_up,
193
+ };
194
+ }
195
+
196
+ /** Poll until the sample counter changes; stores the decoded result. Timeout in s. */
197
+ async _waitSample(timeout) {
198
+ const deadline = Date.now() + timeout * 1000;
199
+ const pin = this._conn.intPin ?? null;
200
+ const last = this._lastCounter;
201
+ for (;;) {
202
+ if (!pin || pin.isHigh()) {
203
+ const data = await this._fetch();
204
+ if (data && (last === null || data[0] !== last)) {
205
+ this._lastResult = this._decode(data);
206
+ return true;
207
+ }
208
+ }
209
+ if (Date.now() > deadline) return false;
210
+ await _sleep(this._pollMs ?? _POLL_MS);
211
+ }
212
+ }
213
+ }
214
+
215
+ /**
216
+ * RRH46410 — full interface. Extends RRH46410Minimal with identity, operation modes (IAQ 2nd
217
+ * Gen, ULP, PBAQ, cleaning), humidity compensation, GPIOs, status, reset, raw commands and the
218
+ * INT interrupt. INT is active high, push-pull: high when a new result is available, low after
219
+ * Get Measurement Results or Set Operation Mode.
220
+ *
221
+ * @param {import('../../connection/base').Connection} connection - Plain I²C connection bound to 0x38.
222
+ */
223
+ class RRH46410Full extends RRH46410Minimal {
224
+ constructor(connection) {
225
+ super(connection);
226
+ this._callback = null;
227
+ this._intPinUsed = null;
228
+ this._pollTimer = null;
229
+ this._polling = false;
230
+ this._edgeHandler = () => { this._service(); };
231
+ }
232
+
233
+ /**
234
+ * Read the product ID and firmware version.
235
+ * @returns {Promise<{productId: number, firmware: number[]}>} Product ID 0x2310 and
236
+ * `[major, minor, patch]`.
237
+ */
238
+ async productId() {
239
+ const d = (await this._transact(CMD_GET_PRODUCT_ID, [], 5)).data;
240
+ return { productId: (d[0] << 8) | d[1], firmware: [d[2], d[3], d[4]] };
241
+ }
242
+
243
+ /**
244
+ * Read the ASIC tracking number.
245
+ * @returns {Promise<Buffer>} 6 bytes.
246
+ */
247
+ async trackingNumber() {
248
+ return Buffer.from((await this._transact(CMD_GET_TRACKING_NUMBER, [], 6)).data);
249
+ }
250
+
251
+ /**
252
+ * Read the current operation mode.
253
+ * @returns {Promise<number>} One of the MODE_* constants (other values behave as SUSPEND).
254
+ */
255
+ async getMode() {
256
+ const mode = (await this._transact(CMD_GET_OPERATION_MODE, [], 1)).data[0];
257
+ this._mode = mode;
258
+ return mode;
259
+ }
260
+
261
+ /**
262
+ * Change the operation mode. Stops a running measurement, restarts the warm-up and sets INT
263
+ * low. Use `cleanSensor` for the cleaning mode.
264
+ * @param {number} mode - MODE_SUSPEND, MODE_IAQ_2ND_GEN, MODE_ULP or MODE_PBAQ.
265
+ * @returns {Promise<void>}
266
+ * @throws {RangeError} If mode is not one of these.
267
+ */
268
+ async setMode(mode) {
269
+ if (![MODE_SUSPEND, MODE_IAQ_2ND_GEN, MODE_ULP, MODE_PBAQ].includes(mode)) {
270
+ throw new RangeError('mode must be MODE_SUSPEND, MODE_IAQ_2ND_GEN, MODE_ULP or MODE_PBAQ');
271
+ }
272
+ await this._setMode(mode);
273
+ }
274
+
275
+ /**
276
+ * Stop measuring (operation mode SUSPEND, about 0.7 µA).
277
+ * @returns {Promise<void>}
278
+ */
279
+ async suspend() {
280
+ await this._setMode(MODE_SUSPEND);
281
+ }
282
+
283
+ /**
284
+ * Read and decode the latest result without waiting.
285
+ * @returns {Promise<object|null>} The decoded result for the current mode (PBAQ has only
286
+ * `tvoc_mg_m3`, `etoh_ppm`, `sample` and `warmed_up`), or null before the first sample.
287
+ */
288
+ async readResults() {
289
+ const data = await this._fetch();
290
+ if (!data) return null;
291
+ this._lastResult = this._decode(data);
292
+ return this._lastResult;
293
+ }
294
+
295
+ /**
296
+ * Wait until the sample counter changes (or INT goes high).
297
+ * @param {number} timeout - Maximum wait in s.
298
+ * @returns {Promise<boolean>} True when a new sample arrived.
299
+ */
300
+ async waitForSample(timeout) {
301
+ return this._waitSample(timeout);
302
+ }
303
+
304
+ /**
305
+ * Supply the ambient relative humidity for compensation; sent as round(percent / 100 × 255).
306
+ * @param {number} percent - Relative humidity in % (0–100).
307
+ * @returns {Promise<void>}
308
+ * @throws {RangeError} If percent is not 0–100.
309
+ */
310
+ async setHumidity(percent) {
311
+ if (!(percent >= 0 && percent <= 100)) throw new RangeError('percent must be 0..100');
312
+ await this._transact(CMD_SET_HUMIDITY, [Math.round(percent / 100 * 255)]);
313
+ }
314
+
315
+ /**
316
+ * Sample period of a mode.
317
+ * @param {number|null} [mode=null] - Operation mode, or null for the current mode.
318
+ * @returns {number} Seconds: 3 (IAQ 2nd Gen), 90 (ULP), 5 (PBAQ), 0 otherwise.
319
+ */
320
+ samplePeriod(mode = null) {
321
+ return _period(mode === null ? this._mode : mode);
322
+ }
323
+
324
+ /**
325
+ * Number of warm-up samples of a mode.
326
+ * @param {number|null} [mode=null] - Operation mode, or null for the current mode.
327
+ * @returns {number} 100 (IAQ 2nd Gen), 10 (ULP), 60 (PBAQ), 0 otherwise.
328
+ */
329
+ warmupSamples(mode = null) {
330
+ return _warmup(mode === null ? this._mode : mode);
331
+ }
332
+
333
+ /**
334
+ * UBA rating text for an IAQ index.
335
+ * @param {number} iaq - IAQ index (1.0–5.0).
336
+ * @returns {string} "very good" (< 2.0), "good", "medium", "poor" or "bad" (≥ 5.0).
337
+ */
338
+ static airQualityLabel(iaq) {
339
+ if (iaq < 2.0) return 'very good';
340
+ if (iaq < 3.0) return 'good';
341
+ if (iaq < 4.0) return 'medium';
342
+ if (iaq < 5.0) return 'poor';
343
+ return 'bad';
344
+ }
345
+
346
+ /** Instance alias of {@link RRH46410Full.airQualityLabel}. */
347
+ airQualityLabel(iaq) {
348
+ return RRH46410Full.airQualityLabel(iaq);
349
+ }
350
+
351
+ /**
352
+ * Run the one-time 1-minute sensor cleaning and wait for it to finish (up to 90 s). Execute
353
+ * it at most once in the sensor's lifetime and do not interrupt it.
354
+ * @param {boolean} [confirm=false] - Must be true; guards against accidental use.
355
+ * @returns {Promise<void>}
356
+ * @throws {Error} If confirm is not true or the module does not return to SUSPEND.
357
+ */
358
+ async cleanSensor(confirm = false) {
359
+ if (confirm !== true) throw new Error('cleanSensor runs once per sensor lifetime; pass confirm=true');
360
+ await this._setMode(MODE_CLEANING);
361
+ const deadline = Date.now() + _CLEAN_TIMEOUT_MS;
362
+ while ((await this.getMode()) === MODE_CLEANING) {
363
+ if (Date.now() > deadline) throw new RRH46410Error('RRH46410 cleaning did not finish');
364
+ await _sleep(1000);
365
+ }
366
+ this._mode = MODE_SUSPEND;
367
+ }
368
+
369
+ static _mask(value) {
370
+ if (!(value >= 0 && value <= 3)) throw new RangeError('GPIO mask must be 0..3');
371
+ return value;
372
+ }
373
+
374
+ /**
375
+ * Configure GPIO1/GPIO2 as outputs.
376
+ * @param {number} directions - Bit 0 = GPIO1 output, bit 1 = GPIO2 output (0–3).
377
+ * @returns {Promise<void>}
378
+ */
379
+ async configGpio(directions) {
380
+ await this._transact(CMD_CONFIG_GPIO, [RRH46410Full._mask(directions)]);
381
+ }
382
+
383
+ /**
384
+ * Read the GPIO levels.
385
+ * @returns {Promise<number>} Bits 0–3 = GPIO1–GPIO4.
386
+ */
387
+ async getGpio() {
388
+ return (await this._transact(CMD_GET_GPIO, [], 1)).data[0];
389
+ }
390
+
391
+ /**
392
+ * Drive GPIO outputs high.
393
+ * @param {number} mask - Bit 0 = GPIO1, bit 1 = GPIO2 (0–3).
394
+ * @returns {Promise<void>}
395
+ */
396
+ async setGpio(mask) {
397
+ await this._transact(CMD_SET_GPIO, [RRH46410Full._mask(mask)]);
398
+ }
399
+
400
+ /**
401
+ * Drive GPIO outputs low.
402
+ * @param {number} mask - Bit 0 = GPIO1, bit 1 = GPIO2 (0–3).
403
+ * @returns {Promise<void>}
404
+ */
405
+ async clearGpio(mask) {
406
+ await this._transact(CMD_CLEAR_GPIO, [RRH46410Full._mask(mask)]);
407
+ }
408
+
409
+ /**
410
+ * Decode the status byte of the last response.
411
+ * @returns {{raw: number, invalid_command: boolean, checksum_error: boolean,
412
+ * sensor_nack: boolean, not_complete: boolean, mode_error: number}} `mode_error` is the
413
+ * bits 3:0 code (0 OK, 0xA sensor damaged).
414
+ */
415
+ status() {
416
+ const s = this._lastStatus;
417
+ return {
418
+ raw: s,
419
+ invalid_command: !!(s & 0x80),
420
+ checksum_error: !!(s & 0x40),
421
+ sensor_nack: !!(s & 0x20),
422
+ not_complete: !!(s & 0x10),
423
+ mode_error: s & 0x0F,
424
+ };
425
+ }
426
+
427
+ /**
428
+ * Reset the module, wait 500 ms and verify the product ID again; it restarts in SUSPEND.
429
+ * @returns {Promise<void>}
430
+ */
431
+ async reset() {
432
+ try {
433
+ await this._conn.write(Buffer.from([CMD_RESET, _checksum([CMD_RESET])]));
434
+ } catch (e) {
435
+ /* the module may not acknowledge while resetting */
436
+ }
437
+ await _sleep(500);
438
+ await this._waitProductId();
439
+ this._mode = MODE_SUSPEND;
440
+ this._lastCounter = null;
441
+ this._samples = 0;
442
+ }
443
+
444
+ /**
445
+ * Send a raw request; checksums are added and verified, the status byte is available from
446
+ * `status()`. Reset (0x8F) has no response.
447
+ * @param {number} command - Command byte.
448
+ * @param {number[]|Buffer} [params=[]] - Request parameter bytes.
449
+ * @param {number} [responseLen=0] - Number of response parameter bytes.
450
+ * @returns {Promise<Buffer>} The response parameters (empty for Reset).
451
+ */
452
+ async sendCommand(command, params = [], responseLen = 0) {
453
+ const p = [...params];
454
+ if (command === CMD_RESET) {
455
+ const req = [command, ...p];
456
+ await this._conn.write(Buffer.from([...req, _checksum(req)]));
457
+ return Buffer.alloc(0);
458
+ }
459
+ return Buffer.from((await this._transact(command, p, responseLen, false)).data);
460
+ }
461
+
462
+ /**
463
+ * Check for a new sample without consuming it.
464
+ * @returns {Promise<boolean>} True if the INT pin is high (pin available), otherwise if the
465
+ * sample counter changed since the last decoded result.
466
+ */
467
+ async pollInterrupt() {
468
+ const pin = this._conn.intPin ?? null;
469
+ if (pin) return !!pin.isHigh();
470
+ const data = await this._fetch();
471
+ return data !== null && data[0] !== this._lastCounter;
472
+ }
473
+
474
+ /**
475
+ * Call `callback(result)` for every new sample. Uses `intPin` (or the connection's `intPin`)
476
+ * on its rising edge, otherwise a 200 ms poll comparing the sample counter. The driver reads
477
+ * the result (which sets INT low) and passes the decoded object.
478
+ * @param {function(object): void} callback - Called with the decoded result.
479
+ * @param {object|null} [intPin=null] - Optional InputPin wired to INT.
480
+ * @returns {Promise<void>}
481
+ */
482
+ async onInterrupt(callback, intPin = null) {
483
+ await this.offInterrupt();
484
+ this._callback = callback;
485
+ const ipin = intPin ?? this._conn.intPin ?? null;
486
+ if (ipin) {
487
+ this._intPinUsed = ipin;
488
+ await ipin.onEdge(this._edgeHandler, 'rising');
489
+ } else {
490
+ this._pollTimer = setInterval(() => { this._service(); }, this._pollMs ?? _POLL_MS);
491
+ if (this._pollTimer.unref) this._pollTimer.unref();
492
+ }
493
+ }
494
+
495
+ /**
496
+ * Unsubscribe from the interrupt.
497
+ * @returns {Promise<void>}
498
+ */
499
+ async offInterrupt() {
500
+ if (this._intPinUsed) {
501
+ await this._intPinUsed.offEdge(this._edgeHandler);
502
+ this._intPinUsed = null;
503
+ }
504
+ if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
505
+ this._callback = null;
506
+ }
507
+
508
+ async _service() {
509
+ if (this._polling || !this._callback) return;
510
+ this._polling = true;
511
+ try {
512
+ const data = await this._fetch();
513
+ if (data && data[0] !== this._lastCounter && this._callback) {
514
+ this._lastResult = this._decode(data);
515
+ this._callback(this._lastResult);
516
+ }
517
+ } catch (e) {
518
+ /* a failed poll is retried on the next tick */
519
+ } finally {
520
+ this._polling = false;
521
+ }
522
+ }
523
+ }
524
+
525
+ for (const cls of [RRH46410Minimal, RRH46410Full]) {
526
+ cls.MODE_SUSPEND = MODE_SUSPEND;
527
+ cls.MODE_IAQ_2ND_GEN = MODE_IAQ_2ND_GEN;
528
+ cls.MODE_ULP = MODE_ULP;
529
+ cls.MODE_PBAQ = MODE_PBAQ;
530
+ cls.MODE_CLEANING = MODE_CLEANING;
531
+ cls.PRODUCT_ID = PRODUCT_ID;
532
+ }
533
+
534
+ module.exports = { RRH46410Minimal, RRH46410Full, RRH46410Error };