"use strict"; const fs = require('mz/fs'), EventEmitter = require('events'), Epoll = require('epoll').Epoll, pSeries = require('p-series') const GPIO_ROOT_PATH = '/sys/class/gpio/' class Interrupt extends EventEmitter { // bus is i2c-bus bus object constructor(pin_number, opts = {}) { super() this.num = pin_number; this.hook = opts.hook // will be passed back with the emit this.path = GPIO_ROOT_PATH + 'gpio' + this.num + '/' this.edge = opts.edge ? opts.edge : 'falling' this.debounce = opts.debounce ? opts.debounce : 200 this.poller = new Epoll(function (err, fd, events) { if (err) { this.emit('error', err) } this.clear() this.emit('fired', this.hook) }.bind(this)) } init() { let tasks = [ fs.writeFile(GPIO_ROOT_PATH + 'export', this.num) // fs.writeFile(this.path + 'direction', 'in'), // fs.writeFile(this.path + 'edge', this.edge), // fs.open(this.path + 'value', 'r+').then(fd => { this.valuefd = fd }), // this.clear().then(() => { this.start() }) ] return this.exit() .then(() => { return pSeries(tasks) }) // .then(() => { return this.exit() }) } fire(name = 'fired') { this.emit(name, this.hook) } clear() { let buffer = Buffer.from([0x00]) return fs.read(this.valuefd, buffer, 0, 1, 0); } exit() { return fs.access(this.path) .then(() => { console.log('unexporting') return fs.writeFile(GPIO_ROOT_PATH + 'unexport', this.num) }) .then(() => { if (this.valuefd) { this.stop() return fs.close(this.valuefd) } }) .catch(err => { return Promise.resolve('already exited') }) } start() { this.poller.add(this.valuefd, Epoll.EPOLLPRI); } stop() { this.poller.remove(this.valuefd).close(); } } module.exports = { Interrupt }