periph 1.5.3 → 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.
Files changed (79) hide show
  1. package/README.md +18 -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/gas/ccs811/complete.js +87 -0
  9. package/examples/gas/ccs811/demo.js +108 -0
  10. package/examples/gas/ccs811/minimal.js +20 -0
  11. package/examples/gas/rrh46410/complete.js +78 -0
  12. package/examples/gas/rrh46410/demo.js +86 -0
  13. package/examples/gas/rrh46410/minimal.js +21 -0
  14. package/examples/humidity/hts221/complete.js +83 -0
  15. package/examples/humidity/hts221/demo.js +94 -0
  16. package/examples/humidity/hts221/minimal.js +22 -0
  17. package/examples/humidity/htu31d/complete.js +50 -0
  18. package/examples/humidity/htu31d/demo.js +65 -0
  19. package/examples/humidity/htu31d/minimal.js +22 -0
  20. package/examples/humidity/shtc3/complete.js +48 -0
  21. package/examples/humidity/shtc3/demo.js +45 -0
  22. package/examples/humidity/shtc3/minimal.js +22 -0
  23. package/examples/led/saa1064/complete.js +51 -0
  24. package/examples/led/saa1064/demo.js +54 -0
  25. package/examples/led/saa1064/minimal.js +23 -0
  26. package/examples/light/apds9250/complete.js +71 -0
  27. package/examples/light/apds9250/demo.js +79 -0
  28. package/examples/light/apds9250/minimal.js +23 -0
  29. package/examples/light/bh1750/complete.js +46 -0
  30. package/examples/light/bh1750/demo.js +52 -0
  31. package/examples/light/bh1750/minimal.js +22 -0
  32. package/examples/light/si1132/complete.js +70 -0
  33. package/examples/light/si1132/demo.js +73 -0
  34. package/examples/light/si1132/minimal.js +22 -0
  35. package/examples/light/si1133/complete.js +89 -0
  36. package/examples/light/si1133/demo.js +93 -0
  37. package/examples/light/si1133/minimal.js +22 -0
  38. package/examples/light/si1145/complete.js +93 -0
  39. package/examples/light/si1145/demo.js +98 -0
  40. package/examples/light/si1145/minimal.js +22 -0
  41. package/examples/pressure/mpl3115a2/complete.js +49 -0
  42. package/examples/pressure/mpl3115a2/demo.js +48 -0
  43. package/examples/pressure/mpl3115a2/minimal.js +22 -0
  44. package/examples/pressure/ms5607/complete.js +49 -0
  45. package/examples/pressure/ms5607/demo.js +65 -0
  46. package/examples/pressure/ms5607/minimal.js +22 -0
  47. package/examples/pressure/ms5611/complete.js +49 -0
  48. package/examples/pressure/ms5611/demo.js +65 -0
  49. package/examples/pressure/ms5611/minimal.js +22 -0
  50. package/examples/pressure/spl06/complete.js +81 -0
  51. package/examples/pressure/spl06/demo.js +106 -0
  52. package/examples/pressure/spl06/minimal.js +22 -0
  53. package/examples/rfid/pn532/complete.js +99 -0
  54. package/examples/rfid/pn532/demo.js +121 -0
  55. package/examples/rfid/pn532/minimal.js +22 -0
  56. package/package.json +1 -1
  57. package/src/chips/color/isl29125.js +379 -0
  58. package/src/chips/environmental/bme688.js +573 -0
  59. package/src/chips/gas/ccs811.js +400 -0
  60. package/src/chips/gas/rrh46410.js +534 -0
  61. package/src/chips/humidity/hts221.js +369 -0
  62. package/src/chips/humidity/htu31d.js +242 -0
  63. package/src/chips/humidity/shtc3.js +239 -0
  64. package/src/chips/led/saa1064.js +241 -0
  65. package/src/chips/light/apds9250.js +431 -0
  66. package/src/chips/light/bh1750.js +196 -0
  67. package/src/chips/light/si1132.js +416 -0
  68. package/src/chips/light/si1133.js +583 -0
  69. package/src/chips/light/si1145.js +630 -0
  70. package/src/chips/pressure/mpl3115a2.js +459 -0
  71. package/src/chips/pressure/ms5607.js +290 -0
  72. package/src/chips/pressure/ms5611.js +290 -0
  73. package/src/chips/pressure/spl06.js +461 -0
  74. package/src/chips/rfid/pn532.js +513 -0
  75. package/src/connection/i2c.js +46 -13
  76. package/src/connection/smbus.js +21 -8
  77. package/src/discovery/registry.js +18 -18
  78. package/examples/gpio/.gitkeep +0 -0
  79. package/src/chips/gpio/.gitkeep +0 -0
@@ -0,0 +1,121 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { PN532Full } = require('../../../src/chips/rfid/pn532');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x24', 16);
8
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
9
+ const hex = (b) => Buffer.from(b).toString('hex').toUpperCase();
10
+
11
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR); // Create I²C connection, (bus=1, addr=0x24) → Connection
12
+ const reader = new PN532Full(connection); // Create PN532 driver, (connection) → void
13
+
14
+ async function main() {
15
+ await reader.init(); // Wake, check firmware, SAM normal mode, finite retries, () → void
16
+
17
+ // --- Identity and health ---
18
+ // IC 0x32 is the PN532; the support byte lists ISO 14443 A/B and ISO 18092.
19
+ // The communication-line self test echoes a pattern through the firmware.
20
+ const fw = await reader.firmwareVersion(); // GetFirmwareVersion, () → object
21
+ console.log(`PN532 IC 0x${fw.ic.toString(16)} firmware ${fw.version}.${fw.revision} support 0x${fw.support.toString(16)}`);
22
+ console.log('status', await reader.generalStatus()); // GetGeneralStatus, () → object
23
+ console.log('self test', await reader.selfTest()); // Diagnose, (test=0x00) → boolean
24
+
25
+ // --- Card polling: 15 s at 1 Hz ---
26
+ // Present a card or tag. The finite retry count makes every poll return
27
+ // after a few milliseconds when the field is empty.
28
+ for (let i = 0; i < 15; i++) {
29
+ const targets = await reader.listPassiveTargets(); // InListPassiveTarget, ({baud=BAUD_106_A, maxTargets=1, ...}) → Target[]
30
+ if (targets.length) {
31
+ const t = targets[0];
32
+ console.log(`${i} s UID ${hex(t.uid)} SENS_RES 0x${t.sensRes.toString(16)} SEL_RES 0x${t.selRes.toString(16)}`);
33
+ await reader.release(t.tg); // InRelease, (target=0) → void
34
+ } else {
35
+ console.log(`${i} s no card`);
36
+ }
37
+ await sleep(1000);
38
+ }
39
+
40
+ // --- Tag access ---
41
+ // SEL_RES 0x00 is an NTAG / MIFARE Ultralight: read page 4 and write it back.
42
+ // SEL_RES 0x08 is a MIFARE Classic 1K: authenticate sector 1 with the transport
43
+ // key FF FF FF FF FF FF, read block 4 and write it back. Writing sector
44
+ // trailers can lock a sector forever.
45
+ const targets = await reader.listPassiveTargets(); // InListPassiveTarget, ({baud=BAUD_106_A, ...}) → Target[]
46
+ if (targets.length) {
47
+ const t = targets[0];
48
+ await reader.deselect(t.tg); // InDeselect, (target=0) → void
49
+ await reader.select(t.tg); // InSelect, (target=0) → void
50
+ try {
51
+ if (t.selRes === 0x00) {
52
+ const page = await reader.ntagReadPage(t.tg, 4); // NTAG READ, (target, page) → Buffer (16)
53
+ console.log('pages 4..7', hex(page));
54
+ await reader.ntagWritePage(t.tg, 4, page.subarray(0, 4)); // NTAG WRITE, (target, page, data 4 bytes) → void
55
+ console.log('raw read', hex(await reader.dataExchange(t.tg, [0x30, 0x00]))); // InDataExchange, (target, data) → Buffer
56
+ } else if (t.selRes & 0x08) {
57
+ await reader.mifareAuthenticate(t.tg, 4, Buffer.alloc(6, 0xFF), t.uid); // MIFARE auth, (target, block, key, uid, keyB=false) → void
58
+ const block = await reader.mifareReadBlock(t.tg, 4); // MIFARE READ, (target, block) → Buffer (16)
59
+ console.log('block 4', hex(block));
60
+ await reader.mifareWriteBlock(t.tg, 4, block); // MIFARE WRITE, (target, block, data 16 bytes) → void
61
+ }
62
+ } catch (e) {
63
+ console.log('tag access failed:', e.message);
64
+ }
65
+ await reader.release(t.tg); // InRelease, (target=0) → void
66
+ } else {
67
+ console.log('no card for the tag access part');
68
+ }
69
+
70
+ // --- Raw RF and raw commands ---
71
+ // InCommunicateThru sends bytes without PN532 protocol handling; with no
72
+ // target selected it reports an error. sendCommand reaches every command.
73
+ try {
74
+ console.log('thru', hex(await reader.communicateThru([0x30, 0x00]))); // InCommunicateThru, (data) → Buffer
75
+ } catch (e) {
76
+ console.log('communicateThru:', e.message);
77
+ }
78
+ console.log('raw GetFirmwareVersion', hex(await reader.sendCommand(0x02))); // Raw command, (command, data=[], timeout=1.0 s) → Buffer
79
+ const txMode = await reader.readRegister(0x6302); // ReadRegister, (address) → number
80
+ console.log(`CIU_TxMode 0x${txMode.toString(16)}`);
81
+ await reader.writeRegister(0x6302, txMode); // WriteRegister, (address, value) → void
82
+
83
+ // --- Wake on card with onInterrupt ---
84
+ // Infinite activation retries make InListPassiveTarget wait for a card;
85
+ // IRQ (or the status-byte poll) wakes the callback when the response is ready.
86
+ await reader.setMaxRetries({ passiveActivation: 0xFF }); // RFConfiguration item 5, ({passiveActivation=2, atr=0xFF, psl=1}) → void
87
+ let ready = false;
88
+ await reader.onInterrupt(() => { ready = true; }); // Subscribe to IRQ, (callback, intPin=null) → void
89
+ await reader.startCommand(0x4A, [0x01, 0x00]); // Command without waiting, (command, data=[]) → void
90
+ console.log('waiting 10 s for a card ...');
91
+ for (let i = 0; i < 100 && !ready; i++) {
92
+ if (await reader.pollInterrupt()) break; // Frame ready?, () → boolean
93
+ await sleep(100);
94
+ }
95
+ await reader.offInterrupt(); // Unsubscribe, () → void
96
+ if (await reader.waitReady(0.01)) { // Wait for a frame, (timeout s) → boolean
97
+ const resp = await reader.readResponse(0x4A); // Read the pending response, (command, timeout=1.0 s) → Buffer
98
+ console.log('card arrived, UID', hex(resp.subarray(6, 6 + resp[5])));
99
+ await reader.release(); // InRelease, (target=0) → void
100
+ } else {
101
+ try {
102
+ await reader.readResponse(0x4A, 0); // Read the pending response, (command, timeout=1.0 s) → Buffer
103
+ } catch (e) {
104
+ /* timed out: the command was aborted with an ACK frame */
105
+ }
106
+ console.log('no card arrived');
107
+ }
108
+ await reader.setMaxRetries(); // RFConfiguration item 5, ({passiveActivation=2, atr=0xFF, psl=1}) → void
109
+ console.log('readUid', await reader.readUid()); // Detect a type A card, (timeout=1.0 s) → Buffer | null
110
+
111
+ // --- RF field off and on, then power down ---
112
+ // With the field off a card loses power; the reader draws less current.
113
+ await reader.setRfField(false); // RFConfiguration item 1, (on, autoRfca=false) → void
114
+ await sleep(1000);
115
+ await reader.setRfField(true); // RFConfiguration item 1, (on, autoRfca=false) → void
116
+ await reader.powerDown(); // PowerDown, (wakeupSources=0x20) → void
117
+ console.log('powered down; the next I²C access wakes the chip');
118
+ connection.close();
119
+ }
120
+
121
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { PN532Minimal } = require('../../../src/chips/rfid/pn532');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x24', 16);
8
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
9
+
10
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR); // Create I²C connection, (bus=1, addr=0x24) → Connection
11
+ const reader = new PN532Minimal(connection); // Create PN532 driver, (connection) → void
12
+
13
+ async function main() {
14
+ await reader.init(); // Wake, check firmware, SAM normal mode, finite retries, () → void
15
+ while (true) {
16
+ const uid = await reader.readUid(); // Detect a type A card, (timeout=1.0 s) → Buffer | null
17
+ console.log('UID', uid ? uid.toString('hex').toUpperCase() : null);
18
+ await sleep(1000);
19
+ }
20
+ }
21
+
22
+ main().catch(err => { console.error(err); process.exit(1); });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "periph",
3
- "version": "1.5.3",
3
+ "version": "1.6.0",
4
4
  "description": "JavaScript drivers for peripheral chips (I2C, SPI)",
5
5
  "main": "src/index.js",
6
6
  "keywords": [
@@ -0,0 +1,379 @@
1
+ 'use strict';
2
+
3
+ const REG_DEVICE_ID = 0x00;
4
+ const REG_CONFIG1 = 0x01;
5
+ const REG_CONFIG2 = 0x02;
6
+ const REG_CONFIG3 = 0x03;
7
+ const REG_LOW_TH = 0x04;
8
+ const REG_HIGH_TH = 0x06;
9
+ const REG_STATUS = 0x08;
10
+ const REG_GREEN = 0x09;
11
+ const REG_RED = 0x0B;
12
+ const REG_BLUE = 0x0D;
13
+
14
+ const DEVICE_ID = 0x7D;
15
+ const RESET_VALUE = 0x46;
16
+
17
+ const CFG1_SYNC = 0x20;
18
+ const CFG1_BITS_12 = 0x10;
19
+ const CFG1_RNG_10000 = 0x08;
20
+ const CFG1_MODE_MASK = 0x07;
21
+ const CFG3_CONVEN = 0x10;
22
+
23
+ const STATUS_BROWNOUT = 0x04;
24
+ const STATUS_CONVERSION = 0x02;
25
+ const STATUS_THRESHOLD = 0x01;
26
+
27
+ const MODE_CODE = {
28
+ power_down: 0, green: 1, red: 2, blue: 3, standby: 4,
29
+ rgb: 5, green_red: 6, green_blue: 7,
30
+ };
31
+ const CHANNEL_CODE = { none: 0, green: 1, red: 2, blue: 3 };
32
+ const PERSISTENCE_CODE = { 1: 0, 2: 1, 4: 2, 8: 3 };
33
+
34
+ const WAIT_LIMIT_MS = 400;
35
+ const POLL_STEP_MS = 10;
36
+ const INT_POLL_INTERVAL_MS = 50;
37
+
38
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
39
+
40
+ /**
41
+ * ISL29125 digital red, green and blue colour light sensor (Renesas / Intersil) — minimal interface.
42
+ *
43
+ * RGB colour sensor with an IR-blocking filter, a 12/16-bit integrating ADC
44
+ * (16 bit: 100 ms), two sensing ranges (375 lux and 10 000 lux full scale) and
45
+ * programmable IR compensation. Results are unsigned 16-bit counts, LSB first.
46
+ * The I²C address is fixed at 0x44. Reading STATUS clears its flags, so the
47
+ * driver keeps the flags it has seen until `pollInterrupt()` / `status()` hands
48
+ * them out.
49
+ */
50
+ class ISL29125Minimal {
51
+ /**
52
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - I²C register connection (1-byte register address).
53
+ */
54
+ constructor(connection) {
55
+ this._conn = connection;
56
+ this._pending = 0;
57
+ }
58
+
59
+ /** Fixed 7-bit I²C address. */
60
+ static get I2C_ADDRESS() { return 0x44; }
61
+
62
+ async _readReg(reg) {
63
+ return (await this._conn.readReg(reg, 1))[0];
64
+ }
65
+
66
+ async _writeReg(reg, value) {
67
+ await this._conn.writeReg(reg, value & 0xFF);
68
+ }
69
+
70
+ async _readStatus() {
71
+ const value = await this._readReg(REG_STATUS);
72
+ this._pending |= value & (STATUS_BROWNOUT | STATUS_CONVERSION | STATUS_THRESHOLD);
73
+ return value;
74
+ }
75
+
76
+ async _waitData() {
77
+ for (let waited = 0; waited <= WAIT_LIMIT_MS; waited += POLL_STEP_MS) {
78
+ if ((await this._readStatus()) & STATUS_CONVERSION) return true;
79
+ if (ISL29125Minimal.pollStepMs > 0) await sleep(ISL29125Minimal.pollStepMs);
80
+ }
81
+ return false;
82
+ }
83
+
84
+ async _readBlock() {
85
+ const raw = await this._conn.readReg(REG_GREEN, 6);
86
+ return {
87
+ red: raw[2] | (raw[3] << 8),
88
+ green: raw[0] | (raw[1] << 8),
89
+ blue: raw[4] | (raw[5] << 8),
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Start the sensor: read DEVICE_ID (must be 0x7D), clear the brown-out flag
95
+ * and write CONFIG1 = 0x0D (RGB, 10 000 lux, 16 bit), CONFIG2 = 0xBF
96
+ * (maximum IR compensation) and CONFIG3 = 0x00.
97
+ * @returns {Promise<void>}
98
+ * @throws {Error} if DEVICE_ID does not identify an ISL29125.
99
+ */
100
+ async init() {
101
+ const id = await this._readReg(REG_DEVICE_ID);
102
+ if (id !== DEVICE_ID) {
103
+ throw new Error('ISL29125 not found (DEVICE_ID 0x' + id.toString(16).padStart(2, '0') + ')');
104
+ }
105
+ await this._writeReg(REG_STATUS, 0x00);
106
+ await this._writeReg(REG_CONFIG3, 0x00);
107
+ await this._writeReg(REG_CONFIG2, 0xBF);
108
+ await this._writeReg(REG_CONFIG1, 0x0D);
109
+ }
110
+
111
+ /**
112
+ * Read red, green and blue from one conversion. Waits for a new result (at
113
+ * most 400 ms), then block-reads 0x09-0x0E.
114
+ * @returns {Promise<{red: number, green: number, blue: number}>} Unsigned 16-bit counts.
115
+ */
116
+ async read() {
117
+ await this._waitData();
118
+ return this._readBlock();
119
+ }
120
+ }
121
+
122
+ /** Poll step while waiting for CONVENF, in ms (tests may set it to 0). */
123
+ ISL29125Minimal.pollStepMs = POLL_STEP_MS;
124
+
125
+ /**
126
+ * ISL29125 full interface — extends Minimal with single-channel reads, mode,
127
+ * range, resolution, synchronisation and IR-compensation configuration,
128
+ * thresholds, persistence, and interrupt delivery.
129
+ */
130
+ class ISL29125Full extends ISL29125Minimal {
131
+ constructor(connection) {
132
+ super(connection);
133
+ this._callback = null;
134
+ this._intPinUsed = null;
135
+ this._pollTimer = null;
136
+ this._polling = false;
137
+ this._edgeHandler = () => { this._service(); };
138
+ }
139
+
140
+ /** Interrupt source: selected channel outside the threshold window. */
141
+ static get SOURCE_THRESHOLD() { return 0x01; }
142
+ /** Interrupt source: conversion complete. */
143
+ static get SOURCE_CONVERSION() { return 0x02; }
144
+ /** STATUS bit 2: power-down or brown-out occurred. */
145
+ static get STATUS_BROWNOUT() { return STATUS_BROWNOUT; }
146
+ /** STATUS bit 1: conversion completed. */
147
+ static get STATUS_CONVERSION() { return STATUS_CONVERSION; }
148
+ /** STATUS bit 0: threshold window crossed. */
149
+ static get STATUS_THRESHOLD() { return STATUS_THRESHOLD; }
150
+
151
+ async _readChannel(reg) {
152
+ const raw = await this._conn.readReg(reg, 2);
153
+ return raw[0] | (raw[1] << 8);
154
+ }
155
+
156
+ /** @returns {Promise<number>} Red count. */
157
+ async readRed() { return this._readChannel(REG_RED); }
158
+
159
+ /** @returns {Promise<number>} Green count. */
160
+ async readGreen() { return this._readChannel(REG_GREEN); }
161
+
162
+ /** @returns {Promise<number>} Blue count. */
163
+ async readBlue() { return this._readChannel(REG_BLUE); }
164
+
165
+ /**
166
+ * Block-read all three channels without waiting.
167
+ * @returns {Promise<{red: number, green: number, blue: number}>} Counts.
168
+ */
169
+ async readRgb() { return this._readBlock(); }
170
+
171
+ /**
172
+ * Report whether a conversion has completed. Reads STATUS, which clears its
173
+ * flags; the flags are kept for `pollInterrupt()` and `status()`.
174
+ * @returns {Promise<boolean>} True if CONVENF was set.
175
+ */
176
+ async dataReady() {
177
+ return Boolean((await this._readStatus()) & STATUS_CONVERSION);
178
+ }
179
+
180
+ async _updateReg(reg, setBits, clearBits) {
181
+ const value = await this._readReg(reg);
182
+ await this._writeReg(reg, (value & ~clearBits) | setBits);
183
+ }
184
+
185
+ /**
186
+ * Select the operating mode (conversions are continuous).
187
+ * @param {string} mode - 'power_down', 'standby', 'green', 'red', 'blue', 'rgb', 'green_red' or 'green_blue'.
188
+ * @returns {Promise<void>}
189
+ */
190
+ async setMode(mode) {
191
+ if (!(mode in MODE_CODE)) throw new RangeError('unknown mode ' + mode);
192
+ await this._updateReg(REG_CONFIG1, MODE_CODE[mode], CFG1_MODE_MASK);
193
+ }
194
+
195
+ /**
196
+ * Select the sensing range.
197
+ * @param {number} lux - 375 or 10000 (full-scale illuminance).
198
+ * @returns {Promise<void>}
199
+ */
200
+ async setRange(lux) {
201
+ if (lux === 375) await this._updateReg(REG_CONFIG1, 0, CFG1_RNG_10000);
202
+ else if (lux === 10000) await this._updateReg(REG_CONFIG1, CFG1_RNG_10000, 0);
203
+ else throw new RangeError('range must be 375 or 10000');
204
+ }
205
+
206
+ /**
207
+ * Select the ADC resolution.
208
+ * @param {number} bits - 12 or 16.
209
+ * @returns {Promise<void>}
210
+ */
211
+ async setResolution(bits) {
212
+ if (bits === 16) await this._updateReg(REG_CONFIG1, 0, CFG1_BITS_12);
213
+ else if (bits === 12) await this._updateReg(REG_CONFIG1, CFG1_BITS_12, 0);
214
+ else throw new RangeError('resolution must be 12 or 16');
215
+ }
216
+
217
+ /**
218
+ * Select the conversion start source.
219
+ * @param {boolean} external - True: the rising edge of INT starts the conversion (INT becomes an input); false: the I²C write starts it.
220
+ * @returns {Promise<void>}
221
+ */
222
+ async setSync(external) {
223
+ await this._updateReg(REG_CONFIG1, external ? CFG1_SYNC : 0, CFG1_SYNC);
224
+ }
225
+
226
+ /**
227
+ * Set the active IR compensation (CONFIG2).
228
+ * @param {boolean} offset - False: codes 0-63; true: codes 106-169.
229
+ * @param {number} adjust - Compensation adjust, 0-63.
230
+ * @returns {Promise<void>}
231
+ */
232
+ async setIrCompensation(offset, adjust) {
233
+ if (adjust < 0 || adjust > 63) throw new RangeError('adjust must be 0-63');
234
+ await this._writeReg(REG_CONFIG2, (offset ? 0x80 : 0) | adjust);
235
+ }
236
+
237
+ /** @returns {Promise<number>} DEVICE_ID (0x7D for the ISL29125). */
238
+ async deviceId() { return this._readReg(REG_DEVICE_ID); }
239
+
240
+ /**
241
+ * Read STATUS (clears the flags on the chip).
242
+ * @returns {Promise<number>} Raw status byte with the flags seen since the last call merged in.
243
+ */
244
+ async status() {
245
+ let value = await this._readStatus();
246
+ value |= this._pending;
247
+ this._pending = 0;
248
+ return value;
249
+ }
250
+
251
+ /** Reset all registers to their defaults (writes 0x46 to register 0x00). @returns {Promise<void>} */
252
+ async softReset() {
253
+ await this._writeReg(REG_DEVICE_ID, RESET_VALUE);
254
+ if (ISL29125Minimal.pollStepMs > 0) await sleep(10);
255
+ this._pending = 0;
256
+ }
257
+
258
+ /**
259
+ * Set the 16-bit threshold window.
260
+ * @param {number} low - Lower threshold (0-65535).
261
+ * @param {number} high - Upper threshold (0-65535).
262
+ * @returns {Promise<void>}
263
+ */
264
+ async setThresholds(low, high) {
265
+ if (low < 0 || high < 0 || low > 0xFFFF || high > 0xFFFF || low > high) {
266
+ throw new RangeError('thresholds must satisfy 0 <= low <= high <= 65535');
267
+ }
268
+ await this._conn.writeReg(REG_LOW_TH, Buffer.from([low & 0xFF, low >> 8]));
269
+ await this._conn.writeReg(REG_HIGH_TH, Buffer.from([high & 0xFF, high >> 8]));
270
+ }
271
+
272
+ /** @returns {Promise<{low: number, high: number}>} Threshold window in counts. */
273
+ async getThresholds() {
274
+ const low = await this._conn.readReg(REG_LOW_TH, 2);
275
+ const high = await this._conn.readReg(REG_HIGH_TH, 2);
276
+ return { low: low[0] | (low[1] << 8), high: high[0] | (high[1] << 8) };
277
+ }
278
+
279
+ /**
280
+ * Select the channel the threshold interrupt monitors.
281
+ * @param {string} channel - 'none', 'green', 'red' or 'blue'.
282
+ * @returns {Promise<void>}
283
+ */
284
+ async setInterruptChannel(channel) {
285
+ if (!(channel in CHANNEL_CODE)) throw new RangeError("channel must be 'none', 'green', 'red' or 'blue'");
286
+ await this._updateReg(REG_CONFIG3, CHANNEL_CODE[channel], 0x03);
287
+ }
288
+
289
+ /**
290
+ * Set the number of integration cycles before the interrupt asserts.
291
+ * @param {number} count - 1, 2, 4 or 8.
292
+ * @returns {Promise<void>}
293
+ */
294
+ async setPersistence(count) {
295
+ if (!(count in PERSISTENCE_CODE)) throw new RangeError('count must be 1, 2, 4 or 8');
296
+ await this._updateReg(REG_CONFIG3, PERSISTENCE_CODE[count] << 2, 0x0C);
297
+ }
298
+
299
+ /**
300
+ * Enable an interrupt source. For `SOURCE_THRESHOLD` select the channel
301
+ * beforehand with `setInterruptChannel()` (green is used if none is set).
302
+ * @param {number} [source] - `SOURCE_THRESHOLD` (default) or `SOURCE_CONVERSION`.
303
+ * @returns {Promise<void>}
304
+ */
305
+ async enableInterrupt(source = ISL29125Full.SOURCE_THRESHOLD) {
306
+ if (source === ISL29125Full.SOURCE_CONVERSION) {
307
+ await this._updateReg(REG_CONFIG3, CFG3_CONVEN, 0);
308
+ } else if (((await this._readReg(REG_CONFIG3)) & 0x03) === 0) {
309
+ await this._updateReg(REG_CONFIG3, 0x01, 0);
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Disable an interrupt source.
315
+ * @param {number} [source] - `SOURCE_THRESHOLD` (INTSEL = none, default) or `SOURCE_CONVERSION`.
316
+ * @returns {Promise<void>}
317
+ */
318
+ async disableInterrupt(source = ISL29125Full.SOURCE_THRESHOLD) {
319
+ if (source === ISL29125Full.SOURCE_CONVERSION) await this._updateReg(REG_CONFIG3, 0, CFG3_CONVEN);
320
+ else await this._updateReg(REG_CONFIG3, 0, 0x03);
321
+ }
322
+
323
+ /**
324
+ * Read STATUS (clearing the flags) and return it.
325
+ * @returns {Promise<number>} Status byte; `STATUS_THRESHOLD` / `STATUS_CONVERSION` are set for events seen since the last poll.
326
+ */
327
+ async pollInterrupt() { return this.status(); }
328
+
329
+ async _arm(intPin) {
330
+ this._intPinUsed = intPin;
331
+ if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
332
+ if (intPin) {
333
+ await intPin.onEdge(this._edgeHandler, 'falling');
334
+ } else {
335
+ this._pollTimer = setInterval(() => { this._service(); }, INT_POLL_INTERVAL_MS);
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Subscribe to INT assertions. `callback(status)` is called with the STATUS
341
+ * byte after the driver has read (and thereby cleared) it. Delivery is via
342
+ * the INT line (options.intPin or connection.intPin, falling edge) or a
343
+ * 50 ms polling timer.
344
+ * @param {function} callback - Called with (status).
345
+ * @param {object} [options]
346
+ * @param {import('../../connection/input_pin').InputPin|null} [options.intPin] - Overrides connection.intPin.
347
+ * @returns {Promise<void>}
348
+ */
349
+ async onInterrupt(callback, options = {}) {
350
+ this._callback = callback;
351
+ await this._arm(options.intPin ?? this._conn.intPin ?? null);
352
+ }
353
+
354
+ /**
355
+ * Unsubscribe and stop delivery.
356
+ * @returns {Promise<void>}
357
+ */
358
+ async offInterrupt() {
359
+ if (this._intPinUsed) {
360
+ await this._intPinUsed.offEdge(this._edgeHandler);
361
+ this._intPinUsed = null;
362
+ }
363
+ if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
364
+ this._callback = null;
365
+ }
366
+
367
+ async _service() {
368
+ if (this._polling) return;
369
+ this._polling = true;
370
+ try {
371
+ const status = await this.pollInterrupt();
372
+ if ((status & (STATUS_THRESHOLD | STATUS_CONVERSION)) && this._callback) this._callback(status);
373
+ } finally {
374
+ this._polling = false;
375
+ }
376
+ }
377
+ }
378
+
379
+ module.exports = { ISL29125Minimal, ISL29125Full };