periph 1.3.2 → 1.4.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 (114) hide show
  1. package/README.md +27 -0
  2. package/examples/accelerometer/bma180/complete.js +83 -0
  3. package/examples/accelerometer/bma180/demo.js +47 -0
  4. package/examples/accelerometer/bma180/minimal.js +21 -0
  5. package/examples/accelerometer/fxos8700/complete.js +111 -0
  6. package/examples/accelerometer/fxos8700/demo.js +80 -0
  7. package/examples/accelerometer/fxos8700/minimal.js +20 -0
  8. package/examples/accelerometer/lis3dh/complete.js +123 -0
  9. package/examples/accelerometer/lis3dh/demo.js +99 -0
  10. package/examples/accelerometer/lis3dh/minimal.js +19 -0
  11. package/examples/accelerometer/lsm303/complete.js +82 -0
  12. package/examples/accelerometer/lsm303/demo.js +96 -0
  13. package/examples/accelerometer/lsm303/minimal.js +23 -0
  14. package/examples/accelerometer/mma8451q/complete.js +96 -0
  15. package/examples/accelerometer/mma8451q/demo.js +120 -0
  16. package/examples/accelerometer/mma8451q/minimal.js +20 -0
  17. package/examples/adc_dac/ad5243/complete.js +52 -0
  18. package/examples/adc_dac/ad5243/demo.js +50 -0
  19. package/examples/adc_dac/ad5243/minimal.js +23 -0
  20. package/examples/adc_dac/ad5248/complete.js +49 -0
  21. package/examples/adc_dac/ad5248/demo.js +42 -0
  22. package/examples/adc_dac/ad5248/minimal.js +21 -0
  23. package/examples/adc_dac/ads1013/complete.js +51 -0
  24. package/examples/adc_dac/ads1013/demo.js +51 -0
  25. package/examples/adc_dac/ads1013/minimal.js +21 -0
  26. package/examples/adc_dac/ads1014/complete.js +88 -0
  27. package/examples/adc_dac/ads1014/demo.js +52 -0
  28. package/examples/adc_dac/ads1014/minimal.js +21 -0
  29. package/examples/adc_dac/ads1113/complete.js +47 -0
  30. package/examples/adc_dac/ads1113/demo.js +39 -0
  31. package/examples/adc_dac/ads1113/minimal.js +20 -0
  32. package/examples/adc_dac/ads1114/complete.js +77 -0
  33. package/examples/adc_dac/ads1114/demo.js +47 -0
  34. package/examples/adc_dac/ads1114/minimal.js +20 -0
  35. package/examples/adc_dac/ads1115/complete.js +82 -0
  36. package/examples/adc_dac/ads1115/demo.js +55 -0
  37. package/examples/adc_dac/ads1115/minimal.js +20 -0
  38. package/examples/adc_dac/es8311/complete.js +80 -0
  39. package/examples/adc_dac/es8311/demo.js +59 -0
  40. package/examples/adc_dac/es8311/minimal.js +18 -0
  41. package/examples/adc_dac/mcp4xxx/complete.js +97 -0
  42. package/examples/adc_dac/mcp4xxx/demo.js +76 -0
  43. package/examples/adc_dac/mcp4xxx/minimal.js +22 -0
  44. package/examples/display/pcf8578/complete.js +58 -0
  45. package/examples/display/pcf8578/demo.js +62 -0
  46. package/examples/display/pcf8578/minimal.js +19 -0
  47. package/examples/display/pcf8579/complete.js +58 -0
  48. package/examples/display/pcf8579/demo.js +61 -0
  49. package/examples/display/pcf8579/minimal.js +19 -0
  50. package/examples/imu/icm20948/complete.js +114 -0
  51. package/examples/imu/icm20948/demo.js +79 -0
  52. package/examples/imu/icm20948/minimal.js +22 -0
  53. package/examples/imu/qmi8658a/complete.js +134 -0
  54. package/examples/imu/qmi8658a/demo.js +81 -0
  55. package/examples/imu/qmi8658a/minimal.js +22 -0
  56. package/examples/io_expander/mcp23008/complete.js +70 -0
  57. package/examples/io_expander/mcp23008/demo.js +58 -0
  58. package/examples/io_expander/mcp23008/minimal.js +20 -0
  59. package/examples/memory/mb85rc/complete.js +40 -0
  60. package/examples/memory/mb85rc/demo.js +58 -0
  61. package/examples/memory/mb85rc/minimal.js +15 -0
  62. package/examples/motor/drv2605/complete.js +100 -0
  63. package/examples/motor/drv2605/demo.js +55 -0
  64. package/examples/motor/drv2605/minimal.js +24 -0
  65. package/examples/motor/tmc2130/complete.js +138 -0
  66. package/examples/motor/tmc2130/demo.js +96 -0
  67. package/examples/motor/tmc2130/minimal.js +30 -0
  68. package/examples/motor/tmc2208/complete.js +92 -0
  69. package/examples/motor/tmc2208/demo.js +85 -0
  70. package/examples/motor/tmc2208/minimal.js +25 -0
  71. package/examples/motor/tmc2209/complete.js +106 -0
  72. package/examples/motor/tmc2209/demo.js +97 -0
  73. package/examples/motor/tmc2209/minimal.js +25 -0
  74. package/examples/motor/tmc5160/complete.js +205 -0
  75. package/examples/motor/tmc5160/demo.js +104 -0
  76. package/examples/motor/tmc5160/minimal.js +35 -0
  77. package/examples/power/axp2101/complete.js +135 -0
  78. package/examples/power/axp2101/demo.js +68 -0
  79. package/examples/power/axp2101/minimal.js +24 -0
  80. package/examples/rtc/pcf85063a/complete.js +68 -0
  81. package/examples/rtc/pcf85063a/demo.js +76 -0
  82. package/examples/rtc/pcf85063a/minimal.js +20 -0
  83. package/package.json +1 -1
  84. package/src/chips/accelerometer/bma180.js +573 -0
  85. package/src/chips/accelerometer/fxos8700.js +1600 -0
  86. package/src/chips/accelerometer/lis3dh.js +1341 -0
  87. package/src/chips/accelerometer/lsm303.js +1471 -0
  88. package/src/chips/accelerometer/mma8451q.js +1406 -0
  89. package/src/chips/adc_dac/_ads111x_base.js +272 -0
  90. package/src/chips/adc_dac/ad5243.js +231 -0
  91. package/src/chips/adc_dac/ad5248.js +194 -0
  92. package/src/chips/adc_dac/ads1013.js +219 -0
  93. package/src/chips/adc_dac/ads1014.js +509 -0
  94. package/src/chips/adc_dac/ads1113.js +112 -0
  95. package/src/chips/adc_dac/ads1114.js +201 -0
  96. package/src/chips/adc_dac/ads1115.js +232 -0
  97. package/src/chips/adc_dac/es8311.js +621 -0
  98. package/src/chips/adc_dac/mcp4xxx.js +982 -0
  99. package/src/chips/display/pcf8578.js +452 -0
  100. package/src/chips/display/pcf8579.js +451 -0
  101. package/src/chips/imu/icm20948.js +849 -0
  102. package/src/chips/imu/qmi8658a.js +1011 -0
  103. package/src/chips/io_expander/mcp23008.js +558 -0
  104. package/src/chips/memory/mb85rc.js +166 -0
  105. package/src/chips/motor/drv2605.js +592 -0
  106. package/src/chips/motor/tmc2130.js +537 -0
  107. package/src/chips/motor/tmc2208.js +490 -0
  108. package/src/chips/motor/tmc2209.js +565 -0
  109. package/src/chips/motor/tmc5160.js +900 -0
  110. package/src/chips/power/axp2101.js +968 -0
  111. package/src/chips/rtc/pcf85063a.js +482 -0
  112. package/src/connection/uart.js +9 -0
  113. package/src/connection/uart_mock.js +65 -0
  114. package/src/discovery/registry.js +45 -19
@@ -0,0 +1,592 @@
1
+ 'use strict';
2
+
3
+ const _REG_STATUS = 0x00;
4
+ const _REG_MODE = 0x01;
5
+ const _REG_RTP_INPUT = 0x02;
6
+ const _REG_LIBRARY = 0x03;
7
+ const _REG_SEQ1 = 0x04;
8
+ const _REG_GO = 0x0C;
9
+ const _REG_ODT = 0x0D;
10
+ const _REG_ATH_CTRL = 0x11;
11
+ const _REG_RATED_VOLTAGE = 0x16;
12
+ const _REG_OD_CLAMP = 0x17;
13
+ const _REG_A_CAL_COMP = 0x18;
14
+ const _REG_FEEDBACK = 0x1A;
15
+ const _REG_CONTROL1 = 0x1B;
16
+ const _REG_CONTROL2 = 0x1C;
17
+ const _REG_CONTROL3 = 0x1D;
18
+ const _REG_CONTROL4 = 0x1E;
19
+ const _REG_VBAT = 0x21;
20
+ const _REG_LRA_PERIOD = 0x22;
21
+
22
+ const _MODE_DEV_RESET = 0x80;
23
+ const _MODE_STANDBY = 0x40;
24
+
25
+ const MODE_INTERNAL_TRIGGER = 0;
26
+ const MODE_EXTERNAL_EDGE = 1;
27
+ const MODE_EXTERNAL_LEVEL = 2;
28
+ const MODE_PWM_ANALOG = 3;
29
+ const MODE_AUDIO_TO_VIBE = 4;
30
+ const MODE_RTP = 5;
31
+ const MODE_DIAGNOSTICS = 6;
32
+ const MODE_AUTO_CALIBRATION = 7;
33
+
34
+ const EFFECTS = {
35
+ EFFECT_STRONG_CLICK: 1,
36
+ EFFECT_SHARP_CLICK: 4,
37
+ EFFECT_SOFT_BUMP: 7,
38
+ EFFECT_DOUBLE_CLICK: 10,
39
+ EFFECT_TRIPLE_CLICK: 12,
40
+ EFFECT_STRONG_BUZZ: 14,
41
+ EFFECT_ALERT_750MS: 15,
42
+ EFFECT_ALERT_1000MS: 16,
43
+ EFFECT_BUZZ: 47,
44
+ EFFECT_PULSING_STRONG: 52,
45
+ EFFECT_LONG_BUZZ: 118,
46
+ };
47
+
48
+ const _SAMPLE_TIME_S = [150e-6, 200e-6, 250e-6, 300e-6];
49
+ const _PEAK_TIMES_MS = [10, 20, 30, 40];
50
+ const _FILTERS_HZ = [100, 125, 150, 200];
51
+
52
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
53
+
54
+ /** Round to the nearest integer and clamp to a register code 0–255. */
55
+ function _clampCode(value) {
56
+ const code = Math.floor(value + 0.5);
57
+ return Math.max(0, Math.min(255, code));
58
+ }
59
+
60
+ /** Drive-time register code for a time in ms (LRA: 0.5 ms + 0.1 ms × code; ERM: 1 ms + 0.2 ms × code). */
61
+ function _driveTimeCode(ms, lra) {
62
+ const code = lra ? Math.floor((ms - 0.5) / 0.1 + 0.5) : Math.floor((ms - 1.0) / 0.2 + 0.5);
63
+ return Math.max(0, Math.min(31, code));
64
+ }
65
+
66
+ /**
67
+ * DRV2605 haptic driver for ERM and LRA actuators (Texas Instruments) — minimal interface.
68
+ *
69
+ * Plays the built-in 123-effect TS2200 ROM library. `init()` runs the
70
+ * initialization sequence: DEV_RESET, DEVICE_ID check, leave standby, and
71
+ * actuator selection (ERM: library A, open loop; LRA: LRA library, closed loop
72
+ * with auto-resonance). The I²C address is fixed at 0x5A; the EN pin must be high.
73
+ */
74
+ class DRV2605Minimal {
75
+ /**
76
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - I²C or SMBus register connection (0x5A).
77
+ * @param {boolean} [lra=false] - false for an ERM, true for an LRA.
78
+ */
79
+ constructor(connection, lra = false) {
80
+ this._conn = connection;
81
+ this._lra = lra;
82
+ this._mode = MODE_INTERNAL_TRIGGER;
83
+ this._standby = false;
84
+ }
85
+
86
+ async _writeReg(reg, value) {
87
+ await this._conn.writeReg(reg & 0xFF, value & 0xFF);
88
+ }
89
+
90
+ async _readReg(reg) {
91
+ const buf = await this._conn.readReg(reg & 0xFF, 1);
92
+ return buf[0];
93
+ }
94
+
95
+ async _updateReg(reg, mask, value) {
96
+ const old = await this._readReg(reg);
97
+ await this._writeReg(reg, (old & ~mask) | (value & mask));
98
+ }
99
+
100
+ async _writeMode(mode, standby = false) {
101
+ await this._writeReg(_REG_MODE, (standby ? _MODE_STANDBY : 0) | mode);
102
+ this._mode = mode;
103
+ this._standby = standby;
104
+ }
105
+
106
+ async _resetChip() {
107
+ await this._writeReg(_REG_MODE, _MODE_DEV_RESET);
108
+ this._mode = MODE_INTERNAL_TRIGGER;
109
+ this._standby = true;
110
+ await sleep(2);
111
+ for (let i = 0; i < 100; i++) {
112
+ if (!((await this._readReg(_REG_MODE)) & _MODE_DEV_RESET)) return;
113
+ await sleep(1);
114
+ }
115
+ throw new Error('DRV2605 reset did not complete');
116
+ }
117
+
118
+ async _ensureInternal() {
119
+ if (this._mode !== MODE_INTERNAL_TRIGGER || this._standby) await this._writeMode(MODE_INTERNAL_TRIGGER);
120
+ }
121
+
122
+ /**
123
+ * Run the initialization sequence (reset, DEVICE_ID check, leave standby, select actuator).
124
+ * @returns {Promise<void>}
125
+ * @throws {Error} If the reset does not complete or DEVICE_ID is not 3.
126
+ */
127
+ async init() {
128
+ await this._resetChip();
129
+ if (((await this._readReg(_REG_STATUS)) >> 5) !== 3) throw new Error('DRV2605 not found (DEVICE_ID != 3)');
130
+ await this._writeMode(MODE_INTERNAL_TRIGGER);
131
+ if (this._lra) {
132
+ await this._writeReg(_REG_FEEDBACK, 0xB6);
133
+ await this._writeReg(_REG_LIBRARY, 0x06);
134
+ } else {
135
+ await this._writeReg(_REG_FEEDBACK, 0x36);
136
+ await this._writeReg(_REG_LIBRARY, 0x01);
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Play one ROM effect and return immediately.
142
+ * Writes the effect to sequencer slot 1 and 0 (end) to slot 2, then sets GO.
143
+ * @param {number} effectId - Effect identifier 1–123 (see the `EFFECT_*` constants).
144
+ * @returns {Promise<void>}
145
+ * @throws {RangeError} If `effectId` is outside 1–123.
146
+ */
147
+ async playEffect(effectId) {
148
+ if (!Number.isInteger(effectId) || effectId < 1 || effectId > 123) throw new RangeError('effectId must be 1-123');
149
+ await this._ensureInternal();
150
+ await this._conn.writeReg(_REG_SEQ1, Buffer.from([effectId, 0]));
151
+ await this._writeReg(_REG_GO, 1);
152
+ }
153
+
154
+ /**
155
+ * Cancel playback by clearing the GO bit.
156
+ * @returns {Promise<void>}
157
+ */
158
+ async stop() {
159
+ await this._writeReg(_REG_GO, 0);
160
+ }
161
+
162
+ /**
163
+ * True while a sequence is playing (GO bit set).
164
+ * @returns {Promise<boolean>}
165
+ */
166
+ async isPlaying() {
167
+ return ((await this._readReg(_REG_GO)) & 0x01) !== 0;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * DRV2605 full interface — extends Minimal with the complete chip functionality:
173
+ * waveform sequencer, real-time playback, mode and library control, drive
174
+ * configuration, auto-calibration, diagnostics, audio-to-vibe, status readout and
175
+ * one-time OTP programming.
176
+ */
177
+ class DRV2605Full extends DRV2605Minimal {
178
+ /**
179
+ * Play a sequence of up to 8 effects and delays.
180
+ * @param {Array<number|Array>} items - Up to 8 steps: a number 1–123 is a ROM effect; `['wait', ms]` is a delay of 0–1270 ms (10 ms steps).
181
+ * @returns {Promise<void>}
182
+ * @throws {RangeError} On an empty or oversized list or an out-of-range step.
183
+ */
184
+ async playSequence(items) {
185
+ if (!Array.isArray(items) || items.length < 1 || items.length > 8) throw new RangeError('items must hold 1-8 steps');
186
+ const data = [];
187
+ for (const item of items) {
188
+ if (typeof item === 'number') {
189
+ if (!Number.isInteger(item) || item < 1 || item > 123) throw new RangeError('effect must be 1-123');
190
+ data.push(item);
191
+ } else {
192
+ if (!Array.isArray(item) || item[0] !== 'wait' || !(item[1] >= 0 && item[1] <= 1270)) throw new RangeError("wait step must be ['wait', 0-1270 ms]");
193
+ data.push(0x80 | Math.floor(item[1] / 10 + 0.5));
194
+ }
195
+ }
196
+ if (data.length < 8) data.push(0);
197
+ await this._ensureInternal();
198
+ await this._conn.writeReg(_REG_SEQ1, Buffer.from(data));
199
+ await this._writeReg(_REG_GO, 1);
200
+ }
201
+
202
+ /**
203
+ * Poll GO until playback finishes.
204
+ * @param {number} [timeoutMs=5000] - Give-up time in ms.
205
+ * @returns {Promise<boolean>} true if playback finished, false on timeout.
206
+ */
207
+ async waitDone(timeoutMs = 5000) {
208
+ const start = Date.now();
209
+ while (await this.isPlaying()) {
210
+ if (Date.now() - start >= timeoutMs) return false;
211
+ await sleep(2);
212
+ }
213
+ return true;
214
+ }
215
+
216
+ /**
217
+ * Cancel playback; also leaves real-time-playback mode (output to zero).
218
+ * @returns {Promise<void>}
219
+ */
220
+ async stop() {
221
+ await super.stop();
222
+ if (this._mode === MODE_RTP) {
223
+ await this._writeReg(_REG_RTP_INPUT, 0);
224
+ await this._writeMode(MODE_INTERNAL_TRIGGER, this._standby);
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Select the ROM library: 0 empty, 1–5 ERM libraries A–E, 6 LRA library.
230
+ * @param {number} library - 0–6.
231
+ * @returns {Promise<void>}
232
+ */
233
+ async setLibrary(library) {
234
+ if (!Number.isInteger(library) || library < 0 || library > 6) throw new RangeError('library must be 0-6');
235
+ await this._updateReg(_REG_LIBRARY, 0x07, library);
236
+ }
237
+
238
+ /**
239
+ * Set MODE<2:0> and leave standby.
240
+ * @param {number} mode - 0–7.
241
+ * @returns {Promise<void>}
242
+ */
243
+ async setMode(mode) {
244
+ if (!Number.isInteger(mode) || mode < 0 || mode > 7) throw new RangeError('mode must be 0-7');
245
+ await this._writeMode(mode);
246
+ }
247
+
248
+ /**
249
+ * Enter software standby (also stops playback).
250
+ * @returns {Promise<void>}
251
+ */
252
+ async standby() { await this._writeMode(this._mode, true); }
253
+
254
+ /**
255
+ * Leave software standby.
256
+ * @returns {Promise<void>}
257
+ */
258
+ async wake() { await this._writeMode(this._mode, false); }
259
+
260
+ /**
261
+ * DEV_RESET and wait for completion; re-run `init()` afterwards.
262
+ * @returns {Promise<void>}
263
+ */
264
+ async reset() { await this._resetChip(); }
265
+
266
+ /**
267
+ * Put the outputs in true high-impedance state.
268
+ * @param {boolean} enabled
269
+ * @returns {Promise<void>}
270
+ */
271
+ async setHiZ(enabled) { await this._updateReg(_REG_LIBRARY, 0x10, enabled ? 0x10 : 0); }
272
+
273
+ async _isLra() { return ((await this._readReg(_REG_FEEDBACK)) & 0x80) !== 0; }
274
+
275
+ async _isOpenLoop(lra) { return ((await this._readReg(_REG_CONTROL3)) & (lra ? 0x01 : 0x20)) !== 0; }
276
+
277
+ /**
278
+ * Select ERM (false) or LRA (true) in N_ERM_LRA; run `calibrate()` afterwards.
279
+ * @param {boolean} lra
280
+ * @returns {Promise<void>}
281
+ */
282
+ async setActuator(lra) { await this._updateReg(_REG_FEEDBACK, 0x80, lra ? 0x80 : 0); }
283
+
284
+ /**
285
+ * Enable open-loop drive (ERM_OPEN_LOOP or LRA_OPEN_LOOP according to the actuator type).
286
+ * @param {boolean} enabled
287
+ * @returns {Promise<void>}
288
+ */
289
+ async setOpenLoop(enabled) {
290
+ const mask = (await this._isLra()) ? 0x01 : 0x20;
291
+ await this._updateReg(_REG_CONTROL3, mask, enabled ? mask : 0);
292
+ }
293
+
294
+ /**
295
+ * Select bidirectional (true) or unidirectional (false) input.
296
+ * @param {boolean} enabled
297
+ * @returns {Promise<void>}
298
+ * @throws {Error} If unidirectional is requested while the loop is open.
299
+ */
300
+ async setBidirectional(enabled) {
301
+ if (!enabled && (await this._isOpenLoop(await this._isLra()))) throw new Error('unidirectional input requires closed-loop operation');
302
+ await this._updateReg(_REG_CONTROL2, 0x80, enabled ? 0x80 : 0);
303
+ }
304
+
305
+ async _enterRtp() {
306
+ if (this._mode !== MODE_RTP || this._standby) await this._writeMode(MODE_RTP);
307
+ }
308
+
309
+ /**
310
+ * Stream a signed real-time-playback amplitude. Enters RTP mode if not already
311
+ * there; leave with `stop()`, `setMode()` or `standby()`.
312
+ * @param {number} level - Amplitude 0.0–1.0 (mapped to 0–127).
313
+ * @returns {Promise<void>}
314
+ */
315
+ async rtpLevel(level) {
316
+ if (!(level >= 0 && level <= 1)) throw new RangeError('level must be 0.0-1.0');
317
+ if (this._mode !== MODE_RTP) await this._updateReg(_REG_CONTROL3, 0x08, 0);
318
+ await this._enterRtp();
319
+ await this._writeReg(_REG_RTP_INPUT, Math.floor(level * 127 + 0.5));
320
+ }
321
+
322
+ /**
323
+ * Write a raw RTP_INPUT byte, interpreted per the RTP data format.
324
+ * @param {number} value - 0–255.
325
+ * @returns {Promise<void>}
326
+ */
327
+ async rtpWrite(value) {
328
+ if (!Number.isInteger(value) || value < 0 || value > 255) throw new RangeError('value must be 0-255');
329
+ await this._enterRtp();
330
+ await this._writeReg(_REG_RTP_INPUT, value);
331
+ }
332
+
333
+ /**
334
+ * Select unsigned (true) or signed (false) RTP data (DATA_FORMAT_RTP).
335
+ * @param {boolean} unsigned
336
+ * @returns {Promise<void>}
337
+ */
338
+ async setRtpFormat(unsigned) { await this._updateReg(_REG_CONTROL3, 0x08, unsigned ? 0x08 : 0); }
339
+
340
+ /**
341
+ * Select analog (true) or PWM (false) input for mode 3 (N_PWM_ANALOG).
342
+ * @param {boolean} analog
343
+ * @returns {Promise<void>}
344
+ */
345
+ async setInput(analog) { await this._updateReg(_REG_CONTROL3, 0x02, analog ? 0x02 : 0); }
346
+
347
+ async _voltsToRatedCode(volts, lraFreqHz) {
348
+ if (!(await this._isLra())) return _clampCode(volts / 21.33e-3);
349
+ if (!(lraFreqHz > 0)) throw new RangeError('lraFreqHz is required to convert volts for an LRA');
350
+ const tSample = _SAMPLE_TIME_S[((await this._readReg(_REG_CONTROL2)) >> 4) & 0x03];
351
+ const factor = 1 - (4 * tSample + 300e-6) * lraFreqHz;
352
+ if (factor <= 0) throw new RangeError('lraFreqHz too high for the sample time');
353
+ return _clampCode(volts * Math.sqrt(factor) / 20.71e-3);
354
+ }
355
+
356
+ /**
357
+ * Set RATED_VOLTAGE from volts or a raw code.
358
+ * @param {{volts?: number, code?: number, lraFreqHz?: number}} opts - Exactly one of `volts` (V, RMS for an LRA) or `code` (0–255); `lraFreqHz` is required with `volts` for an LRA.
359
+ * @returns {Promise<void>}
360
+ */
361
+ async setRatedVoltage({ volts, code, lraFreqHz } = {}) {
362
+ if ((volts === undefined) === (code === undefined)) throw new RangeError('give exactly one of volts or code');
363
+ if (code === undefined) code = await this._voltsToRatedCode(volts, lraFreqHz);
364
+ else if (!Number.isInteger(code) || code < 0 || code > 255) throw new RangeError('code must be 0-255');
365
+ await this._writeReg(_REG_RATED_VOLTAGE, code);
366
+ }
367
+
368
+ /**
369
+ * Set OD_CLAMP from volts or a raw code.
370
+ * @param {{volts?: number, code?: number, lraFreqHz?: number}} opts - Exactly one of `volts` or `code` (0–255); `lraFreqHz` is required with `volts` for LRA open loop.
371
+ * @returns {Promise<void>}
372
+ * @throws {Error} For ERM closed loop with `volts` (pass `code` instead).
373
+ */
374
+ async setOverdriveClamp({ volts, code, lraFreqHz } = {}) {
375
+ if ((volts === undefined) === (code === undefined)) throw new RangeError('give exactly one of volts or code');
376
+ if (code === undefined) {
377
+ const lra = await this._isLra();
378
+ const openLoop = await this._isOpenLoop(lra);
379
+ if (lra && openLoop) {
380
+ if (!(lraFreqHz > 0)) throw new RangeError('lraFreqHz is required for LRA open loop');
381
+ code = _clampCode(volts / (21.33e-3 * Math.sqrt(1 - lraFreqHz * 800e-6)));
382
+ } else if (!lra && !openLoop) {
383
+ throw new Error('ERM closed-loop clamp in volts needs undocumented timing values; pass code');
384
+ } else {
385
+ code = _clampCode(volts / 21.96e-3);
386
+ }
387
+ } else if (!Number.isInteger(code) || code < 0 || code > 255) {
388
+ throw new RangeError('code must be 0-255');
389
+ }
390
+ await this._writeReg(_REG_OD_CLAMP, code);
391
+ }
392
+
393
+ /**
394
+ * Set DRIVE_TIME (LRA: half the resonance period; ERM: back-EMF sample period).
395
+ * @param {number} ms - Time in ms.
396
+ * @returns {Promise<void>}
397
+ */
398
+ async setDriveTime(ms) { await this._updateReg(_REG_CONTROL1, 0x1F, _driveTimeCode(ms, await this._isLra())); }
399
+
400
+ /**
401
+ * Set the FEEDBACK_CONTROL fields (actuator-type bit preserved).
402
+ * @param {number} [brakeFactor=3] - FB_BRAKE_FACTOR 0–7.
403
+ * @param {number} [loopGain=1] - LOOP_GAIN 0–3.
404
+ * @param {number} [bemfGain=2] - BEMF_GAIN 0–3.
405
+ * @returns {Promise<void>}
406
+ */
407
+ async setFeedback(brakeFactor = 3, loopGain = 1, bemfGain = 2) {
408
+ if (!(brakeFactor >= 0 && brakeFactor <= 7 && loopGain >= 0 && loopGain <= 3 && bemfGain >= 0 && bemfGain <= 3)) throw new RangeError('brakeFactor 0-7, loopGain 0-3, bemfGain 0-3');
409
+ await this._updateReg(_REG_FEEDBACK, 0x7F, (brakeFactor << 4) | (loopGain << 2) | bemfGain);
410
+ }
411
+
412
+ /**
413
+ * Set the CONTROL1–CONTROL3 fields not covered by other setters.
414
+ * @param {{startupBoost?: boolean, brakeStabilizer?: boolean, sampleTime?: number, blankingTime?: number, idissTime?: number, lraDriveTwice?: boolean, supplyComp?: boolean, noiseGate?: number}} [opts]
415
+ * @returns {Promise<void>}
416
+ */
417
+ async setAdvanced({ startupBoost = true, brakeStabilizer = true, sampleTime = 3, blankingTime = 1, idissTime = 1, lraDriveTwice = false, supplyComp = true, noiseGate = 2 } = {}) {
418
+ for (const v of [sampleTime, blankingTime, idissTime, noiseGate]) {
419
+ if (!Number.isInteger(v) || v < 0 || v > 3) throw new RangeError('sampleTime, blankingTime, idissTime, noiseGate must be 0-3');
420
+ }
421
+ await this._updateReg(_REG_CONTROL1, 0x80, startupBoost ? 0x80 : 0);
422
+ await this._updateReg(_REG_CONTROL2, 0x7F, (brakeStabilizer ? 0x40 : 0) | (sampleTime << 4) | (blankingTime << 2) | idissTime);
423
+ await this._updateReg(_REG_CONTROL3, 0xD4, (noiseGate << 6) | (supplyComp ? 0 : 0x10) | (lraDriveTwice ? 0x04 : 0));
424
+ }
425
+
426
+ /**
427
+ * Set the ODT, SPT, SNT, BRT offsets (5 ms steps, signed 8-bit).
428
+ * @param {{overdriveMs?: number, sustainPosMs?: number, sustainNegMs?: number, brakeMs?: number}} [opts]
429
+ * @returns {Promise<void>}
430
+ */
431
+ async setTimeOffsets({ overdriveMs = 0, sustainPosMs = 0, sustainNegMs = 0, brakeMs = 0 } = {}) {
432
+ const data = [];
433
+ for (const ms of [overdriveMs, sustainPosMs, sustainNegMs, brakeMs]) {
434
+ const steps = ms >= 0 ? Math.floor(ms / 5 + 0.5) : -Math.floor(-ms / 5 + 0.5);
435
+ if (steps < -128 || steps > 127) throw new RangeError('time offset out of range (-640..635 ms)');
436
+ data.push(steps & 0xFF);
437
+ }
438
+ await this._conn.writeReg(_REG_ODT, Buffer.from(data));
439
+ }
440
+
441
+ /**
442
+ * Run the auto-calibration procedure.
443
+ * @param {boolean} lra - true for an LRA, false for an ERM.
444
+ * @param {number} ratedVoltage - Rated voltage in V (RMS for an LRA).
445
+ * @param {number} overdriveVoltage - Overdrive clamp in V (ERM: open-loop conversion V / 21.96 mV, since the closed-loop correction needs undocumented timing values).
446
+ * @param {number} [lraFreqHz] - LRA resonance in Hz (required for an LRA); also sets DRIVE_TIME to half the period.
447
+ * @returns {Promise<{ok: boolean, comp: number, bemf: number, bemfGain: number}>}
448
+ */
449
+ async calibrate(lra, ratedVoltage, overdriveVoltage, lraFreqHz) {
450
+ if (lra && !(lraFreqHz > 0)) throw new RangeError('lraFreqHz is required for an LRA');
451
+ const wasStandby = this._standby;
452
+ await this._writeMode(MODE_AUTO_CALIBRATION);
453
+ const bemfGain = (await this._readReg(_REG_FEEDBACK)) & 0x03;
454
+ await this._writeReg(_REG_FEEDBACK, (lra ? 0x80 : 0) | (2 << 4) | (2 << 2) | bemfGain);
455
+ await this._updateReg(_REG_CONTROL2, 0x3F, (3 << 4) | (1 << 2) | 1); // SAMPLE_TIME 3, BLANKING 1, IDISS 1
456
+ if (lra) await this._updateReg(_REG_CONTROL1, 0x1F, _driveTimeCode(500 / lraFreqHz, true));
457
+ await this._writeReg(_REG_RATED_VOLTAGE, await this._voltsToRatedCode(ratedVoltage, lraFreqHz));
458
+ await this._writeReg(_REG_OD_CLAMP, _clampCode(overdriveVoltage / 21.96e-3));
459
+ await this._updateReg(_REG_CONTROL4, 0x31, 3 << 4); // AUTO_CAL_TIME = 3; OTP_PROGRAM stays 0
460
+ await this._writeReg(_REG_GO, 1);
461
+ const finished = await this.waitDone(3000);
462
+ const diagFailed = ((await this._readReg(_REG_STATUS)) & 0x08) !== 0;
463
+ const result = await this.getCalibration();
464
+ await this._writeMode(MODE_INTERNAL_TRIGGER, wasStandby);
465
+ return { ok: finished && !diagFailed, ...result };
466
+ }
467
+
468
+ /**
469
+ * Read the stored calibration.
470
+ * @returns {Promise<{comp: number, bemf: number, bemfGain: number}>}
471
+ */
472
+ async getCalibration() {
473
+ const data = await this._conn.readReg(_REG_A_CAL_COMP, 2);
474
+ return { comp: data[0], bemf: data[1], bemfGain: (await this._readReg(_REG_FEEDBACK)) & 0x03 };
475
+ }
476
+
477
+ /**
478
+ * Restore A_CAL_COMP, A_CAL_BEMF and BEMF_GAIN from an earlier calibration.
479
+ * @param {number} comp - 0–255.
480
+ * @param {number} bemf - 0–255.
481
+ * @param {number} bemfGain - 0–3.
482
+ * @returns {Promise<void>}
483
+ */
484
+ async setCalibration(comp, bemf, bemfGain) {
485
+ if (!(comp >= 0 && comp <= 255 && bemf >= 0 && bemf <= 255 && bemfGain >= 0 && bemfGain <= 3)) throw new RangeError('comp/bemf 0-255, bemfGain 0-3');
486
+ await this._conn.writeReg(_REG_A_CAL_COMP, Buffer.from([comp, bemf]));
487
+ await this._updateReg(_REG_FEEDBACK, 0x03, bemfGain);
488
+ }
489
+
490
+ /**
491
+ * Run the actuator diagnostics.
492
+ * @returns {Promise<boolean>} true if the actuator is OK (DIAG_RESULT = 0).
493
+ */
494
+ async diagnose() {
495
+ const wasStandby = this._standby;
496
+ await this._writeMode(MODE_DIAGNOSTICS);
497
+ await this._writeReg(_REG_GO, 1);
498
+ const finished = await this.waitDone(3000);
499
+ const diagFailed = ((await this._readReg(_REG_STATUS)) & 0x08) !== 0;
500
+ await this._writeMode(MODE_INTERNAL_TRIGGER, wasStandby);
501
+ return finished && !diagFailed;
502
+ }
503
+
504
+ /**
505
+ * Configure the audio-to-vibe engine and enter audio-to-vibe mode.
506
+ * @param {{acCouple?: boolean, peakTimeMs?: number, filterHz?: number, minInputV?: number, maxInputV?: number, minDrive?: number, maxDrive?: number}} [opts] - peakTimeMs one of 10/20/30/40; filterHz one of 100/125/150/200; input levels 0–1.8 V; drive 0.0–1.0.
507
+ * @returns {Promise<void>}
508
+ */
509
+ async setAudioToVibe({ acCouple = true, peakTimeMs = 20, filterHz = 125, minInputV = 0.1, maxInputV = 1.8, minDrive = 0.1, maxDrive = 1.0 } = {}) {
510
+ const peak = _PEAK_TIMES_MS.indexOf(peakTimeMs);
511
+ const filter = _FILTERS_HZ.indexOf(filterHz);
512
+ if (peak < 0 || filter < 0) throw new RangeError('peakTimeMs in 10/20/30/40, filterHz in 100/125/150/200');
513
+ if (!(minInputV >= 0 && minInputV <= 1.8 && maxInputV >= 0 && maxInputV <= 1.8 && minDrive >= 0 && minDrive <= 1 && maxDrive >= 0 && maxDrive <= 1)) throw new RangeError('input levels 0-1.8 V, drive 0.0-1.0');
514
+ await this._conn.writeReg(_REG_ATH_CTRL, Buffer.from([
515
+ (peak << 2) | filter,
516
+ _clampCode(minInputV * 255 / 1.8), _clampCode(maxInputV * 255 / 1.8),
517
+ _clampCode(minDrive * 255), _clampCode(maxDrive * 255),
518
+ ]));
519
+ await this._updateReg(_REG_CONTROL1, 0x20, acCouple ? 0x20 : 0);
520
+ await this._updateReg(_REG_CONTROL3, 0x02, 0x02);
521
+ await this._writeMode(MODE_AUDIO_TO_VIBE);
522
+ }
523
+
524
+ /**
525
+ * Read STATUS (clears the latched flags).
526
+ * @returns {Promise<{diagFailed: boolean, fbTimeout: boolean, overTemp: boolean, overCurrent: boolean}>}
527
+ */
528
+ async readStatus() {
529
+ const s = await this._readReg(_REG_STATUS);
530
+ return { diagFailed: (s & 0x08) !== 0, fbTimeout: (s & 0x04) !== 0, overTemp: (s & 0x02) !== 0, overCurrent: (s & 0x01) !== 0 };
531
+ }
532
+
533
+ /**
534
+ * DEVICE_ID (3 for the DRV2605); clears the latched status flags.
535
+ * @returns {Promise<number>}
536
+ */
537
+ async readDeviceId() { return (await this._readReg(_REG_STATUS)) >> 5; }
538
+
539
+ /**
540
+ * VDD in volts from VBAT; valid only during playback.
541
+ * @returns {Promise<number>}
542
+ */
543
+ async readSupplyVoltage() { return (await this._readReg(_REG_VBAT)) * 5.6 / 255; }
544
+
545
+ /**
546
+ * LRA resonance frequency in Hz; valid only during LRA playback.
547
+ * @returns {Promise<number|null>} null if LRA_PERIOD is 0.
548
+ */
549
+ async readLraFrequency() {
550
+ const raw = await this._readReg(_REG_LRA_PERIOD);
551
+ return raw === 0 ? null : 1e6 / (raw * 98.46);
552
+ }
553
+
554
+ /**
555
+ * Burn registers 0x16–0x1A into OTP. **Irreversible, one time only**; VDD must be 4.0–4.4 V.
556
+ * @param {boolean} [confirm=false] - Must be true to proceed.
557
+ * @returns {Promise<void>}
558
+ * @throws {Error} If not confirmed, already programmed, or programming does not complete.
559
+ */
560
+ async programOtp(confirm = false) {
561
+ if (confirm !== true) throw new Error('programOtp is irreversible; pass confirm=true');
562
+ if (await this.otpProgrammed()) throw new Error('OTP already programmed');
563
+ await this._updateReg(_REG_CONTROL4, 0x01, 0x01);
564
+ for (let i = 0; i < 100; i++) {
565
+ await sleep(10);
566
+ if (await this.otpProgrammed()) return;
567
+ }
568
+ throw new Error('OTP programming did not complete');
569
+ }
570
+
571
+ /**
572
+ * OTP_STATUS: true if the OTP has already been programmed.
573
+ * @returns {Promise<boolean>}
574
+ */
575
+ async otpProgrammed() { return ((await this._readReg(_REG_CONTROL4)) & 0x04) !== 0; }
576
+ }
577
+
578
+ for (const cls of [DRV2605Minimal, DRV2605Full]) {
579
+ cls.I2C_ADDRESS = 0x5A;
580
+ cls.DEVICE_ID = 3;
581
+ Object.assign(cls, EFFECTS);
582
+ cls.MODE_INTERNAL_TRIGGER = MODE_INTERNAL_TRIGGER;
583
+ cls.MODE_EXTERNAL_EDGE = MODE_EXTERNAL_EDGE;
584
+ cls.MODE_EXTERNAL_LEVEL = MODE_EXTERNAL_LEVEL;
585
+ cls.MODE_PWM_ANALOG = MODE_PWM_ANALOG;
586
+ cls.MODE_AUDIO_TO_VIBE = MODE_AUDIO_TO_VIBE;
587
+ cls.MODE_RTP = MODE_RTP;
588
+ cls.MODE_DIAGNOSTICS = MODE_DIAGNOSTICS;
589
+ cls.MODE_AUTO_CALIBRATION = MODE_AUTO_CALIBRATION;
590
+ }
591
+
592
+ module.exports = { DRV2605Minimal, DRV2605Full, I2C_ADDRESS: 0x5A, ...EFFECTS };