-
Notifications
You must be signed in to change notification settings - Fork 0
/
allnet.js
executable file
·84 lines (73 loc) · 2.54 KB
/
allnet.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
const winston = require('winston')
// Warning: async loading
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args))
module.exports = function(god, loggerName = 'allnet') {
var self = {
devices: [],
init: function() {
this.logger = winston.loggers.get(loggerName)
god.terminateListeners.push(this.onTerminate.bind(this))
},
onTerminate: async function() {
},
getDeviceForIp: function(ip) {
let device = null
this.devices.forEach(b => { if (b.ip === ip) device = b; })
return device
},
getDeviceForName: function(name) {
let device = null
this.devices.forEach(b => { if (b.name === name) device = b; })
return device
},
addDevice: function(ip, name, fCallback) {
if (this.getDeviceForIp(ip) != null) throw "IP " + ip + " already assigned"
if (this.getDeviceForName(name) != null) throw "Name " + name + " already assigned"
let b = {
'name': name,
'ip': ip,
'callback': fCallback, // TODO we don't have a trigger condition, remove?
}
this.logger.debug('Adding device ' + name + ' with IP ' + ip)
this.devices.push(b)
},
setState: async function(name, value) {
iValue = value && value == 'on' ? '1' : '0'
tValue = iValue ? 'on' : 'off'
let device = this.getDeviceForName(name)
if (device == null) {
this.logger.error("setState: no device known with name " + name)
return
}
this.logger.info('Setting ' + name + ' to ' + tValue)
let res = await fetch('http://' + device.ip + '/r?r=0&s=' + iValue)
// TODO check if res.status == 200
let resText = await res.text()
let match = resText.match(/<A HREF="[^"]+">(ON|OFF)<\/A>/)
// TODO check if match && match.length == 2
tValue = match[1] == 'ON' ? 'on' : 'off'
if (device.callback) device.callback(name, tValue)
return tValue
},
getState: async function(name) {
let device = this.getDeviceForName(name)
if (this.getDeviceForName(name) == null) {
this.logger.error("getState: no device known with name " + name)
return
}
this.logger.debug('Getting status from ' + name)
let res = await fetch('http://' + device.ip + '/xml')
// TODO check if res.status == 200
let resText = await res.text()
let match = resText.match(/<t0>([0-1])<\/t0>/)
// TODO check if match && match.length == 2
let value = match[1]
let tValue = value == '1' ? 'on' : 'off'
this.logger.debug('Status of ' + name + ' is ' + tValue)
if (device.callback) device.callback(name, tValue)
return tValue
},
}
self.init()
return self
}