periph 1.2.0 → 1.2.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 (39) hide show
  1. package/README.md +7 -0
  2. package/examples/motor/drv8830/complete.js +50 -0
  3. package/examples/motor/drv8830/demo.js +57 -0
  4. package/examples/motor/drv8830/minimal.js +23 -0
  5. package/examples/rtc/ds3231/complete.js +77 -0
  6. package/examples/rtc/ds3231/demo.js +60 -0
  7. package/examples/rtc/ds3231/minimal.js +23 -0
  8. package/examples/rtc/pcf8523/complete.js +66 -0
  9. package/examples/rtc/pcf8523/demo.js +65 -0
  10. package/examples/rtc/pcf8523/minimal.js +20 -0
  11. package/examples/temperature/mcp9808/complete.js +89 -0
  12. package/examples/temperature/mcp9808/demo.js +62 -0
  13. package/examples/temperature/mcp9808/minimal.js +21 -0
  14. package/examples/temperature/tmp117/complete.js +90 -0
  15. package/examples/temperature/tmp117/demo.js +73 -0
  16. package/examples/temperature/tmp117/minimal.js +21 -0
  17. package/examples/tof/vl53l0x/complete.js +118 -0
  18. package/examples/tof/vl53l0x/demo.js +83 -0
  19. package/examples/tof/vl53l0x/minimal.js +25 -0
  20. package/examples/tof/vl53l1x/complete.js +151 -0
  21. package/examples/tof/vl53l1x/demo.js +100 -0
  22. package/examples/tof/vl53l1x/minimal.js +25 -0
  23. package/package.json +1 -1
  24. package/src/chips/imu/mpu9250.js +4 -4
  25. package/src/chips/imu/mpu9255.js +5 -5
  26. package/src/chips/motor/drv8830.js +239 -0
  27. package/src/chips/rtc/ds3231.js +504 -0
  28. package/src/chips/rtc/pcf8523.js +539 -0
  29. package/src/chips/temperature/mcp9808.js +488 -0
  30. package/src/chips/temperature/tmp117.js +471 -0
  31. package/src/chips/tof/_vl53_base.js +160 -0
  32. package/src/chips/tof/vl53l0x.js +816 -0
  33. package/src/chips/tof/vl53l1x.js +816 -0
  34. package/examples/motor/.gitkeep +0 -0
  35. package/examples/temperature/.gitkeep +0 -0
  36. package/examples/tof/.gitkeep +0 -0
  37. package/src/chips/motor/.gitkeep +0 -0
  38. package/src/chips/temperature/.gitkeep +0 -0
  39. package/src/chips/tof/.gitkeep +0 -0
@@ -0,0 +1,816 @@
1
+ 'use strict';
2
+
3
+ const { VL53Base } = require('./_vl53_base');
4
+
5
+ const _REG_SYSRANGE_START = 0x00;
6
+ const _REG_SYSTEM_SEQUENCE_CONFIG = 0x01;
7
+ const _REG_SYSTEM_INTERMEASUREMENT = 0x04;
8
+ const _REG_SYSTEM_INTERRUPT_CONFIG = 0x0A;
9
+ const _REG_SYSTEM_INTERRUPT_CLEAR = 0x0B;
10
+ const _REG_SYSTEM_THRESH_HIGH = 0x0C;
11
+ const _REG_SYSTEM_THRESH_LOW = 0x0E;
12
+ const _REG_RESULT_INTERRUPT_STATUS = 0x13;
13
+ const _REG_RESULT_RANGE_STATUS = 0x14;
14
+ const _REG_CROSSTALK_COMPENSATION = 0x20;
15
+ const _REG_PART_TO_PART_RANGE_OFFSET = 0x28;
16
+ const _REG_PHASECAL_CONFIG_TIMEOUT = 0x30;
17
+ const _REG_GLOBAL_CONFIG_VCSEL_WIDTH = 0x32;
18
+ const _REG_FINAL_MIN_COUNT_RATE_RTN = 0x44;
19
+ const _REG_MSRC_CONFIG_TIMEOUT = 0x46;
20
+ const _REG_FINAL_VALID_PHASE_LOW = 0x47;
21
+ const _REG_FINAL_VALID_PHASE_HIGH = 0x48;
22
+ const _REG_DYNAMIC_SPAD_NUM_REQ = 0x4E;
23
+ const _REG_DYNAMIC_SPAD_START_OFFSET = 0x4F;
24
+ const _REG_PRE_RANGE_VCSEL_PERIOD = 0x50;
25
+ const _REG_PRE_RANGE_TIMEOUT = 0x51;
26
+ const _REG_PRE_VALID_PHASE_LOW = 0x56;
27
+ const _REG_PRE_VALID_PHASE_HIGH = 0x57;
28
+ const _REG_MSRC_CONFIG_CONTROL = 0x60;
29
+ const _REG_FINAL_RANGE_VCSEL_PERIOD = 0x70;
30
+ const _REG_FINAL_RANGE_TIMEOUT = 0x71;
31
+ const _REG_POWER_FORCE = 0x80;
32
+ const _REG_GPIO_HV_MUX_ACTIVE_HIGH = 0x84;
33
+ const _REG_I2C_MODE = 0x88;
34
+ const _REG_VHV_PAD_EXTSUP_HV = 0x89;
35
+ const _REG_I2C_SLAVE_DEVICE_ADDRESS = 0x8A;
36
+ const _REG_STOP_VARIABLE = 0x91;
37
+ const _REG_SPAD_ENABLES_REF_0 = 0xB0;
38
+ const _REG_REF_EN_START_SELECT = 0xB6;
39
+ const _REG_MODEL_ID = 0xC0;
40
+ const _REG_REVISION_ID = 0xC2;
41
+ const _REG_OSC_CALIBRATE_VAL = 0xF8;
42
+ const _REG_PAGE_SELECT = 0xFF;
43
+
44
+ const _SEQ_TCC = 0x10;
45
+ const _SEQ_DSS = 0x08;
46
+ const _SEQ_MSRC = 0x04;
47
+ const _SEQ_PRE_RANGE = 0x40;
48
+ const _SEQ_FINAL_RANGE = 0x80;
49
+ const _SEQ_OPERATING = 0xE8;
50
+
51
+ const _MODEL_ID = 0xEE;
52
+ const _RANGE_STATUS_VALID = 11;
53
+ const _MIN_TIMING_BUDGET_US = 20000;
54
+
55
+ // Timing-budget overheads, µs.
56
+ const _START_OVERHEAD = 1910;
57
+ const _END_OVERHEAD = 960;
58
+ const _MSRC_OVERHEAD = 660;
59
+ const _TCC_OVERHEAD = 590;
60
+ const _DSS_OVERHEAD = 690;
61
+ const _PRE_RANGE_OVERHEAD = 660;
62
+ const _FINAL_RANGE_OVERHEAD = 550;
63
+
64
+ // ST DefaultTuningSettings — opaque, written verbatim in this order as (reg, value) pairs.
65
+ const _TUNING = [
66
+ 0xFF, 0x01, 0x00, 0x00, 0xFF, 0x00, 0x09, 0x00, 0x10, 0x00, 0x11, 0x00, 0x24, 0x01, 0x25, 0xFF, 0x75, 0x00,
67
+ 0xFF, 0x01, 0x4E, 0x2C, 0x48, 0x00, 0x30, 0x20, 0xFF, 0x00, 0x30, 0x09, 0x54, 0x00, 0x31, 0x04, 0x32, 0x03,
68
+ 0x40, 0x83, 0x46, 0x25, 0x60, 0x00, 0x27, 0x00, 0x50, 0x06, 0x51, 0x00, 0x52, 0x96, 0x56, 0x08, 0x57, 0x30,
69
+ 0x61, 0x00, 0x62, 0x00, 0x64, 0x00, 0x65, 0x00, 0x66, 0xA0, 0xFF, 0x01, 0x22, 0x32, 0x47, 0x14, 0x49, 0xFF,
70
+ 0x4A, 0x00, 0xFF, 0x00, 0x7A, 0x0A, 0x7B, 0x00, 0x78, 0x21, 0xFF, 0x01, 0x23, 0x34, 0x42, 0x00, 0x44, 0xFF,
71
+ 0x45, 0x26, 0x46, 0x05, 0x40, 0x40, 0x0E, 0x06, 0x20, 0x1A, 0x43, 0x40, 0xFF, 0x00, 0x34, 0x03, 0x35, 0x44,
72
+ 0xFF, 0x01, 0x31, 0x04, 0x4B, 0x09, 0x4C, 0x05, 0x4D, 0x04, 0xFF, 0x00, 0x44, 0x00, 0x45, 0x20, 0x47, 0x08,
73
+ 0x48, 0x28, 0x67, 0x00, 0x70, 0x04, 0x71, 0x01, 0x72, 0xFE, 0x76, 0x00, 0x77, 0x00, 0xFF, 0x01, 0x0D, 0x01,
74
+ 0xFF, 0x00, 0x80, 0x01, 0x01, 0xF8, 0xFF, 0x01, 0x8E, 0x01, 0x00, 0x01, 0xFF, 0x00, 0x80, 0x00,
75
+ ];
76
+
77
+ // Pre-range PRE_RANGE_CONFIG_VALID_PHASE_HIGH per VCSEL period (PCLKs).
78
+ const _PRE_PHASE_HIGH = { 12: 0x18, 14: 0x30, 16: 0x40, 18: 0x50 };
79
+
80
+ // Final-range [VALID_PHASE_HIGH, VALID_PHASE_LOW, VCSEL_WIDTH, PHASECAL_CONFIG_TIMEOUT,
81
+ // page-1 PHASECAL_LIM] per VCSEL period (PCLKs).
82
+ const _FINAL_PHASE = {
83
+ 8: [0x10, 0x08, 0x02, 0x0C, 0x30],
84
+ 10: [0x28, 0x08, 0x03, 0x09, 0x20],
85
+ 12: [0x38, 0x08, 0x03, 0x08, 0x20],
86
+ 14: [0x48, 0x08, 0x03, 0x07, 0x20],
87
+ };
88
+
89
+ // [signal-rate limit MCPS, pre-range PCLKs, final-range PCLKs, timing budget µs].
90
+ const _PROFILES = {
91
+ default: [0.25, 14, 10, 33000],
92
+ long_range: [0.10, 18, 14, 33000],
93
+ high_speed: [0.25, 14, 10, 20000],
94
+ high_accuracy: [0.25, 14, 10, 200000],
95
+ };
96
+
97
+ const _decodeVcsel = (reg) => (reg + 1) << 1;
98
+ const _encodeVcsel = (pclks) => (pclks >> 1) - 1;
99
+ const _macroPeriodNs = (pclks) => Math.floor((2304 * pclks * 1655 + 500) / 1000);
100
+ const _mclksToUs = (mclks, pclks) => Math.floor((mclks * _macroPeriodNs(pclks) + 500) / 1000);
101
+
102
+ function _usToMclks(us, pclks) {
103
+ const period = _macroPeriodNs(pclks);
104
+ return Math.floor((us * 1000 + Math.floor(period / 2)) / period);
105
+ }
106
+
107
+ const _decodeTimeout = (reg16) => (reg16 & 0xFF) * 2 ** (reg16 >> 8) + 1;
108
+
109
+ function _encodeTimeout(mclks) {
110
+ if (mclks <= 0) return 0;
111
+ let ls = mclks - 1;
112
+ let ms = 0;
113
+ while (ls > 0xFF) {
114
+ ls >>>= 1;
115
+ ms++;
116
+ }
117
+ return (ms << 8) | (ls & 0xFF);
118
+ }
119
+
120
+ /**
121
+ * VL53L0X Time-of-Flight laser-ranging sensor (STMicroelectronics) — minimal
122
+ * interface.
123
+ *
124
+ * 940 nm VCSEL emitter, SPAD receiving array and an embedded ranging
125
+ * microcontroller measuring absolute distance up to ~2 m, largely
126
+ * independent of target reflectance. The datasheet has no register map:
127
+ * registers, the tuning table and the init/calibration sequences follow ST's
128
+ * STSW-IMG005 API (the same derivation as Pololu's VL53L0X library).
129
+ * Multi-byte registers are big-endian.
130
+ *
131
+ * The constructor starts the full initialization sequence (boot wait, model
132
+ * ID check, 2V8 I/O mode, reference SPADs, default tuning, GPIO1 = new
133
+ * sample ready active low, ~33 ms timing budget, VHV + phase reference
134
+ * calibration) and leaves the chip idle. JS constructors cannot be async, so
135
+ * every public method awaits it first — `await sensor.init()` right after
136
+ * construction to surface a wrong or absent device at a predictable point.
137
+ * If the connection has an enPin (XSHUT), it is driven high first.
138
+ *
139
+ * Multiple sensors on one bus: all power up at 0x29. Hold every sensor's
140
+ * XSHUT low (each connection disabled), then for each sensor in turn enable
141
+ * its XSHUT, construct a driver on 0x29, call `setAddress(new)`, and build
142
+ * the real driver on a connection at the new address. The new address is
143
+ * volatile — it reverts to 0x29 on power-up or an XSHUT low pulse.
144
+ *
145
+ * Register access, polling, boot wait, interrupt delivery and re-addressing
146
+ * come from the shared VL53Base (specs/tof/_vl53_base.md).
147
+ */
148
+ class VL53L0XMinimal extends VL53Base {
149
+ /**
150
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C connection (0x29).
151
+ */
152
+ constructor(connection) {
153
+ super(connection, 1, 'VL53L0X');
154
+ this._stopVariable = 0;
155
+ this._rangeStatus = 0;
156
+ this._timingBudgetUs = 0;
157
+ this._ready = this._init();
158
+ // The rejection is re-raised by every public method; mark it handled
159
+ // here so it never surfaces as an unhandled rejection on its own.
160
+ this._ready.catch(() => {});
161
+ }
162
+
163
+ /**
164
+ * Wait for the initialization sequence started by the constructor.
165
+ * Optional — every other method awaits it too.
166
+ * @returns {Promise<void>}
167
+ * @throws {Error} If the model ID is not 0xEE or an init poll times out (500 ms).
168
+ */
169
+ async init() {
170
+ await this._ready;
171
+ }
172
+
173
+ async _wr(reg, value) {
174
+ await this._wr8(reg, value);
175
+ }
176
+
177
+ async _rd(reg) {
178
+ return this._rd8(reg);
179
+ }
180
+
181
+ async _wait(reg, mask, untilSet, what) {
182
+ await this._waitUntil(async () => (((await this._rd(reg)) & mask) !== 0) === untilSet, what);
183
+ }
184
+
185
+ async _init() {
186
+ await this._bootWait();
187
+
188
+ const model = await this._rd(_REG_MODEL_ID);
189
+ if (model !== _MODEL_ID) {
190
+ throw new Error('VL53L0X not found: expected model ID 0xEE, got 0x' +
191
+ model.toString(16).padStart(2, '0'));
192
+ }
193
+
194
+ // 2V8 I/O mode, standard I²C mode.
195
+ await this._wr(_REG_VHV_PAD_EXTSUP_HV, (await this._rd(_REG_VHV_PAD_EXTSUP_HV)) | 0x01);
196
+ await this._wr(_REG_I2C_MODE, 0x00);
197
+
198
+ // Stop variable.
199
+ await this._wr(_REG_POWER_FORCE, 0x01);
200
+ await this._wr(_REG_PAGE_SELECT, 0x01);
201
+ await this._wr(_REG_SYSRANGE_START, 0x00);
202
+ this._stopVariable = await this._rd(_REG_STOP_VARIABLE);
203
+ await this._wr(_REG_SYSRANGE_START, 0x01);
204
+ await this._wr(_REG_PAGE_SELECT, 0x00);
205
+ await this._wr(_REG_POWER_FORCE, 0x00);
206
+
207
+ // Disable MSRC and pre-range signal-rate limit checks; 0.25 MCPS limit.
208
+ await this._wr(_REG_MSRC_CONFIG_CONTROL, (await this._rd(_REG_MSRC_CONFIG_CONTROL)) | 0x12);
209
+ await this._wr16(_REG_FINAL_MIN_COUNT_RATE_RTN, 0x0020);
210
+ await this._wr(_REG_SYSTEM_SEQUENCE_CONFIG, 0xFF);
211
+
212
+ const { count, isAperture } = await this._spadInfo();
213
+
214
+ // Reference SPADs.
215
+ const refMap = await this._rdBlock(_REG_SPAD_ENABLES_REF_0, 6);
216
+ await this._wr(_REG_PAGE_SELECT, 0x01);
217
+ await this._wr(_REG_DYNAMIC_SPAD_START_OFFSET, 0x00);
218
+ await this._wr(_REG_DYNAMIC_SPAD_NUM_REQ, 0x2C);
219
+ await this._wr(_REG_PAGE_SELECT, 0x00);
220
+ await this._wr(_REG_REF_EN_START_SELECT, 0xB4);
221
+ const first = isAperture ? 12 : 0;
222
+ let enabled = 0;
223
+ for (let i = 0; i < 48; i++) {
224
+ const byte = i >> 3;
225
+ const bit = 1 << (i & 7);
226
+ if (i < first || enabled === count) {
227
+ refMap[byte] &= ~bit & 0xFF;
228
+ } else if (refMap[byte] & bit) {
229
+ enabled++;
230
+ }
231
+ }
232
+ await this._wrBlock(_REG_SPAD_ENABLES_REF_0, refMap);
233
+
234
+ // Default tuning settings.
235
+ for (let i = 0; i < _TUNING.length; i += 2) await this._wr(_TUNING[i], _TUNING[i + 1]);
236
+
237
+ // GPIO1 = new sample ready, active low.
238
+ await this._wr(_REG_SYSTEM_INTERRUPT_CONFIG, 0x04);
239
+ await this._wr(_REG_GPIO_HV_MUX_ACTIVE_HIGH, (await this._rd(_REG_GPIO_HV_MUX_ACTIVE_HIGH)) & ~0x10 & 0xFF);
240
+ await this._wr(_REG_SYSTEM_INTERRUPT_CLEAR, 0x01);
241
+
242
+ const budget = await this._getTimingBudget();
243
+ await this._wr(_REG_SYSTEM_SEQUENCE_CONFIG, _SEQ_OPERATING);
244
+ await this._setTimingBudget(budget);
245
+
246
+ await this._refCalibration();
247
+ }
248
+
249
+ async _spadInfo() {
250
+ await this._wr(_REG_POWER_FORCE, 0x01);
251
+ await this._wr(_REG_PAGE_SELECT, 0x01);
252
+ await this._wr(_REG_SYSRANGE_START, 0x00);
253
+ await this._wr(_REG_PAGE_SELECT, 0x06);
254
+ await this._wr(0x83, (await this._rd(0x83)) | 0x04);
255
+ await this._wr(_REG_PAGE_SELECT, 0x07);
256
+ await this._wr(0x81, 0x01);
257
+ await this._wr(_REG_POWER_FORCE, 0x01);
258
+ await this._wr(0x94, 0x6B);
259
+ await this._wr(0x83, 0x00);
260
+ await this._wait(0x83, 0xFF, true, 'SPAD info');
261
+ await this._wr(0x83, 0x01);
262
+ const tmp = await this._rd(0x92);
263
+ await this._wr(0x81, 0x00);
264
+ await this._wr(_REG_PAGE_SELECT, 0x06);
265
+ await this._wr(0x83, (await this._rd(0x83)) & ~0x04 & 0xFF);
266
+ await this._wr(_REG_PAGE_SELECT, 0x01);
267
+ await this._wr(_REG_SYSRANGE_START, 0x01);
268
+ await this._wr(_REG_PAGE_SELECT, 0x00);
269
+ await this._wr(_REG_POWER_FORCE, 0x00);
270
+ return { count: tmp & 0x7F, isAperture: ((tmp >> 7) & 0x01) === 1 };
271
+ }
272
+
273
+ async _singleRefCalibration(vhvInit) {
274
+ await this._wr(_REG_SYSRANGE_START, 0x01 | vhvInit);
275
+ await this._wait(_REG_RESULT_INTERRUPT_STATUS, 0x07, true, 'reference calibration');
276
+ await this._wr(_REG_SYSTEM_INTERRUPT_CLEAR, 0x01);
277
+ await this._wr(_REG_SYSRANGE_START, 0x00);
278
+ }
279
+
280
+ async _refCalibration() {
281
+ const seq = await this._rd(_REG_SYSTEM_SEQUENCE_CONFIG);
282
+ await this._wr(_REG_SYSTEM_SEQUENCE_CONFIG, 0x01);
283
+ await this._singleRefCalibration(0x40);
284
+ await this._wr(_REG_SYSTEM_SEQUENCE_CONFIG, 0x02);
285
+ await this._singleRefCalibration(0x00);
286
+ await this._wr(_REG_SYSTEM_SEQUENCE_CONFIG, seq);
287
+ }
288
+
289
+ async _stepTimeouts(enables) {
290
+ const prePclks = _decodeVcsel(await this._rd(_REG_PRE_RANGE_VCSEL_PERIOD));
291
+ const msrcUs = _mclksToUs((await this._rd(_REG_MSRC_CONFIG_TIMEOUT)) + 1, prePclks);
292
+ const preMclks = _decodeTimeout(await this._rd16(_REG_PRE_RANGE_TIMEOUT));
293
+ const preUs = _mclksToUs(preMclks, prePclks);
294
+ const finalPclks = _decodeVcsel(await this._rd(_REG_FINAL_RANGE_VCSEL_PERIOD));
295
+ let finalMclks = _decodeTimeout(await this._rd16(_REG_FINAL_RANGE_TIMEOUT));
296
+ if (enables & _SEQ_PRE_RANGE) finalMclks -= preMclks;
297
+ const finalUs = _mclksToUs(finalMclks, finalPclks);
298
+ return { prePclks, msrcUs, preMclks, preUs, finalPclks, finalUs };
299
+ }
300
+
301
+ _fixedOverheadUs(enables, t) {
302
+ let budget = _START_OVERHEAD + _END_OVERHEAD;
303
+ if (enables & _SEQ_TCC) budget += t.msrcUs + _TCC_OVERHEAD;
304
+ if (enables & _SEQ_DSS) budget += 2 * (t.msrcUs + _DSS_OVERHEAD);
305
+ else if (enables & _SEQ_MSRC) budget += t.msrcUs + _MSRC_OVERHEAD;
306
+ if (enables & _SEQ_PRE_RANGE) budget += t.preUs + _PRE_RANGE_OVERHEAD;
307
+ return budget;
308
+ }
309
+
310
+ async _getTimingBudget() {
311
+ const enables = await this._rd(_REG_SYSTEM_SEQUENCE_CONFIG);
312
+ const t = await this._stepTimeouts(enables);
313
+ let budget = this._fixedOverheadUs(enables, t);
314
+ if (enables & _SEQ_FINAL_RANGE) budget += t.finalUs + _FINAL_RANGE_OVERHEAD;
315
+ return budget;
316
+ }
317
+
318
+ async _setTimingBudget(budgetUs) {
319
+ if (!Number.isInteger(budgetUs) || budgetUs < _MIN_TIMING_BUDGET_US) {
320
+ throw new RangeError(`timing budget must be an integer >= ${_MIN_TIMING_BUDGET_US} us`);
321
+ }
322
+ const enables = await this._rd(_REG_SYSTEM_SEQUENCE_CONFIG);
323
+ const t = await this._stepTimeouts(enables);
324
+ let used = this._fixedOverheadUs(enables, t);
325
+ if (enables & _SEQ_FINAL_RANGE) {
326
+ used += _FINAL_RANGE_OVERHEAD;
327
+ if (used > budgetUs) {
328
+ throw new RangeError(`timing budget ${budgetUs} us is below the enabled steps overhead ${used} us`);
329
+ }
330
+ let finalMclks = _usToMclks(budgetUs - used, t.finalPclks);
331
+ if (enables & _SEQ_PRE_RANGE) finalMclks += t.preMclks;
332
+ await this._wr16(_REG_FINAL_RANGE_TIMEOUT, _encodeTimeout(finalMclks));
333
+ }
334
+ this._timingBudgetUs = budgetUs;
335
+ }
336
+
337
+ async _stopVariablePreamble() {
338
+ await this._wr(_REG_POWER_FORCE, 0x01);
339
+ await this._wr(_REG_PAGE_SELECT, 0x01);
340
+ await this._wr(_REG_SYSRANGE_START, 0x00);
341
+ await this._wr(_REG_STOP_VARIABLE, this._stopVariable);
342
+ await this._wr(_REG_SYSRANGE_START, 0x01);
343
+ await this._wr(_REG_PAGE_SELECT, 0x00);
344
+ await this._wr(_REG_POWER_FORCE, 0x00);
345
+ }
346
+
347
+ async _readResult() {
348
+ const data = await this._rdBlock(_REG_RESULT_RANGE_STATUS, 12);
349
+ await this._wr(_REG_SYSTEM_INTERRUPT_CLEAR, 0x01);
350
+ this._rangeStatus = (data[0] & 0x78) >> 3;
351
+ return data;
352
+ }
353
+
354
+ async _waitAndRead() {
355
+ await this._wait(_REG_RESULT_INTERRUPT_STATUS, 0x07, true, 'data ready');
356
+ const data = await this._readResult();
357
+ return data.readUInt16BE(10);
358
+ }
359
+
360
+ /**
361
+ * Take one single-shot measurement. Blocks for about one timing budget
362
+ * (33 ms by default). Returns the raw range even when the measurement is
363
+ * not valid — typically 8190 or 8191 with no target in range; check
364
+ * `rangeValid()`.
365
+ * @returns {Promise<number>} Distance in mm.
366
+ * @throws {Error} If the measurement does not start or complete within 500 ms.
367
+ */
368
+ async distance() {
369
+ await this._ready;
370
+ return this._locked(async () => {
371
+ await this._stopVariablePreamble();
372
+ await this._wr(_REG_SYSRANGE_START, 0x01);
373
+ await this._wait(_REG_SYSRANGE_START, 0x01, false, 'ranging start');
374
+ return this._waitAndRead();
375
+ });
376
+ }
377
+
378
+ /**
379
+ * Report whether the most recent measurement was valid.
380
+ * @returns {Promise<boolean>} True iff the device range status was 11 (range complete).
381
+ */
382
+ async rangeValid() {
383
+ await this._ready;
384
+ return this._rangeStatus === _RANGE_STATUS_VALID;
385
+ }
386
+
387
+ async _pollInterruptStatus() {
388
+ return this._locked(async () => {
389
+ const status = (await this._rd(_REG_RESULT_INTERRUPT_STATUS)) & 0x07;
390
+ if (status) await this._wr(_REG_SYSTEM_INTERRUPT_CLEAR, 0x01);
391
+ return status;
392
+ });
393
+ }
394
+ }
395
+
396
+ /**
397
+ * VL53L0X full interface — extends Minimal with continuous and timed
398
+ * ranging, the full measurement record, timing budget, signal-rate limit,
399
+ * VCSEL pulse periods, ranging profiles, offset and crosstalk compensation,
400
+ * reference recalibration, address change, distance thresholds,
401
+ * identification, and the Level-2 interrupt API.
402
+ */
403
+ class VL53L0XFull extends VL53L0XMinimal {
404
+ /**
405
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C connection (0x29).
406
+ */
407
+ /**
408
+ * Start continuous ranging.
409
+ * @param {number} [periodMs=0] - 0 for back-to-back mode; otherwise timed
410
+ * mode with this inter-measurement period in ms (should be ≥ the timing budget).
411
+ * @returns {Promise<void>}
412
+ */
413
+ async startContinuous(periodMs = 0) {
414
+ await this._ready;
415
+ return this._locked(async () => {
416
+ await this._stopVariablePreamble();
417
+ if (periodMs > 0) {
418
+ const osc = await this._rd16(_REG_OSC_CALIBRATE_VAL);
419
+ await this._wr32(_REG_SYSTEM_INTERMEASUREMENT, osc !== 0 ? periodMs * osc : periodMs);
420
+ await this._wr(_REG_SYSRANGE_START, 0x04);
421
+ } else {
422
+ await this._wr(_REG_SYSRANGE_START, 0x02);
423
+ }
424
+ });
425
+ }
426
+
427
+ /**
428
+ * Stop continuous ranging. Does not wait for a running measurement.
429
+ * @returns {Promise<void>}
430
+ */
431
+ async stopContinuous() {
432
+ await this._ready;
433
+ return this._locked(async () => {
434
+ await this._wr(_REG_SYSRANGE_START, 0x01);
435
+ await this._wr(_REG_PAGE_SELECT, 0x01);
436
+ await this._wr(_REG_SYSRANGE_START, 0x00);
437
+ await this._wr(_REG_STOP_VARIABLE, 0x00);
438
+ await this._wr(_REG_SYSRANGE_START, 0x01);
439
+ await this._wr(_REG_PAGE_SELECT, 0x00);
440
+ });
441
+ }
442
+
443
+ /**
444
+ * Wait for the next continuous-mode result and read it.
445
+ * @returns {Promise<number>} Distance in mm (check `rangeValid()`).
446
+ * @throws {Error} If no result arrives within 500 ms.
447
+ */
448
+ async readContinuous() {
449
+ await this._ready;
450
+ return this._locked(async () => {
451
+ return this._waitAndRead();
452
+ });
453
+ }
454
+
455
+ /**
456
+ * Report whether a measurement is pending (non-blocking).
457
+ * @returns {Promise<boolean>} True if RESULT_INTERRUPT_STATUS bits 2:0 are non-zero.
458
+ */
459
+ async dataReady() {
460
+ await this._ready;
461
+ return ((await this._rd(_REG_RESULT_INTERRUPT_STATUS)) & 0x07) !== 0;
462
+ }
463
+
464
+ /**
465
+ * Read the full result block and clear the interrupt (non-blocking).
466
+ * @returns {Promise<{distanceMm: number, rangeStatus: number, signalRateMcps: number,
467
+ * ambientRateMcps: number, effectiveSpadCount: number}>} Measurement record
468
+ * (rates in MCPS).
469
+ */
470
+ async readMeasurement() {
471
+ await this._ready;
472
+ return this._locked(async () => {
473
+ const data = await this._readResult();
474
+ return {
475
+ distanceMm: data.readUInt16BE(10),
476
+ rangeStatus: this._rangeStatus,
477
+ signalRateMcps: data.readUInt16BE(6) / 128,
478
+ ambientRateMcps: data.readUInt16BE(8) / 128,
479
+ effectiveSpadCount: data.readUInt16BE(2) / 256,
480
+ };
481
+ });
482
+ }
483
+
484
+ /**
485
+ * Device range status of the most recent measurement.
486
+ * @returns {Promise<number>} 0–15; 11 = valid, 4 = no target (MSRC).
487
+ */
488
+ async rangeStatus() {
489
+ await this._ready;
490
+ return this._rangeStatus;
491
+ }
492
+
493
+ /**
494
+ * Set the per-measurement timing budget.
495
+ * @param {number} budgetUs - Budget in µs, ≥ 20000.
496
+ * @returns {Promise<void>}
497
+ * @throws {RangeError} If below 20000 µs or below the enabled steps' overhead.
498
+ */
499
+ async setTimingBudget(budgetUs) {
500
+ await this._ready;
501
+ return this._locked(async () => {
502
+ await this._setTimingBudget(budgetUs);
503
+ });
504
+ }
505
+
506
+ /**
507
+ * Compute the timing budget from the current registers.
508
+ * @returns {Promise<number>} Budget in µs.
509
+ */
510
+ async timingBudget() {
511
+ await this._ready;
512
+ return this._locked(async () => {
513
+ return this._getTimingBudget();
514
+ });
515
+ }
516
+
517
+ /**
518
+ * Set the final-range return signal-rate limit. Lower values extend range
519
+ * but admit noisier readings.
520
+ * @param {number} limitMcps - Limit in MCPS, 0 to 511.99.
521
+ * @returns {Promise<void>}
522
+ * @throws {RangeError} If out of range.
523
+ */
524
+ async setSignalRateLimit(limitMcps) {
525
+ await this._ready;
526
+ if (!(limitMcps >= 0 && limitMcps <= 511.99)) throw new RangeError('signal rate limit must be 0 to 511.99 MCPS');
527
+ await this._wr16(_REG_FINAL_MIN_COUNT_RATE_RTN, Math.round(limitMcps * 128));
528
+ }
529
+
530
+ /**
531
+ * Read the final-range return signal-rate limit.
532
+ * @returns {Promise<number>} Limit in MCPS.
533
+ */
534
+ async signalRateLimit() {
535
+ await this._ready;
536
+ return (await this._rd16(_REG_FINAL_MIN_COUNT_RATE_RTN)) / 128;
537
+ }
538
+
539
+ /**
540
+ * Set a VCSEL pulse period, then re-apply the timing budget and redo the
541
+ * phase reference calibration.
542
+ * @param {'pre_range'|'final_range'} periodType - Which period to set.
543
+ * @param {number} pclks - Pre-range 12, 14, 16 or 18; final-range 8, 10, 12 or 14.
544
+ * @returns {Promise<void>}
545
+ * @throws {RangeError} If periodType or pclks is invalid.
546
+ * @throws {Error} If the phase calibration times out.
547
+ */
548
+ async setVcselPulsePeriod(periodType, pclks) {
549
+ await this._ready;
550
+ return this._locked(() => this._setVcselPulsePeriod(periodType, pclks));
551
+ }
552
+
553
+ async _setVcselPulsePeriod(periodType, pclks) {
554
+ if (periodType === 'pre_range') {
555
+ if (!(pclks in _PRE_PHASE_HIGH)) throw new RangeError('pre-range VCSEL period must be 12, 14, 16 or 18');
556
+ } else if (periodType === 'final_range') {
557
+ if (!(pclks in _FINAL_PHASE)) throw new RangeError('final-range VCSEL period must be 8, 10, 12 or 14');
558
+ } else {
559
+ throw new RangeError("periodType must be 'pre_range' or 'final_range'");
560
+ }
561
+
562
+ const enables = await this._rd(_REG_SYSTEM_SEQUENCE_CONFIG);
563
+ const t = await this._stepTimeouts(enables);
564
+ const vcsel = _encodeVcsel(pclks);
565
+
566
+ if (periodType === 'pre_range') {
567
+ await this._wr(_REG_PRE_VALID_PHASE_HIGH, _PRE_PHASE_HIGH[pclks]);
568
+ await this._wr(_REG_PRE_VALID_PHASE_LOW, 0x08);
569
+ await this._wr(_REG_PRE_RANGE_VCSEL_PERIOD, vcsel);
570
+ await this._wr16(_REG_PRE_RANGE_TIMEOUT, _encodeTimeout(_usToMclks(t.preUs, pclks)));
571
+ const m = _usToMclks(t.msrcUs, pclks);
572
+ await this._wr(_REG_MSRC_CONFIG_TIMEOUT, m > 256 ? 255 : m - 1);
573
+ } else {
574
+ const [high, low, width, phasecal, lim] = _FINAL_PHASE[pclks];
575
+ await this._wr(_REG_FINAL_VALID_PHASE_HIGH, high);
576
+ await this._wr(_REG_FINAL_VALID_PHASE_LOW, low);
577
+ await this._wr(_REG_GLOBAL_CONFIG_VCSEL_WIDTH, width);
578
+ await this._wr(_REG_PHASECAL_CONFIG_TIMEOUT, phasecal);
579
+ await this._wr(_REG_PAGE_SELECT, 0x01);
580
+ await this._wr(_REG_PHASECAL_CONFIG_TIMEOUT, lim);
581
+ await this._wr(_REG_PAGE_SELECT, 0x00);
582
+ await this._wr(_REG_FINAL_RANGE_VCSEL_PERIOD, vcsel);
583
+ let f = _usToMclks(t.finalUs, pclks);
584
+ if (enables & _SEQ_PRE_RANGE) f += t.preMclks;
585
+ await this._wr16(_REG_FINAL_RANGE_TIMEOUT, _encodeTimeout(f));
586
+ }
587
+
588
+ await this._setTimingBudget(this._timingBudgetUs);
589
+ const seq = await this._rd(_REG_SYSTEM_SEQUENCE_CONFIG);
590
+ await this._wr(_REG_SYSTEM_SEQUENCE_CONFIG, 0x02);
591
+ await this._singleRefCalibration(0x00);
592
+ await this._wr(_REG_SYSTEM_SEQUENCE_CONFIG, seq);
593
+ }
594
+
595
+ /**
596
+ * Read a VCSEL pulse period.
597
+ * @param {'pre_range'|'final_range'} periodType - Which period to read.
598
+ * @returns {Promise<number>} Period in PCLKs.
599
+ * @throws {RangeError} If periodType is invalid.
600
+ */
601
+ async vcselPulsePeriod(periodType) {
602
+ await this._ready;
603
+ if (periodType === 'pre_range') return _decodeVcsel(await this._rd(_REG_PRE_RANGE_VCSEL_PERIOD));
604
+ if (periodType === 'final_range') return _decodeVcsel(await this._rd(_REG_FINAL_RANGE_VCSEL_PERIOD));
605
+ throw new RangeError("periodType must be 'pre_range' or 'final_range'");
606
+ }
607
+
608
+ /**
609
+ * Apply a ranging profile: signal-rate limit, VCSEL periods (pre first),
610
+ * then timing budget. 'default' 0.25 MCPS 14/10 PCLKs 33 ms; 'long_range'
611
+ * 0.10 MCPS 18/14 PCLKs 33 ms (dark conditions); 'high_speed' 20 ms;
612
+ * 'high_accuracy' 200 ms.
613
+ * @param {'default'|'long_range'|'high_speed'|'high_accuracy'} profile - Profile name.
614
+ * @returns {Promise<void>}
615
+ * @throws {RangeError} If profile is unknown.
616
+ */
617
+ async setProfile(profile) {
618
+ await this._ready;
619
+ if (!Object.prototype.hasOwnProperty.call(_PROFILES, profile)) {
620
+ throw new RangeError("profile must be 'default', 'long_range', 'high_speed' or 'high_accuracy'");
621
+ }
622
+ const [limit, pre, fin, budget] = _PROFILES[profile];
623
+ await this.setSignalRateLimit(limit);
624
+ await this._locked(async () => {
625
+ await this._setVcselPulsePeriod('pre_range', pre);
626
+ await this._setVcselPulsePeriod('final_range', fin);
627
+ await this._setTimingBudget(budget);
628
+ });
629
+ }
630
+
631
+ /**
632
+ * Override the part-to-part range offset (volatile).
633
+ * @param {number} offsetMm - Offset in mm, −512.0 to 511.75 (0.25 mm steps).
634
+ * @returns {Promise<void>}
635
+ * @throws {RangeError} If out of range.
636
+ */
637
+ async setOffset(offsetMm) {
638
+ await this._ready;
639
+ if (!(offsetMm >= -512 && offsetMm <= 511.75)) throw new RangeError('offset must be -512.0 to 511.75 mm');
640
+ const q = offsetMm * 4;
641
+ const steps = q >= 0 ? Math.floor(q + 0.5) : -Math.floor(-q + 0.5);
642
+ await this._wr16(_REG_PART_TO_PART_RANGE_OFFSET, steps & 0x0FFF);
643
+ }
644
+
645
+ /**
646
+ * Read the part-to-part range offset.
647
+ * @returns {Promise<number>} Offset in mm.
648
+ */
649
+ async offset() {
650
+ await this._ready;
651
+ let raw = (await this._rd16(_REG_PART_TO_PART_RANGE_OFFSET)) & 0x0FFF;
652
+ if (raw & 0x0800) raw -= 0x1000;
653
+ return raw * 0.25;
654
+ }
655
+
656
+ /**
657
+ * Set the crosstalk compensation peak rate (volatile).
658
+ * @param {number} rateMcps - 0 disables; otherwise 0 < rate < 8.0 MCPS,
659
+ * from the host's own cover-glass calibration.
660
+ * @returns {Promise<void>}
661
+ * @throws {RangeError} If out of range.
662
+ */
663
+ async setCrosstalkCompensation(rateMcps) {
664
+ await this._ready;
665
+ if (!(rateMcps >= 0 && rateMcps < 8)) throw new RangeError('crosstalk rate must be 0 (off) or below 8.0 MCPS');
666
+ await this._wr16(_REG_CROSSTALK_COMPENSATION, Math.round(rateMcps * 8192));
667
+ }
668
+
669
+ /**
670
+ * Re-run the VHV and phase reference calibrations. Call in software
671
+ * standby (not while continuous ranging), and after the die temperature
672
+ * changes by more than 8 °C.
673
+ * @returns {Promise<void>}
674
+ * @throws {Error} If a calibration times out.
675
+ */
676
+ async recalibrate() {
677
+ await this._ready;
678
+ return this._locked(async () => {
679
+ await this._refCalibration();
680
+ });
681
+ }
682
+
683
+ /**
684
+ * Change the chip's I²C address (volatile). The chip answers on the new
685
+ * address immediately; this driver instance becomes unusable. Construct a
686
+ * new connection at the new address and a new driver.
687
+ * @param {number} address - New 7-bit address, 0x08–0x77.
688
+ * @returns {Promise<void>}
689
+ * @throws {RangeError} If out of range.
690
+ */
691
+ async setAddress(address) {
692
+ await this._ready;
693
+ await this._setAddressReg(_REG_I2C_SLAVE_DEVICE_ADDRESS, address);
694
+ }
695
+
696
+ /**
697
+ * Set the distance thresholds used by the threshold interrupt sources.
698
+ * @param {number} lowMm - Low threshold in mm (2 mm resolution).
699
+ * @param {number} highMm - High threshold in mm, lowMm ≤ highMm ≤ 8190.
700
+ * @returns {Promise<void>}
701
+ * @throws {RangeError} If out of range.
702
+ */
703
+ async setInterruptThresholds(lowMm, highMm) {
704
+ await this._ready;
705
+ if (!(lowMm >= 0 && highMm >= lowMm && highMm <= 8190)) {
706
+ throw new RangeError('thresholds must satisfy 0 <= low <= high <= 8190 mm');
707
+ }
708
+ await this._wr16(_REG_SYSTEM_THRESH_LOW, Math.floor(lowMm / 2) & 0x0FFF);
709
+ await this._wr16(_REG_SYSTEM_THRESH_HIGH, Math.floor(highMm / 2) & 0x0FFF);
710
+ }
711
+
712
+ /**
713
+ * Read the distance thresholds.
714
+ * @returns {Promise<{lowMm: number, highMm: number}>} Thresholds in mm.
715
+ */
716
+ async interruptThresholds() {
717
+ await this._ready;
718
+ return {
719
+ lowMm: ((await this._rd16(_REG_SYSTEM_THRESH_LOW)) & 0x0FFF) * 2,
720
+ highMm: ((await this._rd16(_REG_SYSTEM_THRESH_HIGH)) & 0x0FFF) * 2,
721
+ };
722
+ }
723
+
724
+ /**
725
+ * Read IDENTIFICATION_MODEL_ID.
726
+ * @returns {Promise<number>} 0xEE.
727
+ */
728
+ async modelId() {
729
+ await this._ready;
730
+ return this._rd(_REG_MODEL_ID);
731
+ }
732
+
733
+ /**
734
+ * Read IDENTIFICATION_REVISION_ID.
735
+ * @returns {Promise<number>} Revision ID (0x10 on current silicon).
736
+ */
737
+ async revisionId() {
738
+ await this._ready;
739
+ return this._rd(_REG_REVISION_ID);
740
+ }
741
+
742
+ /**
743
+ * Select the GPIO1 interrupt source (replaces the active one). With a
744
+ * threshold source active, `dataReady()`/`readContinuous()` only see a
745
+ * pending status when the threshold condition is met.
746
+ * @param {number} source - One of the SOURCE_* constants.
747
+ * @returns {Promise<void>}
748
+ * @throws {RangeError} If source is not 1–4.
749
+ */
750
+ async enableInterrupt(source) {
751
+ await this._ready;
752
+ if (!(source >= VL53L0XFull.SOURCE_LEVEL_LOW && source <= VL53L0XFull.SOURCE_NEW_SAMPLE_READY)) {
753
+ throw new RangeError('source must be one of the SOURCE_* constants');
754
+ }
755
+ await this._wr(_REG_SYSTEM_INTERRUPT_CONFIG, source);
756
+ }
757
+
758
+ /**
759
+ * Disable GPIO1 interrupts if source is the active one.
760
+ * @param {number} source - One of the SOURCE_* constants.
761
+ * @returns {Promise<void>}
762
+ */
763
+ async disableInterrupt(source) {
764
+ await this._ready;
765
+ if (((await this._rd(_REG_SYSTEM_INTERRUPT_CONFIG)) & 0x07) === source) {
766
+ await this._wr(_REG_SYSTEM_INTERRUPT_CONFIG, 0x00);
767
+ }
768
+ }
769
+
770
+ /**
771
+ * Read and clear the pending interrupt status.
772
+ * @returns {Promise<number>} The SOURCE_* value that fired, or 0 if nothing is pending.
773
+ */
774
+ async pollInterrupt() {
775
+ await this._ready;
776
+ return this._pollInterruptStatus();
777
+ }
778
+
779
+ /**
780
+ * Subscribe to GPIO1 interrupt events. With `connection.intPin` wired the
781
+ * callback runs on every falling edge (GPIO1 is active low); otherwise a
782
+ * 5 ms polling timer is used. The driver reads and clears the status
783
+ * before invoking the callback; the polling fallback consumes results, so
784
+ * don't mix it with `readContinuous()`.
785
+ * @param {(status: number) => void} callback - Receives the SOURCE_* value that fired.
786
+ * @returns {Promise<void>}
787
+ */
788
+ async onInterrupt(callback) {
789
+ await this._ready;
790
+ await this._subscribe(callback);
791
+ }
792
+
793
+ /**
794
+ * Unsubscribe and stop delivery.
795
+ * @returns {Promise<void>}
796
+ */
797
+ async offInterrupt() {
798
+ await this._unsubscribe();
799
+ }
800
+ }
801
+
802
+ /** Default 7-bit I²C address (family base value). */
803
+ VL53L0XMinimal.I2C_ADDRESS = VL53Base.I2C_ADDRESS;
804
+ /** Device range status meaning "range complete — valid". */
805
+ VL53L0XMinimal.RANGE_STATUS_VALID = _RANGE_STATUS_VALID;
806
+
807
+ /** Range < low threshold. */
808
+ VL53L0XFull.SOURCE_LEVEL_LOW = VL53Base.SOURCE_LEVEL_LOW;
809
+ /** Range > high threshold. */
810
+ VL53L0XFull.SOURCE_LEVEL_HIGH = VL53Base.SOURCE_LEVEL_HIGH;
811
+ /** Range < low threshold or > high threshold. */
812
+ VL53L0XFull.SOURCE_OUT_OF_WINDOW = VL53Base.SOURCE_OUT_OF_WINDOW;
813
+ /** A new measurement is available (driver default). */
814
+ VL53L0XFull.SOURCE_NEW_SAMPLE_READY = VL53Base.SOURCE_NEW_SAMPLE_READY;
815
+
816
+ module.exports = { VL53L0XMinimal, VL53L0XFull };