const WebSocketClient = require('ws'); const config = require('./config/config.json'); const data = require('./data/index')(config.bo); module.exports = knex = require('knex')(config.bo), moment = require('moment'); const client = new WebSocketClient(config.urlHO); var pingTimeout; var tiempoVivo = new Date(); client.on('open', function open() { console.log('conection to socket ho is open'); tiempoVivo = new Date(); client.send(JSON.stringify({ gln: config.gln, action: 'gln'})); client.on('message', function incoming(message) { message = JSON.parse(message.toString('utf8')); switch (message.action) { case 'getEntity': data.getEntity(message).then(function(message) { client.send(JSON.stringify(message)); }); break; case 'comprobante': console.log('recibiendo comprobante') data.guardarComprobante(message.req).then(() => { console.log('se guardó'); message.ok = 1; client.send(JSON.stringify(message)); }).catch((ee) => { console.log('no se guardó' + ee); message.ok = 0; client.send(JSON.stringify(message)); }); break; default: break; } }); heartbeat(); }); client.on('error', function(e) { console.log(e); }); client.on('ping', heartbeat); client.on('close', function clear() { clearTimeout(pingTimeout); }); function heartbeat() { console.log('recibiendo ping'); console.log(`tiempo vivo desde ${tiempoVivo}`); clearTimeout(pingTimeout); // Use `WebSocket#terminate()`, which immediately destroys the connection, // instead of `WebSocket#close()`, which waits for the close timer. // Delay should be equal to the interval at which your server // sends out pings plus a conservative assumption of the latency. pingTimeout = setTimeout(() => { client.terminate(); }, 10000 + 1000); } console.log('Sevice connected to wsServer: ' + config.urlHO);