forked from felixfischer/node-red-contrib-fritzbox-presence
-
Notifications
You must be signed in to change notification settings - Fork 7
/
fritzbox-presence.js
59 lines (54 loc) · 1.99 KB
/
fritzbox-presence.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
const fritz = require('./fritz')
const bluebird = require('bluebird')
function setNodeStatusToConnectionError(node, error) {
node.status({ fill: "red", shape: "dot", text: error.message })
node.error(error)
}
function setNodeStatusToQuerying(node) {
node.status({ fill: "yellow", shape: "ring", text: "querying" })
}
module.exports = function(RED) {
function FritzBoxPresence(config) {
RED.nodes.createNode(this, config)
var credentials = RED.nodes.getNode(config.fritz)
var username = credentials.username
var password = credentials.password
var hostname = credentials.hostname
var node = this
let sessionID
this.on('input', () => {
setNodeStatusToQuerying(node)
const options = { host: hostname }
return fritz.checkSession(sessionID, options)
.then((isSession) => {
if (!isSession) {
return fritz.getSessionID(username, password, options)
}
return Promise.resolve(sessionID)
})
.then((foundSessionId) => {
if (foundSessionId === '0000000000000000') {
throw new Error('Unvaild session id')
}
sessionID = foundSessionId
return fritz.getData(sessionID, options)
})
.then((response) => {
response = JSON.parse(response)
const devices = response.data.active
node.status({ fill: "green", shape: "ring", text: `${devices.length} active devices detected` })
node.send({ payload: devices, full_response: response })
})
.catch((err) => {
setNodeStatusToConnectionError(node, err)
})
})
this.on('error', () => {
console.log('ääääääääääääää')
})
this.on('close', function() {
node.status({})
})
}
RED.nodes.registerType("fritzbox-presence", FritzBoxPresence)
}