This repository has been archived by the owner on Nov 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pin.js
90 lines (81 loc) · 2.17 KB
/
pin.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
'use strict';
var rpio;
const Pin = function (config) {
config = config || {};
if (!config.mock) {
rpio = require('rpio');
rpio.init(config);
}
return {
open: function (pinConfig) {
if (pinConfig.pin === undefined ||
(pinConfig.input === undefined &&
pinConfig.output === undefined)) {
console.log(pinConfig);
throw 'Invalid pin configuration';
}
return !config.mock ? new PinRpio(pinConfig) : new PinEmulated(pinConfig);
}
};
};
function PinRpio(pinConfig) {
var pin = pinConfig.pin;
//setup pin
if (pinConfig.input) {
if (pinConfig.pullDown) {
rpio.open(pin, rpio.INPUT, rpio.PULL_DOWN);
}
else if (pinConfig.pullUp) {
rpio.open(pin, rpio.INPUT, rpio.PULL_UP);
}
else {
rpio.open(pin, rpio.INPUT);
}
}
else if (pinConfig.output) {
if (pinConfig.initial === true) {
rpio.open(pin, rpio.OUTPUT, rpio.HIGH);
}
else if (pinConfig.initial === false) {
rpio.open(pin, rpio.OUTPUT, rpio.LOW);
}
else {
throw 'Output pinconfig must define an initial value';
}
}
return {
poll: function (onChange) {
var lastValue = undefined;
rpio.poll(pin, function () {
//ignore consecutive duplicates
var value = rpio.read(pin);
if (value !== lastValue) {
lastValue = value;
onChange(value);
}
});
},
read: function () {
return rpio.read(pin);
},
write: function (value) {
rpio.write(pin, value ? rpio.HIGH : rpio.LOW);
},
close: function () {
rpio.close(pin, rpio.PIN_RESET);
}
};
}
function PinEmulated(pinConfig) {
return {
poll: function (onChange) {
},
read: function () {
},
write: function (value) {
},
close: function () {
}
};
}
module.exports = Pin;