periph 1.5.4 → 1.6.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.
- package/README.md +6 -0
- package/examples/gas/ccs811/complete.js +87 -0
- package/examples/gas/ccs811/demo.js +108 -0
- package/examples/gas/ccs811/minimal.js +20 -0
- package/examples/gas/rrh46410/complete.js +78 -0
- package/examples/gas/rrh46410/demo.js +86 -0
- package/examples/gas/rrh46410/minimal.js +21 -0
- package/examples/light/si1133/complete.js +89 -0
- package/examples/light/si1133/demo.js +93 -0
- package/examples/light/si1133/minimal.js +22 -0
- package/examples/light/si1145/complete.js +93 -0
- package/examples/light/si1145/demo.js +98 -0
- package/examples/light/si1145/minimal.js +22 -0
- package/examples/pressure/spl06/complete.js +81 -0
- package/examples/pressure/spl06/demo.js +106 -0
- package/examples/pressure/spl06/minimal.js +22 -0
- package/examples/rfid/pn532/complete.js +99 -0
- package/examples/rfid/pn532/demo.js +121 -0
- package/examples/rfid/pn532/minimal.js +22 -0
- package/package.json +1 -1
- package/src/chips/gas/ccs811.js +400 -0
- package/src/chips/gas/rrh46410.js +534 -0
- package/src/chips/light/si1133.js +583 -0
- package/src/chips/light/si1145.js +630 -0
- package/src/chips/pressure/spl06.js +461 -0
- package/src/chips/rfid/pn532.js +513 -0
- package/src/connection/i2c.js +46 -13
- package/src/connection/smbus.js +21 -8
- package/src/discovery/registry.js +6 -6
|
@@ -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); });
|
package/package.json
CHANGED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const _REG_STATUS = 0x00;
|
|
4
|
+
const _REG_MEAS_MODE = 0x01;
|
|
5
|
+
const _REG_ALG_RESULT_DATA = 0x02;
|
|
6
|
+
const _REG_RAW_DATA = 0x03;
|
|
7
|
+
const _REG_ENV_DATA = 0x05;
|
|
8
|
+
const _REG_NTC = 0x06;
|
|
9
|
+
const _REG_THRESHOLDS = 0x10;
|
|
10
|
+
const _REG_BASELINE = 0x11;
|
|
11
|
+
const _REG_HW_ID = 0x20;
|
|
12
|
+
const _REG_HW_VERSION = 0x21;
|
|
13
|
+
const _REG_FW_BOOT_VERSION = 0x23;
|
|
14
|
+
const _REG_FW_APP_VERSION = 0x24;
|
|
15
|
+
const _REG_ERROR_ID = 0xE0;
|
|
16
|
+
const _REG_APP_START = 0xF4;
|
|
17
|
+
const _REG_SW_RESET = 0xFF;
|
|
18
|
+
|
|
19
|
+
const _HW_ID = 0x81;
|
|
20
|
+
const _MODE_1 = 0x10;
|
|
21
|
+
const _INT_DATARDY = 0x08;
|
|
22
|
+
const _INT_THRESH = 0x04;
|
|
23
|
+
const _RESET_KEY = [0x11, 0xE5, 0x72, 0x8A];
|
|
24
|
+
// Sample interval in ms per drive mode (0 = idle)
|
|
25
|
+
const _INTERVAL_MS = [0, 1000, 10000, 60000, 250];
|
|
26
|
+
|
|
27
|
+
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* CCS811 indoor air quality gas sensor (ScioSense / ams) — minimal interface.
|
|
31
|
+
*
|
|
32
|
+
* One call returns the equivalent CO₂ (eCO₂) and total VOC (TVOC) values of the chip's internal
|
|
33
|
+
* algorithm. `init()` verifies HW_ID = 0x81, writes APP_START if the chip is still in boot mode
|
|
34
|
+
* and selects drive mode 1 (MEAS_MODE = 0x10: one sample per second, interrupts off). No
|
|
35
|
+
* environment data is written (the chip assumes 50 %RH, 25 °C).
|
|
36
|
+
*
|
|
37
|
+
* The chip stretches the I²C clock; tie nWAKE low. New sensors need a 48 h burn-in and values
|
|
38
|
+
* settle about 20 min after each power-up. I²C address 0x5A (ADDR low) or 0x5B (ADDR high).
|
|
39
|
+
* The constructor does not touch the bus.
|
|
40
|
+
*
|
|
41
|
+
* @param {import('../../connection/register_connection').RegisterConnection} connection - I²C register connection.
|
|
42
|
+
*/
|
|
43
|
+
class CCS811Minimal {
|
|
44
|
+
constructor(connection) {
|
|
45
|
+
this._conn = connection;
|
|
46
|
+
this._measMode = _MODE_1;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Verify the chip, start the application firmware and select drive mode 1.
|
|
51
|
+
* @returns {Promise<void>}
|
|
52
|
+
* @throws {Error} If HW_ID is not 0x81, no valid application is loaded, or the chip does not
|
|
53
|
+
* enter application mode.
|
|
54
|
+
*/
|
|
55
|
+
async init() {
|
|
56
|
+
const id = (await this._conn.readReg(_REG_HW_ID, 1))[0];
|
|
57
|
+
if (id !== _HW_ID) throw new Error(`Unexpected HW_ID 0x${id.toString(16)}, expected 0x81`);
|
|
58
|
+
await this._startApp();
|
|
59
|
+
this._measMode = _MODE_1;
|
|
60
|
+
await this._conn.writeReg(_REG_MEAS_MODE, [this._measMode]);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async _startApp() {
|
|
64
|
+
let status = (await this._conn.readReg(_REG_STATUS, 1))[0];
|
|
65
|
+
if (!(status & CCS811Minimal.STATUS_APP_VALID)) throw new Error('CCS811 has no valid application firmware');
|
|
66
|
+
if (status & CCS811Minimal.STATUS_FW_MODE) return;
|
|
67
|
+
await this._conn.writeReg(_REG_APP_START, []);
|
|
68
|
+
await _sleep(2);
|
|
69
|
+
status = (await this._conn.readReg(_REG_STATUS, 1))[0];
|
|
70
|
+
if (!(status & CCS811Minimal.STATUS_FW_MODE)) throw new Error('CCS811 did not enter application mode');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async _waitDataReady() {
|
|
74
|
+
const mode = (this._measMode >> 4) & 0x07;
|
|
75
|
+
const limit = Math.max(1500, (_INTERVAL_MS[mode] || 0) * 1.5);
|
|
76
|
+
const deadline = Date.now() + limit;
|
|
77
|
+
for (;;) {
|
|
78
|
+
const status = (await this._conn.readReg(_REG_STATUS, 1))[0];
|
|
79
|
+
if (status & CCS811Minimal.STATUS_DATA_READY) return;
|
|
80
|
+
if (Date.now() > deadline) throw new Error('CCS811 data ready timeout');
|
|
81
|
+
await _sleep(20);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async _readResult() {
|
|
86
|
+
const b = await this._conn.readReg(_REG_ALG_RESULT_DATA, 5);
|
|
87
|
+
if (b[4] & CCS811Minimal.STATUS_ERROR) {
|
|
88
|
+
const errorId = (await this._conn.readReg(_REG_ERROR_ID, 1))[0];
|
|
89
|
+
throw new Error(`CCS811 error, ERROR_ID 0x${errorId.toString(16).padStart(2, '0')}`);
|
|
90
|
+
}
|
|
91
|
+
return { eco2_ppm: (b[0] << 8) | b[1], tvoc_ppb: (b[2] << 8) | b[3] };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Wait for the next sample and return it.
|
|
96
|
+
* @returns {Promise<{eco2_ppm: number, tvoc_ppb: number}>} eCO₂ in ppm (400–8192) and TVOC in ppb (0–1187).
|
|
97
|
+
* @throws {Error} On timeout or when the chip reports an error (the message carries ERROR_ID).
|
|
98
|
+
*/
|
|
99
|
+
async read() {
|
|
100
|
+
await this._waitDataReady();
|
|
101
|
+
return this._readResult();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** STATUS.FW_MODE: application mode. */
|
|
106
|
+
CCS811Minimal.STATUS_FW_MODE = 0x80;
|
|
107
|
+
/** STATUS.APP_VALID: valid application firmware loaded. */
|
|
108
|
+
CCS811Minimal.STATUS_APP_VALID = 0x10;
|
|
109
|
+
/** STATUS.DATA_READY: new sample in ALG_RESULT_DATA. */
|
|
110
|
+
CCS811Minimal.STATUS_DATA_READY = 0x08;
|
|
111
|
+
/** STATUS.ERROR: see ERROR_ID. */
|
|
112
|
+
CCS811Minimal.STATUS_ERROR = 0x01;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* CCS811 full interface — extends CCS811Minimal with drive modes, raw sensor data, environment
|
|
116
|
+
* compensation, the NTC input, thresholds, baseline save/restore, versions, soft reset and the
|
|
117
|
+
* nINT interrupt (active low, open-drain, released when ALG_RESULT_DATA is read).
|
|
118
|
+
*
|
|
119
|
+
* @param {import('../../connection/register_connection').RegisterConnection} connection - I²C register connection.
|
|
120
|
+
*/
|
|
121
|
+
class CCS811Full extends CCS811Minimal {
|
|
122
|
+
constructor(connection) {
|
|
123
|
+
super(connection);
|
|
124
|
+
this._callback = null;
|
|
125
|
+
this._intPinUsed = null;
|
|
126
|
+
this._pollTimer = null;
|
|
127
|
+
this._polling = false;
|
|
128
|
+
this._edgeHandler = () => { this._service(); };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
static _intBits(source) {
|
|
132
|
+
let bits = 0;
|
|
133
|
+
if (source & CCS811Full.SOURCE_DATA_READY) bits |= _INT_DATARDY;
|
|
134
|
+
if (source & CCS811Full.SOURCE_THRESHOLD) bits |= _INT_DATARDY | _INT_THRESH;
|
|
135
|
+
return bits;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async _writeMeasMode() {
|
|
139
|
+
await this._conn.writeReg(_REG_MEAS_MODE, [this._measMode]);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async _read16(reg) {
|
|
143
|
+
const b = await this._conn.readReg(reg, 2);
|
|
144
|
+
return (b[0] << 8) | b[1];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Wait for the next sample and return the equivalent CO₂.
|
|
149
|
+
* @returns {Promise<number>} eCO₂ in ppm.
|
|
150
|
+
*/
|
|
151
|
+
async readEco2() {
|
|
152
|
+
return (await this.read()).eco2_ppm;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Wait for the next sample and return the total VOC.
|
|
157
|
+
* @returns {Promise<number>} TVOC in ppb.
|
|
158
|
+
*/
|
|
159
|
+
async readTvoc() {
|
|
160
|
+
return (await this.read()).tvoc_ppb;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Read RAW_DATA.
|
|
165
|
+
* @returns {Promise<[number, number]>} [current_ua (0–63 µA), voltage_v (ADC × 1.65 / 1023)].
|
|
166
|
+
*/
|
|
167
|
+
async readRaw() {
|
|
168
|
+
const raw = await this._read16(_REG_RAW_DATA);
|
|
169
|
+
return [raw >> 10, (raw & 0x3FF) * 1.65 / 1023];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Whether a new sample is waiting (STATUS.DATA_READY).
|
|
174
|
+
* @returns {Promise<boolean>}
|
|
175
|
+
*/
|
|
176
|
+
async dataReady() {
|
|
177
|
+
return ((await this.status()) & CCS811Minimal.STATUS_DATA_READY) !== 0;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Select the drive mode, keeping the interrupt bits. 0 idle, 1 every second, 2 every 10 s,
|
|
182
|
+
* 3 every 60 s, 4 every 250 ms (raw data only). When moving to a slower mode, idle (mode 0)
|
|
183
|
+
* first; the first sample at the new rate may be stale.
|
|
184
|
+
* @param {number} mode - Drive mode 0–4.
|
|
185
|
+
* @returns {Promise<void>}
|
|
186
|
+
* @throws {RangeError} If mode is not 0–4.
|
|
187
|
+
*/
|
|
188
|
+
async setMode(mode) {
|
|
189
|
+
if (!Number.isInteger(mode) || mode < 0 || mode > 4) throw new RangeError('mode must be 0..4');
|
|
190
|
+
this._measMode = (this._measMode & 0x0C) | (mode << 4);
|
|
191
|
+
await this._writeMeasMode();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Write ambient humidity and temperature (ENV_DATA) for the compensation.
|
|
196
|
+
* @param {number} humidityRh - Relative humidity in % (0–100).
|
|
197
|
+
* @param {number} temperatureC - Temperature in °C (-25 to 102).
|
|
198
|
+
* @returns {Promise<void>}
|
|
199
|
+
* @throws {RangeError} If a value is out of range.
|
|
200
|
+
*/
|
|
201
|
+
async setEnvironment(humidityRh, temperatureC) {
|
|
202
|
+
if (!(humidityRh >= 0 && humidityRh <= 100)) throw new RangeError('humidityRh must be 0..100');
|
|
203
|
+
if (!(temperatureC >= -25 && temperatureC <= 102)) throw new RangeError('temperatureC must be -25..102');
|
|
204
|
+
const h = Math.round(humidityRh * 512);
|
|
205
|
+
const t = Math.round((temperatureC + 25) * 512);
|
|
206
|
+
await this._conn.writeReg(_REG_ENV_DATA, [h >> 8, h & 0xFF, t >> 8, t & 0xFF]);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Read the NTC circuit voltages.
|
|
211
|
+
* @returns {Promise<[number, number]>} [v_ref_mv, v_ntc_mv] in mV.
|
|
212
|
+
*/
|
|
213
|
+
async readNtc() {
|
|
214
|
+
const b = await this._conn.readReg(_REG_NTC, 4);
|
|
215
|
+
return [(b[0] << 8) | b[1], (b[2] << 8) | b[3]];
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* NTC resistance V_NTC × R_REF / V_REF.
|
|
220
|
+
* @param {number} rRefOhm - Reference resistor in ohms.
|
|
221
|
+
* @returns {Promise<number>} NTC resistance in ohms.
|
|
222
|
+
* @throws {Error} If V_REF reads 0 (no NTC circuit).
|
|
223
|
+
*/
|
|
224
|
+
async ntcResistance(rRefOhm) {
|
|
225
|
+
const [vRef, vNtc] = await this.readNtc();
|
|
226
|
+
if (vRef === 0) throw new Error('CCS811 NTC reference voltage is 0');
|
|
227
|
+
return vNtc * rRefOhm / vRef;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Set the eCO₂ boundaries for the threshold interrupt.
|
|
232
|
+
* @param {number} [lowMediumPpm=1500] - Low-to-medium boundary in ppm.
|
|
233
|
+
* @param {number} [mediumHighPpm=2500] - Medium-to-high boundary in ppm.
|
|
234
|
+
* @param {number} [hysteresisPpm=50] - Hysteresis in ppm (0–255).
|
|
235
|
+
* @returns {Promise<void>}
|
|
236
|
+
* @throws {RangeError} If a value is out of range or low ≥ high.
|
|
237
|
+
*/
|
|
238
|
+
async setThresholds(lowMediumPpm = 1500, mediumHighPpm = 2500, hysteresisPpm = 50) {
|
|
239
|
+
if (!(lowMediumPpm >= 0 && lowMediumPpm < mediumHighPpm && mediumHighPpm <= 0xFFFF)) {
|
|
240
|
+
throw new RangeError('thresholds must satisfy 0 <= lowMedium < mediumHigh <= 65535');
|
|
241
|
+
}
|
|
242
|
+
if (!(hysteresisPpm >= 0 && hysteresisPpm <= 0xFF)) throw new RangeError('hysteresisPpm must be 0..255');
|
|
243
|
+
await this._conn.writeReg(_REG_THRESHOLDS, [lowMediumPpm >> 8, lowMediumPpm & 0xFF,
|
|
244
|
+
mediumHighPpm >> 8, mediumHighPpm & 0xFF, hysteresisPpm]);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Read the encoded algorithm baseline (save it to non-volatile storage).
|
|
249
|
+
* @returns {Promise<number>} 16-bit baseline.
|
|
250
|
+
*/
|
|
251
|
+
async getBaseline() {
|
|
252
|
+
return this._read16(_REG_BASELINE);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Restore a saved baseline (only after about 20 min of operation).
|
|
257
|
+
* @param {number} baseline - Value from getBaseline().
|
|
258
|
+
* @returns {Promise<void>}
|
|
259
|
+
* @throws {RangeError} If baseline is not 0–65535.
|
|
260
|
+
*/
|
|
261
|
+
async setBaseline(baseline) {
|
|
262
|
+
if (!(Number.isInteger(baseline) && baseline >= 0 && baseline <= 0xFFFF)) {
|
|
263
|
+
throw new RangeError('baseline must be 0..65535');
|
|
264
|
+
}
|
|
265
|
+
await this._conn.writeReg(_REG_BASELINE, [baseline >> 8, baseline & 0xFF]);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Read STATUS.
|
|
270
|
+
* @returns {Promise<number>} STATUS byte (STATUS_* bits).
|
|
271
|
+
*/
|
|
272
|
+
async status() {
|
|
273
|
+
return (await this._conn.readReg(_REG_STATUS, 1))[0];
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Read ERROR_ID (bit 0 write-invalid … bit 5 heater supply).
|
|
278
|
+
* @returns {Promise<number>}
|
|
279
|
+
*/
|
|
280
|
+
async error() {
|
|
281
|
+
return (await this._conn.readReg(_REG_ERROR_ID, 1))[0];
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Read the hardware ID and version.
|
|
286
|
+
* @returns {Promise<[number, number]>} [hw_id (0x81), hw_version (0x1X)].
|
|
287
|
+
*/
|
|
288
|
+
async hardwareVersion() {
|
|
289
|
+
const id = (await this._conn.readReg(_REG_HW_ID, 1))[0];
|
|
290
|
+
const version = (await this._conn.readReg(_REG_HW_VERSION, 1))[0];
|
|
291
|
+
return [id, version];
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async _version(reg) {
|
|
295
|
+
const b = await this._conn.readReg(reg, 2);
|
|
296
|
+
return [b[0] >> 4, b[0] & 0x0F, b[1]];
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Read the bootloader and application firmware versions.
|
|
301
|
+
* @returns {Promise<{boot: number[], app: number[]}>} Each [major, minor, trivial].
|
|
302
|
+
*/
|
|
303
|
+
async firmwareVersion() {
|
|
304
|
+
return { boot: await this._version(_REG_FW_BOOT_VERSION), app: await this._version(_REG_FW_APP_VERSION) };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* SW_RESET into boot mode, then start the application and mode 1 again (init()). Drive mode,
|
|
309
|
+
* interrupt bits, thresholds and environment data return to their defaults.
|
|
310
|
+
* @returns {Promise<void>}
|
|
311
|
+
*/
|
|
312
|
+
async softReset() {
|
|
313
|
+
try {
|
|
314
|
+
await this._conn.writeReg(_REG_SW_RESET, _RESET_KEY);
|
|
315
|
+
} catch (e) {
|
|
316
|
+
/* the chip may not acknowledge while it resets */
|
|
317
|
+
}
|
|
318
|
+
await _sleep(20);
|
|
319
|
+
await this.init();
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Enable nINT for a source, keeping the drive mode.
|
|
324
|
+
* @param {number} source - SOURCE_DATA_READY and/or SOURCE_THRESHOLD (which also sets INT_DATARDY).
|
|
325
|
+
* @returns {Promise<void>}
|
|
326
|
+
*/
|
|
327
|
+
async enableInterrupt(source) {
|
|
328
|
+
this._measMode |= CCS811Full._intBits(source);
|
|
329
|
+
await this._writeMeasMode();
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Disable nINT for a source, keeping the drive mode.
|
|
334
|
+
* @param {number} source - SOURCE_DATA_READY and/or SOURCE_THRESHOLD.
|
|
335
|
+
* @returns {Promise<void>}
|
|
336
|
+
*/
|
|
337
|
+
async disableInterrupt(source) {
|
|
338
|
+
this._measMode &= ~CCS811Full._intBits(source) & 0xFF;
|
|
339
|
+
await this._writeMeasMode();
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Read STATUS. Does not release nINT (reading ALG_RESULT_DATA does).
|
|
344
|
+
* @returns {Promise<number>} STATUS byte; STATUS_DATA_READY marks a new sample.
|
|
345
|
+
*/
|
|
346
|
+
async pollInterrupt() {
|
|
347
|
+
return this.status();
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Subscribe to the interrupt. Uses `intPin` (or the connection's) on its falling edge, else a
|
|
352
|
+
* 20 ms poll of STATUS.DATA_READY. The callback receives the STATUS byte and should read the
|
|
353
|
+
* sample to release nINT.
|
|
354
|
+
* @param {function(number): void} callback - Called with STATUS when DATA_READY is set.
|
|
355
|
+
* @param {object} [intPin=null] - Optional InputPin wired to nINT.
|
|
356
|
+
* @returns {Promise<void>}
|
|
357
|
+
*/
|
|
358
|
+
async onInterrupt(callback, intPin = null) {
|
|
359
|
+
this._callback = callback;
|
|
360
|
+
const ipin = intPin ?? this._conn.intPin ?? null;
|
|
361
|
+
this._intPinUsed = ipin;
|
|
362
|
+
if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
|
|
363
|
+
if (ipin) {
|
|
364
|
+
await ipin.onEdge(this._edgeHandler, 'falling');
|
|
365
|
+
} else {
|
|
366
|
+
this._pollTimer = setInterval(() => { this._service(); }, 20);
|
|
367
|
+
if (this._pollTimer.unref) this._pollTimer.unref();
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Unsubscribe and stop delivery. */
|
|
372
|
+
async offInterrupt() {
|
|
373
|
+
if (this._intPinUsed) {
|
|
374
|
+
await this._intPinUsed.offEdge(this._edgeHandler);
|
|
375
|
+
this._intPinUsed = null;
|
|
376
|
+
}
|
|
377
|
+
if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
|
|
378
|
+
this._callback = null;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
async _service() {
|
|
382
|
+
if (this._polling) return;
|
|
383
|
+
this._polling = true;
|
|
384
|
+
try {
|
|
385
|
+
const status = await this.pollInterrupt();
|
|
386
|
+
if ((status & CCS811Minimal.STATUS_DATA_READY) && this._callback) this._callback(status);
|
|
387
|
+
} catch (e) {
|
|
388
|
+
/* a failed poll is retried on the next edge / tick */
|
|
389
|
+
} finally {
|
|
390
|
+
this._polling = false;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Interrupt source: new sample (MEAS_MODE.INT_DATARDY). */
|
|
396
|
+
CCS811Full.SOURCE_DATA_READY = 0x01;
|
|
397
|
+
/** Interrupt source: eCO₂ threshold crossing (INT_DATARDY + INT_THRESH). */
|
|
398
|
+
CCS811Full.SOURCE_THRESHOLD = 0x02;
|
|
399
|
+
|
|
400
|
+
module.exports = { CCS811Minimal, CCS811Full };
|