This repository has been archived by the owner on Mar 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
button.js
86 lines (71 loc) · 2.02 KB
/
button.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict';
var fs = require('fs'),
events = require('events'),
util = require('util'),
_ = require('lodash'),
fsu = require('./fsutil'),
pullTypes = require('./pulltypes'),
mux = require('./mux'),
Dto = require('./dto'),
dto = new Dto(__dirname + '/../templates/gpio-keys.dts');
var DEFAULT_OPTIONS = {
debounceInterval: 50,
pullType: pullTypes.PULL_UP,
isActiveLow: true
};
Object.freeze(DEFAULT_OPTIONS);
function waitForButton(button) {
fsu.waitForFile('/dev/input/by-path/platform-' + button.name + '.*-event', function (err, device) {
if (err) {
return button.emit('error', err);
}
fs.createReadStream(device).on('data', function (buf) {
if (buf[12] === 1) {
button.emit('pressed');
} else {
button.emit('released');
}
}.bind(button));
button.emit('ready');
});
}
function Button(pin, options) {
var badPin,
config,
muxValue;
if (!(this instanceof Button)) {
return new Button(pin, options);
}
if (pin.gpioNo === undefined) {
badPin = new Error(pin.name + ' doesn\'t support buttons');
setImmediate(function () {
this.emit('error', badPin);
}.bind(this));
return;
}
options = options ? _.defaults(options, DEFAULT_OPTIONS) : DEFAULT_OPTIONS;
muxValue = mux.muxValue(options.pullType, 1);
this.pin = pin;
this.name = 'bot_btn_' + pin.name;
config = {
debounceInterval: options.debounceInterval,
header: pin.name.toUpperCase().replace('_', '.'),
gpioBank: Math.floor(pin.gpioNo / 32),
gpioBankPlusOne: Math.floor(pin.gpioNo / 32) + 1,
gpioOffset: pin.gpioNo % 32,
isActiveLow: options.isActiveLow ? 1 : 0,
label: this.name,
muxOffset: '0x' + pin.muxOffset.toString(16),
muxValue: '0x' + muxValue.toString(16),
name: this.name,
partNumber: this.name
};
dto.install(config, function (err) {
if (err) {
return this.emit('error', err);
}
waitForButton(this);
}.bind(this));
}
util.inherits(Button, events.EventEmitter);
module.exports = Button;