-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
121 lines (92 loc) · 2.81 KB
/
index.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
const EventEmitter = require('events')
const ERR_INVALIDCHANNEL = "Invalid relay channel."
const HIGH = 1
const LOW = 0
class Relay extends EventEmitter {
constructor (port, channels, switchState = 'low', callback) {
super()
if (typeof switchState === 'function') {
callback = arguments[2]
switchState = 'low'
}
this.port = port
this.channels = channels
this.ON = LOW
this.OFF = HIGH
if (switchState === 'high') {
this.ON = HIGH
this.OFF = LOW
}
this.channelStates = channels.reduce((obj, channel) => {
obj[channel] = false
this.setPin(channel, this.OFF)
return obj;
}, {})
setImmediate(() => {
this.emit('ready')
if (callback) {
callback(null, this)
}
})
}
setPin (channel, value) {
var relay = this.port.pin[channel - 1];
relay.write(value);
}
setRawValue (channel, state, callback, silent = false) {
var value = (state ? this.ON : this.OFF)
this.setPin(channel, value)
this.channelStates[channel] = value;
if (callback) {
callback(null);
}
if (!silent) {
setImmediate(() => {
this.emit('latch', channel, state);
});
}
}
isInvalidChannel (channel) {
return !(channel !== 0 && channel <= this.channels.length)
}
getState (channel, callback) {
if (this.isInvalidChannel(channel)) {
return callback && callback(new Error(ERR_INVALIDCHANNEL));
}
var state = this.channelStates[channel] === this.ON ? true : false;
callback && callback(null, state);
}
setState (channel, state, callback) {
if (this.isInvalidChannel(channel)) {
return callback && callback(new Error(ERR_INVALIDCHANNEL));
}
this.setRawValue(channel, state, callback)
}
toggle (channel, callback) {
this.getState(channel, (err, state) => {
if (err) {
return callback && callback(err);
}
this.setRawValue(channel, !state, callback)
})
}
turnOn (channel, callback) {
if (this.isInvalidChannel(channel)) {
return callback && callback(new Error(ERR_INVALIDCHANNEL));
}
this.setRawValue(channel, true, callback)
}
turnOff (channel, callback) {
if (this.isInvalidChannel(channel)) {
return callback && callback(new Error(ERR_INVALIDCHANNEL));
}
this.setRawValue(channel, false, callback)
}
}
const use = (port, channels, callback) => {
return new Relay(port, channels, callback)
}
module.exports = {
use,
Relay
}