domotz-remote-pawn
Version:
Domotz Agent
82 lines (68 loc) • 2.88 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 Georgi Tsatsev <gtsatsev@domotz.com> on 26/07/16.
*
*/
var tcpRequest = function (message, resourceLocator) {
var tcp = resourceLocator.net;
var cmdUtils = resourceLocator.utils.command;
var payload = message.payload;
var host = payload.host;
var port = payload.port;
var msg = payload.message;
var timeout = payload.timeout;
var encoding = payload.encoding;
return {
execute: function (callback) {
var id;
var connection = tcp.createConnection(port, host, function() {
connection.write(msg, encoding);
console.verbose('Message %s with encoding: %s, sent to %s:%d', msg.toString(encoding),
encoding,
host,
port)
});;
connection.on('close', function (){
console.debug('TCP connection to host %s closed', host);
});
connection.on('data', function (msg) {
console.debug('Received %d bytes', msg.length);
console.verbose('Message: %s', msg.toString(encoding));
callback(cmdUtils.getResponse(msg.toString(encoding), null));
clearTimeout(id);
connection.destroy();
});
connection.on('error', function (error) {
console.error('TCP error - Error: {}' + error.message);
console.error(error.stack);
callback(cmdUtils.getResponse(null, error));
connection.destroy();
});
id = setTimeout(function() {
console.debug('TIMEOUT - Closed TCP connection after ' + timeout + ' milliseconds');
callback(cmdUtils.getResponse(null, 'Timeout'));
connection.destroy();
}, timeout);
},
describe: function () {
return message.correlationId + " - tcpRequest - " + host +
':' + port + ' - ' + message.length + ' packets';
}
};
};
module.exports.command = tcpRequest;