nep-cli 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/index.js CHANGED
@@ -18,49 +18,47 @@ const fs = require('fs');
18
18
  const zmqc = require("zeromq/v5-compat");
19
19
 
20
20
  const PORT_MASTER_INFO = 50001; // Default port for master info
21
- const PORT_IMAGES = [];
22
- for (let i = 50050; i <= 50060; i++) {
23
- PORT_IMAGES.push(i);
24
- }
21
+ const PORT_SERVER = 50050;
22
+
25
23
 
26
24
 
27
25
  program
28
- .version(version)
29
- .description('NEP-CLI')
26
+ .version(version)
27
+ .description('NEP-CLI')
30
28
 
31
29
  program
32
- .command('ip')
33
- .description('Display current Wi-Fi and Ethernet IP addresses of this computer')
34
- .action(() => {
35
- try {
36
- // subsitude by interfaces = nep.getNetworkInterfaces --> {"wifi":wifiInterfaces, "eth":ethernetInterface}
37
- const platform = os.platform();
38
- let wifiInterfaces, ethernetInterface;
39
-
40
- if (platform === 'linux') {
41
- wifiInterfaces = Object.keys(os.networkInterfaces()).filter(ifname => /^(wlan|wlp|wl|en)\d*$/i.test(ifname));
42
- ethernetInterface = Object.keys(os.networkInterfaces()).find(ifname => /^(eth|enp|eno)\d*$/i.test(ifname));
43
- } else if (platform === 'win32') {
44
- wifiInterfaces = Object.keys(os.networkInterfaces()).filter(ifname => /^(Wireless|Wi-Fi)/i.test(ifname));
45
- ethernetInterface = Object.keys(os.networkInterfaces()).find(ifname => /^Ethernet/i.test(ifname));
46
- } else if (platform === 'darwin') {
47
- wifiInterfaces = Object.keys(os.networkInterfaces()).filter(ifname => /^en\d*$/i.test(ifname));
48
- ethernetInterface = Object.keys(os.networkInterfaces()).find(ifname => /^en\d*$/i.test(ifname));
49
- } else {
50
- console.log('Unsupported operating system.');
51
- return;
52
- }
30
+ .command('ip')
31
+ .description('Display current Wi-Fi and Ethernet IP addresses of this computer')
32
+ .action(() => {
33
+ try {
34
+ // subsitude by interfaces = nep.getNetworkInterfaces --> {"wifi":wifiInterfaces, "eth":ethernetInterface}
35
+ const platform = os.platform();
36
+ let wifiInterfaces, ethernetInterface;
37
+
38
+ if (platform === 'linux') {
39
+ wifiInterfaces = Object.keys(os.networkInterfaces()).filter(ifname => /^(wlan|wlp|wl|en)\d*$/i.test(ifname));
40
+ ethernetInterface = Object.keys(os.networkInterfaces()).find(ifname => /^(eth|enp|eno)\d*$/i.test(ifname));
41
+ } else if (platform === 'win32') {
42
+ wifiInterfaces = Object.keys(os.networkInterfaces()).filter(ifname => /^(Wireless|Wi-Fi)/i.test(ifname));
43
+ ethernetInterface = Object.keys(os.networkInterfaces()).find(ifname => /^Ethernet/i.test(ifname));
44
+ } else if (platform === 'darwin') {
45
+ wifiInterfaces = Object.keys(os.networkInterfaces()).filter(ifname => /^en\d*$/i.test(ifname));
46
+ ethernetInterface = Object.keys(os.networkInterfaces()).find(ifname => /^en\d*$/i.test(ifname));
47
+ } else {
48
+ console.log('Unsupported operating system.');
49
+ return;
50
+ }
53
51
 
54
- wifiInterfaces.forEach(wifiInterface => {
55
- const ipAddress = nep.getIPAddress(wifiInterface);
56
- nep.printIPAddress(`Wi-Fi (${wifiInterface})`, ipAddress);
57
- });
52
+ wifiInterfaces.forEach(wifiInterface => {
53
+ const ipAddress = nep.getIPAddress(wifiInterface);
54
+ nep.printIPAddress(`Wi-Fi (${wifiInterface})`, ipAddress);
55
+ });
58
56
 
59
- nep.printIPAddress('Ethernet', nep.getIPAddress(ethernetInterface));
60
- } catch (error) {
61
- console.error('An error occurred:', error.message);
62
- }
63
- });
57
+ nep.printIPAddress('Ethernet', nep.getIPAddress(ethernetInterface));
58
+ } catch (error) {
59
+ console.error('An error occurred:', error.message);
60
+ }
61
+ });
64
62
 
65
63
 
66
64
 
@@ -122,28 +120,6 @@ var onRegisteredTopic = function (node_request, topic_register, topic) {
122
120
  }
123
121
 
124
122
 
125
- var onResetTopic = function (node_request) {
126
-
127
- var topic = node_request["topic"]
128
- nep_configuration["current_port"] = Math.max(nep_configuration["current_port"], node_request["port"] + 2);
129
-
130
- if (node_request["socket"] === "publisher" || node_request["socket"] === "subscriber") {
131
- // Create new broker for many2many communication
132
- if (node_request["mode"] === "many2many") {
133
- restartBroker(node_request["topic"], node_request["port"]);
134
- }
135
-
136
- if ("msg_type" in node_request) {
137
- topic_register[topic] = { "port": node_request["port"], "socket": node_request["socket"], 'ip': nep_configuration["IP"], "mode": node_request["mode"], "msg_type": node_request["msg_type"] }
138
- }
139
- else {
140
- topic_register[topic] = { "port": node_request["port"], "socket": node_request["socket"], 'ip': nep_configuration["IP"], "mode": node_request["mode"], "msg_type": "json" }
141
- }
142
-
143
- topic_register[topic]["nodes"] = [];
144
- }
145
-
146
- }
147
123
 
148
124
  var onNewTopic = function (node_request, topic_register) {
149
125
 
@@ -199,16 +175,6 @@ var createBroker = function (topic) {
199
175
  }
200
176
  }
201
177
 
202
- var restartBroker = function (topic, port) {
203
- try {
204
- var broker = new nep.Broker(nep_configuration["IP"], port + 1, port)
205
- //var brokersubex = new BrokerBridgeSUBEX(conf["IP"],IP_EXTERNAL, conf["current_port"] , conf["current_port"])
206
- // Add broker defined to list of brokers
207
- nep_configuration["brokers"][topic] = broker
208
- } catch (error) {
209
- console.log("NEP ERROR: ports " + String(port) + " and " + String(port + 1) + " not avaliable")
210
- }
211
- }
212
178
 
213
179
  var m2mResponse = function (node_request, topic_register, topic) {
214
180
  if ("msg_type" in node_request) {
@@ -241,17 +207,6 @@ var updatePID = function (node_request, topic_register, topic) {
241
207
  }
242
208
 
243
209
 
244
- var restartTopics = function (node_request) {
245
- console.log(node_request)
246
- // Get topic name
247
- var topic = String(node_request['topic'])
248
-
249
- console.log(" --- Reset topic : *" + topic + "* ---")
250
- // Create new broker
251
- onResetTopic(node_request);
252
- onUpdateTopicList(topic_register)
253
- }
254
-
255
210
  const processMsg = (json_msg, nodes_register, topic_register) => {
256
211
  const node_request = JSON.parse(json_msg);
257
212
  const { node, socket, topic, pid } = node_request;
@@ -277,7 +232,7 @@ const processMsg = (json_msg, nodes_register, topic_register) => {
277
232
 
278
233
  // Update node info
279
234
  nodes_register[node] = pid;
280
-
235
+
281
236
  // Check topic status
282
237
  const topicStr = String(topic);
283
238
  if (topicStr in topic_register) {
@@ -293,6 +248,145 @@ const processMsg = (json_msg, nodes_register, topic_register) => {
293
248
  }
294
249
  };
295
250
 
251
+ function startShowServer(port, topic, ip) {
252
+ const app = express();
253
+ const server = http.createServer(app);
254
+ const io = socketIo(server);
255
+ const path = require('path');
256
+
257
+ // Serve static files from node_modules
258
+ app.use(express.static(path.join(__dirname)));
259
+
260
+
261
+ const node = new nep.Node("nep-cli-sub");
262
+ const config = node.hybrid(ip)
263
+
264
+ function getImage(msg) {
265
+ // Send the received image data as-is to connected clients
266
+ io.sockets.emit('image', { image: msg });
267
+ }
268
+
269
+ const sub = node.new_sub(topic, "images", getImage, config);
270
+
271
+ app.get('/', (req, res) => {
272
+ res.sendFile(path.join(__dirname, './image.html')); // Serve your HTML file
273
+ });
274
+
275
+ server.listen(port, () => {
276
+ console.log(`Server is running on http://localhost:${port}`);
277
+ }).on('error', err => {
278
+ console.error(`Error starting server: ${err}`);
279
+ });
280
+
281
+ io.on('connection', (socket) => {
282
+ const frameRate = 30; // Desired frame rate
283
+ const interval = 1000 / frameRate; // Interval between frames
284
+ }).on('error', err => {
285
+ console.error(`Error with socket connection: ${err}`);
286
+ });
287
+ }
288
+
289
+ function startJsonServer(port, topic, ip, msg_type = "json") {
290
+ const app = express();
291
+ const server = http.createServer(app);
292
+ const io = socketIo(server);
293
+ const path = require('path');
294
+ app.use(express.static(path.join(__dirname)));
295
+
296
+ const node = new nep.Node("nep-cli-sub");
297
+ const config = node.hybrid(ip)
298
+
299
+ function getJSON(msg) {
300
+ try {
301
+
302
+ io.sockets.emit('json_data', msg);
303
+ } catch (error) {
304
+
305
+ }
306
+ }
307
+
308
+ const sub = node.new_sub(topic, msg_type, getJSON, config);
309
+
310
+ app.get('/', (req, res) => {
311
+ res.sendFile(path.join(__dirname, './json.html')); // Serve your HTML file
312
+ });
313
+
314
+ server.listen(port, () => {
315
+ console.log(`Server is running on http://localhost:${port}`);
316
+ }).on('error', err => {
317
+ console.error(`Error starting server: ${err}`);
318
+ });
319
+
320
+ io.on('connection', (socket) => {
321
+ const frameRate = 30; // Desired frame rate
322
+ const interval = 1000 / frameRate; // Interval between frames
323
+ }).on('error', err => {
324
+ console.error(`Error with socket connection: ${err}`);
325
+ });
326
+ }
327
+
328
+
329
+ const createRequester = (master_ip, port) => {
330
+ const requester = new zmq.Request();
331
+ requester.connect(`tcp://${master_ip}:${port}`);
332
+ return requester;
333
+ };
334
+
335
+ const sendRequest = async (requester, msg) => {
336
+ const message = JSON.stringify(msg);
337
+ await requester.send(message);
338
+ const [result] = await requester.receive();
339
+ return JSON.parse(result.toString());
340
+ };
341
+
342
+ const selectTopic = async (results, topic) => {
343
+ if (!topic || !results["input"].includes(topic)) {
344
+ const autoComplete = new AutoComplete({
345
+ name: 'topic',
346
+ message: !topic ? 'Select a topic:' : 'Invalid topic. Select a valid topic:',
347
+ choices: results["input"],
348
+ });
349
+ topic = await autoComplete.run();
350
+ }
351
+ return topic;
352
+ };
353
+
354
+ const selectIndex = async (index, maxIndex = 9) => {
355
+ const choices = ["0","1","2","3","4","5","6","7","8","9"];
356
+
357
+ const autoComplete = new AutoComplete({
358
+ name: 'index',
359
+ message: !index ? 'Select a index:' : 'Invalid index. Select a valid index:',
360
+ choices: choices,
361
+ });
362
+ index = await autoComplete.run();
363
+
364
+ return index;
365
+ };
366
+
367
+ const selectMsgType = async (allowedFormats, msg_type, topic) => {
368
+ var msgType = topic.split('/').pop();
369
+ if (msgType && msgType !== topic) {
370
+ msg_type = msgType;
371
+ }
372
+
373
+ if (!msg_type || !allowedFormats.includes(msg_type)) {
374
+ const autoComplete = new AutoComplete({
375
+ name: 'msg_type',
376
+ message: !msg_type ? 'Select a message type:' : `Select a valid format:`,
377
+ choices: allowedFormats,
378
+ });
379
+ msg_type = await autoComplete.run();
380
+ }
381
+ return msg_type;
382
+ };
383
+
384
+ const openSub = (master_ip, topic, msg_type, callback) => {
385
+ const node = new nep.Node("nep-cli-sub");
386
+ const conf = node.hybrid(master_ip);
387
+ const sub = node.new_sub(topic, msg_type, callback, conf);
388
+ };
389
+
296
390
 
297
391
  program
298
392
  .command('app')
@@ -318,6 +412,53 @@ program
318
412
  });
319
413
 
320
414
 
415
+ program
416
+ .command('publish <topic> <message>')
417
+ .description('Publish a message to a NEP+ topic')
418
+ .action((topic, message) => {
419
+
420
+ var openpub = function (master_ip = "127.0.0.1") {
421
+
422
+ var pubFunction = function () {
423
+
424
+ var msg = message.replace(/'/g, '"')
425
+ console.log(JSON.parse(msg))
426
+ pub.publish(JSON.parse(msg))
427
+ console.log("Message published")
428
+
429
+ process.exit(1)
430
+ }
431
+
432
+
433
+ var node = new nep.Node("nep-cli-pub")
434
+ var pub = node.new_pub(topic, "json")
435
+ setTimeout(pubFunction, 1000)
436
+ }
437
+
438
+ async function run() {
439
+ var requester = new zmq.Request;
440
+ var master_ip = "127.0.0.1"
441
+
442
+ requester.connect("tcp://" + master_ip + ":" + PORT_MASTER_INFO);
443
+
444
+ let msg = { "input": "topics" }
445
+ var message = JSON.stringify(msg);
446
+ await requester.send(message)
447
+ const [result] = await requester.receive()
448
+ var results = JSON.parse(result.toString())
449
+ //console.log(results);
450
+ if (results["input"].includes(topic)) {
451
+ console.log("")
452
+ openpub(master_ip)
453
+ }
454
+ else {
455
+ console.log("Topic is not registered");
456
+ }
457
+ }
458
+ run()
459
+ });
460
+
461
+
321
462
  program
322
463
  .command('open [programName]')
323
464
  .description('Open a NEP+ GUI')
@@ -363,13 +504,13 @@ program
363
504
 
364
505
  program
365
506
  .command('master')
366
- .description('Start NEP master in localhost')
507
+ .description('Fetches and displays the list of NEP+ topics from the NEP master')
367
508
  .action(async () => {
368
509
  try {
369
510
  var node = new nep.Node("nep-cli");
370
511
  console.log("Starting NEP master in terminal")
371
512
  var master = new MasterLocal();
372
- var info = new nep.MasterInfoServer(IP = '0.0.0.0', topics = topic_register, port_=PORT_MASTER_INFO);
513
+ var info = new nep.MasterInfoServer(IP = '0.0.0.0', topics = topic_register, port_ = PORT_MASTER_INFO);
373
514
  } catch (error) {
374
515
  if (error.message.includes('EADDRINUSE')) {
375
516
  console.error("Error: Address already in use. Another instance of NEP master might be running.");
@@ -382,7 +523,7 @@ program
382
523
 
383
524
  program
384
525
  .command('topics')
385
- .description('Get list of NEP+ topics')
526
+ .description('Displays the list of NEP+ topics')
386
527
  .action(async () => {
387
528
  const master_ip = "127.0.0.1";
388
529
  const TIMEOUT_DURATION = 5000; // Timeout duration in milliseconds
@@ -433,205 +574,119 @@ program
433
574
  await getTopics(); // Call the function to get topics
434
575
  });
435
576
 
436
-
437
577
  program
438
- .command('listen <topic>')
439
- .description('Subscribe to a NEP+ topic and display JSON messages')
440
- .action(async (topic) => {
441
- const interfaces = os.networkInterfaces();
442
-
443
- var opensub = function (master_ip = "127.0.0.1") {
444
- var callback = function (msg) {
445
- var date = new Date();
446
- var dateString = date.toISOString();
447
- console.log(dateString);
448
-
449
- if (msg.length > 10000) {
450
- console.log("the message is too long to be displayed");
451
- } else {
452
- console.log(msg);
453
- }
454
- };
455
-
456
- var node = new nep.Node("nep-cli-sub");
457
- var conf = node.hybrid(master_ip);
458
- sub = node.new_sub(topic, "json", callback, conf);
459
- };
578
+ .command('show [topic] [index]')
579
+ .description('Displays messages published to a specified NEP+ topic in the default browser. ' +
580
+ 'The [index] parameter specifies the index of the message to display and must be a number between 0 and 49. '
581
+ )
582
+ .action(async (topic, index) => {
583
+ const ip = "127.0.0.1";
584
+
585
+ const allowedFormats = ["json", "msgpack", "bytes", "images", "dictionary", "string"];
586
+ const master_ip = "127.0.0.1";
460
587
 
461
- var master_ip = "127.0.0.1";
462
- async function run() {
463
- var requester = new zmq.Request();
464
- requester.connect("tcp://" + master_ip + ":" + PORT_MASTER_INFO);
588
+ const requester = createRequester(master_ip, PORT_MASTER_INFO);
589
+ const results = await sendRequest(requester, { "input": "topics" });
465
590
 
466
- let msg = { "input": "topics" };
467
- var message = JSON.stringify(msg);
468
- await requester.send(message);
469
- const [result] = await requester.receive();
470
- var results = JSON.parse(result.toString());
591
+ topic = await selectTopic(results, topic);
592
+ var msg_type = await selectMsgType(allowedFormats, msg_type, topic);
593
+ index = await selectIndex(index);
471
594
 
472
- if (results["state"] === "failure") {
473
- console.log("Topic is not registered");
474
- } else {
475
- console.log("");
476
- if (results["input"].includes(topic)) {
477
- opensub(master_ip);
478
- } else {
479
- console.log("Topic is not registered");
480
- }
595
+ const topicid = `${index}: ${topic}`;
596
+ if(parseInt(index) < 50)
597
+ {
598
+ const port = PORT_SERVER + parseInt(index);
599
+ console.log(PORT_SERVER)
600
+ console.log(index)
601
+ console.log(PORT_SERVER + parseInt(index))
602
+
603
+ if (msg_type === "images") {
604
+ open(`http://localhost:${port}/?port=${port}&topic=${encodeURIComponent(topicid)}`);
605
+ startShowServer(port, topic, ip);
606
+ }
607
+ else if (msg_type === "json" || msg_type === "dictionary") {
608
+ open(`http://localhost:${port}/?port=${port}&topic=${encodeURIComponent(topicid)}`);
609
+ startJsonServer(port, topic, ip, msg_type);
481
610
  }
482
- }
483
611
 
484
- run();
612
+ }
613
+ else {
614
+ console.log("Index must be between 0 and 49");
615
+ }
616
+
485
617
  });
486
618
 
487
619
 
488
620
  program
489
- .command('echo <topic>')
621
+ .command('echo [topic]')
490
622
  .description('Subscribe to a NEP+ topic and display raw string messages')
491
- .action(async (topic) => {
492
- const interfaces = os.networkInterfaces();
493
-
494
- var opensub = function (master_ip = "127.0.0.1") {
495
- var callback = function (msg) {
496
- var date = new Date();
497
- var dateString = date.toISOString();
498
- console.log(dateString);
499
-
500
- if (msg.length > 10000) {
501
- console.log("the message is too long to be displayed");
502
- } else {
503
- console.log(msg);
504
- }
505
- };
623
+ .action(async (topic, msg_type) => {
624
+ const allowedFormats = ["json", "msgpack", "bytes", "images", "dictionary", "string"];
625
+ const master_ip = "127.0.0.1";
506
626
 
507
- var node = new nep.Node("nep-cli-sub");
508
- var conf = node.hybrid(master_ip);
509
- sub = node.new_sub(topic, "string", callback, conf);
510
- };
627
+ const requester = createRequester(master_ip, PORT_MASTER_INFO);
628
+ const results = await sendRequest(requester, { "input": "topics" });
511
629
 
512
- var master_ip = "127.0.0.1";
513
- async function run() {
514
- var requester = new zmq.Request();
515
- requester.connect("tcp://" + master_ip + ":" + PORT_MASTER_INFO);
630
+ topic = await selectTopic(results, topic);
631
+ msg_type = await selectMsgType(allowedFormats, msg_type, topic);
516
632
 
517
- let msg = { "input": "topics" };
518
- var message = JSON.stringify(msg);
519
- await requester.send(message);
520
- const [result] = await requester.receive();
521
- var results = JSON.parse(result.toString());
633
+ const callback = (msg) => {
634
+ const date = new Date();
635
+ const dateString = date.toISOString();
636
+ console.log(dateString);
522
637
 
523
- if (results["state"] === "failure") {
524
- console.log("Topic is not registered");
638
+ if (msg.length > 10000) {
639
+ console.log("the message is too long to be displayed");
525
640
  } else {
526
- console.log("");
527
- if (results["input"].includes(topic)) {
528
- opensub(master_ip);
529
- } else {
530
- console.log("Topic is not registered");
531
- }
532
- }
533
- }
534
-
535
- run();
536
- });
537
-
538
-
539
- program
540
- .command('publish <topic> <message>')
541
- .description('Publish a message to a NEP+ topic')
542
- .action((topic, message) => {
543
-
544
- var openpub = function (master_ip = "127.0.0.1") {
545
-
546
- var pubFunction = function () {
547
-
548
- var msg = message.replace(/'/g, '"')
549
- console.log(JSON.parse(msg))
550
- pub.publish(JSON.parse(msg))
551
- console.log("Message published")
552
-
553
- process.exit(1)
641
+ console.log(msg);
554
642
  }
643
+ };
555
644
 
556
-
557
- var node = new nep.Node("nep-cli-pub")
558
- var pub = node.new_pub(topic, "json")
559
- setTimeout(pubFunction, 1000)
560
- }
561
-
562
- async function run() {
563
- var requester = new zmq.Request;
564
- var master_ip = "127.0.0.1"
565
-
566
- requester.connect("tcp://" + master_ip + ":" + PORT_MASTER_INFO);
567
-
568
- let msg = { "input": "topics" }
569
- var message = JSON.stringify(msg);
570
- await requester.send(message)
571
- const [result] = await requester.receive()
572
- var results = JSON.parse(result.toString())
573
- //console.log(results);
574
- if (results["input"].includes(topic)) {
575
- console.log("")
576
- openpub(master_ip)
577
- }
578
- else {
579
- console.log("Topic is not registered");
580
- }
581
- }
582
- run()
645
+ openSub(master_ip, topic, msg_type, callback);
583
646
  });
584
647
 
585
-
586
648
  program
587
- .command('hz <topic> <msg_type>')
588
- .description('Monitor the publishing rate of a NEP+ topic in localhost')
649
+ .command('hz [topic]')
650
+ .description('Monitor the publishing rate of a NEP+ topic')
589
651
  .action(async (topic, msg_type) => {
590
- const interfaces = os.networkInterfaces();
591
- const master_ip = "127.0.0.1"; // Change to the appropriate master IP
592
-
593
- const opensub = function () {
594
- const timestamps = []; // To store message timestamps
652
+ const allowedFormats = ["json", "msgpack", "bytes", "images", "dictionary", "string"];
653
+ const master_ip = "127.0.0.1";
595
654
 
596
- const callback = function (msg) {
597
- const date = new Date();
598
- const timestamp = date.getTime();
655
+ const requester = createRequester(master_ip, PORT_MASTER_INFO);
656
+ const results = await sendRequest(requester, { "input": "topics" });
657
+ const timestamps = []; // Store timestamps of received messages
599
658
 
600
- timestamps.push(timestamp);
659
+ topic = await selectTopic(results, topic);
660
+ msg_type = await selectMsgType(allowedFormats, msg_type, topic);
601
661
 
602
- // Remove timestamps older than ten seconds
603
- const tenSecondsAgo = timestamp - 10000;
604
- while (timestamps[0] < tenSecondsAgo) {
605
- timestamps.shift();
606
- }
607
- };
662
+ const callback = function (msg) {
663
+ const date = new Date();
664
+ const timestamp = date.getTime();
608
665
 
609
- const allowedFormats = ["json", "msgpack", "bytes", "images", "image"];
610
- const messageFormat = allowedFormats.includes(msg_type) ? msg_type : "json";
611
- const node = new nep.Node("nep-cli-sub");
612
- const conf = node.hybrid(master_ip);
666
+ timestamps.push(timestamp);
613
667
 
614
- console.log("Topic:", topic)
615
- console.log("Message type:", messageFormat)
668
+ // Remove timestamps older than ten seconds
669
+ const tenSecondsAgo = timestamp - 10000;
670
+ while (timestamps[0] < tenSecondsAgo) {
671
+ timestamps.shift();
672
+ }
673
+ };
616
674
 
617
- const sub = node.new_sub(topic, messageFormat, callback, conf);
675
+ setInterval(() => {
676
+ // Calculate statistics for the last 10 seconds
677
+ const now = Date.now();
678
+ const tenSecondsAgo = now - 10000;
679
+ const recentTimestamps = timestamps.filter((ts) => ts > tenSecondsAgo);
680
+ const rate = recentTimestamps.length / 10; // Messages per second for a 10-second window
681
+
682
+ console.log("Average rate:", rate.toFixed(2), "Hz");
683
+ console.log("Min:", (10 / Math.max(rate, 0.1)).toFixed(2), "s");
684
+ console.log("Max:", (10 / Math.min(rate, 10)).toFixed(2), "s");
685
+ console.log("Std dev:", calculateStdDev(recentTimestamps, now).toFixed(2), "s");
686
+ console.log("Window:", recentTimestamps.length);
618
687
  console.log("");
688
+ }, 1000);
619
689
 
620
- setInterval(() => {
621
- // Calculate statistics for the last 10 seconds
622
- const now = Date.now();
623
- const tenSecondsAgo = now - 10000;
624
- const recentTimestamps = timestamps.filter((ts) => ts > tenSecondsAgo);
625
- const rate = recentTimestamps.length / 10; // Messages per second for a 10-second window
626
-
627
- console.log("Average rate:", rate.toFixed(2), "Hz");
628
- console.log("Min:", (10 / Math.max(rate, 0.1)).toFixed(2), "s");
629
- console.log("Max:", (10 / Math.min(rate, 10)).toFixed(2), "s");
630
- console.log("Std dev:", calculateStdDev(recentTimestamps, now).toFixed(2), "s");
631
- console.log("Window:", recentTimestamps.length);
632
- console.log("");
633
- }, 1000);
634
- };
635
690
 
636
691
  const calculateStdDev = (timestamps) => {
637
692
  if (timestamps.length < 2) {
@@ -660,30 +715,8 @@ program
660
715
  return stdDeviation;
661
716
  };
662
717
 
718
+ openSub(master_ip, topic, msg_type, callback);
663
719
 
664
- async function run() {
665
- const requester = new zmq.Request();
666
- requester.connect(`tcp://${master_ip}:${PORT_MASTER_INFO}`);
667
-
668
- const msg = { "input": "topics" };
669
- const message = JSON.stringify(msg);
670
- await requester.send(message);
671
- const [result] = await requester.receive();
672
- const results = JSON.parse(result.toString());
673
-
674
- if (results["state"] === "failure") {
675
- console.log("Topic is not registered, use *nep topics* to see the list of avaliable topics");
676
- } else {
677
- console.log("");
678
- if (results["input"].includes(topic)) {
679
- opensub();
680
- } else {
681
- console.log("Topic is not registered, use *nep topics* to see the list of avaliable topics");
682
- }
683
- }
684
- }
685
-
686
- run();
687
720
  });
688
721
 
689
722