forked from ivesdebruycker/node-red-contrib-maxcube
-
Notifications
You must be signed in to change notification settings - Fork 6
/
maxcube.js
executable file
·379 lines (336 loc) · 12.6 KB
/
maxcube.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
var MaxCube = require('maxcube2');
module.exports = function(RED) {
function sendCommStatus(node, success, data, error){
var maxCube = node.serverConfig.maxCube;
var duty_cycle = maxCube.getCommStatus();
node.log(JSON.stringify(duty_cycle));
var msg = {};
msg.success = success;
msg.data = data;
msg.error = error;
msg.comm_status = duty_cycle;
node.send({payload: msg});
}
//missing configurations
function initNode(node, config){
//create node
RED.nodes.createNode(node, config);
//check and propagate configurations
node.serverConfig = RED.nodes.getNode(config.server);
node.singleMessage = config.singleMessage;
if (!node.serverConfig) {
return false;
}
//handle status icons
node.serverConfig.on('closed', function () {
node.status({fill:"red",shape:"ring",text:"disconnected"});
});
node.serverConfig.on('connected', function () {
node.status({fill:"green",shape:"dot",text:"connected"});
});
node.serverConfig.on('error', function (err) {
node.log(err);
node.status({fill:"red",shape:"dot",text:"Error: "+err});
});
return true;
}
function checkInputDisabled(node){
var serverConfig = node.serverConfig;
//temporary disabled by settings
if(serverConfig.disabled){
node.status({fill:"yellow",shape:"dot",text:"disabled"});
node.warn("maxcube "+serverConfig.host+" disabled");
//close existing
if(serverConfig.maxCube){
node.warn("closing exising connection: "+serverConfig.host);
serverConfig.maxCube.close();
}
return true;
}
if(!serverConfig.maxCube){
node.warn("maxCube item is not ready");
node.status({fill:"red",shape:"ring",text:"error"});
}
return false;
}
function validateMsg(msg){
//maxcube.js won't accept mode if lowercase
if(msg.payload.mode){
msg.payload.mode = msg.payload.mode.toUpperCase();
}
}
function MaxcubeNodeIn(config) {
var node = this;
if(!initNode(node, config)){
return;
}
node.on('input', function(msg) {
if(checkInputDisabled(node)){
return;
}
validateMsg(msg);
var maxCube = node.serverConfig.maxCube;
var setTemp = function(rf_address, degrees, mode, untilDate){
// Give the cube 30 seconds to answer
return maxCube.setTemperature(rf_address, degrees, mode, untilDate, 30000).then(function (success) {
let data = [rf_address, degrees, mode, untilDate].filter(function (val) {return val;}).join(', ');
node.status({fill:"green",shape:"dot",text: "last msg: "+JSON.stringify(data)});
sendCommStatus(node, success, data);
if (success) {
node.log('Temperature set (' + data+ ')');
return true;
} else {
node.warn('Temperature set command (' + data+ ') discarded by cube. Maybe duty cycle exceeded.');
throw new Error( 'Temperature set command discarded.' );
}
}).catch(function(e) {
node.warn(e);
sendCommStatus(node, false, undefined, e);
// rethrow error to pass it on up the stack
throw e;
});
};
var resetDevice = function( rf_address ){
// Timeout after 30 seconds
return maxCube.resetError( rf_address, 30000 ).then( function (success) {
node.status( { fill: 'green', shape: 'dot', text: 'last msg: reset ' + JSON.stringify(rf_address) } );
sendCommStatus(node, success, rf_address);
if( success ) {
node.log( 'Device reset: ' + rf_address );
return true;
} else {
node.warn( 'Reset command for device ' + rf_address + ' discarded by cube. Maybe duty cycle exceeded.' );
throw new Error( 'Reset command discarded.' );
}
} ).catch( function( e ) {
node.warn(e);
sendCommStatus(node, false, rf_address, e);
// rethrow error to pass it on up the stack
throw e;
} );
};
let sendCommand = function( rf_address, payload ){
let setTempFunc;
if( payload.degrees || payload.mode || payload.untilDate ) {
// Temperature data is available, so register the function
setTempFunc = function() {
return setTemp( rf_address, payload.degrees, payload.mode, payload.untilDate ).catch( function( err ) {
// Do nothing, everything has been done already
// But still catch the error, because uncaught errors are bad
} );
};
} else {
// No temperature data, so do nothing successfully
setTempFunc = function() {
return true;
};
}
if( payload.reset ){
return resetDevice( rf_address ).then( function( success ) {
return setTempFunc();
} ).catch( function( err ) {
// do nothing, everything has been done already
// but still catch the error, because uncaught errors are bad
} );
} else {
return setTempFunc();
}
};
//specific device
if(msg.payload.rf_address){
sendCommand( msg.payload.rf_address, msg.payload );
} else {
//all devices: query getDeviceStatus, then update all!
// Give the cube 30 seconds to answer
maxCube.getDeviceStatus( undefined, 30000 ).then(function (devices) {
for (var i = 0; i < devices.length; i++) {
var deviceStatus = devices[i];
var deviceInfo = maxCube.getDeviceInfo(deviceStatus.rf_address);
// cube 0 --> No reset, no temperature
// radiator thermostat 1 --> Reset and temperature
// radiator thermostat plus 2 --> Reset and temperature
// wall thermostat 3 --> Reset and temperature
// shutter contact 4 --> No reset, no temperature
// eco button 5 --> Reset, but no temperature. Are we sure about that?
// unknown 6 --> Unknown, so do nothing
let payload = msg.payload;
switch( deviceInfo.device_type ) {
case '0':
case '4':
case '6':
// Do nothing, no matter what the user requested.
payload.reset = false;
payload.degrees = undefined;
payload.mode = undefined;
payload.untilDate = undefined;
break;
case '5':
// Do a reset, but don't send a temperature, even if the user requests.
payload.degrees = undefined;
payload.mode = undefined;
payload.untilDate = undefined;
break;
case '1':
case '2':
case '3':
// Do whatever the user requested.
break;
default:
node.error( 'Unknown device type: ' + deviceInfo.device_type + ' at address ' + deviceStatus.rf_address );
return;
}
node.log( 'Sending command to device ' + deviceStatus.rf_address );
sendCommand( deviceStatus.rf_address, payload );
}
} ).catch( function( err ) {
node.error( 'Uncaught error in getDeviceStatus.' );
} );
}
});
}
RED.nodes.registerType("maxcube in", MaxcubeNodeIn);
function MaxcubeNodeOut(config) {
var node = this;
if(!initNode(node, config)){
return;
}
node.on('input', function(msg) {
if(checkInputDisabled(node)){
return;
}
var additionalData = function(deviceStatus, maxCube){
var deviceInfo = maxCube.getDeviceInfo(deviceStatus.rf_address);
if(deviceInfo){
var whitelist = ['device_type', 'device_name', 'room_name', 'room_id'];
for (var i = 0; i < whitelist.length; i++) {
var key = whitelist[i];
if(deviceInfo[key]){
deviceStatus[key] = deviceInfo[key];
}
}
}
};
var maxCube = node.serverConfig.maxCube;
var duty_cycle = maxCube.getCommStatus();
node.log(JSON.stringify(duty_cycle));
// Give the cube 30 seconds to answer
maxCube.getDeviceStatus( undefined, 30000).then(function (devices) {
if(node.singleMessage){
// send devices statuses as single message
var msg = {};
for (var i = 0; i < devices.length; i++) {
var deviceStatus = devices[i];
additionalData(deviceStatus, maxCube);
msg[deviceStatus.rf_address] = deviceStatus;
}
msg.comm_status = duty_cycle;
node.send({payload: msg});
}else{
// send devices statuses as separate messages
node.send([devices.map(function function_name(deviceStatus) {
// add device name, room name, to status object
additionalData(deviceStatus, maxCube);
deviceStatus.comm_status = duty_cycle;
return { rf_address: deviceStatus.rf_address, payload: deviceStatus };
})]);
}
node.status({fill:"green",shape:"dot",text: "last call: "+new Date().toTimeString()});
});
});
}
RED.nodes.registerType("maxcube out", MaxcubeNodeOut);
function MaxcubeDeviceConfigNodeOut(config) {
var node = this;
if(!initNode(node, config)){
return;
}
node.on('input', function(msg) {
if(checkInputDisabled(node)){
return;
}
var maxCube = node.serverConfig.maxCube;
var duty_cycle = maxCube.getCommStatus();
node.log(JSON.stringify(duty_cycle));
// Give the cube 30 seconds to answer
maxCube.getDeviceStatus( undefined, 30000 ).then(function (devices) {
if(node.singleMessage){
// send devices statuses as single message
var msg = {};
for (var i = 0; i < devices.length; i++) {
var deviceStatus = devices[i];
var conf = maxCube.getDeviceConfiguration(deviceStatus.rf_address);
msg[deviceStatus.rf_address] = conf;
}
msg.comm_status = duty_cycle;
node.send({payload: msg});
}else{
// send devices statuses as separate messages
node.send([devices.map(function function_name(deviceStatus) {
var conf = maxCube.getDeviceConfiguration(deviceStatus.rf_address);
conf.comm_status = duty_cycle;
return { rf_address: deviceStatus.rf_address, payload: conf };
})]);
}
node.status({fill:"green",shape:"dot",text: "last call: "+new Date().toTimeString()});
});
});
}
RED.nodes.registerType("maxcube device config", MaxcubeDeviceConfigNodeOut);
function MaxcubeServerNode(config) {
var node = this;
RED.nodes.createNode(this, config);
node.log(config.singleMessage);
this.host = config.host;
this.port = config.port;
this.disabled = config.disabled;
node.maxcubeConnect = function(){
if(node.maxCube){
node.maxCube.removeAllListeners('closed');
node.maxCube.close();
node.maxCube = undefined;
}
if (node.disabled || !node.host || !node.port) {
node.log("Maxcube disabled");
return;
}
//connect/new instance
node.log("Preparing new maxcube connection");
node.maxCube = new MaxCube(node.host, node.port);
//common events
if(node.maxCube){
node.log("Preparing new Maxcube events callback");
node.maxCube.on('closed', function () {
node.emit('closed');
if(node.maxCube != null) {
node.log("Maxcube connection closed unexpectedly... will try to reconnect in one second.");
setTimeout( node.maxcubeConnect, 1000 );
}
else
node.log("Maxcube connection closed...");
});
node.maxCube.on('error', function (e) {
node.emit('error', e);
node.log("Error connecting to the cube.");
node.log(JSON.stringify(e));
//force node to init connection if not available
node.log("Maxcube was disconnected... will try to reconnect in one second.");
setTimeout( node.maxcubeConnect, 1000 );
});
node.maxCube.on('connected', function () {
node.emit('connected');
node.log("Maxcube connected");
});
}
};
node.on("close", function() {
if(node.maxCube){
var maxCube = node.maxCube;
node.maxCube = null;
maxCube.close();
}
});
//first connection
node.maxcubeConnect();
}
RED.nodes.registerType("maxcube-server", MaxcubeServerNode);
}