-
Notifications
You must be signed in to change notification settings - Fork 2
/
webthingsio-set-property.js
105 lines (104 loc) · 3.67 KB
/
webthingsio-set-property.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
const {getInputValue} = require('./webthingsio-helpers');
module.exports = function(RED) {
function WebthingsioSetPropertyNode(config) {
RED.nodes.createNode(this, config);
if (!config.gateway) {
this.error(RED._('webthingsio-set-property.gatewayMissing'));
return;
}
this.gateway = RED.nodes.getNode(config.gateway);
if (!this.gateway) {
this.error(RED._('webthingsio-set-property.gatewayNotFound'));
return;
}
if (!this.gateway.webthingsEmitter) {
// eslint-disable-next-line max-len
this.error(RED._('webthingsio-set-property.webthingsClientNotFound'));
return;
}
this.gateway.webthingsEmitter.on('connected', () => {
this.status({
fill: 'green',
shape: 'dot',
text: 'node-red:common.status.connected',
});
});
this.gateway.webthingsEmitter.on('disconnected', () => {
this.status({
fill: 'red',
shape: 'ring',
text: 'node-red:common.status.disconnected',
});
});
this.on('input', async (msg, _send, done) => {
if (typeof config.thing !== 'string') {
if (done) {
done(RED._('webthingsio-set-property.thingNameInvalid'));
} else {
this.error(
RED._('webthingsio-set-property.thingNameInvalid'),
msg,
);
}
return;
}
const decodedThingId = decodeURIComponent(config.thing);
if (typeof config.property !== 'string') {
if (done) {
done(RED._('webthingsio-set-property.propertyNameInvalid'));
} else {
this.error(
RED._('webthingsio-set-property.propertyNameInvalid'),
msg,
);
}
return;
}
let value;
try {
value = getInputValue(RED, this, config, msg);
} catch (ex) {
const e = typeof ex === 'string' ? ex : JSON.stringify(ex);
if (done) {
done(
RED._('webthingsio-set-property.parseInputFailed')
.replace('%error', e),
);
} else {
this.error(
RED._('webthingsio-set-property.parseInputFailed')
.replace('%error', e),
msg,
);
}
return;
}
try {
await this.gateway.webthingsEmitter.setProperty(
decodedThingId,
config.property,
value,
);
done();
} catch (ex) {
const e = typeof ex === 'string' ? ex : JSON.stringify(ex);
if (done) {
done(
RED._('webthingsio-set-property.setPropertyFailed')
.replace('%error', e),
);
} else {
this.error(
RED._('webthingsio-set-property.setPropertyFailed')
.replace('%error', e),
msg,
);
}
}
});
}
RED.nodes.registerType(
'webthingsio-set-property',
WebthingsioSetPropertyNode,
);
};