domotz-remote-pawn
Version:
Domotz Agent
79 lines (66 loc) • 2.65 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 Tommaso Latini <tommaso@domotz.com> on 31/03/15.
*
*/
var udpRequest = function (message, resourceLocator) {
var udpUtils = resourceLocator.udp.utils;
var cmdUtils = resourceLocator.utils.command;
var payload = message.payload;
var host = payload.host;
var port = payload.port;
var hexMessage = payload.hex_message;
var burst = payload.burst;
var timeout = payload.timeout;
return {
execute: function (callback) {
var id;
var socket = udpUtils.createSocket();
var buffer = udpUtils.decode(hexMessage);
socket.on('listening', function () {
udpUtils.logListening(socket);
});
socket.on('close', function() {
udpUtils.logClose('client');
});
socket.on('message', function (msg, rinfo) {
udpUtils.logMessage(msg, rinfo);
callback(cmdUtils.getResponse(msg.toString("utf-8"), null));
clearTimeout(id);
socket.close();
});
socket.on('error', function (error) {
udpUtils.logError(error);
callback(cmdUtils.getResponse(null, error));
socket.close();
});
id = setTimeout(function() {
console.debug('TIMEOUT - Closed UDP socket after ' + timeout +
' milliseconds');
callback(cmdUtils.getResponse(null, 'Timeout'));
socket.close();
}, timeout);
udpUtils.send(socket, buffer, host, port, burst);
},
describe: function () {
return message.correlationId + " - udpRequest - " + host +
':' + port + ' - ' + hexMessage.length + ' packets';
}
};
};
module.exports.command = udpRequest;