index.js 2.71 KB
// Include Nodejs' net module.
const Net = require('net');
const converter = require('hex2dec');
// The port number and hostname of the server.
const port = 10001;
const host = 'fipdebo.ddns.net';
var respuesta = '';

// Create a new TCP client.
const client = new Net.Socket();
// Send a connection request to the server.
client.connect({ port: port, host: host }, function() {
    // If there is no error, the server has accepted the request and created a new 
    // socket dedicated to us.
    console.log('TCP connection established with the server.');
    var code = String.fromCharCode(01);
    // The client can now send data to the server by writing to its socket.
    console.info(client.write(code + 'i20100'));
});

// The client can also receive data from the server by reading from its socket.
client.on('data', function(chunk) {
    var data = chunk.toString('utf8');
    console.log('response', data);
    if (respuesta) {
        respuesta += data;
    } else {
        var respuesta = data;
    }
    
    if (data[data.length - 1].charCodeAt(0) == 3) {
        var indice = 0;
        var fecha = new Date();
        var respuesta = respuesta.slice(17, respuesta.length);
        respuesta = respuesta.split('&&')[0];
        console.info(procesar(respuesta));
    }
    
    // Request an end to the connection after the data has been received.
   client.end();
});

client.on('end', function() {
    console.log('Requested an end to the TCP connection');
});

function procesar(respuesta) {
    var tanque = {
        tanque: respuesta.slice(0,2),
        producto: respuesta.slice(2,3),
        estado: respuesta.slice(3,7),
        campos: []
    }

    var campos = parseInt(respuesta.slice(7,9));

    var inicio = 9;
    var fin = 17;

   for (var i = 0; i < campos; i++) {
        tanque.campos.push(procesarCampo(respuesta.slice(inicio,fin)));
        inicio += 8;
        fin += 8;
    }
    
    if ((fin - 8) < respuesta.length) {
        var respuestas = procesar(respuesta.slice((fin - 8), respuesta.length));
    } else {
        var respuestas = [];
    }

    respuestas.unshift(tanque);
    return respuestas;
}

function procesarCampo(campo) {
    var proceso = '';
    
    if (parseInt(campo) == 0) {
        return 0;
    }

    for (var i = 0; i < campo.length; i++) {
        proceso += hexToBinary(campo[i]);
    }

    var signo = proceso[0] == 0 ? 1 : -1;
    var exponente = parseInt(proceso.slice(1, 9), 2);
    var mantiza = parseInt(proceso.slice(9, 32), 2);

    return signo * Math.pow(2, exponente - 127) * (1 + (mantiza / 8388608));
}

function hexToBinary(digito) {
    var binario = parseInt(digito, 16).toString(2);
    
    while (binario.length < 4) {
        binario = '0' + binario;
    }
    
    return binario;
}