periph 1.4.0 → 1.5.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 (112) hide show
  1. package/README.md +27 -0
  2. package/examples/adc_dac/ad5251/complete.js +66 -0
  3. package/examples/adc_dac/ad5251/demo.js +69 -0
  4. package/examples/adc_dac/ad5251/minimal.js +23 -0
  5. package/examples/adc_dac/ad5252/complete.js +66 -0
  6. package/examples/adc_dac/ad5252/demo.js +69 -0
  7. package/examples/adc_dac/ad5252/minimal.js +23 -0
  8. package/examples/adc_dac/ads7828/complete.js +46 -0
  9. package/examples/adc_dac/ads7828/demo.js +45 -0
  10. package/examples/adc_dac/ads7828/minimal.js +17 -0
  11. package/examples/adc_dac/cat5171/complete.js +52 -0
  12. package/examples/adc_dac/cat5171/demo.js +59 -0
  13. package/examples/adc_dac/cat5171/minimal.js +23 -0
  14. package/examples/adc_dac/cs43l22/complete.js +88 -0
  15. package/examples/adc_dac/cs43l22/demo.js +56 -0
  16. package/examples/adc_dac/cs43l22/minimal.js +20 -0
  17. package/examples/adc_dac/ds1881/complete.js +62 -0
  18. package/examples/adc_dac/ds1881/demo.js +61 -0
  19. package/examples/adc_dac/ds1881/minimal.js +25 -0
  20. package/examples/adc_dac/ds3502/complete.js +46 -0
  21. package/examples/adc_dac/ds3502/demo.js +54 -0
  22. package/examples/adc_dac/ds3502/minimal.js +28 -0
  23. package/examples/adc_dac/mcp3422/complete.js +48 -0
  24. package/examples/adc_dac/mcp3422/demo.js +49 -0
  25. package/examples/adc_dac/mcp3422/minimal.js +25 -0
  26. package/examples/display/sh1106/complete.js +101 -0
  27. package/examples/display/sh1106/demo.js +68 -0
  28. package/examples/display/sh1106/minimal.js +25 -0
  29. package/examples/display/ssd1305/complete.js +129 -0
  30. package/examples/display/ssd1305/demo.js +71 -0
  31. package/examples/display/ssd1305/minimal.js +25 -0
  32. package/examples/display/ssd1306/complete.js +115 -0
  33. package/examples/display/ssd1306/demo.js +70 -0
  34. package/examples/display/ssd1306/minimal.js +25 -0
  35. package/examples/environmental/am2315/complete.js +34 -0
  36. package/examples/environmental/am2315/demo.js +46 -0
  37. package/examples/environmental/am2315/minimal.js +21 -0
  38. package/examples/humidity/htu21df/complete.js +49 -0
  39. package/examples/humidity/htu21df/demo.js +50 -0
  40. package/examples/humidity/htu21df/minimal.js +22 -0
  41. package/examples/humidity/sht31/complete.js +53 -0
  42. package/examples/humidity/sht31/demo.js +53 -0
  43. package/examples/humidity/sht31/minimal.js +21 -0
  44. package/examples/humidity/si7021/complete.js +55 -0
  45. package/examples/humidity/si7021/demo.js +58 -0
  46. package/examples/humidity/si7021/minimal.js +21 -0
  47. package/examples/imu/bno055/complete.js +85 -0
  48. package/examples/imu/bno055/demo.js +70 -0
  49. package/examples/imu/bno055/minimal.js +20 -0
  50. package/examples/io_expander/pca6408a/complete.js +63 -0
  51. package/examples/io_expander/pca6408a/demo.js +58 -0
  52. package/examples/io_expander/pca6408a/minimal.js +20 -0
  53. package/examples/io_expander/pca6416a/complete.js +68 -0
  54. package/examples/io_expander/pca6416a/demo.js +60 -0
  55. package/examples/io_expander/pca6416a/minimal.js +20 -0
  56. package/examples/io_expander/pca9536/complete.js +63 -0
  57. package/examples/io_expander/pca9536/demo.js +57 -0
  58. package/examples/io_expander/pca9536/minimal.js +20 -0
  59. package/examples/io_expander/pca9539/complete.js +68 -0
  60. package/examples/io_expander/pca9539/demo.js +60 -0
  61. package/examples/io_expander/pca9539/minimal.js +20 -0
  62. package/examples/light/max44009/complete.js +56 -0
  63. package/examples/light/max44009/demo.js +49 -0
  64. package/examples/light/max44009/minimal.js +22 -0
  65. package/examples/memory/at24c02n/complete.js +39 -0
  66. package/examples/memory/at24c02n/demo.js +39 -0
  67. package/examples/memory/at24c02n/minimal.js +15 -0
  68. package/examples/memory/at24c64/complete.js +39 -0
  69. package/examples/memory/at24c64/demo.js +39 -0
  70. package/examples/memory/at24c64/minimal.js +15 -0
  71. package/examples/memory/cat24c512/complete.js +39 -0
  72. package/examples/memory/cat24c512/demo.js +39 -0
  73. package/examples/memory/cat24c512/minimal.js +15 -0
  74. package/examples/other/pca9541/complete.js +52 -0
  75. package/examples/other/pca9541/demo.js +61 -0
  76. package/examples/other/pca9541/minimal.js +23 -0
  77. package/examples/temperature/tmp102/complete.js +74 -0
  78. package/examples/temperature/tmp102/demo.js +71 -0
  79. package/examples/temperature/tmp102/minimal.js +20 -0
  80. package/examples/tof/vl6180x/complete.js +62 -0
  81. package/examples/tof/vl6180x/demo.js +77 -0
  82. package/examples/tof/vl6180x/minimal.js +23 -0
  83. package/package.json +1 -1
  84. package/src/chips/adc_dac/ad5251.js +345 -0
  85. package/src/chips/adc_dac/ad5252.js +345 -0
  86. package/src/chips/adc_dac/ads7828.js +225 -0
  87. package/src/chips/adc_dac/cat5171.js +213 -0
  88. package/src/chips/adc_dac/cs43l22.js +645 -0
  89. package/src/chips/adc_dac/ds1881.js +357 -0
  90. package/src/chips/adc_dac/ds3502.js +241 -0
  91. package/src/chips/adc_dac/mcp3422.js +312 -0
  92. package/src/chips/display/mono_oled.js +182 -0
  93. package/src/chips/display/sh1106.js +496 -0
  94. package/src/chips/display/ssd1305.js +655 -0
  95. package/src/chips/display/ssd1306.js +458 -0
  96. package/src/chips/environmental/am2315.js +237 -0
  97. package/src/chips/humidity/htu21df.js +222 -0
  98. package/src/chips/humidity/sht31.js +284 -0
  99. package/src/chips/humidity/si7021.js +282 -0
  100. package/src/chips/imu/bno055.js +496 -0
  101. package/src/chips/io_expander/pca6408a.js +407 -0
  102. package/src/chips/io_expander/pca6416a.js +455 -0
  103. package/src/chips/io_expander/pca9536.js +398 -0
  104. package/src/chips/io_expander/pca9539.js +457 -0
  105. package/src/chips/light/max44009.js +336 -0
  106. package/src/chips/memory/at24c02n.js +220 -0
  107. package/src/chips/memory/at24c64.js +220 -0
  108. package/src/chips/memory/cat24c512.js +221 -0
  109. package/src/chips/other/pca9541.js +315 -0
  110. package/src/chips/temperature/tmp102.js +361 -0
  111. package/src/chips/tof/vl6180x.js +580 -0
  112. package/src/discovery/registry.js +65 -13
@@ -0,0 +1,336 @@
1
+ 'use strict';
2
+
3
+ const REG_INT_STATUS = 0x00;
4
+ const REG_INT_ENABLE = 0x01;
5
+ const REG_CONFIG = 0x02;
6
+ const REG_LUX_HIGH = 0x03;
7
+ const REG_LUX_LOW = 0x04;
8
+ const REG_UPPER = 0x05;
9
+ const REG_LOWER = 0x06;
10
+ const REG_TIMER = 0x07;
11
+
12
+ const CFG_CONT = 0x80;
13
+ const CFG_MANUAL = 0x40;
14
+ const CFG_CDR = 0x08;
15
+ const CFG_TIM_MASK = 0x07;
16
+
17
+ const LUX_PER_LSB = 0.045;
18
+ const MAX_LUX = 188006.4; // E = 14, M = 255
19
+ const OVERRANGE_EXP = 15;
20
+ const INTEGRATION_MS = [800.0, 400.0, 200.0, 100.0, 50.0, 25.0, 12.5, 6.25];
21
+ const POLL_INTERVAL_MS = 100;
22
+
23
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
24
+
25
+ function _luxFrom(exponent, mantissa) {
26
+ if (exponent >= OVERRANGE_EXP) return MAX_LUX;
27
+ return (2 ** exponent) * mantissa * LUX_PER_LSB;
28
+ }
29
+
30
+ function _encodeThreshold(lux) {
31
+ if (lux < 11.5) return Math.min(15, Math.round(lux / (16 * LUX_PER_LSB)));
32
+ let exponent = 1;
33
+ let mantissa = 0;
34
+ for (exponent = 1; exponent <= 14; exponent++) {
35
+ mantissa = lux / ((2 ** exponent) * LUX_PER_LSB);
36
+ if (mantissa < 256) break;
37
+ }
38
+ if (exponent > 14) exponent = 14;
39
+ mantissa = Math.max(128, Math.min(255, Math.floor(mantissa)));
40
+ return Math.min(0xEF, (exponent << 4) | (mantissa >> 4));
41
+ }
42
+
43
+ function _decodeThreshold(code, upper) {
44
+ const exponent = code >> 4;
45
+ const nibble = code & 0x0F;
46
+ return (2 ** exponent) * ((nibble << 4) | (upper ? 0x0F : 0x00)) * LUX_PER_LSB;
47
+ }
48
+
49
+ /**
50
+ * MAX44009 ultra-low-power ambient light sensor with ADC (Maxim / Analog
51
+ * Devices) — minimal interface.
52
+ *
53
+ * An on-chip photodiode with automatic ranging reports the illuminance as a
54
+ * 12-bit floating-point value (4-bit exponent, 8-bit mantissa):
55
+ * `lux = 2^E * M * 0.045`, from 0.045 lx to 188 006.4 lx. The I²C address is
56
+ * 0x4A (A0 = GND) or 0x4B (A0 = VCC). A `RegisterConnection` read ends with a
57
+ * STOP, so the lux registers are read as high, low, high and repeated once if
58
+ * the high byte changed in between.
59
+ */
60
+ class MAX44009Minimal {
61
+ /**
62
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - I²C register connection (1-byte register address).
63
+ */
64
+ constructor(connection) {
65
+ this._conn = connection;
66
+ this._lastExponent = 0;
67
+ }
68
+
69
+ /** 7-bit I²C address with A0 = GND. */
70
+ static get I2C_ADDRESS() { return 0x4A; }
71
+
72
+ /** 7-bit I²C address with A0 = VCC. */
73
+ static get I2C_ADDRESS_A0_HIGH() { return 0x4B; }
74
+
75
+ async _readReg(reg) {
76
+ return (await this._conn.readReg(reg, 1))[0];
77
+ }
78
+
79
+ async _writeReg(reg, value) {
80
+ await this._conn.writeReg(reg, value & 0xFF);
81
+ }
82
+
83
+ async _readLuxRegs() {
84
+ let high = await this._readReg(REG_LUX_HIGH);
85
+ let low = await this._readReg(REG_LUX_LOW);
86
+ const high2 = await this._readReg(REG_LUX_HIGH);
87
+ if (high2 !== high) {
88
+ high = high2;
89
+ low = await this._readReg(REG_LUX_LOW);
90
+ }
91
+ const exponent = high >> 4;
92
+ const mantissa = ((high & 0x0F) << 4) | (low & 0x0F);
93
+ this._lastExponent = exponent;
94
+ return { exponent, mantissa };
95
+ }
96
+
97
+ /**
98
+ * Run the initialization sequence: write the reset state (interrupt off,
99
+ * CONFIG 0x03, thresholds fully open, timer 0xFF), read INT_STATUS once to
100
+ * clear a stale interrupt and wait 900 ms (`MAX44009Minimal.initWaitMs`) so the
101
+ * first `lux()` returns a real measurement.
102
+ * @returns {Promise<void>}
103
+ */
104
+ async init() {
105
+ await this._writeReg(REG_INT_ENABLE, 0x00);
106
+ await this._writeReg(REG_CONFIG, 0x03);
107
+ await this._writeReg(REG_UPPER, 0xFF);
108
+ await this._writeReg(REG_LOWER, 0x00);
109
+ await this._writeReg(REG_TIMER, 0xFF);
110
+ await this._readReg(REG_INT_STATUS);
111
+ if (MAX44009Minimal.initWaitMs > 0) await sleep(MAX44009Minimal.initWaitMs);
112
+ }
113
+
114
+ /**
115
+ * Read the ambient illuminance.
116
+ * @returns {Promise<number>} Illuminance in lux (`2^E * M * 0.045`); the maximum 188006.4 lx on overrange (E = 15).
117
+ */
118
+ async lux() {
119
+ const { exponent, mantissa } = await this._readLuxRegs();
120
+ return _luxFrom(exponent, mantissa);
121
+ }
122
+ }
123
+
124
+ /** Wait after init so the first lux() returns a real measurement, in ms (tests may set it to 0). */
125
+ MAX44009Minimal.initWaitMs = 900;
126
+
127
+ /**
128
+ * MAX44009 full interface — extends Minimal with raw readings, measurement
129
+ * mode and range configuration, interrupt thresholds and delay, and interrupt
130
+ * delivery.
131
+ */
132
+ class MAX44009Full extends MAX44009Minimal {
133
+ constructor(connection) {
134
+ super(connection);
135
+ this._callback = null;
136
+ this._intPinUsed = null;
137
+ this._pollTimer = null;
138
+ this._polling = false;
139
+ this._edgeHandler = () => { this._service(); };
140
+ }
141
+
142
+ /** Status bit 0: light level outside the threshold window for longer than the delay. */
143
+ static get SOURCE_THRESHOLD() { return 0x01; }
144
+
145
+ /**
146
+ * Read the lux registers as one consistent sample.
147
+ * @returns {Promise<{exponent: number, mantissa: number, overrange: boolean}>} Exponent 0–15, 8-bit mantissa, overrange = (E = 15).
148
+ */
149
+ async readRaw() {
150
+ const { exponent, mantissa } = await this._readLuxRegs();
151
+ return { exponent, mantissa, overrange: exponent >= OVERRANGE_EXP };
152
+ }
153
+
154
+ /**
155
+ * Whether the last reading was overrange (E = 15).
156
+ * @returns {boolean}
157
+ */
158
+ isOverrange() {
159
+ return this._lastExponent >= OVERRANGE_EXP;
160
+ }
161
+
162
+ /**
163
+ * Lux per mantissa LSB for the last reading, `2^E * 0.045`.
164
+ * @returns {number}
165
+ */
166
+ resolution() {
167
+ return (2 ** Math.min(this._lastExponent, 14)) * LUX_PER_LSB;
168
+ }
169
+
170
+ async _updateConfig(setBits, clearBits) {
171
+ const cfg = await this._readReg(REG_CONFIG);
172
+ await this._writeReg(REG_CONFIG, (cfg & ~clearBits) | setBits);
173
+ }
174
+
175
+ /**
176
+ * Select continuous or low-power measurement mode.
177
+ * @param {boolean} continuous - true: a new measurement as soon as one finishes; false: one per 800 ms.
178
+ * @returns {Promise<void>}
179
+ */
180
+ async setContinuous(continuous) {
181
+ await this._updateConfig(continuous ? CFG_CONT : 0, CFG_CONT);
182
+ }
183
+
184
+ /**
185
+ * Select automatic mode (the chip chooses current divider and integration time).
186
+ * @returns {Promise<void>}
187
+ */
188
+ async setAutomatic() {
189
+ await this._updateConfig(0, CFG_MANUAL);
190
+ }
191
+
192
+ /**
193
+ * Select manual mode.
194
+ * @param {number} integrationMs - Integration time; rounded to the nearest of 800, 400, 200, 100, 50, 25, 12.5, 6.25 ms.
195
+ * @param {boolean} [divideBy8=false] - true to divide the photodiode current by 8 (high brightness).
196
+ * @returns {Promise<void>}
197
+ */
198
+ async setManual(integrationMs, divideBy8 = false) {
199
+ let best = 0;
200
+ let bestErr = Math.abs(INTEGRATION_MS[0] - integrationMs);
201
+ for (let tim = 1; tim < 8; tim++) {
202
+ const err = Math.abs(INTEGRATION_MS[tim] - integrationMs);
203
+ if (err < bestErr) { best = tim; bestErr = err; }
204
+ }
205
+ const cfg = await this._readReg(REG_CONFIG);
206
+ await this._writeReg(REG_CONFIG, (cfg & CFG_CONT) | CFG_MANUAL | (divideBy8 ? CFG_CDR : 0) | best);
207
+ }
208
+
209
+ /**
210
+ * Read the CONFIG register.
211
+ * @returns {Promise<{continuous: boolean, manual: boolean, divideBy8: boolean, integrationMs: number}>}
212
+ */
213
+ async getConfig() {
214
+ const cfg = await this._readReg(REG_CONFIG);
215
+ return {
216
+ continuous: Boolean(cfg & CFG_CONT),
217
+ manual: Boolean(cfg & CFG_MANUAL),
218
+ divideBy8: Boolean(cfg & CFG_CDR),
219
+ integrationMs: INTEGRATION_MS[cfg & CFG_TIM_MASK],
220
+ };
221
+ }
222
+
223
+ /**
224
+ * Set the interrupt threshold window.
225
+ * @param {number} lowLux - Lower threshold in lux.
226
+ * @param {number} highLux - Upper threshold in lux.
227
+ * @returns {Promise<void>}
228
+ * @throws {RangeError} if lowLux is greater than highLux.
229
+ */
230
+ async setThresholds(lowLux, highLux) {
231
+ if (lowLux > highLux) throw new RangeError('lowLux must not exceed highLux');
232
+ await this._writeReg(REG_LOWER, _encodeThreshold(lowLux));
233
+ await this._writeReg(REG_UPPER, _encodeThreshold(highLux));
234
+ }
235
+
236
+ /**
237
+ * Read the interrupt threshold window (the upper one carries the implied low nibble 1111).
238
+ * @returns {Promise<{lowLux: number, highLux: number}>}
239
+ */
240
+ async getThresholds() {
241
+ const low = await this._readReg(REG_LOWER);
242
+ const high = await this._readReg(REG_UPPER);
243
+ return { lowLux: _decodeThreshold(low, false), highLux: _decodeThreshold(high, true) };
244
+ }
245
+
246
+ /**
247
+ * Set how long the light must stay outside the window before the interrupt.
248
+ * @param {number} seconds - Delay in seconds, 0–25.5 (0.1 s steps).
249
+ * @returns {Promise<void>}
250
+ */
251
+ async setThresholdDelay(seconds) {
252
+ await this._writeReg(REG_TIMER, Math.max(0, Math.min(255, Math.round(seconds / 0.1))));
253
+ }
254
+
255
+ /**
256
+ * Read the threshold delay.
257
+ * @returns {Promise<number>} Delay in seconds.
258
+ */
259
+ async getThresholdDelay() {
260
+ return (await this._readReg(REG_TIMER)) * 0.1;
261
+ }
262
+
263
+ /**
264
+ * Enable the interrupt (INT_ENABLE = 1).
265
+ * @returns {Promise<void>}
266
+ */
267
+ async enableInterrupt() {
268
+ await this._writeReg(REG_INT_ENABLE, 0x01);
269
+ }
270
+
271
+ /**
272
+ * Disable the interrupt (INT_ENABLE = 0; also clears a pending status).
273
+ * @returns {Promise<void>}
274
+ */
275
+ async disableInterrupt() {
276
+ await this._writeReg(REG_INT_ENABLE, 0x00);
277
+ }
278
+
279
+ /**
280
+ * Read INT_STATUS (clearing it).
281
+ * @returns {Promise<number>} Status; bit 0 (SOURCE_THRESHOLD) set if the light was outside the window for longer than the delay.
282
+ */
283
+ async pollInterrupt() {
284
+ return (await this._readReg(REG_INT_STATUS)) & 0x01;
285
+ }
286
+
287
+ async _arm(intPin) {
288
+ this._intPinUsed = intPin;
289
+ if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
290
+ if (intPin) {
291
+ await intPin.onEdge(this._edgeHandler, 'falling');
292
+ } else {
293
+ this._pollTimer = setInterval(() => { this._service(); }, POLL_INTERVAL_MS);
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Subscribe to INT assertions. `callback(status)` is called after the driver
299
+ * has read (and thereby cleared) INT_STATUS. Delivery is via the INT line
300
+ * (options.intPin or connection.intPin, falling edge) or a 100 ms polling timer.
301
+ * @param {function} callback - Called with (status).
302
+ * @param {object} [options]
303
+ * @param {import('../../connection/input_pin').InputPin|null} [options.intPin] - Overrides connection.intPin.
304
+ * @returns {Promise<void>}
305
+ */
306
+ async onInterrupt(callback, options = {}) {
307
+ this._callback = callback;
308
+ await this._arm(options.intPin ?? this._conn.intPin ?? null);
309
+ }
310
+
311
+ /**
312
+ * Unsubscribe and stop delivery.
313
+ * @returns {Promise<void>}
314
+ */
315
+ async offInterrupt() {
316
+ if (this._intPinUsed) {
317
+ await this._intPinUsed.offEdge(this._edgeHandler);
318
+ this._intPinUsed = null;
319
+ }
320
+ if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
321
+ this._callback = null;
322
+ }
323
+
324
+ async _service() {
325
+ if (this._polling) return;
326
+ this._polling = true;
327
+ try {
328
+ const status = await this.pollInterrupt();
329
+ if (status && this._callback) this._callback(status);
330
+ } finally {
331
+ this._polling = false;
332
+ }
333
+ }
334
+ }
335
+
336
+ module.exports = { MAX44009Minimal, MAX44009Full };
@@ -0,0 +1,220 @@
1
+ 'use strict';
2
+
3
+ const SIZE = 0x0100;
4
+ const PAGE = 8;
5
+ const WRITE_TIMEOUT_MS = 10; // tWR = 5 ms max, plus margin
6
+
7
+ const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8
+
9
+ function _checkAddress(address) {
10
+ if (!Number.isInteger(address) || address < 0 || address >= SIZE) {
11
+ throw new RangeError('address out of range 0-255');
12
+ }
13
+ }
14
+
15
+ function _checkRange(address, length) {
16
+ if (!Number.isInteger(address) || !Number.isInteger(length) ||
17
+ length < 0 || address < 0 || address + length > SIZE) {
18
+ throw new RangeError('range outside 0-255');
19
+ }
20
+ }
21
+
22
+ /**
23
+ * AT24C02N 2 Kbit (256 B) I2C EEPROM — minimal interface.
24
+ *
25
+ * Self-timed writes (5 ms max) are completed by ACK polling: after every
26
+ * write the driver polls the device address until the chip answers again, so
27
+ * a resolved write is always committed. The chip has no configuration
28
+ * registers; it is ready after power-up.
29
+ *
30
+ * Memory layout: 0x00-0x00FF, 8-bit address, big-endian on the wire,
31
+ * 8 pages of 8 bytes.
32
+ *
33
+ * Writes are ignored by the chip while the WP pin is high (hardware only;
34
+ * the driver cannot detect it — verify with a read-back if WP is wired).
35
+ */
36
+ class AT24C02NMinimal {
37
+ /**
38
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - I²C or SMBus register connection with regBytes=1, pointing at the device (address 0x50-0x57).
39
+ */
40
+ constructor(connection) {
41
+ this._conn = connection;
42
+ }
43
+
44
+ /** ACK-poll: an address-only write is acknowledged once the write cycle has ended. */
45
+ async _waitReady(timeoutMs) {
46
+ const deadline = Date.now() + timeoutMs;
47
+ for (;;) {
48
+ try {
49
+ await this._conn.writeReg(0, Buffer.alloc(0));
50
+ return true;
51
+ } catch (e) {
52
+ // NACK while the write cycle is running
53
+ }
54
+ if (Date.now() >= deadline) return false;
55
+ await _sleep(1);
56
+ }
57
+ }
58
+
59
+ async _commit() {
60
+ if (!(await this._waitReady(WRITE_TIMEOUT_MS))) {
61
+ throw new Error('AT24C02N write cycle did not complete');
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Read a single byte (random read).
67
+ * @param {number} address - Memory address 0-255.
68
+ * @returns {Promise<number>} Byte value 0-255.
69
+ * @throws {RangeError} If the address is outside 0-255.
70
+ */
71
+ async readByte(address) {
72
+ _checkAddress(address);
73
+ return (await this._conn.readReg(address, 1))[0];
74
+ }
75
+
76
+ /**
77
+ * Write a single byte, then ACK-poll until the write cycle completes.
78
+ * @param {number} address - Memory address 0-255.
79
+ * @param {number} value - Byte value 0-255.
80
+ * @returns {Promise<void>}
81
+ * @throws {RangeError} If the address is outside 0-255.
82
+ * @throws {Error} If the chip does not answer again within the write-cycle timeout.
83
+ */
84
+ async writeByte(address, value) {
85
+ _checkAddress(address);
86
+ await this._conn.writeReg(address, value & 0xFF);
87
+ await this._commit();
88
+ }
89
+ }
90
+
91
+ /**
92
+ * AT24C02N full interface — extends minimal with block access and page writes.
93
+ *
94
+ * Writes are split at 8-byte page boundaries (a write crossing a boundary
95
+ * would wrap inside the page and corrupt data); ranges that would run past
96
+ * 0x00FF are rejected instead of wrapping to 0x0000 as the hardware would.
97
+ *
98
+ */
99
+ class AT24C02NFull extends AT24C02NMinimal {
100
+ /**
101
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - I²C or SMBus register connection with regBytes=1 (address 0x50-0x57).
102
+ */
103
+ constructor(connection) {
104
+ super(connection);
105
+ this._maxChunk = 30;
106
+ }
107
+
108
+ /**
109
+ * Maximum data bytes per bus transaction (default 30; Arduino Wire limits transfers to 32 bytes including the address byte).
110
+ * @type {number}
111
+ */
112
+ get maxChunk() { return this._maxChunk; }
113
+
114
+ set maxChunk(value) {
115
+ if (!Number.isInteger(value) || value < 1) throw new RangeError('maxChunk must be >= 1');
116
+ this._maxChunk = value;
117
+ }
118
+
119
+ /**
120
+ * Array size in bytes.
121
+ * @returns {number} 256.
122
+ */
123
+ size() { return SIZE; }
124
+
125
+ /**
126
+ * Write page size in bytes.
127
+ * @returns {number} 8.
128
+ */
129
+ pageSize() { return PAGE; }
130
+
131
+ /**
132
+ * ACK-poll until the chip answers its device address again.
133
+ * @param {number} timeoutMs - Maximum time to poll in milliseconds.
134
+ * @returns {Promise<boolean>} True if the chip responded within the timeout.
135
+ */
136
+ async waitReady(timeoutMs) {
137
+ return this._waitReady(timeoutMs);
138
+ }
139
+
140
+ /**
141
+ * Sequential read, split into transactions of at most maxChunk bytes.
142
+ * @param {number} address - Starting address 0-255.
143
+ * @param {number} length - Number of bytes to read.
144
+ * @returns {Promise<Buffer>} `length` bytes.
145
+ * @throws {RangeError} If address..address+length is not inside 0x00-0x00FF.
146
+ */
147
+ async read(address, length) {
148
+ _checkRange(address, length);
149
+ const parts = [];
150
+ while (length > 0) {
151
+ const n = Math.min(length, this._maxChunk);
152
+ parts.push(await this._conn.readReg(address, n));
153
+ address += n;
154
+ length -= n;
155
+ }
156
+ return Buffer.concat(parts);
157
+ }
158
+
159
+ /**
160
+ * Write one page (or part of it) in a single transaction, then ACK-poll.
161
+ * @param {number} address - Starting address 0-255.
162
+ * @param {Buffer|number[]} data - 1-8 bytes, all inside the same 8-byte page.
163
+ * @returns {Promise<void>}
164
+ * @throws {RangeError} If the data crosses a page boundary, is longer than a page, or runs outside 0x00-0x00FF.
165
+ */
166
+ async writePage(address, data) {
167
+ const buf = Buffer.from(data);
168
+ _checkRange(address, buf.length);
169
+ if (buf.length > PAGE || (address % PAGE) + buf.length > PAGE) {
170
+ throw new RangeError('write crosses a page boundary');
171
+ }
172
+ if (buf.length === 0) return;
173
+ await this._conn.writeReg(address, buf);
174
+ await this._commit();
175
+ }
176
+
177
+ /**
178
+ * Write `data` starting at `address`, split at page boundaries. Each chunk is
179
+ * at most maxChunk bytes and never crosses a 8-byte page boundary; the write
180
+ * cycle is ACK-polled after every chunk.
181
+ * @param {number} address - Starting address 0-255.
182
+ * @param {Buffer|number[]} data - Bytes to write.
183
+ * @returns {Promise<void>}
184
+ * @throws {RangeError} If address..address+data.length is not inside 0x00-0x00FF.
185
+ */
186
+ async write(address, data) {
187
+ const buf = Buffer.from(data);
188
+ _checkRange(address, buf.length);
189
+ let off = 0;
190
+ while (off < buf.length) {
191
+ const room = PAGE - ((address + off) % PAGE);
192
+ const n = Math.min(room, this._maxChunk, buf.length - off);
193
+ await this._conn.writeReg(address + off, buf.subarray(off, off + n));
194
+ await this._commit();
195
+ off += n;
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Write `value` over a range, page by page.
201
+ * @param {number} address - Starting address 0-255.
202
+ * @param {number} length - Number of bytes to fill.
203
+ * @param {number} [value=0] - Byte value 0-255.
204
+ * @returns {Promise<void>}
205
+ * @throws {RangeError} If address..address+length is not inside 0x00-0x00FF.
206
+ */
207
+ async fill(address, length, value = 0) {
208
+ _checkRange(address, length);
209
+ let done = 0;
210
+ while (done < length) {
211
+ const room = PAGE - ((address + done) % PAGE);
212
+ const n = Math.min(room, this._maxChunk, length - done);
213
+ await this._conn.writeReg(address + done, Buffer.alloc(n, value & 0xFF));
214
+ await this._commit();
215
+ done += n;
216
+ }
217
+ }
218
+ }
219
+
220
+ module.exports = { AT24C02NMinimal, AT24C02NFull };