'use strict' // Creates an ES6 Interrupt class wrapper using the pigio C library and pigpio javascript wrapper package // The pigipio C library is specifically coded for the Raspberry Pi but might be adapatable to any single board computer (sbc) with Gpios // assuming they would be pigio C, compatiable. // Must have pigpio C library installed first. // On interrupt emits "fired" which can be caught by the code calling this interrupt instance for handling // Understand there are two interrupts here. One is this class and one on the sbc/rpi via pigpio // The sbc/pigpio interrupt emits an event which is listened for by this class which then emits // a "fired" event which can be can be listed to by having a handle to an instance this class. const pigpio = require('pigpio'), sbcGpio = pigpio.Gpio, EventEmitter = require('events') class Interrupt extends EventEmitter { constructor(pin_number, handler, opts = {}) { super() this.pin_number = pin_number this.handler = handler this.mode = sbcGpio.INPUT this.pull = opts.pull ? opts.pull : sbcGpio.PUD_DOWN this.edge = opts.edge ? opts.edge : sbcGpio.RISING_EDGE this.sbc_interrupt = new sbcGpio( this.pin_number, { mode: this.mode, pullUpDown: this.pull, // do not! 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)) }) 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(`the sbc interrupt tripped by sbc pin ${interrupt.pin_number}`) interrupt.emit('fired') // emit an event that can be listened for by the device that created the interrupt instance }) // rock n roll!!, start the pigpio interrupt this.sbc_interrupt.enableInterrupt(this.edge) } // manual firing for testing fire() { let interrupt = this console.log('manually firing interrupt', this.handler) this.emit('fired') } exit() { pigpio.terminate() return Promise.reject(`keyboard termination...terminating interrupt on pin ${this.pin_number}`) } } module.exports = Interrupt