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,1600 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * FXOS8700CQ 6-axis e-compass driver — 14-bit accelerometer + 16-bit
5
+ * magnetometer (NXP).
6
+ *
7
+ * The FXOS8700CQ combines a three-axis MEMS accelerometer (±2 / ±4 / ±8 g,
8
+ * 0.244 / 0.488 / 0.976 mg/LSB) and a three-axis magnetometer (fixed ±1200 µT
9
+ * range, 0.1 µT/LSB) behind **one I²C address** and **one shared ADC**. In
10
+ * *hybrid mode* both sensors are sampled in an interleaved fashion at half the
11
+ * programmed output data rate (ODR) and all twelve data bytes can be read in a
12
+ * single burst. The accelerometer side adds a 32-sample FIFO, a high-pass
13
+ * filtered output, embedded freefall / motion, transient, tap, orientation and
14
+ * Auto-SLEEP / WAKE detectors; the magnetometer side adds hard-iron offsets,
15
+ * an autonomous min / max tracker with hardware auto-calibration and a
16
+ * relative die-temperature sensor.
17
+ *
18
+ * I²C framing is the plain register-pointer protocol (write the register
19
+ * address, repeated START, read). There is no auto-increment bit; multi-byte
20
+ * transfers auto-increment within one transaction.
21
+ *
22
+ * The vector-magnitude detectors (0x5F-0x72), the magnetic threshold detector
23
+ * (0x52-0x5A, `M_INT_SRC`) and the per-axis freefall / motion thresholds
24
+ * (0x73-0x78) are not wrapped by the API: use `readRegister()` /
25
+ * `writeRegister()`.
26
+ *
27
+ * The constructor starts the initialization sequence asynchronously; await
28
+ * `init()` (every public method also waits for it).
29
+ */
30
+
31
+ /** I²C address for SA1 = 0, SA0 = 0 (default). */
32
+ const I2C_ADDRESS = 0x1E;
33
+ /** All four selectable I²C addresses. */
34
+ const I2C_ADDRESSES = [0x1C, 0x1D, 0x1E, 0x1F];
35
+
36
+ // Registers.
37
+ const REG_STATUS = 0x00;
38
+ const REG_OUT_X_MSB = 0x01;
39
+ const REG_F_SETUP = 0x09;
40
+ const REG_TRIG_CFG = 0x0A;
41
+ const REG_SYSMOD = 0x0B;
42
+ const REG_INT_SOURCE = 0x0C;
43
+ const REG_WHO_AM_I = 0x0D;
44
+ const REG_XYZ_DATA_CFG = 0x0E;
45
+ const REG_HP_FILTER_CUTOFF = 0x0F;
46
+ const REG_PL_STATUS = 0x10;
47
+ const REG_PL_CFG = 0x11;
48
+ const REG_PL_COUNT = 0x12;
49
+ const REG_PL_BF_ZCOMP = 0x13;
50
+ const REG_PL_THS = 0x14;
51
+ const REG_A_FFMT_CFG = 0x15;
52
+ const REG_A_FFMT_SRC = 0x16;
53
+ const REG_A_FFMT_THS = 0x17;
54
+ const REG_A_FFMT_COUNT = 0x18;
55
+ const REG_TRANSIENT_CFG = 0x1D;
56
+ const REG_TRANSIENT_SRC = 0x1E;
57
+ const REG_TRANSIENT_THS = 0x1F;
58
+ const REG_TRANSIENT_COUNT = 0x20;
59
+ const REG_PULSE_CFG = 0x21;
60
+ const REG_PULSE_SRC = 0x22;
61
+ const REG_PULSE_THSX = 0x23;
62
+ const REG_PULSE_TMLT = 0x26;
63
+ const REG_PULSE_LTCY = 0x27;
64
+ const REG_PULSE_WIND = 0x28;
65
+ const REG_ASLP_COUNT = 0x29;
66
+ const REG_CTRL1 = 0x2A;
67
+ const REG_CTRL2 = 0x2B;
68
+ const REG_CTRL3 = 0x2C;
69
+ const REG_CTRL4 = 0x2D;
70
+ const REG_CTRL5 = 0x2E;
71
+ const REG_OFF_X = 0x2F;
72
+ const REG_M_DR_STATUS = 0x32;
73
+ const REG_M_OUT_X_MSB = 0x33;
74
+ const REG_M_OFF_X_MSB = 0x3F;
75
+ const REG_MAX_X_MSB = 0x45;
76
+ const REG_MIN_X_MSB = 0x4B;
77
+ const REG_TEMP = 0x51;
78
+ const REG_M_CTRL1 = 0x5B;
79
+ const REG_M_CTRL2 = 0x5C;
80
+ const REG_M_CTRL3 = 0x5D;
81
+
82
+ // Bit masks.
83
+ const CTRL1_ACTIVE = 0x01;
84
+ const CTRL1_F_READ = 0x02;
85
+ const CTRL1_LNOISE = 0x04;
86
+ const CTRL1_DR_MASK = 0x38;
87
+ const CTRL1_ASLP_MASK = 0xC0;
88
+ const CTRL2_ST = 0x80;
89
+ const CTRL2_RST = 0x40;
90
+ const CTRL2_SMODS_MASK = 0x18;
91
+ const CTRL2_SLPE = 0x04;
92
+ const CTRL2_MODS_MASK = 0x03;
93
+ const STATUS_ZYXDR = 0x08;
94
+ const M_CTRL1_ACAL = 0x80;
95
+ const M_CTRL1_RST = 0x40;
96
+ const M_CTRL1_OST = 0x20;
97
+ const M_CTRL1_OS_MASK = 0x1C;
98
+ const M_CTRL1_HMS_MASK = 0x03;
99
+ const M_CTRL2_HYB_AUTOINC = 0x20;
100
+
101
+ const WHO_AM_I_VALUES = [0xC7, 0xC4];
102
+
103
+ // System output data rates selected by CTRL_REG1.dr (Hz).
104
+ const ODR_HZ = [800.0, 400.0, 200.0, 100.0, 50.0, 12.5, 6.25, 1.5625];
105
+
106
+ // Debounce time steps in ms (also PULSE_TMLT with the pulse LPF on), indexed
107
+ // [mods][row]; `row` is the CTRL_REG1.dr code, shifted by one in hybrid mode.
108
+ const STEP_MS = [
109
+ [1.25, 2.5, 5.0, 10.0, 20.0, 20.0, 20.0, 20.0],
110
+ [1.25, 2.5, 5.0, 10.0, 20.0, 80.0, 80.0, 80.0],
111
+ [1.25, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5],
112
+ [1.25, 2.5, 5.0, 10.0, 20.0, 80.0, 160.0, 160.0],
113
+ ];
114
+
115
+ // PULSE_TMLT steps with the pulse low-pass filter off (LTCY / WIND are twice).
116
+ const PULSE_STEP_NO_LPF_MS = [
117
+ [0.625, 0.625, 1.25, 2.5, 5.0, 5.0, 5.0, 5.0],
118
+ [0.625, 0.625, 1.25, 2.5, 5.0, 20.0, 20.0, 20.0],
119
+ [0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625],
120
+ [0.625, 1.25, 2.5, 5.0, 10.0, 40.0, 40.0, 40.0],
121
+ ];
122
+
123
+ // Orientation trip angle (degrees) -> P_L_THS<4:0>.
124
+ const PL_THRESHOLDS = {
125
+ 15: 0x07, 20: 0x09, 30: 0x0C, 35: 0x0D, 40: 0x0F,
126
+ 45: 0x10, 55: 0x13, 60: 0x14, 70: 0x17, 75: 0x19,
127
+ };
128
+
129
+ // Auto-SLEEP rates (Hz) -> CTRL_REG1.aslp_rate.
130
+ const ASLP_RATES = [[50.0, 0], [12.5, 1], [6.25, 2], [1.56, 3]];
131
+
132
+ const COUNTS_PER_G = { 2: 4096.0, 4: 2048.0, 8: 1024.0 };
133
+ const MAG_UT_PER_LSB = 0.1;
134
+
135
+ /**
136
+ * Interrupt source constants for the FXOS8700.
137
+ *
138
+ * The values equal the bit positions of `INT_SOURCE`, `CTRL_REG4` and
139
+ * `CTRL_REG5`, so they are also the return mask of `pollInterrupt()`.
140
+ */
141
+ const FXOS8700Source = {
142
+ /** New sample (accelerometer in accel-only mode, magnetometer otherwise). */
143
+ SOURCE_DATA_READY: 0x01,
144
+ /** Accelerometer vector-magnitude change (configured via raw registers). */
145
+ SOURCE_ACCEL_VECM: 0x02,
146
+ /** Freefall / motion (`A_FFMT_SRC.ea`). */
147
+ SOURCE_FF_MT: 0x04,
148
+ /** Single / double tap (`PULSE_SRC.ea`). */
149
+ SOURCE_PULSE: 0x08,
150
+ /** Orientation change (`PL_STATUS.newlp`). */
151
+ SOURCE_ORIENTATION: 0x10,
152
+ /** Transient (`TRANSIENT_SRC.ea`). */
153
+ SOURCE_TRANSIENT: 0x20,
154
+ /** FIFO overflow or watermark. */
155
+ SOURCE_FIFO: 0x40,
156
+ /** WAKE <-> SLEEP transition. */
157
+ SOURCE_AUTO_SLEEP: 0x80,
158
+ };
159
+
160
+ /**
161
+ * Sleep `ms` milliseconds.
162
+ *
163
+ * @param {number} ms - Delay in milliseconds.
164
+ * @returns {Promise<void>}
165
+ */
166
+ function _delayMs(ms) {
167
+ return new Promise((resolve) => setTimeout(resolve, ms));
168
+ }
169
+
170
+ /**
171
+ * Clamp `value` into `[low, high]`.
172
+ *
173
+ * @param {number} value - Value.
174
+ * @param {number} low - Lower bound.
175
+ * @param {number} high - Upper bound.
176
+ * @returns {number} Clamped value.
177
+ */
178
+ function _clamp(value, low, high) {
179
+ return value < low ? low : (value > high ? high : value);
180
+ }
181
+
182
+ /**
183
+ * Sign-extend an unsigned 16-bit value.
184
+ *
185
+ * @param {number} value - Raw 16-bit value.
186
+ * @returns {number} Signed value.
187
+ */
188
+ function _toSigned16(value) {
189
+ return value & 0x8000 ? value - 0x10000 : value;
190
+ }
191
+
192
+ /**
193
+ * Sign-extend an unsigned 8-bit value.
194
+ *
195
+ * @param {number} value - Raw 8-bit value.
196
+ * @returns {number} Signed value.
197
+ */
198
+ function _toSigned8(value) {
199
+ return value & 0x80 ? value - 0x100 : value;
200
+ }
201
+
202
+ /**
203
+ * FXOS8700 minimal interface — acceleration and magnetic field.
204
+ *
205
+ * The constructor starts the datasheet initialization sequence: it verifies
206
+ * `WHO_AM_I` (0xC7, or 0xC4 on pre-production parts), performs a software
207
+ * reset and starts hybrid mode.
208
+ *
209
+ * Default configuration: hybrid mode, system ODR 200 Hz (100 Hz per sensor),
210
+ * ±2 g (4096 counts/g), 14-bit output, normal accelerometer oversampling,
211
+ * magnetometer OSR 7, low-noise off, `hyb_autoinc_mode` on, no FIFO, no
212
+ * detectors, no interrupt routing, interrupts active-low push-pull.
213
+ */
214
+ class FXOS8700Minimal {
215
+ /**
216
+ * @param {object} connection - Register connection (I²C) bound to 0x1C-0x1F.
217
+ */
218
+ constructor(connection) {
219
+ this._conn = connection;
220
+ this._mode = 2; // 0 accel only, 1 mag only, 2 hybrid
221
+ this._dr = 2; // CTRL_REG1.dr code
222
+ this._fsG = 2;
223
+ this._mods = 0; // accelerometer oversampling (wake)
224
+ this._lnoise = false;
225
+ this._fRead = false; // true = 8-bit fast read
226
+ this._fifoMode = 0;
227
+ this._hyb = true; // hyb_autoinc_mode
228
+ this._ready = this._runInit();
229
+ // The rejection is re-raised by every public method.
230
+ this._ready.catch(() => {});
231
+ }
232
+
233
+ /**
234
+ * Wait for the initialization sequence started by the constructor.
235
+ *
236
+ * @returns {Promise<void>}
237
+ * @throws {Error} If `WHO_AM_I` is neither 0xC7 nor 0xC4.
238
+ */
239
+ async init() {
240
+ await this._ready;
241
+ }
242
+
243
+ /**
244
+ * Run the initialization sequence: verify `WHO_AM_I`, software reset (the
245
+ * `rst` write is not acknowledged and the NACK is ignored) and start
246
+ * hybrid mode at 200 Hz system ODR, ±2 g, magnetometer OSR 7.
247
+ *
248
+ * @returns {Promise<void>}
249
+ */
250
+ async _runInit() {
251
+ await _delayMs(1);
252
+ if (!WHO_AM_I_VALUES.includes(await this._whoAmI())) {
253
+ throw new Error('FXOS8700 not found: unexpected WHO_AM_I');
254
+ }
255
+ await this._softReset();
256
+ if (!WHO_AM_I_VALUES.includes(await this._whoAmI())) {
257
+ throw new Error('FXOS8700 not found after reset');
258
+ }
259
+ await this._conn.writeReg(REG_CTRL1, 0x00);
260
+ await this._conn.writeReg(REG_M_CTRL1, 0x1F);
261
+ await this._conn.writeReg(REG_M_CTRL2, M_CTRL2_HYB_AUTOINC);
262
+ await this._conn.writeReg(REG_XYZ_DATA_CFG, 0x00);
263
+ await this._conn.writeReg(REG_CTRL2, 0x00);
264
+ await this._conn.writeReg(REG_CTRL1, 0x11);
265
+ this._mode = 2;
266
+ this._dr = 2;
267
+ this._fsG = 2;
268
+ this._mods = 0;
269
+ this._lnoise = false;
270
+ this._fRead = false;
271
+ this._fifoMode = 0;
272
+ this._hyb = true;
273
+ await _delayMs(this._turnOnMs());
274
+ }
275
+
276
+ /**
277
+ * Read `WHO_AM_I`, retrying on NACK for up to 10 ms.
278
+ *
279
+ * @returns {Promise<number>} The identity byte.
280
+ */
281
+ async _whoAmI() {
282
+ for (let attempt = 0; attempt < 10; attempt++) {
283
+ try {
284
+ return (await this._conn.readReg(REG_WHO_AM_I, 1))[0];
285
+ } catch (e) {
286
+ await _delayMs(1);
287
+ }
288
+ }
289
+ return (await this._conn.readReg(REG_WHO_AM_I, 1))[0];
290
+ }
291
+
292
+ /**
293
+ * Write `CTRL_REG2.rst` tolerating the missing ACK, then wait 2 ms.
294
+ *
295
+ * @returns {Promise<void>}
296
+ */
297
+ async _softReset() {
298
+ try {
299
+ await this._conn.writeReg(REG_CTRL2, CTRL2_RST);
300
+ } catch (e) {
301
+ // The chip resets its I²C interface and does not ACK.
302
+ }
303
+ await _delayMs(2);
304
+ }
305
+
306
+ /**
307
+ * Read the acceleration.
308
+ *
309
+ * @returns {Promise<{x:number, y:number, z:number}>} Acceleration in g.
310
+ */
311
+ async readAccel() {
312
+ await this._ready;
313
+ const raw = await this._readAccelCounts();
314
+ const scale = this._accelScale();
315
+ return { x: raw.x / scale, y: raw.y / scale, z: raw.z / scale };
316
+ }
317
+
318
+ /**
319
+ * Read the magnetic flux density.
320
+ *
321
+ * Reading `M_OUT_X_MSB` first latches the X / Y / Z set, so the six bytes
322
+ * are always read as one burst.
323
+ *
324
+ * @returns {Promise<{x:number, y:number, z:number}>} Field in µT.
325
+ */
326
+ async readMag() {
327
+ await this._ready;
328
+ const raw = await this._readMagCounts();
329
+ return { x: raw.x * MAG_UT_PER_LSB, y: raw.y * MAG_UT_PER_LSB, z: raw.z * MAG_UT_PER_LSB };
330
+ }
331
+
332
+ // --- Helpers shared with FXOS8700Full --------------------------------
333
+
334
+ /**
335
+ * Counts per g at the current range and resolution.
336
+ *
337
+ * @returns {number} Counts per g.
338
+ */
339
+ _accelScale() {
340
+ const cpg = COUNTS_PER_G[this._fsG];
341
+ return this._fRead ? cpg / 64.0 : cpg;
342
+ }
343
+
344
+ /**
345
+ * Decode three accelerometer axes from a buffer.
346
+ *
347
+ * @param {Buffer} data - Raw bytes.
348
+ * @param {number} [offset=0] - Start index.
349
+ * @returns {{x:number, y:number, z:number}} Signed counts.
350
+ */
351
+ _decodeAccel(data, offset = 0) {
352
+ if (this._fRead) {
353
+ return {
354
+ x: _toSigned8(data[offset]),
355
+ y: _toSigned8(data[offset + 1]),
356
+ z: _toSigned8(data[offset + 2]),
357
+ };
358
+ }
359
+ const axis = (i) => _toSigned16((data[offset + 2 * i] << 8) | data[offset + 2 * i + 1]) >> 2;
360
+ return { x: axis(0), y: axis(1), z: axis(2) };
361
+ }
362
+
363
+ /**
364
+ * Read the signed accelerometer counts (14-bit, or 8-bit in fast read).
365
+ *
366
+ * @returns {Promise<{x:number, y:number, z:number}>} Counts.
367
+ */
368
+ async _readAccelCounts() {
369
+ const n = this._fRead ? 3 : 6;
370
+ return this._decodeAccel(await this._conn.readReg(REG_OUT_X_MSB, n));
371
+ }
372
+
373
+ /**
374
+ * Decode three magnetometer axes (16-bit, MSB first).
375
+ *
376
+ * @param {Buffer} data - Raw bytes.
377
+ * @param {number} [offset=0] - Start index.
378
+ * @returns {{x:number, y:number, z:number}} Signed counts.
379
+ */
380
+ _decodeMag(data, offset = 0) {
381
+ const axis = (i) => _toSigned16((data[offset + 2 * i] << 8) | data[offset + 2 * i + 1]);
382
+ return { x: axis(0), y: axis(1), z: axis(2) };
383
+ }
384
+
385
+ /**
386
+ * Read the signed magnetometer counts.
387
+ *
388
+ * @returns {Promise<{x:number, y:number, z:number}>} Counts.
389
+ */
390
+ async _readMagCounts() {
391
+ return this._decodeMag(await this._conn.readReg(REG_M_OUT_X_MSB, 6));
392
+ }
393
+
394
+ /**
395
+ * System output data rate in Hz.
396
+ *
397
+ * @returns {number} ODR.
398
+ */
399
+ _odrHz() {
400
+ return ODR_HZ[this._dr];
401
+ }
402
+
403
+ /**
404
+ * STANDBY -> ACTIVE turn-on time, 2 / ODR + 2 ms (rounded up).
405
+ *
406
+ * @returns {number} Milliseconds.
407
+ */
408
+ _turnOnMs() {
409
+ return Math.floor(2000.0 / this._odrHz()) + 3;
410
+ }
411
+ }
412
+
413
+ const _FXOS8700FullMixin = (Base) => class extends Base {
414
+ /**
415
+ * @param {object} connection - Register connection (I²C) bound to 0x1C-0x1F.
416
+ */
417
+ constructor(connection) {
418
+ super(connection);
419
+ this._callback = null;
420
+ this._intPinUsed = null;
421
+ this._pollTimer = null;
422
+ this._lastStatus = 0;
423
+ }
424
+
425
+ // --- Mode / power ----------------------------------------------------
426
+
427
+ /**
428
+ * Enter STANDBY (`active` = 0) and wait until `SYSMOD` reads 0 (up to
429
+ * 300 ms when leaving mag-only / hybrid mode).
430
+ *
431
+ * @returns {Promise<void>}
432
+ */
433
+ async standby() {
434
+ await this._ready;
435
+ const c1 = (await this._conn.readReg(REG_CTRL1, 1))[0];
436
+ await this._conn.writeReg(REG_CTRL1, c1 & ~CTRL1_ACTIVE & 0xFF);
437
+ await this._waitStandby();
438
+ }
439
+
440
+ /**
441
+ * Enter ACTIVE (`active` = 1) and wait the turn-on time.
442
+ *
443
+ * @returns {Promise<void>}
444
+ */
445
+ async activate() {
446
+ await this._ready;
447
+ const c1 = (await this._conn.readReg(REG_CTRL1, 1))[0];
448
+ await this._conn.writeReg(REG_CTRL1, c1 | CTRL1_ACTIVE);
449
+ await _delayMs(this._turnOnMs());
450
+ }
451
+
452
+ /**
453
+ * Poll `SYSMOD` until it reads 00 (up to 350 ms).
454
+ *
455
+ * @returns {Promise<void>}
456
+ * @throws {Error} If the chip does not reach STANDBY.
457
+ */
458
+ async _waitStandby() {
459
+ for (let i = 0; i < 350; i++) {
460
+ if (((await this._conn.readReg(REG_SYSMOD, 1))[0] & 0x03) === 0) {
461
+ return;
462
+ }
463
+ await _delayMs(1);
464
+ }
465
+ throw new Error('FXOS8700 did not enter STANDBY');
466
+ }
467
+
468
+ /**
469
+ * Enter STANDBY if ACTIVE.
470
+ *
471
+ * @returns {Promise<boolean>} Whether the chip was ACTIVE.
472
+ */
473
+ async _begin() {
474
+ await this._ready;
475
+ const c1 = (await this._conn.readReg(REG_CTRL1, 1))[0];
476
+ if (c1 & CTRL1_ACTIVE) {
477
+ await this._conn.writeReg(REG_CTRL1, c1 & ~CTRL1_ACTIVE & 0xFF);
478
+ await this._waitStandby();
479
+ return true;
480
+ }
481
+ return false;
482
+ }
483
+
484
+ /**
485
+ * Restore ACTIVE if `wasActive`.
486
+ *
487
+ * @param {boolean} wasActive - Value returned by `_begin()`.
488
+ * @returns {Promise<void>}
489
+ */
490
+ async _end(wasActive) {
491
+ if (wasActive) {
492
+ await this.activate();
493
+ }
494
+ }
495
+
496
+ /**
497
+ * Read-modify-write a register: clear `mask`, OR in `value`.
498
+ *
499
+ * @param {number} reg - Register.
500
+ * @param {number} mask - Bits to replace.
501
+ * @param {number} value - New bits.
502
+ * @returns {Promise<void>}
503
+ */
504
+ async _modify(reg, mask, value) {
505
+ const cur = (await this._conn.readReg(reg, 1))[0];
506
+ await this._conn.writeReg(reg, (cur & ~mask & 0xFF) | (value & mask));
507
+ }
508
+
509
+ /**
510
+ * Software reset (`CTRL_REG2.rst`). The chip does not acknowledge the
511
+ * write (tolerated) and returns to STANDBY with every register at its
512
+ * reset value. Create a new driver (or call `_runInit()`) afterwards.
513
+ *
514
+ * @returns {Promise<void>}
515
+ */
516
+ async reset() {
517
+ await this._ready;
518
+ await this._softReset();
519
+ this._mode = 0;
520
+ this._dr = 0;
521
+ this._fsG = 2;
522
+ this._mods = 0;
523
+ this._lnoise = false;
524
+ this._fRead = false;
525
+ this._fifoMode = 0;
526
+ this._hyb = false;
527
+ }
528
+
529
+ /**
530
+ * Re-run the initialization sequence (use after `reset()`).
531
+ *
532
+ * @returns {Promise<void>}
533
+ */
534
+ async reinit() {
535
+ this._ready = this._runInit();
536
+ this._ready.catch(() => {});
537
+ await this._ready;
538
+ }
539
+
540
+ /**
541
+ * Select accelerometer-only, magnetometer-only or hybrid operation.
542
+ *
543
+ * @param {number} mode - 0 accelerometer only, 1 magnetometer only, 2 hybrid.
544
+ * @returns {Promise<void>}
545
+ * @throws {Error} If `mode` is not 0, 1 or 2.
546
+ */
547
+ async setMode(mode) {
548
+ if (![0, 1, 2].includes(mode)) {
549
+ throw new Error('mode must be 0, 1 or 2');
550
+ }
551
+ const was = await this._begin();
552
+ await this._modify(REG_M_CTRL1, M_CTRL1_HMS_MASK, [0, 1, 3][mode]);
553
+ if (mode === 2) {
554
+ await this._modify(REG_M_CTRL2, M_CTRL2_HYB_AUTOINC, M_CTRL2_HYB_AUTOINC);
555
+ this._hyb = true;
556
+ }
557
+ this._mode = mode;
558
+ await this._end(was);
559
+ }
560
+
561
+ /**
562
+ * Select the accelerometer full-scale range.
563
+ *
564
+ * @param {number} rangeG - 2, 4 or 8 (g).
565
+ * @returns {Promise<void>}
566
+ * @throws {Error} For any other value, or 8 while low-noise mode is on.
567
+ */
568
+ async setRange(rangeG) {
569
+ await this._ready;
570
+ if (![2, 4, 8].includes(rangeG)) {
571
+ throw new Error('rangeG must be 2, 4 or 8');
572
+ }
573
+ if (rangeG === 8 && this._lnoise) {
574
+ throw new Error('±8 g is not available in low-noise mode');
575
+ }
576
+ await this._modify(REG_XYZ_DATA_CFG, 0x03, { 2: 0, 4: 1, 8: 2 }[rangeG]);
577
+ this._fsG = rangeG;
578
+ }
579
+
580
+ /**
581
+ * Select the system output data rate (each sensor runs at half this rate
582
+ * in hybrid mode).
583
+ *
584
+ * @param {number} rateHz - 800, 400, 200, 100, 50, 12.5, 6.25 or 1.5625 (1.56 accepted).
585
+ * @returns {Promise<void>}
586
+ * @throws {Error} If the rate is not supported.
587
+ */
588
+ async setDataRate(rateHz) {
589
+ let code = -1;
590
+ ODR_HZ.forEach((hz, i) => {
591
+ if (Math.abs(hz - rateHz) <= 0.01 * hz) {
592
+ code = i;
593
+ }
594
+ });
595
+ if (code < 0) {
596
+ throw new Error('unsupported data rate');
597
+ }
598
+ const was = await this._begin();
599
+ await this._modify(REG_CTRL1, CTRL1_DR_MASK, code << 3);
600
+ this._dr = code;
601
+ await this._end(was);
602
+ }
603
+
604
+ /**
605
+ * Select the accelerometer oversampling mode.
606
+ *
607
+ * @param {number} mode - 0 normal, 1 low-noise low-power, 2 high resolution, 3 low power.
608
+ * @param {?number} [sleepMode=null] - Same encoding for SLEEP mode; unchanged if null.
609
+ * @returns {Promise<void>}
610
+ * @throws {Error} If a mode is outside 0-3.
611
+ */
612
+ async setAccelOversampling(mode, sleepMode = null) {
613
+ if (![0, 1, 2, 3].includes(mode) || (sleepMode !== null && ![0, 1, 2, 3].includes(sleepMode))) {
614
+ throw new Error('oversampling mode must be 0-3');
615
+ }
616
+ const was = await this._begin();
617
+ await this._modify(REG_CTRL2, CTRL2_MODS_MASK, mode);
618
+ if (sleepMode !== null) {
619
+ await this._modify(REG_CTRL2, CTRL2_SMODS_MASK, sleepMode << 3);
620
+ }
621
+ this._mods = mode;
622
+ await this._end(was);
623
+ }
624
+
625
+ /**
626
+ * Select the magnetometer oversampling ratio code (`m_os`, datasheet
627
+ * Table 203; e.g. at 200 Hz 0-5 give 2x, 6 gives 4x and 7 gives 8x).
628
+ *
629
+ * @param {number} ratio - 0-7 for active mode.
630
+ * @param {?number} [sleepRatio=null] - 0-7 for Auto-SLEEP; unchanged if null.
631
+ * @returns {Promise<void>}
632
+ * @throws {Error} If a value is outside 0-7.
633
+ */
634
+ async setMagOversampling(ratio, sleepRatio = null) {
635
+ await this._ready;
636
+ const ok = (v) => Number.isInteger(v) && v >= 0 && v <= 7;
637
+ if (!ok(ratio) || (sleepRatio !== null && !ok(sleepRatio))) {
638
+ throw new Error('oversampling ratio must be 0-7');
639
+ }
640
+ await this._modify(REG_M_CTRL1, M_CTRL1_OS_MASK, ratio << 2);
641
+ if (sleepRatio !== null) {
642
+ await this._modify(REG_M_CTRL3, 0x70, sleepRatio << 4);
643
+ }
644
+ }
645
+
646
+ /**
647
+ * Enable or disable the reduced-noise mode (`lnoise`).
648
+ *
649
+ * @param {boolean} enabled - True to enable; limits the range to ±4 g.
650
+ * @returns {Promise<void>}
651
+ * @throws {Error} If enabling while the range is ±8 g.
652
+ */
653
+ async setLowNoise(enabled) {
654
+ await this._ready;
655
+ if (enabled && this._fsG === 8) {
656
+ throw new Error('low-noise mode is not available at ±8 g');
657
+ }
658
+ const was = await this._begin();
659
+ await this._modify(REG_CTRL1, CTRL1_LNOISE, enabled ? CTRL1_LNOISE : 0);
660
+ this._lnoise = !!enabled;
661
+ await this._end(was);
662
+ }
663
+
664
+ /**
665
+ * Select 14-bit or 8-bit (fast read) accelerometer output.
666
+ *
667
+ * @param {number} bits - 14 or 8.
668
+ * @returns {Promise<void>}
669
+ * @throws {Error} If `bits` is not 14 or 8, or the FIFO is on.
670
+ */
671
+ async setResolution(bits) {
672
+ await this._ready;
673
+ if (bits !== 14 && bits !== 8) {
674
+ throw new Error('bits must be 14 or 8');
675
+ }
676
+ if (this._fifoMode !== 0) {
677
+ throw new Error('resolution cannot change while the FIFO is on');
678
+ }
679
+ const was = await this._begin();
680
+ await this._modify(REG_CTRL1, CTRL1_F_READ, bits === 8 ? CTRL1_F_READ : 0);
681
+ this._fRead = bits === 8;
682
+ await this._end(was);
683
+ }
684
+
685
+ // --- Data ----------------------------------------------------------------
686
+
687
+ /**
688
+ * Read the raw accelerometer counts.
689
+ *
690
+ * @returns {Promise<{x:number, y:number, z:number}>} Signed counts (14-bit right-aligned, or 8-bit).
691
+ */
692
+ async readRawAccel() {
693
+ await this._ready;
694
+ return this._readAccelCounts();
695
+ }
696
+
697
+ /**
698
+ * Read the raw magnetometer counts.
699
+ *
700
+ * @returns {Promise<{x:number, y:number, z:number}>} Signed 16-bit counts (0.1 µT/LSB).
701
+ */
702
+ async readRawMag() {
703
+ await this._ready;
704
+ return this._readMagCounts();
705
+ }
706
+
707
+ /**
708
+ * Read accelerometer and magnetometer with one burst from 0x01.
709
+ *
710
+ * @returns {Promise<{accel:{x:number,y:number,z:number}, mag:{x:number,y:number,z:number}}>}
711
+ * Acceleration in g and magnetic field in µT.
712
+ * @throws {Error} If the chip is not in hybrid mode.
713
+ */
714
+ async readHybrid() {
715
+ await this._ready;
716
+ if (this._mode !== 2 || !this._hyb) {
717
+ throw new Error('readHybrid needs hybrid mode with hyb_autoinc_mode');
718
+ }
719
+ const nAccel = this._fRead ? 3 : 6;
720
+ const data = await this._conn.readReg(REG_OUT_X_MSB, nAccel + 6);
721
+ const acc = this._decodeAccel(data, 0);
722
+ const mag = this._decodeMag(data, nAccel);
723
+ const scale = this._accelScale();
724
+ return {
725
+ accel: { x: acc.x / scale, y: acc.y / scale, z: acc.z / scale },
726
+ mag: { x: mag.x * MAG_UT_PER_LSB, y: mag.y * MAG_UT_PER_LSB, z: mag.z * MAG_UT_PER_LSB },
727
+ };
728
+ }
729
+
730
+ /**
731
+ * Read the die temperature (`int8(TEMP) * 0.96`; relative, uncalibrated).
732
+ *
733
+ * @returns {Promise<number>} Temperature in °C.
734
+ * @throws {Error} In accelerometer-only mode.
735
+ */
736
+ async readTemperature() {
737
+ await this._ready;
738
+ if (this._mode === 0) {
739
+ throw new Error('temperature needs the magnetometer to be active');
740
+ }
741
+ return _toSigned8((await this._conn.readReg(REG_TEMP, 1))[0]) * 0.96;
742
+ }
743
+
744
+ /**
745
+ * Whether a new accelerometer sample is ready (`STATUS.zyxdr`; not valid
746
+ * while the FIFO is on).
747
+ *
748
+ * @returns {Promise<boolean>} True if new data is available.
749
+ */
750
+ async newAccelData() {
751
+ await this._ready;
752
+ return ((await this._conn.readReg(REG_STATUS, 1))[0] & STATUS_ZYXDR) !== 0;
753
+ }
754
+
755
+ /**
756
+ * Whether a new magnetometer sample is ready (`M_DR_STATUS.zyxdr`).
757
+ *
758
+ * @returns {Promise<boolean>} True if new data is available.
759
+ */
760
+ async newMagData() {
761
+ await this._ready;
762
+ return ((await this._conn.readReg(REG_M_DR_STATUS, 1))[0] & STATUS_ZYXDR) !== 0;
763
+ }
764
+
765
+ /**
766
+ * Read the `STATUS` byte.
767
+ *
768
+ * @returns {Promise<number>} Status byte.
769
+ */
770
+ async readStatus() {
771
+ await this._ready;
772
+ return (await this._conn.readReg(REG_STATUS, 1))[0];
773
+ }
774
+
775
+ /**
776
+ * Read the `M_DR_STATUS` byte.
777
+ *
778
+ * @returns {Promise<number>} Status byte.
779
+ */
780
+ async readMagStatus() {
781
+ await this._ready;
782
+ return (await this._conn.readReg(REG_M_DR_STATUS, 1))[0];
783
+ }
784
+
785
+ /**
786
+ * Read `SYSMOD` bits 1:0.
787
+ *
788
+ * @returns {Promise<number>} 0 standby, 1 wake, 2 sleep.
789
+ */
790
+ async readSystemMode() {
791
+ await this._ready;
792
+ return (await this._conn.readReg(REG_SYSMOD, 1))[0] & 0x03;
793
+ }
794
+
795
+ /**
796
+ * Select high-pass-filtered output data. The cutoff in Hz depends on ODR
797
+ * and oversampling mode (datasheet Table 64; effective ODR halved in
798
+ * hybrid mode).
799
+ *
800
+ * @param {boolean} enabled - True to output high-pass-filtered data (`hpf_out`).
801
+ * @param {number} [cutoff=0] - `sel` code 0-3.
802
+ * @returns {Promise<void>}
803
+ * @throws {Error} If `cutoff` is outside 0-3.
804
+ */
805
+ async setHighPassOutput(enabled, cutoff = 0) {
806
+ await this._ready;
807
+ if (![0, 1, 2, 3].includes(cutoff)) {
808
+ throw new Error('cutoff must be 0-3');
809
+ }
810
+ const was = await this._begin();
811
+ await this._modify(REG_XYZ_DATA_CFG, 0x10, enabled ? 0x10 : 0);
812
+ await this._modify(REG_HP_FILTER_CUTOFF, 0x03, cutoff);
813
+ await this._end(was);
814
+ }
815
+
816
+ /**
817
+ * Write the per-axis accelerometer offset registers (added to the
818
+ * measurement; 2 mg/LSB, ±0.256 g).
819
+ *
820
+ * @param {number} xG - X offset in g.
821
+ * @param {number} yG - Y offset in g.
822
+ * @param {number} zG - Z offset in g.
823
+ * @returns {Promise<void>}
824
+ */
825
+ async setAccelOffset(xG, yG, zG) {
826
+ const data = Buffer.from([xG, yG, zG].map((v) => _clamp(Math.round(v / 0.002), -128, 127) & 0xFF));
827
+ const was = await this._begin();
828
+ await this._conn.writeReg(REG_OFF_X, data);
829
+ await this._end(was);
830
+ }
831
+
832
+ /**
833
+ * Read the accelerometer offsets.
834
+ *
835
+ * @returns {Promise<{x:number, y:number, z:number}>} Offsets in g.
836
+ */
837
+ async getAccelOffset() {
838
+ await this._ready;
839
+ const d = await this._conn.readReg(REG_OFF_X, 3);
840
+ return { x: _toSigned8(d[0]) * 0.002, y: _toSigned8(d[1]) * 0.002, z: _toSigned8(d[2]) * 0.002 };
841
+ }
842
+
843
+ /**
844
+ * Write the hard-iron offset registers (15-bit value in bits 15:1,
845
+ * subtracted from each measurement, 0.1 µT/LSB).
846
+ *
847
+ * @param {number} xUt - X offset to subtract, in µT.
848
+ * @param {number} yUt - Y offset to subtract, in µT.
849
+ * @param {number} zUt - Z offset to subtract, in µT.
850
+ * @returns {Promise<void>}
851
+ */
852
+ async setMagOffset(xUt, yUt, zUt) {
853
+ await this._ready;
854
+ const out = [];
855
+ for (const v of [xUt, yUt, zUt]) {
856
+ const word = (_clamp(Math.round(v / 0.1), -16384, 16383) << 1) & 0xFFFF;
857
+ out.push(word >> 8, word & 0xFF);
858
+ }
859
+ await this._conn.writeReg(REG_M_OFF_X_MSB, Buffer.from(out));
860
+ }
861
+
862
+ /**
863
+ * Read the hard-iron offsets.
864
+ *
865
+ * @returns {Promise<{x:number, y:number, z:number}>} Offsets in µT.
866
+ */
867
+ async getMagOffset() {
868
+ await this._ready;
869
+ const d = await this._conn.readReg(REG_M_OFF_X_MSB, 6);
870
+ const axis = (i) => (_toSigned16((d[2 * i] << 8) | d[2 * i + 1]) >> 1) * 0.1;
871
+ return { x: axis(0), y: axis(1), z: axis(2) };
872
+ }
873
+
874
+ /**
875
+ * Select raw magnetometer output (`m_raw`).
876
+ *
877
+ * @param {boolean} raw - True = hard-iron offsets are not applied to the output.
878
+ * @returns {Promise<void>}
879
+ */
880
+ async setMagRaw(raw) {
881
+ await this._ready;
882
+ await this._modify(REG_M_CTRL3, 0x80, raw ? 0x80 : 0);
883
+ }
884
+
885
+ /**
886
+ * Enable or disable hardware hard-iron auto-calibration (`m_acal`).
887
+ * Enabling also clears `m_raw` and enables min/max tracking. Rotate the
888
+ * board through all orientations while on; the offsets stay in `M_OFF_*`
889
+ * afterwards (NXP AN4399).
890
+ *
891
+ * @param {boolean} enabled - True to enable.
892
+ * @returns {Promise<void>}
893
+ */
894
+ async setMagAutoCalibration(enabled) {
895
+ await this._ready;
896
+ if (enabled) {
897
+ await this._modify(REG_M_CTRL3, 0x80, 0);
898
+ const was = await this._begin();
899
+ await this._modify(REG_M_CTRL2, 0x10, 0);
900
+ await this._end(was);
901
+ }
902
+ await this._modify(REG_M_CTRL1, M_CTRL1_ACAL, enabled ? M_CTRL1_ACAL : 0);
903
+ }
904
+
905
+ /**
906
+ * Read the tracked magnetic minimum and maximum.
907
+ *
908
+ * @returns {Promise<{min:{x:number,y:number,z:number}, max:{x:number,y:number,z:number}}>} Values in µT.
909
+ */
910
+ async readMagMinMax() {
911
+ await this._ready;
912
+ const mn = this._decodeMag(await this._conn.readReg(REG_MIN_X_MSB, 6));
913
+ const mx = this._decodeMag(await this._conn.readReg(REG_MAX_X_MSB, 6));
914
+ const k = MAG_UT_PER_LSB;
915
+ return {
916
+ min: { x: mn.x * k, y: mn.y * k, z: mn.z * k },
917
+ max: { x: mx.x * k, y: mx.y * k, z: mx.z * k },
918
+ };
919
+ }
920
+
921
+ /**
922
+ * Reset the min/max registers to 0x7FFF / 0x8000 (`m_maxmin_rst`).
923
+ *
924
+ * @returns {Promise<void>}
925
+ */
926
+ async resetMagMinMax() {
927
+ await this._ready;
928
+ await this._modify(REG_M_CTRL2, 0x04, 0x04);
929
+ }
930
+
931
+ /**
932
+ * Select the automatic magnetic reset (degauss) period.
933
+ *
934
+ * @param {number} mode - 0 every ODR cycle, 1 every 16, 2 every 512, 3 disabled.
935
+ * @returns {Promise<void>}
936
+ * @throws {Error} If `mode` is outside 0-3.
937
+ */
938
+ async setMagReset(mode) {
939
+ await this._ready;
940
+ if (![0, 1, 2, 3].includes(mode)) {
941
+ throw new Error('mode must be 0-3');
942
+ }
943
+ const was = await this._begin();
944
+ await this._modify(REG_M_CTRL2, 0x03, mode);
945
+ await this._end(was);
946
+ }
947
+
948
+ /**
949
+ * Trigger a one-shot magnetic reset (`m_rst`).
950
+ *
951
+ * @returns {Promise<void>}
952
+ */
953
+ async triggerMagReset() {
954
+ await this._ready;
955
+ await this._modify(REG_M_CTRL1, M_CTRL1_RST, M_CTRL1_RST);
956
+ }
957
+
958
+ /**
959
+ * Take one magnetic measurement in STANDBY (`m_ost`); ACTIVE is restored.
960
+ *
961
+ * @returns {Promise<{x:number, y:number, z:number}>} Field in µT.
962
+ * @throws {Error} In accelerometer-only mode or if the measurement times out (1 s).
963
+ */
964
+ async measureMagOnce() {
965
+ await this._ready;
966
+ if (this._mode === 0) {
967
+ throw new Error('one-shot measurement needs the magnetometer');
968
+ }
969
+ const was = await this._begin();
970
+ await this._modify(REG_M_CTRL1, M_CTRL1_OST, M_CTRL1_OST);
971
+ let done = false;
972
+ for (let i = 0; i < 1000; i++) {
973
+ if (((await this._conn.readReg(REG_M_CTRL1, 1))[0] & M_CTRL1_OST) === 0) {
974
+ done = true;
975
+ break;
976
+ }
977
+ await _delayMs(1);
978
+ }
979
+ if (!done) {
980
+ await this._end(was);
981
+ throw new Error('magnetic one-shot measurement timed out');
982
+ }
983
+ const value = await this.readMag();
984
+ await this._end(was);
985
+ return value;
986
+ }
987
+
988
+ /**
989
+ * Compute the tilt-compensated compass heading from one accelerometer and
990
+ * one magnetometer sample (chip frame: X forward, Y right, Z down; verify
991
+ * the axis signs on hardware).
992
+ *
993
+ * @param {number} [declinationDeg=0] - Magnetic declination added to the result.
994
+ * @returns {Promise<number>} Heading in degrees, [0, 360).
995
+ */
996
+ async heading(declinationDeg = 0.0) {
997
+ await this._ready;
998
+ let a;
999
+ let m;
1000
+ if (this._mode === 2 && this._hyb) {
1001
+ ({ accel: a, mag: m } = await this.readHybrid());
1002
+ } else {
1003
+ a = await this.readAccel();
1004
+ m = await this.readMag();
1005
+ }
1006
+ const roll = Math.atan2(a.y, a.z);
1007
+ const pitch = Math.atan2(-a.x, a.y * Math.sin(roll) + a.z * Math.cos(roll));
1008
+ const mx2 = m.x * Math.cos(pitch) + m.z * Math.sin(pitch);
1009
+ const my2 = m.x * Math.sin(roll) * Math.sin(pitch) + m.y * Math.cos(roll)
1010
+ - m.z * Math.sin(roll) * Math.cos(pitch);
1011
+ const deg = Math.atan2(-my2, mx2) * 180 / Math.PI + declinationDeg;
1012
+ return ((deg % 360) + 360) % 360;
1013
+ }
1014
+
1015
+ // --- FIFO ----------------------------------------------------------------
1016
+
1017
+ /**
1018
+ * Configure the 32-sample accelerometer FIFO. Changing between two enabled
1019
+ * modes goes through disabled. The FIFO holds accelerometer data only.
1020
+ *
1021
+ * @param {number} mode - 0 disabled, 1 circular, 2 fill, 3 trigger.
1022
+ * @param {number} [watermark=0] - 0-63 (0 disables the flag).
1023
+ * @returns {Promise<void>}
1024
+ * @throws {Error} If an argument is out of range.
1025
+ */
1026
+ async setFifo(mode, watermark = 0) {
1027
+ await this._ready;
1028
+ if (![0, 1, 2, 3].includes(mode) || !Number.isInteger(watermark) || watermark < 0 || watermark > 63) {
1029
+ throw new Error('invalid FIFO mode or watermark');
1030
+ }
1031
+ const was = await this._begin();
1032
+ if (this._fifoMode !== 0 && mode !== 0 && mode !== this._fifoMode) {
1033
+ await this._conn.writeReg(REG_F_SETUP, 0x00);
1034
+ }
1035
+ await this._conn.writeReg(REG_F_SETUP, (mode << 6) | watermark);
1036
+ this._fifoMode = mode;
1037
+ await this._end(was);
1038
+ }
1039
+
1040
+ /**
1041
+ * Select the FIFO trigger sources (`TRIG_CFG`).
1042
+ *
1043
+ * @param {{transient?:boolean, orientation?:boolean, pulse?:boolean, motion?:boolean}} [sources] - Source enables.
1044
+ * @returns {Promise<void>}
1045
+ */
1046
+ async setFifoTrigger({ transient = false, orientation = false, pulse = false, motion = false } = {}) {
1047
+ const value = (transient ? 0x20 : 0) | (orientation ? 0x10 : 0) | (pulse ? 0x08 : 0) | (motion ? 0x04 : 0);
1048
+ const was = await this._begin();
1049
+ await this._conn.writeReg(REG_TRIG_CFG, value);
1050
+ await this._end(was);
1051
+ }
1052
+
1053
+ /**
1054
+ * Number of samples in the FIFO (0-32).
1055
+ *
1056
+ * @returns {Promise<number>} Sample count.
1057
+ */
1058
+ async fifoLevel() {
1059
+ await this._ready;
1060
+ return (await this._conn.readReg(REG_STATUS, 1))[0] & 0x3F;
1061
+ }
1062
+
1063
+ /**
1064
+ * Decode `F_STATUS` (clears `SOURCE_FIFO`).
1065
+ *
1066
+ * @returns {Promise<{overflow:boolean, watermark:boolean, count:number}>} Decoded status.
1067
+ */
1068
+ async readFifoStatus() {
1069
+ await this._ready;
1070
+ const v = (await this._conn.readReg(REG_STATUS, 1))[0];
1071
+ return { overflow: (v & 0x80) !== 0, watermark: (v & 0x40) !== 0, count: v & 0x3F };
1072
+ }
1073
+
1074
+ /**
1075
+ * Drain accelerometer samples from the FIFO. Each sample is read with its
1076
+ * own 6-byte (3 in 8-bit mode) transaction from 0x01, so the hybrid
1077
+ * auto-increment jump to the magnetometer never matters.
1078
+ *
1079
+ * @param {?number} [count=null] - Maximum number of samples; default all.
1080
+ * @returns {Promise<Array<{x:number, y:number, z:number}>>} Samples in g.
1081
+ */
1082
+ async readFifo(count = null) {
1083
+ let n = await this.fifoLevel();
1084
+ if (count !== null && count < n) {
1085
+ n = count;
1086
+ }
1087
+ const scale = this._accelScale();
1088
+ const out = [];
1089
+ for (let i = 0; i < n; i++) {
1090
+ const c = await this._readAccelCounts();
1091
+ out.push({ x: c.x / scale, y: c.y / scale, z: c.z / scale });
1092
+ }
1093
+ return out;
1094
+ }
1095
+
1096
+ /**
1097
+ * Enable or disable the FIFO gate (`fifo_gate`).
1098
+ *
1099
+ * @param {boolean} enabled - True to block FIFO input around WAKE/SLEEP transitions.
1100
+ * @returns {Promise<void>}
1101
+ */
1102
+ async setFifoGate(enabled) {
1103
+ const was = await this._begin();
1104
+ await this._modify(REG_CTRL3, 0x80, enabled ? 0x80 : 0);
1105
+ await this._end(was);
1106
+ }
1107
+
1108
+ // --- Detectors -----------------------------------------------------------
1109
+
1110
+ /**
1111
+ * Debounce time step in ms at the effective ODR and oversampling.
1112
+ *
1113
+ * @returns {number} Step in ms.
1114
+ */
1115
+ _stepMs() {
1116
+ const row = Math.min(this._dr + (this._mode === 2 ? 1 : 0), 7);
1117
+ return STEP_MS[this._mods][row];
1118
+ }
1119
+
1120
+ /**
1121
+ * PULSE_TMLT time step in ms.
1122
+ *
1123
+ * @param {boolean} lpf - Pulse low-pass filter enabled.
1124
+ * @returns {number} Step in ms.
1125
+ */
1126
+ _pulseStepMs(lpf) {
1127
+ const row = Math.min(this._dr + (this._mode === 2 ? 1 : 0), 7);
1128
+ return lpf ? STEP_MS[this._mods][row] : PULSE_STEP_NO_LPF_MS[this._mods][row];
1129
+ }
1130
+
1131
+ /**
1132
+ * Encode a 7-bit threshold (0.063 g/LSB).
1133
+ *
1134
+ * @param {number} thresholdG - Threshold in g.
1135
+ * @returns {number} Register value.
1136
+ */
1137
+ _threshold(thresholdG) {
1138
+ return _clamp(Math.round(thresholdG / 0.063), 0, 127);
1139
+ }
1140
+
1141
+ /**
1142
+ * Configure the freefall / motion detector (`A_FFMT_*`).
1143
+ *
1144
+ * @param {boolean} motion - True = motion (any enabled axis above), false = freefall (all below).
1145
+ * @param {{axes?:number, thresholdG?:number, debounceMs?:number, latch?:boolean, debounceClear?:boolean}} [opts]
1146
+ * axes: mask X=1, Y=2, Z=4 (default 7); thresholdG: 0.063 g/LSB (default 0.3);
1147
+ * debounceMs; latch until `A_FFMT_SRC` is read; debounceClear clears the counter when the condition is lost.
1148
+ * @returns {Promise<void>}
1149
+ */
1150
+ async setFreefallMotion(motion, { axes = 7, thresholdG = 0.3, debounceMs = 0, latch = false, debounceClear = false } = {}) {
1151
+ const cfg = (latch ? 0x80 : 0) | (motion ? 0x40 : 0) | ((axes & 7) << 3);
1152
+ const ths = (debounceClear ? 0x80 : 0) | this._threshold(thresholdG);
1153
+ const count = _clamp(Math.round(debounceMs / this._stepMs()), 0, 255);
1154
+ const was = await this._begin();
1155
+ await this._conn.writeReg(REG_A_FFMT_CFG, cfg);
1156
+ await this._conn.writeReg(REG_A_FFMT_THS, ths);
1157
+ await this._conn.writeReg(REG_A_FFMT_COUNT, count);
1158
+ await this._end(was);
1159
+ }
1160
+
1161
+ /**
1162
+ * Read `A_FFMT_SRC` (clears the flags when latched).
1163
+ *
1164
+ * @returns {Promise<number>} Source byte.
1165
+ */
1166
+ async readMotionSource() {
1167
+ await this._ready;
1168
+ return (await this._conn.readReg(REG_A_FFMT_SRC, 1))[0];
1169
+ }
1170
+
1171
+ /**
1172
+ * Configure the transient detector (`TRANSIENT_*`).
1173
+ *
1174
+ * @param {{axes?:number, thresholdG?:number, debounceMs?:number, bypassHpf?:boolean, latch?:boolean}} [opts]
1175
+ * axes: mask X=1, Y=2, Z=4 (default 7); thresholdG (default 0.3); debounceMs;
1176
+ * bypassHpf: motion-like behaviour; latch until `TRANSIENT_SRC` is read.
1177
+ * @returns {Promise<void>}
1178
+ */
1179
+ async setTransient({ axes = 7, thresholdG = 0.3, debounceMs = 0, bypassHpf = false, latch = false } = {}) {
1180
+ const cfg = (latch ? 0x10 : 0) | ((axes & 7) << 1) | (bypassHpf ? 1 : 0);
1181
+ const count = _clamp(Math.round(debounceMs / this._stepMs()), 0, 255);
1182
+ const was = await this._begin();
1183
+ await this._conn.writeReg(REG_TRANSIENT_CFG, cfg);
1184
+ await this._conn.writeReg(REG_TRANSIENT_THS, this._threshold(thresholdG));
1185
+ await this._conn.writeReg(REG_TRANSIENT_COUNT, count);
1186
+ await this._end(was);
1187
+ }
1188
+
1189
+ /**
1190
+ * Read `TRANSIENT_SRC` — **clears** the interrupt.
1191
+ *
1192
+ * @returns {Promise<number>} Source byte.
1193
+ */
1194
+ async readTransientSource() {
1195
+ await this._ready;
1196
+ return (await this._conn.readReg(REG_TRANSIENT_SRC, 1))[0];
1197
+ }
1198
+
1199
+ /**
1200
+ * Configure tap (pulse) detection (`PULSE_*`).
1201
+ *
1202
+ * @param {{single?:number, double?:number, thresholdG?:(number|number[]), timeLimitMs?:number,
1203
+ * latencyMs?:number, windowMs?:number, latch?:boolean, doubleAbort?:boolean, lpf?:boolean,
1204
+ * hpf?:boolean}} [opts] single/double: axis masks (X=1, Y=2, Z=4); thresholdG: [x, y, z]
1205
+ * or one number (default 0.5); timeLimitMs 30; latencyMs 100; windowMs 300; latch until
1206
+ * `PULSE_SRC` is read; doubleAbort; lpf / hpf: pulse filters (default on).
1207
+ * @returns {Promise<void>}
1208
+ */
1209
+ async setPulse({ single = 0, double = 0, thresholdG = [0.5, 0.5, 0.5], timeLimitMs = 30, latencyMs = 100,
1210
+ windowMs = 300, latch = false, doubleAbort = false, lpf = true, hpf = true } = {}) {
1211
+ const ths = typeof thresholdG === 'number' ? [thresholdG, thresholdG, thresholdG] : thresholdG;
1212
+ let cfg = (doubleAbort ? 0x80 : 0) | (latch ? 0x40 : 0);
1213
+ for (let i = 0; i < 3; i++) {
1214
+ if ((single >> i) & 1) {
1215
+ cfg |= 1 << (2 * i);
1216
+ }
1217
+ if ((double >> i) & 1) {
1218
+ cfg |= 2 << (2 * i);
1219
+ }
1220
+ }
1221
+ const step = this._pulseStepMs(lpf);
1222
+ const tmlt = _clamp(Math.round(timeLimitMs / step), 0, 255);
1223
+ const ltcy = _clamp(Math.round(latencyMs / (2 * step)), 0, 255);
1224
+ const wind = _clamp(Math.round(windowMs / (2 * step)), 0, 255);
1225
+ const was = await this._begin();
1226
+ await this._conn.writeReg(REG_PULSE_CFG, cfg);
1227
+ await this._conn.writeReg(REG_PULSE_THSX, Buffer.from(ths.map((t) => this._threshold(t))));
1228
+ await this._conn.writeReg(REG_PULSE_TMLT, tmlt);
1229
+ await this._conn.writeReg(REG_PULSE_LTCY, ltcy);
1230
+ await this._conn.writeReg(REG_PULSE_WIND, wind);
1231
+ await this._modify(REG_HP_FILTER_CUTOFF, 0x30, (hpf ? 0 : 0x20) | (lpf ? 0x10 : 0));
1232
+ await this._end(was);
1233
+ }
1234
+
1235
+ /**
1236
+ * Read `PULSE_SRC` — **clears** the interrupt.
1237
+ *
1238
+ * @returns {Promise<number>} Source byte.
1239
+ */
1240
+ async readPulseSource() {
1241
+ await this._ready;
1242
+ return (await this._conn.readReg(REG_PULSE_SRC, 1))[0];
1243
+ }
1244
+
1245
+ /**
1246
+ * Configure orientation (portrait / landscape) detection.
1247
+ *
1248
+ * @param {{enabled?:boolean, debounceMs?:number, thresholdDeg?:number, hysteresis?:number,
1249
+ * zLock?:number, backFront?:number}} [opts] thresholdDeg: 15, 20, 30, 35, 40, 45 (default),
1250
+ * 55, 60, 70 or 75; hysteresis `hys` code 0-7 (default 4); zLock code 0-7 (default 4);
1251
+ * backFront code 0-3 (default 2).
1252
+ * @returns {Promise<void>}
1253
+ * @throws {Error} For an invalid argument, or if `pl_ths + hys` is outside 1-31.
1254
+ */
1255
+ async setOrientation({ enabled = true, debounceMs = 0, thresholdDeg = 45, hysteresis = 4, zLock = 4,
1256
+ backFront = 2 } = {}) {
1257
+ if (!(thresholdDeg in PL_THRESHOLDS)) {
1258
+ throw new Error('unsupported thresholdDeg');
1259
+ }
1260
+ if (!(hysteresis >= 0 && hysteresis <= 7) || !(zLock >= 0 && zLock <= 7)
1261
+ || !(backFront >= 0 && backFront <= 3)) {
1262
+ throw new Error('hysteresis/zLock/backFront out of range');
1263
+ }
1264
+ const ths = PL_THRESHOLDS[thresholdDeg];
1265
+ if (ths + hysteresis < 1 || ths + hysteresis > 31) {
1266
+ throw new Error('pl_ths + hys must be within 1-31');
1267
+ }
1268
+ const count = _clamp(Math.round(debounceMs / this._stepMs()), 0, 255);
1269
+ const was = await this._begin();
1270
+ await this._conn.writeReg(REG_PL_CFG, 0x80 | (enabled ? 0x40 : 0));
1271
+ await this._conn.writeReg(REG_PL_COUNT, count);
1272
+ await this._conn.writeReg(REG_PL_THS, (ths << 3) | hysteresis);
1273
+ await this._conn.writeReg(REG_PL_BF_ZCOMP, (backFront << 6) | zLock);
1274
+ await this._end(was);
1275
+ }
1276
+
1277
+ /**
1278
+ * Decode `PL_STATUS` — **clears** `newlp`.
1279
+ *
1280
+ * @returns {Promise<{changed:boolean, lockout:boolean, portraitLandscape:number, back:boolean}>}
1281
+ * portraitLandscape: 0 portrait up, 1 portrait down, 2 landscape right, 3 landscape left.
1282
+ */
1283
+ async readOrientation() {
1284
+ await this._ready;
1285
+ const v = (await this._conn.readReg(REG_PL_STATUS, 1))[0];
1286
+ return {
1287
+ changed: (v & 0x80) !== 0,
1288
+ lockout: (v & 0x40) !== 0,
1289
+ portraitLandscape: (v >> 1) & 0x03,
1290
+ back: (v & 0x01) !== 0,
1291
+ };
1292
+ }
1293
+
1294
+ /**
1295
+ * Configure Auto-SLEEP / WAKE.
1296
+ *
1297
+ * @param {boolean} enabled - Enable Auto-SLEEP (`slpe`).
1298
+ * @param {{sleepRateHz?:number, timeoutS?:number, wakeSources?:number}} [opts] sleepRateHz: 50
1299
+ * (default), 12.5, 6.25 or 1.56 (halved in hybrid mode); timeoutS: inactivity time (default 10);
1300
+ * wakeSources: mask of `SOURCE_TRANSIENT`, `SOURCE_ORIENTATION`, `SOURCE_PULSE`, `SOURCE_FF_MT`
1301
+ * and `SOURCE_ACCEL_VECM`.
1302
+ * @returns {Promise<void>}
1303
+ * @throws {Error} For an unsupported rate or source.
1304
+ */
1305
+ async setAutoSleep(enabled, { sleepRateHz = 50, timeoutS = 10, wakeSources = 0 } = {}) {
1306
+ let code = -1;
1307
+ for (const [hz, c] of ASLP_RATES) {
1308
+ if (Math.abs(hz - sleepRateHz) <= 0.01 * hz) {
1309
+ code = c;
1310
+ }
1311
+ }
1312
+ if (code < 0) {
1313
+ throw new Error('unsupported sleep rate');
1314
+ }
1315
+ if (wakeSources & ~0x3E) {
1316
+ throw new Error('unsupported wake source');
1317
+ }
1318
+ const step = this._dr === 7 ? 0.64 : 0.32;
1319
+ const count = _clamp(Math.round(timeoutS / step), 0, 255);
1320
+ const was = await this._begin();
1321
+ await this._modify(REG_CTRL1, CTRL1_ASLP_MASK, code << 6);
1322
+ await this._conn.writeReg(REG_ASLP_COUNT, count);
1323
+ await this._modify(REG_CTRL2, CTRL2_SLPE, enabled ? CTRL2_SLPE : 0);
1324
+ await this._modify(REG_CTRL3, 0x7C, (wakeSources & 0x3E) << 1);
1325
+ await this._end(was);
1326
+ }
1327
+
1328
+ // --- Interrupts ----------------------------------------------------------
1329
+
1330
+ /**
1331
+ * Configure INT1 / INT2 polarity and drive (`ipol`, `pp_od`).
1332
+ *
1333
+ * @param {boolean} [activeHigh=false] - True for active-high.
1334
+ * @param {boolean} [openDrain=false] - True for open-drain (needs an external pull-up).
1335
+ * @returns {Promise<void>}
1336
+ */
1337
+ async setInterruptPins(activeHigh = false, openDrain = false) {
1338
+ const was = await this._begin();
1339
+ await this._modify(REG_CTRL3, 0x03, (activeHigh ? 0x02 : 0) | (openDrain ? 0x01 : 0));
1340
+ await this._end(was);
1341
+ }
1342
+
1343
+ /**
1344
+ * Enable an interrupt source and route it to INT1 or INT2. Only routes the
1345
+ * source; the detector behind it is configured with the `set*` methods.
1346
+ *
1347
+ * @param {number} source - A `FXOS8700Source.SOURCE_*` mask.
1348
+ * @param {number} [pin=1] - 1 for INT1, 2 for INT2.
1349
+ * @returns {Promise<void>}
1350
+ * @throws {Error} If `pin` is not 1 or 2.
1351
+ */
1352
+ async enableInterrupt(source, pin = 1) {
1353
+ if (pin !== 1 && pin !== 2) {
1354
+ throw new Error('pin must be 1 or 2');
1355
+ }
1356
+ const was = await this._begin();
1357
+ await this._modify(REG_CTRL4, source, source);
1358
+ await this._modify(REG_CTRL5, source, pin === 1 ? source : 0);
1359
+ await this._end(was);
1360
+ }
1361
+
1362
+ /**
1363
+ * Disable an interrupt source (clears its `int_en_*` bit).
1364
+ *
1365
+ * @param {number} source - A `FXOS8700Source.SOURCE_*` mask.
1366
+ * @returns {Promise<void>}
1367
+ */
1368
+ async disableInterrupt(source) {
1369
+ const was = await this._begin();
1370
+ await this._modify(REG_CTRL4, source, 0);
1371
+ await this._end(was);
1372
+ }
1373
+
1374
+ /**
1375
+ * Read `INT_SOURCE` and clear the pending sources. For every set bit
1376
+ * except `SOURCE_DATA_READY` and `SOURCE_ACCEL_VECM` the matching source
1377
+ * register is read so the flag (and the pin) clears.
1378
+ *
1379
+ * @returns {Promise<number>} A mask of `FXOS8700Source.SOURCE_*` constants.
1380
+ */
1381
+ async pollInterrupt() {
1382
+ await this._ready;
1383
+ const status = (await this._conn.readReg(REG_INT_SOURCE, 1))[0];
1384
+ const clear = [
1385
+ [FXOS8700Source.SOURCE_AUTO_SLEEP, REG_SYSMOD],
1386
+ [FXOS8700Source.SOURCE_FIFO, REG_STATUS],
1387
+ [FXOS8700Source.SOURCE_TRANSIENT, REG_TRANSIENT_SRC],
1388
+ [FXOS8700Source.SOURCE_ORIENTATION, REG_PL_STATUS],
1389
+ [FXOS8700Source.SOURCE_PULSE, REG_PULSE_SRC],
1390
+ [FXOS8700Source.SOURCE_FF_MT, REG_A_FFMT_SRC],
1391
+ ];
1392
+ for (const [bit, reg] of clear) {
1393
+ if (status & bit) {
1394
+ await this._conn.readReg(reg, 1);
1395
+ }
1396
+ }
1397
+ return status;
1398
+ }
1399
+
1400
+ /**
1401
+ * Subscribe to the INT1 or INT2 line. The edge follows the configured
1402
+ * polarity. Without an INT pin on the connection a 5 ms polling timer
1403
+ * takes over.
1404
+ *
1405
+ * @param {function(number): void} callback - Receives the `pollInterrupt()` mask.
1406
+ * @param {number} [pin=1] - 1 for INT1, 2 for INT2.
1407
+ * @returns {Promise<void>}
1408
+ * @throws {Error} If the pin is not 1 or 2.
1409
+ */
1410
+ async onInterrupt(callback, pin = 1) {
1411
+ await this._ready;
1412
+ if (pin !== 1 && pin !== 2) {
1413
+ throw new Error('pin must be 1 or 2');
1414
+ }
1415
+ this._callback = callback;
1416
+ const intPin = this._conn.intPin || null;
1417
+ this._intPinUsed = intPin;
1418
+ if (intPin) {
1419
+ const ctrl3 = await this._conn.readReg(REG_CTRL3, 1);
1420
+ const activeHigh = (ctrl3[0] & 0x02) !== 0;
1421
+ this._intHandler = this._intHandler.bind(this);
1422
+ intPin.onEdge(this._intHandler, activeHigh ? 'rising' : 'falling');
1423
+ } else {
1424
+ this._lastStatus = await this.pollInterrupt();
1425
+ this._pollTimer = setInterval(() => {
1426
+ this._pollLoop();
1427
+ }, 5);
1428
+ }
1429
+ }
1430
+
1431
+ /**
1432
+ * Unsubscribe from the INT1 or INT2 line.
1433
+ *
1434
+ * @param {number} [pin=1] - 1 for INT1, 2 for INT2.
1435
+ * @returns {Promise<void>}
1436
+ */
1437
+ async offInterrupt(pin = 1) {
1438
+ if (this._intPinUsed) {
1439
+ this._intPinUsed.offEdge(this._intHandler);
1440
+ this._intPinUsed = null;
1441
+ } else if (this._pollTimer) {
1442
+ clearInterval(this._pollTimer);
1443
+ this._pollTimer = null;
1444
+ }
1445
+ this._callback = null;
1446
+ }
1447
+
1448
+ /**
1449
+ * Handle an INT edge: read the status and dispatch it.
1450
+ *
1451
+ * @returns {Promise<void>}
1452
+ */
1453
+ async _intHandler() {
1454
+ const status = await this.pollInterrupt();
1455
+ if (this._callback) {
1456
+ this._callback(status);
1457
+ }
1458
+ }
1459
+
1460
+ /**
1461
+ * Poll the interrupt status and dispatch on change.
1462
+ *
1463
+ * @returns {Promise<void>}
1464
+ */
1465
+ async _pollLoop() {
1466
+ const status = await this.pollInterrupt();
1467
+ if (status !== this._lastStatus) {
1468
+ this._lastStatus = status;
1469
+ if (this._callback) {
1470
+ this._callback(status);
1471
+ }
1472
+ }
1473
+ }
1474
+
1475
+ // --- Escape hatch / self-test ------------------------------------------
1476
+
1477
+ /**
1478
+ * Read raw register bytes (vector-magnitude, magnetic threshold and
1479
+ * per-axis FFMT registers). No STANDBY handling.
1480
+ *
1481
+ * @param {number} reg - Start register address.
1482
+ * @param {number} [length=1] - Number of bytes.
1483
+ * @returns {Promise<Buffer>} The register contents.
1484
+ */
1485
+ async readRegister(reg, length = 1) {
1486
+ await this._ready;
1487
+ return this._conn.readReg(reg, length);
1488
+ }
1489
+
1490
+ /**
1491
+ * Write raw register bytes. No STANDBY handling.
1492
+ *
1493
+ * @param {number} reg - Start register address.
1494
+ * @param {(Buffer|number[]|number)} data - Bytes to write.
1495
+ * @returns {Promise<void>}
1496
+ */
1497
+ async writeRegister(reg, data) {
1498
+ await this._ready;
1499
+ await this._conn.writeReg(reg, data);
1500
+ }
1501
+
1502
+ /**
1503
+ * Average 8 accelerometer readings (accel-only, 14-bit).
1504
+ *
1505
+ * @returns {Promise<{x:number, y:number, z:number}>} Mean counts.
1506
+ */
1507
+ async _averageCounts() {
1508
+ const samples = 8;
1509
+ let sx = 0;
1510
+ let sy = 0;
1511
+ let sz = 0;
1512
+ for (let i = 0; i < samples; i++) {
1513
+ await _delayMs(12);
1514
+ const c = this._decodeAccel(await this._conn.readReg(REG_OUT_X_MSB, 6));
1515
+ sx += c.x;
1516
+ sy += c.y;
1517
+ sz += c.z;
1518
+ }
1519
+ return { x: Math.floor(sx / samples), y: Math.floor(sy / samples), z: Math.floor(sz / samples) };
1520
+ }
1521
+
1522
+ /**
1523
+ * Run the accelerometer self-test and restore the configuration. STANDBY,
1524
+ * ±2 g, 100 Hz accelerometer-only, normal oversampling; the difference of
1525
+ * two 8-sample averages (before / after `st`) is checked against the
1526
+ * datasheet minimum X >= +192, Y >= +270, Z >= +1275 counts.
1527
+ *
1528
+ * @returns {Promise<{ok:boolean, dx:number, dy:number, dz:number}>} Differences in 14-bit counts.
1529
+ */
1530
+ async selfTest() {
1531
+ await this._ready;
1532
+ const regs = [REG_CTRL1, REG_CTRL2, REG_XYZ_DATA_CFG, REG_M_CTRL1];
1533
+ const saved = {};
1534
+ for (const r of regs) {
1535
+ saved[r] = (await this._conn.readReg(r, 1))[0];
1536
+ }
1537
+ const cache = [this._mode, this._dr, this._fsG, this._mods, this._lnoise, this._fRead];
1538
+ await this.standby();
1539
+ await this._conn.writeReg(REG_XYZ_DATA_CFG, 0x00);
1540
+ await this._conn.writeReg(REG_M_CTRL1, saved[REG_M_CTRL1] & ~M_CTRL1_HMS_MASK & 0xFF);
1541
+ await this._conn.writeReg(REG_CTRL2, 0x00);
1542
+ this._mode = 0;
1543
+ this._dr = 3;
1544
+ this._fsG = 2;
1545
+ this._mods = 0;
1546
+ this._lnoise = false;
1547
+ this._fRead = false;
1548
+ await this._conn.writeReg(REG_CTRL1, (3 << 3) | CTRL1_ACTIVE);
1549
+ await _delayMs(this._turnOnMs());
1550
+ const before = await this._averageCounts();
1551
+ await this._conn.writeReg(REG_CTRL2, CTRL2_ST);
1552
+ await _delayMs(25);
1553
+ const after = await this._averageCounts();
1554
+ await this._conn.writeReg(REG_CTRL2, 0x00);
1555
+ await this.standby();
1556
+ await this._conn.writeReg(REG_XYZ_DATA_CFG, saved[REG_XYZ_DATA_CFG]);
1557
+ await this._conn.writeReg(REG_M_CTRL1, saved[REG_M_CTRL1]);
1558
+ await this._conn.writeReg(REG_CTRL2, saved[REG_CTRL2]);
1559
+ [this._mode, this._dr, this._fsG, this._mods, this._lnoise, this._fRead] = cache;
1560
+ await this._conn.writeReg(REG_CTRL1, saved[REG_CTRL1]);
1561
+ if (saved[REG_CTRL1] & CTRL1_ACTIVE) {
1562
+ await _delayMs(this._turnOnMs());
1563
+ }
1564
+ const dx = after.x - before.x;
1565
+ const dy = after.y - before.y;
1566
+ const dz = after.z - before.z;
1567
+ return { ok: dx >= 192 && dy >= 270 && dz >= 1275, dx, dy, dz };
1568
+ }
1569
+ };
1570
+
1571
+ /**
1572
+ * FXOS8700 full interface — the complete chip functionality.
1573
+ *
1574
+ * Methods that change a STANDBY-only register put the chip into STANDBY,
1575
+ * write, and restore ACTIVE internally, so the caller never manages the mode.
1576
+ * Every such change flushes the FIFO and resets the detectors' debounce
1577
+ * counters.
1578
+ */
1579
+ class FXOS8700Full extends _FXOS8700FullMixin(FXOS8700Minimal) {}
1580
+
1581
+ FXOS8700Full.MODE_ACCEL_ONLY = 0;
1582
+ FXOS8700Full.MODE_MAG_ONLY = 1;
1583
+ FXOS8700Full.MODE_HYBRID = 2;
1584
+ FXOS8700Full.FIFO_DISABLED = 0;
1585
+ FXOS8700Full.FIFO_CIRCULAR = 1;
1586
+ FXOS8700Full.FIFO_FILL = 2;
1587
+ FXOS8700Full.FIFO_TRIGGER = 3;
1588
+ FXOS8700Full.I2C_ADDRESS = I2C_ADDRESS;
1589
+ FXOS8700Minimal.I2C_ADDRESS = I2C_ADDRESS;
1590
+
1591
+ // The interrupt source constants are also exposed directly on the class.
1592
+ Object.assign(FXOS8700Full, FXOS8700Source);
1593
+
1594
+ module.exports = {
1595
+ FXOS8700Minimal,
1596
+ FXOS8700Full,
1597
+ FXOS8700Source,
1598
+ I2C_ADDRESS,
1599
+ I2C_ADDRESSES,
1600
+ };