-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-device.js
68 lines (67 loc) · 2.97 KB
/
create-device.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
const axios = require('axios')
module.exports = function(RED) {
function CreateDevice(config) {
RED.nodes.createNode(this,config);
// Retrieve the config node
this.server = RED.nodes.getNode(config.server);
this.idents = {}
if (this.server) {
var node = this;
node.on('input', function(msg, send, done) {
send = send || function() { node.send.apply(node,arguments) }
if (typeof msg.payload === 'object' && msg.payload.hasOwnProperty('ident') && node.server.token &&
!this.idents[msg.payload.ident]) {
axios.post(
"https://" + (node.server.host || "flespi.io") + "/gw/devices",
[
{
"name": config.name.replace('%ident%', msg.payload.ident),
"device_type_id": parseInt(config.devicetype || 0) ,
"messages_ttl": parseInt(config.messagesttl || 0),
"configuration": {
"ident": msg.payload.ident
}
}
],
{
headers: {Authorization: "FlespiToken " + node.server.token.replace('FlespiToken ', '')}
}
).then(
(response) => {
this.idents[msg.payload.ident] = true;
if (response.data.result && response.data.result[0]) {
msg.payload = response.data.result[0];
send([msg, null]);
}
if (response.data.errors) {
msg.payload = response.data.errors;
send([null, msg]);
}
},
(error) => {
this.idents[msg.payload.ident] = true;
if (errors.response.data.result && errors.response.data.result[0]) {
msg.payload = errors.response.data.result[0];
send([msg, null]);
}
if (error.response.data.errors) {
msg.payload = error.response.data.errors;
send([null, msg]);
}
// done(JSON.stringify(msg));
}
).catch ((e) => {
// done(JSON.stringify(e))
})
}
});
} else {
// No server config
}
}
RED.nodes.registerType("create-device", CreateDevice, {
credentials: {
token: {type:"password"}
}
});
}