domotz-remote-pawn
Version:
Domotz Agent
80 lines (73 loc) • 3.26 kB
JavaScript
/** This file is part of Domotz Agent.
* Copyright (C) 2023 Domotz Ltd
*
* Domotz Agent is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Domotz Agent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Domotz Agent. If not, see <http://www.gnu.org/licenses/>.
*
*
* Measure the baseline latency
* Created by Stefano Cicero <stefano.cicero@domotz.com> on 25/09/23.
*/
module.exports = function (resourceLocator) {
const q = resourceLocator.q;
const dns = resourceLocator.networkTools.dns;
const myConsole = resourceLocator.log.decorateLogs();
const ipUtils = resourceLocator.ip;
function getSettings(settingsManager) {
return {
baselinePingNumber: settingsManager.getSetting('configuration.settings.latency.baseline_ping_number', 50),
maxPingNumber: settingsManager.getSetting('configuration.settings.latency.max_ping_number', 300),
server: settingsManager.getSetting('configuration.settings.latency.server', 'echo.domotz.com'),
timeout: settingsManager.getSetting('configuration.settings.latency.timeout_ms', 1000),
packetSize: settingsManager.getSetting('configuration.settings.latency.packet_size_byte', 32),
interPingDelay: settingsManager.getSetting('configuration.settings.latency.inter_ping_delay', 10),
isLatencyMeasurementActive: settingsManager.getSetting('configuration.settings.latency.measurement', true),
warmupPeriod: settingsManager.getSetting('configuration.settings.latency.warmup_period', 1000),
};
}
var serverIP;
function isValidIPv4(ip) {
var ipAddress = new ipUtils.Address4(ip);
return ipAddress.valid;
}
// accept as argument an ip address or a hostname
function serverLookup(server) {
const deferred = q.defer();
if (serverIP) {
myConsole.debug('Using cached ip address');
deferred.resolve(serverIP);
} else if (isValidIPv4(server)) {
deferred.resolve(server);
} else {
dns.lookup(server, function (err, ip) {
if (err) {
myConsole.warn('Error resolving hostname %s: %s', server, JSON.stringify(err));
deferred.reject('Error resolving hostname');
return;
}
myConsole.debug('Successfully resolved hostname %s: %s', server, JSON.stringify(ip));
if (typeof ip === 'string') {
serverIP = ip;
} else {
serverIP = ip[0];
}
deferred.resolve(serverIP);
});
}
return deferred.promise;
}
return {
getSettings: getSettings,
serverLookup: serverLookup,
};
};