domotz-remote-pawn
Version:
Domotz Agent
82 lines (73 loc) • 3.29 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 factory = function (engineRequest, devicesInfo, avahiCommands, procUtils) {
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, device, mac) {
if (device.zeroconf_name !== zeroconfName) {
console.info('DISCOVERY - (' + SERVICE_NAME + '): Zeroconf name successfully recovered for device %s: ' +
'%s', mac, zeroconfName);
var resource = '/device/' + device.id;
var name = {zeroconf_name: zeroconfName};
engineRequest.send(resource, 'PUT', name);
} else {
console.debug('DISCOVERY - (' + SERVICE_NAME + '): Zeroconf name for device: %s is not ' +
'changed. [%s]', mac, zeroconfName);
}
}
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 devicesInfo.get(mac).then(function (device) {
if (!device) {
console.info('DISCOVERY - (' + SERVICE_NAME + "): Ignoring missing device %s - most probably the device has been" +
" just discovered", mac);
} else {
procUtils.exec(avahiCommands.getHostResolveCmd(ip))
.then(function (res) {
update(parseResult(res), device, mac);
})
.catch(errorHandler).
finally(function () {
"use strict";
devicesInfo.setUpdateTimeToNow(device.mac, SERVICE_NAME);
});
}
});
}
}
return {
resolve: resolve
};
}
;
module.exports.factory = factory;