/
onoff.js
290 lines (241 loc) · 8.27 KB
/
onoff.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"use strict";
const fs = require('fs');
const debounce = require('lodash.debounce');
const Epoll = require('epoll').Epoll;
const GPIO_ROOT_PATH = '/sys/class/gpio/';
// fs reads and writes use Buffers
const HIGH_BUF = Buffer.from('1');
const LOW_BUF = Buffer.from('0');
// lib returns numeric data and expects numeric data as arguments
const HIGH = 1;
const LOW = 0;
const waitForAccessPermission = (paths) => {
paths.forEach((path) => {
let tries = 0;
while (true) {
try {
tries += 1;
const fd = fs.openSync(path, 'r+');
fs.closeSync(fd);
break;
} catch (e) {
if (tries === 10000) {
throw e;
}
}
}
});
};
class Gpio {
constructor(gpio, direction, edge, options) {
if (typeof edge === 'object' && !options) {
options = edge;
edge = undefined;
}
options = options || {};
this._gpio = gpio;
this._gpioPath = GPIO_ROOT_PATH + 'gpio' + this._gpio + '/';
this._debounceTimeout = options.debounceTimeout || 0;
this._readBuffer = Buffer.alloc(16);
this._listeners = [];
if (!fs.existsSync(this._gpioPath)) {
// The GPIO hasn't been exported yet so export it
fs.writeFileSync(GPIO_ROOT_PATH + 'export', this._gpio);
// Avoid the access permission issue described here:
// https://github.com/raspberrypi/linux/issues/553
// On some syetems udev rules are used to set access permissions on the
// GPIO sysfs files enabling those files to be accessed without root
// privileges. This takes a while so wait for it to happen.
let permissionRequiredPaths = [
this._gpioPath + 'direction',
this._gpioPath + 'active_low',
this._gpioPath + 'value',
];
// On some systems the edge file will not exist if the GPIO does not
// support interrupts
// https://github.com/fivdi/onoff/issues/77#issuecomment-321980735
if (edge && direction === 'in') {
permissionRequiredPaths.push(this._gpioPath + 'edge');
}
waitForAccessPermission(permissionRequiredPaths);
if (typeof options.activeLow === 'boolean') {
fs.writeFileSync(
this._gpioPath + 'active_low',
options.activeLow ? HIGH_BUF : LOW_BUF
);
}
fs.writeFileSync(this._gpioPath + 'direction', direction);
// On some systems writing to the edge file for an output GPIO will
// result in an "EIO, i/o error"
// https://github.com/fivdi/onoff/issues/87
if (edge && direction === 'in') {
fs.writeFileSync(this._gpioPath + 'edge', edge);
}
} else {
// The GPIO has already been exported, perhaps by onoff itself, perhaps
// by quick2wire gpio-admin on the Pi, perhaps by the WiringPi gpio
// utility on the Pi, or perhaps by something else. In any case, an
// attempt is made to set the direction and edge to the requested
// values here. If quick2wire gpio-admin was used for the export, the
// user should have access to both direction and edge files. This is
// important as gpio-admin sets niether direction nor edge. If the
// WiringPi gpio utility was used, the user should have access to edge
// file, but not the direction file. This is also ok as the WiringPi
// gpio utility can set both direction and edge. If there are any
// errors while attempting to perform the modifications, just keep on
// truckin'.
try {
if (typeof options.activeLow === 'boolean') {
fs.writeFileSync(
this._gpioPath + 'active_low',
options.activeLow ? HIGH_BUF : LOW_BUF
);
}
} catch (ignore) {
}
try {
const reconfigureDirection =
typeof options.reconfigureDirection === 'boolean' ? options.reconfigureDirection : true;
if (reconfigureDirection || this.direction() !== direction) {
fs.writeFileSync(this._gpioPath + 'direction', direction);
}
} catch (ignore) {
}
try {
// On some systems writing to the edge file for an output GPIO will
// result in an "EIO, i/o error"
// https://github.com/fivdi/onoff/issues/87
if (edge && direction === 'in') {
fs.writeFileSync(this._gpioPath + 'edge', edge);
}
} catch (ignore) {
}
}
// Cache fd for performance
this._valueFd = fs.openSync(this._gpioPath + 'value', 'r+');
{
// A poller is created for both inputs and outputs. A poller isn't
// actully needed for an output but the setDirection method can be
// invoked to change the direction of a GPIO from output to input and
// then a poller may be needed.
const pollerEventHandler = (err, fd, events) => {
const value = this.readSync();
if ((value === LOW && this._fallingEnabled) ||
(value === HIGH && this._risingEnabled)) {
this._listeners.slice(0).forEach((callback) => {
callback(err, value);
});
}
};
this._risingEnabled = edge === 'both' || edge === 'rising';
this._fallingEnabled = edge === 'both' || edge === 'falling';
// Read GPIO value before polling to prevent an initial unauthentic
// interrupt
this.readSync();
if (this._debounceTimeout > 0) {
const db = debounce(pollerEventHandler, this._debounceTimeout);
this._poller = new Epoll((err, fd, events) => {
this.readSync(); // Clear interrupt
db(err, fd, events);
});
} else {
this._poller = new Epoll(pollerEventHandler);
}
}
}
read(callback) {
fs.read(this._valueFd, this._readBuffer, 0, 1, 0, (err, bytes, buf) => {
if (typeof callback === 'function') {
if (err) {
return callback(err);
}
callback(null, buf[0] === HIGH_BUF[0] ? HIGH : LOW);
}
});
}
readSync() {
fs.readSync(this._valueFd, this._readBuffer, 0, 1, 0);
return this._readBuffer[0] === HIGH_BUF[0] ? HIGH : LOW;
}
write(value, callback) {
const writeBuffer = value === HIGH ? HIGH_BUF : LOW_BUF;
fs.write(this._valueFd, writeBuffer, 0, writeBuffer.length, 0, callback);
}
writeSync(value) {
const writeBuffer = value === HIGH ? HIGH_BUF : LOW_BUF;
fs.writeSync(this._valueFd, writeBuffer, 0, writeBuffer.length, 0);
}
watch(callback) {
this._listeners.push(callback);
if (this._listeners.length === 1) {
this._poller.add(this._valueFd, Epoll.EPOLLPRI);
}
}
unwatch(callback) {
if (this._listeners.length > 0) {
if (typeof callback !== 'function') {
this._listeners = [];
} else {
this._listeners = this._listeners.filter((listener) => {
return callback !== listener;
});
}
if (this._listeners.length === 0) {
this._poller.remove(this._valueFd);
}
}
}
unwatchAll() {
this.unwatch();
}
direction() {
return fs.readFileSync(this._gpioPath + 'direction').toString().trim();
}
setDirection(direction) {
fs.writeFileSync(this._gpioPath + 'direction', direction);
}
edge() {
return fs.readFileSync(this._gpioPath + 'edge').toString().trim();
}
setEdge(edge) {
fs.writeFileSync(this._gpioPath + 'edge', edge);
this._risingEnabled = edge === 'both' || edge === 'rising';
this._fallingEnabled = edge === 'both' || edge === 'falling';
}
activeLow() {
return fs.readFileSync(
this._gpioPath + 'active_low')[0] === HIGH_BUF[0] ? true : false;
}
setActiveLow(invert) {
fs.writeFileSync(this._gpioPath + 'active_low', !!invert ? HIGH_BUF : LOW_BUF);
}
unexport() {
this.unwatchAll();
fs.closeSync(this._valueFd);
try {
fs.writeFileSync(GPIO_ROOT_PATH + 'unexport', this._gpio);
} catch (ignore) {
// Flow of control always arrives here when cape_universal is enabled on
// the bbb.
}
}
static get accessible() {
let fd;
try {
fd = fs.openSync(GPIO_ROOT_PATH + 'export', 'w');
} catch(e) {
// e.code === 'ENOENT' / 'EACCES' are most common
// though any failure to open will also result in a gpio
// failure to export.
return false;
} finally {
if (fd) {
fs.closeSync(fd);
}
}
return true;
}
}
Gpio.HIGH = HIGH;
Gpio.LOW = LOW;
exports.Gpio = Gpio;