periph 1.2.1 → 1.3.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 (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,278 @@
1
+ 'use strict';
2
+
3
+ const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4
+
5
+ /** Busy-wait for sub-millisecond pulses (setTimeout cannot do microseconds). */
6
+ function delayUs(us) {
7
+ const end = process.hrtime.bigint() + BigInt(Math.ceil(us)) * 1000n;
8
+ while (process.hrtime.bigint() < end) { /* spin */ }
9
+ }
10
+
11
+ /**
12
+ * How the controller's data pin is wired to the host.
13
+ *
14
+ * - SIMPLEX: MOSI -> DIN, write only; readData() is not available.
15
+ * - HALF_DUPLEX_HW: DIN/DOUT shared with MOSI, read through the SPI peripheral's
16
+ * hardware 3-wire mode. Not available through spi-device.
17
+ * - HALF_DUPLEX_PIN: MOSI -- resistor -- MISO joined at DIN/DOUT, read through a
18
+ * full-duplex (hardware or software) SPI master.
19
+ */
20
+ const WireMode = Object.freeze({ SIMPLEX: 0, HALF_DUPLEX_HW: 1, HALF_DUPLEX_PIN: 2 });
21
+
22
+ /**
23
+ * Display connection (SPI + D/C#, RES#, BUSY) for Node.js.
24
+ *
25
+ * Bundles an SPI link to a display controller (OLED: SH1106; e-paper: SSD1683,
26
+ * UC8276C; ...) with its side-band lines: D/C# (command/data), RES# (hardware
27
+ * reset) and BUSY. RES# and BUSY are optional: an OLED has no BUSY line and may
28
+ * tie RES# high. Chip drivers call sendCommand(), sendData(), readData(),
29
+ * reset() and waitBusy() and never touch D/C, RES, BUSY or CS themselves. See
30
+ * specs/transport_display.md.
31
+ *
32
+ * The BUSY polarity differs between controllers, so it is chip-level
33
+ * knowledge: waitBusy() takes it as an argument and busyLevel() returns the raw
34
+ * level.
35
+ *
36
+ * CS is hardware CS only: every sendCommand()/sendData()/readData() byte group
37
+ * is its own SPI transfer; a command and its parameters are separate CS windows
38
+ * and readData() uses one window per byte.
39
+ *
40
+ * Two ways to reach the controller; give exactly one of:
41
+ * - Hardware SPI: `busNumber` + `deviceNumber` open spi-device (kernel-owned CS),
42
+ * or `device`, an already-opened spi-device object (used by tests).
43
+ * - Software SPI: `spi`, a SoftSPI-like object (write(buf), read(n)), plus `cs`,
44
+ * an OutputPin driven here for each transfer.
45
+ */
46
+ class DisplayConnection {
47
+ /**
48
+ * @param {object} options
49
+ * @param {import('./output_pin').OutputPin} options.dc - D/C# pin (false = command, true = data).
50
+ * @param {import('./output_pin').OutputPin|null} [options.res=null] - RES# pin, or null if not wired.
51
+ * @param {import('./input_pin').InputPin|null} [options.busy=null] - BUSY pin read with isHigh(), or null.
52
+ * @param {number} [options.wireMode=WireMode.SIMPLEX] - A WireMode value.
53
+ * @param {number} [options.busNumber] - Hardware mode: SPI bus number.
54
+ * @param {number} [options.deviceNumber] - Hardware mode: chip-select line on the bus.
55
+ * @param {number} [options.maxSpeedHz=4000000] - Hardware mode: SPI clock in Hz.
56
+ * @param {object} [options.device] - Hardware mode: an already-opened spi-device object.
57
+ * @param {object} [options.spi] - Software mode: SoftSPI-like object.
58
+ * @param {import('./output_pin').OutputPin} [options.cs] - Software mode: CS# pin (active low).
59
+ * @param {number} [options.resetPulseUs=200] - RES# low time in microseconds.
60
+ * @param {number} [options.resetSettleMs=10] - Wait after RES# is released in milliseconds.
61
+ * @param {import('./output_pin').OutputPin|null} [options.enPin=null] - Optional EN-pin OutputPin.
62
+ * @param {boolean} [options.enActiveHigh=true] - True if the EN pin is active-high.
63
+ */
64
+ constructor(options = {}) {
65
+ const hardware = options.busNumber !== undefined || options.device !== undefined;
66
+ const software = options.spi !== undefined;
67
+ if (hardware === software) {
68
+ throw new Error('specify exactly one of {busNumber, deviceNumber} / {device} or {spi, cs}');
69
+ }
70
+ if (!options.dc) throw new Error('dc pin is required');
71
+ const wireMode = options.wireMode ?? WireMode.SIMPLEX;
72
+ if (![WireMode.SIMPLEX, WireMode.HALF_DUPLEX_HW, WireMode.HALF_DUPLEX_PIN].includes(wireMode)) {
73
+ throw new Error(`unknown wireMode ${wireMode}`);
74
+ }
75
+ if (wireMode === WireMode.HALF_DUPLEX_HW) {
76
+ throw new Error('HALF_DUPLEX_HW is not available through spi-device; use HALF_DUPLEX_PIN');
77
+ }
78
+ if (software) {
79
+ if (!options.cs) throw new Error('software SPI needs a cs OutputPin');
80
+ if (wireMode === WireMode.HALF_DUPLEX_PIN && typeof options.spi.read !== 'function') {
81
+ throw new Error('HALF_DUPLEX_PIN needs a software SPI with read() and a MISO pin');
82
+ }
83
+ }
84
+
85
+ this._dc = options.dc;
86
+ this._res = options.res ?? null;
87
+ this._busy = options.busy ?? null;
88
+ this._cs = software ? options.cs : null;
89
+ this._soft = software ? options.spi : null;
90
+ this.wireMode = wireMode;
91
+ this._resetPulseUs = options.resetPulseUs ?? 200;
92
+ this._resetSettleMs = options.resetSettleMs ?? 10;
93
+ this.enPin = options.enPin ?? null;
94
+ this.enActiveHigh = options.enActiveHigh ?? true;
95
+ this._enabled = true;
96
+
97
+ if (hardware) {
98
+ if (options.device !== undefined) {
99
+ this._device = options.device;
100
+ } else {
101
+ const spi = require('spi-device');
102
+ this._device = spi.openSync(options.busNumber, options.deviceNumber, {
103
+ mode: spi.MODE0,
104
+ maxSpeedHz: options.maxSpeedHz ?? 4_000_000,
105
+ });
106
+ }
107
+ } else {
108
+ this._device = null;
109
+ }
110
+ this._ready = this._init();
111
+ }
112
+
113
+ /** Set the idle levels of the side-band lines (D/C# low, RES# high, CS# high). */
114
+ async _init() {
115
+ await this._dc.set(false);
116
+ if (this._res) await this._res.set(true);
117
+ if (this._cs) await this._cs.set(true);
118
+ }
119
+
120
+ /** Resolves once the constructor has driven the idle levels. @returns {Promise<void>} */
121
+ ready() { return this._ready; }
122
+
123
+ /** Resume operation; drives the hardware EN pin to its active level if wired. @returns {Promise<void>} */
124
+ async enable() {
125
+ this._enabled = true;
126
+ if (this.enPin) await this.enPin.set(this.enActiveHigh);
127
+ }
128
+
129
+ /** Gate all bus operations; drives the hardware EN pin inactive if wired. @returns {Promise<void>} */
130
+ async disable() {
131
+ this._enabled = false;
132
+ if (this.enPin) await this.enPin.set(!this.enActiveHigh);
133
+ }
134
+
135
+ /** @returns {boolean} The current software-gate state. */
136
+ isEnabled() { return this._enabled; }
137
+
138
+ /**
139
+ * Hardware reset: RES# low for resetPulseUs, then high and wait resetSettleMs.
140
+ *
141
+ * Does not wait for BUSY; chip drivers call waitBusy() afterwards with their
142
+ * polarity. No-op if disabled or no RES# pin was given.
143
+ * @returns {Promise<void>}
144
+ */
145
+ async reset() {
146
+ if (!this._enabled || !this._res) return;
147
+ await this._res.set(false);
148
+ delayUs(this._resetPulseUs);
149
+ await this._res.set(true);
150
+ await sleepMs(this._resetSettleMs);
151
+ }
152
+
153
+ /**
154
+ * Wait @p ms milliseconds (for chips without a BUSY pin, e.g. a power-up wait).
155
+ * @param {number} ms - Time in milliseconds.
156
+ * @returns {Promise<void>}
157
+ */
158
+ async delayMs(ms) { await sleepMs(ms); }
159
+
160
+ /**
161
+ * Wait at least `us` microseconds (for chips that need a gap between bytes, e.g. the ST7036's 30 us).
162
+ * Sub-millisecond waits spin on process.hrtime for under 1 ms and use a timer beyond; where the
163
+ * host cannot be that precise the wait is longer, which is harmless.
164
+ * @param {number} us - Time in microseconds.
165
+ * @returns {Promise<void>}
166
+ */
167
+ async delayUs(us) {
168
+ if (us >= 1000) { await sleepMs(Math.ceil(us / 1000)); return; }
169
+ const end = process.hrtime.bigint() + BigInt(Math.ceil(us)) * 1000n;
170
+ while (process.hrtime.bigint() < end) { /* busy wait */ }
171
+ }
172
+
173
+ /** @returns {boolean} Raw level of the BUSY line; false when no BUSY pin was given. */
174
+ busyLevel() {
175
+ return this._busy !== null && this._busy.isHigh();
176
+ }
177
+
178
+ /**
179
+ * Poll BUSY (every millisecond) until it is no longer active.
180
+ * @param {boolean} busyActiveHigh - true if the controller drives BUSY high while busy
181
+ * (SSD1683), false if it drives it low (UC8276C BUSY_N).
182
+ * @param {number|null} [timeoutMs=null] - Give up after this many milliseconds; null waits forever.
183
+ * @returns {Promise<boolean>} true when the controller became ready (or has no BUSY pin),
184
+ * false on timeout.
185
+ */
186
+ async waitBusy(busyActiveHigh, timeoutMs = null) {
187
+ if (this._busy === null) return true;
188
+ const start = Date.now();
189
+ while (this._busy.isHigh() === !!busyActiveHigh) {
190
+ if (timeoutMs !== null && Date.now() - start >= timeoutMs) return false;
191
+ await sleepMs(1);
192
+ }
193
+ return true;
194
+ }
195
+
196
+ async _spiWrite(buf) {
197
+ if (this._soft) {
198
+ await this._cs.set(false);
199
+ this._soft.write(buf);
200
+ await this._cs.set(true);
201
+ } else {
202
+ this._device.transferSync([{ sendBuffer: buf, byteLength: buf.length }]);
203
+ }
204
+ }
205
+
206
+ async _spiRead(n) {
207
+ if (this._soft) {
208
+ await this._cs.set(false);
209
+ const out = this._soft.read(n);
210
+ await this._cs.set(true);
211
+ return out;
212
+ }
213
+ const receiveBuffer = Buffer.alloc(n);
214
+ this._device.transferSync([{ receiveBuffer, byteLength: n }]);
215
+ return receiveBuffer;
216
+ }
217
+
218
+ /**
219
+ * Send a command byte (D/C# low), then optional parameter bytes (D/C# high).
220
+ *
221
+ * The command byte and the parameters are separate SPI transfers (separate
222
+ * CS windows). No-op if disabled.
223
+ * @param {number} cmd - Command byte.
224
+ * @param {Buffer|Uint8Array|number[]} [data=[]] - Parameter bytes.
225
+ * @returns {Promise<void>}
226
+ */
227
+ async sendCommand(cmd, data = []) {
228
+ if (!this._enabled) return;
229
+ await this._dc.set(false);
230
+ await this._spiWrite(Buffer.from([cmd]));
231
+ const payload = Buffer.isBuffer(data) ? data : Buffer.from(data);
232
+ if (payload.length > 0) {
233
+ await this._dc.set(true);
234
+ await this._spiWrite(payload);
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Send data bytes (D/C# high) as one SPI transfer. No-op if disabled.
240
+ * @param {Buffer|Uint8Array|number[]} data - Bytes to send, e.g. a pixel plane.
241
+ * @returns {Promise<void>}
242
+ */
243
+ async sendData(data) {
244
+ if (!this._enabled) return;
245
+ const payload = Buffer.isBuffer(data) ? data : Buffer.from(data);
246
+ if (payload.length === 0) return;
247
+ await this._dc.set(true);
248
+ await this._spiWrite(payload);
249
+ }
250
+
251
+ /**
252
+ * Read length bytes the controller drives after a read command (D/C# high).
253
+ *
254
+ * One CS window per byte. A disabled connection returns zeros.
255
+ * @param {number} length - Number of bytes to read.
256
+ * @returns {Promise<Buffer>} The bytes read.
257
+ * @throws {Error} In SIMPLEX wire mode.
258
+ */
259
+ async readData(length) {
260
+ if (this.wireMode === WireMode.SIMPLEX) {
261
+ throw new Error('readData() is not available in SIMPLEX wire mode');
262
+ }
263
+ if (!this._enabled) return Buffer.alloc(length);
264
+ await this._dc.set(true);
265
+ const out = Buffer.alloc(length);
266
+ for (let i = 0; i < length; i++) {
267
+ out[i] = (await this._spiRead(1))[0];
268
+ }
269
+ return out;
270
+ }
271
+
272
+ /** Close the SPI device if this connection opened one. */
273
+ close() {
274
+ if (this._device && typeof this._device.closeSync === 'function') this._device.closeSync();
275
+ }
276
+ }
277
+
278
+ module.exports = { DisplayConnection, WireMode };
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ const { WireMode } = require('./display');
4
+
5
+ /**
6
+ * In-memory fake display connection for unit tests — no hardware, no bus.
7
+ *
8
+ * Has the public interface of the real connection (sendCommand, sendData,
9
+ * readData, reset, waitBusy, busyLevel, enable/disable) and records every call
10
+ * in order in `events`: {type:'reset'}, {type:'command', cmd, data},
11
+ * {type:'data', data}, {type:'read', length}, {type:'waitBusy',
12
+ * busyActiveHigh, timeoutMs}, {type:'delay', ms}, {type:'delayUs', us}.
13
+ */
14
+ class DisplayConnectionMock {
15
+ /**
16
+ * @param {object} [options]
17
+ * @param {number} [options.wireMode=WireMode.SIMPLEX] - readData() throws in SIMPLEX.
18
+ */
19
+ constructor({ wireMode = WireMode.SIMPLEX } = {}) {
20
+ this.wireMode = wireMode;
21
+ this.events = [];
22
+ this.ready = true; // waitBusy() result; set false to simulate a timeout
23
+ this.busyHigh = false; // raw level returned by busyLevel()
24
+ this._readQueue = [];
25
+ this._enabled = true;
26
+ }
27
+
28
+ /** Queue bytes that later readData() calls return, in order. @param {Buffer|number[]} data */
29
+ queueRead(data) { this._readQueue.push(...data); }
30
+
31
+ /** @returns {Array<{cmd:number,data:Buffer}>} sendCommand() calls so far. */
32
+ get commands() {
33
+ return this.events.filter((e) => e.type === 'command').map((e) => ({ cmd: e.cmd, data: e.data }));
34
+ }
35
+
36
+ /** @returns {number} Number of reset() calls so far. */
37
+ get resetCount() { return this.events.filter((e) => e.type === 'reset').length; }
38
+
39
+ async enable() { this._enabled = true; }
40
+ async disable() { this._enabled = false; }
41
+ isEnabled() { return this._enabled; }
42
+
43
+ async reset() { if (this._enabled) this.events.push({ type: 'reset' }); }
44
+ async delayMs(ms) { this.events.push({ type: 'delay', ms }); }
45
+ async delayUs(us) { this.events.push({ type: 'delayUs', us }); }
46
+ busyLevel() { return this.busyHigh; }
47
+
48
+ async waitBusy(busyActiveHigh, timeoutMs = null) {
49
+ this.events.push({ type: 'waitBusy', busyActiveHigh, timeoutMs });
50
+ return this.ready;
51
+ }
52
+
53
+ async sendCommand(cmd, data = []) {
54
+ if (!this._enabled) return;
55
+ this.events.push({ type: 'command', cmd, data: Buffer.from(data) });
56
+ }
57
+
58
+ async sendData(data) {
59
+ if (!this._enabled) return;
60
+ this.events.push({ type: 'data', data: Buffer.from(data) });
61
+ }
62
+
63
+ async readData(length) {
64
+ if (this.wireMode === WireMode.SIMPLEX) {
65
+ throw new Error('readData() is not available in SIMPLEX wire mode');
66
+ }
67
+ if (!this._enabled) return Buffer.alloc(length);
68
+ this.events.push({ type: 'read', length });
69
+ const out = Buffer.alloc(length);
70
+ for (let i = 0; i < length; i++) out[i] = this._readQueue.length ? this._readQueue.shift() : 0;
71
+ return out;
72
+ }
73
+
74
+ close() {}
75
+ }
76
+
77
+ module.exports = { DisplayConnectionMock };
@@ -20,11 +20,13 @@ class HX711Connection {
20
20
  * @param {object} dout - opengpio Input instance (boolean `.value`).
21
21
  * @param {object} pdSck - opengpio Output instance (boolean `.value`).
22
22
  * @param {import('./output_pin').OutputPin|null} [enPin=null] - Optional EN-pin OutputPin.
23
+ * @param {boolean} [enActiveHigh=true] - True if the EN pin is active-high (default); false for active-low.
23
24
  */
24
- constructor(dout, pdSck, enPin = null) {
25
+ constructor(dout, pdSck, enPin = null, enActiveHigh = true) {
25
26
  this._dout = dout;
26
27
  this._sck = pdSck;
27
28
  this.enPin = enPin;
29
+ this.enActiveHigh = enActiveHigh;
28
30
  this._enabled = true;
29
31
  this._sck.value = false;
30
32
  }
@@ -34,7 +36,7 @@ class HX711Connection {
34
36
  */
35
37
  async enable() {
36
38
  this._enabled = true;
37
- if (this.enPin) await this.enPin.set(true);
39
+ if (this.enPin) await this.enPin.set(this.enActiveHigh);
38
40
  }
39
41
 
40
42
  /** Gate readRaw(); drives the hardware EN pin low if wired.
@@ -42,7 +44,7 @@ class HX711Connection {
42
44
  */
43
45
  async disable() {
44
46
  this._enabled = false;
45
- if (this.enPin) await this.enPin.set(false);
47
+ if (this.enPin) await this.enPin.set(!this.enActiveHigh);
46
48
  }
47
49
 
48
50
  /** @returns {boolean} The current software-gate state. */
@@ -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
  * I²C connection for Node.js (wraps i2c-bus, uses /dev/i2c-N on Linux).
@@ -9,15 +9,17 @@ const { Connection } = require('./connection');
9
9
  * One instance represents one device on the bus; the bus is opened
10
10
  * synchronously at construction. Call close() to release the bus when done.
11
11
  */
12
- class I2CConnection extends Connection {
12
+ class I2CConnection extends RegisterConnection {
13
13
  /**
14
14
  * @param {number} busNumber - I²C bus number (opens /dev/i2c-{busNumber}).
15
15
  * @param {number} addr - 7-bit device address.
16
16
  * @param {import('./input_pin').InputPin|null} [intPin=null] - Optional INT-line InputPin.
17
17
  * @param {import('./output_pin').OutputPin|null} [enPin=null] - Optional EN-pin OutputPin.
18
+ * @param {boolean} [enActiveHigh=true] - True if the EN pin is active-high (default); false for active-low.
19
+ * @param {number} [regBytes=1] - Register address width in bytes, big-endian.
18
20
  */
19
- constructor(busNumber, addr, intPin = null, enPin = null) {
20
- super(intPin, enPin);
21
+ constructor(busNumber, addr, intPin = null, enPin = null, regBytes = 1, enActiveHigh = true) {
22
+ super(intPin, enPin, regBytes, enActiveHigh);
21
23
  this._bus = i2c.openSync(busNumber);
22
24
  this._addr = addr;
23
25
  }
@@ -26,6 +26,32 @@ class I2CConnectionMock {
26
26
  this.writes = [];
27
27
  this._readQueue = [];
28
28
  this._addressWidth = 1;
29
+ this._failWrites = 0;
30
+ this._failSkip = 0;
31
+ this._failReads = 0;
32
+ }
33
+
34
+ /**
35
+ * Make `n` write() / writeRead() calls reject (a NACK) after letting the next `after` succeed;
36
+ * the failing calls are still logged in `writes`.
37
+ */
38
+ failNextWrites(n, after = 0) {
39
+ this._failWrites = n;
40
+ this._failSkip = after;
41
+ }
42
+
43
+ /** Make the next `n` read() calls reject; the read queue is not consumed. */
44
+ failNextReads(n) {
45
+ this._failReads = n;
46
+ }
47
+
48
+ _maybeFailWrite() {
49
+ if (this._failSkip > 0) {
50
+ this._failSkip--;
51
+ } else if (this._failWrites > 0) {
52
+ this._failWrites--;
53
+ throw new Error('I2C NACK (mock)');
54
+ }
29
55
  }
30
56
 
31
57
  /** Set the register address width in bytes (default 1). */
@@ -56,6 +82,7 @@ class I2CConnectionMock {
56
82
  async write(data) {
57
83
  const buf = Buffer.from(data);
58
84
  this.writes.push(buf);
85
+ this._maybeFailWrite();
59
86
  if (buf.length > this._addressWidth) {
60
87
  const reg = this._readAddress(buf);
61
88
  for (let i = this._addressWidth; i < buf.length; i++) {
@@ -65,6 +92,10 @@ class I2CConnectionMock {
65
92
  }
66
93
 
67
94
  async read(n) {
95
+ if (this._failReads > 0) {
96
+ this._failReads--;
97
+ throw new Error('I2C NACK (mock)');
98
+ }
68
99
  if (this._readQueue.length > 0) {
69
100
  const front = this._readQueue.shift();
70
101
  const out = Buffer.alloc(n);
@@ -77,6 +108,7 @@ class I2CConnectionMock {
77
108
  async writeRead(data, n) {
78
109
  const buf = Buffer.from(data);
79
110
  this.writes.push(buf);
111
+ this._maybeFailWrite();
80
112
  const reg = this._readAddress(buf);
81
113
  const out = Buffer.alloc(n);
82
114
  for (let i = 0; i < n; i++) {
@@ -85,6 +117,21 @@ class I2CConnectionMock {
85
117
  return out;
86
118
  }
87
119
 
120
+ async readReg(reg, length) {
121
+ return this.writeRead(this._regAddrBytes(reg), length);
122
+ }
123
+
124
+ async writeReg(reg, data) {
125
+ const payload = Buffer.isBuffer(data) ? data : Buffer.from(typeof data === 'number' ? [data] : data);
126
+ return this.write(Buffer.concat([this._regAddrBytes(reg), payload]));
127
+ }
128
+
129
+ _regAddrBytes(reg) {
130
+ const addr = Buffer.alloc(this._addressWidth);
131
+ addr.writeUIntBE(reg, 0, this._addressWidth);
132
+ return addr;
133
+ }
134
+
88
135
  async close() {}
89
136
  }
90
137
 
@@ -1,12 +1,16 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * Delivers edge notifications from a chip's INT line.
4
+ * Delivers edge notifications from a chip's INT line, and reads its level.
5
5
  *
6
- * Intentionally minimal: it only signals that *an* edge occurred. The chip
7
- * driver always calls pollInterrupt() to determine the cause. Multiple
8
- * handlers may be registered on the same InputPin instance — the common
9
- * pattern for chips with open-drain INT outputs wired to a single GPIO.
6
+ * Edge delivery is intentionally minimal: it only signals that *an* edge
7
+ * occurred. The chip driver always calls pollInterrupt() to determine the
8
+ * cause. Multiple handlers may be registered on the same InputPin instance —
9
+ * the common pattern for chips with open-drain INT outputs wired to a single
10
+ * GPIO.
11
+ *
12
+ * Level signals that a driver samples at a moment of its own choosing (a
13
+ * BUSY output, a data-ready line) use isHigh() instead of an edge handler.
10
14
  */
11
15
  class InputPin {
12
16
  /**
@@ -25,6 +29,17 @@ class InputPin {
25
29
  * @abstract
26
30
  */
27
31
  async offEdge(_callback) { throw new Error('abstract'); }
32
+
33
+ /**
34
+ * Read the electrical level of the line now (synchronous).
35
+ *
36
+ * The raw level: no inversion and no debounce. Active-low signals are
37
+ * interpreted by the chip driver. A level read does not disturb a
38
+ * registered edge handler. There is no default body.
39
+ * @returns {boolean} true when the line is at logic high.
40
+ * @abstract
41
+ */
42
+ isHigh() { throw new Error('abstract'); }
28
43
  }
29
44
 
30
45
  /**
@@ -89,6 +104,17 @@ class EpollInputPin extends InputPin {
89
104
  return buf[0] === 0x31 ? 1 : 0; // ASCII '1' vs '0'
90
105
  }
91
106
 
107
+ /**
108
+ * Read the level from the sysfs value file (the armed descriptor when edges
109
+ * are registered, otherwise a one-off read).
110
+ * @returns {boolean}
111
+ */
112
+ isHigh() {
113
+ if (this._fd !== null) return this._readValue() === 1;
114
+ const fs = require('fs');
115
+ return fs.readFileSync(this._valuePath)[0] === 0x31;
116
+ }
117
+
92
118
  async offEdge(callback) {
93
119
  this._handlers = this._handlers.filter(h => h !== callback);
94
120
  if (this._handlers.length === 0 && this._armed) {
@@ -131,6 +157,11 @@ class PollingInputPin extends InputPin {
131
157
  }
132
158
  }
133
159
 
160
+ /** @returns {boolean} The level returned by the readValue function. */
161
+ isHigh() {
162
+ return Number(this._readValue()) === 1;
163
+ }
164
+
134
165
  async offEdge(callback) {
135
166
  this._handlers = this._handlers.filter(h => h !== callback);
136
167
  if (this._handlers.length === 0 && this._timer) {
@@ -0,0 +1,14 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Interpret the low `bits` bits of `value` as two's-complement signed.
5
+ * @param {number} value - Unsigned raw register value.
6
+ * @param {number} bits - Width of the value in bits (e.g. 16, 24).
7
+ * @returns {number} The signed interpretation of the low `bits` bits of `value`.
8
+ */
9
+ function toSigned(value, bits) {
10
+ const signBit = 1 << (bits - 1);
11
+ return (value & (signBit - 1)) - (value & signBit);
12
+ }
13
+
14
+ module.exports = { toSigned };
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+
3
+ const { Connection } = require('./connection');
4
+
5
+ /**
6
+ * Connection with register-addressed read/write, for I2C/SMBus/SPI-style buses.
7
+ *
8
+ * Sits between Connection and the register-capable concrete classes
9
+ * (I2CConnection, SMBusConnection, SPIConnection); every other concrete
10
+ * connection (UARTConnection, HX711Connection, NeoPixelConnection,
11
+ * SiPoConnection, DHTxxConnection) is unaffected and continues to extend
12
+ * Connection only.
13
+ *
14
+ * The default implementation below (writeRead/write of a leading, big-endian
15
+ * register-address of `regBytes` bytes) matches I2C/SMBus behavior as-is;
16
+ * SPIConnection overrides both to build its single-byte command byte instead
17
+ * (see specs/feature_register_access_design.md §11.2 for why SPI stays
18
+ * single-byte).
19
+ */
20
+ class RegisterConnection extends Connection {
21
+ /**
22
+ * @param {import('./input_pin').InputPin|null} [intPin=null] - Optional INT-line InputPin.
23
+ * @param {import('./output_pin').OutputPin|null} [enPin=null] - Optional EN-pin OutputPin.
24
+ * @param {boolean} [enActiveHigh=true] - True if the EN pin is active-high (default); false for active-low.
25
+ * @param {number} [regBytes=1] - Register address width in bytes, big-endian.
26
+ */
27
+ constructor(intPin = null, enPin = null, regBytes = 1, enActiveHigh = true) {
28
+ super(intPin, enPin, enActiveHigh);
29
+ this._regBytes = regBytes;
30
+ }
31
+
32
+ /**
33
+ * Read `length` bytes starting at register `reg`.
34
+ * @param {number} reg - Register address.
35
+ * @param {number} length - Number of bytes to read.
36
+ * @returns {Promise<Buffer>} Data received from the device.
37
+ */
38
+ async readReg(reg, length) {
39
+ return this.writeRead(this._regAddrBytes(reg), length);
40
+ }
41
+
42
+ /**
43
+ * Write `data` to register `reg`.
44
+ * @param {number} reg - Register address.
45
+ * @param {Buffer|Uint8Array|number} data - Bytes to write, or a single int for a 1-byte register.
46
+ * @returns {Promise<void>}
47
+ */
48
+ async writeReg(reg, data) {
49
+ const payload = Buffer.isBuffer(data) ? data : Buffer.from(typeof data === 'number' ? [data] : data);
50
+ return this.write(Buffer.concat([this._regAddrBytes(reg), payload]));
51
+ }
52
+
53
+ /**
54
+ * Build a big-endian register address of `this._regBytes` bytes.
55
+ * @param {number} reg - Register address.
56
+ * @returns {Buffer}
57
+ */
58
+ _regAddrBytes(reg) {
59
+ const addr = Buffer.alloc(this._regBytes);
60
+ addr.writeUIntBE(reg, 0, this._regBytes);
61
+ return addr;
62
+ }
63
+ }
64
+
65
+ module.exports = { RegisterConnection };
@@ -32,6 +32,7 @@ class SiPoConnection {
32
32
  * @param {object} [options.serIn] - Software mode: opengpio Output instance for SER IN.
33
33
  * @param {object} [options.srck] - Software mode: opengpio Output instance for SRCK.
34
34
  * @param {import('./output_pin').OutputPin|null} [options.enPin=null] - Optional EN-pin OutputPin.
35
+ * @param {boolean} [options.enActiveHigh=true] - True if the EN pin is active-high (default); false for active-low.
35
36
  */
36
37
  constructor(rck, options = {}) {
37
38
  const hardware = options.busNumber !== undefined;
@@ -47,6 +48,7 @@ class SiPoConnection {
47
48
  this._serIn = options.serIn ?? null;
48
49
  this._srck = options.srck ?? null;
49
50
  this.enPin = options.enPin ?? null;
51
+ this.enActiveHigh = options.enActiveHigh ?? true;
50
52
  this._enabled = true;
51
53
 
52
54
  if (hardware) {
@@ -68,7 +70,7 @@ class SiPoConnection {
68
70
  */
69
71
  async enable() {
70
72
  this._enabled = true;
71
- if (this.enPin) await this.enPin.set(true);
73
+ if (this.enPin) await this.enPin.set(this.enActiveHigh);
72
74
  }
73
75
 
74
76
  /** Gate write()/clear()/setOutputEnable(); drives the hardware EN pin low if wired.
@@ -76,7 +78,7 @@ class SiPoConnection {
76
78
  */
77
79
  async disable() {
78
80
  this._enabled = false;
79
- if (this.enPin) await this.enPin.set(false);
81
+ if (this.enPin) await this.enPin.set(!this.enActiveHigh);
80
82
  }
81
83
 
82
84
  /** @returns {boolean} The current software-gate state. */