-
Notifications
You must be signed in to change notification settings - Fork 124
/
onoff.js
347 lines (288 loc) · 8.9 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
'use strict';
const fs = require('fs');
const debounce = require('lodash.debounce');
const Epoll = require('epoll').Epoll;
const GPIO_ROOT_PATH = '/sys/class/gpio/';
const HIGH_BUF = Buffer.from('1');
const LOW_BUF = Buffer.from('0');
const HIGH = 1;
const LOW = 0;
const exportGpio = gpio => {
if (!fs.existsSync(gpio._gpioPath)) {
// The GPIO hasn't been exported yet so export it
fs.writeFileSync(GPIO_ROOT_PATH + 'export', '' + gpio._gpio);
return false;
}
// 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'.
return true;
};
// 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 complete.
const waitForGpioAccessPermission = (
gpio, direction, edge, gpioPreviouslyExported
) => {
let permissionRequiredPaths = [
gpio._gpioPath + 'value',
];
if (gpioPreviouslyExported === false) {
permissionRequiredPaths.push(gpio._gpioPath + 'direction');
permissionRequiredPaths.push(gpio._gpioPath + 'active_low');
// 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(gpio._gpioPath + 'edge');
}
}
permissionRequiredPaths.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;
}
}
}
});
};
const configureGpio = (
gpio, direction, edge, options, gpioPreviouslyExported
) => {
const throwIfNeeded = err => {
if (gpioPreviouslyExported === false) {
throw err;
}
};
try {
if (typeof options.activeLow === 'boolean') {
gpio.setActiveLow(options.activeLow);
}
} catch (err) {
throwIfNeeded(err);
}
try {
const reconfigureDirection =
typeof options.reconfigureDirection === 'boolean' ?
options.reconfigureDirection : true;
const requestedDirection =
direction === 'high' || direction === 'low' ? 'out' : direction;
if (reconfigureDirection || gpio.direction() !== requestedDirection) {
gpio.setDirection(direction);
}
} catch (err) {
throwIfNeeded(err);
}
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') {
gpio.setEdge(edge);
}
} catch (err) {
throwIfNeeded(err);
}
};
const configureInterruptHandler = gpio => {
// A poller is created for both inputs and outputs. A poller isn't
// actually 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 = gpio.readSync();
if ((value === LOW && gpio._fallingEnabled) ||
(value === HIGH && gpio._risingEnabled)) {
gpio._listeners.slice(0).forEach(callback => {
callback(err, value);
});
}
};
// Read GPIO value before polling to prevent an initial unauthentic
// interrupt
gpio.readSync();
if (gpio._debounceTimeout > 0) {
const db = debounce(pollerEventHandler, gpio._debounceTimeout);
gpio._poller = new Epoll((err, fd, events) => {
gpio.readSync(); // Clear interrupt
db(err, fd, events);
});
} else {
gpio._poller = new Epoll(pollerEventHandler);
}
};
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._readSyncBuffer = Buffer.alloc(16);
this._listeners = [];
const gpioPreviouslyExported = exportGpio(this);
waitForGpioAccessPermission(
this, direction, edge, gpioPreviouslyExported
);
configureGpio(this, direction, edge, options, gpioPreviouslyExported);
this._valueFd = fs.openSync(this._gpioPath + 'value', 'r+');
configureInterruptHandler(this);
}
read(callback) {
const readValue = callback => {
fs.read(this._valueFd, this._readBuffer, 0, 1, 0, (err, bytes, buf) => {
if (typeof callback === 'function') {
if (err) {
return callback(err);
}
callback(null, convertBufferToBit(buf));
}
});
};
if (callback) {
readValue(callback);
} else {
return new Promise((resolve, reject) => {
readValue((err, value) => {
if (err) {
reject(err);
} else {
resolve(value);
}
});
});
}
}
readSync() {
fs.readSync(this._valueFd, this._readSyncBuffer, 0, 1, 0);
return convertBufferToBit(this._readSyncBuffer);
}
write(value, callback) {
const writeValue = (value, callback) => {
const writeBuffer = convertBitToBuffer(value);
fs.write(
this._valueFd, writeBuffer, 0, writeBuffer.length, 0, callback
);
};
if (callback) {
writeValue(value, callback);
} else {
return new Promise((resolve, reject) => {
writeValue(value, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
}
writeSync(value) {
const writeBuffer = convertBitToBuffer(value);
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 convertBufferToBoolean(
fs.readFileSync(this._gpioPath + 'active_low')
);
}
setActiveLow(invert) {
fs.writeFileSync(
this._gpioPath + 'active_low', convertBooleanToBuffer(!!invert)
);
}
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', fs.constants.O_WRONLY);
} 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;
}
}
const convertBitToBuffer = bit => convertBooleanToBuffer(bit === HIGH);
const convertBufferToBit =
buffer => convertBufferToBoolean(buffer) ? HIGH : LOW;
const convertBooleanToBuffer = boolean => boolean ? HIGH_BUF : LOW_BUF;
const convertBufferToBoolean = buffer => buffer[0] === HIGH_BUF[0];
Gpio.HIGH = HIGH;
Gpio.LOW = LOW;
module.exports.Gpio = Gpio;