periph 1.5.4 → 1.6.1

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 (73) hide show
  1. package/README.md +17 -0
  2. package/examples/gas/ccs811/complete.js +87 -0
  3. package/examples/gas/ccs811/demo.js +108 -0
  4. package/examples/gas/ccs811/minimal.js +20 -0
  5. package/examples/gas/rrh46410/complete.js +78 -0
  6. package/examples/gas/rrh46410/demo.js +86 -0
  7. package/examples/gas/rrh46410/minimal.js +21 -0
  8. package/examples/gas/rrh62000/complete.js +74 -0
  9. package/examples/gas/rrh62000/demo.js +87 -0
  10. package/examples/gas/rrh62000/minimal.js +22 -0
  11. package/examples/gas/scd30/complete.js +73 -0
  12. package/examples/gas/scd30/demo.js +102 -0
  13. package/examples/gas/scd30/minimal.js +20 -0
  14. package/examples/gas/scd40/complete.js +76 -0
  15. package/examples/gas/scd40/demo.js +109 -0
  16. package/examples/gas/scd40/minimal.js +20 -0
  17. package/examples/light/si1133/complete.js +89 -0
  18. package/examples/light/si1133/demo.js +93 -0
  19. package/examples/light/si1133/minimal.js +22 -0
  20. package/examples/light/si1145/complete.js +93 -0
  21. package/examples/light/si1145/demo.js +98 -0
  22. package/examples/light/si1145/minimal.js +22 -0
  23. package/examples/light/tsl2561/complete.js +74 -0
  24. package/examples/light/tsl2561/demo.js +46 -0
  25. package/examples/light/tsl2561/minimal.js +22 -0
  26. package/examples/light/tsl2591/complete.js +90 -0
  27. package/examples/light/tsl2591/demo.js +119 -0
  28. package/examples/light/tsl2591/minimal.js +22 -0
  29. package/examples/light/vcnl4040/complete.js +102 -0
  30. package/examples/light/vcnl4040/demo.js +125 -0
  31. package/examples/light/vcnl4040/minimal.js +25 -0
  32. package/examples/light/vcnl4200/complete.js +101 -0
  33. package/examples/light/vcnl4200/demo.js +126 -0
  34. package/examples/light/vcnl4200/minimal.js +25 -0
  35. package/examples/pressure/spl06/complete.js +81 -0
  36. package/examples/pressure/spl06/demo.js +106 -0
  37. package/examples/pressure/spl06/minimal.js +22 -0
  38. package/examples/rfid/pn532/complete.js +99 -0
  39. package/examples/rfid/pn532/demo.js +121 -0
  40. package/examples/rfid/pn532/minimal.js +22 -0
  41. package/examples/rfid/st25dv/complete.js +94 -0
  42. package/examples/rfid/st25dv/demo.js +121 -0
  43. package/examples/rfid/st25dv/minimal.js +21 -0
  44. package/examples/rtc/bq32000/complete.js +53 -0
  45. package/examples/rtc/bq32000/demo.js +77 -0
  46. package/examples/rtc/bq32000/minimal.js +20 -0
  47. package/examples/rtc/ds1307/complete.js +54 -0
  48. package/examples/rtc/ds1307/demo.js +96 -0
  49. package/examples/rtc/ds1307/minimal.js +20 -0
  50. package/examples/rtc/ds1371/complete.js +53 -0
  51. package/examples/rtc/ds1371/demo.js +85 -0
  52. package/examples/rtc/ds1371/minimal.js +25 -0
  53. package/package.json +1 -1
  54. package/src/chips/gas/ccs811.js +400 -0
  55. package/src/chips/gas/rrh46410.js +534 -0
  56. package/src/chips/gas/rrh62000.js +418 -0
  57. package/src/chips/gas/scd30.js +368 -0
  58. package/src/chips/gas/scd40.js +451 -0
  59. package/src/chips/light/si1133.js +583 -0
  60. package/src/chips/light/si1145.js +630 -0
  61. package/src/chips/light/tsl2561.js +445 -0
  62. package/src/chips/light/tsl2591.js +561 -0
  63. package/src/chips/light/vcnl4040.js +576 -0
  64. package/src/chips/light/vcnl4200.js +592 -0
  65. package/src/chips/pressure/spl06.js +461 -0
  66. package/src/chips/rfid/pn532.js +513 -0
  67. package/src/chips/rfid/st25dv.js +628 -0
  68. package/src/chips/rtc/bq32000.js +334 -0
  69. package/src/chips/rtc/ds1307.js +327 -0
  70. package/src/chips/rtc/ds1371.js +453 -0
  71. package/src/connection/i2c.js +46 -13
  72. package/src/connection/smbus.js +21 -8
  73. package/src/discovery/registry.js +17 -17
@@ -0,0 +1,453 @@
1
+ 'use strict';
2
+
3
+ const _REG_TOD0 = 0x00;
4
+ const _REG_WDALM0 = 0x04;
5
+ const _REG_CONTROL = 0x07;
6
+ const _REG_STATUS = 0x08;
7
+
8
+ const _CTRL_EOSC = 0x80;
9
+ const _CTRL_WACE = 0x40;
10
+ const _CTRL_WDALM = 0x20;
11
+ const _CTRL_INTCN = 0x08;
12
+ const _CTRL_RS = 0x06;
13
+ const _CTRL_AIE = 0x01;
14
+
15
+ const _STATUS_OSF = 0x80;
16
+ const _STATUS_AF = 0x01;
17
+
18
+ const _SQW_RATES = { 1: 0x00, 4096: 0x02, 8192: 0x04, 32768: 0x06 };
19
+ const _SECONDS_MAX = 0xFFFFFFFF;
20
+ const _COUNTER_MAX = 0xFFFFFF;
21
+ const _DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
22
+
23
+ function _check(name, value, low, high) {
24
+ if (!Number.isInteger(value) || value < low || value > high) {
25
+ throw new RangeError(`${name} must be ${low}-${high}`);
26
+ }
27
+ }
28
+
29
+ function _isLeap(year) {
30
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
31
+ }
32
+
33
+ /**
34
+ * Convert a Unix-time counter value to a UTC calendar date/time.
35
+ * @param {number} seconds - 0..4294967295.
36
+ * @returns {{year: number, month: number, day: number, weekday: number, hour: number, minute: number, second: number}}
37
+ * `weekday` is ISO 8601 (1=Monday..7=Sunday).
38
+ */
39
+ function secondsToDatetime(seconds) {
40
+ const days = Math.floor(seconds / 86400);
41
+ const rem = seconds % 86400;
42
+ // Civil-from-days (H. Hinnant); all values are non-negative here.
43
+ const z = days + 719468;
44
+ const era = Math.floor(z / 146097);
45
+ const doe = z - era * 146097;
46
+ const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
47
+ const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
48
+ const mp = Math.floor((5 * doy + 2) / 153);
49
+ const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
50
+ const month = mp < 10 ? mp + 3 : mp - 9;
51
+ const year = yoe + era * 400 + (month <= 2 ? 1 : 0);
52
+ return {
53
+ year, month, day,
54
+ weekday: (days + 3) % 7 + 1, // 1970-01-01 was a Thursday
55
+ hour: Math.floor(rem / 3600),
56
+ minute: Math.floor(rem / 60) % 60,
57
+ second: rem % 60,
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Convert a UTC calendar date/time to the Unix-time counter value.
63
+ * @param {number} year - 1970-2106.
64
+ * @param {number} month - 1-12.
65
+ * @param {number} day - 1..days in month.
66
+ * @param {number} hour - 0-23.
67
+ * @param {number} minute - 0-59.
68
+ * @param {number} second - 0-59.
69
+ * @returns {number} Seconds since 1970-01-01 00:00:00 UTC.
70
+ * @throws {RangeError} If a field is out of range or the result exceeds 32 bits.
71
+ */
72
+ function datetimeToSeconds(year, month, day, hour, minute, second) {
73
+ _check('year', year, 1970, 2106);
74
+ _check('month', month, 1, 12);
75
+ _check('day', day, 1, month === 2 && _isLeap(year) ? 29 : _DAYS_IN_MONTH[month - 1]);
76
+ _check('hour', hour, 0, 23);
77
+ _check('minute', minute, 0, 59);
78
+ _check('second', second, 0, 59);
79
+ const y = year - (month <= 2 ? 1 : 0);
80
+ const era = Math.floor(y / 400);
81
+ const yoe = y - era * 400;
82
+ const doy = Math.floor((153 * (month > 2 ? month - 3 : month + 9) + 2) / 5) + day - 1;
83
+ const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
84
+ const days = era * 146097 + doe - 719468;
85
+ const seconds = days * 86400 + hour * 3600 + minute * 60 + second;
86
+ if (seconds > _SECONDS_MAX) throw new RangeError('date/time must not be after 2106-02-07 06:28:15');
87
+ return seconds;
88
+ }
89
+
90
+ /**
91
+ * DS1371 I²C 32-bit binary counter watchdog clock (Maxim Integrated /
92
+ * Analog Devices) — minimal interface.
93
+ *
94
+ * A 32-bit binary seconds counter (no BCD calendar) plus a 24-bit counter
95
+ * that works as a periodic alarm, a watchdog or three bytes of RAM. Fixed
96
+ * I²C address 0x68 (shared with the DS1307, DS3231 and PCF8523 — no
97
+ * identity register). `init()` reads STATUS once and writes nothing; the
98
+ * power-up defaults (oscillator running, 32.768 kHz square wave, counter
99
+ * disabled) are left as found.
100
+ *
101
+ * Epoch convention: the counter is treated as Unix time (seconds since
102
+ * 1970-01-01 00:00:00 UTC), valid until 2106-02-07 06:28:15; calendar
103
+ * conversion is done in the driver (UTC, no leap seconds). `weekday` is
104
+ * ISO 8601 (1=Monday..7=Sunday).
105
+ */
106
+ class DS1371Minimal {
107
+ /**
108
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - I²C register connection at address 0x68.
109
+ */
110
+ constructor(connection) {
111
+ this._conn = connection;
112
+ }
113
+
114
+ async _readReg(reg) {
115
+ return (await this._conn.readReg(reg, 1))[0];
116
+ }
117
+
118
+ async _writeReg(reg, value) {
119
+ await this._conn.writeReg(reg, value & 0xFF);
120
+ }
121
+
122
+ /**
123
+ * Confirm the device answers by reading STATUS (no identity register, no writes).
124
+ * @returns {Promise<void>}
125
+ */
126
+ async init() {
127
+ await this._readReg(_REG_STATUS);
128
+ }
129
+
130
+ /**
131
+ * Read the 32-bit time-of-day counter in one 4-byte burst.
132
+ * @returns {Promise<number>} Seconds since the Unix epoch; check `oscillatorStopped()` (Full) for validity.
133
+ */
134
+ async getSeconds() {
135
+ const b = await this._conn.readReg(_REG_TOD0, 4);
136
+ return (b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24)) >>> 0;
137
+ }
138
+
139
+ /**
140
+ * Write the 32-bit counter in one transaction and clear OSF. The write
141
+ * resets the divider chain; the next increment follows one second later.
142
+ * @param {number} seconds - 0..4294967295 (Unix time).
143
+ * @returns {Promise<void>}
144
+ * @throws {RangeError} If seconds is out of range.
145
+ */
146
+ async setSeconds(seconds) {
147
+ _check('seconds', seconds, 0, _SECONDS_MAX);
148
+ await this._conn.writeReg(_REG_TOD0, Buffer.from([
149
+ seconds & 0xFF, (seconds >>> 8) & 0xFF, (seconds >>> 16) & 0xFF, (seconds >>> 24) & 0xFF]));
150
+ await this._writeReg(_REG_STATUS, _STATUS_AF); // OSF <- 0; writing AF = 1 leaves AF unchanged
151
+ }
152
+
153
+ /**
154
+ * Read the counter and convert it to a UTC calendar date/time (OSF is not checked).
155
+ * @returns {Promise<{year: number, month: number, day: number, weekday: number, hour: number, minute: number, second: number}>}
156
+ */
157
+ async getDatetime() {
158
+ return secondsToDatetime(await this.getSeconds());
159
+ }
160
+
161
+ /**
162
+ * Convert a UTC calendar date/time to seconds and write the counter (clears OSF).
163
+ * `weekday` is range-checked but otherwise ignored.
164
+ * @param {number} year - 1970-2106 (up to 2106-02-07 06:28:15).
165
+ * @param {number} month - 1-12.
166
+ * @param {number} day - 1..days in month.
167
+ * @param {number} weekday - 1-7 (ignored).
168
+ * @param {number} hour - 0-23.
169
+ * @param {number} minute - 0-59.
170
+ * @param {number} second - 0-59.
171
+ * @returns {Promise<void>}
172
+ * @throws {RangeError} If any field is out of range.
173
+ */
174
+ async setDatetime(year, month, day, weekday, hour, minute, second) {
175
+ _check('weekday', weekday, 1, 7);
176
+ await this.setSeconds(datetimeToSeconds(year, month, day, hour, minute, second));
177
+ }
178
+ }
179
+
180
+ /**
181
+ * DS1371 full interface — extends Minimal with oscillator control, the
182
+ * square wave, the periodic alarm, the watchdog, the 3-byte RAM and the
183
+ * interrupt API.
184
+ */
185
+ class DS1371Full extends DS1371Minimal {
186
+ /**
187
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - I²C register connection at address 0x68.
188
+ */
189
+ constructor(connection) {
190
+ super(connection);
191
+ this._callback = null;
192
+ this._edgeHandler = null;
193
+ this._pollTimer = null;
194
+ }
195
+
196
+ async _writeCounter(value) {
197
+ await this._conn.writeReg(_REG_WDALM0, Buffer.from([value & 0xFF, (value >> 8) & 0xFF, (value >> 16) & 0xFF]));
198
+ }
199
+
200
+ /**
201
+ * Report the oscillator stop flag.
202
+ * @returns {Promise<boolean>} True if the oscillator is or was stopped since OSF was last cleared.
203
+ */
204
+ async oscillatorStopped() {
205
+ return ((await this._readReg(_REG_STATUS)) & _STATUS_OSF) !== 0;
206
+ }
207
+
208
+ /**
209
+ * Clear OSF (AF is left unchanged).
210
+ * @returns {Promise<void>}
211
+ */
212
+ async clearOscillatorFlag() {
213
+ await this._writeReg(_REG_STATUS, _STATUS_AF);
214
+ }
215
+
216
+ /**
217
+ * Start the oscillator (EOSC = 0).
218
+ * @returns {Promise<void>}
219
+ */
220
+ async startOscillator() {
221
+ await this._writeReg(_REG_CONTROL, (await this._readReg(_REG_CONTROL)) & ~_CTRL_EOSC);
222
+ }
223
+
224
+ /**
225
+ * Stop the oscillator (EOSC = 1) for low-power standby; the counter halts and OSF is set.
226
+ * @returns {Promise<void>}
227
+ */
228
+ async stopOscillator() {
229
+ await this._writeReg(_REG_CONTROL, (await this._readReg(_REG_CONTROL)) | _CTRL_EOSC);
230
+ }
231
+
232
+ /**
233
+ * Output a square wave on SQW/INT, or turn it off.
234
+ * @param {number|null} frequencyHz - 1, 4096, 8192 or 32768 (INTCN = 0, RS2:RS1);
235
+ * `null` selects the interrupt mode with AIE = 0 so the pin stays high impedance.
236
+ * @returns {Promise<void>}
237
+ * @throws {RangeError} If frequencyHz is not a supported rate or null.
238
+ */
239
+ async setSquareWave(frequencyHz) {
240
+ if (frequencyHz !== null && frequencyHz !== undefined && !(frequencyHz in _SQW_RATES)) {
241
+ throw new RangeError('frequencyHz must be 1, 4096, 8192, 32768 or null');
242
+ }
243
+ const control = await this._readReg(_REG_CONTROL);
244
+ if (frequencyHz === null || frequencyHz === undefined) {
245
+ await this._writeReg(_REG_CONTROL, (control | _CTRL_INTCN) & ~_CTRL_AIE);
246
+ return;
247
+ }
248
+ await this._writeReg(_REG_CONTROL, (control & ~(_CTRL_INTCN | _CTRL_RS)) | _SQW_RATES[frequencyHz]);
249
+ }
250
+
251
+ /**
252
+ * Start the periodic alarm: AF is set every `seconds` seconds. Clears
253
+ * WACE and WD/ALM, writes the 24-bit value, then sets WACE = 1. With
254
+ * `enableInterrupt` also sets INTCN = AIE = 1 (SQW/INT low until AF is
255
+ * cleared), otherwise AIE = 0.
256
+ * @param {number} seconds - Alarm period, 1-16777215.
257
+ * @param {boolean} [enableInterrupt=true] - Drive SQW/INT on the alarm.
258
+ * @returns {Promise<void>}
259
+ * @throws {RangeError} If seconds is out of range.
260
+ */
261
+ async setAlarm(seconds, enableInterrupt = true) {
262
+ _check('seconds', seconds, 1, _COUNTER_MAX);
263
+ let control = (await this._readReg(_REG_CONTROL)) & ~(_CTRL_WACE | _CTRL_WDALM);
264
+ await this._writeReg(_REG_CONTROL, control);
265
+ await this._writeCounter(seconds);
266
+ control |= _CTRL_WACE;
267
+ if (enableInterrupt) control |= _CTRL_INTCN | _CTRL_AIE;
268
+ else control &= ~_CTRL_AIE;
269
+ await this._writeReg(_REG_CONTROL, control);
270
+ }
271
+
272
+ /**
273
+ * Arm the watchdog: timeout = ticks / 4096 s. Clears WACE, sets WD/ALM,
274
+ * writes the 24-bit value (WDS must be low meanwhile), then toggles WACE
275
+ * 0 -> 1 with INTCN = AIE = 1. On timeout AF is set and SQW/INT pulses
276
+ * low for 250 ms. Keep it alive with `feedWatchdog()` or a rising edge on WDS.
277
+ * @param {number} ticks - Timeout in 1/4096 s ticks, 1-16777215.
278
+ * @returns {Promise<void>}
279
+ * @throws {RangeError} If ticks is out of range.
280
+ */
281
+ async setWatchdog(ticks) {
282
+ _check('ticks', ticks, 1, _COUNTER_MAX);
283
+ const control = ((await this._readReg(_REG_CONTROL)) & ~_CTRL_WACE) | _CTRL_WDALM;
284
+ await this._writeReg(_REG_CONTROL, control);
285
+ await this._writeCounter(ticks);
286
+ await this._writeReg(_REG_CONTROL, control | _CTRL_WACE | _CTRL_INTCN | _CTRL_AIE);
287
+ }
288
+
289
+ /**
290
+ * Reload and restart the watchdog by reading one counter byte.
291
+ * @returns {Promise<void>}
292
+ */
293
+ async feedWatchdog() {
294
+ await this._readReg(_REG_WDALM0);
295
+ }
296
+
297
+ /**
298
+ * Read the 24-bit watchdog/alarm counter seed. Reading the counter
299
+ * reloads it, so in watchdog mode this also feeds the watchdog.
300
+ * @returns {Promise<number>} Counter value (seconds in alarm mode, 1/4096 s ticks in watchdog mode).
301
+ */
302
+ async getWatchdog() {
303
+ const b = await this._conn.readReg(_REG_WDALM0, 3);
304
+ return b[0] | (b[1] << 8) | (b[2] << 16);
305
+ }
306
+
307
+ /**
308
+ * Stop the alarm or watchdog (WACE = 0, AIE = 0).
309
+ * @returns {Promise<void>}
310
+ */
311
+ async disableAlarm() {
312
+ await this._writeReg(_REG_CONTROL, (await this._readReg(_REG_CONTROL)) & ~(_CTRL_WACE | _CTRL_AIE));
313
+ }
314
+
315
+ /**
316
+ * Report the alarm/watchdog flag.
317
+ * @returns {Promise<boolean>} True when the counter reached zero (AF = 1).
318
+ */
319
+ async alarmFlag() {
320
+ return ((await this._readReg(_REG_STATUS)) & _STATUS_AF) !== 0;
321
+ }
322
+
323
+ /**
324
+ * Clear AF (OSF is written back unchanged); a watchdog pulse is not shortened.
325
+ * @returns {Promise<void>}
326
+ */
327
+ async clearAlarmFlag() {
328
+ await this._writeReg(_REG_STATUS, (await this._readReg(_REG_STATUS)) & _STATUS_OSF);
329
+ }
330
+
331
+ /**
332
+ * Read the three watchdog/alarm bytes as RAM (only meaningful while WACE = 0).
333
+ * @returns {Promise<Buffer>} 3 bytes.
334
+ */
335
+ async readRam() {
336
+ return Buffer.from(await this._conn.readReg(_REG_WDALM0, 3));
337
+ }
338
+
339
+ /**
340
+ * Write the three watchdog/alarm bytes as RAM in one transaction (only while WACE = 0).
341
+ * @param {Buffer|Uint8Array|number[]} data - Exactly 3 bytes.
342
+ * @returns {Promise<void>}
343
+ * @throws {RangeError} If data is not 3 bytes long.
344
+ */
345
+ async writeRam(data) {
346
+ if (data.length !== 3) throw new RangeError('data must be 3 bytes');
347
+ await this._conn.writeReg(_REG_WDALM0, Buffer.from(data));
348
+ }
349
+
350
+ /**
351
+ * Read the CONTROL register.
352
+ * @returns {Promise<number>} Raw CONTROL byte (EOSC bit 7, WACE 6, WD/ALM 5, INTCN 3, RS2:RS1 2:1, AIE 0).
353
+ */
354
+ async getControl() {
355
+ return this._readReg(_REG_CONTROL);
356
+ }
357
+
358
+ /**
359
+ * Read STATUS and clear AF if it is set.
360
+ * @returns {Promise<number>} Pre-clear STATUS byte — mask with `STATUS_ALARM` / `STATUS_OSC_STOP`.
361
+ */
362
+ async pollInterrupt() {
363
+ const status = await this._readReg(_REG_STATUS);
364
+ if (status & _STATUS_AF) await this._writeReg(_REG_STATUS, status & _STATUS_OSF);
365
+ return status;
366
+ }
367
+
368
+ static _checkSource(source) {
369
+ if (source !== DS1371Full.SOURCE_ALARM && source !== DS1371Full.SOURCE_WATCHDOG) {
370
+ throw new RangeError('source must be SOURCE_ALARM or SOURCE_WATCHDOG');
371
+ }
372
+ }
373
+
374
+ /**
375
+ * Select the counter mode for `source`, set INTCN = AIE = 1 and toggle
376
+ * WACE 0 -> 1 so a value written earlier by `setAlarm()`/`setWatchdog()` runs.
377
+ * @param {number} source - `DS1371Full.SOURCE_ALARM` or `SOURCE_WATCHDOG`.
378
+ * @returns {Promise<void>}
379
+ * @throws {RangeError} For any other value.
380
+ */
381
+ async enableInterrupt(source) {
382
+ DS1371Full._checkSource(source);
383
+ let control = (await this._readReg(_REG_CONTROL)) & ~(_CTRL_WACE | _CTRL_WDALM);
384
+ if (source === DS1371Full.SOURCE_WATCHDOG) control |= _CTRL_WDALM;
385
+ await this._writeReg(_REG_CONTROL, control);
386
+ await this._writeReg(_REG_CONTROL, control | _CTRL_WACE | _CTRL_INTCN | _CTRL_AIE);
387
+ }
388
+
389
+ /**
390
+ * Disable the alarm/watchdog interrupt (AIE = WACE = INTCN = 0); SQW/INT
391
+ * returns to the square wave.
392
+ * @param {number} source - `DS1371Full.SOURCE_ALARM` or `SOURCE_WATCHDOG`.
393
+ * @returns {Promise<void>}
394
+ * @throws {RangeError} For any other value.
395
+ */
396
+ async disableInterrupt(source) {
397
+ DS1371Full._checkSource(source);
398
+ await this._writeReg(_REG_CONTROL,
399
+ (await this._readReg(_REG_CONTROL)) & ~(_CTRL_AIE | _CTRL_WACE | _CTRL_INTCN));
400
+ }
401
+
402
+ /**
403
+ * Subscribe to alarm/watchdog interrupts. Uses `connection.intPin.onEdge()`
404
+ * (falling edge on SQW/INT) when an INT-line InputPin is wired; falls back
405
+ * to a 5 ms polling loop otherwise.
406
+ * @param {function(number): void} callback - Called with the pre-clear STATUS byte when AF was set.
407
+ * @returns {Promise<void>}
408
+ */
409
+ async onInterrupt(callback) {
410
+ this._callback = callback;
411
+ const dispatch = async () => {
412
+ const status = await this.pollInterrupt();
413
+ if ((status & _STATUS_AF) && this._callback) this._callback(status);
414
+ };
415
+ if (this._conn.intPin) {
416
+ this._edgeHandler = dispatch;
417
+ await this._conn.intPin.onEdge(this._edgeHandler, 'falling');
418
+ } else {
419
+ this._pollTimer = setInterval(dispatch, 5);
420
+ }
421
+ }
422
+
423
+ /**
424
+ * Unsubscribe and stop delivery.
425
+ * @returns {Promise<void>}
426
+ */
427
+ async offInterrupt() {
428
+ if (this._conn.intPin && this._edgeHandler) {
429
+ await this._conn.intPin.offEdge(this._edgeHandler);
430
+ this._edgeHandler = null;
431
+ }
432
+ if (this._pollTimer) {
433
+ clearInterval(this._pollTimer);
434
+ this._pollTimer = null;
435
+ }
436
+ this._callback = null;
437
+ }
438
+ }
439
+
440
+ /** Fixed 7-bit I²C address. */
441
+ DS1371Minimal.I2C_ADDRESS = 0x68;
442
+ /** Interrupt source: periodic alarm (WD/ALM = 0, one-second tick). */
443
+ DS1371Full.SOURCE_ALARM = 0x01;
444
+ /** Interrupt source: watchdog timeout (WD/ALM = 1, 1/4096 s tick, 250 ms pulse). */
445
+ DS1371Full.SOURCE_WATCHDOG = 0x02;
446
+ /** STATUS bit 7 — oscillator stop flag. */
447
+ DS1371Full.STATUS_OSC_STOP = 0x80;
448
+ /** STATUS bit 0 — alarm/watchdog flag. */
449
+ DS1371Full.STATUS_ALARM = 0x01;
450
+ /** Largest value of the 24-bit watchdog/alarm counter. */
451
+ DS1371Full.COUNTER_MAX = _COUNTER_MAX;
452
+
453
+ module.exports = { DS1371Minimal, DS1371Full, secondsToDatetime, datetimeToSeconds };
@@ -3,6 +3,25 @@
3
3
  const i2c = require('i2c-bus');
4
4
  const { RegisterConnection } = require('./register_connection');
5
5
 
6
+ /** Largest read readI2cBlockSync (SMBus I²C block read) can do in one transaction. */
7
+ const I2C_BLOCK_MAX = 32;
8
+
9
+ /**
10
+ * Throw if an i2c-bus call moved fewer bytes than requested. i2c-bus already
11
+ * throws (with errno) when the underlying read()/write()/ioctl() fails; this
12
+ * catches the short transfer it reports only through its return value.
13
+ * @param {string} what - Call name for the message, e.g. 'i2cReadSync(0x48)'.
14
+ * @param {number} got - Bytes the call reported.
15
+ * @param {number} want - Bytes requested.
16
+ */
17
+ function checkCount(what, got, want) {
18
+ if (got !== want) {
19
+ const err = new Error(`${what} transferred ${got} of ${want} bytes`);
20
+ err.code = 'EIO';
21
+ throw err;
22
+ }
23
+ }
24
+
6
25
  /**
7
26
  * I²C connection for Node.js (wraps i2c-bus, uses /dev/i2c-N on Linux).
8
27
  *
@@ -29,7 +48,8 @@ class I2CConnection extends RegisterConnection {
29
48
  * @param {Buffer|Uint8Array} data - Bytes to write.
30
49
  */
31
50
  async _write(data) {
32
- this._bus.i2cWriteSync(this._addr, data.length, data);
51
+ const buf = Buffer.from(data);
52
+ checkCount(this._what('i2cWriteSync'), this._bus.i2cWriteSync(this._addr, buf.length, buf), buf.length);
33
53
  }
34
54
 
35
55
  /**
@@ -39,27 +59,40 @@ class I2CConnection extends RegisterConnection {
39
59
  */
40
60
  async _read(n) {
41
61
  const buf = Buffer.alloc(n);
42
- this._bus.i2cReadSync(this._addr, n, buf);
62
+ checkCount(this._what('i2cReadSync'), this._bus.i2cReadSync(this._addr, n, buf), n);
43
63
  return buf;
44
64
  }
45
65
 
46
66
  /**
47
- * Write a single register address byte then read data back (repeated start).
67
+ * Write register/command bytes then read data back.
48
68
  *
49
- * Uses readI2cBlockSync, which accepts exactly one command byte. Only
50
- * data[0] is sent; any additional bytes in data are ignored. This is a
51
- * library constraint: i2c-bus v5 has no synchronous multi-message transfer
52
- * API (I2C_RDWR with multiple messages), so multi-byte writes before the
53
- * repeated start are not supported in synchronous mode.
69
+ * i2c-bus has no synchronous combined (I2C_RDWR) transfer, so:
70
+ * - one command byte and at most 32 bytes to read: readI2cBlockSync, a single
71
+ * transaction with a repeated START between the phases;
72
+ * - anything else (multi-byte register addresses, reads over 32 bytes): the
73
+ * full `data` is written, then `n` bytes are read, as two transactions
74
+ * (STOP + START). No bytes of `data` are dropped.
54
75
  *
55
- * @param {Buffer|Uint8Array} data - Register address to send; only data[0] is used.
76
+ * Either way a short transfer throws.
77
+ *
78
+ * @param {Buffer|Uint8Array} data - Register/command bytes to send.
56
79
  * @param {number} n - Number of bytes to read back.
57
80
  * @returns {Buffer} Data received from the device.
58
81
  */
59
82
  async _writeRead(data, n) {
60
- const buf = Buffer.alloc(n);
61
- this._bus.readI2cBlockSync(this._addr, data[0], n, buf);
62
- return buf;
83
+ if (data.length === 1 && n <= I2C_BLOCK_MAX) {
84
+ const buf = Buffer.alloc(n);
85
+ checkCount(this._what('readI2cBlockSync'),
86
+ this._bus.readI2cBlockSync(this._addr, data[0], n, buf), n);
87
+ return buf;
88
+ }
89
+ await this._write(data);
90
+ return this._read(n);
91
+ }
92
+
93
+ /** @private Call name plus device address for error messages. */
94
+ _what(call) {
95
+ return `${call}(0x${this._addr.toString(16).padStart(2, '0')})`;
63
96
  }
64
97
 
65
98
  /**
@@ -70,4 +103,4 @@ class I2CConnection extends RegisterConnection {
70
103
  }
71
104
  }
72
105
 
73
- module.exports = { I2CConnection };
106
+ module.exports = { I2CConnection, checkCount, I2C_BLOCK_MAX };
@@ -2,6 +2,7 @@
2
2
 
3
3
  const i2c = require('i2c-bus');
4
4
  const { RegisterConnection } = require('./register_connection');
5
+ const { checkCount, I2C_BLOCK_MAX } = require('./i2c');
5
6
 
6
7
  /**
7
8
  * Computes CRC-8 with polynomial 0x07 (x⁸ + x² + x + 1), initial value 0x00.
@@ -57,7 +58,7 @@ class SMBusConnection extends RegisterConnection {
57
58
  const pec = crc8(Buffer.concat([Buffer.from([this._addr << 1]), buf]));
58
59
  buf = Buffer.concat([buf, Buffer.from([pec])]);
59
60
  }
60
- this._bus.i2cWriteSync(this._addr, buf.length, buf);
61
+ checkCount(this._what('i2cWriteSync'), this._bus.i2cWriteSync(this._addr, buf.length, buf), buf.length);
61
62
  }
62
63
 
63
64
  /**
@@ -72,7 +73,7 @@ class SMBusConnection extends RegisterConnection {
72
73
  async _read(n) {
73
74
  const count = this._pec ? n + 1 : n;
74
75
  const buf = Buffer.alloc(count);
75
- this._bus.i2cReadSync(this._addr, count, buf);
76
+ checkCount(this._what('i2cReadSync'), this._bus.i2cReadSync(this._addr, count, buf), count);
76
77
  if (this._pec) {
77
78
  const data = buf.slice(0, n);
78
79
  const expected = crc8(Buffer.concat([Buffer.from([(this._addr << 1) | 1]), data]));
@@ -83,21 +84,28 @@ class SMBusConnection extends RegisterConnection {
83
84
  }
84
85
 
85
86
  /**
86
- * Write a register address byte then read data back (repeated start), with optional PEC.
87
+ * Write register/command bytes then read data back, with optional PEC.
87
88
  *
88
- * PEC covers the full transaction: write address + write data +
89
- * read address + read data. The same single-command-byte limitation as
90
- * I2CConnection applies: only data[0] is sent as the write byte.
89
+ * One command byte and at most 32 bytes to read (PEC byte included) use
90
+ * readI2cBlockSync: one transaction with a repeated START, and the PEC covers
91
+ * write address + command + read address + read data. Anything else is a
92
+ * write (with its own PEC) followed by a read (with its own PEC) as two
93
+ * transactions; no bytes of `data` are dropped. A short transfer throws.
91
94
  *
92
- * @param {Buffer|Uint8Array} data - Register address to send; only data[0] is used.
95
+ * @param {Buffer|Uint8Array} data - Register/command bytes to send.
93
96
  * @param {number} n - Number of data bytes to read back.
94
97
  * @returns {Buffer} The n data bytes (PEC byte stripped if enabled).
95
98
  * @throws {Error} If the received PEC byte does not match.
96
99
  */
97
100
  async _writeRead(data, n) {
98
101
  const count = this._pec ? n + 1 : n;
102
+ if (data.length !== 1 || count > I2C_BLOCK_MAX) {
103
+ await this._write(data);
104
+ return this._read(n);
105
+ }
99
106
  const buf = Buffer.alloc(count);
100
- this._bus.readI2cBlockSync(this._addr, data[0], count, buf);
107
+ checkCount(this._what('readI2cBlockSync'),
108
+ this._bus.readI2cBlockSync(this._addr, data[0], count, buf), count);
101
109
  if (this._pec) {
102
110
  const payload = buf.slice(0, n);
103
111
  const expected = crc8(Buffer.concat([
@@ -112,6 +120,11 @@ class SMBusConnection extends RegisterConnection {
112
120
  return buf;
113
121
  }
114
122
 
123
+ /** @private Call name plus device address for error messages. */
124
+ _what(call) {
125
+ return `${call}(0x${this._addr.toString(16).padStart(2, '0')})`;
126
+ }
127
+
115
128
  /**
116
129
  * Close the I²C bus. Must be called when the connection is no longer needed.
117
130
  */