/** * Este archivo es parte del proyecto EMA Libre. * * Contiene el codigo fuente, cuya funcion principal * es presentar una interfaz interactiva en modo WEB * iniciando un servidor web minimalista y flexible para Node.js * denominado express permitiendo iniciar, detener y visualizar el estado * y los registros de EMA Libre Cliente. * * LICENSE: This file is part of EMA Libre. * EMA Libre 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. * * EMA Libre 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 EMA Libre. If not, see . * * @copyright Copyright (c) 2019 GUGLER (http://www.gugler.com.ar) * @license https://www.gnu.org/licenses/gpl-3.0.html GPL License * @version 3.0 * @link http://www.gugler.com.ar * @since File available since Release 3.0 */ // Librerias o Modulos const express = require('express'); const fsconf = require('fs'); const EMA = require('../core/ema.js'); // Core de EMA. const PORT = process.env.PORT || 8080; // Puerto por defecto. const os = require('os'); var app = express(); var server; // API REST app.get('/salir', function (req, res) { server.close(); res.json(''); //res.sendStatus(200) }); app.get('/plataforma', function (req, res) { const pid = process.pid; const ppid = process.ppid; const plataforma = process.platform; const arquitectura = process.arch; const version_node = process.version; res.json([pid,ppid,plataforma,arquitectura,version_node]); }); app.get('/configGeneralEMA', function (req, res) { var configGeneralEMA = null; configGeneralEMA = eval(fsconf.readFileSync('conf/ConfiguracionGeneral.js')+''); res.json(configGeneralEMA); }); app.get('/configGlobalEMA', function (req, res) { var configGlobalEMA = null; configGlobalEMA = eval(fsconf.readFileSync('conf/ConfiguracionGlobal.js')+''); res.json(configGlobalEMA); }); app.get('/tamanioArchivos', function (req, res) { // Se calcula la Cantidad y tamaño de los Tanques y Debug if (fsconf.existsSync("logs/registro_diario.log")) {var estadoarchivoTD = fsconf.statSync("logs/registro_diario.log"); var TamanioenMegaTD = (estadoarchivoTD.size)/ 1000000.0; }else{var TamanioenMegaTD = 'No Existe';} if (fsconf.existsSync("logs/TanquePendientes.log")) {var estadoarchivoTP = fsconf.statSync("logs/TanquePendientes.log"); var TamanioenMegaTP = (estadoarchivoTP.size)/ 1000000.0; }else{var estadoarchivoTP = 'No Existe';} if (fsconf.existsSync("logs/debug.log")) {var estadoarchivoD = fsconf.statSync("logs/debug.log"); var TamanioenMegaD = (estadoarchivoD.size)/ 1000000.0; }else{var TamanioenMegaD = 'No Existe';} res.json([TamanioenMegaTD.toFixed(2),TamanioenMegaTP.toFixed(2),TamanioenMegaD.toFixed(2)]) }); // EMA_ESTADO si es [true,''] esta encendida, si no [false,'Motivo del error'] app.get('/EMA_Estado', (req, res) => res.json(EMA.Estado())); app.get('/EMA_EstadoUSB', function (req, res) { EMA.EstadoUSB(function(EstadoUSB) { res.json(EstadoUSB); }); }); app.get('/RepeticionesConError', function (req, res) {res.json(EMA.RepeticionesConError());}); app.get('/TiempoActualRecolector', function (req, res) {res.json(EMA.TiempoActualRecolector());}); app.get('/Visor', function (req, res) { var cantreg = 1; EMA.Visor(cantreg, function (error, datos) { if (error != null) { res.json([error,datos]); }else{ res.json([null,datos]); } }); }); app.get('/IncrementarRepeticionesConError', function (req, res) { EMA.Configuracion.RepeticionesConError += 1; // Reinicio el contador de errores al iniciar el servidor web res.json(''); }); app.get('/UltimoPublicado', function (req, res) {res.json(EMA.UltimoPublicado());}); app.get('/UltimoRegistro', function (req, res) {res.json(EMA.UltimoRegistro());}); app.get('/HayPendientes', function (req, res) {res.json(EMA.HayPendientes());}); app.get('/EstadoSensores', function (req, res) {res.json(EMA.EstadoSensores());}); app.get('/iniciar', function (req, res) {EMA.Conectar();res.json('ok'); }); app.get('/detener', function (req, res) {EMA.Detener(); ;res.json('ok'); }); app.get('/purgarDebug', function (req, res) { fsconf.writeFile('logs/debug.log', '',{encoding: 'utf8', autoClose: true}, function(err) { EMA.RegistrarLog("1|PURGADO|Archivo de Debug"); if (err) { EMA.RegistrarLog('0|ERROR|Depurando archivo registro de logs :' + err); } }); res.json('ok'); }); app.get('/purgarPendiente', function (req, res) { fsconf.writeFile('logs/TanquePendientes.log', JSON.stringify([], null, 4),{encoding: 'utf8', autoClose: true}, function(err) { EMA.RegistrarLog("1|PURGADO|Archivo de Pendientes"); if (err) { EMA.RegistrarLog('0|ERROR|Depurando archivo registro de logs :' + err); } }); res.json('ok'); }); app.get('/GuardarConf/:configuracion_nueva', function (req, res) { var configuracion_nueva = '// Configuraciones generales de EMA RECOLECTOR\n\n' + req.params.configuracion_nueva; fsconf.writeFile('./conf/ConfiguracionGeneral.js', configuracion_nueva, function(err) { if( err ){ EMA.RegistrarLog("0|CORE|Upps, existió un problema intentando almacenar la configuración."); } else{ EMA.Reconfigurar(); EMA.RegistrarLog("0|CORE|Se almaceno correctamente la configuración"); } }); res.json('ok'); }); app.get('/VerHistorico', function (req, res) { var Archivo = fsconf.readFileSync('./logs/registro_diario.log', {encoding: 'utf8', autoClose: true}); res.json(Archivo); }); app.get('/verLogs', function (req, res) { var Archivo = fsconf.readFileSync('./logs/debug.log', {encoding: 'utf8', autoClose: true}); res.json(Archivo); }) app.get('/interfaces', (req, res) => { const interfaces = os.networkInterfaces(); res.json(interfaces); }); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); next();}); app.use(express.static('gui_web')); // Bootstrap 4 y librerías necesarias // CSS app.use('/css', express.static(__dirname + '/../node_modules/bootstrap/dist/css')); app.use('/css', express.static(__dirname + '/../node_modules/datatables/media/css')); app.use('/css', express.static(__dirname + '/../node_modules/nprogress')); app.use('/css', express.static(__dirname + '/../node_modules/bootstrap-select/dist/css')); app.use('/css', express.static(__dirname + '/../gui_common/css')); // IMG app.use('/images', express.static(__dirname + '/../node_modules/datatables/media/images')); app.use('/gui_common/iconos', express.static(__dirname + '/../gui_common/iconos')); app.use('/gui_common/img', express.static(__dirname + '/../gui_common/img')); // JS app.use('/js', express.static(__dirname + '/../node_modules/jquery/dist')); app.use('/js', express.static(__dirname + '/../node_modules/popper.js/dist/umd')); app.use('/js', express.static(__dirname + '/../node_modules/bootstrap/dist/js')); app.use('/js', express.static(__dirname + '/../node_modules/bootstrap-select/dist/js')); app.use('/js', express.static(__dirname + '/../node_modules/datatables/media/js')); app.use('/js', express.static(__dirname + '/../node_modules/notify-js-lib/dist')); app.use('/js', express.static(__dirname + '/../node_modules/nprogress')); app.use('/js', express.static(__dirname + '/../node_modules/datatables-buttons/js')); app.use('/js', express.static(__dirname + '/../gui_common/libs/RGraph')); app.use('/controlador', express.static(__dirname + '/../gui_common/controlador')); app.get('/', function (req, res) {res.sendFile(__dirname + "/index.html");}); // Se levanta el puerto function EncenderServidoreIniciar() { // Se espera 5 segundo y se inicia el recolector en modo web server = app.listen(PORT, () => { // Obtener todas las interfaces de red const interfaces = os.networkInterfaces(); console.log("\nServidor disponible en las siguientes direcciones:"); // Recorrer todas las interfaces e IPs for (const interfaceName in interfaces) { interfaces[interfaceName].forEach((interface) => { // Mostrar solo IPv4 y omitir direcciones internas if (interface.family === 'IPv4') { console.log(`http://${interface.address}:${PORT}`); } }); } }); setTimeout(function(){console.log("Se inicio el recolector automaticamente.");EMA.Conectar();}, 5000); } function EncenderServidor() { // Se inicia el servidor solamente server = app.listen(PORT, () => { // Obtener todas las interfaces de red const interfaces = os.networkInterfaces(); console.log("\nServidor disponible en las siguientes direcciones:"); // Recorrer todas las interfaces e IPs for (const interfaceName in interfaces) { interfaces[interfaceName].forEach((interface) => { // Mostrar solo IPv4 y omitir direcciones internas if (interface.family === 'IPv4') { console.log(`http://${interface.address}:${PORT}`); } }); } }); // Se consulta si esta activado el iniciar automaticamente y si es asi, se prende el recolector var configGeneralEMA = null; configGeneralEMA = eval(fsconf.readFileSync('conf/ConfiguracionGeneral.js')+''); IniciarAutomaticamente = configGeneralEMA.ConfGeneral.inicio_automatico; console.log(""); if(IniciarAutomaticamente) { console.log("Configuración de Inicio: "+ IniciarAutomaticamente + " --> Se esta iniciando el recolector automaticamente en 5 segundos..."); setTimeout(function(){EMA.Conectar();}, 5000); } else { console.log("Configuración de Inicio: "+ IniciarAutomaticamente); } } function DetenerServidor() {server.close();} var parametros = process.argv; // Se lee el parametro if (parametros.indexOf('encender') === -1){}else { EncenderServidoreIniciar();} if (parametros.indexOf('iniciar') === -1){}else { EncenderServidor();} if (parametros.indexOf('detener') === -1){}else { DetenerServidor();}