import DeadJim from 'death' import { Gpio } from 'onoff' import to from 'await-to-js' import logger from '@uci-utils/logger' let log = logger({package:'@uci/gpio', file:'/src/gpio.js'}) class Pin extends Gpio { constructor(pin, opts = {}) { if (typeof pin !=='number') pin = parseInt(pin) // make sure pin is a number! // TODO check against a set of known acceptable pin numbers based on SBC log.debug({pin:pin, msg:'construtor - creating gpio pin'}) if (isNaN(pin)) throw new Error('not a valid gpio pin number') super(pin,opts.direction || 'out',opts) this.id = (opts.id || 'gpio') + ':' + pin log.debug({ pin: pin, opts: opts, method:'constructor', line:15, msg:'created gpio with these opts'}) this.number = pin this.direction = opts.direction || 'out' this.value = opts.init || 0 } // end constructor async init() { await this.set(this.value) DeadJim((signal,err) => { log.warn({signal:signal, method:'init', line:56, error:err, msg:'gpio process was killed, unexporting pin'}) this.unexport() // kill the kernel entry }) } async on() { return await this.set(1) } async off() { return await this.set(0) } async toggle() { return await this.set(!this.value) } async set(value) { log.debug({msg:'set a pin', value:value, number:this.number}) // this.write(parseInt(value) || 0).then(res => console.log('returning from write')) let [err] = await to(this.write(parseInt(value) || 0)) if (err) { log.warn({error:err, pin:this.number, msg:'error reading gpio pin'}) throw err } let curValue = await this.read() if (value !== curValue) throw new Error(`pin ${this.number} was not set correctly: ${value}:${curValue}`) return curValue } async read() { let [err, res] = await to(super.read()) // super.read here just calls this.read making an infinite loop and blowing the stack, should call onoff's read if (err) { log.warn({error:err, pin:this.pin, msg:'error reading gpio pin'}) return err } this.value=res this.state = res ? 'on' : 'off' return this.value } async get() { return this.value } } // end Class export default Pin //example hook // async function defaultHook(packet) { // return a promise or use await if anything async happens in hook // new Promise((resolve) => { // console.log('==========default hook =============') // return packet // resolve(packet) // }) // }