uci-i2c-device/src/device-packet.mjs

56 lines
2.3 KiB
JavaScript

import Base from '@uci/base'
// import Base from '../../uci-base/src/base'
import commands from './bus-device-commands'
// import logger from '../../uci-logger/src/logger'
import logger from '@uci/logger'
let log = {}
const LOG_OPTS = (id) => {
return {
repo:'uci-i2c-device',
npm:'@uci/i2c-device',
file:'src/device-packet.mjs',
class:'Device',
id:id,
instance_created:new Date().getTime()
}}
export default class Device extends Base {
constructor(opts) {
if (!opts.bus) opts.bus ={}
opts.bus.name = opts.bus.name || 'bus' //optional bus socket name
// either device process instance runs on same host (use named pipe) or not (the host of bus must be given)
if (opts[opts.bus.name].host) opts[opts.bus.name].port = opts[opts.bus.name].port || 1776
else opts[opts.bus.name].path = opts[opts.bus.name].path || (process.env.SOCKETS_DIR || __dirname) + '/i2c-bus.sock'
opts.sockets = (opts.sockets ? (opts.sockets+',') : '') + opts.bus.name + '#c>' + ((opts[opts.bus.name].path) ? 'n' :'t')
super(opts)
console.log({opts:opts},'created i2c device with these options')
log = logger.child(LOG_OPTS(this.id))
if (!opts.address) log.fatal({opts:opts},'no i2c bus address supplied' )
this.address = opts.address
this._bus_name = opts.bus.name
this._channel = opts.channel // if using TAC9546A channel number on which device is attached
this.bus = this.bindFuncs(commands)
}
async init(){
await super.init()
let res = await this.bus.ack()
let socket = this.socket[this._bus_name].opts
let connection = socket.path || socket.host + ':' + socket.port
if (!res.ack) throw `no device operational on bus '${socket.id}' (${connection}) at address ${this.address}=0x${this.address.toString(16)}`
return res
}
async _setChannel() {
// TODO convert to package - uci-mux
// console.log('before set',this.address,this.id,this._channel, await this.socket.bus.send(getState)
// if (this._channel) {
// if (!await this.socket.bus.send(address) { return Promise.reject('Channel set but no mux on bus')}
// return await this.socket.bus.send(set(this._channel)
// }
return Promise.resolve() // no channel for device either no mux or device is attached to mux bypass
}
} // end of MCP230XX Class