-
Notifications
You must be signed in to change notification settings - Fork 0
/
led_module.js
75 lines (56 loc) · 1.85 KB
/
led_module.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
const gpio = require('rpi-gpio')
const LEDStateEnum = Object.freeze( {"on": 1, "off": 0} )
const LEDColorEnum = Object.freeze( {"green": 38, "red": 40} )
const LEDModeEnum = Object.freeze( {"solid": 0, "blinking": 1} )
class LEDManager {
constructor(ledColor) {
this.color = ledColor
this.state = LEDStateEnum.off
this.mode = LEDModeEnum.solid
gpio.setup(this.color, gpio.DIR_OUT)
}
on(mode, duration = 0) {
this._clearHandlers()
this.state = LEDStateEnum.on
this.mode = mode
console.log('LED ' + this.color + ' is ON - mode: ' + mode + ', duration: ' + duration)
const _this = this
if (mode === LEDModeEnum.solid) {
gpio.write(this.color, LEDStateEnum.on, function() {
if (duration > 0) {
_this.timeoutHandler = setTimeout(function() {
_this.off()
}, duration)
}
})
} else {
var lightOn = true
this.blinkingIntervalHandler = setInterval(function() {
gpio.write(_this.color, lightOn, function() {
lightOn = !lightOn
})
}, 50)
if (duration > 0) {
this.timeoutHandler = setTimeout(function () {
_this.off()
}, duration)
}
}
}
off() {
console.log('LED ' + this.color + ' is OFF')
this.state = LEDStateEnum.off
this._clearHandlers()
gpio.write(this.color, LEDStateEnum.off)
}
_clearHandlers() {
clearInterval(this.blinkingIntervalHandler)
clearTimeout(this.timeoutHandler)
}
}
module.exports = {
LEDManager: LEDManager,
LEDStateEnum: LEDStateEnum,
LEDColorEnum: LEDColorEnum,
LEDModeEnum: LEDModeEnum
}