Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 60 additions & 5 deletions lib/i2c.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
const wire = require('../build/Release/i2c');
const { EventEmitter } = require('events');
const util = require('util');

const tick = setImmediate || process.nextTick;

//
// Add promisify to the wire object so we can use async/await
//
for (const key in wire) {
if (typeof wire[key] === 'function') {
wire[`${key}Async`] = util.promisify(wire[key]);
}
}

class i2c extends EventEmitter {

constructor(address, options) {
Expand Down Expand Up @@ -31,11 +42,10 @@ class i2c extends EventEmitter {
console.log(`Error: ${err}`);
});

this.open(this.options.device, (err) => {
if (!err) {
this.setAddress(this.address);
}
});
(async () => {
await this.openAsync(this.options.device);
this.setAddress(this.address);
})().catch((err) => this.emit('error', err));
}

scan(callback) {
Expand Down Expand Up @@ -141,6 +151,51 @@ class i2c extends EventEmitter {
}
});
}

async scanAsync() {
const data = await wire.scanAsync();
return data.filter((num) => num >= 0);
}

async openAsync(device) {
return wire.openAsync(device);
}

async writeAsync(buf) {
this.setAddress(this.address);
if (!Buffer.isBuffer(buf)) {
buf = Buffer.from(buf);
}
return wire.writeAsync(buf);
}

async writeByteAsync(byte) {
this.setAddress(this.address);
return wire.writeByteAsync(byte);
}

async writeBytesAsync(cmd, buf) {
this.setAddress(this.address);
if (!Buffer.isBuffer(buf)) {
buf = Buffer.from(buf);
}
return wire.writeBlockAsync(cmd, buf);
}

async readAsync(len) {
this.setAddress(this.address);
return wire.readAsync(len);
}

async readByteAsync() {
this.setAddress(this.address);
return wire.readByteAsync();
}

async readBytesAsync(cmd, len) {
this.setAddress(this.address);
return wire.readBlockAsync(cmd, len, null);
}
}

module.exports = i2c;