periph 1.0.1 → 1.2.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 (241) hide show
  1. package/README.md +54 -12
  2. package/examples/accelerometer/adxl345/complete.js +52 -0
  3. package/examples/accelerometer/adxl345/demo.js +34 -0
  4. package/examples/accelerometer/adxl345/minimal.js +18 -0
  5. package/examples/accelerometer/adxl362/complete.js +57 -0
  6. package/examples/accelerometer/adxl362/demo.js +51 -0
  7. package/examples/accelerometer/adxl362/minimal.js +21 -0
  8. package/examples/adc_dac/ad7705/complete.js +32 -0
  9. package/examples/adc_dac/ad7705/demo.js +42 -0
  10. package/examples/adc_dac/ad7705/minimal.js +16 -0
  11. package/examples/adc_dac/ad7706/complete.js +35 -0
  12. package/examples/adc_dac/ad7706/demo.js +44 -0
  13. package/examples/adc_dac/ad7706/minimal.js +16 -0
  14. package/examples/adc_dac/hx710a/complete.js +45 -0
  15. package/examples/adc_dac/hx710a/demo.js +52 -0
  16. package/examples/adc_dac/hx710a/minimal.js +16 -0
  17. package/examples/adc_dac/hx710b/complete.js +45 -0
  18. package/examples/adc_dac/hx710b/demo.js +64 -0
  19. package/examples/adc_dac/hx710b/minimal.js +16 -0
  20. package/examples/adc_dac/hx711/complete.js +42 -0
  21. package/examples/adc_dac/hx711/demo.js +35 -0
  22. package/examples/adc_dac/hx711/minimal.js +16 -0
  23. package/examples/adc_dac/mcp4725/complete.js +19 -17
  24. package/examples/adc_dac/mcp4725/demo.js +5 -5
  25. package/examples/adc_dac/mcp4725/minimal.js +8 -6
  26. package/examples/adc_dac/mcp4728/complete.js +43 -0
  27. package/examples/adc_dac/mcp4728/demo.js +41 -0
  28. package/examples/adc_dac/mcp4728/minimal.js +13 -0
  29. package/examples/adc_dac/pcf8591/complete.js +41 -0
  30. package/examples/adc_dac/pcf8591/demo.js +39 -0
  31. package/examples/adc_dac/pcf8591/minimal.js +19 -0
  32. package/examples/comms/mcp2515/complete.js +75 -0
  33. package/examples/comms/mcp2515/demo.js +66 -0
  34. package/examples/comms/mcp2515/minimal.js +27 -0
  35. package/examples/comms/rda5807m/complete.js +55 -0
  36. package/examples/comms/rda5807m/demo.js +68 -0
  37. package/examples/comms/rda5807m/minimal.js +15 -0
  38. package/examples/comms/rfm9x/complete.js +50 -0
  39. package/examples/comms/rfm9x/demo.js +55 -0
  40. package/examples/comms/rfm9x/minimal.js +20 -0
  41. package/examples/display/pcf8576/complete.js +35 -0
  42. package/examples/display/pcf8576/demo.js +48 -0
  43. package/examples/display/pcf8576/minimal.js +20 -0
  44. package/examples/environmental/aht21/complete.js +32 -0
  45. package/examples/environmental/aht21/demo.js +46 -0
  46. package/examples/environmental/aht21/minimal.js +12 -0
  47. package/examples/environmental/bme280/complete.js +37 -0
  48. package/examples/environmental/bme280/demo.js +67 -0
  49. package/examples/environmental/bme280/minimal.js +20 -0
  50. package/examples/environmental/bme680/complete.js +40 -0
  51. package/examples/environmental/bme680/demo.js +54 -0
  52. package/examples/environmental/bme680/minimal.js +21 -0
  53. package/examples/gas/ens160/complete.js +54 -0
  54. package/examples/gas/ens160/demo.js +54 -0
  55. package/examples/gas/ens160/minimal.js +29 -0
  56. package/examples/gnss/neo6/complete.js +49 -0
  57. package/examples/gnss/neo6/demo.js +54 -0
  58. package/examples/gnss/neo6/minimal.js +30 -0
  59. package/examples/gyroscope/l3g4200d/complete.js +56 -0
  60. package/examples/gyroscope/l3g4200d/demo.js +49 -0
  61. package/examples/gyroscope/l3g4200d/minimal.js +19 -0
  62. package/examples/gyroscope/l3gd20h/complete.js +42 -0
  63. package/examples/gyroscope/l3gd20h/demo.js +29 -0
  64. package/examples/gyroscope/l3gd20h/minimal.js +13 -0
  65. package/examples/humidity/dht11/complete.js +22 -0
  66. package/examples/humidity/dht11/demo.js +38 -0
  67. package/examples/humidity/dht11/minimal.js +18 -0
  68. package/examples/imu/mpu6050/complete.js +58 -0
  69. package/examples/imu/mpu6050/demo.js +37 -0
  70. package/examples/imu/mpu6050/minimal.js +14 -0
  71. package/examples/imu/mpu9250/complete.js +65 -0
  72. package/examples/imu/mpu9250/demo.js +53 -0
  73. package/examples/imu/mpu9250/minimal.js +21 -0
  74. package/examples/imu/mpu9255/complete.js +73 -0
  75. package/examples/imu/mpu9255/demo.js +73 -0
  76. package/examples/imu/mpu9255/minimal.js +21 -0
  77. package/examples/io_expander/mcp23017/complete.js +70 -77
  78. package/examples/io_expander/mcp23017/demo.js +37 -33
  79. package/examples/io_expander/mcp23017/minimal.js +15 -11
  80. package/examples/io_expander/pcf8574/complete.js +60 -65
  81. package/examples/io_expander/pcf8574/demo.js +30 -25
  82. package/examples/io_expander/pcf8574/minimal.js +15 -11
  83. package/examples/io_expander/pcf8575/complete.js +24 -20
  84. package/examples/io_expander/pcf8575/demo.js +27 -23
  85. package/examples/io_expander/pcf8575/minimal.js +16 -12
  86. package/examples/io_expander/tpic6b595/complete.js +57 -0
  87. package/examples/io_expander/tpic6b595/demo.js +75 -0
  88. package/examples/io_expander/tpic6b595/minimal.js +26 -0
  89. package/examples/led/apa102/complete.js +72 -0
  90. package/examples/led/apa102/demo.js +92 -0
  91. package/examples/led/apa102/minimal.js +21 -0
  92. package/examples/led/sk6812rgbw/complete.js +42 -40
  93. package/examples/led/sk6812rgbw/demo.js +16 -16
  94. package/examples/led/sk6812rgbw/minimal.js +15 -17
  95. package/examples/led/ws2812b/complete.js +40 -38
  96. package/examples/led/ws2812b/demo.js +16 -16
  97. package/examples/led/ws2812b/minimal.js +13 -14
  98. package/examples/led/ws2814/complete.js +71 -0
  99. package/examples/led/ws2814/demo.js +82 -0
  100. package/examples/led/ws2814/minimal.js +23 -0
  101. package/examples/light/apds-9930/complete.js +46 -0
  102. package/examples/light/apds-9930/demo.js +31 -0
  103. package/examples/light/apds-9930/minimal.js +20 -0
  104. package/examples/light/apds9960/complete.js +64 -0
  105. package/examples/light/apds9960/demo.js +34 -0
  106. package/examples/light/apds9960/minimal.js +12 -0
  107. package/examples/magnetometer/as5600/complete.js +31 -29
  108. package/examples/magnetometer/as5600/demo.js +35 -33
  109. package/examples/magnetometer/as5600/minimal.js +7 -7
  110. package/examples/magnetometer/hmc5883l/complete.js +47 -0
  111. package/examples/magnetometer/hmc5883l/demo.js +50 -0
  112. package/examples/magnetometer/hmc5883l/minimal.js +15 -0
  113. package/examples/memory/24aa02uid/complete.js +42 -0
  114. package/examples/memory/24aa02uid/demo.js +42 -0
  115. package/examples/memory/24aa02uid/minimal.js +12 -0
  116. package/examples/other/mpr121/complete.js +50 -0
  117. package/examples/other/mpr121/demo.js +30 -0
  118. package/examples/other/mpr121/minimal.js +17 -0
  119. package/examples/power/ade7953/complete.js +44 -0
  120. package/examples/power/ade7953/demo.js +28 -0
  121. package/examples/power/ade7953/minimal.js +15 -0
  122. package/examples/power/ina219/complete.js +20 -18
  123. package/examples/power/ina219/demo.js +15 -13
  124. package/examples/power/ina219/minimal.js +8 -8
  125. package/examples/power/ina226/complete.js +24 -22
  126. package/examples/power/ina226/demo.js +22 -20
  127. package/examples/power/ina226/minimal.js +5 -5
  128. package/examples/power/ina3221/complete.js +51 -49
  129. package/examples/power/ina3221/demo.js +13 -13
  130. package/examples/power/ina3221/minimal.js +8 -8
  131. package/examples/pressure/bmp085/complete.js +29 -0
  132. package/examples/pressure/bmp085/demo.js +34 -0
  133. package/examples/pressure/bmp085/minimal.js +19 -0
  134. package/examples/pressure/bmp180/complete.js +20 -17
  135. package/examples/pressure/bmp180/demo.js +24 -22
  136. package/examples/pressure/bmp180/minimal.js +13 -11
  137. package/examples/pressure/bmp280/complete.js +29 -22
  138. package/examples/pressure/bmp280/demo.js +42 -23
  139. package/examples/pressure/bmp280/minimal.js +13 -11
  140. package/examples/pressure/bmp384/complete.js +29 -0
  141. package/examples/pressure/bmp384/demo.js +40 -0
  142. package/examples/pressure/bmp384/minimal.js +18 -0
  143. package/examples/pressure/bmp581/complete.js +34 -0
  144. package/examples/pressure/bmp581/demo.js +56 -0
  145. package/examples/pressure/bmp581/minimal.js +19 -0
  146. package/examples/pressure/lps22df/complete.js +50 -0
  147. package/examples/pressure/lps22df/demo.js +41 -0
  148. package/examples/pressure/lps22df/minimal.js +19 -0
  149. package/examples/pressure/lps28dfw/complete.js +37 -0
  150. package/examples/pressure/lps28dfw/demo.js +33 -0
  151. package/examples/pressure/lps28dfw/minimal.js +19 -0
  152. package/examples/pressure/lps33hw/complete.js +43 -0
  153. package/examples/pressure/lps33hw/demo.js +43 -0
  154. package/examples/pressure/lps33hw/minimal.js +19 -0
  155. package/examples/rfid/mfrc522/complete.js +44 -0
  156. package/examples/rfid/mfrc522/demo.js +70 -0
  157. package/examples/rfid/mfrc522/minimal.js +17 -0
  158. package/package.json +5 -1
  159. package/src/chips/accelerometer/adxl345.js +482 -0
  160. package/src/chips/accelerometer/adxl362.js +594 -0
  161. package/src/chips/adc_dac/ad7705.js +345 -0
  162. package/src/chips/adc_dac/ad7706.js +331 -0
  163. package/src/chips/adc_dac/hx710a.js +184 -0
  164. package/src/chips/adc_dac/hx710b.js +186 -0
  165. package/src/chips/adc_dac/hx711.js +165 -0
  166. package/src/chips/adc_dac/mcp4725.js +48 -40
  167. package/src/chips/adc_dac/mcp4728.js +297 -0
  168. package/src/chips/adc_dac/pcf8591.js +196 -0
  169. package/src/chips/comms/mcp2515.js +659 -0
  170. package/src/chips/comms/rda5807m.js +393 -0
  171. package/src/chips/comms/rfm9x.js +590 -0
  172. package/src/chips/display/pcf8576.js +232 -0
  173. package/src/chips/environmental/aht21.js +185 -0
  174. package/src/chips/environmental/bme280.js +385 -0
  175. package/src/chips/environmental/bme680.js +512 -0
  176. package/src/chips/gas/ens160.js +298 -0
  177. package/src/chips/gnss/neo6.js +438 -0
  178. package/src/chips/gyroscope/l3g4200d.js +366 -0
  179. package/src/chips/gyroscope/l3gd20h.js +314 -0
  180. package/src/chips/humidity/dht11.js +135 -0
  181. package/src/chips/imu/mpu6050.js +289 -0
  182. package/src/chips/imu/mpu9250.js +394 -0
  183. package/src/chips/imu/mpu9255.js +447 -0
  184. package/src/chips/io_expander/mcp23017.js +240 -157
  185. package/src/chips/io_expander/pcf8574.js +149 -124
  186. package/src/chips/io_expander/pcf8575.js +164 -135
  187. package/src/chips/io_expander/tpic6b595.js +242 -0
  188. package/src/chips/led/_NeoPixelRGBBase.js +204 -0
  189. package/src/chips/led/_NeoPixelRGBWBase.js +218 -0
  190. package/src/chips/led/apa102.js +236 -0
  191. package/src/chips/led/sk6812rgbw.js +15 -149
  192. package/src/chips/led/ws2812b.js +14 -139
  193. package/src/chips/led/ws2814.js +49 -0
  194. package/src/chips/light/apds-9930.js +342 -0
  195. package/src/chips/light/apds9960.js +499 -0
  196. package/src/chips/magnetometer/as5600.js +102 -82
  197. package/src/chips/magnetometer/hmc5883l.js +222 -0
  198. package/src/chips/memory/_24aa02uid.js +182 -0
  199. package/src/chips/other/mpr121.js +375 -0
  200. package/src/chips/power/ade7953.js +427 -0
  201. package/src/chips/power/ina219.js +45 -40
  202. package/src/chips/power/ina226.js +50 -45
  203. package/src/chips/power/ina3221.js +95 -76
  204. package/src/chips/pressure/bmp085.js +251 -0
  205. package/src/chips/pressure/bmp180.js +54 -37
  206. package/src/chips/pressure/bmp280.js +188 -206
  207. package/src/chips/pressure/bmp384.js +410 -0
  208. package/src/chips/pressure/bmp581.js +489 -0
  209. package/src/chips/pressure/lps22df.js +341 -0
  210. package/src/chips/pressure/lps28dfw.js +314 -0
  211. package/src/chips/pressure/lps33hw.js +255 -0
  212. package/src/chips/rfid/mfrc522.js +674 -0
  213. package/src/connection/connection.js +111 -0
  214. package/src/connection/dhtxx.js +138 -0
  215. package/src/connection/dhtxx_mock.js +39 -0
  216. package/src/connection/hx711.js +132 -0
  217. package/src/connection/hx711_mock.js +52 -0
  218. package/src/{transport → connection}/i2c.js +13 -9
  219. package/src/connection/i2c_mock.js +91 -0
  220. package/src/connection/input_pin.js +156 -0
  221. package/src/connection/neo6_mock.js +45 -0
  222. package/src/{transport → connection}/neopixel.js +23 -4
  223. package/src/connection/output_pin.js +41 -0
  224. package/src/connection/sipo.js +159 -0
  225. package/src/{transport → connection}/smbus.js +14 -10
  226. package/src/{transport → connection}/spi.js +12 -8
  227. package/src/connection/spi_mock.js +151 -0
  228. package/src/{transport → connection}/uart.js +33 -26
  229. package/examples/display/.gitkeep +0 -0
  230. package/examples/environmental/.gitkeep +0 -0
  231. package/examples/gnss/.gitkeep +0 -0
  232. package/examples/humidity/.gitkeep +0 -0
  233. package/examples/imu/.gitkeep +0 -0
  234. package/examples/light/.gitkeep +0 -0
  235. package/examples/pressure/.gitkeep +0 -0
  236. package/src/chips/display/.gitkeep +0 -0
  237. package/src/chips/environmental/.gitkeep +0 -0
  238. package/src/chips/gnss/.gitkeep +0 -0
  239. package/src/chips/imu/.gitkeep +0 -0
  240. package/src/chips/light/.gitkeep +0 -0
  241. package/src/chips/pressure/.gitkeep +0 -0
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ const { SPIConnection } = require('../../../src/connection/spi');
4
+ const { MFRC522Full } = require('../../../src/chips/rfid/mfrc522');
5
+
6
+ const connection = new SPIConnection(0, 0, { maxSpeedHz: 1_000_000, mode: 0 });
7
+ const mfrc = new MFRC522Full(connection);
8
+
9
+ // --- Prepaid-card credit counter ---
10
+ // Simulates a transit-gate / vending-machine credit system using a MIFARE
11
+ // Classic value block. The factory default key A (FF FF FF FF FF FF) is
12
+ // used for the demo only — replace with a per-deployment secret in any
13
+ // real access-control system.
14
+ const CREDITS_BLOCK = 4;
15
+ const INITIAL_CREDITS = 10;
16
+
17
+ (async () => {
18
+ // --- Detect a card and select it for authenticated access ---
19
+ const uid = await mfrc.selectCard(); // Anticollision/Select only, () → Buffer | null
20
+ if (!uid) {
21
+ console.log('no card in field');
22
+ } else {
23
+ // --- Authenticate with the well-known MIFARE factory default key A ---
24
+ // In a real deployment this would be a per-card key stored securely
25
+ // (e.g. diversified per card UID and held in an HSM or secure element).
26
+ const factoryKey = Buffer.from([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
27
+ if (!(await mfrc.authenticate(CREDITS_BLOCK, MFRC522Full.KEY_A, factoryKey, uid.subarray(0, 4)))) { // MFAuthent, (block, key, uid) → bool
28
+ console.log('authentication failed');
29
+ } else {
30
+ // --- Read the current value block; initialise it if unprogrammed ---
31
+ let block = await mfrc.readBlock(CREDITS_BLOCK); // Read 16-byte block, (blockAddress) → Buffer
32
+ const allZero = block && block.every((b) => b === 0);
33
+ if (allZero) {
34
+ const valueBlock = Buffer.alloc(16);
35
+ valueBlock.writeUInt32LE(INITIAL_CREDITS, 0);
36
+ const v = INITIAL_CREDITS;
37
+ valueBlock.writeUInt32LE((~v) >>> 0, 4);
38
+ valueBlock.writeUInt32LE(INITIAL_CREDITS, 8);
39
+ valueBlock[12] = CREDITS_BLOCK;
40
+ valueBlock[13] = (~CREDITS_BLOCK) & 0xFF;
41
+ valueBlock[14] = CREDITS_BLOCK;
42
+ valueBlock[15] = (~CREDITS_BLOCK) & 0xFF;
43
+ await mfrc.writeBlock(CREDITS_BLOCK, valueBlock); // Write 16 bytes, (block, data=16 B) → bool
44
+ await mfrc.restoreValue(CREDITS_BLOCK); // Restore + Transfer, (block) → bool
45
+ // normalises the value-block layout
46
+ }
47
+
48
+ // --- "Spend" one credit; refuse if balance is zero ---
49
+ block = await mfrc.readBlock(CREDITS_BLOCK); // Read current value, (block) → Buffer
50
+ if (block) {
51
+ const credits = block.readUInt32LE(0);
52
+ if (credits <= 0) {
53
+ console.log('Access denied — no credits remaining');
54
+ } else {
55
+ await mfrc.decrementValue(CREDITS_BLOCK, 1); // Decrement + Transfer, (block, delta) → bool
56
+ const updated = await mfrc.readBlock(CREDITS_BLOCK); // Read updated value, (block) → Buffer
57
+ if (updated) {
58
+ const newBalance = updated.readUInt32LE(0);
59
+ console.log(`spent 1 credit — remaining: ${newBalance}`);
60
+ }
61
+ }
62
+ }
63
+ await mfrc.stopCrypto(); // Clear MFCrypto1On, () → void
64
+ }
65
+ await mfrc.haltCard(); // Send HLTA, () → void
66
+ }
67
+
68
+ await connection.close();
69
+ console.log('===DONE: 0 passed, 0 failed===');
70
+ })();
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ const { SPIConnection } = require('../../../src/connection/spi');
4
+ const { MFRC522Minimal } = require('../../../src/chips/rfid/mfrc522');
5
+
6
+ const connection = new SPIConnection(0, 0, { maxSpeedHz: 1_000_000, mode: 0 }); // Create SPI connection, (bus, device, options)
7
+ const mfrc = new MFRC522Minimal(connection); // Create MFRC522 driver, (connection, busType='spi')
8
+
9
+ (async () => {
10
+ for (let i = 0; i < 10; i++) {
11
+ const present = await mfrc.isCardPresent(); // Detect card in field, () → bool
12
+ const uid = await mfrc.readUid(); // Read card UID (REQA → anticollision → HLTA), () → Buffer | null
13
+ console.log(`present=${present} uid=${uid ? uid.toString('hex') : 'null'}`);
14
+ }
15
+ await connection.close();
16
+ console.log('===DONE: 0 passed, 0 failed===');
17
+ })();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "periph",
3
- "version": "1.0.1",
3
+ "version": "1.2.0",
4
4
  "description": "JavaScript drivers for peripheral chips (I2C, SPI)",
5
5
  "main": "src/index.js",
6
6
  "keywords": [
@@ -16,5 +16,9 @@
16
16
  "i2c-bus": "^5.2.2",
17
17
  "spi-device": "^3.1.0",
18
18
  "serialport": "^12.0.0"
19
+ },
20
+ "optionalDependencies": {
21
+ "opengpio": "^2.0.2",
22
+ "epoll": "^4.0.1"
19
23
  }
20
24
  }
@@ -0,0 +1,482 @@
1
+ 'use strict';
2
+
3
+ const _REG_DEVID = 0x00;
4
+ const _REG_THRESH_TAP = 0x1D;
5
+ const _REG_OFSX = 0x1E;
6
+ const _REG_OFSY = 0x1F;
7
+ const _REG_OFSZ = 0x20;
8
+ const _REG_DUR = 0x21;
9
+ const _REG_LATENT = 0x22;
10
+ const _REG_WINDOW = 0x23;
11
+ const _REG_THRESH_ACT = 0x24;
12
+ const _REG_THRESH_INACT = 0x25;
13
+ const _REG_TIME_INACT = 0x26;
14
+ const _REG_ACT_INACT_CTL = 0x27;
15
+ const _REG_THRESH_FF = 0x28;
16
+ const _REG_TIME_FF = 0x29;
17
+ const _REG_TAP_AXES = 0x2A;
18
+ const _REG_BW_RATE = 0x2C;
19
+ const _REG_POWER_CTL = 0x2D;
20
+ const _REG_INT_ENABLE = 0x2E;
21
+ const _REG_INT_MAP = 0x2F;
22
+ const _REG_INT_SOURCE = 0x30;
23
+ const _REG_DATA_FORMAT = 0x31;
24
+ const _REG_DATAX0 = 0x32;
25
+ const _REG_FIFO_CTL = 0x38;
26
+ const _REG_FIFO_STATUS = 0x39;
27
+
28
+ const _DEVID_VALUE = 0xE5;
29
+ const _DATA_FORMAT_DEFAULT = 0x08;
30
+ const _BW_RATE_DEFAULT = 0x0A;
31
+ const _POWER_CTL_DEFAULT = 0x08;
32
+ const _FULL_RES_SCALE_G_PER_LSB = 3.9e-3;
33
+
34
+ const _RATE_CODES = [
35
+ [0x0F, 3200.0],
36
+ [0x0E, 1600.0],
37
+ [0x0D, 800.0],
38
+ [0x0C, 400.0],
39
+ [0x0B, 200.0],
40
+ [0x0A, 100.0],
41
+ [0x09, 50.0],
42
+ [0x08, 25.0],
43
+ [0x07, 12.5],
44
+ [0x06, 6.25],
45
+ ];
46
+
47
+ function _delayMs(ms) {
48
+ const end = Date.now() + ms;
49
+ while (Date.now() < end) { /* spin */ }
50
+ }
51
+
52
+ /**
53
+ * ADXL345 3-axis MEMS accelerometer (Analog Devices) — minimal interface.
54
+ *
55
+ * Reads X, Y, Z acceleration in *g* with sensible defaults; no configuration
56
+ * is required beyond the connection. Supports both I²C and SPI.
57
+ *
58
+ * Default configuration (written at construction):
59
+ * - Full-resolution mode (3.9 mg/LSB at any range)
60
+ * - ±2 g measurement range
61
+ * - 100 Hz output data rate, normal power
62
+ * - FIFO bypass, all interrupts disabled, no offsets
63
+ *
64
+ * Constructor caveat: JS constructors cannot be async, but the original
65
+ * synchronous constructor validated DEVID and threw synchronously on
66
+ * mismatch — that guarantee cannot be preserved exactly. The whole init
67
+ * sequence is fired off unawaited; a DEVID mismatch now surfaces as an
68
+ * *unhandled promise rejection* shortly after construction rather than a
69
+ * synchronous throw from `new ADXL345Minimal(...)`. Callers that need to
70
+ * detect "wrong or absent device" deterministically should call an async
71
+ * method (e.g. `await accel.read()`) right after construction and handle
72
+ * its rejection.
73
+ */
74
+ class ADXL345Minimal {
75
+ /**
76
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C or SPI connection.
77
+ * @param {string} [busType='i2c'] - Bus type: 'i2c' or 'spi'.
78
+ */
79
+ constructor(connection, busType = 'i2c') {
80
+ this._conn = connection;
81
+ this._busType = busType;
82
+ this._rangeBits = 0;
83
+ this._fullRes = true;
84
+ this._init();
85
+ }
86
+
87
+ async _init() {
88
+ await this._writeReg(_REG_DATA_FORMAT, _DATA_FORMAT_DEFAULT);
89
+ await this._writeReg(_REG_BW_RATE, _BW_RATE_DEFAULT);
90
+ await this._writeReg(_REG_POWER_CTL, _POWER_CTL_DEFAULT);
91
+ const devid = await this._readReg(_REG_DEVID);
92
+ if (devid !== _DEVID_VALUE) {
93
+ throw new Error('ADXL345 DEVID: expected 0x' + _DEVID_VALUE.toString(16) +
94
+ ', got 0x' + devid.toString(16));
95
+ }
96
+ _delayMs(11);
97
+ }
98
+
99
+ _cmdByte(reg, read, multi) {
100
+ let addr = reg & 0x3F;
101
+ if (multi) addr |= 0x40;
102
+ if (read) addr |= 0x80;
103
+ return addr;
104
+ }
105
+
106
+ async _writeReg(reg, value) {
107
+ if (this._busType === 'spi') {
108
+ const cmd = this._cmdByte(reg, false, false);
109
+ await this._conn.write(Buffer.from([cmd, value & 0xFF]));
110
+ } else {
111
+ await this._conn.write(Buffer.from([reg & 0xFF, value & 0xFF]));
112
+ }
113
+ }
114
+
115
+ async _readReg(reg) {
116
+ if (this._busType === 'spi') {
117
+ const cmd = this._cmdByte(reg, true, false);
118
+ return (await this._conn.writeRead(Buffer.from([cmd]), 1))[0];
119
+ }
120
+ return (await this._conn.writeRead(Buffer.from([reg & 0xFF]), 1))[0];
121
+ }
122
+
123
+ async _readBurst(reg, n) {
124
+ if (this._busType === 'spi') {
125
+ const cmd = this._cmdByte(reg, true, n > 1);
126
+ return this._conn.writeRead(Buffer.from([cmd]), n);
127
+ }
128
+ return this._conn.writeRead(Buffer.from([reg & 0xFF]), n);
129
+ }
130
+
131
+ /**
132
+ * Read 3-axis linear acceleration.
133
+ *
134
+ * Reads all six data bytes (DATAX0..DATAZ1) in one burst so the X, Y,
135
+ * Z samples are guaranteed to come from a single measurement.
136
+ *
137
+ * @returns {Promise<number[]>} [x, y, z] acceleration in *g*.
138
+ */
139
+ async read() {
140
+ const raw = await this._readBurst(_REG_DATAX0, 6);
141
+ const rx = raw.readInt16LE(0);
142
+ const ry = raw.readInt16LE(2);
143
+ const rz = raw.readInt16LE(4);
144
+ const scale = this._fullRes
145
+ ? _FULL_RES_SCALE_G_PER_LSB
146
+ : [3.9e-3, 7.8e-3, 15.6e-3, 31.2e-3][this._rangeBits & 0x03];
147
+ return [rx * scale, ry * scale, rz * scale];
148
+ }
149
+ }
150
+
151
+ /**
152
+ * ADXL345 full interface — extends ADXL345Minimal with configuration, FIFO,
153
+ * tap / activity / inactivity / free-fall detection, and interrupt routing.
154
+ *
155
+ * Adds range and data-rate selection, low-power mode, self-test,
156
+ * per-axis offset calibration (in *g*), single/double-tap detection,
157
+ * activity and inactivity detection, free-fall detection, 32-level FIFO,
158
+ * interrupt routing (INT1 / INT2), and sleep / auto-sleep / link mode.
159
+ */
160
+ class ADXL345Full extends ADXL345Minimal {
161
+ /**
162
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C or SPI connection.
163
+ * @param {string} [busType='i2c'] - Bus type: 'i2c' or 'spi'.
164
+ */
165
+ constructor(connection, busType = 'i2c') {
166
+ super(connection, busType);
167
+ }
168
+
169
+ /**
170
+ * Set the measurement range to ±2/±4/±8/±16 g.
171
+ * @param {number} rangeG - One of 2, 4, 8, 16. FULL_RES is preserved.
172
+ * @returns {Promise<void>}
173
+ */
174
+ async setRange(rangeG) {
175
+ const code = {2: 0, 4: 1, 8: 2, 16: 3}[rangeG];
176
+ if (code === undefined) {
177
+ throw new Error('rangeG must be one of 2, 4, 8, 16');
178
+ }
179
+ this._rangeBits = code;
180
+ let df = await this._readReg(_REG_DATA_FORMAT);
181
+ df = (df & ~0x03) | (code & 0x03);
182
+ if (this._fullRes) df |= 0x08;
183
+ await this._writeReg(_REG_DATA_FORMAT, df);
184
+ }
185
+
186
+ /**
187
+ * Set the output data rate to the nearest supported value.
188
+ * @param {number} rateHz - Requested ODR in Hz.
189
+ * @returns {Promise<void>}
190
+ */
191
+ async setDataRate(rateHz) {
192
+ let bestCode = _RATE_CODES[_RATE_CODES.length - 1][0];
193
+ let bestRate = _RATE_CODES[_RATE_CODES.length - 1][1];
194
+ for (const [code, actual] of _RATE_CODES) {
195
+ if (Math.abs(actual - rateHz) < Math.abs(bestRate - rateHz)) {
196
+ bestCode = code; bestRate = actual;
197
+ }
198
+ }
199
+ let bw = await this._readReg(_REG_BW_RATE);
200
+ bw = (bw & ~0x0F) | (bestCode & 0x0F);
201
+ await this._writeReg(_REG_BW_RATE, bw);
202
+ }
203
+
204
+ /**
205
+ * Enable or disable low-power mode (higher noise).
206
+ * @param {boolean} enabled
207
+ * @returns {Promise<void>}
208
+ */
209
+ async setLowPower(enabled) {
210
+ let bw = await this._readReg(_REG_BW_RATE);
211
+ if (enabled) bw |= 0x10;
212
+ else bw &= ~0x10;
213
+ await this._writeReg(_REG_BW_RATE, bw);
214
+ }
215
+
216
+ /**
217
+ * Set per-axis offset in *g*.
218
+ * @param {number} x - X offset in *g*.
219
+ * @param {number} y - Y offset in *g*.
220
+ * @param {number} z - Z offset in *g*.
221
+ * @returns {Promise<void>}
222
+ */
223
+ async setOffset(x, y, z) {
224
+ await this._writeReg(_REG_OFSX, this._encodeOffset(x));
225
+ await this._writeReg(_REG_OFSY, this._encodeOffset(y));
226
+ await this._writeReg(_REG_OFSZ, this._encodeOffset(z));
227
+ }
228
+
229
+ _encodeOffset(offsetG) {
230
+ let raw = Math.round(offsetG / 15.6e-3);
231
+ if (raw > 127) raw = 127;
232
+ if (raw < -128) raw = -128;
233
+ return raw & 0xFF;
234
+ }
235
+
236
+ /**
237
+ * Measure and write per-axis offsets to null sensor bias.
238
+ *
239
+ * @param {number} [targetX=0] - Expected X reading during calibration (in *g*).
240
+ * @param {number} [targetY=0] - Expected Y reading during calibration (in *g*).
241
+ * @param {number} [targetZ=1] - Expected Z reading during calibration (in *g*).
242
+ * @param {number} [samples=128] - Number of samples to average.
243
+ * @returns {Promise<void>}
244
+ */
245
+ async calibrateOffset(targetX = 0.0, targetY = 0.0, targetZ = 1.0, samples = 128) {
246
+ let sx = 0, sy = 0, sz = 0;
247
+ for (let i = 0; i < samples; i++) {
248
+ const [x, y, z] = await this.read();
249
+ sx += x; sy += y; sz += z;
250
+ _delayMs(11);
251
+ }
252
+ sx /= samples; sy /= samples; sz /= samples;
253
+ await this.setOffset(targetX - sx, targetY - sy, targetZ - sz);
254
+ }
255
+
256
+ /**
257
+ * Configure single-tap detection and enable the SINGLE_TAP interrupt.
258
+ * @param {number} thresholdG - Tap threshold in *g* (62.5 mg/LSB).
259
+ * @param {number} durationMs - Maximum tap duration in ms (625 µs/LSB).
260
+ * @param {number} [axes=0x07] - Bitmask of participating axes.
261
+ * @param {boolean} [suppress=false] - Suppress double-tap if acceleration persists.
262
+ * @returns {Promise<void>}
263
+ */
264
+ async setTapDetection(thresholdG, durationMs, axes = 0x07, suppress = false) {
265
+ await this._writeReg(_REG_THRESH_TAP, Math.round(thresholdG / 62.5e-3) & 0xFF);
266
+ await this._writeReg(_REG_DUR, Math.round(durationMs / 0.625) & 0xFF);
267
+ const tapAxes = (axes & 0x07) | (suppress ? 0x08 : 0x00);
268
+ await this._writeReg(_REG_TAP_AXES, tapAxes);
269
+ await this._enableInterrupt(ADXL345Full.INT_SINGLE_TAP);
270
+ }
271
+
272
+ /**
273
+ * Configure double-tap latency and window; enable DOUBLE_TAP interrupt.
274
+ * @param {number} latencyMs - Time after a tap when a second tap is expected (1.25 ms/LSB).
275
+ * @param {number} windowMs - Time window after latency for the second tap (1.25 ms/LSB).
276
+ * @returns {Promise<void>}
277
+ */
278
+ async setDoubleTap(latencyMs, windowMs) {
279
+ await this._writeReg(_REG_LATENT, Math.round(latencyMs / 1.25) & 0xFF);
280
+ await this._writeReg(_REG_WINDOW, Math.round(windowMs / 1.25) & 0xFF);
281
+ await this._enableInterrupt(ADXL345Full.INT_DOUBLE_TAP);
282
+ }
283
+
284
+ /**
285
+ * Configure activity detection.
286
+ * @param {number} thresholdG - Activity threshold in *g* (62.5 mg/LSB).
287
+ * @param {number} [axes=0x70] - ACT_INACT_CTL activity bits.
288
+ * @param {boolean} [acCoupled=true] - AC-coupled activity detection.
289
+ * @returns {Promise<void>}
290
+ */
291
+ async setActivity(thresholdG, axes = 0x70, acCoupled = true) {
292
+ await this._writeReg(_REG_THRESH_ACT, Math.round(thresholdG / 62.5e-3) & 0xFF);
293
+ let aic = await this._readReg(_REG_ACT_INACT_CTL);
294
+ aic &= ~0xF0;
295
+ if (acCoupled) aic |= 0x80;
296
+ aic |= axes & 0x70;
297
+ await this._writeReg(_REG_ACT_INACT_CTL, aic);
298
+ await this._enableInterrupt(ADXL345Full.INT_ACTIVITY);
299
+ }
300
+
301
+ /**
302
+ * Configure inactivity detection.
303
+ * @param {number} thresholdG - Inactivity threshold in *g* (62.5 mg/LSB).
304
+ * @param {number} timeSec - Inactivity time in seconds.
305
+ * @param {number} [axes=0x07] - ACT_INACT_CTL inactivity bits.
306
+ * @param {boolean} [acCoupled=false]
307
+ * @returns {Promise<void>}
308
+ */
309
+ async setInactivity(thresholdG, timeSec, axes = 0x07, acCoupled = false) {
310
+ await this._writeReg(_REG_THRESH_INACT, Math.round(thresholdG / 62.5e-3) & 0xFF);
311
+ await this._writeReg(_REG_TIME_INACT, Math.round(timeSec) & 0xFF);
312
+ let aic = await this._readReg(_REG_ACT_INACT_CTL);
313
+ aic &= ~0x0F;
314
+ if (acCoupled) aic |= 0x08;
315
+ aic |= axes & 0x07;
316
+ await this._writeReg(_REG_ACT_INACT_CTL, aic);
317
+ await this._enableInterrupt(ADXL345Full.INT_INACTIVITY);
318
+ }
319
+
320
+ /**
321
+ * Configure free-fall detection and enable the FREE_FALL interrupt.
322
+ * @param {number} thresholdG - Free-fall threshold in *g* (62.5 mg/LSB).
323
+ * @param {number} timeMs - Free-fall time in ms (5 ms/LSB).
324
+ * @returns {Promise<void>}
325
+ */
326
+ async setFreeFall(thresholdG, timeMs) {
327
+ await this._writeReg(_REG_THRESH_FF, Math.round(thresholdG / 62.5e-3) & 0xFF);
328
+ await this._writeReg(_REG_TIME_FF, Math.round(timeMs / 5.0) & 0xFF);
329
+ await this._enableInterrupt(ADXL345Full.INT_FREE_FALL);
330
+ }
331
+
332
+ /**
333
+ * Enable or disable an interrupt source and route it to INT1 or INT2.
334
+ * @param {number} source - One of the ``INT_*`` constants.
335
+ * @param {boolean} enabled
336
+ * @param {number} [pin=1] - 1 for INT1, 2 for INT2.
337
+ * @returns {Promise<void>}
338
+ */
339
+ async setInterrupt(source, enabled, pin = 1) {
340
+ let ie = await this._readReg(_REG_INT_ENABLE);
341
+ let im = await this._readReg(_REG_INT_MAP);
342
+ if (enabled) {
343
+ ie |= source;
344
+ if (pin === 2) im |= source;
345
+ else im &= ~source;
346
+ } else {
347
+ ie &= ~source;
348
+ }
349
+ await this._writeReg(_REG_INT_ENABLE, ie);
350
+ await this._writeReg(_REG_INT_MAP, im);
351
+ }
352
+
353
+ async _enableInterrupt(source) {
354
+ await this.setInterrupt(source, true, 1);
355
+ }
356
+
357
+ /**
358
+ * Read the INT_SOURCE register; clears latched interrupts.
359
+ * @returns {Promise<number>} Bitmask of active interrupt sources.
360
+ */
361
+ async readInterruptSource() {
362
+ return this._readReg(_REG_INT_SOURCE);
363
+ }
364
+
365
+ /**
366
+ * Configure the FIFO.
367
+ * @param {number} mode - One of FIFO_BYPASS, FIFO_FIFO, FIFO_STREAM, FIFO_TRIGGER.
368
+ * @param {number} [samples=16] - Watermark / retained-samples count.
369
+ * @returns {Promise<void>}
370
+ */
371
+ async setFifoMode(mode, samples = 16) {
372
+ const fifoCtl = (mode & 0xC0) | (samples & 0x1F);
373
+ await this._writeReg(_REG_FIFO_CTL, fifoCtl);
374
+ }
375
+
376
+ /**
377
+ * @returns {Promise<number>} Number of FIFO entries currently available (0–32).
378
+ */
379
+ async fifoCount() {
380
+ const status = await this._readReg(_REG_FIFO_STATUS);
381
+ return status & 0x3F;
382
+ }
383
+
384
+ /**
385
+ * Drain the FIFO, returning all available (x, y, z) samples in *g*.
386
+ * @returns {Promise<Array<[number, number, number]>>} Up to 32 samples.
387
+ */
388
+ async readFifo() {
389
+ const n = await this.fifoCount();
390
+ const out = [];
391
+ for (let i = 0; i < n; i++) {
392
+ const raw = await this._readBurst(_REG_DATAX0, 6);
393
+ const rx = raw.readInt16LE(0);
394
+ const ry = raw.readInt16LE(2);
395
+ const rz = raw.readInt16LE(4);
396
+ const scale = this._fullRes
397
+ ? _FULL_RES_SCALE_G_PER_LSB
398
+ : [3.9e-3, 7.8e-3, 15.6e-3, 31.2e-3][this._rangeBits & 0x03];
399
+ out.push([rx * scale, ry * scale, rz * scale]);
400
+ }
401
+ return out;
402
+ }
403
+
404
+ /**
405
+ * Enter or leave sleep mode.
406
+ * @param {boolean} enabled
407
+ * @param {number} [wakeupHz=8] - Sample rate during sleep (8 / 4 / 2 / 1).
408
+ * @returns {Promise<void>}
409
+ */
410
+ async setSleep(enabled, wakeupHz = 8) {
411
+ let pwr = await this._readReg(_REG_POWER_CTL);
412
+ if (enabled) {
413
+ const wakeupCode = {8: ADXL345Full.WAKEUP_8_HZ, 4: ADXL345Full.WAKEUP_4_HZ,
414
+ 2: ADXL345Full.WAKEUP_2_HZ, 1: ADXL345Full.WAKEUP_1_HZ}[wakeupHz];
415
+ if (wakeupCode === undefined) {
416
+ throw new Error('wakeupHz must be 8, 4, 2, or 1');
417
+ }
418
+ pwr = (pwr & ~0x06) | wakeupCode | 0x08;
419
+ pwr |= 0x04;
420
+ } else {
421
+ pwr &= ~0x04;
422
+ }
423
+ await this._writeReg(_REG_POWER_CTL, pwr);
424
+ }
425
+
426
+ /**
427
+ * Enable or disable the activity/inactivity serial-link mode.
428
+ * @param {boolean} enabled
429
+ * @returns {Promise<void>}
430
+ */
431
+ async setLinkMode(enabled) {
432
+ let pwr = await this._readReg(_REG_POWER_CTL);
433
+ if (enabled) pwr |= 0x40;
434
+ else pwr &= ~0x40;
435
+ await this._writeReg(_REG_POWER_CTL, pwr);
436
+ }
437
+
438
+ /**
439
+ * Enable or disable auto-sleep on inactivity (requires Link=1).
440
+ * @param {boolean} enabled
441
+ * @returns {Promise<void>}
442
+ */
443
+ async setAutoSleep(enabled) {
444
+ let pwr = await this._readReg(_REG_POWER_CTL);
445
+ if (enabled) pwr |= 0x20;
446
+ else pwr &= ~0x20;
447
+ await this._writeReg(_REG_POWER_CTL, pwr);
448
+ }
449
+
450
+ /**
451
+ * Enable or disable the electrostatic self-test force on all axes.
452
+ * @param {boolean} enabled
453
+ * @returns {Promise<void>}
454
+ */
455
+ async selfTest(enabled) {
456
+ let df = await this._readReg(_REG_DATA_FORMAT);
457
+ if (enabled) df |= 0x80;
458
+ else df &= ~0x80;
459
+ await this._writeReg(_REG_DATA_FORMAT, df);
460
+ }
461
+ }
462
+
463
+ ADXL345Full.INT_DATA_READY = 0x80;
464
+ ADXL345Full.INT_SINGLE_TAP = 0x40;
465
+ ADXL345Full.INT_DOUBLE_TAP = 0x20;
466
+ ADXL345Full.INT_ACTIVITY = 0x10;
467
+ ADXL345Full.INT_INACTIVITY = 0x08;
468
+ ADXL345Full.INT_FREE_FALL = 0x04;
469
+ ADXL345Full.INT_WATERMARK = 0x02;
470
+ ADXL345Full.INT_OVERRUN = 0x01;
471
+
472
+ ADXL345Full.FIFO_BYPASS = 0x00;
473
+ ADXL345Full.FIFO_FIFO = 0x40;
474
+ ADXL345Full.FIFO_STREAM = 0x80;
475
+ ADXL345Full.FIFO_TRIGGER = 0xC0;
476
+
477
+ ADXL345Full.WAKEUP_8_HZ = 0x00;
478
+ ADXL345Full.WAKEUP_4_HZ = 0x02;
479
+ ADXL345Full.WAKEUP_2_HZ = 0x04;
480
+ ADXL345Full.WAKEUP_1_HZ = 0x06;
481
+
482
+ module.exports = { ADXL345Minimal, ADXL345Full };