domotz-remote-pawn
Version:
Domotz Agent
88 lines (78 loc) • 3.32 kB
JavaScript
/** This file is part of Domotz Agent.
* Copyright (C) 2016 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/>.
* Created by tom on 19/12/15.
*/
const RESOLVE_REG_EXP = /^(.*).local.$/i;
const SERVICE_NAME = 'AVAHI_RESOLVE';
var nameByMac = {};
var factory = function (engineRequest, devicesInfo, avahiCommands, procUtils) {
var q = require('q');
function errorHandler(err) {
if (err.code === 9) {
console.verbose('AVAHI_RESOLVE: Avahi Discovery: Timeout Reached');
} else {
console.debug(err.toString('utf8'));
}
}
function parseResult(res) {
var str = res.trim();
var matches = str.match(RESOLVE_REG_EXP);
return matches[1];
}
function update(zeroconfName, mac) {
if (nameByMac[mac] !== zeroconfName && zeroconfName !== undefined) {
console.info('DISCOVERY - (' + SERVICE_NAME + '): Zeroconf name successfully recovered for device %s: ' + '%s', mac, zeroconfName);
var resource = '/subnet/ip/device/' + mac + '/zeroconf-name';
var name = { zeroconf_name: zeroconfName };
engineRequest
.sendWithPromise(resource, 'PUT', name)
.then(function () {
'use strict';
console.debug('DISCOVERY - (' + SERVICE_NAME + '): Old name for device [%s] was %s', mac, nameByMac[mac]);
nameByMac[mac] = zeroconfName;
console.debug('DISCOVERY - (' + SERVICE_NAME + '): Storing name %s for device [%s]', nameByMac[mac], mac);
})
.catch(function () {
console.error('Error reporting zeroconf name');
});
} else {
console.debug('DISCOVERY - (' + SERVICE_NAME + '): Zeroconf name for device: %s is not changed. [%s]', mac, nameByMac[mac]);
}
}
function resolve(dev) {
var mac = dev.mac;
var ip = dev.ip;
if (devicesInfo.isToBeUpdated(mac, SERVICE_NAME)) {
console.debug('DISCOVERY - (' + SERVICE_NAME + '): Resolving zeroconf name for device with IP: ' + ip + ' and MAC: ' + mac);
return procUtils
.exec(avahiCommands.getHostResolveCmd(ip))
.then(function (res) {
update(parseResult(res), mac);
})
.catch(errorHandler)
.finally(function () {
'use strict';
devicesInfo.setUpdateTimeToNow(mac, SERVICE_NAME);
});
} else {
return q();
}
}
return {
resolve: resolve,
};
};
module.exports.factory = factory;