periph 1.5.4 → 1.6.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 (73) hide show
  1. package/README.md +17 -0
  2. package/examples/gas/ccs811/complete.js +87 -0
  3. package/examples/gas/ccs811/demo.js +108 -0
  4. package/examples/gas/ccs811/minimal.js +20 -0
  5. package/examples/gas/rrh46410/complete.js +78 -0
  6. package/examples/gas/rrh46410/demo.js +86 -0
  7. package/examples/gas/rrh46410/minimal.js +21 -0
  8. package/examples/gas/rrh62000/complete.js +74 -0
  9. package/examples/gas/rrh62000/demo.js +87 -0
  10. package/examples/gas/rrh62000/minimal.js +22 -0
  11. package/examples/gas/scd30/complete.js +73 -0
  12. package/examples/gas/scd30/demo.js +102 -0
  13. package/examples/gas/scd30/minimal.js +20 -0
  14. package/examples/gas/scd40/complete.js +76 -0
  15. package/examples/gas/scd40/demo.js +109 -0
  16. package/examples/gas/scd40/minimal.js +20 -0
  17. package/examples/light/si1133/complete.js +89 -0
  18. package/examples/light/si1133/demo.js +93 -0
  19. package/examples/light/si1133/minimal.js +22 -0
  20. package/examples/light/si1145/complete.js +93 -0
  21. package/examples/light/si1145/demo.js +98 -0
  22. package/examples/light/si1145/minimal.js +22 -0
  23. package/examples/light/tsl2561/complete.js +74 -0
  24. package/examples/light/tsl2561/demo.js +46 -0
  25. package/examples/light/tsl2561/minimal.js +22 -0
  26. package/examples/light/tsl2591/complete.js +90 -0
  27. package/examples/light/tsl2591/demo.js +119 -0
  28. package/examples/light/tsl2591/minimal.js +22 -0
  29. package/examples/light/vcnl4040/complete.js +102 -0
  30. package/examples/light/vcnl4040/demo.js +125 -0
  31. package/examples/light/vcnl4040/minimal.js +25 -0
  32. package/examples/light/vcnl4200/complete.js +101 -0
  33. package/examples/light/vcnl4200/demo.js +126 -0
  34. package/examples/light/vcnl4200/minimal.js +25 -0
  35. package/examples/pressure/spl06/complete.js +81 -0
  36. package/examples/pressure/spl06/demo.js +106 -0
  37. package/examples/pressure/spl06/minimal.js +22 -0
  38. package/examples/rfid/pn532/complete.js +99 -0
  39. package/examples/rfid/pn532/demo.js +121 -0
  40. package/examples/rfid/pn532/minimal.js +22 -0
  41. package/examples/rfid/st25dv/complete.js +94 -0
  42. package/examples/rfid/st25dv/demo.js +121 -0
  43. package/examples/rfid/st25dv/minimal.js +21 -0
  44. package/examples/rtc/bq32000/complete.js +53 -0
  45. package/examples/rtc/bq32000/demo.js +77 -0
  46. package/examples/rtc/bq32000/minimal.js +20 -0
  47. package/examples/rtc/ds1307/complete.js +54 -0
  48. package/examples/rtc/ds1307/demo.js +96 -0
  49. package/examples/rtc/ds1307/minimal.js +20 -0
  50. package/examples/rtc/ds1371/complete.js +53 -0
  51. package/examples/rtc/ds1371/demo.js +85 -0
  52. package/examples/rtc/ds1371/minimal.js +25 -0
  53. package/package.json +1 -1
  54. package/src/chips/gas/ccs811.js +400 -0
  55. package/src/chips/gas/rrh46410.js +534 -0
  56. package/src/chips/gas/rrh62000.js +418 -0
  57. package/src/chips/gas/scd30.js +368 -0
  58. package/src/chips/gas/scd40.js +451 -0
  59. package/src/chips/light/si1133.js +583 -0
  60. package/src/chips/light/si1145.js +630 -0
  61. package/src/chips/light/tsl2561.js +445 -0
  62. package/src/chips/light/tsl2591.js +561 -0
  63. package/src/chips/light/vcnl4040.js +576 -0
  64. package/src/chips/light/vcnl4200.js +592 -0
  65. package/src/chips/pressure/spl06.js +461 -0
  66. package/src/chips/rfid/pn532.js +513 -0
  67. package/src/chips/rfid/st25dv.js +628 -0
  68. package/src/chips/rtc/bq32000.js +334 -0
  69. package/src/chips/rtc/ds1307.js +327 -0
  70. package/src/chips/rtc/ds1371.js +453 -0
  71. package/src/connection/i2c.js +46 -13
  72. package/src/connection/smbus.js +21 -8
  73. package/src/discovery/registry.js +17 -17
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { SPL06Full } = require('../../../src/chips/pressure/spl06');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x77', 16);
8
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
9
+
10
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR); // Create I²C connection, (bus=1, addr=0x77) → Connection
11
+ const sensor = new SPL06Full(connection); // Create SPL06 driver, (connection) → void
12
+
13
+ async function main() {
14
+ // --- Identity and calibration ---
15
+ // init() checks ID = 0x10; the nine coefficients are factory-trimmed per
16
+ // part and drive every compensated value below.
17
+ await sensor.init(); // Check ID, read coefficients, apply defaults, () → void
18
+ console.log('ID 0x10 verified', sensor.coefficients()); // Decoded calibration, () → {c0 … c30}
19
+
20
+ // --- Altimeter: 20 s at 1 Hz, altitude relative to the first reading ---
21
+ // The first pressure becomes the reference level, so the altitude column
22
+ // shows how far the sensor moved since start (about 12 Pa per metre).
23
+ const p0 = await sensor.readPressure(); // Reference pressure, () → number Pa
24
+ for (let i = 0; i < 20; i++) {
25
+ const m = await sensor.read(); // Temperature and pressure, () → {temperature_c °C, pressure_pa Pa}
26
+ const t = await sensor.readTemperature(); // Temperature only, () → number °C
27
+ const h = await sensor.altitude(p0); // Altitude vs. reference, (seaLevelPa) → number m
28
+ console.log(`${i} s ${m.temperature_c.toFixed(2)} C (${t.toFixed(2)} C) ${m.pressure_pa.toFixed(2)} Pa ${h.toFixed(2)} m`);
29
+ await sleep(1000);
30
+ }
31
+
32
+ // --- Oversampling: noise and measurement time at 1x, 16x and 128x ---
33
+ // More oversampling means less noise but longer measurements; above 8x
34
+ // the driver sets P_SHIFT automatically.
35
+ for (const osr of [1, 16, 128]) {
36
+ await sensor.setPressureConfig(osr, 1); // Pressure oversampling, (oversampling, rate) → void
37
+ const values = [];
38
+ const start = Date.now();
39
+ for (let j = 0; j < 10; j++) values.push(await sensor.readPressure()); // Pressure, () → number Pa
40
+ const per = (Date.now() - start) / 10;
41
+ const mean = values.reduce((a, b) => a + b, 0) / values.length;
42
+ const sd = Math.sqrt(values.reduce((a, v) => a + (v - mean) ** 2, 0) / values.length);
43
+ console.log(`${osr}x: mean ${mean.toFixed(2)} Pa sd ${sd.toFixed(2)} Pa ${per.toFixed(1)} ms per reading`);
44
+ }
45
+
46
+ // --- Variometer: background mode at 8 Hz ---
47
+ // The chip measures on its own; readContinuous only fetches the latest
48
+ // results, so the host never waits for a conversion it started itself.
49
+ await sensor.setPressureConfig(16, 8); // 16x, 8 Hz, (oversampling, rate) → void
50
+ await sensor.setTemperatureConfig(1, 8); // 1x, 8 Hz, (oversampling, rate) → void
51
+ await sensor.startContinuous(true, true); // Background mode, (pressure, temperature) → void
52
+ let last = null;
53
+ for (let i = 0; i < 16; i++) {
54
+ const c = await sensor.readContinuous(); // Latest results, () → {temperature_c, pressure_pa}
55
+ if (last !== null) console.log(`${c.pressure_pa.toFixed(2)} Pa climb ${(-(c.pressure_pa - last) / 12 * 8).toFixed(2)} m/s`);
56
+ last = c.pressure_pa;
57
+ }
58
+ console.log('ready flags', await sensor.dataReady()); // Ready flags, () → [pressureReady, temperatureReady]
59
+ await sensor.stop(); // Standby, () → void
60
+
61
+ // --- FIFO: let the chip collect 32 results, then read them in one go ---
62
+ // Each entry's LSB marks it as pressure or temperature; the host can sleep
63
+ // while the chip fills the FIFO (32 entries = 2 s at 8 Hz for both).
64
+ await sensor.flushFifo(); // Empty the FIFO, () → void
65
+ await sensor.enableFifo(); // FIFO on, () → void
66
+ await sensor.startContinuous(); // Background mode, (pressure=true, temperature=true) → void
67
+ for (let i = 0; i < 50 && !(await sensor.fifoStatus())[1]; i++) { // Wait for full, () → [empty, full]
68
+ await sleep(100);
69
+ }
70
+ await sensor.stop(); // Standby, () → void
71
+ const entries = await sensor.readFifo(); // Drain FIFO, () → [{kind, value}]
72
+ const pressures = entries.filter((e) => e.kind === 'pressure').map((e) => e.value);
73
+ const pmean = pressures.reduce((a, b) => a + b, 0) / Math.max(pressures.length, 1);
74
+ console.log(`${entries.length} FIFO entries, ${pressures.length} pressure, mean ${pmean.toFixed(2)} Pa`);
75
+ await sensor.disableFifo(); // FIFO off, () → void
76
+
77
+ // --- Data-ready interrupt ---
78
+ // SDO doubles as the interrupt line; the callback receives the INT_STS bits.
79
+ // Without an INT pin on the connection the driver polls INT_STS instead.
80
+ await sensor.enableInterrupt(SPL06Full.SOURCE_PRESSURE); // Pressure-ready interrupt, (source) → void
81
+ await sensor.pollInterrupt(); // Clear stale status, () → number
82
+ await sensor.onInterrupt((status) => console.log(`interrupt 0x${status.toString(16)}`)); // Subscribe, (callback, intPin=null) → void
83
+ await sensor.startContinuous(true, true); // Background mode, (pressure, temperature) → void
84
+ await sleep(2000);
85
+ await sensor.offInterrupt(); // Unsubscribe, () → void
86
+ await sensor.disableInterrupt(SPL06Full.SOURCE_PRESSURE); // Disable source, (source) → void
87
+ await sensor.stop(); // Standby, () → void
88
+
89
+ // --- Compensation by hand ---
90
+ // compensate() turns raw register values into SI units with the stored
91
+ // coefficients; useful for logging raw data and converting it later.
92
+ await sensor.setPressureConfig(16, 1); // Back to 16x, (oversampling, rate) → void
93
+ await sensor.setTemperatureConfig(1, 1); // Back to 1x, (oversampling, rate) → void
94
+ const [praw, traw] = await sensor.readRaw(); // Raw results, () → [praw, traw]
95
+ console.log('raw', praw, traw, '->', sensor.compensate(praw, traw, 16, 1)); // Compensate, (praw, traw, pOversampling, tOversampling) → {temperature_c, pressure_pa}
96
+
97
+ // --- Wrap up ---
98
+ // Standby, empty FIFO and a soft reset leave the chip as after power-up
99
+ // (plus the driver defaults).
100
+ await sensor.stop(); // Standby, () → void
101
+ await sensor.flushFifo(); // Empty the FIFO, () → void
102
+ await sensor.reset(); // Soft reset and defaults, () → void
103
+ await connection.close();
104
+ }
105
+
106
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { SPL06Minimal } = require('../../../src/chips/pressure/spl06');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x77', 16);
8
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
9
+
10
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR); // Create I²C connection, (bus=1, addr=0x77) → Connection
11
+ const sensor = new SPL06Minimal(connection); // Create SPL06 driver, (connection) → void
12
+
13
+ async function main() {
14
+ await sensor.init(); // Check ID, read coefficients, apply defaults, () → void
15
+ while (true) {
16
+ const m = await sensor.read(); // Measure temperature and pressure, () → {temperature_c: number °C, pressure_pa: number Pa}
17
+ console.log('%s Pa, %s C', m.pressure_pa.toFixed(2), m.temperature_c.toFixed(2));
18
+ await sleep(1000);
19
+ }
20
+ }
21
+
22
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { PN532Full } = require('../../../src/chips/rfid/pn532');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x24', 16);
8
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
9
+
10
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR); // Create I²C connection, (bus=1, addr=0x24) → Connection
11
+ // The PN532 address is fixed; I0 low and I1 high select the I²C interface.
12
+ const reader = new PN532Full(connection); // Create PN532 driver, (connection) → void
13
+ // Constructor stores the connection only; no bus traffic yet.
14
+
15
+ async function main() {
16
+ await reader.init(); // Wake, check firmware, SAM normal mode, finite retries, () → void
17
+ // GetFirmwareVersion (IC 0x32), SAMConfiguration normal mode, MxRtyPassiveActivation = 2.
18
+
19
+ console.log(await reader.firmwareVersion()); // GetFirmwareVersion, () → {ic, version, revision, support, iso14443a, iso14443b, iso18092}
20
+ // IC 0x32, firmware 1.6 on current parts; the support bits list the protocols.
21
+ console.log(await reader.generalStatus()); // GetGeneralStatus, () → {error, field, targets, samStatus}
22
+ // Last error code, external field detected, active targets, SAM status.
23
+ console.log(await reader.selfTest()); // Diagnose, (test=0x00) → boolean
24
+ // Communication line test: the chip echoes an 8-byte pattern.
25
+ console.log(await reader.selfTest(0x01)); // Diagnose, (test=0x01) → boolean
26
+ // ROM checksum test.
27
+
28
+ console.log('UID', await reader.readUid()); // Detect a type A card, (timeout=1.0 s) → Buffer | null
29
+ // InListPassiveTarget at 106 kbps type A, then InRelease.
30
+
31
+ const targets = await reader.listPassiveTargets({ baud: PN532Full.BAUD_106_A, maxTargets: 1 }); // InListPassiveTarget, ({baud=BAUD_106_A, maxTargets=1, initiatorData=[], timeout=1.0 s}) → Target[]
32
+ // Keeps the target active; target.tg is the logical number for the next commands.
33
+ if (targets.length) {
34
+ const t = targets[0];
35
+ console.log(t);
36
+ await reader.deselect(t.tg); // InDeselect, (target=0) → void
37
+ // Puts the card to sleep but keeps its information in the PN532.
38
+ await reader.select(t.tg); // InSelect, (target=0) → void
39
+ // Wakes and reselects the deselected card.
40
+ if (t.uid.length === 7) {
41
+ console.log(await reader.ntagReadPage(t.tg, 4)); // NTAG READ, (target, page) → Buffer (16)
42
+ // Returns pages 4..7 (16 bytes).
43
+ await reader.ntagWritePage(t.tg, 4, [1, 2, 3, 4]); // NTAG WRITE, (target, page, data 4 bytes) → void
44
+ // Writes one 4-byte user page.
45
+ } else {
46
+ await reader.mifareAuthenticate(t.tg, 4, Buffer.alloc(6, 0xFF), t.uid); // MIFARE auth, (target, block, key 6 bytes, uid, keyB=false) → void
47
+ // Key A authentication of sector 1 with the transport key.
48
+ const data = await reader.mifareReadBlock(t.tg, 4); // MIFARE READ, (target, block) → Buffer (16)
49
+ // Reads block 4.
50
+ await reader.mifareWriteBlock(t.tg, 4, data); // MIFARE WRITE, (target, block, data 16 bytes) → void
51
+ // Writes the same 16 bytes back.
52
+ }
53
+ console.log(await reader.dataExchange(t.tg, [0x30, 0x00])); // InDataExchange, (target, data) → Buffer
54
+ // Raw READ of block/page 0 with PN532 framing and CRC.
55
+ await reader.release(t.tg); // InRelease, (target=0) → void
56
+ // Ends the session with the card.
57
+ }
58
+
59
+ await reader.setRfField(false); // RFConfiguration item 1, (on, autoRfca=false) → void
60
+ // RF field off; a card in the field loses power.
61
+ await reader.setRfField(true); // RFConfiguration item 1, (on, autoRfca=false) → void
62
+ // RF field back on.
63
+ await reader.setMaxRetries({ passiveActivation: 2 }); // RFConfiguration item 5, ({passiveActivation=2, atr=0xFF, psl=1}) → void
64
+ // 0xFF would retry forever.
65
+ const txMode = await reader.readRegister(0x6302); // ReadRegister, (address) → number
66
+ // 0x6302 is CIU_TxMode in the PN532's SFR space.
67
+ await reader.writeRegister(0x6302, txMode); // WriteRegister, (address, value) → void
68
+ // Writes the value back unchanged.
69
+ console.log(await reader.sendCommand(0x02)); // Raw command, (command, data=[], timeout=1.0 s) → Buffer
70
+ // GetFirmwareVersion through the raw frame interface.
71
+ try {
72
+ console.log(await reader.communicateThru([0x26])); // InCommunicateThru, (data) → Buffer
73
+ // Raw RF exchange with the current target; fails without one.
74
+ } catch (e) {
75
+ console.log('communicateThru:', e.message);
76
+ }
77
+
78
+ await reader.startCommand(0x02); // Command without waiting, (command, data=[]) → void
79
+ // Writes the frame and reads the ACK only.
80
+ console.log(await reader.waitReady(1.0)); // Wait for a frame, (timeout s) → boolean
81
+ // Polls the status byte every 1 ms.
82
+ console.log(await reader.pollInterrupt()); // Frame ready?, () → boolean
83
+ // A single status-byte read.
84
+ console.log(await reader.readResponse(0x02)); // Read the pending response, (command, timeout=1.0 s) → Buffer
85
+ // Header, NACK, full frame, checksums.
86
+
87
+ await reader.onInterrupt(() => console.log('frame ready')); // Subscribe to IRQ, (callback, intPin=null) → void
88
+ // Falling edge on IRQ, or a 10 ms status-byte poll without an IRQ pin.
89
+ await reader.sendCommand(0x02); // Raw command, (command, data=[], timeout=1.0 s) → Buffer
90
+ await sleep(100);
91
+ await reader.offInterrupt(); // Unsubscribe, () → void
92
+ // Stops the edge handler or the polling timer.
93
+
94
+ await reader.powerDown(); // PowerDown, (wakeupSources=0x20) → void
95
+ // Sleeps until the next I²C access; the driver retries the wake-up write.
96
+ connection.close();
97
+ }
98
+
99
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,121 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { PN532Full } = require('../../../src/chips/rfid/pn532');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x24', 16);
8
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
9
+ const hex = (b) => Buffer.from(b).toString('hex').toUpperCase();
10
+
11
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR); // Create I²C connection, (bus=1, addr=0x24) → Connection
12
+ const reader = new PN532Full(connection); // Create PN532 driver, (connection) → void
13
+
14
+ async function main() {
15
+ await reader.init(); // Wake, check firmware, SAM normal mode, finite retries, () → void
16
+
17
+ // --- Identity and health ---
18
+ // IC 0x32 is the PN532; the support byte lists ISO 14443 A/B and ISO 18092.
19
+ // The communication-line self test echoes a pattern through the firmware.
20
+ const fw = await reader.firmwareVersion(); // GetFirmwareVersion, () → object
21
+ console.log(`PN532 IC 0x${fw.ic.toString(16)} firmware ${fw.version}.${fw.revision} support 0x${fw.support.toString(16)}`);
22
+ console.log('status', await reader.generalStatus()); // GetGeneralStatus, () → object
23
+ console.log('self test', await reader.selfTest()); // Diagnose, (test=0x00) → boolean
24
+
25
+ // --- Card polling: 15 s at 1 Hz ---
26
+ // Present a card or tag. The finite retry count makes every poll return
27
+ // after a few milliseconds when the field is empty.
28
+ for (let i = 0; i < 15; i++) {
29
+ const targets = await reader.listPassiveTargets(); // InListPassiveTarget, ({baud=BAUD_106_A, maxTargets=1, ...}) → Target[]
30
+ if (targets.length) {
31
+ const t = targets[0];
32
+ console.log(`${i} s UID ${hex(t.uid)} SENS_RES 0x${t.sensRes.toString(16)} SEL_RES 0x${t.selRes.toString(16)}`);
33
+ await reader.release(t.tg); // InRelease, (target=0) → void
34
+ } else {
35
+ console.log(`${i} s no card`);
36
+ }
37
+ await sleep(1000);
38
+ }
39
+
40
+ // --- Tag access ---
41
+ // SEL_RES 0x00 is an NTAG / MIFARE Ultralight: read page 4 and write it back.
42
+ // SEL_RES 0x08 is a MIFARE Classic 1K: authenticate sector 1 with the transport
43
+ // key FF FF FF FF FF FF, read block 4 and write it back. Writing sector
44
+ // trailers can lock a sector forever.
45
+ const targets = await reader.listPassiveTargets(); // InListPassiveTarget, ({baud=BAUD_106_A, ...}) → Target[]
46
+ if (targets.length) {
47
+ const t = targets[0];
48
+ await reader.deselect(t.tg); // InDeselect, (target=0) → void
49
+ await reader.select(t.tg); // InSelect, (target=0) → void
50
+ try {
51
+ if (t.selRes === 0x00) {
52
+ const page = await reader.ntagReadPage(t.tg, 4); // NTAG READ, (target, page) → Buffer (16)
53
+ console.log('pages 4..7', hex(page));
54
+ await reader.ntagWritePage(t.tg, 4, page.subarray(0, 4)); // NTAG WRITE, (target, page, data 4 bytes) → void
55
+ console.log('raw read', hex(await reader.dataExchange(t.tg, [0x30, 0x00]))); // InDataExchange, (target, data) → Buffer
56
+ } else if (t.selRes & 0x08) {
57
+ await reader.mifareAuthenticate(t.tg, 4, Buffer.alloc(6, 0xFF), t.uid); // MIFARE auth, (target, block, key, uid, keyB=false) → void
58
+ const block = await reader.mifareReadBlock(t.tg, 4); // MIFARE READ, (target, block) → Buffer (16)
59
+ console.log('block 4', hex(block));
60
+ await reader.mifareWriteBlock(t.tg, 4, block); // MIFARE WRITE, (target, block, data 16 bytes) → void
61
+ }
62
+ } catch (e) {
63
+ console.log('tag access failed:', e.message);
64
+ }
65
+ await reader.release(t.tg); // InRelease, (target=0) → void
66
+ } else {
67
+ console.log('no card for the tag access part');
68
+ }
69
+
70
+ // --- Raw RF and raw commands ---
71
+ // InCommunicateThru sends bytes without PN532 protocol handling; with no
72
+ // target selected it reports an error. sendCommand reaches every command.
73
+ try {
74
+ console.log('thru', hex(await reader.communicateThru([0x30, 0x00]))); // InCommunicateThru, (data) → Buffer
75
+ } catch (e) {
76
+ console.log('communicateThru:', e.message);
77
+ }
78
+ console.log('raw GetFirmwareVersion', hex(await reader.sendCommand(0x02))); // Raw command, (command, data=[], timeout=1.0 s) → Buffer
79
+ const txMode = await reader.readRegister(0x6302); // ReadRegister, (address) → number
80
+ console.log(`CIU_TxMode 0x${txMode.toString(16)}`);
81
+ await reader.writeRegister(0x6302, txMode); // WriteRegister, (address, value) → void
82
+
83
+ // --- Wake on card with onInterrupt ---
84
+ // Infinite activation retries make InListPassiveTarget wait for a card;
85
+ // IRQ (or the status-byte poll) wakes the callback when the response is ready.
86
+ await reader.setMaxRetries({ passiveActivation: 0xFF }); // RFConfiguration item 5, ({passiveActivation=2, atr=0xFF, psl=1}) → void
87
+ let ready = false;
88
+ await reader.onInterrupt(() => { ready = true; }); // Subscribe to IRQ, (callback, intPin=null) → void
89
+ await reader.startCommand(0x4A, [0x01, 0x00]); // Command without waiting, (command, data=[]) → void
90
+ console.log('waiting 10 s for a card ...');
91
+ for (let i = 0; i < 100 && !ready; i++) {
92
+ if (await reader.pollInterrupt()) break; // Frame ready?, () → boolean
93
+ await sleep(100);
94
+ }
95
+ await reader.offInterrupt(); // Unsubscribe, () → void
96
+ if (await reader.waitReady(0.01)) { // Wait for a frame, (timeout s) → boolean
97
+ const resp = await reader.readResponse(0x4A); // Read the pending response, (command, timeout=1.0 s) → Buffer
98
+ console.log('card arrived, UID', hex(resp.subarray(6, 6 + resp[5])));
99
+ await reader.release(); // InRelease, (target=0) → void
100
+ } else {
101
+ try {
102
+ await reader.readResponse(0x4A, 0); // Read the pending response, (command, timeout=1.0 s) → Buffer
103
+ } catch (e) {
104
+ /* timed out: the command was aborted with an ACK frame */
105
+ }
106
+ console.log('no card arrived');
107
+ }
108
+ await reader.setMaxRetries(); // RFConfiguration item 5, ({passiveActivation=2, atr=0xFF, psl=1}) → void
109
+ console.log('readUid', await reader.readUid()); // Detect a type A card, (timeout=1.0 s) → Buffer | null
110
+
111
+ // --- RF field off and on, then power down ---
112
+ // With the field off a card loses power; the reader draws less current.
113
+ await reader.setRfField(false); // RFConfiguration item 1, (on, autoRfca=false) → void
114
+ await sleep(1000);
115
+ await reader.setRfField(true); // RFConfiguration item 1, (on, autoRfca=false) → void
116
+ await reader.powerDown(); // PowerDown, (wakeupSources=0x20) → void
117
+ console.log('powered down; the next I²C access wakes the chip');
118
+ connection.close();
119
+ }
120
+
121
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { PN532Minimal } = require('../../../src/chips/rfid/pn532');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x24', 16);
8
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
9
+
10
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR); // Create I²C connection, (bus=1, addr=0x24) → Connection
11
+ const reader = new PN532Minimal(connection); // Create PN532 driver, (connection) → void
12
+
13
+ async function main() {
14
+ await reader.init(); // Wake, check firmware, SAM normal mode, finite retries, () → void
15
+ while (true) {
16
+ const uid = await reader.readUid(); // Detect a type A card, (timeout=1.0 s) → Buffer | null
17
+ console.log('UID', uid ? uid.toString('hex').toUpperCase() : null);
18
+ await sleep(1000);
19
+ }
20
+ }
21
+
22
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,94 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { ST25DVFull, ST25DVSource } = require('../../../src/chips/rfid/st25dv');
5
+
6
+ async function main() {
7
+ const user = new I2CConnection(1, 0x53, null, null, 2); // Create user-area connection, (bus=1, addr=0x53, intPin=null, enPin=null, regBytes=2) → Connection
8
+ const system = new I2CConnection(1, 0x57, null, null, 2); // Create system-area connection, (bus=1, addr=0x57, intPin=null, enPin=null, regBytes=2) → Connection
9
+ const tag = new ST25DVFull(user, system); // Create ST25DV driver, (user, system, gpoActiveHigh=false) → void
10
+ await tag.init(); // Read MEM_SIZE, BLK_SIZE, IC_REF, () → void
11
+ // derives the user memory size from the system area
12
+
13
+ console.log('Size:', tag.memorySize(), 'bytes'); // Get user memory size, () → number bytes
14
+ // (MEM_SIZE + 1) × (BLK_SIZE + 1)
15
+ console.log('IC_REF: 0x' + tag.icReference().toString(16)); // Get IC reference, () → number
16
+ // 0x24 = ST25DV04K, 0x26 = ST25DV16K/64K
17
+ console.log('UID:', (await tag.uid()).toString('hex')); // Read unique ID, () → Buffer (8)
18
+ // most significant byte first, starts with E0 02
19
+ console.log('IC_REV:', await tag.icRevision()); // Read IC revision, () → number
20
+ // IC_REV register 0x0020
21
+
22
+ await tag.write(0x0100, Buffer.from(Array.from({ length: 40 }, (_, i) => i))); // Write user memory, (address, data) → void
23
+ // split into 16-byte-aligned writes, ACK-polled each
24
+ console.log('Data:', (await tag.read(0x0100, 40)).toString('hex')); // Read user memory, (address, length) → Buffer
25
+ // 16-byte-aligned reads, retried while an RF reader holds the bus
26
+ await tag.waitWriteComplete(); // Wait for the write cycle, () → void
27
+ // ACK polling on 0x53
28
+
29
+ console.log('IT_TIME:', (await tag.readSystem(0x0001, 1))[0]); // Read system area, (address, length) → Buffer
30
+ // raw access to the static registers at 0x57
31
+ console.log('Session:', await tag.sessionOpen()); // Query I²C security session, () → boolean
32
+ // I2C_SSO_Dyn bit 0
33
+ console.log('Password OK:', await tag.presentPassword(Buffer.alloc(8))); // Present I²C password, (password 8 bytes) → boolean
34
+ // opens the session needed for system-area writes
35
+ await tag.writePassword(Buffer.alloc(8)); // Change I²C password, (password 8 bytes) → void
36
+ // here rewritten with the factory value
37
+ await tag.writeSystem(0x0001, 0x03); // Write system area, (address, data) → void
38
+ // IT_TIME back to its reset value, ACK-polled
39
+
40
+ await tag.setAreaEnd(1, tag.memorySize() / 32 - 1); // Set end of area 1-3, (area 1–3, endBlock 0–255) → void
41
+ // area n ends at byte endBlock × 32 + 31
42
+ await tag.setAreaProtection(1, 0x00, 0x00); // Set area protection, (area 1–4, rf 0–15, i2c 0–3) → void
43
+ // RFAnSS value and the area's I2CSS bits
44
+ console.log('Area 1 protection:', await tag.getAreaProtection(1)); // Get area protection, (area 1–4) → {rf, i2c}
45
+
46
+ await tag.setGpo(ST25DVFull.GPO_FIELD_CHANGE); // Write static GPO register, (sources, enable=true) → void
47
+ // the chip copies it into GPO_CTRL_Dyn
48
+ console.log('GPO: 0x' + (await tag.getGpo()).toString(16)); // Read static GPO register, () → number
49
+ await tag.setGpoRuntime(true); // Switch GPO output at runtime, (enable) → void
50
+ // GPO_CTRL_Dyn.GPO_EN, no session needed
51
+ await tag.setInterruptPulse(3); // Set GPO pulse duration, (value 0–7) → void
52
+ // 301 µs − value × 37.65 µs
53
+
54
+ console.log('Field present:', await tag.fieldPresent()); // Query RF field, () → boolean
55
+ // EH_CTRL_Dyn.FIELD_ON
56
+ await tag.setEnergyHarvesting(false); // Control energy harvesting, (enabled, forced=false) → void
57
+ // EH_EN now, EH_MODE written only when it changes
58
+ await tag.setRfState(); // Set RF interface state, (disable=false, sleep=false) → void
59
+ // runtime RF_MNGT_Dyn
60
+
61
+ await tag.enableMailbox(); // Enable fast transfer mode, () → void
62
+ // sets MB_MODE if needed, then MB_CTRL_Dyn.MB_EN
63
+ await tag.setMailboxWatchdog(0); // Set mailbox watchdog, (value 0–7) → void
64
+ // 2^(value−1) × 30 ms, 0 disables it
65
+ await tag.mailboxWrite(Buffer.from('ping')); // Put mailbox message, (data 1–256 bytes) → void
66
+ // single write starting at 0x2008
67
+ console.log('Mailbox:', await tag.mailboxStatus()); // Decode mailbox status, () → object
68
+ // enabled, hostPut, rfPut, hostMiss, rfMiss, …
69
+ console.log('Message:', (await tag.mailboxRead()).toString()); // Read mailbox message, () → Buffer
70
+ // MB_LEN_Dyn + 1 bytes, empty if no message
71
+ await tag.disableMailbox(); // Disable fast transfer mode, () → void
72
+ // clears MB_EN, which also drops the message
73
+
74
+ await tag.writeNdef([0xD1, 0x01, 0x05, 0x54, 0x02, 0x65, 0x6E, 0x48, 0x69, 0x21]); // Write NDEF message, (message) → void
75
+ // capability container + TLV 03 <len> … FE
76
+ console.log('NDEF:', (await tag.readNdef()).toString('hex')); // Read NDEF message, () → Buffer
77
+ // parses the CC and the first NDEF TLV
78
+ await tag.lockCcfile(false); // Lock CC file blocks, (lock=true) → void
79
+ // false keeps blocks 0/1 RF-writable
80
+
81
+ await tag.enableInterrupt(ST25DVSource.FIELD_RISING | ST25DVSource.RF_WRITE); // Enable interrupt sources, (source) → void
82
+ // static GPO register bits plus GPO_EN
83
+ await tag.onInterrupt((s) => console.log('GPO event: 0x' + s.toString(16))); // Subscribe to GPO events, (callback, intPin=null) → void
84
+ // 10 ms IT_STS_Dyn polling without a GPO pin
85
+ console.log('Pending: 0x' + (await tag.pollInterrupt()).toString(16)); // Read and clear IT_STS_Dyn, () → number
86
+ // ST25DVSource mask, 0 = none
87
+ await tag.offInterrupt(); // Unsubscribe, () → void
88
+ await tag.disableInterrupt(ST25DVSource.RF_WRITE); // Disable interrupt sources, (source) → void
89
+ // clears the matching GPO enable bits
90
+ user.close();
91
+ system.close();
92
+ }
93
+
94
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,121 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { ST25DVFull, ST25DVSource } = require('../../../src/chips/rfid/st25dv');
5
+
6
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
7
+
8
+ async function main() {
9
+ // --- Two connections, one chip ---
10
+ // The ST25DV answers on 0x53 (user memory, dynamic registers, mailbox) and on
11
+ // 0x57 (system configuration). Both use 16-bit register addresses.
12
+ const user = new I2CConnection(1, 0x53, null, null, 2); // Create user-area connection, (bus=1, addr=0x53, intPin=null, enPin=null, regBytes=2) → Connection
13
+ const system = new I2CConnection(1, 0x57, null, null, 2); // Create system-area connection, (bus=1, addr=0x57, intPin=null, enPin=null, regBytes=2) → Connection
14
+ const tag = new ST25DVFull(user, system); // Create ST25DV driver, (user, system, gpoActiveHigh=false) → void
15
+ await tag.init(); // Read MEM_SIZE, BLK_SIZE, IC_REF, () → void
16
+
17
+ // --- Identify the tag ---
18
+ // IC_REF tells the 04K apart from the 16K/64K; the size comes from MEM_SIZE.
19
+ console.log('IC_REF 0x' + tag.icReference().toString(16), 'revision', await tag.icRevision()); // Get IC reference, () → number ; Read IC revision, () → number
20
+ console.log('UID', (await tag.uid()).toString('hex'), '-', tag.memorySize(), 'bytes'); // Read unique ID, () → Buffer (8) ; Get user memory size, () → number bytes
21
+
22
+ // --- NDEF text record a phone can read ---
23
+ // Record header D1 (MB/ME/SR, well-known), type 'T', status 02 (language "en").
24
+ const text = Buffer.from('Hello from Periph');
25
+ const record = Buffer.concat([Buffer.from([0xD1, 0x01, 3 + text.length, 0x54, 0x02]), Buffer.from('en'), text]);
26
+ await tag.writeNdef(record); // Write NDEF message, (message) → void
27
+ console.log('NDEF read back:', (await tag.readNdef()).equals(record)); // Read NDEF message, () → Buffer
28
+
29
+ // --- Raw bytes across a 256-byte page boundary ---
30
+ // The driver splits the write into 16-byte-aligned pieces and ACK-polls each.
31
+ const saved = await tag.read(0x00F8, 32); // Read user memory, (address, length) → Buffer
32
+ const pattern = Buffer.from(Array.from({ length: 32 }, (_, i) => 0x40 + i));
33
+ await tag.write(0x00F8, pattern); // Write user memory, (address, data) → void
34
+ await tag.waitWriteComplete(); // Wait for the write cycle, () → void
35
+ console.log('Page-crossing write ok:', (await tag.read(0x00F8, 32)).equals(pattern)); // Read user memory, (address, length) → Buffer
36
+ await tag.write(0x00F8, saved); // Write user memory, (address, data) → void
37
+
38
+ // --- Password session and two memory areas ---
39
+ // Area 1 = first 1 KiB (stays open), area 2 = the rest: RF writes need RF
40
+ // password 1, I2C writes need the I2C session. The factory I2C password is 0.
41
+ const pwd = Buffer.alloc(8);
42
+ console.log('Session before:', await tag.sessionOpen()); // Query I²C security session, () → boolean
43
+ console.log('Password accepted:', await tag.presentPassword(pwd)); // Present I²C password, (password 8 bytes) → boolean
44
+ const end1 = Math.min(tag.memorySize(), 1024) / 32 - 1;
45
+ const last = tag.memorySize() / 32 - 1;
46
+ await tag.setAreaEnd(1, end1); // Set end of area 1-3, (area 1–3, endBlock 0–255) → void
47
+ await tag.setAreaEnd(2, last); // Set end of area 1-3, (area 1–3, endBlock 0–255) → void
48
+ await tag.setAreaEnd(3, last); // Set end of area 1-3, (area 1–3, endBlock 0–255) → void
49
+ await tag.setAreaProtection(2, 0x05, 0x01); // Set area protection, (area 1–4, rf 0–15, i2c 0–3) → void
50
+ console.log('Area 2 protection:', await tag.getAreaProtection(2)); // Get area protection, (area 1–4) → {rf, i2c}
51
+
52
+ // --- Change and restore the I2C password ---
53
+ const newPwd = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0]);
54
+ await tag.writePassword(newPwd); // Change I²C password, (password 8 bytes) → void
55
+ console.log('New password accepted:', await tag.presentPassword(newPwd)); // Present I²C password, (password 8 bytes) → boolean
56
+ await tag.writePassword(pwd); // Change I²C password, (password 8 bytes) → void
57
+ console.log('Factory password restored:', await tag.presentPassword(pwd)); // Present I²C password, (password 8 bytes) → boolean
58
+
59
+ // --- GPO events while a phone approaches ---
60
+ // Field change and RF write events pulse GPO; without a GPO pin the driver
61
+ // polls IT_STS_Dyn every 10 ms. Hold a phone to the antenna now.
62
+ await tag.setInterruptPulse(3); // Set GPO pulse duration, (value 0–7) → void
63
+ await tag.setGpo(ST25DVFull.GPO_FIELD_CHANGE); // Write static GPO register, (sources, enable=true) → void
64
+ await tag.enableInterrupt(ST25DVSource.FIELD_RISING | ST25DVSource.RF_WRITE); // Enable interrupt sources, (source) → void
65
+ console.log('GPO register: 0x' + (await tag.getGpo()).toString(16)); // Read static GPO register, () → number
66
+ console.log('Pending before: 0x' + (await tag.pollInterrupt()).toString(16)); // Read and clear IT_STS_Dyn, () → number
67
+ await tag.onInterrupt((status) => { // Subscribe to GPO events, (callback, intPin=null) → void
68
+ const names = [];
69
+ if (status & ST25DVSource.FIELD_RISING) names.push('field on');
70
+ if (status & ST25DVSource.FIELD_FALLING) names.push('field off');
71
+ if (status & ST25DVSource.RF_WRITE) names.push('RF write');
72
+ console.log(' GPO event:', names.join(', ') || '0x' + status.toString(16));
73
+ });
74
+ for (let i = 0; i < 10; i++) {
75
+ console.log(' field present:', await tag.fieldPresent()); // Query RF field, () → boolean
76
+ await sleep(1000);
77
+ }
78
+ await tag.offInterrupt(); // Unsubscribe, () → void
79
+ await tag.disableInterrupt(ST25DVSource.RF_WRITE); // Disable interrupt sources, (source) → void
80
+
81
+ // --- Fast transfer mode: host <-> phone mailbox ---
82
+ // The host puts a message; an RF reader (e.g. the ST25 app) reads it and can
83
+ // answer. The watchdog releases an unread message after 2^(7-1) x 30 ms.
84
+ await tag.enableMailbox(); // Enable fast transfer mode, () → void
85
+ await tag.setMailboxWatchdog(7); // Set mailbox watchdog, (value 0–7) → void
86
+ await tag.mailboxWrite(Buffer.from('hello reader')); // Put mailbox message, (data 1–256 bytes) → void
87
+ for (let i = 0; i < 10; i++) {
88
+ const st = await tag.mailboxStatus(); // Decode mailbox status, () → object
89
+ if (st.rfPut) {
90
+ console.log('Reader says:', (await tag.mailboxRead()).toString()); // Read mailbox message, () → Buffer
91
+ break;
92
+ }
93
+ console.log(' mailbox:', st);
94
+ await sleep(1000);
95
+ }
96
+ await tag.disableMailbox(); // Disable fast transfer mode, () → void
97
+
98
+ // --- Energy harvesting and RF state ---
99
+ await tag.setEnergyHarvesting(true); // Control energy harvesting, (enabled, forced=false) → void
100
+ await sleep(1000);
101
+ await tag.setEnergyHarvesting(false); // Control energy harvesting, (enabled, forced=false) → void
102
+ await tag.setRfState(false, true); // Set RF interface state, (disable=false, sleep=false) → void
103
+ console.log('RF asleep: a phone no longer sees the tag');
104
+ await sleep(2000);
105
+ await tag.setRfState(); // Set RF interface state, (disable=false, sleep=false) → void
106
+
107
+ // --- Restore the delivery defaults ---
108
+ // One area, no protection, field-change GPO only, mailbox off, CC unlocked.
109
+ await tag.setAreaProtection(2, 0x00, 0x00); // Set area protection, (area 1–4, rf 0–15, i2c 0–3) → void
110
+ await tag.setAreaEnd(1, last); // Set end of area 1-3, (area 1–3, endBlock 0–255) → void
111
+ await tag.setGpo(ST25DVFull.GPO_FIELD_CHANGE); // Write static GPO register, (sources, enable=true) → void
112
+ await tag.setGpoRuntime(true); // Switch GPO output at runtime, (enable) → void
113
+ await tag.writeSystem(0x000D, 0x00); // Write system area, (address, data) → void
114
+ console.log('MB_MODE:', (await tag.readSystem(0x000D, 1))[0]); // Read system area, (address, length) → Buffer
115
+ await tag.lockCcfile(false); // Lock CC file blocks, (lock=true) → void
116
+ console.log('Done.');
117
+ user.close();
118
+ system.close();
119
+ }
120
+
121
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { ST25DVMinimal } = require('../../../src/chips/rfid/st25dv');
5
+
6
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
7
+
8
+ async function main() {
9
+ const user = new I2CConnection(1, 0x53, null, null, 2); // Create user-area connection, (bus=1, addr=0x53, intPin=null, enPin=null, regBytes=2) → Connection
10
+ const system = new I2CConnection(1, 0x57, null, null, 2); // Create system-area connection, (bus=1, addr=0x57, intPin=null, enPin=null, regBytes=2) → Connection
11
+ const tag = new ST25DVMinimal(user, system); // Create ST25DV driver, (user, system, gpoActiveHigh=false) → void
12
+ await tag.init(); // Read MEM_SIZE, BLK_SIZE, IC_REF, () → void
13
+
14
+ await tag.write(0x0100, Buffer.from('Hello NFC')); // Write user memory, (address, data) → void
15
+ for (;;) {
16
+ console.log('Memory:', (await tag.read(0x0100, 9)).toString()); // Read user memory, (address, length) → Buffer
17
+ await sleep(1000);
18
+ }
19
+ }
20
+
21
+ main().catch(err => { console.error(err); process.exit(1); });