uci-interrupt/lib/interrupt.js

77 lines
2.1 KiB
JavaScript

"use strict";
const
pigpio = require('pigpio'),
Gpio = pigpio.Gpio,
EventEmitter = require('events')
//,_ = require('uci-utils')
//const debounce = require('debounce');
class Interrupt extends EventEmitter {
constructor(pin_number, handler, opts = {}) {
super()
this.pin_number = pin_number
this.handler = handler
this.mode = Gpio.INPUT
this.pull = opts.pull ? opts.pull : Gpio.PUD_DOWN
this.edge = opts.edge ? opts.edge : Gpio.RISING_EDGE
this.sbc_interrupt = new Gpio(
this.pin_number, {
mode: this.mode,
pullUpDown: this.pull,
// edge: this.edge // don't set edge here as it will start the emitter -- see pigio js
}
)
}
init() {
// console.log(`initialize interrupt ${this.pin_number}`)
return Promise.resolve()
}
get pin() {
return this.pin_number
}
async start() {
console.log(`starting interrupt on pin ${ this.pin_number}`)
// for cntrl-c exit of interrupt
process.on('SIGINT', () => {
this.exit().then((resp) => console.log("\n", resp)) // unexport on cntrl-c
.catch(err => console.log("error:", err))
})
// There are two interrupts here. One on the I2c mcp board and one on the sbc/rpi
// The mcp interrupt trips the sbc interrupt which emits an event to run handler attached to the mcp class interrupt
let interrupt = this // scope `this` for use in the listener for each interrupt
console.log(`interrupt listener set for rpi ${interrupt.pin_number}`)
this.sbc_interrupt.on('interrupt', function () {
console.log(`rpi interrupt tripped by rpi pin ${interrupt.pin_number}`)
interrupt.emit('fired')
})
// rock n roll!!, turn on the pigpio interrupt
this.sbc_interrupt.enableInterrupt(this.edge)
// return Promise.resolve("interrupt on pin listener")
}
// manual firing for testing
fire(name = 'fired') {
console.log('firing interrupt handler', this.handler)
this.emit(name, this.handler)
}
exit() {
pigpio.terminate()
return Promise.reject(`keyboard termination...terminating interrupt on pin ${this.pin_number}`)
}
}
module.exports = {
Interrupt
}