uci-i2c-bus/examples/bus.js

88 lines
2.1 KiB
JavaScript

import { readFile as read } from 'fs-read-data'
import onDeath from 'ondeath'
import Bus from '../src/bus.js'
let options = {}
;
(async () => {
options = await read('./examples/bus.yaml')
options.id = options.id ||'i2c-bus'
// console.log('----------------switches start options--------\n',options,'\n---------------------------------')
// console.log('----------------switches interrupt options--------\n',options.interrupt,'\n---------------------------------')
let i2cbus = new Bus(options)
if ((process.env.UCI_ENV ||'').includes('dev')) {
i2cbus.on('log',ev => {
switch (ev.level) {
// case 'warning':
// case 'error':
// case 'testing':
case 'ready':
case 'state':
case 'i2c':
case 'fatal':
// case 'info':
console.log(ev.level.toUpperCase(),'\n',ev)
break
}
})
process.once('SIGUSR2', async () => {
shutdown.call(i2cbus)
process.kill(process.pid, 'SIGUSR2')
})
} // dev
onDeath( async () => {
console.log('\nThe I2C Bus, \nHe\'s dead Jim')
shutdown.call(i2cbus)
console.log('shutdown done')
process.exit()
})
console.log('before init')
await i2cbus.init()
console.log('after init',i2cbus.ready.observers,i2cbus.ready.state)
i2cbus.ready.all.subscribe(
(ready) => {
if (!ready) {
console.log(options.name, 'YIKES! some observer is not reporting ready')
let failed = i2cbus.ready.state.filter(obs=> obs[1]===false).map(obs=>[obs[0],i2cbus.ready.getObserverDetails(obs)])
console.log('those that have failed\n',failed)
} else {
console.log(options.name, ': This I2C BUS is ONLINE!!!!')
console.log(i2cbus.ready.state)
}
})
})().catch(err => {
console.log('FATAL: UNABLE TO START IC2BUS - KILLING FOR OS RESTART !\n',err, options)
process.exitCode = 1
process.kill(process.pid, 'SIGINT')
})
async function shutdown (){
let names = Object.keys(this.getSocket())
console.log(names)
for (let name of names) {
console.log(name)
console.log(await this.removeSocket(name))
console.log('after remove', name)
}
this.removeAllListeners()
}