forked from JamesBarwell/rpi-gpio.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpi-gpio.js
599 lines (529 loc) · 16.1 KB
/
rpi-gpio.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
var fs = require('fs');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var retry = require('async-retry');
var debug = require('debug')('rpi-gpio');
var Epoll = require('epoll').Epoll;
var PATH = '/sys/class/gpio';
var PINS = {
v1: {
// 1: 3.3v
// 2: 5v
'3': 0,
// 4: 5v
'5': 1,
// 6: ground
'7': 4,
'8': 14,
// 9: ground
'10': 15,
'11': 17,
'12': 18,
'13': 21,
// 14: ground
'15': 22,
'16': 23,
// 17: 3.3v
'18': 24,
'19': 10,
// 20: ground
'21': 9,
'22': 25,
'23': 11,
'24': 8,
// 25: ground
'26': 7
},
v2: {
// 1: 3.3v
// 2: 5v
'3': 2,
// 4: 5v
'5': 3,
// 6: ground
'7': 4,
'8': 14,
// 9: ground
'10': 15,
'11': 17,
'12': 18,
'13': 27,
// 14: ground
'15': 22,
'16': 23,
// 17: 3.3v
'18': 24,
'19': 10,
// 20: ground
'21': 9,
'22': 25,
'23': 11,
'24': 8,
// 25: ground
'26': 7,
// Model B+ pins
// 27: ID_SD
// 28: ID_SC
'29': 5,
// 30: ground
'31': 6,
'32': 12,
'33': 13,
// 34: ground
'35': 19,
'36': 16,
'37': 26,
'38': 20,
// 39: ground
'40': 21
}
};
var RETRY_OPTS = {
retries: 100,
minTimeout: 10,
factor: 1
}
var DIR_IN = 'in';
var DIR_OUT = 'out';
var DIR_LOW = 'low';
var DIR_HIGH = 'high';
var MODE_RPI = 'mode_rpi';
var MODE_BCM = 'mode_bcm';
var EDGE_NONE = 'none';
var EDGE_RISING = 'rising';
var EDGE_FALLING = 'falling';
var EDGE_BOTH = 'both';
function Gpio() {
var currentPins;
var currentValidBcmPins;
var exportedInputPins = {};
var exportedOutputPins = {};
var getPinForCurrentMode = getPinRpi;
var pollers = {};
this.DIR_IN = DIR_IN;
this.DIR_OUT = DIR_OUT;
this.DIR_LOW = DIR_LOW;
this.DIR_HIGH = DIR_HIGH;
this.MODE_RPI = MODE_RPI;
this.MODE_BCM = MODE_BCM;
this.EDGE_NONE = EDGE_NONE;
this.EDGE_RISING = EDGE_RISING;
this.EDGE_FALLING = EDGE_FALLING;
this.EDGE_BOTH = EDGE_BOTH;
/**
* Set pin reference mode. Defaults to 'mode_rpi'.
*
* @param {string} mode Pin reference mode, 'mode_rpi' or 'mode_bcm'
*/
this.setMode = function(mode) {
if (mode === this.MODE_RPI) {
getPinForCurrentMode = getPinRpi;
} else if (mode === this.MODE_BCM) {
getPinForCurrentMode = getPinBcm;
} else {
throw new Error('Cannot set invalid mode');
}
};
/**
* Setup a channel for use as an input or output
*
* @param {number} channel Reference to the pin in the current mode's schema
* @param {string} direction The pin direction, either 'in' or 'out'
* @param edge edge Informs the GPIO chip if it needs to generate interrupts. Either 'none', 'rising', 'falling' or 'both'. Defaults to 'none'
* @param {function} onSetup Optional callback
*/
this.setup = function(channel, direction, edge, onSetup /*err*/) {
if (arguments.length === 2 && typeof direction == 'function') {
onSetup = direction;
direction = this.DIR_OUT;
edge = this.EDGE_NONE;
} else if (arguments.length === 3 && typeof edge == 'function') {
onSetup = edge;
edge = this.EDGE_NONE;
}
channel = parseInt(channel)
direction = direction || this.DIR_OUT;
edge = edge || this.EDGE_NONE;
onSetup = onSetup || function() {};
if (typeof channel !== 'number') {
return process.nextTick(function() {
onSetup(new Error('Channel must be a number'));
});
}
if (direction !== this.DIR_IN &&
direction !== this.DIR_OUT &&
direction !== this.DIR_LOW &&
direction !== this.DIR_HIGH
) {
return process.nextTick(function() {
onSetup(new Error('Cannot set invalid direction'));
});
}
if ([
this.EDGE_NONE,
this.EDGE_RISING,
this.EDGE_FALLING,
this.EDGE_BOTH
].indexOf(edge) == -1) {
return process.nextTick(function() {
onSetup(new Error('Cannot set invalid edge'));
});
}
var pinForSetup;
var onListen = function(readChannel) {
this.read(readChannel, function(err, value) {
if (err) {
debug(
'Error reading channel value after change, %d',
readChannel
);
return
}
debug(
'emitting change on channel %s with value %s',
readChannel,
value
);
this.emit('change', readChannel, value);
}.bind(this));
}.bind(this);
setRaspberryVersion()
.then(function() {
pinForSetup = getPinForCurrentMode(channel);
if (!pinForSetup) {
throw new Error(
'Channel ' + channel + ' does not map to a GPIO pin'
);
}
debug('set up pin %d', pinForSetup);
return isExported(pinForSetup)
})
.then(function(isExported) {
if (isExported) {
return unexportPin(pinForSetup);
}
})
.then(function() {
return exportPin(pinForSetup);
})
.then(function() {
return retry(function() {
return setEdge(pinForSetup, edge);
}, RETRY_OPTS);
})
.then(function() {
if (direction === DIR_IN) {
exportedInputPins[pinForSetup] = true;
} else {
exportedOutputPins[pinForSetup] = true;
}
return retry(function() {
return setDirection(pinForSetup, direction)
}, RETRY_OPTS);
})
.then(function() {
return retry(function() {
return listen(channel, onListen);
}, RETRY_OPTS);
})
.then(function() {
onSetup();
})
.catch(function(err) {
onSetup(err);
});
};
/**
* Write a value to a channel
*
* @param {number} channel The channel to write to
* @param {boolean} value If true, turns the channel on, else turns off
* @param {function} cb Optional callback
*/
this.write = this.output = function(channel, value, cb /*err*/) {
var pin = getPinForCurrentMode(channel);
cb = cb || function() {}
if (!exportedOutputPins[pin]) {
return process.nextTick(function() {
cb(new Error('Pin has not been exported for write'));
});
}
value = (!!value && value !== '0') ? '1' : '0';
debug('writing pin %d with value %s', pin, value);
fs.writeFile(PATH + '/gpio' + pin + '/value', value, cb);
};
/**
* Read a value from a channel
*
* @param {number} channel The channel to read from
* @param {function} cb Callback which receives the channel's boolean value
*/
this.read = this.input = function(channel, cb /*err,value*/) {
if (typeof cb !== 'function') {
throw new Error('A callback must be provided')
}
var pin = getPinForCurrentMode(channel);
if (!exportedInputPins[pin] && !exportedOutputPins[pin]) {
return process.nextTick(function() {
cb(new Error('Pin has not been exported'));
});
}
fs.readFile(PATH + '/gpio' + pin + '/value', 'utf-8', function(err, data) {
if (err) {
return cb(err)
}
data = (data + '').trim() || '0';
debug('read pin %s with value %s', pin, data);
return cb(null, data === '1');
});
};
/**
* Unexport any pins setup by this module
*
* @param {function} cb Optional callback
*/
this.destroy = function(cb) {
var tasks = Object.keys(exportedOutputPins)
.concat(Object.keys(exportedInputPins))
.map(function(pin) {
return new Promise(function(resolve, reject) {
removeListener(pin, pollers)
unexportPin(pin)
.then(resolve)
.catch(reject);
});
});
Promise.all(tasks)
.then(function() {
return cb();
})
.catch(function(err) {
return cb(err);
});
};
/**
* Reset the state of the module
*/
this.reset = function() {
exportedOutputPins = {};
exportedInputPins = {};
this.removeAllListeners();
currentPins = undefined;
currentValidBcmPins = undefined;
getPinForCurrentMode = getPinRpi;
pollers = {}
};
// Init
EventEmitter.call(this);
this.reset();
// Private functions requiring access to state
function setRaspberryVersion() {
if (currentPins) {
return Promise.resolve();
}
return new Promise(function(resolve, reject) {
fs.readFile('/proc/cpuinfo', 'utf8', function(err, data) {
if (err) {
return reject(err);
}
// Match the last 4 digits of the number following "Revision:"
var match = data.match(/Revision\s*:\s*[0-9a-f]*([0-9a-f]{4})/);
if (!match) {
var errorMessage = 'Unable to match Revision in /proc/cpuinfo: ' + data;
return reject(new Error(errorMessage));
}
var revisionNumber = parseInt(match[1], 16);
var pinVersion = (revisionNumber < 4) ? 'v1' : 'v2';
debug(
'seen hardware revision %d; using pin mode %s',
revisionNumber,
pinVersion
);
// Create a list of valid BCM pins for this Raspberry Pi version.
// This will be used to validate channel numbers in getPinBcm
currentValidBcmPins = []
Object.keys(PINS[pinVersion]).forEach(
function(pin) {
// Lookup the BCM pin for the RPI pin and add it to the list
currentValidBcmPins.push(PINS[pinVersion][pin]);
}
);
currentPins = PINS[pinVersion];
return resolve();
});
});
};
function getPinRpi(channel) {
return currentPins[channel] + '';
};
function getPinBcm(channel) {
channel = parseInt(channel, 10);
return currentValidBcmPins.indexOf(channel) !== -1 ? (channel + '') : null;
};
/**
* Listen for interrupts on a channel
*
* @param {number} channel The channel to watch
* @param {function} cb Callback which receives the channel's err
*/
function listen(channel, onChange) {
var pin = getPinForCurrentMode(channel);
if (!exportedInputPins[pin] && !exportedOutputPins[pin]) {
throw new Error('Channel %d has not been exported', channel);
}
debug('listen for pin %d', pin);
var poller = new Epoll(function(err, innerfd, events) {
if (err) throw err
clearInterrupt(innerfd);
onChange(channel);
});
var fd = fs.openSync(PATH + '/gpio' + pin + '/value', 'r+');
clearInterrupt(fd);
poller.add(fd, Epoll.EPOLLPRI);
// Append ready-to-use remove function
pollers[pin] = function() {
poller.remove(fd).close();
}
};
}
util.inherits(Gpio, EventEmitter);
function setEdge(pin, edge) {
debug('set edge %s on pin %d', edge.toUpperCase(), pin);
return new Promise(function(resolve, reject) {
fs.writeFile(PATH + '/gpio' + pin + '/edge', edge, function(err) {
if (err) {
return reject(err);
}
return resolve();
});
});
}
function setDirection(pin, direction) {
debug('set direction %s on pin %d', direction.toUpperCase(), pin);
return new Promise(function(resolve, reject) {
fs.writeFile(PATH + '/gpio' + pin + '/direction', direction, function(err) {
if (err) {
return reject(err);
}
return resolve();
});
});
}
function exportPin(pin) {
debug('export pin %d', pin);
return new Promise(function(resolve, reject) {
fs.writeFile(PATH + '/export', pin, function(err) {
if (err) {
return reject(err);
}
return resolve();
});
});
}
function unexportPin(pin) {
debug('unexport pin %d', pin);
return new Promise(function(resolve, reject) {
fs.writeFile(PATH + '/unexport', pin, function(err) {
if (err) {
return reject(err);
}
return resolve();
});
});
}
function isExported(pin) {
return new Promise(function(resolve, reject) {
fs.exists(PATH + '/gpio' + pin, function(exists) {
return resolve(exists);
});
});
}
function removeListener(pin, pollers) {
if (!pollers[pin]) {
return
}
debug('remove listener for pin %d', pin)
pollers[pin]()
delete pollers[pin]
}
function clearInterrupt(fd) {
fs.readSync(fd, Buffer.alloc(1), 0, 1, 0);
}
var GPIO = new Gpio();
// Promise
GPIO.promise = {
DIR_IN: DIR_IN,
DIR_OUT: DIR_OUT,
DIR_LOW: DIR_LOW,
DIR_HIGH: DIR_HIGH,
MODE_RPI: MODE_RPI,
MODE_BCM: MODE_BCM,
EDGE_NONE: EDGE_NONE,
EDGE_RISING: EDGE_RISING,
EDGE_FALLING: EDGE_FALLING,
EDGE_BOTH: EDGE_BOTH,
/**
* @see {@link Gpio.setup}
* @param channel
* @param direction
* @param edge
* @returns {Promise}
*/
setup: function (channel, direction, edge) {
return new Promise(function (resolve, reject) {
function done(error) {
if (error) return reject(error);
resolve();
}
GPIO.setup(channel, direction, edge, done)
})
},
/**
* @see {@link Gpio.write}
* @param channel
* @param value
* @returns {Promise}
*/
write: function (channel, value) {
return new Promise(function (resolve, reject) {
function done(error) {
if (error) return reject(error);
resolve();
}
GPIO.write(channel, value, done)
})
},
/**
* @see {@link Gpio.read}
* @param channel
* @returns {Promise}
*/
read: function (channel) {
return new Promise(function (resolve, reject) {
function done(error, result) {
if (error) return reject(error);
resolve(result);
}
GPIO.read(channel, done)
})
},
/**
* @see {@link Gpio.destroy}
* @returns {Promise}
*/
destroy: function () {
return new Promise(function (resolve, reject) {
function done(error) {
if (error) return reject(error);
resolve();
}
GPIO.destroy(done)
})
},
on: GPIO.on.bind(GPIO),
once: GPIO.once.bind(GPIO),
addListener: GPIO.addListener.bind(GPIO),
removeListener: GPIO.removeListener.bind(GPIO),
removeAllListeners: GPIO.removeAllListeners.bind(GPIO),
};
module.exports = GPIO;