-
Notifications
You must be signed in to change notification settings - Fork 8
/
ctrlx-config.js
450 lines (394 loc) · 15 KB
/
ctrlx-config.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/**
*
* MIT License
*
* Copyright (c) 2020-2021 Bosch Rexroth AG
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
module.exports = function(RED) {
'use strict';
const CtrlxCore = require('./lib/CtrlxCore');
const CtrlxProblemError = require('./lib/CtrlxProblemError');
/* ---------------------------------------------------------------------------
* API for frontend UI
* -------------------------------------------------------------------------*/
// https://discourse.nodered.org/t/create-an-admin-configuration-api-https-endpoint/4423/7
// https://discourse.nodered.org/t/accessing-server-side-from-client-side/26022/4
RED.httpAdmin.get('/ctrlx/browse', function(req, res) {
// console.log(req.query);
const id = req.query.id;
const username = req.query.username;
const password = req.query.password;
const hostname = req.query.hostname;
const path = req.query.path;
if (hostname && username && password) {
// The frontend send us hostname, username and a password, so let's use this information
// and establish a connection to browse on the device.
let ctrlx = new CtrlxCore(hostname, username, password);
ctrlx.logIn()
.then(() => ctrlx.datalayerBrowse(path))
.then((data) => {
if (!data || !data.value) {
return res.end('[]');
}
res.end(JSON.stringify(data.value));
})
.catch((err) => {
if (err instanceof CtrlxProblemError) {
res.statusCode = err.status;
return res.end(err.toStringExtended());
} else if (err instanceof Error) {
res.statusCode = 500;
return res.end(err.message);
}
})
.finally(() => {
// We have to catch, because this fails for bad credentials
ctrlx.logOut().catch((err) => RED.log.warn('Failed to log out when trying to browse with error ' + err.message));
});
} else if (id) {
// Let's use an already instances config node in the runtime to make our browse on the device.
const configNode = RED.nodes.getNode(id);
if (!configNode) {
res.statusCode = 404;
res.end('[]');
return;
}
configNode.datalayerBrowse(null, path, (err, data) => {
if (err instanceof CtrlxProblemError) {
res.statusCode = err.status;
return res.end(err.toStringExtended());
} else if (err instanceof Error) {
res.statusCode = 500;
return res.end(err.message);
}
if (!data || !data.value) {
return res.end('[]');
}
res.end(JSON.stringify(data.value));
})
} else {
// we do not have enough infos to establish a session to a device and query the infos.
res.statusCode = 400;
return res.end('[]');
}
});
/* ---------------------------------------------------------------------------
* NODE - config
* -------------------------------------------------------------------------*/
function CtrlxConfig(config) {
RED.nodes.createNode(this, config);
// Configuration options passed by Node Red
this.name = config.name;
this.debug = config.debug;
this.hostname = config.hostname;
if (this.credentials) {
this.username = this.credentials.username;
this.password = this.credentials.password;
}
// Config node state
this.connected = false;
this.connecting = false;
this.closing = false;
this.ctrlX = new CtrlxCore(this.hostname, this.username, this.password);
this.ctrlX.autoReconnect = true;
// If the config node is missing certain options (it was probably deployed prior to an update to the node code),
// select/generate sensible options for the new fields
if (typeof this.debug === 'undefined') {
this.debug = false;
}
//
// Define functions called by nodes
//
let node = this;
this.users = {};
this.pendingRequests = {};
// Register function to be called by all nodes which are attached to this config node.
this.register = function(ctrlxNode) {
node.users[ctrlxNode.id] = ctrlxNode;
if (Object.keys(node.users).length === 1) {
node.connect();
}
};
// Unregister of attached ctrlX node. We log out of ctrlX when the last node unregistered.
this.deregister = function(ctrlxNode, done) {
delete node.users[ctrlxNode.id];
if (node.closing) {
return done();
}
if (Object.keys(node.users).length === 0) {
if (node.ctrlX) {
node.ctrlX.logOut()
.then(() => done())
.catch(() => done());
}
} else {
done();
}
};
// This function performs the login. Will be automatically called as soon as
// the first node registers.
this.connect = function() {
if (!node.connected && !node.connecting) {
node.connecting = true;
try {
node.ctrlX.logIn()
.then((data) => {
node.connecting = false;
node.connected = true;
if (node.debug) {
node.log('Successfully logged in to: ' + node.hostname);
node.log('Token will expire at ' + new Date(data.token_expireTime).toLocaleString() + ' local time');
}
for (let id in node.users) {
if (Object.prototype.hasOwnProperty.call(node.users, id)) {
node.users[id].setStatus({ fill: 'green', shape: 'dot', text: 'authenticated' });
}
}
// Now execute all the pending requests
for (let id in node.pendingRequests) {
if (Object.prototype.hasOwnProperty.call(node.pendingRequests, id)) {
switch (node.pendingRequests[id].method) {
case 'READ': {
node.datalayerRead(id, node.pendingRequests[id].path, node.pendingRequests[id].callback);
break;
}
case 'READ_WITH_ARG': {
node.datalayerReadWithArg(id, node.pendingRequests[id].path, node.pendingRequests[id].arg, node.pendingRequests[id].callback);
break;
}
case 'WRITE': {
node.datalayerWrite(id, node.pendingRequests[id].path, node.pendingRequests[id].data, node.pendingRequests[id].callback);
break;
}
case 'CREATE': {
node.datalayerCreate(id, node.pendingRequests[id].path, node.pendingRequests[id].data, node.pendingRequests[id].callback);
break;
}
case 'DELETE': {
node.datalayerDelete(id, node.pendingRequests[id].path, node.pendingRequests[id].callback);
break;
}
case 'METADATA': {
node.datalayerReadMetadata(id, node.pendingRequests[id].path, node.pendingRequests[id].callback);
break;
}
case 'BROWSE': {
node.datalayerBrowse(id, node.pendingRequests[id].path, node.pendingRequests[id].callback);
break;
}
case 'SUBSCRIBE': {
node.datalayerSubscribe(id, node.pendingRequests[id].paths, node.pendingRequests[id].options, node.pendingRequests[id].callback);
break;
}
default: {
node.error('internal error: received invalid pending request!');
}
}
delete node.pendingRequests[id];
}
}
})
.catch((err) => {
node.connecting = false;
node.connected = false;
if (node.debug) {
node.log('Failed to log in to ' + node.hostname + ' with error ' + err.message);
}
for (let id in node.users) {
if (Object.prototype.hasOwnProperty.call(node.users, id)) {
node.users[id].setStatus({ fill: 'red', shape: 'ring', text: 'authentication failed' });
}
}
// Now cancel all the pending requests
for (let id in node.pendingRequests) {
if (Object.prototype.hasOwnProperty.call(node.pendingRequests, id)) {
node.pendingRequests[id].callback(err, null);
delete node.pendingRequests[id];
}
}
// Try again, except if the node has been closed in the meanwhile. E.g. because
// the node has been deleted or the flow has been reployed with new settings.
if (!node.closing) {
setTimeout(node.connect, 5000);
}
});
} catch (err) {
node.error(err);
}
}
};
this.setTimeout = function(timeout) {
node.ctrlX.timeout = timeout;
}
this.datalayerRead = function(nodeRef, path, callback) {
if (node.connected) {
node.ctrlX.datalayerRead(path)
.then((data) => callback(null, data))
.catch((err) => callback(err, null));
} else if (node.connecting) {
node.pendingRequests[nodeRef.id] = {
method: 'READ',
path: path,
callback: callback
};
} else {
callback(new Error('No session available! Please check connection and credentials.'), null);
}
}
this.datalayerReadWithArg = function(nodeRef, path, arg, callback) {
if (node.connected) {
node.ctrlX.datalayerRead(path, arg)
.then((data) => callback(null, data))
.catch((err) => callback(err, null));
} else if (node.connecting) {
node.pendingRequests[nodeRef.id] = {
method: 'READ_WITH_ARG',
path: path,
arg: arg,
callback: callback
};
} else {
callback(new Error('No session available! Please check connection and credentials.'), null);
}
}
this.datalayerWrite = function(nodeRef, path, data, callback) {
if (node.connected) {
node.ctrlX.datalayerWrite(path, data)
.then(() => callback(null))
.catch((err) => callback(err));
} else if (node.connecting) {
node.pendingRequests[nodeRef.id] = {
method: 'WRITE',
path: path,
data: data,
callback: callback
};
} else {
callback(new Error('No session available! Please check connection and credentials.'), null);
}
}
this.datalayerCreate = function(nodeRef, path, data, callback) {
if (node.connected) {
node.ctrlX.datalayerCreate(path, data)
.then((data) => callback(null, data))
.catch((err) => callback(err, null));
} else if (node.connecting) {
node.pendingRequests[nodeRef.id] = {
method: 'CREATE',
path: path,
data: data,
callback: callback
};
} else {
callback(new Error('No session available! Please check connection and credentials.'), null);
}
}
this.datalayerDelete = function(nodeRef, path, callback) {
if (node.connected) {
node.ctrlX.datalayerDelete(path)
.then(() => callback(null))
.catch((err) => callback(err, null));
} else if (node.connecting) {
node.pendingRequests[nodeRef.id] = {
method: 'DELETE',
path: path,
callback: callback
};
} else {
callback(new Error('No session available! Please check connection and credentials.'), null);
}
}
this.datalayerReadMetadata = function(nodeRef, path, callback) {
if (node.connected) {
node.ctrlX.datalayerReadMetadata(path)
.then((data) => callback(null, data))
.catch((err) => callback(err, null));
} else if (node.connecting) {
node.pendingRequests[nodeRef.id] = {
method: 'METADATA',
path: path,
callback: callback
};
} else {
callback(new Error('No session available! Please check connection and credentials.'), null);
}
}
this.datalayerBrowse = function(nodeRef, path, callback) {
if (node.connected) {
node.ctrlX.datalayerBrowse(path)
.then((data) => callback(null, data))
.catch((err) => callback(err, null));
} else if (node.connecting && nodeRef) {
node.pendingRequests[nodeRef.id] = {
method: 'BROWSE',
path: path,
callback: callback
};
} else {
callback(new Error('No session available! Please check connection and credentials.'), null);
}
}
this.datalayerSubscribe = function(nodeRef, paths, options, callback) {
if (node.connected) {
node.ctrlX.datalayerSubscribe(paths, options)
.then((data) => callback(null, data))
.catch((err) => callback(err, null));
} else if (node.connecting) {
node.pendingRequests[nodeRef.id] = {
method: 'SUBSCRIBE',
paths: paths,
options: options,
callback: callback
};
} else {
callback(new Error('No session available! Please check connection and credentials.'), null);
}
}
this.logAdditionalDebugErrorInfo = function(node, err) {
if (!this.debug) {
return;
}
if (err instanceof CtrlxProblemError) {
let message = err.toStringExtended();
node.log(`${message}`);
} else {
node.log(err.toString());
}
}
//
// Close handler
//
node.on("close", function(done) {
// Logout, when node is closing down.
node.closing = true;
node.ctrlX.logOut()
.then(() => done())
.catch(() => done());
});
}
RED.nodes.registerType("ctrlx-config", CtrlxConfig, {
credentials: {
username: { type: "text" },
password: { type: "password" }
}
});
};