periph 1.2.0 → 1.3.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 (153) hide show
  1. package/README.md +18 -0
  2. package/examples/accelerometer/bma150/complete.js +62 -0
  3. package/examples/accelerometer/bma150/demo.js +65 -0
  4. package/examples/accelerometer/bma150/minimal.js +18 -0
  5. package/examples/adc_dac/hy3131/complete.js +66 -0
  6. package/examples/adc_dac/hy3131/demo.js +37 -0
  7. package/examples/adc_dac/hy3131/minimal.js +18 -0
  8. package/examples/discovery/complete.js +25 -0
  9. package/examples/discovery/demo.js +30 -0
  10. package/examples/discovery/minimal.js +12 -0
  11. package/examples/display/il0373/complete.js +71 -0
  12. package/examples/display/il0373/demo.js +49 -0
  13. package/examples/display/il0373/minimal.js +26 -0
  14. package/examples/display/ssd1331/complete.js +83 -0
  15. package/examples/display/ssd1331/demo.js +49 -0
  16. package/examples/display/ssd1331/minimal.js +27 -0
  17. package/examples/display/st7036/complete.js +71 -0
  18. package/examples/display/st7036/demo.js +56 -0
  19. package/examples/display/st7036/minimal.js +21 -0
  20. package/examples/display/uc1611s/complete.js +135 -0
  21. package/examples/display/uc1611s/complete_spi.js +128 -0
  22. package/examples/display/uc1611s/demo.js +90 -0
  23. package/examples/display/uc1611s/demo_spi.js +91 -0
  24. package/examples/display/uc1611s/minimal.js +28 -0
  25. package/examples/display/uc1611s/minimal_spi.js +30 -0
  26. package/examples/display/uc8159/complete.js +64 -0
  27. package/examples/display/uc8159/demo.js +41 -0
  28. package/examples/display/uc8159/minimal.js +28 -0
  29. package/examples/display/uc8276c/complete.js +73 -0
  30. package/examples/display/uc8276c/demo.js +49 -0
  31. package/examples/display/uc8276c/minimal.js +26 -0
  32. package/examples/environmental/bme280/complete.js +1 -1
  33. package/examples/environmental/bme280/demo.js +1 -1
  34. package/examples/environmental/bme280/minimal.js +1 -1
  35. package/examples/gyroscope/l3g4200d/complete.js +1 -1
  36. package/examples/gyroscope/l3g4200d/demo.js +1 -1
  37. package/examples/gyroscope/l3g4200d/minimal.js +1 -1
  38. package/examples/memory/23x1024/complete.js +54 -0
  39. package/examples/memory/23x1024/demo.js +51 -0
  40. package/examples/memory/23x1024/minimal.js +22 -0
  41. package/examples/memory/mx25l12845e/complete.js +66 -0
  42. package/examples/memory/mx25l12845e/demo.js +66 -0
  43. package/examples/memory/mx25l12845e/minimal.js +27 -0
  44. package/examples/memory/sd_spi/complete.js +55 -0
  45. package/examples/memory/sd_spi/demo.js +67 -0
  46. package/examples/memory/sd_spi/minimal.js +32 -0
  47. package/examples/motor/drv8830/complete.js +50 -0
  48. package/examples/motor/drv8830/demo.js +57 -0
  49. package/examples/motor/drv8830/minimal.js +23 -0
  50. package/examples/pressure/bmp280/complete.js +1 -1
  51. package/examples/pressure/bmp280/demo.js +1 -1
  52. package/examples/pressure/bmp280/minimal.js +1 -1
  53. package/examples/pressure/bmp581/complete.js +1 -1
  54. package/examples/pressure/bmp581/demo.js +1 -1
  55. package/examples/pressure/bmp581/minimal.js +1 -1
  56. package/examples/pressure/lps22df/complete.js +1 -1
  57. package/examples/pressure/lps22df/demo.js +1 -1
  58. package/examples/pressure/lps22df/minimal.js +1 -1
  59. package/examples/rtc/ds3231/complete.js +77 -0
  60. package/examples/rtc/ds3231/demo.js +60 -0
  61. package/examples/rtc/ds3231/minimal.js +23 -0
  62. package/examples/rtc/pcf8523/complete.js +66 -0
  63. package/examples/rtc/pcf8523/demo.js +65 -0
  64. package/examples/rtc/pcf8523/minimal.js +20 -0
  65. package/examples/temperature/mcp9808/complete.js +89 -0
  66. package/examples/temperature/mcp9808/demo.js +62 -0
  67. package/examples/temperature/mcp9808/minimal.js +21 -0
  68. package/examples/temperature/tmp117/complete.js +90 -0
  69. package/examples/temperature/tmp117/demo.js +73 -0
  70. package/examples/temperature/tmp117/minimal.js +21 -0
  71. package/examples/tof/vl53l0x/complete.js +118 -0
  72. package/examples/tof/vl53l0x/demo.js +83 -0
  73. package/examples/tof/vl53l0x/minimal.js +25 -0
  74. package/examples/tof/vl53l1x/complete.js +151 -0
  75. package/examples/tof/vl53l1x/demo.js +100 -0
  76. package/examples/tof/vl53l1x/minimal.js +25 -0
  77. package/package.json +1 -1
  78. package/src/chips/accelerometer/adxl345.js +10 -31
  79. package/src/chips/accelerometer/adxl362.js +7 -7
  80. package/src/chips/accelerometer/bma150.js +419 -0
  81. package/src/chips/adc_dac/ad7705.js +36 -9
  82. package/src/chips/adc_dac/ad7706.js +39 -9
  83. package/src/chips/adc_dac/hy3131.js +311 -0
  84. package/src/chips/display/il0373.js +607 -0
  85. package/src/chips/display/ssd1331.js +412 -0
  86. package/src/chips/display/st7036.js +401 -0
  87. package/src/chips/display/uc1611s.js +648 -0
  88. package/src/chips/display/uc8159.js +394 -0
  89. package/src/chips/display/uc8276c.js +658 -0
  90. package/src/chips/environmental/bme280.js +31 -46
  91. package/src/chips/environmental/bme680.js +38 -43
  92. package/src/chips/gas/ens160.js +18 -26
  93. package/src/chips/gyroscope/l3g4200d.js +34 -50
  94. package/src/chips/gyroscope/l3gd20h.js +24 -40
  95. package/src/chips/imu/mpu6050.js +29 -41
  96. package/src/chips/imu/mpu9250.js +45 -69
  97. package/src/chips/imu/mpu9255.js +54 -78
  98. package/src/chips/io_expander/mcp23017.js +24 -33
  99. package/src/chips/light/apds-9930.js +52 -60
  100. package/src/chips/light/apds9960.js +69 -77
  101. package/src/chips/magnetometer/as5600.js +13 -27
  102. package/src/chips/magnetometer/hmc5883l.js +32 -29
  103. package/src/chips/memory/_23x1024.js +228 -0
  104. package/src/chips/memory/_24aa02uid.js +8 -11
  105. package/src/chips/memory/mx25l12845e.js +467 -0
  106. package/src/chips/memory/sd_spi.js +486 -0
  107. package/src/chips/motor/drv8830.js +239 -0
  108. package/src/chips/other/mpr121.js +7 -7
  109. package/src/chips/power/ina219.js +5 -8
  110. package/src/chips/power/ina226.js +5 -8
  111. package/src/chips/power/ina3221.js +5 -8
  112. package/src/chips/pressure/bmp085.js +17 -11
  113. package/src/chips/pressure/bmp180.js +7 -7
  114. package/src/chips/pressure/bmp280.js +21 -33
  115. package/src/chips/pressure/bmp384.js +28 -39
  116. package/src/chips/pressure/bmp581.js +59 -70
  117. package/src/chips/pressure/lps22df.js +50 -52
  118. package/src/chips/pressure/lps28dfw.js +15 -13
  119. package/src/chips/pressure/lps33hw.js +7 -5
  120. package/src/chips/rtc/ds3231.js +504 -0
  121. package/src/chips/rtc/pcf8523.js +533 -0
  122. package/src/chips/temperature/mcp9808.js +490 -0
  123. package/src/chips/temperature/tmp117.js +471 -0
  124. package/src/chips/tof/_vl53_base.js +160 -0
  125. package/src/chips/tof/vl53l0x.js +816 -0
  126. package/src/chips/tof/vl53l1x.js +816 -0
  127. package/src/connection/connection.js +6 -4
  128. package/src/connection/dhtxx.js +5 -3
  129. package/src/connection/display.js +278 -0
  130. package/src/connection/display_mock.js +77 -0
  131. package/src/connection/hx711.js +5 -3
  132. package/src/connection/i2c.js +6 -4
  133. package/src/connection/i2c_mock.js +47 -0
  134. package/src/connection/input_pin.js +36 -5
  135. package/src/connection/register.js +14 -0
  136. package/src/connection/register_connection.js +65 -0
  137. package/src/connection/sipo.js +4 -2
  138. package/src/connection/sipo_mock.js +49 -0
  139. package/src/connection/smbus.js +6 -4
  140. package/src/connection/softspi.js +73 -0
  141. package/src/connection/spi.js +110 -23
  142. package/src/connection/spi_mock.js +50 -0
  143. package/src/connection/uart.js +2 -1
  144. package/src/discovery/discovery.js +218 -0
  145. package/src/discovery/registry.js +85 -0
  146. package/src/storage/block_device.js +95 -0
  147. package/src/storage/ram_block_device.js +72 -0
  148. package/examples/motor/.gitkeep +0 -0
  149. package/examples/temperature/.gitkeep +0 -0
  150. package/examples/tof/.gitkeep +0 -0
  151. package/src/chips/motor/.gitkeep +0 -0
  152. package/src/chips/temperature/.gitkeep +0 -0
  153. package/src/chips/tof/.gitkeep +0 -0
@@ -0,0 +1,486 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * SD / SDHC / SDXC / microSD card in SPI mode (specs/memory/sd_spi.md).
5
+ *
6
+ * `SDSPIMinimal` runs the SPI-mode init sequence in `init()` and offers single
7
+ * 512-byte block reads and writes. `SDSPIFull` adds multi-block transfers,
8
+ * erase, CID/CSD/OCR access and CRC checking, and implements the common
9
+ * `BlockDevice` contract (specs/feature_block_device.md).
10
+ *
11
+ * The connection must be an SPI connection with the optional extensions
12
+ * `idleClocks`, `setSpeed`, `select` / `deselect` and `readInto`
13
+ * (specs/transport_spi.md) and must clock 0xFF on MOSI while reading. Cards are
14
+ * 3.3 V only. Call `await sd.init()` before use (the constructor cannot await
15
+ * bus I/O).
16
+ */
17
+
18
+ const {
19
+ BlockDevice, NotReady, OutOfRange, Crc, Timeout, Io,
20
+ } = require('../../storage/block_device');
21
+
22
+ const CRC16_T = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
23
+ 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF];
24
+
25
+ const INIT_TIMEOUT_MS = 1000;
26
+ const TOKEN_TIMEOUT_MS = 200;
27
+ const BUSY_TIMEOUT_MS = 500;
28
+ const ERASE_TIMEOUT_MS = 30000;
29
+
30
+ const BLOCK_SIZE = 512;
31
+
32
+ /** Card generations returned by `cardType()`. */
33
+ const CardType = Object.freeze({ NONE: 0, SDV1: 1, SDV2: 2, SDHC: 3 });
34
+
35
+ /**
36
+ * CRC7 (polynomial x^7 + x^3 + 1) of `data`, not shifted.
37
+ * @param {Uint8Array} data
38
+ * @returns {number}
39
+ */
40
+ function crc7(data) {
41
+ let crc = 0;
42
+ for (let b of data) {
43
+ for (let i = 0; i < 8; i++) {
44
+ crc = (crc << 1) & 0xFF;
45
+ if ((b ^ crc) & 0x80) crc ^= 0x09;
46
+ b = (b << 1) & 0xFF;
47
+ }
48
+ }
49
+ return crc & 0x7F;
50
+ }
51
+
52
+ /**
53
+ * CRC16-CCITT (polynomial 0x1021, initial value 0) of `data`.
54
+ * @param {Uint8Array} data
55
+ * @returns {number}
56
+ */
57
+ function crc16(data) {
58
+ let crc = 0;
59
+ for (const b of data) {
60
+ crc ^= b << 8;
61
+ crc = ((crc << 4) & 0xFFFF) ^ CRC16_T[crc >> 12];
62
+ crc = ((crc << 4) & 0xFFFF) ^ CRC16_T[crc >> 12];
63
+ }
64
+ return crc;
65
+ }
66
+
67
+ /** SD card in SPI mode — minimal interface (init, single-block read/write). */
68
+ class SDSPIMinimal {
69
+ /**
70
+ * @param {object} connection - SPI connection with the optional extensions.
71
+ * @param {object} [options]
72
+ * @param {number} [options.speedHz=12000000] - Data-phase clock after init (init always runs at 400 kHz).
73
+ * @param {boolean} [options.crc=false] - Enable CMD59 and send/verify CRC16 on data blocks.
74
+ */
75
+ constructor(connection, options = {}) {
76
+ this._c = connection;
77
+ this._speed = options.speedHz ?? 12_000_000;
78
+ this._wantCrc = options.crc ?? false;
79
+ this._crcOn = false;
80
+ this._type = CardType.NONE;
81
+ this._blockAddressing = false;
82
+ this._blockCount = 0;
83
+ this._csd = Buffer.alloc(16);
84
+ }
85
+
86
+ // ---- bus primitives --------------------------------------------------
87
+
88
+ async _rx() {
89
+ return (await this._c.read(1))[0];
90
+ }
91
+
92
+ async _waitReady(ms) {
93
+ const start = Date.now();
94
+ for (;;) {
95
+ if ((await this._rx()) === 0xFF) return;
96
+ if (Date.now() - start >= ms) throw new Timeout('card busy');
97
+ }
98
+ }
99
+
100
+ async _release() {
101
+ await this._c.deselect();
102
+ await this._c.idleClocks(8); // let the card free MISO
103
+ }
104
+
105
+ /** Send a command with CS already selected; returns R1 (0xFF on no response). */
106
+ async _command(cmd, arg) {
107
+ if (cmd !== 12 && cmd !== 0) await this._waitReady(BUSY_TIMEOUT_MS);
108
+ const frame = Buffer.alloc(6);
109
+ frame[0] = 0x40 | cmd;
110
+ frame.writeUInt32BE(arg >>> 0, 1);
111
+ frame[5] = (crc7(frame.subarray(0, 5)) << 1) | 1;
112
+ await this._c.write(frame);
113
+ if (cmd === 12) await this._rx(); // discard the stuff byte that follows CMD12
114
+ for (let i = 0; i < 10; i++) { // Ncr <= 8 bytes
115
+ const r = await this._rx();
116
+ if (!(r & 0x80)) return r;
117
+ }
118
+ return 0xFF;
119
+ }
120
+
121
+ async _appCommand(cmd, arg) {
122
+ const r = await this._command(55, 0);
123
+ if (r > 1) return r;
124
+ return this._command(cmd, arg);
125
+ }
126
+
127
+ async _readData(length) {
128
+ const start = Date.now();
129
+ let token;
130
+ for (;;) {
131
+ token = await this._rx();
132
+ if (token !== 0xFF) break;
133
+ if (Date.now() - start >= TOKEN_TIMEOUT_MS) throw new Timeout('no data token');
134
+ }
135
+ if (token !== 0xFE) throw new Io(`data error token 0x${token.toString(16)}`);
136
+ const data = Buffer.alloc(length);
137
+ await this._c.readInto(data);
138
+ const crc = Buffer.alloc(2);
139
+ await this._c.readInto(crc);
140
+ if (this._crcOn && crc.readUInt16BE(0) !== crc16(data)) throw new Crc('data CRC16 mismatch');
141
+ return data;
142
+ }
143
+
144
+ async _writeData(token, data) {
145
+ await this._waitReady(BUSY_TIMEOUT_MS);
146
+ await this._c.write(Buffer.from([token]));
147
+ if (token === 0xFD) return; // stop-tran token has no payload
148
+ await this._c.write(data);
149
+ const crc = Buffer.from([0xFF, 0xFF]);
150
+ if (this._crcOn) crc.writeUInt16BE(crc16(data), 0);
151
+ await this._c.write(crc);
152
+ const resp = (await this._rx()) & 0x1F;
153
+ if (resp === 0x05) return;
154
+ if (resp === 0x0B) throw new Crc('write CRC rejected');
155
+ throw new Io(`write rejected 0x${resp.toString(16)}`);
156
+ }
157
+
158
+ async _readRegister(cmd) {
159
+ await this._c.select();
160
+ try {
161
+ if ((await this._command(cmd, 0)) !== 0) throw new Io(`CMD${cmd} failed`);
162
+ return await this._readData(16);
163
+ } finally {
164
+ await this._release();
165
+ }
166
+ }
167
+
168
+ _address(block) {
169
+ return this._blockAddressing ? block : block * BLOCK_SIZE;
170
+ }
171
+
172
+ // ---- init ------------------------------------------------------------
173
+
174
+ /**
175
+ * Run the SPI-mode init sequence (also usable to re-init a swapped card).
176
+ * @returns {Promise<void>}
177
+ * @throws {NotReady} No card responded, or the card is unsupported.
178
+ * @throws {Timeout} The card never left the idle state.
179
+ */
180
+ async init() {
181
+ this._type = CardType.NONE;
182
+ this._blockCount = 0;
183
+ this._crcOn = false;
184
+ await this._c.setSpeed(400_000);
185
+ await this._c.deselect();
186
+ await this._c.idleClocks(80);
187
+
188
+ let idle = false;
189
+ for (let i = 0; i < 10 && !idle; i++) { // CMD0 with CS low enters SPI mode; fresh cards need a few tries
190
+ await this._c.select();
191
+ try {
192
+ idle = (await this._command(0, 0)) === 0x01;
193
+ } finally {
194
+ await this._release();
195
+ }
196
+ }
197
+ if (!idle) throw new NotReady('no card responded to CMD0');
198
+
199
+ await this._c.select();
200
+ try {
201
+ let v2 = false;
202
+ const r = await this._command(8, 0x1AA);
203
+ if (r === 0x01) {
204
+ const r7 = await this._c.read(4);
205
+ if ((r7[2] & 0x0F) !== 0x01 || r7[3] !== 0xAA) throw new NotReady('CMD8 echo mismatch');
206
+ v2 = true;
207
+ } else if (!(r & 0x04)) { // anything but "illegal command" (v1 card) is a failure
208
+ throw new NotReady('CMD8 failed');
209
+ }
210
+
211
+ const start = Date.now();
212
+ for (;;) {
213
+ if ((await this._appCommand(41, v2 ? 0x40000000 : 0)) === 0x00) break;
214
+ if (Date.now() - start >= INIT_TIMEOUT_MS) throw new Timeout('ACMD41 never completed');
215
+ }
216
+
217
+ this._type = v2 ? CardType.SDV2 : CardType.SDV1;
218
+ this._blockAddressing = false;
219
+ if (v2 && (await this._command(58, 0)) === 0x00) {
220
+ const ocr = await this._c.read(4);
221
+ if (ocr[0] & 0x40) {
222
+ this._blockAddressing = true;
223
+ this._type = CardType.SDHC;
224
+ }
225
+ }
226
+ if (!this._blockAddressing) await this._command(16, BLOCK_SIZE);
227
+ if (this._wantCrc && (await this._command(59, 1)) === 0x00) this._crcOn = true;
228
+ } catch (e) {
229
+ this._type = CardType.NONE;
230
+ throw e;
231
+ } finally {
232
+ await this._release();
233
+ }
234
+
235
+ await this._c.setSpeed(this._speed);
236
+ this._csd = await this._readRegister(9);
237
+ this._blockCount = SDSPIMinimal._csdBlocks(this._csd);
238
+ }
239
+
240
+ static _csdBlocks(csd) {
241
+ if ((csd[0] >> 6) === 1) { // CSD v2: C_SIZE = CSD[69:48]
242
+ const csize = ((csd[7] & 0x3F) << 16) | (csd[8] << 8) | csd[9];
243
+ return (csize + 1) * 1024;
244
+ }
245
+ const readBlLen = csd[5] & 0x0F; // CSD v1
246
+ const csize = ((csd[6] & 0x03) << 10) | (csd[7] << 2) | (csd[8] >> 6);
247
+ const mult = ((csd[9] & 0x03) << 1) | (csd[10] >> 7);
248
+ return Math.floor(((csize + 1) * 2 ** (mult + 2) * 2 ** readBlLen) / BLOCK_SIZE);
249
+ }
250
+
251
+ // ---- minimal API -----------------------------------------------------
252
+
253
+ /** @returns {number} Capacity in 512-byte blocks (from the CSD). */
254
+ blockCount() { return this._blockCount; }
255
+
256
+ /** @returns {number} Alias of blockCount() (FatFs terminology). */
257
+ sectorCount() { return this._blockCount; }
258
+
259
+ /** @returns {number} Card generation, a `CardType` value. */
260
+ cardType() { return this._type; }
261
+
262
+ /**
263
+ * Read one 512-byte block (CMD17).
264
+ * @param {number} block
265
+ * @returns {Promise<Buffer>}
266
+ * @throws {OutOfRange} `block` beyond the card.
267
+ */
268
+ async readBlock(block) {
269
+ if (block < 0 || block >= this._blockCount) throw new OutOfRange(`block ${block} out of range`);
270
+ await this._c.select();
271
+ try {
272
+ if ((await this._command(17, this._address(block))) !== 0) throw new Io('CMD17 failed');
273
+ return await this._readData(BLOCK_SIZE);
274
+ } finally {
275
+ await this._release();
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Write one 512-byte block (CMD24).
281
+ * @param {number} block
282
+ * @param {Buffer} data - 512 bytes.
283
+ * @returns {Promise<void>}
284
+ * @throws {OutOfRange} `block` beyond the card.
285
+ */
286
+ async writeBlock(block, data) {
287
+ if (data.length !== BLOCK_SIZE) throw new RangeError('data must be 512 bytes');
288
+ if (block < 0 || block >= this._blockCount) throw new OutOfRange(`block ${block} out of range`);
289
+ await this._c.select();
290
+ try {
291
+ if ((await this._command(24, this._address(block))) !== 0) throw new Io('CMD24 failed');
292
+ await this._writeData(0xFE, data);
293
+ await this._waitReady(BUSY_TIMEOUT_MS);
294
+ } finally {
295
+ await this._release();
296
+ }
297
+ }
298
+ }
299
+
300
+ /**
301
+ * SD card in SPI mode — full interface; implements `BlockDevice`.
302
+ *
303
+ * Adds multi-block transfers (CMD18/CMD25), erase, CID/CSD/OCR access and CRC
304
+ * checking (on by default).
305
+ */
306
+ class SDSPIFull extends SDSPIMinimal {
307
+ /**
308
+ * @param {object} connection - SPI connection with the optional extensions.
309
+ * @param {object} [options]
310
+ * @param {number} [options.speedHz=12000000]
311
+ * @param {boolean} [options.crc=true] - CMD59 and CRC16 checking.
312
+ */
313
+ constructor(connection, options = {}) {
314
+ super(connection, { ...options, crc: options.crc ?? true });
315
+ this._name = '';
316
+ }
317
+
318
+ async init() {
319
+ await super.init();
320
+ try {
321
+ const cid = await this._readRegister(10);
322
+ this._name = cid.subarray(3, 8).toString('latin1'); // PNM = CID[103:64]
323
+ } catch (_e) {
324
+ this._name = '';
325
+ }
326
+ }
327
+
328
+ blockSize() { return BLOCK_SIZE; }
329
+ eraseSize() { return BLOCK_SIZE; }
330
+ needsErase() { return false; }
331
+
332
+ /**
333
+ * Read `count` consecutive blocks (CMD18 for `count > 1`).
334
+ * @param {number} block
335
+ * @param {number} [count=1]
336
+ * @returns {Promise<Buffer>}
337
+ */
338
+ async read(block, count = 1) {
339
+ if (count < 1) return Buffer.alloc(0);
340
+ if (block < 0 || block + count > this._blockCount) throw new OutOfRange('read beyond end');
341
+ if (count === 1) return this.readBlock(block);
342
+ const parts = [];
343
+ await this._c.select();
344
+ try {
345
+ if ((await this._command(18, this._address(block))) !== 0) throw new Io('CMD18 failed');
346
+ try {
347
+ for (let i = 0; i < count; i++) parts.push(await this._readData(BLOCK_SIZE));
348
+ } finally {
349
+ await this._command(12, 0);
350
+ await this._waitReady(BUSY_TIMEOUT_MS);
351
+ }
352
+ } finally {
353
+ await this._release();
354
+ }
355
+ return Buffer.concat(parts);
356
+ }
357
+
358
+ /**
359
+ * Program `data.length / 512` consecutive blocks (CMD25 for more than one).
360
+ * @param {number} block
361
+ * @param {Buffer} data
362
+ * @returns {Promise<void>}
363
+ */
364
+ async write(block, data) {
365
+ const count = data.length / BLOCK_SIZE;
366
+ if (!Number.isInteger(count) || count < 1) throw new RangeError('data must be a multiple of 512 bytes');
367
+ if (block < 0 || block + count > this._blockCount) throw new OutOfRange('write beyond end');
368
+ if (count === 1) return this.writeBlock(block, data);
369
+ await this._c.select();
370
+ try {
371
+ await this._appCommand(23, count); // pre-erase hint; cards may ignore it
372
+ if ((await this._command(25, this._address(block))) !== 0) throw new Io('CMD25 failed');
373
+ let err = null;
374
+ try {
375
+ for (let i = 0; i < count; i++) await this._writeData(0xFC, data.subarray(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE));
376
+ } catch (e) {
377
+ err = e;
378
+ }
379
+ await this._waitReady(BUSY_TIMEOUT_MS);
380
+ await this._writeData(0xFD, Buffer.alloc(0));
381
+ await this._rx(); // stuff byte after the stop token
382
+ await this._waitReady(BUSY_TIMEOUT_MS);
383
+ if (err) throw err;
384
+ } finally {
385
+ await this._release();
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Erase `count` blocks (CMD32/33/38); contents afterwards are card dependent.
391
+ * @param {number} block
392
+ * @param {number} [count=1]
393
+ * @returns {Promise<void>}
394
+ */
395
+ async erase(block, count = 1) {
396
+ if (count < 1) return;
397
+ if (block < 0 || block + count > this._blockCount) throw new OutOfRange('erase beyond end');
398
+ await this._c.select();
399
+ try {
400
+ if ((await this._command(32, this._address(block))) !== 0
401
+ || (await this._command(33, this._address(block + count - 1))) !== 0
402
+ || (await this._command(38, 0)) !== 0) throw new Io('erase command failed');
403
+ await this._waitReady(ERASE_TIMEOUT_MS);
404
+ } finally {
405
+ await this._release();
406
+ }
407
+ }
408
+
409
+ /** Wait until the card has finished programming. */
410
+ async sync() {
411
+ await this._c.select();
412
+ try {
413
+ await this._waitReady(BUSY_TIMEOUT_MS);
414
+ } finally {
415
+ await this._release();
416
+ }
417
+ }
418
+
419
+ /** @returns {object} Geometry and capabilities (see BlockDevice#info). */
420
+ info() {
421
+ return {
422
+ blockSize: BLOCK_SIZE, blockCount: this._blockCount, eraseSize: BLOCK_SIZE, needsErase: false,
423
+ readOnly: false, badBlocks: false, name: this._name,
424
+ };
425
+ }
426
+
427
+ /** @returns {Promise<Buffer>} The 16-byte CID register (manufacturer, name, revision, serial, date). */
428
+ async cid() { return this._readRegister(10); }
429
+
430
+ /** @returns {Buffer} The 16-byte CSD register as read during init. */
431
+ csd() { return Buffer.from(this._csd); }
432
+
433
+ /** @returns {Promise<number>} The OCR word (CMD58). */
434
+ async ocr() {
435
+ await this._c.select();
436
+ try {
437
+ if ((await this._command(58, 0)) !== 0) throw new Io('CMD58 failed');
438
+ return (await this._c.read(4)).readUInt32BE(0);
439
+ } finally {
440
+ await this._release();
441
+ }
442
+ }
443
+
444
+ /**
445
+ * Enable/disable CMD59 and CRC16 checking.
446
+ * @param {boolean} enabled
447
+ * @returns {Promise<void>}
448
+ */
449
+ async setCrc(enabled) {
450
+ await this._c.select();
451
+ try {
452
+ if ((await this._command(59, enabled ? 1 : 0)) !== 0) throw new Io('CMD59 failed');
453
+ } finally {
454
+ await this._release();
455
+ }
456
+ this._crcOn = !!enabled;
457
+ }
458
+
459
+ /**
460
+ * Change the SCK frequency after init.
461
+ * @param {number} hz
462
+ * @returns {Promise<boolean>}
463
+ */
464
+ async setSpeed(hz) { return this._c.setSpeed(hz); }
465
+
466
+ /** @returns {Promise<boolean>} True if a card responds to CMD13. */
467
+ async isPresent() {
468
+ await this._c.select();
469
+ try {
470
+ const r = await this._command(13, 0);
471
+ if (r !== 0xFF) await this._rx(); // R2 second byte
472
+ return r !== 0xFF;
473
+ } finally {
474
+ await this._release();
475
+ }
476
+ }
477
+
478
+ async isBad(_unit) { return false; }
479
+ async markBad(_unit) {}
480
+ }
481
+
482
+ // JavaScript has single inheritance: SDSPIFull extends SDSPIMinimal and conforms to the BlockDevice
483
+ // contract by duck typing; the marker makes `sd instanceof BlockDevice` true.
484
+ BlockDevice.mark(SDSPIFull);
485
+
486
+ module.exports = { SDSPIMinimal, SDSPIFull, CardType, crc7, crc16, BLOCK_SIZE };