-
Notifications
You must be signed in to change notification settings - Fork 3
/
gpio.js
79 lines (66 loc) · 1.8 KB
/
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
'use strict';
var path = require('path');
var util = require('util');
var child_process = require('child_process');
var fs = require('fs');
var exec = child_process.exec;
var assert = require('assert');
var pins = require('./pins.js');
var gpioInitPath = path.join(path.dirname(fs.realpathSync(__filename)), 'gpio_init.sh')
function getPinPath(pin) {
return util.format('/sys/class/gpio/gpio%d/value', pin.id);
}
function Gpio() {
this.pins = pins;
}
Gpio.prototype.init = function init(options, cb) {
var self = this;
assert(options.busyPin);
assert(options.enablePin)
console.log(gpioInitPath);
child_process.execFile(gpioInitPath, function(error, stdout, stderr) {
console.log(stdout);
console.log(stderr);
if (error) {
return cb(error);
}
//config-pin P9.12 out #EN
//config-pin P8.10 in #BUSY
self.set(options.busyPin, 'in', function(err) {
if (err) {
return cb(err);
}
self.set(options.enablePin, 'out', function(err) {
return cb(err);
});
});
});
}
Gpio.prototype.get = function get(pin, cb) {
fs.readFile(getPinPath(pin), function (err, data) {
if (err) throw err;
return cb(null, parseInt(data));
});
}
function genCommand(pin, value) {
return util.format('config-pin %s %s', pin.name, value);
}
Gpio.prototype.execCommand = function execCommand(command, cb) {
exec(command, function (error, stdout, stderr) {
if (stderr) {
console.log('stderr: ' + stderr);
}
cb(error);
});
}
Gpio.prototype.set = function set(pin, value, cb) {
var strValue = 'low';
if (value === 'in' || value === 'out') {
strValue = value;
} else if (value && value !== '0') {
strValue = 'hi';
}
var command = genCommand(pin, strValue);
this.execCommand(command, cb);
}
module.exports = new Gpio();