uci-interrupt/lib/interrupt.js

92 lines
2.5 KiB
JavaScript

"use strict";
const fs = require('mz/fs'),
EventEmitter = require('events'),
Epoll = require('epoll').Epoll,
_ = require('uci-utils')
const pWaitFor = require('p-wait-for')
const pathExists = require('path-exists');
const debounce = require('debounce');
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.delay = opts.delay ? opts.delay : 50
this.dbt = opts.debounce ? opts.debounce : 300
this.poller = new Epoll(
debounce((err, fd, events) => {
if (err) { this.emit('error', err) } else { this.clear().then(this.emit('fired', this.hook)) }
}, this.dbt, true)
)
}
init() {
let tasks = [
() => { return fs.writeFile(GPIO_ROOT_PATH + 'export', this.num).then(() => { console.log('exported') }) },
() => {
return pWaitFor(() => pathExists(this.path + 'direction')).then(_.pDelay(this.delay))
.then(() => { return fs.writeFile(this.path + 'direction', 'in').then(() => { console.log('direction set') }) })
},
() => { return fs.writeFile(this.path + 'edge', this.edge).then(() => { console.log('edge') }) },
() => { return fs.open(this.path + 'value', 'r+').then(fd => { this.valuefd = fd }) },
() => { return this.clear().then(() => { return this.start() }) }
]
process.on('SIGINT', () => {
this.exit().then(() => console.log('\nunexported and closed')) // unexport on cntrl-c
})
return this.exit() // make sure pin is unexported
.then((resp) => {
console.log(resp)
return _.pSeries(tasks)
})
}
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 pathExists(this.path)
.then(() => {
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 unexported') })
}
start() {
this.poller.add(this.valuefd, Epoll.EPOLLPRI);
}
stop() {
this.poller.remove(this.valuefd).close();
}
}
module.exports = {
Interrupt
}