index.js
2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// 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 = '190.15.193.76';
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 + 'i201TT'));
});
// The client can also receive data from the server by reading from its socket.
client.on('data', function(chunk) {
var data = chunk.toString('utf8');
if (respuesta) {
respuesta += data;
} else {
var respuesta = data;
}
if (data[data.length - 1].charCodeAt(0) == 3 && respuesta.slice(1,5) == 'i201') {
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;
}