-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstratonws.js
482 lines (397 loc) · 16.7 KB
/
stratonws.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
module.exports = function (RED) {
var ws = require("ws");
var url = require('url');
var abortConnection = function (socket) {
var response;
try {
response = ["HTTP/1.1 401 Unauthorized", "Content-type: text/html"];
return socket.write(response.concat("", "").join("\r\n"));
} finally {
try {
socket.destroy();
} catch (_error) {
console.log(_error);
}
}
};
var upgradeConnection = function (socket) {
return socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + 'Upgrade: WebSocket\r\n' + 'Connection: Upgrade\r\n' + '\r\n');
};
function StratonWSNode(config) {
RED.nodes.createNode(this,config);
var node = this;
//Get Var list members
node.listVariables = [];
node.statusVarList = -1;
node.socketVarList = null;
// Store local copies of the node configuration (as defined in the .html)
node.remoteUrl = config.address;
node.closing = false;
node.disconnectCount = 0;
node.port_count = 1;
var flowContext = node.context().flow;
var nodeContext = this.context();
var globalContext = this.context().global;
flowContext.set("stratonWS_disconnect_count", node.disconnectCount);
this.subs = config.subs || [];
for (var i = 0; i < this.subs.length; i += 1) {
var sub = this.subs[i];
//node.trace("sub " + sub);
}
node.port_count = node.subs.length + 1;
node.status({
fill: "red",
shape: "ring",
text: "disconnected"
});
function treatReqAnswer(pObj) {
var i,j;
var ports = new Array(node.port_count);
for (i = 0; i < node.port_count; i += 1) {
ports[i] = null;
}
if (typeof pObj !== 'undefined') {
//node.trace("pObj.cmd " + pObj.cmd);
//node.trace("pObj.error " + pObj.error);
//node.trace("pObj.data " + pObj.data);
if ((typeof pObj.cmd !== 'undefined')) {
//node.trace("sendMsgToPorts: " + node.port_count);
msg = {
cmd: pObj.cmd,
payload: pObj.data,
statusCode: pObj.error,
extStatusCode: pObj.extError
};
ports[node.port_count-1] = msg; //always set the msg (full object) to the LAST output (general)
// For other port only get them if read2
if (pObj.cmd == "read2" && pObj.error == 200 && (typeof pObj.data !== 'undefined') && pObj.data.length > 0) {
//For each variable in the message from websocket
for (i = 0; i < pObj.data.length; i++) {
//search for the port index
for (j = 0; j < node.subs.length; j += 1) {
var sub = node.subs[j];
if (pObj.data[i].name == sub) {
//node.trace("found " + pObj.data[0].name + " at " + i);
msg = {
cmd: pObj.cmd,
payload: pObj.data[i].value,
statusCode: pObj.error,
extStatusCode: pObj.extError
};
ports[j] = msg;
}
}
}
}
//send msg
node.send(ports);
}
}
}
function startconn() {// Connect to remote endpoint
//node.trace(node.remoteUrl);
var socket = new ws(node.remoteUrl);
node.server = socket;
// keep for closing
handleConnection(socket);
}
function sendWS(cmd) {
//node.trace("sendCommand " + cmd);
try {
if (node.server !== null) {
node.server.send(cmd);
}
} catch (err) { // Error
}
}
function stratonGetStatusWS() {
sendWS("{\"cmd\":\"status2\"}");
}
function stratonSubscribeWS(varName, periodMs) {
var strVars = '{\"cmd\":\"subscribe2\",\"param\":{\"period\":' + periodMs + '},\"data\":[';
strVars += '{\"name\":\"';
strVars += varName;
strVars += '\"}';
strVars += ']}';
sendWS(strVars);
}
function stratonWriteValueWS(varName, varValue) {
var strVars = '{\"cmd\":\"write2\",\"data\":[';
strVars += '{\"name\":\"';
strVars += varName;
strVars += '\"';
strVars += ',';
strVars += '\"value\":\"';
strVars += varValue;
strVars += '\"}';
strVars += ']}';
sendWS(strVars);
}
function stratonSubscribeArrayWS(nameArray, periodMs) {
if (nameArray.length > 0) {
var i;
var strVars = '{\"cmd\":\"subscribe2\",\"param\":{\"period\":' + periodMs.toString() + '},\"data\":[';
for (i = 0; i < nameArray.length; i++) {
strVars += '{\"name\":\"';
strVars += nameArray[i];
strVars += '\"}';
if (i < (nameArray.length - 1))
strVars += ',';
}
strVars += ']}';
sendWS(strVars);
}
}
function handleConnection(/*socket*/socket)
{
socket.on('open', function ()
{
//node.trace("open");
//stratonGetStatusWS();
var varArrayVarNames = [];
//go through all the subscriptions in properties
//and suscribe to variables
for (var i = 0; i < node.subs.length; i += 1) {
var sub = node.subs[i];
//node.trace("Sub=" + sub);
if (sub !== "") {
varArrayVarNames.push(sub);
}
}
if (varArrayVarNames.length > 0) {
//node.trace("SUB " + varArrayVarNames.length + "vars");
stratonSubscribeArrayWS(varArrayVarNames, 500);
}
//node.emit('opened', '');
node.status({
fill: "green",
shape: "dot",
text: "connected "
});
});
socket.on('close', function ()
{
node.disconnectCount++;
flowContext.set("stratonWS_disconnect_count", node.disconnectCount);
//node.trace("close");
node.status({
fill: "red",
shape: "ring",
text: "disconnected"
});
//node.emit('closed');
if (!node.closing) {
node.tout = setTimeout(function () {
startconn();
}, 30000);
// try to reconnect every 30 secs
}
});
// We received a message on the WebSocket
socket.on('message', function (data, flags)
{
//node.trace(data);
var p;
try {
p = JSON.parse(data);
} catch (err) {
//node.trace("parse failed");
}
if (typeof p !== 'undefined')
{
//node.trace("socket:" + p.cmd);
//if the message contains the field error
if (typeof p.error !== 'undefined')
{
if (p.error != 200)
{
node.status({
fill: "yellow",
shape: "dot",
text: p.error + " " + p.errorTxt
});
}
else
{
node.status({
fill: "green",
shape: "dot",
text:"connected"
});
}
}
//Node send payload
treatReqAnswer(p);
}
});
socket.on('error', function (err)
{
//node.trace("error");
//node.emit('erro');
if (!node.closing) {
node.tout = setTimeout(function () {
startconn();
}, 30000);
// try to reconnect every 30 secs
}
});
}
function handleAuthentication(req, socket, head) {
var authorization,
jwtToken,
parts,
scheme;
authorization = req.headers.authorization;
if (typeof (node.auth0) == "undefined" || !node.auth0) {
return upgradeConnection(socket);
}
if (!authorization) {
return abortConnection(socket, 400, 'Bad Request');
}
parts = authorization.split(" ");
if (parts.length !== 2) {
return abortConnection(socket, 400, 'Bad Request');
}
scheme = parts[0];
jwtToken = parts[1];
if ("Bearer" !== scheme || !jwtToken) {
return abortConnection(socket, 400, 'Bad Request');
}
var request = require('request');
var options = {
uri: node.auth0,
method: 'POST',
json: {
id_token: jwtToken
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
req.tokeninfo = body || {};
req.tokeninfo.authorized = true;
if (node.role && req.tokeninfo && req.tokeninfo.roles && req.tokeninfo.roles.indexOf(node.role) == -1) {
req.tokeninfo.authorized = false;
}
if (node.group && req.tokeninfo && req.tokeninfo.groups && req.tokeninfo.groups.indexOf(node.group) == -1) {
req.tokeninfo.authorized = false;
}
if (req.tokeninfo.authorized) {
return upgradeConnection(socket);
} else {
return abortConnection(socket, 401, 'Unauthorized - HEKKK');
}
} else {
return abortConnection(socket, 503, 'The authentication service is unavailable.');
}
});
}
// start outbound connection
node.closing = false;
startconn();
node.on("close", function () {
// Workaround https://github.com/einaros/ws/pull/253
// Remove listeners from RED.server
node.closing = true;
node.server.close();
if (node.tout) {
clearTimeout(node.tout);
}
});
// We received something from the Node input
node.on('input', function (msg) {
var strCmd = "";
var value = RED.util.getMessageProperty(msg,"payload");
if (value !== undefined) {
if (typeof value === "string") { //payload is a string
strCmd = value;
}
else if (typeof value === "object") { //payload is an object
strCmd = JSON.stringify(msg.payload); // we make it a string to be transfered on the WS
}
}
if( strCmd !== '' )
{
//node.trace("input " + strCmd);
sendWS(strCmd);
}
});
}
RED.nodes.registerType("straton websocket", StratonWSNode);
// Create an admin configuration API endpoint
// Sometimes a custom node needs to be able to look up additional data at configuration time (e.g. when editing the configuration of a node instance in the admin interface).
// The approved way to do this is for the node to register an extra http endpoint to use as an API.
// see https://github.com/node-red/cookbook.nodered.org/wiki/Create-an-admin-configuration-API-endpoint
// Handle request to get the list of variables
//RED.httpAdmin.get('/stratonvarlist/:id', RED.auth.needsPermission('stratonread.read'), function (req, res) {
RED.httpAdmin.post('/stratonvarlist/:id/:remoteurl', RED.auth.needsPermission('stratonws.read'), function (req, res) {
console.log("inside httpAdmin" + req.params.id + req.params.remoteurl);
msg = {
status: -1,
data: []
};
var node = RED.nodes.getNode(req.params.id);
if (node !== null && typeof node !== "undefined") {
var reqnodeid = req.params.id;
function handleConnectionGetVarList(socket) {
// On open socket, we wend a command to get the lsit of variables
// We empty the array of var names
// We set status to 0 : in process
socket.on('open', function () {
socket.send("{\"cmd\":\"list2\"}");
node.statusVarList = 0;
node.listVariables = [];
});
socket.on('close', function () {
});
// On receiving message socket
socket.on('message', function (data, flags) {
//node.trace(data);
var pObj;
try {
pObj = JSON.parse(data);
} catch (err) { // Error
node.statusVarList = 1; // Operation done
node.listVariables = []; // No variables
}
if (typeof pObj !== 'undefined') {
if (pObj.cmd == "list2") {
node.statusVarList = 1; // Operation done
node.listVariables = []; // Empty array
if (pObj.cmd == "list2" && pObj.error == 200 && (typeof pObj.data !== 'undefined') && pObj.data.length > 0) {
//For each variable in the message from websocket
for (i = 0; i < pObj.data.length; i++) {
node.listVariables.push(/*reqnodeid + */pObj.data[i]); // put var name in array
}
}
}
}
socket.close();
node.socketVarList = null;
});
socket.on('error', function (err) {
});
}
// We open a socket and try to get the variable list
// if there is no operation currently and the socket is closed
if (node.statusVarList == -1) {
if (node.socketVarList === null) {
node.listVariables = [];
node.statusVarList = 0;
node.socketVarList = new ws("ws://" + req.params.remoteurl);
handleConnectionGetVarList(node.socketVarList);
}
}
msg = {
status: node.statusVarList,
data: node.listVariables
};
//for (var i = 0; i < node.listVariables.length; i++) {
// console.log(node.listVariables[i]);
//}
} else {
// if node not saved I'm here.
msg.status = -1;
}
res.json(msg);
});
}