periph 1.2.1 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +11 -0
  2. package/examples/accelerometer/bma150/complete.js +62 -0
  3. package/examples/accelerometer/bma150/demo.js +65 -0
  4. package/examples/accelerometer/bma150/minimal.js +18 -0
  5. package/examples/adc_dac/hy3131/complete.js +66 -0
  6. package/examples/adc_dac/hy3131/demo.js +37 -0
  7. package/examples/adc_dac/hy3131/minimal.js +18 -0
  8. package/examples/discovery/complete.js +25 -0
  9. package/examples/discovery/demo.js +30 -0
  10. package/examples/discovery/minimal.js +12 -0
  11. package/examples/display/il0373/complete.js +71 -0
  12. package/examples/display/il0373/demo.js +49 -0
  13. package/examples/display/il0373/minimal.js +26 -0
  14. package/examples/display/ssd1331/complete.js +83 -0
  15. package/examples/display/ssd1331/demo.js +49 -0
  16. package/examples/display/ssd1331/minimal.js +27 -0
  17. package/examples/display/st7036/complete.js +71 -0
  18. package/examples/display/st7036/demo.js +56 -0
  19. package/examples/display/st7036/minimal.js +21 -0
  20. package/examples/display/uc1611s/complete.js +135 -0
  21. package/examples/display/uc1611s/complete_spi.js +128 -0
  22. package/examples/display/uc1611s/demo.js +90 -0
  23. package/examples/display/uc1611s/demo_spi.js +91 -0
  24. package/examples/display/uc1611s/minimal.js +28 -0
  25. package/examples/display/uc1611s/minimal_spi.js +30 -0
  26. package/examples/display/uc8159/complete.js +64 -0
  27. package/examples/display/uc8159/demo.js +41 -0
  28. package/examples/display/uc8159/minimal.js +28 -0
  29. package/examples/display/uc8276c/complete.js +73 -0
  30. package/examples/display/uc8276c/demo.js +49 -0
  31. package/examples/display/uc8276c/minimal.js +26 -0
  32. package/examples/environmental/bme280/complete.js +1 -1
  33. package/examples/environmental/bme280/demo.js +1 -1
  34. package/examples/environmental/bme280/minimal.js +1 -1
  35. package/examples/gyroscope/l3g4200d/complete.js +1 -1
  36. package/examples/gyroscope/l3g4200d/demo.js +1 -1
  37. package/examples/gyroscope/l3g4200d/minimal.js +1 -1
  38. package/examples/memory/23x1024/complete.js +54 -0
  39. package/examples/memory/23x1024/demo.js +51 -0
  40. package/examples/memory/23x1024/minimal.js +22 -0
  41. package/examples/memory/mx25l12845e/complete.js +66 -0
  42. package/examples/memory/mx25l12845e/demo.js +66 -0
  43. package/examples/memory/mx25l12845e/minimal.js +27 -0
  44. package/examples/memory/sd_spi/complete.js +55 -0
  45. package/examples/memory/sd_spi/demo.js +67 -0
  46. package/examples/memory/sd_spi/minimal.js +32 -0
  47. package/examples/pressure/bmp280/complete.js +1 -1
  48. package/examples/pressure/bmp280/demo.js +1 -1
  49. package/examples/pressure/bmp280/minimal.js +1 -1
  50. package/examples/pressure/bmp581/complete.js +1 -1
  51. package/examples/pressure/bmp581/demo.js +1 -1
  52. package/examples/pressure/bmp581/minimal.js +1 -1
  53. package/examples/pressure/lps22df/complete.js +1 -1
  54. package/examples/pressure/lps22df/demo.js +1 -1
  55. package/examples/pressure/lps22df/minimal.js +1 -1
  56. package/package.json +1 -1
  57. package/src/chips/accelerometer/adxl345.js +10 -31
  58. package/src/chips/accelerometer/adxl362.js +7 -7
  59. package/src/chips/accelerometer/bma150.js +419 -0
  60. package/src/chips/adc_dac/ad7705.js +36 -9
  61. package/src/chips/adc_dac/ad7706.js +39 -9
  62. package/src/chips/adc_dac/hy3131.js +311 -0
  63. package/src/chips/display/il0373.js +607 -0
  64. package/src/chips/display/ssd1331.js +412 -0
  65. package/src/chips/display/st7036.js +401 -0
  66. package/src/chips/display/uc1611s.js +648 -0
  67. package/src/chips/display/uc8159.js +394 -0
  68. package/src/chips/display/uc8276c.js +658 -0
  69. package/src/chips/environmental/bme280.js +31 -46
  70. package/src/chips/environmental/bme680.js +38 -43
  71. package/src/chips/gas/ens160.js +18 -26
  72. package/src/chips/gyroscope/l3g4200d.js +34 -50
  73. package/src/chips/gyroscope/l3gd20h.js +24 -40
  74. package/src/chips/imu/mpu6050.js +29 -41
  75. package/src/chips/imu/mpu9250.js +42 -66
  76. package/src/chips/imu/mpu9255.js +51 -75
  77. package/src/chips/io_expander/mcp23017.js +24 -33
  78. package/src/chips/light/apds-9930.js +52 -60
  79. package/src/chips/light/apds9960.js +69 -77
  80. package/src/chips/magnetometer/as5600.js +13 -27
  81. package/src/chips/magnetometer/hmc5883l.js +32 -29
  82. package/src/chips/memory/_23x1024.js +228 -0
  83. package/src/chips/memory/_24aa02uid.js +8 -11
  84. package/src/chips/memory/mx25l12845e.js +467 -0
  85. package/src/chips/memory/sd_spi.js +486 -0
  86. package/src/chips/motor/drv8830.js +4 -4
  87. package/src/chips/other/mpr121.js +7 -7
  88. package/src/chips/power/ina219.js +5 -8
  89. package/src/chips/power/ina226.js +5 -8
  90. package/src/chips/power/ina3221.js +5 -8
  91. package/src/chips/pressure/bmp085.js +17 -11
  92. package/src/chips/pressure/bmp180.js +7 -7
  93. package/src/chips/pressure/bmp280.js +21 -33
  94. package/src/chips/pressure/bmp384.js +28 -39
  95. package/src/chips/pressure/bmp581.js +59 -70
  96. package/src/chips/pressure/lps22df.js +50 -52
  97. package/src/chips/pressure/lps28dfw.js +15 -13
  98. package/src/chips/pressure/lps33hw.js +7 -5
  99. package/src/chips/rtc/ds3231.js +8 -8
  100. package/src/chips/rtc/pcf8523.js +8 -14
  101. package/src/chips/temperature/mcp9808.js +9 -7
  102. package/src/chips/temperature/tmp117.js +4 -4
  103. package/src/connection/connection.js +6 -4
  104. package/src/connection/dhtxx.js +5 -3
  105. package/src/connection/display.js +278 -0
  106. package/src/connection/display_mock.js +77 -0
  107. package/src/connection/hx711.js +5 -3
  108. package/src/connection/i2c.js +6 -4
  109. package/src/connection/i2c_mock.js +47 -0
  110. package/src/connection/input_pin.js +36 -5
  111. package/src/connection/register.js +14 -0
  112. package/src/connection/register_connection.js +65 -0
  113. package/src/connection/sipo.js +4 -2
  114. package/src/connection/sipo_mock.js +49 -0
  115. package/src/connection/smbus.js +6 -4
  116. package/src/connection/softspi.js +73 -0
  117. package/src/connection/spi.js +110 -23
  118. package/src/connection/spi_mock.js +50 -0
  119. package/src/connection/uart.js +2 -1
  120. package/src/discovery/discovery.js +218 -0
  121. package/src/discovery/registry.js +85 -0
  122. package/src/storage/block_device.js +95 -0
  123. package/src/storage/ram_block_device.js +72 -0
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * In-memory fake SiPo connection for unit tests — no hardware, no bus.
5
+ *
6
+ * Models the write-only shift-register protocol chip drivers in this repo
7
+ * use (TPIC6B595, SN74HC595, ...): write() shifts + latches, clear() pulses
8
+ * SRCLR, setOutputEnable() drives G. SRCLR/G availability is configurable
9
+ * at construction, matching the real connection's thrown Error when the
10
+ * corresponding GPIO line wasn't wired.
11
+ */
12
+ class SiPoConnectionMock {
13
+ /**
14
+ * @param {object} [options]
15
+ * @param {boolean} [options.hasSrclr=true] - true if SRCLR is "wired".
16
+ * @param {boolean} [options.hasG=true] - true if G is "wired".
17
+ */
18
+ constructor({ hasSrclr = true, hasG = true } = {}) {
19
+ this.writes = [];
20
+ this.clearCount = 0;
21
+ this.outputEnableCalls = [];
22
+ this._hasSrclr = hasSrclr;
23
+ this._hasG = hasG;
24
+ this._enabled = true;
25
+ }
26
+
27
+ enable() { this._enabled = true; }
28
+ disable() { this._enabled = false; }
29
+ isEnabled() { return this._enabled; }
30
+
31
+ write(data) {
32
+ if (!this._enabled) return;
33
+ this.writes.push(Buffer.from(data));
34
+ }
35
+
36
+ clear() {
37
+ if (!this._hasSrclr) throw new Error('SRCLR not configured');
38
+ this.clearCount++;
39
+ }
40
+
41
+ setOutputEnable(enabled) {
42
+ if (!this._hasG) throw new Error('G not configured');
43
+ this.outputEnableCalls.push(enabled);
44
+ }
45
+
46
+ close() {}
47
+ }
48
+
49
+ module.exports = { SiPoConnectionMock };
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const i2c = require('i2c-bus');
4
- const { Connection } = require('./connection');
4
+ const { RegisterConnection } = require('./register_connection');
5
5
 
6
6
  /**
7
7
  * Computes CRC-8 with polynomial 0x07 (x⁸ + x² + x + 1), initial value 0x00.
@@ -26,17 +26,19 @@ function crc8(data) {
26
26
  * appends a CRC-8 byte to writes and verifies it on reads. PEC is computed in
27
27
  * software using raw i2c transfers. Call close() to release the bus when done.
28
28
  */
29
- class SMBusConnection extends Connection {
29
+ class SMBusConnection extends RegisterConnection {
30
30
  /**
31
31
  * @param {number} busNumber - I²C bus number (opens /dev/i2c-{busNumber}).
32
32
  * @param {number} addr - 7-bit device address (0x08–0x77).
33
33
  * @param {boolean} [pec=false] - Enable Packet Error Code (CRC-8) checking.
34
34
  * @param {import('./input_pin').InputPin|null} [intPin=null] - Optional INT-line InputPin.
35
35
  * @param {import('./output_pin').OutputPin|null} [enPin=null] - Optional EN-pin OutputPin.
36
+ * @param {boolean} [enActiveHigh=true] - True if the EN pin is active-high (default); false for active-low.
37
+ * @param {number} [regBytes=1] - Register address width in bytes, big-endian.
36
38
  * @throws {RangeError} If addr is outside the valid SMBus range.
37
39
  */
38
- constructor(busNumber, addr, pec = false, intPin = null, enPin = null) {
39
- super(intPin, enPin);
40
+ constructor(busNumber, addr, pec = false, intPin = null, enPin = null, regBytes = 1, enActiveHigh = true) {
41
+ super(intPin, enPin, regBytes, enActiveHigh);
40
42
  if (addr < 0x08 || addr > 0x77) {
41
43
  throw new RangeError('SMBus address must be in range 0x08-0x77');
42
44
  }
@@ -0,0 +1,73 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Bit-banged SPI master (mode 0, MSB first) over GPIO pins.
5
+ *
6
+ * The software-SPI primitive for the display connection on hosts where
7
+ * spi-device (a hardware controller) is not the right choice. Chip select is
8
+ * not part of the bus object: the connection drives CS itself.
9
+ *
10
+ * Reading needs the MISO input. For a display controller whose DIN and DOUT
11
+ * share one pin, MISO is wired to that pin and MOSI is joined to it through a
12
+ * series resistor, so the host keeps driving MOSI (dummy bytes) while the chip
13
+ * drives the line and wins — no direction switch is needed.
14
+ *
15
+ * sck and mosi are opengpio-style outputs (assign a boolean to `.value`,
16
+ * synchronous); miso is an InputPin read with isHigh().
17
+ */
18
+ class SoftSPI {
19
+ /**
20
+ * @param {object} sck - Output for the clock (idles low).
21
+ * @param {object} mosi - Output for the data line to the device.
22
+ * @param {import('./input_pin').InputPin|null} [miso=null] - Input sampling the
23
+ * data line from the device; null for a write-only bus.
24
+ */
25
+ constructor(sck, mosi, miso = null) {
26
+ this._sck = sck;
27
+ this._mosi = mosi;
28
+ this._miso = miso;
29
+ this._sck.value = false;
30
+ }
31
+
32
+ /** @returns {boolean} true when a MISO pin was given. */
33
+ canRead() { return this._miso !== null; }
34
+
35
+ /**
36
+ * Shift data out MSB-first, SPI mode 0.
37
+ * @param {Buffer|Uint8Array} data - Bytes to send.
38
+ */
39
+ write(data) {
40
+ for (const byte of data) {
41
+ for (let bit = 7; bit >= 0; bit--) {
42
+ this._mosi.value = !!((byte >> bit) & 1);
43
+ this._sck.value = true;
44
+ this._sck.value = false;
45
+ }
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Clock in n bytes from MISO while sending `fill` on MOSI.
51
+ * @param {number} n - Number of bytes to read.
52
+ * @param {number} [fill=0] - Byte driven on MOSI during every clocked byte.
53
+ * @returns {Buffer} The sampled bytes, MSB-first.
54
+ * @throws {Error} If no MISO pin was given.
55
+ */
56
+ read(n, fill = 0x00) {
57
+ if (this._miso === null) throw new Error('SoftSPI has no MISO pin');
58
+ const out = Buffer.alloc(n);
59
+ for (let i = 0; i < n; i++) {
60
+ let value = 0;
61
+ for (let bit = 7; bit >= 0; bit--) {
62
+ this._mosi.value = !!((fill >> bit) & 1);
63
+ this._sck.value = true;
64
+ value = (value << 1) | (this._miso.isHigh() ? 1 : 0);
65
+ this._sck.value = false;
66
+ }
67
+ out[i] = value;
68
+ }
69
+ return out;
70
+ }
71
+ }
72
+
73
+ module.exports = { SoftSPI };
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const spi = require('spi-device');
4
- const { Connection } = require('./connection');
4
+ const { RegisterConnection } = require('./register_connection');
5
5
 
6
6
  /**
7
7
  * SPI connection for Node.js (wraps spi-device).
@@ -9,65 +9,152 @@ const { Connection } = require('./connection');
9
9
  * Opens the spidev device synchronously at construction. CS is managed by
10
10
  * the kernel spidev driver. Call close() when done.
11
11
  */
12
- class SPIConnection extends Connection {
12
+ class SPIConnection extends RegisterConnection {
13
13
  /**
14
14
  * @param {number} busNumber - SPI bus number.
15
15
  * @param {number} deviceNumber - Chip-select line on the bus.
16
16
  * @param {object} [options]
17
17
  * @param {number} [options.mode=spi.MODE0] - SPI mode (0–3).
18
18
  * @param {number} [options.maxSpeedHz=1_000_000] - Clock frequency in Hz.
19
+ * @param {number} [options.readBit=0x80] - Bit ORed into the command byte
20
+ * for a read; 0 if the chip has no such bit.
21
+ * @param {number|null} [options.multiByteBit=null] - Bit ORed in for multi-byte
22
+ * (burst) transfers when length > 1; null if the chip has no such bit and
23
+ * always auto-increments.
19
24
  * @param {import('./input_pin').InputPin|null} [options.intPin=null] - Optional INT-line InputPin.
20
25
  * @param {import('./output_pin').OutputPin|null} [options.enPin=null] - Optional EN-pin OutputPin.
26
+ * @param {boolean} [options.enActiveHigh=true] - True if the EN pin is active-high (default); false for active-low.
27
+ * @param {import('./output_pin').OutputPin|null} [options.csPin=null] - OutputPin that drives chip select
28
+ * itself. When given, the kernel's CS is disabled (`noChipSelect`) and the optional extensions
29
+ * `idleClocks` / `select` / `deselect` work (needed by SD cards); without it they reject.
21
30
  */
22
31
  constructor(busNumber, deviceNumber, options = {}) {
23
- super(options.intPin ?? null, options.enPin ?? null);
32
+ super(options.intPin ?? null, options.enPin ?? null, options.enActiveHigh ?? true);
24
33
  this._device = spi.openSync(busNumber, deviceNumber, {
25
34
  mode: options.mode ?? spi.MODE0,
26
35
  maxSpeedHz: options.maxSpeedHz ?? 1_000_000,
36
+ ...(options.csPin ? { noChipSelect: true } : {}),
27
37
  });
38
+ this._csPin = options.csPin ?? null;
39
+ this._held = false;
40
+ if (this._csPin) this._csPin.set(true);
41
+ this._readBit = options.readBit ?? 0x80;
42
+ this._multiByteBit = options.multiByteBit ?? null;
43
+ }
44
+
45
+ /**
46
+ * Read `length` bytes starting at register `reg`, building the SPI command byte.
47
+ * @param {number} reg - Register address.
48
+ * @param {number} length - Number of bytes to read.
49
+ * @returns {Promise<Buffer>} Data received from the device.
50
+ */
51
+ async readReg(reg, length) {
52
+ let cmd = reg | this._readBit;
53
+ if (length > 1 && this._multiByteBit) cmd |= this._multiByteBit;
54
+ return this.writeRead(Buffer.from([cmd]), length);
55
+ }
56
+
57
+ /**
58
+ * Write `data` to register `reg`, building the SPI command byte.
59
+ * @param {number} reg - Register address.
60
+ * @param {Buffer|Uint8Array|number} data - Bytes to write, or a single int for a 1-byte register.
61
+ * @returns {Promise<void>}
62
+ */
63
+ async writeReg(reg, data) {
64
+ const payload = Buffer.isBuffer(data) ? data : Buffer.from(typeof data === 'number' ? [data] : data);
65
+ const cmd = (reg & ~this._readBit) | ((payload.length > 1 && this._multiByteBit) ? this._multiByteBit : 0);
66
+ return this.write(Buffer.concat([Buffer.from([cmd]), payload]));
28
67
  }
29
68
 
30
69
  /**
31
70
  * Send bytes to the device.
32
71
  * @param {Buffer|Uint8Array} data - Bytes to send.
33
72
  */
34
- async _write(data) {
35
- const sendBuffer = Buffer.isBuffer(data) ? data : Buffer.from(data);
73
+ /**
74
+ * Clock `n` bits of 0xFF with CS deasserted (rounded up to whole bytes).
75
+ * @param {number} n
76
+ * @returns {Promise<void>}
77
+ */
78
+ async idleClocks(n) {
79
+ if (!this._csPin) throw new Error('idleClocks needs options.csPin (noChipSelect + GPIO chip select)');
80
+ await this._csPin.set(true);
81
+ const sendBuffer = Buffer.alloc(Math.ceil(n / 8), 0xFF);
36
82
  this._device.transferSync([{ sendBuffer, byteLength: sendBuffer.length }]);
83
+ if (this._held) await this._csPin.set(false);
84
+ }
85
+
86
+ /**
87
+ * Change the SCK frequency.
88
+ * @param {number} hz
89
+ * @returns {Promise<boolean>} true
90
+ */
91
+ async setSpeed(hz) {
92
+ this._device.setOptionsSync({ maxSpeedHz: hz });
93
+ return true;
94
+ }
95
+
96
+ /**
97
+ * Assert CS and hold it low across following operations until deselect().
98
+ * @returns {Promise<void>}
99
+ */
100
+ async select() {
101
+ if (!this._csPin) throw new Error('select needs options.csPin (noChipSelect + GPIO chip select)');
102
+ await this._csPin.set(false);
103
+ this._held = true;
37
104
  }
38
105
 
39
106
  /**
40
- * Read bytes from the device.
41
- * @param {number} n - Number of bytes to read.
42
- * @returns {Buffer} Data received from the device.
107
+ * Release CS asserted by select().
108
+ * @returns {Promise<void>}
43
109
  */
110
+ async deselect() {
111
+ this._held = false;
112
+ if (this._csPin) await this._csPin.set(true);
113
+ }
114
+
115
+ /**
116
+ * Fill `buf` with `buf.length` bytes read from the device (MOSI idles high).
117
+ * @param {Buffer} buf
118
+ * @returns {Promise<void>}
119
+ */
120
+ async readInto(buf) {
121
+ await this._csLow();
122
+ const sendBuffer = Buffer.alloc(buf.length, 0xFF);
123
+ this._device.transferSync([{ sendBuffer, receiveBuffer: buf, byteLength: buf.length }]);
124
+ await this._csHigh();
125
+ }
126
+
127
+ async _csLow() {
128
+ if (this._csPin && !this._held) await this._csPin.set(false);
129
+ }
130
+
131
+ async _csHigh() {
132
+ if (this._csPin && !this._held) await this._csPin.set(true);
133
+ }
134
+
135
+ async _write(data) {
136
+ const sendBuffer = Buffer.isBuffer(data) ? data : Buffer.from(data);
137
+ await this._csLow();
138
+ this._device.transferSync([{ sendBuffer, byteLength: sendBuffer.length }]);
139
+ await this._csHigh();
140
+ }
141
+
44
142
  async _read(n) {
45
143
  const receiveBuffer = Buffer.alloc(n);
46
- this._device.transferSync([{ receiveBuffer, byteLength: n }]);
144
+ await this.readInto(receiveBuffer);
47
145
  return receiveBuffer;
48
146
  }
49
147
 
50
- /**
51
- * Full-duplex write+read in a single SPI transfer (CS held for the entire transfer).
52
- *
53
- * Sends len(data)+n bytes total and discards the first len(data) received
54
- * bytes (chip response during the command phase).
55
- *
56
- * @param {Buffer|Uint8Array} data - Command bytes to send.
57
- * @param {number} n - Number of response bytes expected.
58
- * @returns {Buffer} The n response bytes.
59
- */
60
148
  async _writeRead(data, n) {
61
149
  const prefix = Buffer.isBuffer(data) ? data : Buffer.from(data);
62
- const sendBuffer = Buffer.concat([prefix, Buffer.alloc(n)]);
150
+ const sendBuffer = Buffer.concat([prefix, Buffer.alloc(n, 0xFF)]);
63
151
  const receiveBuffer = Buffer.alloc(sendBuffer.length);
152
+ await this._csLow();
64
153
  this._device.transferSync([{ sendBuffer, receiveBuffer, byteLength: sendBuffer.length }]);
154
+ await this._csHigh();
65
155
  return receiveBuffer.subarray(prefix.length);
66
156
  }
67
157
 
68
- /**
69
- * Close the SPI device. Must be called when the connection is no longer needed.
70
- */
71
158
  async close() {
72
159
  this._device.closeSync();
73
160
  }
@@ -44,8 +44,20 @@ class SPIConnectionMock {
44
44
  this.registers = new Map();
45
45
  this.writes = [];
46
46
  this._readQueue = [];
47
+ this.events = [];
47
48
  }
48
49
 
50
+ /** Record an `idleClocks` call on `events`. */
51
+ async idleClocks(n) { this.events.push(['idleClocks', n]); }
52
+ /** Record a `setSpeed` call on `events`; resolves true. */
53
+ async setSpeed(hz) { this.events.push(['setSpeed', hz]); return true; }
54
+ /** Record a `select` call on `events`. */
55
+ async select() { this.events.push(['select']); }
56
+ /** Record a `deselect` call on `events`. */
57
+ async deselect() { this.events.push(['deselect']); }
58
+ /** Fill `buf` like `read(buf.length)`. */
59
+ async readInto(buf) { (await this.read(buf.length)).copy(buf); }
60
+
49
61
  /**
50
62
  * Preload consecutive register bytes starting at `reg`.
51
63
  * @param {number} reg - First register address.
@@ -95,6 +107,26 @@ class SPIConnectionMock {
95
107
  if ((cmd & 0xE0) === 0x40) {
96
108
  return false;
97
109
  }
110
+ // ADXL362 WRITE REGISTER: 0x0A opcode + address + data byte(s).
111
+ if (cmd === 0x0A && buf.length >= 3) {
112
+ const reg = buf[1];
113
+ for (let i = 2; i < buf.length; i++) {
114
+ this.registers.set(reg + i - 2, buf[i]);
115
+ }
116
+ return true;
117
+ }
118
+ // Generic fallback for chips (e.g. AD7705) whose single command byte
119
+ // *is* the register address directly, rather than MCP2515's
120
+ // opcode-plus-address framing -- mirrors the Python/C++ SPI mocks'
121
+ // behaviour: any 2+-byte write updates the register map starting at
122
+ // buf[0].
123
+ if (buf.length >= 2) {
124
+ const reg = buf[0];
125
+ for (let i = 1; i < buf.length; i++) {
126
+ this.registers.set(reg + i - 1, buf[i]);
127
+ }
128
+ return true;
129
+ }
98
130
  return false;
99
131
  }
100
132
 
@@ -135,6 +167,13 @@ class SPIConnectionMock {
135
167
  else startReg = 0x71 + (offset & 0x03);
136
168
  } else if (cmd === 0xA0 || cmd === 0xB0) {
137
169
  startReg = 0;
170
+ } else if (cmd === 0x0B && buf.length >= 2) {
171
+ // ADXL362 READ REGISTER: 0x0B opcode + address byte.
172
+ startReg = buf[1];
173
+ } else {
174
+ // Generic fallback (see _applyWrite): the command byte itself
175
+ // is the register address for chips like AD7705.
176
+ startReg = cmd;
138
177
  }
139
178
  if (startReg !== null) {
140
179
  for (let i = 0; i < n; i++) {
@@ -144,6 +183,17 @@ class SPIConnectionMock {
144
183
  return out;
145
184
  }
146
185
 
186
+ /** @param {number} reg @param {number} length */
187
+ async readReg(reg, length) {
188
+ return this.writeRead(Buffer.from([reg]), length);
189
+ }
190
+
191
+ /** @param {number} reg @param {Buffer|Uint8Array|number} data */
192
+ async writeReg(reg, data) {
193
+ const payload = Buffer.isBuffer(data) ? data : Buffer.from(typeof data === 'number' ? [data] : data);
194
+ return this.write(Buffer.concat([Buffer.from([reg]), payload]));
195
+ }
196
+
147
197
  /** No-op. */
148
198
  async close() {}
149
199
  }
@@ -25,9 +25,10 @@ class UARTConnection extends Connection {
25
25
  * @param {{chip: number, line: number}|null} [options.de_gpio=null] - gpiod chip+line for RS-485 DE; null disables.
26
26
  * @param {import('./input_pin').InputPin|null} [options.intPin=null] - Optional INT-line InputPin.
27
27
  * @param {import('./output_pin').OutputPin|null} [options.enPin=null] - Optional EN-pin OutputPin.
28
+ * @param {boolean} [options.enActiveHigh=true] - True if the EN pin is active-high (default); false for active-low.
28
29
  */
29
30
  constructor(path, options = {}) {
30
- super(options.intPin ?? null, options.enPin ?? null);
31
+ super(options.intPin ?? null, options.enPin ?? null, options.enActiveHigh ?? true);
31
32
  this._baudRate = options.baudRate ?? 9600;
32
33
  this._timeoutMs = options.timeoutMs ?? 1000;
33
34
  this._de_gpio = options.de_gpio ?? null;
@@ -0,0 +1,218 @@
1
+ 'use strict';
2
+
3
+ // I²C bus auto-discovery for Node.js on Linux (specs/feature_i2c_discovery.md).
4
+ //
5
+ // scan() enumerates responding addresses; discover() maps them to the chips in
6
+ // the generated registry (registry.js, built from registry/chips.json) and
7
+ // confirms a chip only when an identity-register read matches exactly one
8
+ // candidate. Everything else is reported as candidates.
9
+
10
+ const i2c = require('i2c-bus');
11
+ const { CHIPS } = require('./registry');
12
+
13
+ const FIRST_ADDRESS = 0x08;
14
+ const LAST_ADDRESS = 0x77;
15
+
16
+ // i2cdetect-compatible policy: EEPROM-class ranges are probed with a read byte.
17
+ const READ_BYTE_RANGES = [[0x30, 0x37], [0x50, 0x5f]];
18
+
19
+ const ABSENT = new Set(['ENXIO', 'EREMOTEIO']);
20
+ const UNSUPPORTED = new Set(['EOPNOTSUPP', 'EINVAL', 'ENOTSUP']);
21
+ const NO_BUFFER = Buffer.alloc(0);
22
+
23
+ /**
24
+ * @typedef {Object} DiscoveredDevice
25
+ * @property {number} address - 7-bit address (lowest address of an alias block).
26
+ * @property {string[]} candidates - Registry chip ids that could be here; [] if unknown to the registry.
27
+ * @property {string|null} identified - Chip id confirmed by an identity read, else null.
28
+ * @property {string|null} driver - Driver name of the identified chip, if it has one.
29
+ * @property {boolean} inUseByKernel - True when a kernel driver owns the address (EBUSY).
30
+ * @property {string|null} probeSkippedReason - "kernel_bound", "write_sensitive_candidate" or null.
31
+ * @property {number[]} aliases - Other addresses merged into this device (24AA02UID), else [].
32
+ */
33
+
34
+ function errorCode(e) {
35
+ if (e && typeof e.code === 'string') return e.code;
36
+ const n = e && Math.abs(Number(e.errno));
37
+ return { 6: 'ENXIO', 16: 'EBUSY', 121: 'EREMOTEIO', 95: 'EOPNOTSUPP', 22: 'EINVAL' }[n] || 'EIO';
38
+ }
39
+
40
+ function openBus(bus) {
41
+ if (typeof bus === 'number') return { handle: i2c.openSync(bus), owned: true };
42
+ return { handle: bus, owned: false };
43
+ }
44
+
45
+ function usesReadByte(addr) {
46
+ return READ_BYTE_RANGES.some(([lo, hi]) => addr >= lo && addr <= hi);
47
+ }
48
+
49
+ // A zero-length write is the closest i2c-bus offers to a quick write; adapters
50
+ // that reject it fall back to a read byte (always acceptable, spec section 3.2).
51
+ function probeAddress(handle, addr) {
52
+ if (!usesReadByte(addr)) {
53
+ try {
54
+ handle.i2cWriteSync(addr, 0, NO_BUFFER);
55
+ return;
56
+ } catch (e) {
57
+ if (!UNSUPPORTED.has(errorCode(e))) throw e;
58
+ }
59
+ }
60
+ handle.receiveByteSync(addr);
61
+ }
62
+
63
+ /**
64
+ * Scan a bus and report which responding addresses are kernel-bound.
65
+ * @param {number|object} bus - Bus number (opens /dev/i2c-N) or an open i2c-bus handle.
66
+ * @param {number} [first=0x08]
67
+ * @param {number} [last=0x77]
68
+ * @returns {Promise<Map<number, boolean>>} address -> inUseByKernel for every address that responded.
69
+ * @throws {Error} If every probed address failed with something other than a NACK.
70
+ */
71
+ async function scanDetailed(bus, first = FIRST_ADDRESS, last = LAST_ADDRESS) {
72
+ const { handle, owned } = openBus(bus);
73
+ try {
74
+ const found = new Map();
75
+ let errors = 0;
76
+ let lastError = null;
77
+ for (let addr = first; addr <= last; addr++) {
78
+ try {
79
+ probeAddress(handle, addr);
80
+ found.set(addr, false);
81
+ } catch (e) {
82
+ const code = errorCode(e);
83
+ if (code === 'EBUSY') found.set(addr, true);
84
+ else if (!ABSENT.has(code)) {
85
+ errors++;
86
+ lastError = e;
87
+ }
88
+ }
89
+ }
90
+ if (errors > 0 && errors === last - first + 1) throw lastError;
91
+ return found;
92
+ } finally {
93
+ if (owned) handle.closeSync();
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Return the sorted 7-bit addresses that respond on the bus.
99
+ * @param {number|object} bus - Bus number or an open i2c-bus handle.
100
+ * @param {number} [first=0x08]
101
+ * @param {number} [last=0x77]
102
+ * @returns {Promise<number[]>}
103
+ */
104
+ async function scan(bus, first = FIRST_ADDRESS, last = LAST_ADDRESS) {
105
+ return [...(await scanDetailed(bus, first, last)).keys()].sort((a, b) => a - b);
106
+ }
107
+
108
+ // Writes the register address (big-endian, probe.regBytes bytes), then reads.
109
+ // Uses STOP between the two phases: i2c-bus has no synchronous repeated-start
110
+ // transfer, and identity registers are readable that way on every chip in the registry.
111
+ function readIdentity(handle, addr, probe, cache) {
112
+ const key = `${probe.register}:${probe.regBytes}:${probe.length}:${probe.order}`;
113
+ if (!cache.has(key)) {
114
+ let value = null;
115
+ try {
116
+ const reg = Buffer.alloc(probe.regBytes);
117
+ for (let i = probe.regBytes - 1, r = probe.register; i >= 0; i--, r = Math.floor(r / 256)) reg[i] = r & 0xff;
118
+ handle.i2cWriteSync(addr, reg.length, reg);
119
+ const data = Buffer.alloc(probe.length);
120
+ handle.i2cReadSync(addr, probe.length, data);
121
+ value = 0;
122
+ for (let i = 0; i < probe.length; i++) {
123
+ const b = data[probe.order === 'little' ? probe.length - 1 - i : i];
124
+ value = value * 256 + b;
125
+ }
126
+ } catch (e) {
127
+ value = null;
128
+ }
129
+ cache.set(key, value);
130
+ }
131
+ return { key, value: cache.get(key) };
132
+ }
133
+
134
+ function sortedIds(chips) {
135
+ return chips.map(c => c.id).sort();
136
+ }
137
+
138
+ function device(address, props) {
139
+ return Object.assign({
140
+ address, candidates: [], identified: null, driver: null,
141
+ inUseByKernel: false, probeSkippedReason: null, aliases: [],
142
+ }, props);
143
+ }
144
+
145
+ function classify(handle, addr, cands, inUse, active) {
146
+ if (cands.length === 0) return device(addr, { inUseByKernel: inUse });
147
+ const ids = sortedIds(cands);
148
+ if (inUse) return device(addr, { candidates: ids, inUseByKernel: true, probeSkippedReason: 'kernel_bound' });
149
+ const probed = cands.filter(c => c.probe);
150
+ if (probed.length === 0) return device(addr, { candidates: ids });
151
+ if (!active && cands.some(c => c.writeSensitive)) {
152
+ return device(addr, { candidates: ids, probeSkippedReason: 'write_sensitive_candidate' });
153
+ }
154
+
155
+ const cache = new Map();
156
+ const matched = [];
157
+ for (const c of probed) {
158
+ const { value } = readIdentity(handle, addr, c.probe, cache);
159
+ // >>> 0 keeps the AND unsigned for 32-bit masks.
160
+ if (value !== null && c.probe.expected.includes((value & c.probe.mask) >>> 0)) matched.push(c);
161
+ }
162
+ if (matched.length === 1) {
163
+ return device(addr, { candidates: [matched[0].id], identified: matched[0].id, driver: matched[0].driver });
164
+ }
165
+ if (matched.length > 1) return device(addr, { candidates: sortedIds(matched) });
166
+ return device(addr, { candidates: sortedIds(cands.filter(c => !c.probe)) });
167
+ }
168
+
169
+ /**
170
+ * Scan the bus and name the chips that are connected.
171
+ *
172
+ * identified is set only when an identity-register read matches exactly one
173
+ * chip; otherwise candidates lists what the address could be. Addresses with a
174
+ * write-sensitive candidate are not probed unless active is true.
175
+ *
176
+ * @param {number|object} bus - Bus number or an open i2c-bus handle.
177
+ * @param {Object} [options]
178
+ * @param {boolean} [options.active=false] - Also probe addresses that have write-sensitive candidates.
179
+ * @param {Array} [options.registry] - Chip table in the registry.js CHIPS format (default: built in).
180
+ * @returns {Promise<DiscoveredDevice[]>} Sorted by address.
181
+ */
182
+ async function discover(bus, { active = false, registry = CHIPS } = {}) {
183
+ const { handle, owned } = openBus(bus);
184
+ try {
185
+ const present = await scanDetailed(handle);
186
+ const byAddr = new Map();
187
+ for (const chip of registry) {
188
+ for (const a of chip.addresses) {
189
+ if (!byAddr.has(a)) byAddr.set(a, []);
190
+ byAddr.get(a).push(chip);
191
+ }
192
+ }
193
+
194
+ const devices = [];
195
+ const merged = new Set();
196
+ for (const chip of registry) {
197
+ if (!chip.aliased) continue;
198
+ if (chip.addresses.every(a => present.has(a))) {
199
+ // A full block also fits any non-aliased chip that lists every address (24AA025UID).
200
+ const twins = registry.filter(o => o !== chip && !o.aliased && chip.addresses.every(a => o.addresses.includes(a)));
201
+ devices.push(device(chip.addresses[0], {
202
+ candidates: sortedIds([chip, ...twins]),
203
+ inUseByKernel: chip.addresses.some(a => present.get(a)),
204
+ aliases: chip.addresses.slice(1),
205
+ }));
206
+ chip.addresses.forEach(a => merged.add(a));
207
+ }
208
+ }
209
+ for (const addr of [...present.keys()].sort((a, b) => a - b)) {
210
+ if (!merged.has(addr)) devices.push(classify(handle, addr, byAddr.get(addr) || [], present.get(addr), active));
211
+ }
212
+ return devices.sort((a, b) => a.address - b.address);
213
+ } finally {
214
+ if (owned) handle.closeSync();
215
+ }
216
+ }
217
+
218
+ module.exports = { scan, scanDetailed, discover, FIRST_ADDRESS, LAST_ADDRESS };