2013-10-25 19:22:45 +02:00
|
|
|
|
2014-06-29 00:35:33 +02:00
|
|
|
module.exports = function(RED) {
|
|
|
|
"use strict";
|
2016-02-13 12:15:02 +01:00
|
|
|
var spawn = require('child_process').spawn;
|
|
|
|
var plat = require('os').platform();
|
2013-10-04 09:24:09 +02:00
|
|
|
|
2014-06-29 00:35:33 +02:00
|
|
|
function PingNode(n) {
|
|
|
|
RED.nodes.createNode(this,n);
|
|
|
|
this.host = n.host;
|
|
|
|
this.timer = n.timer * 1000;
|
|
|
|
var node = this;
|
2013-10-04 09:24:09 +02:00
|
|
|
|
2014-06-29 00:35:33 +02:00
|
|
|
node.tout = setInterval(function() {
|
2016-02-13 12:15:02 +01:00
|
|
|
var ex;
|
|
|
|
if (plat == "linux") { ex = spawn('ping', ['-n', '-w', '5', '-c', '1', node.host]); }
|
|
|
|
else if (plat.match(/^win/)) { ex = spawn('ping', ['-n', '1', '-w', '5000', node.host]); }
|
2017-02-06 23:13:19 +01:00
|
|
|
else if (plat == "darwin" || plat == "freebsd") { ex = spawn('ping', ['-n', '-t', '5', '-c', '1', node.host]); }
|
2016-02-13 12:15:02 +01:00
|
|
|
else { node.error("Sorry - your platform - "+plat+" - is not recognised."); }
|
|
|
|
var res = false;
|
|
|
|
var line = "";
|
|
|
|
//var regex = /from.*time.(.*)ms/;
|
|
|
|
var regex = /=.*[<|=]([0-9]*).*TTL|ttl..*=([0-9\.]*)/;
|
|
|
|
ex.stdout.on('data', function (data) {
|
|
|
|
line += data.toString();
|
|
|
|
});
|
|
|
|
//ex.stderr.on('data', function (data) {
|
|
|
|
//console.log('[ping] stderr: ' + data);
|
|
|
|
//});
|
|
|
|
ex.on('close', function (code) {
|
|
|
|
var m = regex.exec(line)||"";
|
|
|
|
if (m !== '') {
|
|
|
|
if (m[1]) { res = Number(m[1]); }
|
|
|
|
if (m[2]) { res = Number(m[2]); }
|
|
|
|
}
|
|
|
|
var msg = { payload:false, topic:node.host };
|
|
|
|
if (code === 0) { msg = { payload:res, topic:node.host }; }
|
|
|
|
try { node.send(msg); }
|
|
|
|
catch(e) {}
|
2014-06-29 00:35:33 +02:00
|
|
|
});
|
|
|
|
}, node.timer);
|
2013-10-04 09:24:09 +02:00
|
|
|
|
2014-06-29 00:35:33 +02:00
|
|
|
this.on("close", function() {
|
2016-02-13 12:15:02 +01:00
|
|
|
if (this.tout) { clearInterval(this.tout); }
|
2014-06-29 00:35:33 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
RED.nodes.registerType("ping",PingNode);
|
2013-10-04 09:24:09 +02:00
|
|
|
}
|