77 lines
2.2 KiB
JavaScript
77 lines
2.2 KiB
JavaScript
|
|
import i2c from 'i2c-bus'
|
|
import pify from 'pify'
|
|
// import Base from '@uci/base'
|
|
import Base from '../../uci-base/src/base'
|
|
|
|
export default class Bus extends Base {
|
|
constructor(opts) {
|
|
opts.sockets = opts.sockets || 'us'
|
|
super(opts)
|
|
this.busnum = opts.busnum || 1
|
|
this.i2cbus = i2c.open(this.busnum, () => {})
|
|
this.funcs = bus_funcs
|
|
// this.init = this.init.bind(this)
|
|
}
|
|
|
|
async init(){
|
|
// console.log('init', this.rw)
|
|
await super.init()
|
|
}
|
|
|
|
async rw (packet){
|
|
// console.dir('=>',packet.bus.fusncs)
|
|
if (!packet.bus.func) return {error: 'no i2c bus function in packet', packet: packet.bus }
|
|
if (this.funcs[packet.bus.func]) {
|
|
packet.bus.response = await this.funcs[packet.bus.func].bind(this)(packet.bus.args)
|
|
packet.cmd = 'reply'
|
|
return packet
|
|
}
|
|
return {error: 'no i2c bus function available for packet function', packet: packet.bus }
|
|
}
|
|
|
|
} // end of Bus Packet Class
|
|
|
|
const bus_funcs = {
|
|
|
|
scan: function () { return pify(this.i2cbus.scan).bind(this.i2cbus)() },
|
|
close: function () { return pify(this.i2cbus.close).bind(this.i2cbus)() },
|
|
|
|
readRaw: function (arg) {
|
|
return pify(this.i2cbus.i2cRead).bind(this.i2cbus)(arg.address, arg.length, arg.buffer)
|
|
},
|
|
|
|
writeRaw: function (arg) {
|
|
return pify(this.i2cbus.i2cWrite).bind(this.i2cbus)(arg.address, arg.length, arg.buffer)
|
|
},
|
|
|
|
read: function (arg) {
|
|
// console.log('read: address, cmd', address, cmd)
|
|
return pify(this.i2cbus.readByte).bind(this.i2cbus)(arg.address, arg.cmd)
|
|
},
|
|
|
|
write: function (arg) {
|
|
// console.log('write: address, cmd, byte', arg.address, arg.cmd, arg.byte)
|
|
return pify(this.i2cbus.writeByte.bind(this.i2cbus))(arg.address, arg.cmd, arg.byte)
|
|
},
|
|
|
|
read2: function (arg) {
|
|
return pify(this.i2cbus.readWord.bind(this.i2cbus))(arg.address, arg.cmd)
|
|
},
|
|
|
|
write2: function (arg) {
|
|
return pify(this.i2cbus.writeWord.bind(this.i2cbus))(arg.address, arg.cmd, arg.bytes)
|
|
},
|
|
|
|
receive: function (arg) {
|
|
// console.log('receivebyte', address)
|
|
return pify(this.i2cbus.receiveByte.bind(this.i2cbus))(arg.address)
|
|
},
|
|
|
|
send: function (arg) {
|
|
// console.log('sendbyte', address,byte)
|
|
return pify(this.i2cbus.sendByte.bind(this.i2cbus))(arg.address, arg.byte)
|
|
}
|
|
|
|
}
|