-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvelux-api.js
61 lines (55 loc) · 1.68 KB
/
velux-api.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
module.exports = function (RED) {
'use strict'
var util = require('util')
var debug = require('debug')('node-red-contrib-velux:velux-api')
function veluxApi(config) {
RED.nodes.createNode(this, config)
var node = this
node.veluxDatasource = RED.nodes.getNode(config.datasource)
if (node.veluxDatasource) {
node.hasTopic = (config.topic||'').length > 0
debug('config:',config)
node.veluxDatasource.subscribeApi(node)
node.on("input", function(msg) {
debug('input:','msg',msg)
if (!node.hasTopic || !msg.topic || config.topic == msg.topic) {
var api = Object.assign({},msg.payload)
if (!api.api && !api.apiText) {
api.api = config.api
}
node.veluxDatasource.callAPI(api)
.then((data)=>{
var outmsg = {payload : data}
if (node.hasTopic) {
outmsg.topic = config.topic
}
node.send(outmsg)
})
.catch((err)=>{
node.error(util.format('Velux API %s', err))
})
}
})
node.onNTF = function(data) {
if (config.ntf) {
debug('apiNTF:',config.ntf.indexOf(data.api),data)
config.ntf.map((ntf)=>{
if (ntf == data.api) {
var outmsg = {payload : data}
if (node.hasTopic) {
outmsg.topic = config.topic
}
node.send(outmsg)
}
})
}
}
node.on('close', function (done) {
debug('close:')
node.veluxDatasource.unsubscribeApi(node)
done()
})
}
}
RED.nodes.registerType('Velux Api', veluxApi)
}