-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpio.js
executable file
·66 lines (58 loc) · 1.62 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
const Gpio = require('onoff').Gpio;
const winston = require('winston')
module.exports = function(god, loggerName = 'gpio') {
var self = {
listeners: [],
inputs: [],
logger: {},
init: function() {
this.logger = winston.loggers.get(loggerName)
god.terminateListeners.push(this.onTerminate.bind(this))
},
onTerminate: async function() {
this.inputs.forEach(b => {
try {
this.logger.info("GPIO: freeing '" + b.name + "' on pin " + b.id)
b.obj.unexport()
} catch (e) {
if (e.startsWith('Error: EBADF: bad file descriptor')) {
// simplify error message
this.logger.error("Exception during freeing of GPIO pin: --- %s", e)
} else {
this.logger.error("Exception during freeing of GPIO pin: %o", e)
}
}
})
},
getObjForId: function(id) {
let obj = null
this.inputs.forEach(b => { if (b.id === id) obj = b; })
return obj
},
addInput: function(id, name, fCallback) {
if (this.getObjForId(id) != null) {
throw "pin" + id + " already used" // gpio usage error
}
let obj = new Gpio(id, 'in', 'both')
let b = {
'name': name,
'id': id,
'obj': obj,
'callback': fCallback,
}
this.inputs.push(b)
obj.watch((err, value) => this.onInputChange(id, err, value))
},
onInputChange: function(id, err, value) {
if (err) {
this.logger.error("GPIO " + id + " Error: " + err)
throw err
}
let obj = this.getObjForId(id)
this.logger.info("GPIO '" + obj.name + "' changed to " + value)
this.inputs.forEach(b => { if (b.id == id) b.callback(value) })
},
}
self.init()
return self
}