-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGPIOValve.js
70 lines (51 loc) · 1.36 KB
/
GPIOValve.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
const Gpio = require('onoff').Gpio;
class GPIOValve {
constructor(pin, openOnHigh = true) {
if (!pin) { throw new Error('A valve control pin must be specified') }
this._openLevel = +openOnHigh
this._closedLevel = +!openOnHigh
this._valve = new Gpio(pin, 'out')
this._writeClosed()
process.on('SIGINT', () => {
this._valve.unexport()
})
}
openFor(duration, done) {
this._startTime = Date.now()
this._duration = duration * 1000
this.open()
this._timer = setTimeout(() => {
this.close()
done()
}, this._duration)
}
get elasped() {
if (!this._isOpen) { return 0 }
return msToS(Date.now() - this._startTime)
}
get remaining() {
if (!this._isOpen) { return 0 }
return msToS(this._duration) - this.elasped
}
open() {
this._isOpen = true
this._writeOpen()
}
close() {
this._isOpen = false
this._startTime = 0
this._duration = 0
clearTimeout(this._timer)
this._writeClosed()
}
_writeOpen() {
this._valve.writeSync(this._openLevel)
}
_writeClosed() {
this._valve.writeSync(this._closedLevel)
}
}
module.exports = GPIOValve
function msToS(val) {
return Math.round(val / 1000)
}