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,254 @@
1
+ 'use strict';
2
+
3
+ const _CMD_ENTER_PROG = Buffer.from([0xA0, 0x00, 0x00]);
4
+ const _CMD_EXIT_PROG = Buffer.from([0x80, 0x00, 0x00]);
5
+
6
+ const _REG_RH_READ = 0x06;
7
+ const _REG_RH_WRITE = 0x46;
8
+ const _REG_T_READ = 0x11;
9
+ const _REG_T_WRITE = 0x51;
10
+ const _REG_ID_HIGH = 0x1E;
11
+ const _REG_ID_LOW = 0x1F;
12
+
13
+ const _NVM_OK = 0x81;
14
+ const _RES_MASK = 0x0C00;
15
+ const _BITS = [8, 10, 12, 14];
16
+ const _FULL_SCALE = 16383.0;
17
+
18
+ const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
19
+
20
+ function _rawHumidity(data) {
21
+ return ((data[0] & 0x3F) << 8) | data[1];
22
+ }
23
+
24
+ function _rawTemperature(data) {
25
+ return (data[2] << 6) | (data[3] >> 2);
26
+ }
27
+
28
+ function _toHumidity(raw) {
29
+ return raw / _FULL_SCALE * 100.0;
30
+ }
31
+
32
+ function _toTemperature(raw) {
33
+ return raw / _FULL_SCALE * 165.0 - 40.0;
34
+ }
35
+
36
+ /**
37
+ * HS30xx humidity and temperature sensor — minimal interface.
38
+ *
39
+ * Covers the whole Renesas HS3xxx family (HS3001, HS3002, HS3003 — they differ only in
40
+ * accuracy class and housing, not in protocol). Each `read()` sends a measurement request
41
+ * (MR, an address-only write), waits 40 ms, fetches four bytes (data fetch, DF) and converts
42
+ * them. If the status bits report stale data it waits 10 ms and fetches once more.
43
+ *
44
+ * The constructor performs no bus access: bytes written within 10 ms of power-up could be
45
+ * taken as NVM programming commands.
46
+ *
47
+ * Default configuration (factory): 14-bit humidity and temperature resolution, fixed 40 ms
48
+ * wait after the request, no NVM access.
49
+ */
50
+ class HS30xxMinimal {
51
+ /**
52
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C connection pointing at the device (address 0x44).
53
+ */
54
+ constructor(connection) {
55
+ this._conn = connection;
56
+ this._wait = 40;
57
+ }
58
+
59
+ async _fetch(length) {
60
+ // MR is an address-only write (no data byte); the DF read follows after the conversion.
61
+ await this._conn.write(Buffer.alloc(0));
62
+ await _sleep(this._wait);
63
+ let data = await this._conn.read(length);
64
+ if ((data[0] >> 6) !== 0) {
65
+ await _sleep(10);
66
+ data = await this._conn.read(length);
67
+ if ((data[0] >> 6) !== 0) throw new Error('HS30xx returned stale data');
68
+ }
69
+ return data;
70
+ }
71
+
72
+ /**
73
+ * Measure temperature and humidity (request, 40 ms wait, 4-byte fetch; the output is always scaled to 14 bits).
74
+ * @returns {Promise<{temperature_c: number, humidity_pct: number}>} Temperature in °C (-40 to 125) and relative humidity in %RH (0 to 100).
75
+ * @throws {Error} If the data are still flagged stale after one retry.
76
+ */
77
+ async read() {
78
+ const data = await this._fetch(4);
79
+ return {
80
+ temperature_c: _toTemperature(_rawTemperature(data)),
81
+ humidity_pct: _toHumidity(_rawHumidity(data)),
82
+ };
83
+ }
84
+ }
85
+
86
+ /**
87
+ * HS30xx full interface — raw values, wait override, NVM resolution and ID, dew point.
88
+ *
89
+ * Extends `HS30xxMinimal`. The NVM methods (resolution, ID) need the sensor's programming
90
+ * mode, which can only be entered within 10 ms after power-up. They therefore take a
91
+ * `powerCycle` function that cuts and restores the sensor supply (e.g. via a MOSFET or a
92
+ * GPIO powering the sensor); without it they throw.
93
+ */
94
+ class HS30xxFull extends HS30xxMinimal {
95
+ /** @param {import('../../connection/connection').Connection} connection - Configured I²C connection (address 0x44). */
96
+ constructor(connection) {
97
+ super(connection);
98
+ }
99
+
100
+ /**
101
+ * Measure temperature only (4-byte data fetch, humidity discarded).
102
+ * @returns {Promise<number>} Temperature in °C.
103
+ */
104
+ async readTemperature() {
105
+ return _toTemperature(_rawTemperature(await this._fetch(4)));
106
+ }
107
+
108
+ /**
109
+ * Measure humidity only (2-byte data fetch).
110
+ * @returns {Promise<number>} Relative humidity in %RH.
111
+ */
112
+ async readHumidity() {
113
+ return _toHumidity(_rawHumidity(await this._fetch(2)));
114
+ }
115
+
116
+ /**
117
+ * Measure and return the raw 14-bit values and the status field, without a stale check.
118
+ * @returns {Promise<{raw_humidity: number, raw_temperature: number, status: number}>} Status: 0 = valid, 1 = stale.
119
+ */
120
+ async readRaw() {
121
+ await this._conn.write(Buffer.alloc(0));
122
+ await _sleep(this._wait);
123
+ const data = await this._conn.read(4);
124
+ return { raw_humidity: _rawHumidity(data), raw_temperature: _rawTemperature(data), status: data[0] >> 6 };
125
+ }
126
+
127
+ /**
128
+ * Override the wait between measurement request and data fetch (default 40 ms).
129
+ * Lower resolutions convert faster: 0.1 ms + RH_time/2 + T_time/2 (datasheet).
130
+ * @param {number} ms - Wait in milliseconds, greater than 0.
131
+ */
132
+ setMeasurementWait(ms) {
133
+ if (!(ms > 0)) throw new RangeError('ms must be > 0');
134
+ this._wait = ms;
135
+ }
136
+
137
+ /** Send the enter-programming-mode command (0xA0 0x00 0x00) and wait 120 µs; only valid within 10 ms after power-up. */
138
+ async enterProgrammingMode() {
139
+ await this._conn.write(_CMD_ENTER_PROG);
140
+ await _sleep(1);
141
+ }
142
+
143
+ /** Send the leave-programming-mode command (0x80 0x00 0x00) and return to measurement operation. */
144
+ async exitProgrammingMode() {
145
+ await this._conn.write(_CMD_EXIT_PROG);
146
+ }
147
+
148
+ /**
149
+ * Read one 16-bit NVM register (programming mode only).
150
+ * @param {number} reg - NVM read address (0x06, 0x11, 0x1E or 0x1F).
151
+ * @returns {Promise<number>} Register value (0 to 65535).
152
+ * @throws {Error} If the response status byte is not 0x81.
153
+ */
154
+ async readNvm(reg) {
155
+ await this._conn.write(Buffer.from([reg, 0x00, 0x00]));
156
+ await _sleep(1);
157
+ const data = await this._conn.read(3);
158
+ if (data[0] !== _NVM_OK) throw new Error('HS30xx NVM read failed (status 0x' + data[0].toString(16) + ')');
159
+ return (data[1] << 8) | data[2];
160
+ }
161
+
162
+ async _writeNvm(reg, value) {
163
+ await this._conn.write(Buffer.from([reg, (value >> 8) & 0xFF, value & 0xFF]));
164
+ await _sleep(14);
165
+ }
166
+
167
+ async _program(powerCycle) {
168
+ if (typeof powerCycle !== 'function') throw new Error('HS30xx NVM access needs a powerCycle function');
169
+ await powerCycle();
170
+ await this.enterProgrammingMode();
171
+ }
172
+
173
+ /**
174
+ * Read the NVM resolution settings (power-cycles the sensor).
175
+ * @param {function(): (void|Promise<void>)} powerCycle - Cuts and restores the sensor supply; the programming-mode command follows immediately.
176
+ * @returns {Promise<{humidity_bits: number, temperature_bits: number}>} Each 8, 10, 12 or 14.
177
+ * @throws {Error} If powerCycle is missing or the NVM read fails.
178
+ */
179
+ async getResolution(powerCycle) {
180
+ await this._program(powerCycle);
181
+ try {
182
+ const rh = await this.readNvm(_REG_RH_READ);
183
+ const t = await this.readNvm(_REG_T_READ);
184
+ return { humidity_bits: _BITS[(rh >> 10) & 3], temperature_bits: _BITS[(t >> 10) & 3] };
185
+ } finally {
186
+ await this.exitProgrammingMode();
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Write the NVM resolution settings (power-cycles the sensor; bits 11:10 only).
192
+ * Each register is read, bits 11:10 replaced and the whole word written back, then the driver waits 14 ms for the NVM commit.
193
+ * @param {number|null} humidityBits - 8, 10, 12 or 14, or null to leave unchanged.
194
+ * @param {number|null} temperatureBits - 8, 10, 12 or 14, or null to leave unchanged.
195
+ * @param {function(): (void|Promise<void>)} powerCycle - Cuts and restores the sensor supply.
196
+ * @throws {RangeError} If a value is not 8, 10, 12 or 14.
197
+ * @throws {Error} If powerCycle is missing or an NVM read fails.
198
+ */
199
+ async setResolution(humidityBits, temperatureBits, powerCycle) {
200
+ for (const bits of [humidityBits, temperatureBits]) {
201
+ if (bits !== null && bits !== undefined && !_BITS.includes(bits)) {
202
+ throw new RangeError('resolution must be 8, 10, 12 or 14 bits');
203
+ }
204
+ }
205
+ await this._program(powerCycle);
206
+ try {
207
+ for (const [bits, rreg, wreg] of [[humidityBits, _REG_RH_READ, _REG_RH_WRITE],
208
+ [temperatureBits, _REG_T_READ, _REG_T_WRITE]]) {
209
+ if (bits !== null && bits !== undefined) {
210
+ const value = await this.readNvm(rreg);
211
+ await this._writeNvm(wreg, (value & ~_RES_MASK & 0xFFFF) | (_BITS.indexOf(bits) << 10));
212
+ }
213
+ }
214
+ } finally {
215
+ await this.exitProgrammingMode();
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Read the 32-bit sensor ID from NVM (power-cycles the sensor).
221
+ * @param {function(): (void|Promise<void>)} powerCycle - Cuts and restores the sensor supply.
222
+ * @returns {Promise<number>} 32-bit ID.
223
+ * @throws {Error} If powerCycle is missing or the NVM read fails.
224
+ */
225
+ async readId(powerCycle) {
226
+ await this._program(powerCycle);
227
+ try {
228
+ const high = await this.readNvm(_REG_ID_HIGH);
229
+ const low = await this.readNvm(_REG_ID_LOW);
230
+ return ((high << 16) | low) >>> 0;
231
+ } finally {
232
+ await this.exitProgrammingMode();
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Run one measurement and return the dew point (Magnus formula).
238
+ * @returns {Promise<number>} Dew point in °C; -273.15 if humidity is 0 %RH.
239
+ */
240
+ async dewPoint() {
241
+ const m = await this.read();
242
+ if (m.humidity_pct <= 0.0) return -273.15;
243
+ const gamma = Math.log(m.humidity_pct / 100.0) + 17.62 * m.temperature_c / (243.12 + m.temperature_c);
244
+ return 243.12 * gamma / (17.62 - gamma);
245
+ }
246
+ }
247
+
248
+ // The HS3001, HS3002 and HS3003 share one protocol and differ only in accuracy class and
249
+ // housing, so they are plain aliases of the HS30xx drivers.
250
+ module.exports = {
251
+ HS30xxMinimal, HS30xxFull,
252
+ HS3001Minimal: HS30xxMinimal, HS3002Minimal: HS30xxMinimal, HS3003Minimal: HS30xxMinimal,
253
+ HS3001Full: HS30xxFull, HS3002Full: HS30xxFull, HS3003Full: HS30xxFull,
254
+ };
@@ -0,0 +1,382 @@
1
+ 'use strict';
2
+
3
+ const _CMD_T_NOHOLD = 0xF3;
4
+ const _CMD_HT_HOLD = 0xE5;
5
+ const _CMD_HT_NOHOLD = 0xF5;
6
+ const _CMD_READ_REG = 0xA7;
7
+ const _CMD_WRITE_REG = 0xA6;
8
+ const _CMD_STOP_PERIODIC = 0x30;
9
+ const _CMD_READ_ID = 0xD7;
10
+ const _CMD_SOFT_RESET = 0xFE;
11
+
12
+ const _REG_RESOLUTION = 0x00;
13
+ const _REG_PERIODIC = 0x02;
14
+ const _REG_ALERT_EN = 0x03;
15
+
16
+ // [low-byte register, high-byte register] of each 14-bit threshold
17
+ const _THRESHOLDS = {
18
+ rhHigh: [0x0F, 0x10], rhHighReset: [0x0D, 0x0E],
19
+ rhLow: [0x11, 0x12], rhLowReset: [0x13, 0x14],
20
+ tempHigh: [0x07, 0x08], tempHighReset: [0x05, 0x06],
21
+ tempLow: [0x09, 0x0A], tempLowReset: [0x0B, 0x0C],
22
+ };
23
+
24
+ const _BITS = [8, 10, 12, 14];
25
+ const _FULL_SCALE = 16383.0;
26
+
27
+ const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
28
+
29
+ function _crc8(data) {
30
+ let crc = 0xFF;
31
+ for (const byte of data) {
32
+ crc ^= byte;
33
+ for (let i = 0; i < 8; i++) crc = (crc & 0x80) ? ((crc << 1) ^ 0x1D) & 0xFF : (crc << 1) & 0xFF;
34
+ }
35
+ return crc;
36
+ }
37
+
38
+ function _checkCrc(frame) {
39
+ // Temperature-only frames (3 bytes) take the humidity bytes as zero.
40
+ const data = frame.length === 3 ? Buffer.from([0, 0, frame[0], frame[1]]) : frame.subarray(0, 4);
41
+ return _crc8(data) === frame[frame.length - 1];
42
+ }
43
+
44
+ const _rawHumidity = (f) => ((f[0] & 0x3F) << 8) | f[1];
45
+ const _rawTemperature = (f, o = 2) => ((f[o] & 0x3F) << 8) | f[o + 1];
46
+ const _toHumidity = (raw) => raw / _FULL_SCALE * 100.0;
47
+ const _toTemperature = (raw) => raw / _FULL_SCALE * 165.0 - 40.0;
48
+
49
+ /**
50
+ * HS40xx humidity and temperature sensor — minimal interface.
51
+ *
52
+ * Covers the Renesas HS4001 and HS4003, which share one protocol (HS4002 and the HS401x
53
+ * variants differ only physically and get no separate class). Each `read()` sends the no-hold
54
+ * humidity + temperature command (0xF5), waits 3 ms, reads five bytes (retrying while the
55
+ * sensor NACKs the read header), verifies the CRC-8 and converts. A CRC mismatch is retried once.
56
+ *
57
+ * The constructor performs no bus access.
58
+ *
59
+ * Default configuration (power-on): 14-bit resolution, one-shot no-hold measurements, CRC
60
+ * checked, periodic mode and alerts off.
61
+ */
62
+ class HS40xxMinimal {
63
+ /**
64
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C connection pointing at the device (address 0x54).
65
+ */
66
+ constructor(connection) {
67
+ this._conn = connection;
68
+ }
69
+
70
+ async _readFrame(length, timeoutMs = 20) {
71
+ // The sensor NACKs the read header while converting; retry until it answers.
72
+ const deadline = Date.now() + timeoutMs;
73
+ for (;;) {
74
+ try {
75
+ return Buffer.from(await this._conn.read(length));
76
+ } catch (e) {
77
+ if (Date.now() >= deadline) throw e;
78
+ await _sleep(1);
79
+ }
80
+ }
81
+ }
82
+
83
+ async _measure(cmd, length, hold = false) {
84
+ for (let attempt = 0; attempt < 2; attempt++) {
85
+ await this._conn.write(Buffer.from([cmd]));
86
+ if (!hold) await _sleep(3);
87
+ const frame = await this._readFrame(length);
88
+ if (_checkCrc(frame)) return frame;
89
+ }
90
+ throw new Error('HS40xx CRC mismatch');
91
+ }
92
+
93
+ /**
94
+ * Measure temperature and humidity (no-hold 0xF5, 5 bytes, CRC verified).
95
+ * @returns {Promise<{temperature_c: number, humidity_pct: number}>} Temperature in °C (-40 to 125) and relative humidity in %RH (0 to 100).
96
+ * @throws {Error} If the CRC is wrong after one retry, or the sensor keeps NACKing for more than 20 ms.
97
+ */
98
+ async read() {
99
+ const f = await this._measure(_CMD_HT_NOHOLD, 5);
100
+ return { temperature_c: _toTemperature(_rawTemperature(f)), humidity_pct: _toHumidity(_rawHumidity(f)) };
101
+ }
102
+ }
103
+
104
+ /**
105
+ * HS40xx full interface — single values, hold mode, resolution, periodic mode, alerts, ID.
106
+ *
107
+ * Extends `HS40xxMinimal`. Registers are volatile: they return to their defaults whenever the
108
+ * supply is cut or after `softReset()`.
109
+ */
110
+ class HS40xxFull extends HS40xxMinimal {
111
+ /** @param {import('../../connection/connection').Connection} connection - Configured I²C connection (address 0x54). */
112
+ constructor(connection) {
113
+ super(connection);
114
+ this._alertsEnabled = false;
115
+ this._periodS = 1;
116
+ this._activeHigh = true;
117
+ this._callback = null;
118
+ this._edgeHandler = null;
119
+ this._intPin = null;
120
+ this._pollTimer = null;
121
+ }
122
+
123
+ /**
124
+ * Measure temperature only (no-hold 0xF3, 3 bytes, CRC verified).
125
+ * @returns {Promise<number>} Temperature in °C.
126
+ */
127
+ async readTemperature() {
128
+ const f = await this._measure(_CMD_T_NOHOLD, 3);
129
+ return _toTemperature(_rawTemperature(f, 0));
130
+ }
131
+
132
+ /**
133
+ * Measure humidity (uses the 0xF5 humidity + temperature command).
134
+ * @returns {Promise<number>} Relative humidity in %RH.
135
+ */
136
+ async readHumidity() {
137
+ return (await this.read()).humidity_pct;
138
+ }
139
+
140
+ /**
141
+ * Measure with the hold command 0xE5 (the sensor stretches SCL until done; needs a stretching-capable controller and SCL >= 200 kHz).
142
+ * @returns {Promise<{temperature_c: number, humidity_pct: number}>}
143
+ */
144
+ async readHold() {
145
+ const f = await this._measure(_CMD_HT_HOLD, 5, true);
146
+ return { temperature_c: _toTemperature(_rawTemperature(f)), humidity_pct: _toHumidity(_rawHumidity(f)) };
147
+ }
148
+
149
+ /**
150
+ * Measure and return the raw 14-bit values (CRC verified).
151
+ * @returns {Promise<{raw_humidity: number, raw_temperature: number}>}
152
+ */
153
+ async readRaw() {
154
+ const f = await this._measure(_CMD_HT_NOHOLD, 5);
155
+ return { raw_humidity: _rawHumidity(f), raw_temperature: _rawTemperature(f) };
156
+ }
157
+
158
+ /**
159
+ * Read one configuration register (command 0xA7 + address, then a 1-byte read).
160
+ * @param {number} reg - Register address (0x00 to 0x14).
161
+ * @returns {Promise<number>} Register value (0 to 255).
162
+ */
163
+ async readRegister(reg) {
164
+ await this._conn.write(Buffer.from([_CMD_READ_REG, reg]));
165
+ return (await this._readFrame(1))[0];
166
+ }
167
+
168
+ /**
169
+ * Write one configuration register (command 0xA6 + address + data).
170
+ * @param {number} reg - Register address (0x00 to 0x14).
171
+ * @param {number} value - Byte to write (0 to 255).
172
+ */
173
+ async writeRegister(reg, value) {
174
+ await this._conn.write(Buffer.from([_CMD_WRITE_REG, reg, value & 0xFF]));
175
+ }
176
+
177
+ async _modify(reg, mask, bits) {
178
+ const value = ((await this.readRegister(reg)) & ~mask & 0xFF) | (bits & mask);
179
+ await this.writeRegister(reg, value);
180
+ }
181
+
182
+ /**
183
+ * Set the measurement resolutions (register 0x00, read-modify-write).
184
+ * @param {number|null} humidityBits - 8, 10, 12 or 14, or null to leave unchanged.
185
+ * @param {number|null} temperatureBits - 8, 10, 12 or 14, or null to leave unchanged.
186
+ * @throws {RangeError} If a value is not 8, 10, 12 or 14.
187
+ */
188
+ async setResolution(humidityBits = null, temperatureBits = null) {
189
+ for (const bits of [humidityBits, temperatureBits]) {
190
+ if (bits !== null && bits !== undefined && !_BITS.includes(bits)) {
191
+ throw new RangeError('resolution must be 8, 10, 12 or 14 bits');
192
+ }
193
+ }
194
+ let mask = 0;
195
+ let value = 0;
196
+ if (humidityBits !== null && humidityBits !== undefined) { mask |= 0x0C; value |= _BITS.indexOf(humidityBits) << 2; }
197
+ if (temperatureBits !== null && temperatureBits !== undefined) { mask |= 0x03; value |= _BITS.indexOf(temperatureBits); }
198
+ if (mask) await this._modify(_REG_RESOLUTION, mask, value);
199
+ }
200
+
201
+ /**
202
+ * Read the measurement resolutions.
203
+ * @returns {Promise<{humidity_bits: number, temperature_bits: number}>} Each 8, 10, 12 or 14.
204
+ */
205
+ async getResolution() {
206
+ const reg = await this.readRegister(_REG_RESOLUTION);
207
+ return { humidity_bits: _BITS[(reg >> 2) & 3], temperature_bits: _BITS[reg & 3] };
208
+ }
209
+
210
+ /**
211
+ * Start periodic measurement mode (register 0x02 bit 7 plus the period).
212
+ * @param {number} [periodS=1] - Measurement period in seconds: 0.5, 1 or 2.5.
213
+ * @throws {RangeError} If the period is not supported.
214
+ */
215
+ async startPeriodic(periodS = 1) {
216
+ const code = { 0.5: 0, 1: 1, 2.5: 2 }[periodS];
217
+ if (code === undefined) throw new RangeError('periodS must be 0.5, 1 or 2.5');
218
+ this._alertsEnabled = ((await this.readRegister(_REG_ALERT_EN)) & 0x0F) !== 0;
219
+ this._periodS = periodS;
220
+ await this._modify(_REG_PERIODIC, 0xB0, 0x80 | (code << 4));
221
+ }
222
+
223
+ /** Leave periodic mode (command 0x30); the sensor then sleeps. */
224
+ async stopPeriodic() {
225
+ await this._conn.write(Buffer.from([_CMD_STOP_PERIODIC]));
226
+ }
227
+
228
+ /**
229
+ * Fetch the latest periodic result (a plain read; CRC verified). The frame has a leading
230
+ * status byte when any alert is enabled.
231
+ * @returns {Promise<{temperature_c: number, humidity_pct: number, status: number}>} Status is the SOURCE_* bitmask of the active alerts (0 when alerts are off).
232
+ * @throws {Error} If the CRC does not match.
233
+ */
234
+ async readPeriodic() {
235
+ let frame = await this._readFrame(this._alertsEnabled ? 6 : 5);
236
+ let status = 0;
237
+ if (this._alertsEnabled) {
238
+ status = frame[0] & 0x0F;
239
+ frame = frame.subarray(1);
240
+ }
241
+ if (!_checkCrc(frame)) throw new Error('HS40xx CRC mismatch');
242
+ return { temperature_c: _toTemperature(_rawTemperature(frame)), humidity_pct: _toHumidity(_rawHumidity(frame)), status };
243
+ }
244
+
245
+ /**
246
+ * Program alert trigger / reset thresholds; only the given ones are written.
247
+ * @param {{rhHigh?: number, rhHighReset?: number, rhLow?: number, rhLowReset?: number, tempHigh?: number, tempHighReset?: number, tempLow?: number, tempLowReset?: number}} thresholds - Humidity in %RH, temperature in °C.
248
+ */
249
+ async setAlertThresholds(thresholds = {}) {
250
+ for (const name of Object.keys(_THRESHOLDS)) {
251
+ const v = thresholds[name];
252
+ if (v === undefined || v === null) continue;
253
+ const raw = name.startsWith('rh') ? v / 100.0 * _FULL_SCALE : (v + 40.0) / 165.0 * _FULL_SCALE;
254
+ const word = Math.max(0, Math.min(16383, Math.round(raw)));
255
+ const [lowReg, highReg] = _THRESHOLDS[name];
256
+ await this.writeRegister(lowReg, word & 0xFF);
257
+ await this.writeRegister(highReg, word >> 8);
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Set the ALERT pin polarity (register 0x02 bit 0).
263
+ * @param {boolean} activeHigh - true for active high when triggered (default), false for active low.
264
+ */
265
+ async setAlertPolarity(activeHigh) {
266
+ this._activeHigh = !!activeHigh;
267
+ await this._modify(_REG_PERIODIC, 0x01, activeHigh ? 1 : 0);
268
+ }
269
+
270
+ /**
271
+ * Enable alert source(s) in register 0x03.
272
+ * @param {number} source - Bitmask of `HS40xxFull.SOURCE_*`.
273
+ */
274
+ async enableInterrupt(source) {
275
+ const value = (await this.readRegister(_REG_ALERT_EN)) | (source & 0x0F);
276
+ await this.writeRegister(_REG_ALERT_EN, value);
277
+ this._alertsEnabled = (value & 0x0F) !== 0;
278
+ }
279
+
280
+ /**
281
+ * Disable alert source(s) in register 0x03.
282
+ * @param {number} source - Bitmask of `HS40xxFull.SOURCE_*`.
283
+ */
284
+ async disableInterrupt(source) {
285
+ const value = (await this.readRegister(_REG_ALERT_EN)) & ~(source & 0x0F) & 0xFF;
286
+ await this.writeRegister(_REG_ALERT_EN, value);
287
+ this._alertsEnabled = (value & 0x0F) !== 0;
288
+ }
289
+
290
+ /**
291
+ * Fetch the latest periodic result and return the alert status; needs periodic mode with an alert source enabled.
292
+ * @returns {Promise<number>} Bitmask of `HS40xxFull.SOURCE_*` for the alerts currently active.
293
+ * @throws {Error} If no alert source is enabled or the CRC does not match.
294
+ */
295
+ async pollInterrupt() {
296
+ if (!this._alertsEnabled) throw new Error('HS40xx alerts are not enabled');
297
+ return (await this.readPeriodic()).status;
298
+ }
299
+
300
+ async _dispatch() {
301
+ if (!this._callback) return;
302
+ try {
303
+ this._callback(await this.pollInterrupt());
304
+ } catch (e) {
305
+ // ignore a failed poll
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Subscribe to the ALERT pin; falls back to polling at the periodic interval.
311
+ * @param {function(number): void} callback - Called with the status bitmask.
312
+ * @param {object} [intPin] - Optional InputPin; defaults to `connection.intPin`.
313
+ */
314
+ async onInterrupt(callback, intPin = null) {
315
+ this._callback = callback;
316
+ const pin = intPin || this._conn.intPin;
317
+ if (pin) {
318
+ this._intPin = pin;
319
+ this._edgeHandler = () => this._dispatch();
320
+ await pin.onEdge(this._edgeHandler, this._activeHigh ? 'rising' : 'falling');
321
+ } else {
322
+ let busy = false;
323
+ this._pollTimer = setInterval(async () => {
324
+ if (busy) return;
325
+ busy = true;
326
+ try { await this._dispatch(); } finally { busy = false; }
327
+ }, this._periodS * 1000);
328
+ }
329
+ }
330
+
331
+ /** Unsubscribe from the ALERT pin (or stop the polling task). */
332
+ async offInterrupt() {
333
+ this._callback = null;
334
+ if (this._intPin && this._edgeHandler) await this._intPin.offEdge(this._edgeHandler);
335
+ this._intPin = null;
336
+ this._edgeHandler = null;
337
+ if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
338
+ }
339
+
340
+ /**
341
+ * Read the 32-bit sensor ID (command 0xD7, 4 bytes MSB first).
342
+ * @returns {Promise<number>} Unique 32-bit device ID.
343
+ */
344
+ async readId() {
345
+ await this._conn.write(Buffer.from([_CMD_READ_ID]));
346
+ const d = await this._readFrame(4);
347
+ return ((d[0] << 24) | (d[1] << 16) | (d[2] << 8) | d[3]) >>> 0;
348
+ }
349
+
350
+ /** Stop periodic mode, send the soft reset (0xFE) and wait 500 ms. */
351
+ async softReset() {
352
+ await this.stopPeriodic();
353
+ await this._conn.write(Buffer.from([_CMD_SOFT_RESET]));
354
+ await _sleep(500);
355
+ this._alertsEnabled = false;
356
+ this._activeHigh = true;
357
+ }
358
+
359
+ /**
360
+ * Run one measurement and return the dew point (Magnus formula).
361
+ * @returns {Promise<number>} Dew point in °C; -273.15 if humidity is 0 %RH.
362
+ */
363
+ async dewPoint() {
364
+ const m = await this.read();
365
+ if (m.humidity_pct <= 0.0) return -273.15;
366
+ const gamma = Math.log(m.humidity_pct / 100.0) + 17.62 * m.temperature_c / (243.12 + m.temperature_c);
367
+ return 243.12 * gamma / (17.62 - gamma);
368
+ }
369
+ }
370
+
371
+ HS40xxFull.SOURCE_RH_LOW = 0x01;
372
+ HS40xxFull.SOURCE_RH_HIGH = 0x02;
373
+ HS40xxFull.SOURCE_TEMP_LOW = 0x04;
374
+ HS40xxFull.SOURCE_TEMP_HIGH = 0x08;
375
+
376
+ // HS4001 and HS4003 share one protocol, so they are plain aliases of the HS40xx drivers
377
+ // (HS4002 and the HS401x variants are only physically different).
378
+ module.exports = {
379
+ HS40xxMinimal, HS40xxFull,
380
+ HS4001Minimal: HS40xxMinimal, HS4003Minimal: HS40xxMinimal,
381
+ HS4001Full: HS40xxFull, HS4003Full: HS40xxFull,
382
+ };