Dejo de trackear carpetas ignoradas

This commit is contained in:
Exequiel Aramburu 2025-11-16 18:06:19 -03:00
parent 1c8c9a36bb
commit ed11169f36
28 changed files with 33431 additions and 504 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules

View File

@ -1,22 +1,28 @@
// Libreria (async () => {
var NwBuilder = require('nw-builder'); try {
// Definiciones // 📦 Cargar la función principal desde nw-builder
var nw = new NwBuilder({ const nwbuild = (await import('nw-builder')).default;
appDir: './src', // COMPILADOR: Directorio de la Aplicacion
files: ['./src/**', '!./src/node_module/mocha/**', '!./src/node_module/chai/**', '!./src/package-lock.json'], // COMPILADOR: Directorio de Codigo Fuente a compilar // 🚀 Configuración del build
platforms: ['linux64'], // COMPILADOR: Plataformas Linux a compilar await nwbuild({
version: '0.94.0', // COMPILADOR: Version del Compilador mode: 'build', // COMPILADOR: Modo 'build' (empaquetar) o 'run' (ejecutar sin empaquetar)
flavor: 'normal', // opciones sdk, normal srcDir: [
buildDir: 'build', // COMPILADOR: Destino de la compilacion. './src/**', // COMPILADOR: Directorio fuente
zip: false, // COMPILADOR: No comprimir (False) '!./src/node_module/mocha/**', // EXCEPCIÓN: Excluir pruebas
appName: 'emalibre' // APLICACION: Nombre de la aplicacion. '!./src/node_module/chai/**',
'!./src/package-lock.json'
],
platform: 'linux', // COMPILADOR: Plataforma de destino
arch: 'x64', // COMPILADOR: Arquitectura de destino
version: '0.94.0', // COMPILADOR: Versión de NW.js a usar
flavor: 'normal', // COMPILADOR: Variante NW.js ('normal' o 'sdk')
outDir: 'build/emalibre', // COMPILADOR: Carpeta de salida
appName: 'emalibre', // APLICACIÓN: Nombre de la app compilada
zip: false, // COMPILADOR: No comprimir
}); });
// Logs
//nw.on('log', console.log);
nw.onLog = console.log;
// Construir
nw.build().then(function () {
console.log('Correcto!'); console.log('Correcto!');
}).catch(function (error) { } catch (error) {
console.error(error); console.error('❌ Error durante la compilación:', error);
}); }
})();

View File

@ -41,9 +41,9 @@ printf "\033[1;4m--->Version de EmaL: $VERSION \033[0m\n"
printf "\033[1;4m--->Version de NWJs: $NWJS_VERSION \033[0m\n" printf "\033[1;4m--->Version de NWJs: $NWJS_VERSION \033[0m\n"
echo "" echo ""
printf "\033[1;10m1) Limpiando compilacion anterior. \033[0m" printf "\033[1;10m1) Limpiando compilacion anterior. \033[0m"
sudo mkdir build/Deb64/usr/bin 2> /dev/null sudo mkdir build/Deb64/usnerando node_modules con NPM del proyr/bin 2> /dev/null
sudo mkdir build/Deb64/usr/share/emalibre 2> /dev/null sudo mkdir build/Deb64/usr/share/emalibre 2> /dev/null
sudo rm -fr build/emalibre/linux64 sudo rm -fr build/emalibre/package.nw/src
sudo rm -fr build/Deb64/usr/bin/* sudo rm -fr build/Deb64/usr/bin/*
sudo rm -fr build/Deb64/usr/share/emalibre/* sudo rm -fr build/Deb64/usr/share/emalibre/*
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
@ -92,13 +92,13 @@ printf "\033[1;10m4) Empaquetando el proyecto emalibre. \033[0m"
CHECK_EMPAQUETADO=`node empaquetarLinux.js | grep "Correcto!" | wc -l` CHECK_EMPAQUETADO=`node empaquetarLinux.js | grep "Correcto!" | wc -l`
if [ "${CHECK_EMPAQUETADO}" -eq "1" ]; then printf "\033[1;32m --> OK. \033[0m\n"; else printf "\033[5;91m --> ERROR. Problema empaquetando con nw-builder. \033[0m\n";exit 1; fi if [ "${CHECK_EMPAQUETADO}" -eq "1" ]; then printf "\033[1;32m --> OK. \033[0m\n"; else printf "\033[5;91m --> ERROR. Problema empaquetando con nw-builder. \033[0m\n";exit 1; fi
printf "\033[1;10m5) Aplicando Permisos al proyecto. \033[0m" printf "\033[1;10m5) Aplicando Permisos al proyecto. \033[0m"
sudo chmod -R 777 build/emalibre/linux64 & spinner "Procesando..." sudo chmod -R 777 build/emalibre/package.nw/src & spinner "Procesando..."
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m6) Eliminando node_modules del proyecto. \033[0m" printf "\033[1;10m6) Eliminando node_modules del proyecto. \033[0m"
sudo rm -fr build/emalibre/linux64/node_modules & spinner "Procesando..." sudo rm -fr build/emalibre/package.nw/src/node_modules & spinner "Procesando..."
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m7) Generando node_modules con NPM del proyecto. \033[0m" printf "\033[1;10m7) Generando node_modules con NPM del proyecto. \033[0m"
cd build/emalibre/linux64 cd build/emalibre/package.nw/src
npm install ---production -no-audit -silent 2> /tmp/ema.log 1> /dev/null npm install ---production -no-audit -silent 2> /tmp/ema.log 1> /dev/null
printf "\033[1;32m --> OK. \033[0m\n"; printf "\033[1;32m --> OK. \033[0m\n";
printf "\033[1;10m8) Se purgan los tanques y logs. \033[0m" printf "\033[1;10m8) Se purgan los tanques y logs. \033[0m"
@ -107,16 +107,16 @@ sudo echo "[]" > logs/TanquePendientes.log
sudo echo "[]" > logs/registro_diario.log sudo echo "[]" > logs/registro_diario.log
printf "\033[1;32m --> OK. \033[0m\n"; printf "\033[1;32m --> OK. \033[0m\n";
printf "\033[1;10m9) Se blanquea el archivo de Configuracion General. \033[0m" printf "\033[1;10m9) Se blanquea el archivo de Configuracion General. \033[0m"
sudo cp ../../conf/ConfiguracionGeneral.js conf/ConfiguracionGeneral.js sudo cp ../../../conf/ConfiguracionGeneral.js conf/ConfiguracionGeneral.js
printf "\033[1;32m --> OK. \033[0m\n"; printf "\033[1;32m --> OK. \033[0m\n";
cd .. cd ..
sudo cp -R linux64 Linux64_nogui # Se copia antes del postLINUX (que implementa NWJS) para el modo consola y web sudo cp -R src src_nogui # Se copia antes del postLINUX (que implementa NWJS) para el modo consola y web
sudo chmod -R 777 Linux64_nogui sudo chmod -R 777 src_nogui
cd linux64 cd src
npm run postLINUX -no-audit -silent 2> /tmp/ema.log 1> /dev/null & spinner "Procesando..." npm run postLINUX -no-audit -silent 2> /tmp/ema.log 1> /dev/null & spinner "Procesando..."
CHECK_NW_NODE_BUILD=`cat /tmp/ema.log | grep "gyp info ok" | wc -l` CHECK_NW_NODE_BUILD=`cat /tmp/ema.log | grep "gyp info ok" | wc -l`
if [ "${CHECK_NW_NODE_BUILD}" -eq "1" ]; then printf "\033[1;32m --> OK. \033[0m\n"; else printf "\033[5;91m --> ERROR. Verifique el modulo NW con node-hid. \033[0m\n";exit 1; fi if [ "${CHECK_NW_NODE_BUILD}" -eq "1" ]; then printf "\033[1;32m --> OK. \033[0m\n"; else printf "\033[5;91m --> ERROR. Verifique el modulo NW con node-hid. \033[0m\n";exit 1; fi
cd ../../.. cd ../../../..
# ************************************************************** # **************************************************************
# Compilar EMA Libre Cliente (Carpincho) en modo GRAFICO Desktop # Compilar EMA Libre Cliente (Carpincho) en modo GRAFICO Desktop
@ -133,7 +133,7 @@ sudo rm -fr build/Deb64/usr/bin/*
sudo rm -fr build/Deb64/usr/share/emalibre/* sudo rm -fr build/Deb64/usr/share/emalibre/*
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m2) Copiando los fuentes de EMA Libre para 64bit. \033[0m" printf "\033[1;10m2) Copiando los fuentes de EMA Libre para 64bit. \033[0m"
sudo cp -R build/emalibre/linux64/* build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/* build/Deb64/usr/share/emalibre/
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m3) Remplazando el archivo de control DEB. \033[0m" printf "\033[1;10m3) Remplazando el archivo de control DEB. \033[0m"
sudo cp -f build/controlDeb/control_linux_gui build/Deb64/DEBIAN/control & spinner "Procesando..." sudo cp -f build/controlDeb/control_linux_gui build/Deb64/DEBIAN/control & spinner "Procesando..."
@ -191,15 +191,15 @@ sudo rm -fr build/Deb64/usr/bin/*
sudo rm -fr build/Deb64/usr/share/emalibre/* sudo rm -fr build/Deb64/usr/share/emalibre/*
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m2) Copiando los fuentes de EMA Libre para 64bit. \033[0m" printf "\033[1;10m2) Copiando los fuentes de EMA Libre para 64bit. \033[0m"
sudo cp -R build/emalibre/Linux64_nogui/core build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/core build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/logs build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/logs build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/conf build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/conf build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/tmp build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/tmp build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/node_modules build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/node_modules build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/CHANGELOG build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/CHANGELOG build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/COPYING build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/COPYING build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/AUTHORS build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/AUTHORS build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/package.json build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/package.json build/Deb64/usr/share/emalibre/
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m3) Remplazando el archivo de control DEB. \033[0m" printf "\033[1;10m3) Remplazando el archivo de control DEB. \033[0m"
sudo cp -f build/controlDeb/control_linux_console build/Deb64/DEBIAN/control & spinner "Procesando..." sudo cp -f build/controlDeb/control_linux_console build/Deb64/DEBIAN/control & spinner "Procesando..."
@ -239,17 +239,17 @@ sudo rm -fr build/Deb64/usr/bin/*
sudo rm -fr build/Deb64/usr/share/emalibre/* sudo rm -fr build/Deb64/usr/share/emalibre/*
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m2) Copiando los fuentes de EMA Libre para 64bit. \033[0m" printf "\033[1;10m2) Copiando los fuentes de EMA Libre para 64bit. \033[0m"
sudo cp -R build/emalibre/Linux64_nogui/core build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/core build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/logs build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/logs build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/conf build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/conf build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/gui_web build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/gui_web build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/gui_common build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/gui_common build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/tmp build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/tmp build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/node_modules build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/node_modules build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/CHANGELOG build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/CHANGELOG build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/COPYING build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/COPYING build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/AUTHORS build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/AUTHORS build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/package.json build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/package.nw/src_nogui/package.json build/Deb64/usr/share/emalibre/
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m3) Remplazando el archivo de control DEB. \033[0m" printf "\033[1;10m3) Remplazando el archivo de control DEB. \033[0m"
sudo cp -f build/controlDeb/control_linux_web build/Deb64/DEBIAN/control & spinner "Procesando..." sudo cp -f build/controlDeb/control_linux_web build/Deb64/DEBIAN/control & spinner "Procesando..."
@ -264,7 +264,7 @@ sudo chown -R root:root build/Deb64
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
cd build cd build
printf "\033[1;10m7) Generando Paquete Deb para Web 64bit Linux. \033[0m\n" printf "\033[1;10m7) Generando Paquete Deb para Web 64bit Linux. \033[0m\n"
sudo dpkg -b Deb64 debs/"emalibre-web-linux_$VERSION.deb" sudo dpkg -b Deb64 demalibreebs/"emalibre-web-linux_$VERSION.deb"
printf "\033[5;10m Finalizo con exito, build/debs/emalibre-console-linux_$VERSION.deb. \033[0m" printf "\033[5;10m Finalizo con exito, build/debs/emalibre-console-linux_$VERSION.deb. \033[0m"
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m8) Limpiando archivos temporales. \033[0m" printf "\033[1;10m8) Limpiando archivos temporales. \033[0m"

3425
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,10 @@
"main": "CompilarEmaLibreWindows.js", "main": "CompilarEmaLibreWindows.js",
"name": "emalibre", "name": "emalibre",
"description": "EMA Compilador", "description": "EMA Compilador",
"version": "1.35.0", "version": "1.36.0",
"type": "module",
"author": "Laboratorio de Investigacion Gugler",
"homepage": "https://ema.gugler.com.ar",
"window": { "window": {
"frame": false, "frame": false,
"toolbar": false "toolbar": false
@ -19,14 +22,14 @@
], ],
"scripts": { "scripts": {
"test": "mocha --exit|| true", "test": "mocha --exit|| true",
"global": "npm i -g nw-gyp nw@0.94.0-sdk", "global": "npm i -g nw-gyp nw@0.101.0-sdk",
"nw_rebuild_linux": "nw-gyp rebuild --target=0.94.0 --verbose --arch=x64 --directory=src/node_modules/node-hid", "nw_rebuild_linux": "nw-gyp rebuild --target=0.101.0 --verbose --arch=x64 --directory=src/node_modules/node-hid",
"nw_rebuild_windows": "nw-gyp rebuild --target=0.94.0 --verbose --arch=x64 --directory=src/node_modules/node-hid", "nw_rebuild_windows": "nw-gyp rebuild --target=0.101.0 --verbose --arch=x64 --directory=src/node_modules/node-hid",
"nw_rebuild_arm": "nw-gyp rebuild --target=0.28.4 --verbose --arch=arm --directory=src/node_modules/node-hid" "nw_rebuild_arm": "nw-gyp rebuild --target=0.28.4 --verbose --arch=arm --directory=src/node_modules/node-hid"
}, },
"devDependencies": { "devDependencies": {
"chai": "^4.3.4", "chai": "^4.3.4",
"mocha": "^8.3.2", "mocha": "^8.3.2",
"nw-builder": "^3.5.7" "nw-builder": "^4.13.16"
} }
} }

View File

@ -6,10 +6,10 @@ Desarrollado por el Laboratorio de Investigación Gugler perteneciente a la Facu
de Ciencia y Tecnología de la Universidad Autónoma de Entre Ríos. A continuación de Ciencia y Tecnología de la Universidad Autónoma de Entre Ríos. A continuación
se detalla la lista de colaboradores y desarrolladores: se detalla la lista de colaboradores y desarrolladores:
Exequiel Aramburu <exequiel@gugler.com.ar>. Exequiel Aramburu <aramburu.exequiel@uader.edu.ar>.
José Luis Mengarelli <jlmenga@gugler.com.ar>. José Luis Mengarelli <mengarelli.joseluis@uader.edu.ar>.
Federico Bonnet <federico@gugler.com.ar>. Federico Bonnet <bonnet.federico@uader.edu.ar>.
Alexis Sostersich <alexis@gugler.com.ar>. Alexis Sostersich <sostersich.alexis@uader.edu.ar>.
Marcos Elias Rios Nuñez <marcos@gugler.com.ar>. Marcos Elias Rios Nuñez <marcos@gugler.com.ar>.
Se agradece a la Facultad de Ciencia y Tecnología de la Universidad Autónoma de Entre Ríos Se agradece a la Facultad de Ciencia y Tecnología de la Universidad Autónoma de Entre Ríos

View File

@ -1,3 +1,19 @@
** Versión 1.36: (Julio 10 , 2025)
+ Se incorporó recolectar por WIFI/IP.
+ Mejoras menores de estilo(ej:iconos en logs).
+ Se actualizó la funcion de registrar logs para que solo
registre en el nivel parametrizado (1-9), los 0 se registran siempre.
+ Se mantiene la versión de nwjs por compatibilidad con node-hid.
+ Se actualizó la versión de :
RGraph 6.20 → 6.22
bootstrap 4.5.3 → 4.6.2
express 4.21.2 → 5.1.0
forever 3.0.4 → 4.0.3
node 15.10.0 → 24.4.0
node-hid 1.3.1 → 2.2.0
nodemailer 6.10.1 → 7.0.5
terminal-kit 2.11.7 → 3.1.2
** Versión 1.35: (Diciembre 10 , 2024) ** Versión 1.35: (Diciembre 10 , 2024)
+ Se actualizó la versión de nwjs → 0.94.0 + Se actualizó la versión de nwjs → 0.94.0
+ Se actualizó la versión de node → 22.07.0. + Se actualizó la versión de node → 22.07.0.

View File

@ -0,0 +1,31 @@
// Configuraciones generales de EMA RECOLECTOR
module.exports = {
"ConfGeneral": {
"Tiempo_de_Recoleccion": 10,
"UTC": -3,
"SistemaMetrico": "SI",
"debug": 6,
"debugTamanio": 10,
"NombreEstacion": "pepe",
"Modo": "Recolector_IP",
"Llave_R": "e5303ab3-2a8b-4d42-90ab-1c8367d8521d",
"inicio_automatico": false,
"Audio": false,
"notificar_cambios": true,
"audioVoces": "Sin Voces",
"IP": "192.168.1.220",
"Puerto": "5000",
"Ruta": "/datos"
},
"ConfEmail": {
"ActivarCorreos": false,
"ReceptorEmail": "exe",
"Servicio": "Deshabilitado",
"Usuario": "",
"Password": "",
"Server": "",
"Puerto": ""
},
"ConfPublicador": []
};

View File

@ -0,0 +1,8 @@
// Configuraciones globales de EMA RECOLECTOR // No Parametrizables.
module.exports = {
'ConfGlobal': {
'Version': 1.36,
'Nombre': 'EMA Libre Cliente'
}
};

View File

@ -40,9 +40,17 @@ const fs = require('fs'); // Libreria fs para el manejo de archivos.
const util = require('util'); // Utilidades. const util = require('util'); // Utilidades.
var Guardar = []; // Tanque diario de registros leidos (para acumulados). var Guardar = []; // Tanque diario de registros leidos (para acumulados).
var versionEMA = configGlobalEMA.ConfGlobal.Nombre + ' v' + configGlobalEMA.ConfGlobal.Version; var versionEMA = configGlobalEMA.ConfGlobal.Nombre + ' v' + configGlobalEMA.ConfGlobal.Version;
const http = require('http');
const https = require('https');
var DatosRecolectadosAnterior = []; // Datos recolectados de la estacion meteorologica.
APP = module.exports = { APP = module.exports = {
Configuracion: { Configuracion: {
Modo: configGeneralEMA.ConfGeneral.Modo, // Modo de funcionamiento de EMA.
Puerto: configGeneralEMA.ConfGeneral.Puerto, // Puerto de comunicacion.
IP: configGeneralEMA.ConfGeneral.IP, // IP de comunicacion.
Patch: configGeneralEMA.ConfGeneral.Ruta, // Ruta de comunicacion.
debug: configGeneralEMA.ConfGeneral.debug, // Se obtiene el nivel de debug del archivo de Conf General. debug: configGeneralEMA.ConfGeneral.debug, // Se obtiene el nivel de debug del archivo de Conf General.
utc: configGeneralEMA.ConfGeneral.UTC, // Se obtiene la fecha en formato UTC del archivo de Conf General. utc: configGeneralEMA.ConfGeneral.UTC, // Se obtiene la fecha en formato UTC del archivo de Conf General.
Errores: '', // Errores detectado en el funcionamiento de EMA. Errores: '', // Errores detectado en el funcionamiento de EMA.
@ -67,6 +75,9 @@ APP = module.exports = {
tempAlmacenadoPendientes: [] // Ultimo Registro de las Redes Publicadas. tempAlmacenadoPendientes: [] // Ultimo Registro de las Redes Publicadas.
}, },
RegistrarLog: function (reg, depurar) { RegistrarLog: function (reg, depurar) {
let nivel = reg.split('|')[0];
// Si el nivel de debug es mayor o igual al configurado, se registra.
if(APP.Configuracion.debug >= nivel) {
if (typeof depurar !== 'undefined') { depurar = false; } if (typeof depurar !== 'undefined') { depurar = false; }
// se convierte la fecha a la UTC parametrizada // se convierte la fecha a la UTC parametrizada
var d = new Date(); var d = new Date();
@ -94,21 +105,23 @@ APP = module.exports = {
encoding: 'utf8', encoding: 'utf8',
autoClose: true autoClose: true
}, function (err) { }, function (err) {
if (err) { APP.RegistrarLog('0|ERROR|Depurando archivo registro de logs :' + err); } if (err) { APP.RegistrarLog('0|ERROR| 🔴 Depurando archivo registro de logs :' + err); }
APP.RegistrarLog('0|PURGADO|Depurando automaticamente archivo registro de logs.'); APP.RegistrarLog('0|PURGADO| 🔴 Depurando automaticamente archivo registro de logs.');
}); });
} else { } else {
// GUARDA LOS REGISTROS DE LOGS // GUARDA LOS REGISTROS DE LOGS
fs.appendFile('./logs/debug.log', registrologs, { fs.appendFile('./logs/debug.log', registrologs, {
encoding: 'utf8', encoding: 'utf8',
autoClose: true autoClose: true
}, function (err) { }, function (err) {
if (err) { if (err) {
APP.RegistrarLog('0|ERROR|Guardando registro de logs en archivo :' + err); APP.RegistrarLog('0|ERROR| 🔴 Guardando registro de logs en archivo :' + err);
} }
}); });
} }
registrologs=null;fecha=null;dia=null;mes=null;segundos=null;minutos=null;horas=null;fechaHora=null;utc=null;d=null; registrologs=null;fecha=null;dia=null;mes=null;segundos=null;minutos=null;horas=null;fechaHora=null;utc=null;d=null;
}
}, },
RepeticionesConError: function () { RepeticionesConError: function () {
return APP.Configuracion.RepeticionesConError; return APP.Configuracion.RepeticionesConError;
@ -125,22 +138,36 @@ APP = module.exports = {
} }
}, },
EstadoUSB: function (callback) { EstadoUSB: function (callback) {
try{ callback(recolector.status()); }catch(e){APP.RegistrarLog('0|CORE|Error: '+e);return false;} try{ callback(recolector.status()); }catch(e){APP.RegistrarLog('0|CORE|🔴 Error: '+e);return false;}
}, },
Salir: function () { Salir: function () {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|SALIR: Se cerro el core de EMA LIBRE. Hasta luego!!!.'); APP.RegistrarLog('0|CORE|SALIR: Se cerro el core de EMA LIBRE. Hasta luego!!!.');
if (configGeneralEMA.ConfEmail.ActivarCorreos === true) Correo.EnviarEmail(configGeneralEMA,'EMA - OFFLINE', '<b>Estimado</b>,<br><br> Le informamos que la estación <b>' + configGeneralEMA.ConfGeneral.NombreEstacion + '</b> se detuvo y se cerro el software EMA LIBRE.<br><br>Saludos Cordiales.'); if (configGeneralEMA.ConfEmail.ActivarCorreos === true) Correo.EnviarEmail(configGeneralEMA,'EMA - OFFLINE', '<b>Estimado</b>,<br><br> Le informamos que la estación <b>' + configGeneralEMA.ConfGeneral.NombreEstacion + '</b> se detuvo y se cerro el software EMA LIBRE.<br><br>Saludos Cordiales.');
APP.Configuracion.Errores = 'Se Salio del Recolector'; APP.Configuracion.Errores = 'Se Salio del Recolector';
}, },
Detener: function () { Detener: function () {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|DETENER: Se detiene el recolector de EMA LIBRE.'); APP.RegistrarLog('0|CORE|DETENER: Se detiene el recolector de EMA LIBRE.');
APP.Configuracion.RunTime = 0; APP.Configuracion.RunTime = 0;
APP.Configuracion.Errores = 'Se detuvo manualmente el Recolector'; APP.Configuracion.Errores = 'Se detuvo manualmente el Recolector';
APP.LimpiarM(); APP.LimpiarM();
if(APP.Configuracion.Modo === 'Recolector_IP')
{
let PORT = APP.Configuracion.Puerto;
let HOST = APP.Configuracion.IP;
http.get(`http://${HOST}:${PORT}/detener_servidor`, (res) => {
res.on('data', (chunk) => {
});
res.on('end', () => {
APP.RegistrarLog('0|CORE| Petición de apagado enviada correctamente.');
});
}).on('error', (err) => {
APP.RegistrarLog('0|CORE| ❌ Error al enviar petición');
});
}
}, },
Reconfigurar: function () { Reconfigurar: function () {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|RECONFIGURANDO: Se reconfigura el recolectorde EMA LIBRE.'); APP.RegistrarLog('0|CORE|RECONFIGURANDO: Se reconfigura el recolectorde EMA LIBRE.');
if (configGeneralEMA.ConfEmail.ActivarCorreos === true) Correo.EnviarEmail(configGeneralEMA,'EMA - CONFIG', '<b>Estimado</b>,<br><br> Le informamos que se modificó la configuración de la estación <b>' + configGeneralEMA.ConfGeneral.NombreEstacion + '</b>.<br><br>Saludos Cordiales.'); if (configGeneralEMA.ConfEmail.ActivarCorreos === true) Correo.EnviarEmail(configGeneralEMA,'EMA - CONFIG', '<b>Estimado</b>,<br><br> Le informamos que se modificó la configuración de la estación <b>' + configGeneralEMA.ConfGeneral.NombreEstacion + '</b>.<br><br>Saludos Cordiales.');
APP.Configuracion.TiempoContinuo = configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion; APP.Configuracion.TiempoContinuo = configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion;
APP.Configuracion.debug = configGeneralEMA.ConfGeneral.debug; APP.Configuracion.debug = configGeneralEMA.ConfGeneral.debug;
@ -149,14 +176,14 @@ APP = module.exports = {
Iniciar: function () { Iniciar: function () {
APP.RegistrarLog('0|CORE|INICIAR:Iniciando.'); APP.RegistrarLog('0|CORE|INICIAR:Iniciando.');
if (APP.Configuracion.Run === 1 && APP.Configuracion.RunTime === 0) { if (APP.Configuracion.Run === 1 && APP.Configuracion.RunTime === 0) {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|INICIAR: Se inicio el recolector de EMA LIBRE.'); APP.RegistrarLog('0|CORE|INICIAR: Se inicio el recolector de EMA LIBRE.');
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|DEBUG: ' + APP.Configuracion.debug); APP.RegistrarLog('0|CORE|DEBUG: ' + APP.Configuracion.debug);
APP.Configuracion.RunTime = 1; APP.Configuracion.RunTime = 1;
APP.Continuo(); if(APP.Configuracion.Modo != 'Recolector_IP') APP.Continuo();
} else { } else {
APP.RegistrarLog('0|CORE|Hay un proceso corriendo, se elimina.'); APP.RegistrarLog('0|CORE|Hay un proceso corriendo, se elimina.');
APP.LimpiarM(); APP.LimpiarM();
APP.Continuo(); if(APP.Configuracion.Modo != 'Recolector_IP') APP.Continuo();
} }
}, },
LimpiarM: function () { LimpiarM: function () {
@ -177,7 +204,7 @@ APP = module.exports = {
autoClose: true autoClose: true
}, (err) => { }, (err) => {
if (err) { if (err) {
APP.RegistrarLog('1|ERROR: Guardando registro diario en archivo :' + err); APP.RegistrarLog('1|ERROR: 🔴 Guardando registro diario en archivo :' + err);
} }
}); });
}, },
@ -199,6 +226,7 @@ APP = module.exports = {
} }
}, },
UltimoRegistro: function () { UltimoRegistro: function () {
if (typeof APP.Configuracion.UltimoRegistro !== 'undefined' && APP.Configuracion.UltimoRegistro !== '') { if (typeof APP.Configuracion.UltimoRegistro !== 'undefined' && APP.Configuracion.UltimoRegistro !== '') {
return APP.Configuracion.UltimoRegistro; return APP.Configuracion.UltimoRegistro;
} else { } else {
@ -230,6 +258,260 @@ APP = module.exports = {
// Metodo para conectar/verificar la conexion USB de la EMA USB. // Metodo para conectar/verificar la conexion USB de la EMA USB.
Conectar: function () { Conectar: function () {
try { try {
if(APP.Configuracion.Modo === 'Recolector_IP'){
APP.RegistrarLog('0|CORE|Estableciendo Time Zone UTC ' + configGeneralEMA.ConfGeneral.UTC);
APP.RegistrarLog('0|CORE|Verificando Estado de la EMA...');
APP.RegistrarLog('0|CORE| 🟢 Iniciando el Modo Recolector por IP/WIFI.');
APP.Configuracion.TiempoContinuo = configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion;
APP.Configuracion.debug = configGeneralEMA.ConfGeneral.debug;
// se levanta el puerto para escuchar las peticiones al puerto indicado.
// const url = require('url'); // para parsear req.url
const PORT = APP.Configuracion.Puerto;
const HOST = APP.Configuracion.IP;
const RUTA = APP.Configuracion.Patch; // e.g., "/datos"
const server = http.createServer((req, res) => {
//const parsedUrl = url.parse(req.url, true);
//const pathname = parsedUrl.pathname.toLowerCase();
//const method = req.method.toUpperCase();
//const ip = req.socket.remoteAddress.replace('::ffff:', '');
const base = `http://${HOST}:${PORT}`;
let urlRaw = req.url;
// Si la ruta empieza con "/xxxx" y no tiene "?" pero sí "&", agregamos "?"
if (urlRaw.startsWith(RUTA) && !urlRaw.includes('?') && urlRaw.includes('&')) {
urlRaw = urlRaw.replace(RUTA, RUTA + '?');
}
const myURL = new URL(urlRaw, base);
const pathname = myURL.pathname.toLowerCase();
const method = req.method.toUpperCase();
const ip = req.socket.remoteAddress.replace('::ffff:', '');
APP.RegistrarLog('0|CORE| 📥 Recepcion de datos origen ' + ip + ' metodo ' + method + ' ruta ' + pathname);
//Para detener el servidor
if (pathname === '/detener_servidor') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Servidor detenido');
APP.RegistrarLog('0|CORE| 🔴 Servidor detenido por botón');
server.close(() => {
});
}
//Para recibir la información de la estacion WIFI/IP
if (pathname === RUTA) {
if (method === 'GET') {
let Vector = Object.fromEntries(myURL.searchParams.entries());
// se convierte la fecha a la UTC parametrizada
var d = new Date();
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var db = new Date(utc + (3600000 * (APP.Configuracion.utc))); // UTC - Configurado
var dbutc = new Date(utc); // UTC Pura
// Se da formato a la fecha y hora
var minutos = db.getMinutes();
if (minutos <= 9) { minutos = '0' + minutos; }
var hora = db.getHours();
if (hora <= 9) { hora = '0' + hora; }
var mes = db.getMonth() + 1;
if (mes <= 9) { mes = '0' + mes; }
var dia = db.getDate();
if (dia <= 9) { dia = '0' + dia; }
var segundo = db.getSeconds();
if (segundo <= 9) { segundo = '0' + segundo; }
var fecha = dia + '/' + mes + '/' + db.getFullYear() + ' ' + hora + ':' + minutos + ':' + segundo;
var fechaISO = db.getFullYear() + '-' + mes + '-' + dia + 'T' + hora + ':' + minutos + ':' + segundo;
dia = null;
mes = null;
hora = null;
minutos = null;
segundo = null;
db = null;
utc = null;
d = null;
// UTC PURA
var minutost = dbutc.getMinutes();
if (minutost <= 9) { minutost = '0' + minutost; }
var horat = dbutc.getHours();
if (horat <= 9) { horat = '0' + horat; }
var mest = dbutc.getMonth() + 1;
if (mest <= 9) { mest = '0' + mest; }
var diat = dbutc.getDate();
if (diat <= 9) { diat = '0' + diat; }
var segundot = dbutc.getSeconds();
if (segundot <= 9) { segundot = '0' + segundot; }
var fechaUTC = dbutc.getFullYear() + '-' + mest + '-' + diat + '+' + horat + ':' + minutost + ':' + segundot;
diat = null;
mest = null;
horat = null;
minutost = null;
segundot = null;
dbutc = null;
let TemperaturaExternaC = ((parseFloat(Vector['tempf']) - 32) * 5 / 9).toFixed(2);
let TemperaturaInternaC = ((parseFloat(Vector['indoortempf']) - 32) * 5 / 9).toFixed(2);
let vientoEnKm = (parseFloat(Vector['windspeedmph']) * 1.60934);
let rafagaEnKm = (parseFloat(Vector['windgustmph']) * 1.60934);
let luxerIntencidad = Vector['solarradiation'] * 683; // luxerIntencidad en Luxer
let PresionR = (parseFloat(Vector['baromin']) * 33.8639).toFixed(2);
let PresionA = (parseFloat(Vector['absbaromin']) * 33.8639).toFixed(2);
let x = Vector['winddir'];
// direccion del viento por nombre
switch (true) {
case x === 0:
VientoDireccion = 'Norte';
break;
case x > 0 && x < 90:
VientoDireccion = 'Nordeste';
break;
case x === 90:
VientoDireccion = 'Este';
break;
case x > 90 && x < 180:
VientoDireccion = 'Sudeste';
break;
case x === 180:
VientoDireccion = 'Sur';
break;
case x > 180 && x < 270:
VientoDireccion = 'Sudoeste';
break;
case x === 270:
VientoDireccion = 'Oeste';
break;
case x > 270 && x < 360:
VientoDireccion = 'Noroeste';
break;
default:
VientoDireccion = 'N/A';
}
x = null;
let DatosRecolectados = [
fecha, // *0: Fecha local
fechaISO, // *1: Fecha ISO
parseFloat(TemperaturaExternaC), // *2: Temperatura exterior
parseFloat(TemperaturaInternaC), // *3: Temperatura interior
parseFloat(Vector['humidity']), // *4: Humedad exterior
parseFloat(Vector['indoorhumidity']), // *5: Humedad interior
luxerIntencidad, // *6: Luz Intencidad en Klux
parseFloat(Vector['UV']), // *7: Radiación UV
vientoEnKm, // *8: Velocidad viento
rafagaEnKm, // *9: Ráfaga
parseFloat(Vector['winddir']), // *10: Dirección viento (grados)
VientoDireccion, // *11: Dirección viento (nombre)
parseFloat(PresionA), // *12: Presión absoluta hpa
parseFloat(PresionR), // *13: Presión relativa hpa
parseFloat(Vector['totalrainin']), // *14: Lluvia acumulada
parseFloat(Vector['dewptf']), // *15: Punto de rocío
fechaUTC, // *16: UTC desde 'dateutc'
Vector['lowbatt'] // *17: Estado batería
];
const Etiquetas = [
'Fecha local',
'Fecha ISO',
'Temperatura exterior (°C)',
'Temperatura interior (°C)',
'Humedad exterior (%)',
'Humedad interior (%)',
'Luz (kLux)',
'Radiación UV',
'Viento (km/h)',
'Ráfaga (km/h)',
'Dirección viento (°)',
'Dirección viento (nombre)',
'Presión absoluta (hpa)',
'Presión relativa (hpa)',
'Lluvia total (in)',
'Punto de rocío (°F)',
'Fecha UTC',
'Batería Baja (0-No/1-Si)'
];
// Se verifican cambios
if (DatosRecolectadosAnterior.length < 1) { DatosRecolectadosAnterior = DatosRecolectados;}
let cambios = {};
let bandera_cambios = false;
for (let i = 0; i < DatosRecolectados.length; i++) {
if ( i === 0 || i === 1 || i === 16) continue; // ignorar índices 0, 1 y 16 que son fechas
if (DatosRecolectados[i] !== DatosRecolectadosAnterior[i]) {
bandera_cambios = true;
cambios[Etiquetas[i]] = {
valorAnterior: DatosRecolectadosAnterior[i],
valorNuevo: DatosRecolectados[i]
};
}
}
//cambios = JSON.stringify(cambios, null, 2);
DatosRecolectados.forEach((dato, i) => {
APP.RegistrarLog(`5|REGISTRO|${i} - ${Etiquetas[i]}: ${dato}`);
});
// ACA SE ENVIA AL VALIDADOR Y A LAS REDES CONFIGURADAS
var Datos = [];
Datos = ['validar', DatosRecolectados,cambios,bandera_cambios];
Validador.Registros(Datos, function (errorvalidador, estadovalidador)
{
if (estadovalidador === true) {
APP.Configuracion.Repeticiones += 1;
APP.Configuracion.RepeticionesConError = 0;
APP.Configuracion.TiempoMaximo = 0;
APP.Configuracion.TiempoFueraDeLinea = 0;
APP.Configuracion.FechaLanzadoTimeout = Date.now();
APP.Registro_Diario(Datos[1],cambios,bandera_cambios);
APP.Publicar_en_Redes();
Datos = null;
} else {
APP.Configuracion.Repeticiones = 0;
APP.Configuracion.Estado_Val_Ant = errorvalidador[0];
APP.RegistrarLog('0|VALIDADOR|Datos recolectados incorrectos: ' + errorvalidador[1]);
Datos = null;
} });
APP.Configuracion.EstadoSensores = DatosRecolectados[17];
DatosRecolectadosAnterior = DatosRecolectados; // Guardar los datos recolectados para la proxima vez.
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Datos GET recibidos');
} else if (method === 'POST' || method === 'PATCH') {
let body = '';
req.on('data', chunk => { body += chunk.toString(); });
req.on('end', () => {
const formData = querystring.parse(body);
APP.RegistrarLog('Datos formulario:', formData);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Datos POST/PATCH recibidos');
});
} else {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Método no permitido');
}
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Ruta no encontrada');
}
});
server.listen(PORT, HOST, () => {
APP.RegistrarLog(`0|CORE| 🟢 Servidor escuchando en ${HOST}:${PORT}`);
APP.Configuracion.Errores = `🟢 Servidor escuchando en ${HOST}:${PORT}`;
APP.Configuracion.TiempoMaximo = 0;
APP.Configuracion.Run = 1;
APP.Iniciar(); // Se llama a la funcion INICIO
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
APP.RegistrarLog(`0|CORE| ❌ Error: El puerto ${PORT} ya está en uso.`);
APP.Configuracion.Errores = '❌ Error el puerto ya está en uso.';
} else if (err.code === 'EACCES') {
APP.RegistrarLog(`0|CORE| ❌ Error: Permiso denegado para usar el puerto ${PORT}.`);
APP.Configuracion.Errores = '❌ Permiso denegado para usar el puerto.';
} else {
APP.RegistrarLog(`0|CORE| ❌ Error al iniciar servidor: ${err.message}`);
APP.Configuracion.Errores = '❌ Error al iniciar servidor.';
}
});
}else{
APP.RegistrarLog('0|CORE|Estableciendo Time Zone UTC ' + configGeneralEMA.ConfGeneral.UTC); APP.RegistrarLog('0|CORE|Estableciendo Time Zone UTC ' + configGeneralEMA.ConfGeneral.UTC);
APP.RegistrarLog('0|CORE|Verificando Estado de la EMA...'); APP.RegistrarLog('0|CORE|Verificando Estado de la EMA...');
APP.Configuracion.TiempoContinuo = configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion; APP.Configuracion.TiempoContinuo = configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion;
@ -247,19 +529,19 @@ APP = module.exports = {
APP.Configuracion.Run = 0; APP.Configuracion.Run = 0;
throw new Error('Problemas con el USB, por favor desconecte y conecte el mismo.'); throw new Error('Problemas con el USB, por favor desconecte y conecte el mismo.');
} else { } else {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|Info de Estado: Fuera de Linea.'); APP.RegistrarLog('0|CORE|Info de Estado: Fuera de Linea.');
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|Info de Detalle: EMA no conectada.'); APP.RegistrarLog('0|CORE|Info de Detalle: EMA no conectada.');
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|Info de Acción: Verifique la conexion USB de la EMA.'); APP.RegistrarLog('0|CORE|Info de Acción: Verifique la conexion USB de la EMA.');
APP.Configuracion.Errores = 'Se espera ' + APP.Configuracion.TiempoContinuo + ' segundos y se prueba conectar nuevamente.'; APP.Configuracion.Errores = 'Se espera ' + APP.Configuracion.TiempoContinuo + ' segundos y se prueba conectar nuevamente.';
throw new Error('Problemas con la lectura USB'); throw new Error('Problemas con la lectura USB');
} }
} else { } else {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|ESTADO: Online'); APP.RegistrarLog('0|CORE|ESTADO: Online');
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|PLATAFORMA: ' + recolector.conf.plataforma); APP.RegistrarLog('0|CORE|PLATAFORMA: ' + recolector.conf.plataforma);
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|AUTOR:Gugler Lab'); APP.RegistrarLog('0|CORE|AUTOR:Gugler Lab');
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|VERSION:' + configGlobalEMA.ConfGlobal.Version); APP.RegistrarLog('0|CORE|VERSION:' + configGlobalEMA.ConfGlobal.Version);
if (APP.Configuracion.Run === 0) { if (APP.Configuracion.Run === 0) {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|INICIAR: Se inicio el motor de EMA LIBRE.'); APP.RegistrarLog('0|CORE|🟢 Se inicio el motor de EMA LIBRE.');
APP.Configuracion.Errores = 'CORE: INICIAR-> Se inicio el motor de EMA LIBRE.'; APP.Configuracion.Errores = 'CORE: INICIAR-> Se inicio el motor de EMA LIBRE.';
APP.Configuracion.Run = 1; APP.Configuracion.Run = 1;
} }
@ -275,12 +557,13 @@ APP = module.exports = {
throw new Error('Conexión usb no detectada, se desconectó en funcionamiento.'); throw new Error('Conexión usb no detectada, se desconectó en funcionamiento.');
} }
} }
}
} catch (ex) { } catch (ex) {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|EXCEP|Información de la excepcion: -> ' + ex + ''); APP.RegistrarLog('0|EXCEP|Información de la excepcion: -> ' + ex + '');
APP.Configuracion.Errores = 'EXCEP: Información de la excepcion: -> ' + ex; APP.Configuracion.Errores = 'EXCEP: Información de la excepcion: -> ' + ex;
var tiempo = (APP.Configuracion.TiempoMaximo + APP.Configuracion.TiempoContinuo) * 1000; var tiempo = (APP.Configuracion.TiempoMaximo + APP.Configuracion.TiempoContinuo) * 1000;
APP.Configuracion.TiempoFueraDeLinea += tiempo; APP.Configuracion.TiempoFueraDeLinea += tiempo;
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|EXCEP|Se espera ' + (tiempo / 1000) + ' segundos y se prueba conectar nuevamente ....'); APP.RegistrarLog('0|EXCEP|Se espera ' + (tiempo / 1000) + ' segundos y se prueba conectar nuevamente ....');
APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Conectar, tiempo)); APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Conectar, tiempo));
tiempo=null; tiempo=null;
} }
@ -302,8 +585,8 @@ APP = module.exports = {
} }
APP.RegistrarLog('1|MAIL|Se envio correo notificando que la estacion ' + configGeneralEMA.ConfGeneral.NombreEstacion + ' se encuentra fuera de linea por mas de: ' + (APP.Configuracion.TiempoFueraDeLinea / 1000) + 's o ' + (APP.Configuracion.TiempoFueraDeLinea / 1000 / 60).toFixed(2) + ' minutos'); APP.RegistrarLog('1|MAIL|Se envio correo notificando que la estacion ' + configGeneralEMA.ConfGeneral.NombreEstacion + ' se encuentra fuera de linea por mas de: ' + (APP.Configuracion.TiempoFueraDeLinea / 1000) + 's o ' + (APP.Configuracion.TiempoFueraDeLinea / 1000 / 60).toFixed(2) + ' minutos');
} }
if (APP.Configuracion.debug > -1) APP.RegistrarLog('1|ERROR|' + err + '.'); APP.RegistrarLog('1|ERROR| 🔴 ' + err + '.');
if (APP.Configuracion.debug > -1) APP.RegistrarLog('1|ERROR|Se espera ' + (tiempo / 1000) + ' segundos ( Tiempo fuera de linea: ' + (APP.Configuracion.TiempoFueraDeLinea / 1000) + 's o ' + (APP.Configuracion.TiempoFueraDeLinea / 1000 / 60).toFixed(2) + ' minutos), luego se intenta iniciar el recolector.'); APP.RegistrarLog('1|ERROR| 🔴 Se espera ' + (tiempo / 1000) + ' segundos ( Tiempo fuera de linea: ' + (APP.Configuracion.TiempoFueraDeLinea / 1000) + 's o ' + (APP.Configuracion.TiempoFueraDeLinea / 1000 / 60).toFixed(2) + ' minutos), luego se intenta iniciar el recolector.');
APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Conectar, tiempo)); APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Conectar, tiempo));
tiempo = null; tiempo = null;
}); });
@ -314,7 +597,7 @@ APP = module.exports = {
if (APP.Configuracion.BanderaPendientes === 0) { // Pregunto si no esta destanqueando if (APP.Configuracion.BanderaPendientes === 0) { // Pregunto si no esta destanqueando
APP.Configuracion.TanquePendiente = []; APP.Configuracion.TanquePendiente = [];
APP.Configuracion.BanderaPendientes = 1; APP.Configuracion.BanderaPendientes = 1;
if (APP.Configuracion.debug > 4) APP.RegistrarLog('3|PENDIENTE|Verificando el Tanque de Pendientes.'); APP.RegistrarLog('3|PENDIENTE|Verificando el Tanque de Pendientes.');
try { try {
fs.readFile('./logs/TanquePendientes.log', { fs.readFile('./logs/TanquePendientes.log', {
encoding: 'utf8', encoding: 'utf8',
@ -328,7 +611,7 @@ APP = module.exports = {
if (data.length < 10) { if (data.length < 10) {
APP.Configuracion.CantidadPendientes = 0; APP.Configuracion.CantidadPendientes = 0;
APP.Configuracion.BanderaPendientes = 0; APP.Configuracion.BanderaPendientes = 0;
if (APP.Configuracion.debug > 2) APP.RegistrarLog('3|PENDIENTE|Tanque PENDIENTES vacio.'); APP.RegistrarLog('3|PENDIENTE|Tanque PENDIENTES vacio.');
} else { } else {
Guardar = []; Guardar = [];
var EnviarPendientes = []; var EnviarPendientes = [];
@ -336,7 +619,7 @@ APP = module.exports = {
var CantRegistros = Pendientes.length; var CantRegistros = Pendientes.length;
var intentos = 0; var intentos = 0;
APP.Configuracion.CantidadPendientes = CantRegistros; APP.Configuracion.CantidadPendientes = CantRegistros;
if (APP.Configuracion.debug > 4) APP.RegistrarLog('3|PENDIENTE|Cantidad Registros en Pendientes: ' + CantRegistros); APP.RegistrarLog('3|PENDIENTE|Cantidad Registros en Pendientes: ' + CantRegistros);
for (var i = 0, t = CantRegistros; i < t; ++i) { for (var i = 0, t = CantRegistros; i < t; ++i) {
EnviarPendientes[0] = [Pendientes[i].TipoRed, Pendientes[i].Usuario, Pendientes[i].Password, Pendientes[i].Server, Pendientes[i].Puerto, Pendientes[i].Ruta, Pendientes[i].Llave_W, Pendientes[i].Nombre, 'PENDIENTE']; EnviarPendientes[0] = [Pendientes[i].TipoRed, Pendientes[i].Usuario, Pendientes[i].Password, Pendientes[i].Server, Pendientes[i].Puerto, Pendientes[i].Ruta, Pendientes[i].Llave_W, Pendientes[i].Nombre, 'PENDIENTE'];
EnviarPendientes[1] = Pendientes[i].registro; EnviarPendientes[1] = Pendientes[i].registro;
@ -346,7 +629,7 @@ APP = module.exports = {
Redes.EviarRedesMeteorologicas(versionEMA, EnviarPendientes, function (red, estadored, errorRedes, idRed, registro) { Redes.EviarRedesMeteorologicas(versionEMA, EnviarPendientes, function (red, estadored, errorRedes, idRed, registro) {
var RegistroEnviado = JSON.parse(registro); var RegistroEnviado = JSON.parse(registro);
if (estadored === 'ERROR') { // si falla el destanqueo if (estadored === 'ERROR') { // si falla el destanqueo
if (APP.Configuracion.debug > 2) APP.RegistrarLog('3|PENDIENTE|Error no se pudo publicar la Red : ' + red + ' - Estado:' + estadored); APP.RegistrarLog('3|PENDIENTE|Error no se pudo publicar la Red : ' + red + ' - Estado:' + estadored);
var Pendiente = { var Pendiente = {
idRed: RegistroEnviado[2], idRed: RegistroEnviado[2],
TipoRed: RegistroEnviado[0][0], TipoRed: RegistroEnviado[0][0],
@ -378,7 +661,7 @@ APP = module.exports = {
EnviarPendientes = null; EnviarPendientes = null;
} }
} catch (ex) { // si hay un error en el archivo tanque de pendiente se blanquea y se vuelve a llamar la misma. } catch (ex) { // si hay un error en el archivo tanque de pendiente se blanquea y se vuelve a llamar la misma.
if (APP.Configuracion.debug > 0) APP.RegistrarLog('1|ERROR|Tanque Pendientes corrupto.Se blanqueo el tanque diario para depurar el error. 2: ' + ex); APP.RegistrarLog('1|ERROR| 🔴 Tanque Pendientes corrupto.Se blanqueo el tanque diario para depurar el error. 2: ' + ex);
APP.Configuracion.TanquePendiente = []; APP.Configuracion.TanquePendiente = [];
APP.Configuracion.BanderaPendientes = 0; APP.Configuracion.BanderaPendientes = 0;
fs.writeFile('./logs/TanquePendientes.log', JSON.stringify(APP.Configuracion.TanquePendiente, null, 4), { fs.writeFile('./logs/TanquePendientes.log', JSON.stringify(APP.Configuracion.TanquePendiente, null, 4), {
@ -386,20 +669,20 @@ APP = module.exports = {
autoClose: true autoClose: true
}, function (err) { }, function (err) {
if (err) { if (err) {
APP.RegistrarLog('1|ERROR: Guardando registro de prendientes de Ema Center en archivo :' + err); APP.RegistrarLog('1|ERROR|🔴 Guardando registro de prendientes de Ema Center en archivo :' + err);
} }
}); });
} }
}); });
} catch (ex) { // si hay un error en el archivo tanque de pendiente se blanquea y se vuelve a llamar la misma. } catch (ex) { // si hay un error en el archivo tanque de pendiente se blanquea y se vuelve a llamar la misma.
if (APP.Configuracion.debug > 0) APP.RegistrarLog('1|ERROR|Tanque Pendientes corrupto.Se blanqueo el tanque diario para depurar el error. 1: ' +ex); APP.RegistrarLog('1|ERROR| 🔴 Tanque Pendientes corrupto.Se blanqueo el tanque diario para depurar el error. 1: ' +ex);
APP.Configuracion.TanquePendiente = []; APP.Configuracion.TanquePendiente = [];
fs.writeFile('./logs/TanquePendientes.log', JSON.stringify([], null, 4), { fs.writeFile('./logs/TanquePendientes.log', JSON.stringify([], null, 4), {
encoding: 'utf8', encoding: 'utf8',
autoClose: true autoClose: true
}, function (err) { }, function (err) {
if (err) { if (err) {
APP.RegistrarLog('1|ERROR: Guardando registro de prendientes de Ema Center en archivo :' + err); APP.RegistrarLog('1|ERROR| 🔴 Guardando registro de prendientes de Ema Center en archivo :' + err);
} }
}); });
} }
@ -435,7 +718,7 @@ APP = module.exports = {
}); });
} }
} catch (ex) { // si hay un error en el archivo tanque de pendiente se blanquea y se vuelve a llamar la misma. } catch (ex) { // si hay un error en el archivo tanque de pendiente se blanquea y se vuelve a llamar la misma.
if (APP.Configuracion.debug > 0) APP.RegistrarLog('1|ERROR|Tanque Pendientes corrupto.Se blanqueo el tanque diario para depurar el error. 3:'+ex); APP.RegistrarLog('1|ERROR| 🔴 Tanque Pendientes corrupto.Se blanqueo el tanque diario para depurar el error. 3:'+ex);
APP.Configuracion.BanderaPendientes = 0; APP.Configuracion.BanderaPendientes = 0;
APP.Configuracion.TanquePendiente = []; APP.Configuracion.TanquePendiente = [];
APP.Guardar_Pendientes( '', false); APP.Guardar_Pendientes( '', false);
@ -473,7 +756,7 @@ APP = module.exports = {
"error": errorRedes "error": errorRedes
}; };
APP.Configuracion.UltimoPublicado[idRed] = RegistroPublicado; APP.Configuracion.UltimoPublicado[idRed] = RegistroPublicado;
if (APP.Configuracion.debug > 2) APP.RegistrarLog('3|RED|Red No Publicada: ' + red + ' - Estado:' + estadored + ' ' + errorRedes); APP.RegistrarLog('3|RED|Red No Publicada: ' + red + ' - Estado:' + estadored + ' ' + errorRedes);
if ((red === 'emacenter') || (red === 'emacentergugler')) { if ((red === 'emacenter') || (red === 'emacentergugler')) {
APP.RegistrarLog('0|PENDIENTE_ALM|Se almaceno en el tanque de pendientes red EmaCenter: ' + RegistroEnviado[0][7]); APP.RegistrarLog('0|PENDIENTE_ALM|Se almaceno en el tanque de pendientes red EmaCenter: ' + RegistroEnviado[0][7]);
RegistroEnviado[1].tanque = true; RegistroEnviado[1].tanque = true;
@ -524,7 +807,7 @@ APP = module.exports = {
} }
} }
APP.Configuracion.UltimoPublicado[idRed] = RegistroPublicado; APP.Configuracion.UltimoPublicado[idRed] = RegistroPublicado;
if (APP.Configuracion.debug > 2) APP.RegistrarLog('3|RED|Red Publicada: ' + red + ' - Estado:' + estadored); APP.RegistrarLog('3|RED|Red Publicada: ' + red + ' - Estado:' + estadored);
} }
}); // CALLBACK ENVIAR RED }); // CALLBACK ENVIAR RED
} else { } else {
@ -554,7 +837,6 @@ APP = module.exports = {
// Metodo para obtener datos de EMA CENTER en modo visor por llave de lectura // Metodo para obtener datos de EMA CENTER en modo visor por llave de lectura
Visor: function (cant, callback) { Visor: function (cant, callback) {
var http = require('https');
var timeout = 5000; var timeout = 5000;
var ServidorEMACENTER = { var ServidorEMACENTER = {
hostname: 'emacenter.gugler.com.ar', hostname: 'emacenter.gugler.com.ar',
@ -563,8 +845,8 @@ APP = module.exports = {
method: 'GET' method: 'GET'
}; };
if (typeof callback !== 'function') callback = function () {}; if (typeof callback !== 'function') callback = function () {};
if (APP.Configuracion.debug > 7) APP.RegistrarLog('8|VISOR|Buscando un registro en EMACENTER(' + ServidorEMACENTER.hostname + ')...'); APP.RegistrarLog('8|VISOR|Buscando un registro en EMACENTER(' + ServidorEMACENTER.hostname + ')...');
var request = http.request(ServidorEMACENTER, function (response) { var request = https.request(ServidorEMACENTER, function (response) {
if (response.statusCode === 200) { // RESPUESTA HTML Y COMPARA if (response.statusCode === 200) { // RESPUESTA HTML Y COMPARA
var message = ''; var message = '';
response.on('data', function (chunk) { response.on('data', function (chunk) {
@ -576,23 +858,23 @@ APP = module.exports = {
// Se verifica la Respuesta // Se verifica la Respuesta
// APP.RegistrarLog(Respuesta); // APP.RegistrarLog(Respuesta);
if (typeof Respuesta.error === 'undefined') { if (typeof Respuesta.error === 'undefined') {
if (APP.Configuracion.debug > 5) APP.RegistrarLog('6|VISOR|Registro obtenido de ' + Respuesta.modelo + ' de Fecha: ' + Respuesta.registros[0].fecha); APP.RegistrarLog('6|VISOR|Registro obtenido de ' + Respuesta.modelo + ' de Fecha: ' + Respuesta.registros[0].fecha);
callback(null, Respuesta); callback(null, Respuesta);
} else { } else {
if (APP.Configuracion.debug > 5) APP.RegistrarLog('6|ERROR|Registro con algun error.'); APP.RegistrarLog('6|ERROR| 🔴 Registro con algun error.');
callback(Respuesta.error, null); callback(Respuesta.error, null);
} }
}); });
} else { } else {
var respuesta = 'Codigo: ' + response.statusCode; var respuesta = 'Codigo: ' + response.statusCode;
if (APP.Configuracion.debug > 5) APP.RegistrarLog('6|ERROR|No se pudo obtener el registro (Modo Visor). ' + respuesta); APP.RegistrarLog('6|ERROR| 🔴 No se pudo obtener el registro (Modo Visor). ' + respuesta);
callback(respuesta, null); callback(respuesta, null);
} }
}); });
request.on('socket', function (socket) { request.on('socket', function (socket) {
socket.setTimeout(timeout); socket.setTimeout(timeout);
socket.on('timeout', function () { socket.on('timeout', function () {
if (APP.Configuracion.debug > 5) APP.RegistrarLog('6|ERROR|TimeOut cuando se intenta obtener el registro (Modo Visor). Codigo: ' + request.statusCode); APP.RegistrarLog('6|ERROR| 🔴 TimeOut cuando se intenta obtener el registro (Modo Visor). Codigo: ' + request.statusCode);
request.abort(); request.abort();
}); });
}).on('error', function (error) { }).on('error', function (error) {
@ -636,17 +918,17 @@ APP = module.exports = {
}, (err, data) => { }, (err, data) => {
var Guardar = []; var Guardar = [];
if (err) { if (err) {
if (APP.Configuracion.debug > 0) APP.RegistrarLog('1|ERROR|Tanque diario corrupto.Se blanqueo el tanque diario para depurar el error.'); APP.RegistrarLog('1|ERROR| 🔴 Tanque diario corrupto.Se blanqueo el tanque diario para depurar el error.');
APP.Guardar_Diario(Guardar); APP.Guardar_Diario(Guardar);
} else { } else {
var DepurarLog = false; var DepurarLog = false;
if (data.length < 10) { if (data.length < 10) {
if (APP.Configuracion.debug > 2) APP.RegistrarLog('3|ARCHIVO|Tanque diario vacio.'); APP.RegistrarLog('3|ARCHIVO|Tanque diario vacio.');
} else { } else {
try { try {
var RegistroDiario = JSON.parse(data); var RegistroDiario = JSON.parse(data);
var CantRegistros = RegistroDiario.length; var CantRegistros = RegistroDiario.length;
if (APP.Configuracion.debug > 4) APP.RegistrarLog('5|ARCHIVO|Cantidad registros diarios: ' + CantRegistros); APP.RegistrarLog('8|ARCHIVO|Cantidad registros diarios: ' + CantRegistros);
var RegistroNuevoDia = Datos[0].substring(0, 2); var RegistroNuevoDia = Datos[0].substring(0, 2);
var RegistroNuevoHora = Datos[0].substring(11, 13); var RegistroNuevoHora = Datos[0].substring(11, 13);
var RegistroNuevoMinuto = Datos[0].substring(14, 15); var RegistroNuevoMinuto = Datos[0].substring(14, 15);
@ -737,7 +1019,7 @@ APP = module.exports = {
vientoDireccionPromDia = vientoDireccionPromDia / CantidadV; vientoDireccionPromDia = vientoDireccionPromDia / CantidadV;
RegistroDiario = null; RegistroDiario = null;
} catch (ex) { // si hay un error en el archivo registro_diario se blanquea y se vuelve a llamar la misma. } catch (ex) { // si hay un error en el archivo registro_diario se blanquea y se vuelve a llamar la misma.
if (APP.Configuracion.debug > 0) APP.RegistrarLog('1|ERROR|Tanque diario corrupto.Se blanqueo el tanque diario para depurar el error.'); APP.RegistrarLog('1|ERROR| 🔴 Tanque diario corrupto.Se blanqueo el tanque diario para depurar el error.');
Guardar = []; Guardar = [];
APP.Guardar_Diario(Guardar); APP.Guardar_Diario(Guardar);
} }
@ -770,10 +1052,9 @@ APP = module.exports = {
if (LLuviaAcumuladaMinutos > 0) { LluviaActual = LLuviaAcumuladaMinutos; } else { LLuviaAcumuladaMinutos = 0; LluviaActual = 0; } if (LLuviaAcumuladaMinutos > 0) { LluviaActual = LLuviaAcumuladaMinutos; } else { LLuviaAcumuladaMinutos = 0; LluviaActual = 0; }
if (LLuviaAcumuladaHora < 0) { LLuviaAcumuladaHora = 0; } if (LLuviaAcumuladaHora < 0) { LLuviaAcumuladaHora = 0; }
if (LLuviaAcumuladaDia < 0) { LLuviaAcumuladaDia = 0; } if (LLuviaAcumuladaDia < 0) { LLuviaAcumuladaDia = 0; }
if (APP.Configuracion.debug > 4) APP.RegistrarLog('5|REGISTRO|Calculado - Lluvia Hora: ' + LLuviaAcumuladaHora.toFixed(2)); APP.RegistrarLog('5|REGISTRO|Calculado - Lluvia Hora: ' + LLuviaAcumuladaHora.toFixed(2));
if (APP.Configuracion.debug > 4) APP.RegistrarLog('5|REGISTRO|Calculado - Lluvia Actual: ' + LLuviaAcumuladaMinutos.toFixed(2)); APP.RegistrarLog('5|REGISTRO|Calculado - Lluvia Actual: ' + LLuviaAcumuladaMinutos.toFixed(2));
if (APP.Configuracion.debug > 4) APP.RegistrarLog('5|REGISTRO|Calculado - Lluvia Dia: ' + LLuviaAcumuladaDia.toFixed(2)); APP.RegistrarLog('5|REGISTRO|Calculado - Lluvia Dia: ' + LLuviaAcumuladaDia.toFixed(2));
var RegistroJSON = { var RegistroJSON = {
fecha: Datos[0], fecha: Datos[0],
fechaISO: Datos[1], fechaISO: Datos[1],
@ -888,19 +1169,19 @@ APP = module.exports = {
utc = null; utc = null;
d = null; d = null;
if (recolector.status() === true) { if (recolector.status() === true) {
if (APP.Configuracion.debug > 7 && APP.Configuracion.Repeticiones > 1) APP.RegistrarLog('8|LECTURA|Inicio Lectura'); if (APP.Configuracion.Repeticiones > 1) APP.RegistrarLog('8|LECTURA|Inicio Lectura');
if (APP.Configuracion.debug > 7) APP.RegistrarLog('8|REGISTRO|Estado: online (' + APP.Configuracion.RepeticionesConError + ')'); APP.RegistrarLog('8|REGISTRO|Estado: online (' + APP.Configuracion.RepeticionesConError + ')');
if (APP.Configuracion.debug > 7) APP.RegistrarLog('8|REGISTRO|Fecha: ' + fechac); APP.RegistrarLog('8|REGISTRO|Fecha: ' + fechac);
if (APP.Configuracion.debug > 7) APP.RegistrarLog('8|REGISTRO|Tiempo Recolección: ' + APP.Configuracion.TiempoContinuo); APP.RegistrarLog('8|REGISTRO|Tiempo Recolección: ' + APP.Configuracion.TiempoContinuo);
if (APP.Configuracion.debug > 7) APP.RegistrarLog('8|REGISTRO|Cant. Lect. sin corte: ' + APP.Configuracion.Repeticiones); APP.RegistrarLog('8|REGISTRO|Cant. Lect. sin corte: ' + APP.Configuracion.Repeticiones);
//Se busca un registro usb (PROMESA - resultado(registro,cambios, true o false(si hay cambios)) //Se busca un registro usb (PROMESA - resultado(registro,cambios, true o false(si hay cambios))
recolector.Recolectar().then((resultado)=> recolector.Recolectar().then((resultado)=>
{ {
//APP.RegistrarLog(resultado[1]); //APP.RegistrarLog(resultado[1]);
var datosRecolectados = resultado[0]; var datosRecolectados = resultado[0];
if ((APP.Configuracion.RepeticionesConError) > APP.Configuracion.Cantidad_No_Lectura) { if ((APP.Configuracion.RepeticionesConError) > APP.Configuracion.Cantidad_No_Lectura) {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|IMPORTANTE: No se puede leer la EMA por USB. Supero la Cantidad Máxima de No Lectura definida.'); APP.RegistrarLog('0|CORE|IMPORTANTE: No se puede leer la EMA por USB. Supero la Cantidad Máxima de No Lectura definida.');
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|IMPORTANTE: Supero la Cantidad Máxima de No Lectura definida.'); APP.RegistrarLog('0|CORE|IMPORTANTE: Supero la Cantidad Máxima de No Lectura definida.');
throw new Error('NolecturaUSB'); throw new Error('NolecturaUSB');
} }
if (typeof datosRecolectados !== 'undefined') if (typeof datosRecolectados !== 'undefined')
@ -925,7 +1206,7 @@ APP = module.exports = {
} else { } else {
APP.Configuracion.Repeticiones = 0; APP.Configuracion.Repeticiones = 0;
APP.Configuracion.Estado_Val_Ant = errorvalidador[0]; APP.Configuracion.Estado_Val_Ant = errorvalidador[0];
if (APP.Configuracion.debug > 0) APP.RegistrarLog('0|VALIDADOR|Datos recolectados incorrectos: ' + errorvalidador[1]); APP.RegistrarLog('0|VALIDADOR|Datos recolectados incorrectos: ' + errorvalidador[1]);
APP.Configuracion.FechaLanzadoTimeout = Date.now(); APP.Configuracion.FechaLanzadoTimeout = Date.now();
APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Continuo, APP.Configuracion.TiempoContinuo * 1000)); APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Continuo, APP.Configuracion.TiempoContinuo * 1000));
Datos = null; Datos = null;
@ -949,11 +1230,11 @@ APP = module.exports = {
APP.Configuracion.RunTime = 0; APP.Configuracion.RunTime = 0;
} }
} catch (ex) { } catch (ex) {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|EXCEP|Información de la excepción: -> ' + ex + ''); APP.RegistrarLog('0|EXCEP|Información de la excepción: -> ' + ex + '');
APP.Configuracion.Errores = 'EXCEP: Información de la excepción: -> ' + ex; APP.Configuracion.Errores = 'EXCEP: Información de la excepción: -> ' + ex;
var tiempo = (APP.Configuracion.TiempoMaximo + APP.Configuracion.TiempoContinuo) * 1000; var tiempo = (APP.Configuracion.TiempoMaximo + APP.Configuracion.TiempoContinuo) * 1000;
APP.Configuracion.TiempoFueraDeLinea += tiempo; APP.Configuracion.TiempoFueraDeLinea += tiempo;
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|EXCEP|Se espera ' + (tiempo / 1000) + ' segundos y se prueba conectar nuevamente ....'); APP.RegistrarLog('0|EXCEP|Se espera ' + (tiempo / 1000) + ' segundos y se prueba conectar nuevamente ....');
APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Conectar, tiempo)); APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Conectar, tiempo));
tiempo = null; tiempo = null;
} }

View File

@ -33,6 +33,7 @@ const configGlobalEMA = require('./../conf/ConfiguracionGlobal.js'); // Configur
const funcionesActualizar = require('./../core/actualizar.js'); // Se incluye el core de EMA. const funcionesActualizar = require('./../core/actualizar.js'); // Se incluye el core de EMA.
const EMA = require('./../core/ema.js'); // Se incluye el core de EMA. const EMA = require('./../core/ema.js'); // Se incluye el core de EMA.
const gui = require('nw.gui'); // Libreria Grafica const gui = require('nw.gui'); // Libreria Grafica
const os = require('os'); // Libreria del sistema operativo
// **********************Vairales Generales********************* // **********************Vairales Generales*********************
const iconoEncendido = './gui_common/iconos/icono_enc.png'; // Imagen del Icono Encendido const iconoEncendido = './gui_common/iconos/icono_enc.png'; // Imagen del Icono Encendido
const iconoApagado = './gui_common/iconos/icono_off.png'; // Imagen del Icono Apagado const iconoApagado = './gui_common/iconos/icono_off.png'; // Imagen del Icono Apagado
@ -302,6 +303,23 @@ async function controlPendientes () {
async function mostrarEstados (EstadoSensores) { async function mostrarEstados (EstadoSensores) {
// Se consulta por los sensores // Se consulta por los sensores
if(configGeneralEMA.ConfGeneral.Modo === "Recolector_IP")
{
if (EstadoSensores === "0") {
$('#signal').attr('src', '../gui_common/img/signal.webp');
$('#signal').attr('title', 'Estacion IP/WIFI Conectada');
}else{
$('#signal').attr('src', '../gui_common/img/no_signal.webp');
if(EMA.UltimoRegistro()){
$('#signal').attr('title', 'Bateria Baja Controlar');
HABLA(0, 'Bateria baja de la estacion IP/WIFI externa', 'warn');}
}
$('#signal').addClass('parpadea');
$('#signal').tooltip('dispose');
$('#signal').tooltip();
}else{
var Resultado = !((EstadoSensores.lost_sensor_contact) || (EstadoSensores.rain_overflow)); var Resultado = !((EstadoSensores.lost_sensor_contact) || (EstadoSensores.rain_overflow));
if (Resultado && (configGeneralEMA.ConfGeneral.Modo !== 'Visor')) { if (Resultado && (configGeneralEMA.ConfGeneral.Modo !== 'Visor')) {
$('#signal').attr('src', '../gui_common/img/signal.webp'); $('#signal').attr('src', '../gui_common/img/signal.webp');
@ -320,16 +338,15 @@ async function mostrarEstados (EstadoSensores) {
EstadoSensores = null; EstadoSensores = null;
Resultado = null; Resultado = null;
} }
}
async function RegistroActual (barratermino) async function RegistroActual (barratermino)
{ {
//console.log('ENTRO REGISTRO ACTUAL'); //console.log('ENTRO REGISTRO ACTUAL');
if (['Recolector_USB', 'Recolector_IP'].includes(configGeneralEMA.ConfGeneral.Modo))
if (configGeneralEMA.ConfGeneral.Modo === 'Recolector')
{ // se comprueba el modo se encuentra en Recolector { // se comprueba el modo se encuentra en Recolector
if(barratermino == true){ if(barratermino == true){
//BARRA TERMINO //BARRA TERMINO
//console.log('ENTRO AL BARRA TERMINO RECOLECTOR');
await esperar(100); await esperar(100);
EstadoMenuInicio(); EstadoMenuInicio();
await esperar(100); await esperar(100);
@ -346,10 +363,16 @@ async function RegistroActual (barratermino)
var EstadoEMA = EMA.Estado(); var EstadoEMA = EMA.Estado();
if (EstadoEMA[0] === true) if (EstadoEMA[0] === true)
{ {
$('#mensaje').html('Recolectando.');
$('#img_mensaje').attr('src', iconoControlTrue);
$('#mensajedetalle').html('Operando.');
$('#img_detalle').attr('src', iconoControlTrue); $('#img_detalle').attr('src', iconoControlTrue);
$('#img_mensaje').attr('src', iconoControlTrue);
if(configGeneralEMA.ConfGeneral.Modo === "Recolector_IP")
{
$('#mensaje').html('Recolectado por IP.');
}else{
$('#mensaje').html('Recolectando.');
$('#mensajedetalle').html('Operando.');
}
controlPendientes(); controlPendientes();
UltimoReg = EMA.UltimoRegistro(); UltimoReg = EMA.UltimoRegistro();
var EstadoSensores = EMA.EstadoSensores(); var EstadoSensores = EMA.EstadoSensores();
@ -357,22 +380,31 @@ async function RegistroActual (barratermino)
{ {
mostrarEstados(EstadoSensores); mostrarEstados(EstadoSensores);
}else{EstadoSensores=null;} }else{EstadoSensores=null;}
if (UltimoReg == false) { if (UltimoReg == false)
{
// Se consulta por la cantidad de errores // Se consulta por la cantidad de errores
if (EMA.RepeticionesConError() > 2) { if (EMA.RepeticionesConError() > 3) {
await esperar(10000); await esperar(10000);
HABLA(0, 'No se pueden obtener registros (Intentos ' + EMA.RepeticionesConError() + '). Desconecte y vuelva a conectar el USB. Se prueba reiniciar el servicio.', 'error'); if(configGeneralEMA.ConfGeneral.Modo === "Recolector_IP")
{$('#img_mensaje').attr('src', iconoNeutro);$('#img_detalle').attr('src', iconoNeutro);
HABLA(0, 'No se pueden obtener registros (Intentos ' + EMA.RepeticionesConError() + '). Revise por favor su configuración IP/WIFI de la estación. Se prueba reiniciar el servicio.', 'error');}
else{
HABLA(0, 'No se pueden obtener registros (Intentos ' + EMA.RepeticionesConError() + '). Desconecte y vuelva a conectar el USB. Se prueba reiniciar el servicio.', 'error')
}
await esperar(15000); await esperar(15000);
DETENER(); DETENER();
await esperar(5000); await esperar(5000);
INICIAR(); INICIAR();
return false; return false;
} else { } else {
$('#mensaje').html('(' + EMA.RepeticionesConError() + ') Sincronizando ...');
$('#img_mensaje').attr('src', iconoNeutro); $('#mensajedetalle').html('(' + EMA.RepeticionesConError() + ') Sincronizando ...');
await esperar(200); if(configGeneralEMA.ConfGeneral.Modo === "Recolector_IP") EMA.Configuracion.RepeticionesConError += 1;
$('#img_detalle').attr('src', iconoNeutro);
await esperar(2000);
RegistroActual(); RegistroActual();
return false; return false;
} }
} }
} else { } else {
@ -459,7 +491,7 @@ async function RegistroActual (barratermino)
async function BarradeProgreso () { async function BarradeProgreso () {
// const startTime = performance.now(); // const startTime = performance.now();
// Se consulta el tiempo actual del recolector // Se consulta el tiempo actual del recolector
if (configGeneralEMA.ConfGeneral.Modo === 'Recolector') if (configGeneralEMA.ConfGeneral.Modo != 'Visor')
{ // EN MODO RECOLECTOR { // EN MODO RECOLECTOR
var tiempoActualRecolector; var tiempoActualRecolector;
tiempoActualRecolector = EMA.TiempoActualRecolector(); tiempoActualRecolector = EMA.TiempoActualRecolector();
@ -479,7 +511,7 @@ async function BarradeProgreso () {
cant++; cant++;
if(cant == 1){ RegistroActual(true);} else{return true;}; if(cant == 1){ RegistroActual(true);} else{return true;};
// solo si esta en modo visor // solo si esta en modo visor
if (configGeneralEMA.ConfGeneral.Modo !== 'Recolector') {document.getElementById('RedesMet').innerHTML = "<span class='badge badge-success' title='Obtenido Correctamente'>" + ModeloVisor + ': ' + UltimoReg.fecha.substring(10, 20) + '</span><br>';} if (configGeneralEMA.ConfGeneral.Modo === 'Visor') {document.getElementById('RedesMet').innerHTML = "<span class='badge badge-success' title='Obtenido Correctamente'>" + ModeloVisor + ': ' + UltimoReg.fecha.substring(10, 20) + '</span><br>';}
if (win.x > -10000) if (win.x > -10000)
{ // Solo si no esta minimizado { // Solo si no esta minimizado
NProgress.done(); NProgress.done();
@ -516,11 +548,48 @@ async function BarradeProgreso () {
// ********************** Menu Acciones ******************************************************************* // ********************** Menu Acciones *******************************************************************
function MenuConfig () { function MenuConfig () {
if ($('#Modo').val() === 'Recolector') {
$('#bloque_secundario').hide();
$('#LlaveR').hide();
$('#bloque_por_IP_WIFI').hide();
if (['Recolector_USB', 'Recolector_IP'].includes($('#Modo').val())) {
$('#LlaveR').attr('disabled', true); $('#LlaveR').attr('disabled', true);
$('#LlaveR').val(''); $('#LlaveR').val('');
$('#LlaveR').hide(); if ($('#Modo').val() === 'Recolector_USB') {
//nada por ahora :).
}else{ //esta en modo Recolector_IP
console.log("entro en modo IP");
$('#bloque_secundario').show();
$('#bloque_por_IP_WIFI').show();
const interfaces = os.networkInterfaces();
// Limpiar las opciones previas (excepto la de "Seleccionar IP")
const $ipGroup = $('#ipGroup');
$ipGroup.find('option:not([value=""])').remove();
// Recorremos las interfaces de red
let ipEncontrada = false;
for (const name in interfaces) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
const $option = $('<option>', {
value: iface.address,
text: iface.address
});
$ipGroup.append($option);
ipEncontrada = true;
}
}
}
if (!ipEncontrada) { const $option = $('<option>', {
value: "false",
text: "No se encontraron interfaces"
});
$ipGroup.append($option);
}
$('#r_ip').selectpicker('refresh');
}
} else { } else {
$('#bloque_secundario').show();
$('#LlaveR').attr('disabled', false); $('#LlaveR').attr('disabled', false);
$('#LlaveR').show(); $('#LlaveR').show();
$('#Llave_R').val(configGeneralEMA.ConfGeneral.Llave_R); $('#Llave_R').val(configGeneralEMA.ConfGeneral.Llave_R);
@ -637,7 +706,31 @@ async function MenuGUI (elemento) {
voiceSelect.appendChild(option); voiceSelect.appendChild(option);
voiceSelect.selectedIndex = "0"; voiceSelect.selectedIndex = "0";
} }
const interfaces = os.networkInterfaces();
// Limpiar las opciones previas (excepto la de "Seleccionar IP")
const $ipGroup = $('#ipGroup');
$ipGroup.find('option:not([value=""])').remove();
// Recorremos las interfaces de red
let ipEncontrada = false;
for (const name in interfaces) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
const $option = $('<option>', {
value: iface.address,
text: iface.address
});
$ipGroup.append($option);
ipEncontrada = true;
}
}
}
if (!ipEncontrada) { const $option = $('<option>', {
value: "false",
text: "No se encontraron interfaces"
});
$ipGroup.append($option);
}
$('#r_ip').selectpicker('refresh');
$('#NombreEstacion').val(configGeneralEMA.ConfGeneral.NombreEstacion); $('#NombreEstacion').val(configGeneralEMA.ConfGeneral.NombreEstacion);
$('#Modo').val(configGeneralEMA.ConfGeneral.Modo); $('#Modo').val(configGeneralEMA.ConfGeneral.Modo);
$('#Modo').selectpicker('render'); $('#Modo').selectpicker('render');
@ -649,6 +742,10 @@ async function MenuGUI (elemento) {
$('#Tipo_SMTP').val(configGeneralEMA.ConfEmail.Servicio); $('#Tipo_SMTP').val(configGeneralEMA.ConfEmail.Servicio);
$('#Tipo_SMTP').selectpicker('render'); $('#Tipo_SMTP').selectpicker('render');
$('#Tiempo_de_Recoleccion').selectpicker('render'); $('#Tiempo_de_Recoleccion').selectpicker('render');
$('#r_ip').val(configGeneralEMA.ConfGeneral.IP);
$('#r_ip').selectpicker('render');
$('#r_puerto').val(configGeneralEMA.ConfGeneral.Puerto);
$('#r_path').val(configGeneralEMA.ConfGeneral.Ruta);
$('#Debug').val(configGeneralEMA.ConfGeneral.debug); $('#Debug').val(configGeneralEMA.ConfGeneral.debug);
$('#debugMB').val(configGeneralEMA.ConfGeneral.debugTamanio); $('#debugMB').val(configGeneralEMA.ConfGeneral.debugTamanio);
$('#Debug').selectpicker('render'); $('#Debug').selectpicker('render');
@ -678,7 +775,7 @@ async function MenuGUI (elemento) {
} }
$('#vocesAudio').selectpicker('render'); $('#vocesAudio').selectpicker('render');
// Control para el modo // Control para el modo
if ($('#Modo').val() === 'Recolector') { if (['Recolector_USB', 'Recolector_IP'].includes($('#Modo').val())) {
$('#LlaveR').attr('disabled', true); $('#LlaveR').attr('disabled', true);
$('#LlaveR').val(''); $('#LlaveR').val('');
$('#LlaveR').hide(); $('#LlaveR').hide();

View File

@ -112,6 +112,8 @@ async function EstadoMenuInicio()
$('#imodo').html(configGeneralEMA.ConfGeneral.Modo); $('#imodo').html(configGeneralEMA.ConfGeneral.Modo);
if(configGeneralEMA.ConfGeneral.Modo != ''){$("#img_modo").attr("src",icono_control_true);}else{$("#img_modo").attr("src",icono_control_false);} if(configGeneralEMA.ConfGeneral.Modo != ''){$("#img_modo").attr("src",icono_control_true);}else{$("#img_modo").attr("src",icono_control_false);}
if(configGeneralEMA.ConfGeneral.Modo != 'Visor') // Se consulta el modo (Recolector o Visor) if(configGeneralEMA.ConfGeneral.Modo != 'Visor') // Se consulta el modo (Recolector o Visor)
{
if(configGeneralEMA.ConfGeneral.Modo === 'Recolector_USB') // Modo Recolector USB
{ {
EMA.EstadoUSB(function(EstadoUSB) EMA.EstadoUSB(function(EstadoUSB)
{ {
@ -146,6 +148,29 @@ async function EstadoMenuInicio()
} }
EstadoUSB=null; EstadoUSB=null;
}); });
}else{ // Modo Recolector por IP/WIFI
EstadoEMA_Control = EMA.Estado();
if(EstadoEMA_Control[0])
{
$("#img_estado").attr("src",icono_control_true);$('#estado').html("En Linea");
$('#botoniniciar').attr("disabled",true);
$('#botondetener').attr("disabled",false);
$('#iusb').html("Recolectado por IP");$("#img_estacion").attr("src",icono_control_true);
$('#mensaje').html("Recolectado por IP");$("#img_mensaje").attr("src",icono_control_true);
$("#img_detalle").attr("src",icono_control_true);
MensajeR = "Recolectando de " + configGeneralEMA.ConfGeneral.IP + ":" + configGeneralEMA.ConfGeneral.Puerto + configGeneralEMA.ConfGeneral.Ruta;
;$('#mensajedetalle').html(MensajeR);
}else{
MensajeR = "Al iniciar comenzara a recoletar en " + configGeneralEMA.ConfGeneral.IP + ":" + configGeneralEMA.ConfGeneral.Puerto + configGeneralEMA.ConfGeneral.Ruta;
$('#mensaje').html("Encienda EMA Libre");
$('#botoniniciar').attr("disabled",false);
$('#botondetener').attr("disabled",true);
$("#img_estacion").attr("src",icono_control_neutro);$('#iusb').html("Estación Wifi/IP sin recepción");
$("#img_mensaje").attr("src",icono_control_neutro);$('#mensaje').html("Encienda EMA Libre.");
$("#img_estado").attr("src",icono_control_neutro);$('#estado').html("Fuera de Linea");
$("#img_detalle").attr("src",icono_control_neutro);$('#mensajedetalle').html(MensajeR);
}
}
}else{ // Modo Visor Control }else{ // Modo Visor Control
$('#iusb').html("Por Llave Lectura"); $('#iusb').html("Por Llave Lectura");
if($( "#signal" ).hasClass( "parpadea" )) if($( "#signal" ).hasClass( "parpadea" ))
@ -340,14 +365,17 @@ async function ClimaActual()
if(UltimoReg.cambio === true && configGeneralEMA.ConfGeneral.notificar_cambios === true){ if(UltimoReg.cambio === true && configGeneralEMA.ConfGeneral.notificar_cambios === true){
var cambiosCarpincho = ''; var cambiosCarpincho = '';
// Obteniendo todas las claves del JSON // Obteniendo todas las claves del JSON
let contador = 0;
for (var clave in UltimoReg.diferencia){ for (var clave in UltimoReg.diferencia){
// Controlando que json realmente tenga esa propiedad if(configGeneralEMA.ConfGeneral.Modo != 'Recolector_IP') // Modo Recolector USB
if (UltimoReg.diferencia.hasOwnProperty(clave)) { { if (UltimoReg.diferencia.hasOwnProperty(clave)) {cambiosCarpincho += ' ' + mapaDatos.get(clave) + '.'; }
// Mostrando en pantalla la clave junto a su valor }else{ // Modo Recolector por IP/WIFI
cambiosCarpincho += ' ' + mapaDatos.get(clave) + '.'; //" (" + UltimoReg.diferencia[clave]+"), "; if (contador === 0) {cambiosCarpincho += clave;}else{cambiosCarpincho += ', ' + clave;}
} }
contador++;
} }
if(cambiosCarpincho != '') HABLA(0, 'Hay cambios de ' + cambiosCarpincho ,"info"); cambiosCarpincho += ".";
if (typeof cambiosCarpincho !== 'undefined' && cambiosCarpincho !== '') HABLA(0, 'Hay cambios de ' + cambiosCarpincho ,"info");
} }
// Se borran las variables // Se borran las variables
SALIDA_ENTRADA=null;NOCHE_DIA=null;LLUEVE=null;image=null; SALIDA_ENTRADA=null;NOCHE_DIA=null;LLUEVE=null;image=null;
@ -874,6 +902,9 @@ function GuardarConf(origen)
configGeneralEMA.ConfGeneral.UTC = parseInt($('#utc').val()); configGeneralEMA.ConfGeneral.UTC = parseInt($('#utc').val());
configGeneralEMA.ConfGeneral.SistemaMetrico = $('#SistemaMetrico').val(); configGeneralEMA.ConfGeneral.SistemaMetrico = $('#SistemaMetrico').val();
configGeneralEMA.ConfGeneral.Modo = $('#Modo').val(); configGeneralEMA.ConfGeneral.Modo = $('#Modo').val();
configGeneralEMA.ConfGeneral.IP = $('#r_ip').val();
configGeneralEMA.ConfGeneral.Puerto = $('#r_puerto').val();
configGeneralEMA.ConfGeneral.Ruta = $('#r_path').val();
configGeneralEMA.ConfGeneral.Llave_R = $('#Llave_R').val(); configGeneralEMA.ConfGeneral.Llave_R = $('#Llave_R').val();
configGeneralEMA.ConfGeneral.debugTamanio = parseInt($('#debugMB').val()); configGeneralEMA.ConfGeneral.debugTamanio = parseInt($('#debugMB').val());
if($('#inicio_auto').val() == "Activado"){configGeneralEMA.ConfGeneral.inicio_automatico = true;}else{configGeneralEMA.ConfGeneral.inicio_automatico = false;} if($('#inicio_auto').val() == "Activado"){configGeneralEMA.ConfGeneral.inicio_automatico = true;}else{configGeneralEMA.ConfGeneral.inicio_automatico = false;}
@ -930,7 +961,7 @@ function VerHistorico(lugar)
document.getElementById("mostrarregistrosH").style.display = "none"; document.getElementById("mostrarregistrosH").style.display = "none";
document.getElementById("actualizando").style.display = "block"; document.getElementById("actualizando").style.display = "block";
$('#botonresfrescar').attr("disabled",true); $('#botonresfrescar').attr("disabled",true);
if(configGeneralEMA.ConfGeneral.Modo == 'Recolector') // se comprueba el modo se encuentra en Recolector if(['Recolector_USB', 'Recolector_IP'].includes(configGeneralEMA.ConfGeneral.Modo)) // se comprueba el modo se encuentra en Recolector
{ {
fsconf.readFile('./logs/registro_diario.log', {encoding: 'utf8', autoClose: true},function (err, data) fsconf.readFile('./logs/registro_diario.log', {encoding: 'utf8', autoClose: true},function (err, data)
{ if (err) throw err; { if (err) throw err;
@ -1229,12 +1260,14 @@ async function MostrarTabla(DATOS,DIV,TABLA)
{ {
$('#'+DIV).empty(); $('#'+DIV).empty();
$('#'+DIV).html(DATOS); $('#'+DIV).html(DATOS);
$('#'+TABLA).DataTable( const tabla = $('#'+TABLA).DataTable(
{ {
dom: 'Bfrtip', dom: 'Bfrtip',
buttons: ['copy','csv'], buttons: ['copy','csv'],
pageLength: 8, pageLength: 8,
scrollX: true, scrollX: true,
responsive:true,
autoWidth: false,
//scrollCollapse: true, //scrollCollapse: true,
//lengthChange: false, //lengthChange: false,
//ordering: true, //ordering: true,
@ -1248,6 +1281,14 @@ async function MostrarTabla(DATOS,DIV,TABLA)
//console.log('Termino datatable'); //console.log('Termino datatable');
document.getElementById(DIV).style.display = "block"; document.getElementById(DIV).style.display = "block";
document.getElementById("actualizando").style.display = "none"; document.getElementById("actualizando").style.display = "none";
$('.buttons-csv').removeClass('btn-default').addClass('btn-primary');
$('.buttons-csv span').text('💾 Exportar CSV');
$('.buttons-copy').removeClass('btn-default').addClass('btn-secondary');
$('.buttons-copy span').text(' 📋 Copiar al portapeles');
// Ajusta las columnas después de mostrar la tabla
setTimeout(function() {
tabla.columns.adjust();
}, 300);
}, },
language: {url: "../gui_common/css/Spanish.json"} language: {url: "../gui_common/css/Spanish.json"}
}); });
@ -1263,7 +1304,7 @@ async function graficoEstadisticas()
document.getElementById("grafico").style.display = "none"; document.getElementById("grafico").style.display = "none";
document.getElementById("actualizando").style.display = "block"; document.getElementById("actualizando").style.display = "block";
//Se genera el grafico //Se genera el grafico
if(configGeneralEMA.ConfGeneral.Modo == 'Recolector') // se comprueba el modo se encuentra en Recolector if(['Recolector_USB', 'Recolector_IP'].includes(configGeneralEMA.ConfGeneral.Modo)) // se comprueba el modo se encuentra en Recolector
{ {
fsconf.readFile('./logs/registro_diario.log', { fsconf.readFile('./logs/registro_diario.log', {
@ -1343,6 +1384,7 @@ async function graficoEstadisticas()
{ if(!isNaN(parseInt(validacion[i]),10)) totalErrores += parseInt(validacion[i],10);}; { if(!isNaN(parseInt(validacion[i]),10)) totalErrores += parseInt(validacion[i],10);};
// Se genera grafico de resumen // Se genera grafico de resumen
new Chart(document.getElementById("graph_inicio"), { new Chart(document.getElementById("graph_inicio"), {
type: 'bar', type: 'bar',
data: { data: {
@ -1404,7 +1446,6 @@ async function graficoEstadisticas()
} }
}); });
RegistroDiarioTmp = null;CantRegistros=null;CantiddPendientesAlmacenados=null; CantiddPendientesPublicados = null;RegistroDiarioConCambios = null; RegistroDiarioTmp = null;CantRegistros=null;CantiddPendientesAlmacenados=null; CantiddPendientesPublicados = null;RegistroDiarioConCambios = null;
//Se genera el grafico //Se genera el grafico

View File

@ -52,22 +52,48 @@ if (voices.length === 0) {
if (actualizar) { if (actualizar) {
// Si el parámetro es 'update', abrir la ventana de actualización // Si el parámetro es 'update', abrir la ventana de actualización
gui.Window.open('./gui/index_actualizar.html', { gui.Window.open('./gui/index_actualizar.html', {
position: 'center',
width: 630, width: 630,
height: 400 height: 400
}, function(win) {
// Centrar manualmente
const screen = gui.Screen.screens[0];
const x = Math.round((screen.bounds.width - 630) / 2);
const y = Math.round((screen.bounds.height - 400) / 2);
win.moveTo(x, y);
}); });
} else { } else {
// Si no, abrir la ventana principal de la aplicación con un tamaño reducido // Si no, abrir la ventana principal de la aplicación con un tamaño reducido
gui.Window.open('./gui/index.html', { gui.Window.open('./gui/index.html', {
frame: false, frame: false,
show: true, show: false, // Oculta la ventana al crearla
position: 'center',
width: 450, width: 450,
height: 200, height: 200,
min_width: 450, min_width: 450,
min_height: 200, min_height: 200,
max_width: 450, max_width: 450,
max_height: 200 max_height: 200
}, function(win) {
gui.Screen.Init();
setTimeout(function() {
const screens = gui.Screen.screens;
const winX = win.x;
const winY = win.y;
let currentScreen = screens[0];
for (let screen of screens) {
if (
winX >= screen.bounds.x &&
winX < screen.bounds.x + screen.bounds.width &&
winY >= screen.bounds.y &&
winY < screen.bounds.y + screen.bounds.height
) {
currentScreen = screen;
break;
}
}
const x = Math.round(currentScreen.bounds.x + (currentScreen.bounds.width - win.width) / 2);
const y = Math.round(currentScreen.bounds.y + (currentScreen.bounds.height - win.height) / 2);
win.moveTo(x, y);
win.show(); // Mostrar la ventana ya centrada
}, 100);
}); });
} }

View File

@ -13,7 +13,9 @@
<link rel="stylesheet" href="../node_modules/nprogress/nprogress.css"> <link rel="stylesheet" href="../node_modules/nprogress/nprogress.css">
<link rel="stylesheet" href="../gui_common/css/style.css"> <link rel="stylesheet" href="../gui_common/css/style.css">
<!-- Librerías JS --> <!-- Librerías JS -->
<!-- Libreria bootstrap/jquery para graficos --> <!-- Libreria bootstrap/jquery para graficos -->
<script src="../node_modules/jquery/dist/jquery.min.js"></script> <script src="../node_modules/jquery/dist/jquery.min.js"></script>
<script src="../node_modules/popper.js/dist/umd/popper.min.js"></script> <script src="../node_modules/popper.js/dist/umd/popper.min.js"></script>
@ -31,7 +33,8 @@
<script src="../gui_common/libs/RGraph/RGraph.gauge.js"></script> <script src="../gui_common/libs/RGraph/RGraph.gauge.js"></script>
<script src="../gui_common/libs/RGraph/RGraph.odo.js"></script> <script src="../gui_common/libs/RGraph/RGraph.odo.js"></script>
<script src="../gui_common/libs/RGraph/RGraph.drawing.image.js"></script> <script src="../gui_common/libs/RGraph/RGraph.drawing.image.js"></script>
<script src="../node_modules/chart.js/dist/Chart.min.js"></script> <<script src="../node_modules/chart.js/dist/Chart.min.js"></script>
<!-- Barra de progreso --> <!-- Barra de progreso -->
<script src="../node_modules/nprogress/nprogress.js"></script> <script src="../node_modules/nprogress/nprogress.js"></script>
<!-- Libreria Notificaciones emergentes --> <!-- Libreria Notificaciones emergentes -->
@ -39,6 +42,12 @@
<!-- Libreria del Controlador --> <!-- Libreria del Controlador -->
<script src="controlador/funcionesgenerales.js"></script> <script src="controlador/funcionesgenerales.js"></script>
<script src="controlador/admingui.js"></script> <script src="controlador/admingui.js"></script>
<style>
.text-center { text-align: center !important; }
.text-right { text-align: right !important; }
.text-left { text-align: left !important; }
.vertical-align-top { vertical-align: top !important; }
</style>
</head> </head>
<body class="dia"> <body class="dia">
@ -73,11 +82,13 @@
<br><br> <br><br>
<div id="superior" class="container"> <div id="superior" class="container">
<div class="row"> <div class="row">
<div class="col-2" align="center" style="vertical-align:top;"> <div class="col-2 text-center vertical-align-top">
<div class="row"> <div class="row">
<div class="col-12 col-right align-self-center"> <div class="col-12 col-right align-self-center">
<br> <br>
<span class="text-muted text-align-center"><img id="carpincho_img" align="center" src="../gui_common/iconos/icono_app.webp" height="48px" width="48px" onclick="HABLA(0,'Hola, soy Carpincho, ¿qué deseas?.','info');" onmouseover="GUIÑA(0);"></span> <span class="text-muted text-center">
<img id="carpincho_img" style="display: block; margin: 0 auto;" src="../gui_common/iconos/icono_app.webp" height="48px" width="48px" onclick="HABLA(0,'Hola, soy Carpincho, ¿qué deseas?.','info');" onmouseover="GUIÑA(0);">
</span>
</div> </div>
<div class="col-12 col-left align-self-center"> <div class="col-12 col-left align-self-center">
<span class='badge badge-ultimalectura' style="font-size:small">Última Lectura<br> <span id='fecha' class='badge badge-primary'>-</span></span> <span class='badge badge-ultimalectura' style="font-size:small">Última Lectura<br> <span id='fecha' class='badge badge-primary'>-</span></span>
@ -85,17 +96,19 @@
</div> </div>
<br> <br>
</div> </div>
<div class="col-3" align="center" style="vertical-align:top;"></div> <div class="col-3 text-center vertical-align-top"></div>
<div class="col-2" align="center"><div id="clima"> </div><br></div> <div class="col-2 text-center">
<div class="col-2" align="center"> <div id="clima"></div><br>
<div id="DIVModo" style="vertical-align:top;visibility: hidden"> </div> </div>
<div id="DIVPendientes" style="vertical-align:top;visibility: hidden"> <div class="col-2 text-center">
<div id="DIVModo" class="vertical-align-top" style="visibility: hidden"></div>
<div id="DIVPendientes" class="vertical-align-top" style="visibility: hidden">
<span class='badge badge-warning'>Registros Pendientes</span> <span class='badge badge-warning'>Registros Pendientes</span>
<span id="Pendientes" class='badge badge-warning'></span> <span id="Pendientes" class='badge badge-warning'></span>
<span id="Destanqueo" class="parpadea texttanque" style="vertical-align:top;visibility: hidden"><strong>Destanqueando</strong></span> <span id="Destanqueo" class="parpadea texttanque vertical-align-top" style="visibility: hidden"><strong>Destanqueando</strong></span>
</div> </div>
</div> </div>
<div class="col-3" align="right" id="RedesMet" style="list-group row vertical-align:top;"> </div> <div class="col-3 text-right" id="RedesMet" class="list-group row" style="vertical-align: top;"></div>
</div> </div>
<div class="container container-fluid"> <div class="container container-fluid">
<ul class="nav nav-tabs nav-inverse nav-pills nav-fill" id="list-tab" role="tablist"> <ul class="nav nav-tabs nav-inverse nav-pills nav-fill" id="list-tab" role="tablist">
@ -122,7 +135,7 @@
</li> </li>
</ul> </ul>
<div class="tab-content jumbotron" id="" style="padding: 15px;padding-bottom:15px;margin-bottom:15px"> <div class="tab-content jumbotron" id="" style="padding: 15px;padding-bottom:15px;margin-bottom:15px">
<div id="actualizando_inicio" style="display:none" align="center"><br><br><br><br><img src='../gui_common/img/animadas/cargando2.gif' width='100' height='100' /> <br><br><br><br> </div> <div id="actualizando_inicio" style="display:none" class="text-center"><br><br><br><br><img src='../gui_common/img/animadas/cargando2.gif' width='100' height='100' /> <br><br><br><br> </div>
<div class="tab-pane fade show active" id="inicio" role="tabpanel" aria-badgeledby="inicio-tab"></div> <div class="tab-pane fade show active" id="inicio" role="tabpanel" aria-badgeledby="inicio-tab"></div>
<div class="tab-pane fade text-center" id="interior" role="tabpanel" aria-badgeledby="interior-tab"></div> <div class="tab-pane fade text-center" id="interior" role="tabpanel" aria-badgeledby="interior-tab"></div>
<div class="tab-pane fade text-center" id="exterior" role="tabpanel" aria-badgeledby="exterior-tab"></div> <div class="tab-pane fade text-center" id="exterior" role="tabpanel" aria-badgeledby="exterior-tab"></div>

View File

@ -1,30 +1,56 @@
<head>
<!-- ...código existente... -->
<style>
hr {
height: 4px;
border: none;
background-color: #bbb;
margin: 20px 0;
}
.hr-suave {
height: 1px;
border: none;
background-color: #ccc;
opacity: 0.5;
margin: 20px 0;
}
.text-right { text-align: right !important; }
.text-left { text-align: left !important; }
.text-center { text-align: center !important; }
.vertical-align-top { vertical-align: top !important; }
</style>
</head>
<body>
<div class="col-centered"> <div class="col-centered">
<h1>Configuración General</h1> <h1>Configuración General</h1>
<div class="row"> <div class="row">
<div class="col-12" align="right" style="vertical-align:top;"><button class="btn btn-sm btn-success" onclick="MenuGUI('logs');" role="button">Ver Logs</button> </div> <div class="col-12 text-right" style="vertical-align:top;"><button class="btn btn-sm btn-success" onclick="MenuGUI('logs');" role="button">Ver Logs</button> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-3" align="left" style="vertical-align:top;"></div> <div class="col-4 col-centered">
<div class="col-6" align="center" style="vertical-align:top;">
<div class="col-12 col-centered">
<label class="control-label">Nombre de tu estación</label><br>
<input type="text" class="btn btn-primary" id="NombreEstacion" autocomplete='name' placeholder="Ingrese el nombre" maxlength="20" size="25"></br></br>
</div>
</div>
</div>
<div class="row">
<div class="col-3 col-centered">
<label class="control-label">Ema Modo</label><br> <label class="control-label">Ema Modo</label><br>
<select id='Modo' name="Modo" onchange="MenuConfig();" class="selectpicker show-tick" data-width="fit" data-style="btn-primary"> <select id='Modo' name="Modo" onchange="MenuConfig();" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Recolector USB"> <optgroup label="Recolector">
<option value="Recolector">Recolector</option> <option value="Recolector_USB">Recolector USB</option>
<option value="Recolector_IP">Recolector IP/WIFI</option>
</optgroup> </optgroup>
<optgroup label="Visor por Llave"> <optgroup label="Visor">
<option value="Visor">Visor</option> <option value="Visor">Visor Llave</option>
</optgroup> </optgroup>
</select> </select>
</div> </div>
<div class="col-3 col-centered"> <div class="col-4 col-centered">
<label class="control-label">Nombre de tu estación</label><br>
<input type="text" class="btn btn-primary" id="NombreEstacion" autocomplete='name' placeholder="Ingrese el nombre" maxlength="20" size="30"></br></br>
</div>
<div class="col-4 col-centered">
<label for="inputEmail" class="control-label">Correo del Administrador</label><br>
<input type="email" class="btn btn-primary" id="Email_receptor" autocomplete='email' placeholder="Email" maxlength="50" size="35">
</div>
</div>
<hr class="hr-suave">
<div class="row">
<div class="col-2 col-centered">
<label class="control-label">Inicio Automático</label><br> <label class="control-label">Inicio Automático</label><br>
<select id='inicio_auto' name="inicio_auto" class="selectpicker show-tick" data-width="fit" data-style="btn-primary"> <select id='inicio_auto' name="inicio_auto" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Iniciar el recolector/visor con el aplicativo"> <optgroup label="Iniciar el recolector/visor con el aplicativo">
@ -33,16 +59,7 @@
</optgroup> </optgroup>
</select> </select>
</div> </div>
<div class="col-3 col-centered"> <div class="col-2 col-centered">
<label class="control-label">Audio</label><br>
<select id='audio' name="audio" onchange="MenuConfig();" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Audio de carpincho">
<option value="Activado">Activado</option>
<option value="Desactivado">Desactivado</option>
</optgroup>
</select>
</div>
<div class="col-3 col-centered">
<label class="control-label">Notificar Cambios</label><br> <label class="control-label">Notificar Cambios</label><br>
<select id='notificar_cambios' name="notificar_cambios" onchange="MenuConfig();" class="selectpicker show-tick" data-width="fit" data-style="btn-primary"> <select id='notificar_cambios' name="notificar_cambios" onchange="MenuConfig();" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Notificar de carpincho"> <optgroup label="Notificar de carpincho">
@ -51,22 +68,24 @@
</optgroup> </optgroup>
</select> </select>
</div> </div>
<div class="col-2 col-centered">
<label class="control-label">Audio</label><br>
<select id='audio' name="audio" onchange="MenuConfig();" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Audio de carpincho">
<option value="Activado">Activado</option>
<option value="Desactivado">Desactivado</option>
</optgroup>
</select>
</div> </div>
<hr> <div class="col-3 col-centered" id="vocesAudioDiv">
<div class="row"> <label class="control-label">Voz del Audio</label></br>
<div class="col-6 col-centered" id="LlaveR">
<label class="control-label">Llave de Lectura</label></br>
<input type="text" class="btn btn-primary" id="Llave_R" placeholder="Ingrese LLave" maxlength="40" size="44"></br></br>
</div>
<div class="col-6 col-centered" id="vocesAudioDiv">
<label class="control-label">Seleccione la Voz para el Audio</label></br>
<select id='vocesAudio' name="vocesAudio" class="selectpicker show-tick" data-width="fit" data-style="btn-primary" size="100"> <select id='vocesAudio' name="vocesAudio" class="selectpicker show-tick" data-width="fit" data-style="btn-primary" size="100">
<optgroup label="Lista de Voces"> <optgroup label="Lista de Voces">
</optgroup> </optgroup>
</select> </select>
</div> </div>
</div> </div>
<hr> <hr class="hr-suave">
<div class="row"> <div class="row">
<div class="col-2 col-centered"> <div class="col-2 col-centered">
<label class="control-label">Recolección</label><br> <label class="control-label">Recolección</label><br>
@ -164,12 +183,8 @@
</optgroup> </optgroup>
</select> </select>
</div> </div>
<div class="col-4 col-centered">
<label for="inputEmail" class="control-label">Correo del Administrador</label><br>
<input type="email" class="btn btn-primary" id="Email_receptor" autocomplete='email' placeholder="Email" maxlength="30" size="15">
</div> </div>
</div> <hr class="hr-suave">
<hr>
<div class="row"> <div class="row">
<div class="col-3 col-centered"> <div class="col-3 col-centered">
<label class="control-label">SMTP TIPO</label><br> <label class="control-label">SMTP TIPO</label><br>
@ -192,7 +207,7 @@
</div> </div>
<div class="col-3 col-centered"> <div class="col-3 col-centered">
<label class="control-label">Contraseña</label><br> <label class="control-label">Contraseña</label><br>
<input type="password" class="btn btn-primary" id="Contrasenia_SMTP" placeholder="Contraseña" maxlength="40" size="16" value="-"> <input type="password" class="btn btn-primary" id="Contrasenia_SMTP" placeholder="Contraseña" maxlength="40" size="16">
</div> </div>
<div class="col-2 col-centered" id="Server"> <div class="col-2 col-centered" id="Server">
<label class="control-label">Server</label><br> <label class="control-label">Server</label><br>
@ -202,10 +217,48 @@
<label class="control-label">Puerto</label><br> <label class="control-label">Puerto</label><br>
<input type="text" class="btn btn-primary" id="Puerto_SMTP" placeholder="Puerto" maxlength="4" size="5"> <input type="text" class="btn btn-primary" id="Puerto_SMTP" placeholder="Puerto" maxlength="4" size="5">
</div> </div>
</div><br> </div>
</div>
<!-- Segun seleccion cambia debajo el bloque secundario -->
<div id="bloque_secundario">
<hr>
<label class="control-label">Configuración específica para el Modo</label>
<div class="col-centered">
<div class="row">
<div class="col-6 col-centered" id="LlaveR">
<label class="control-label">Llave de Lectura</label></br>
<input type="text" class="btn btn-primary" id="Llave_R" placeholder="Ingrese LLave" maxlength="40" size="44"></br></br>
</div>
</div>
<div id="bloque_por_IP_WIFI" class="row">
<div class="col-4 col-centered">
<label class="control-label">IP</label><br>
<select id='r_ip' name="IP" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="IP's" id="ipGroup">
</select>
</div>
<div class="col-2 col-centered">
<label class="control-label">Puerto</label></br>
<input type="text" class="btn btn-primary" id="r_puerto" placeholder="Puerto" maxlength="4" size="5" value="5000">
</div>
<div class="col-4 col-centered">
<label class="control-label">Path</label></br>
<input type="text" class="btn btn-primary" id="r_path" placeholder="Puerto" maxlength="15" size="25" value="/datos">
</div>
</div>
</div>
</div>
<hr class="hr-suave">
<div class="row"> <div class="row">
<div class="col-12 col-centered"> <div class="col-12 col-centered">
<button type="button" id="botonguardar" class="btn btn-sm btn-success" onclick="GuardarConf('conf')" role="button">Guardar</button> <button type="button" id="botonguardar" class="btn btn-sm btn-success" onclick="GuardarConf('conf')" role="button">Guardar</button>
</div> </div>
</div> </div>
</div>
</body>

View File

@ -1,4 +1,4 @@
'version:2024-12-01 (6.20)'; 'version:2025-06-24 (6.22)';
// //
// o---------------------------------------------------------------------------------o // o---------------------------------------------------------------------------------o
// | This file is part of the RGraph package - you can learn more at: | // | This file is part of the RGraph package - you can learn more at: |
@ -38,6 +38,8 @@
RGraph.cache = []; RGraph.cache = [];
RGraph.GET = {}; RGraph.GET = {};
RGraph.GET.__parts__ = null; RGraph.GET.__parts__ = null;
RGraph.Queue = {__store__: []};
RGraph.PHP = {};
RGraph.ObjectRegistry = {}; RGraph.ObjectRegistry = {};
RGraph.ObjectRegistry.objects = {}; RGraph.ObjectRegistry.objects = {};
@ -512,6 +514,30 @@
//
// Returns a column of data from a 2D array.
//
// @param array arr The 2D array
// @param number col The column of data to extract. Starts at zero.
// @retun array The new array of data.
//
RGraph.arrayColumn = function (arr, col)
{
if (col > arr.length || Math.abs(col) > Math.abs(arr.length + 1)) {
return null;
}
return arr.map(v => v[col < 0 ? col + v.length : col]);
};
// //
// A convenient way to get the last element in the array: // A convenient way to get the last element in the array:
// //
@ -1478,7 +1504,24 @@
if ( typeof window.event.offsetX === 'number' if ( typeof window.event.offsetX === 'number'
&& typeof window.event.offsetY === 'number' && typeof window.event.offsetY === 'number'
) { ) {
return [window.event.offsetX, window.event.offsetY];
var ret = [
window.event.offsetX,
window.event.offsetY
];
//
// Is the canvas scaled in order for it to look much
// nicer. If so, the scaling needs to be accounted
// for here.
//
var obj = window.event.target.__object__;
if (obj && obj.properties.scaled) {
ret[0] *= obj.properties.scaledFactor;
ret[1] *= obj.properties.scaledFactor;
}
return ret;
} }
var args = RGraph.getArgs(arguments, 'event'); var args = RGraph.getArgs(arguments, 'event');
@ -2610,6 +2653,7 @@
// //
// @param object obj The graph object // @param object obj The graph object
// //
RGraph.drawIngraphLabels =
RGraph.drawInGraphLabels = function () RGraph.drawInGraphLabels = function ()
{ {
var args = RGraph.getArgs(arguments, 'object'); var args = RGraph.getArgs(arguments, 'object');
@ -3203,17 +3247,21 @@
// //
RGraph.fireCustomEvent = function () RGraph.fireCustomEvent = function ()
{ {
var args = RGraph.getArgs(arguments, 'object,name'); var args = RGraph.getArgs(arguments, 'object,name,meta');
// Prepend the name with "on" if necessary // Prepend the name with "on" if necessary
if (args.name.substr(0,2) !== 'on') { if (args.name.substr(0,2) !== 'on') {
args.name = 'on' + args.name; args.name = 'on' + args.name;
} }
// The event name without preceding "on", eg
// draw, firstdraw or beforedraw etc.
var eventName = args.name.replace(/^on/,'');
if (args.object && args.object.isrgraph) { if (args.object && args.object.isrgraph) {
// This allows the eventsMouseout property to work // This allows the eventsMouseout property to
// (for some reason...) // work (for some reason...)
// //
// 25/10/19 - Taken out // 25/10/19 - Taken out
// //
@ -3222,7 +3270,7 @@
//} //}
// DOM1 style of adding custom events // DOM1 style of adding custom events
if (args.object[args.name]) { if (args.object[args.name]) {
(args.object[args.name])(args.object); (args.object[args.name])(args.object, args.meta);
} }
var uid = args.object.uid; var uid = args.object.uid;
@ -3234,7 +3282,19 @@
for(var j=0; j<RGraph.events[uid].length; ++j) { for(var j=0; j<RGraph.events[uid].length; ++j) {
if (RGraph.events[uid][j] && RGraph.events[uid][j][1] === args.name) { if (RGraph.events[uid][j] && RGraph.events[uid][j][1] === args.name) {
RGraph.events[uid][j][2](args.object); RGraph.events[uid][j][2](args.object, args.meta);
}
}
}
// Allow for the events property (new in
// Summer 2025.
if (args.object.properties.events && args.object.properties.events[eventName] && (RGraph.isFunction(args.object.properties.events[eventName]) || RGraph.isArray(args.object.properties.events[eventName]))) {
if (RGraph.isFunction (args.object.properties.events[eventName])) {
(args.object.properties.events[eventName])(args.object, args.meta);
} else if (RGraph.isArray(args.object.properties.events[eventName])) {
for (var i=0; i<args.object.properties.events[eventName].length; ++i) {
(args.object.properties.events[eventName][i])(args.object, args.meta);
} }
} }
} }
@ -3442,7 +3502,8 @@
{ {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)
{ {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); var r = Math.random()*16|0,
v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16); return v.toString(16);
}); });
}; };
@ -4589,7 +4650,8 @@
// //
// New text function. Accepts two arguments: // New text function. Accepts one argument:
//
// o opt - An object/hash/map of properties. This can consist of: // o opt - An object/hash/map of properties. This can consist of:
// object The RGraph chart object (THIS OR BELOW OPTION IS REQUIRED) // object The RGraph chart object (THIS OR BELOW OPTION IS REQUIRED)
// context The canvases context. This can be given in // context The canvases context. This can be given in
@ -5611,6 +5673,15 @@
var group = 0; var group = 0;
var grouped_index = 0; var grouped_index = 0;
//
// Allow for the arguments to be in any order
//
if (RGraph.isNumber(args.data) && RGraph.isArray(args.index)) {
var tmp = args.data;
args.data = args.index;
args.index = tmp;
}
while (--args.index >= 0) { while (--args.index >= 0) {
if (RGraph.isNullish(args.data[group])) { if (RGraph.isNullish(args.data[group])) {
@ -5655,8 +5726,17 @@
{ {
var args = RGraph.getArgs(arguments, 'object,dataset,index'); var args = RGraph.getArgs(arguments, 'object,dataset,index');
// Handle just the data being given instead of the whole
// object
if (RGraph.isObject(args.object) && args.object.isrgraph) {
var data = args.object.data;
} else {
var data = args.object;
}
for (var i=0,seq=0; i<=args.dataset; ++i) { for (var i=0,seq=0; i<=args.dataset; ++i) {
for (var j=0; j<args.object.data[args.dataset].length; ++j) { for (var j=0; j<data[args.dataset].length; ++j) {
if (i === args.dataset && j === args.index) { if (i === args.dataset && j === args.index) {
return seq; return seq;
@ -5782,11 +5862,16 @@
// OR // OR
// //
// @param string str The string to parse // @param string str The string to parse
// @param string unis Either ms (milliseconds - the default)
// or s for seconds.
// @return number A number, as returned by Date.parse() // @return number A number, as returned by Date.parse()
// //
RGraph.parseDate = function () RGraph.parseDate = function ()
{ {
var args = RGraph.getArgs(arguments, 'str'); var args = RGraph.getArgs(arguments, 'str,units');
// Force to a string
args.str = String(args.str);
// First off - remove the T from the format: YYYY-MM-DDTHH:MM:SS // First off - remove the T from the format: YYYY-MM-DDTHH:MM:SS
if (args.str.match(/^\d\d\d\d-\d\d-\d\d(t|T)\d\d:\d\d(:\d\d)?$/)) { if (args.str.match(/^\d\d\d\d-\d\d-\d\d(t|T)\d\d:\d\d(:\d\d)?$/)) {
@ -5882,7 +5967,9 @@
String(defaults.seconds).length === 1 ? '0' + (defaults.seconds) : defaults.seconds String(defaults.seconds).length === 1 ? '0' + (defaults.seconds) : defaults.seconds
); );
return Date.parse(args.str); var ms = Date.parse(args.str);
return args.units === 's' ? ms / 1000 : ms;
// //
// Support functions // Support functions
@ -6607,6 +6694,11 @@
return true; return true;
} }
// Check for NaN
if (Number.isNaN(obj)) {
return true;
}
return false; return false;
}; };
@ -10566,6 +10658,48 @@
//
// Adds a style to the document. You give the whole
// selector/style string and it will add it.
//
// If a style element hasn't already been created
// it will create one and then reuse it on subsequent
// calls to this function.
//
// @param string style The styles to assign to the
// new class. An example:
//
// table tr td {color: red;}
//
RGraph.addCss = function ()
{
var args = RGraph.getArgs(arguments, 'style');
var append = false;
if (!RGraph.addCss.styleElement) {
RGraph.addCss.styleElement = document.createElement('style');
// Should the element be appended to the
// document?
append = true;
}
var el = RGraph.addCss.styleElement;
el.insertAdjacentHTML('beforeend', args.style);
// Append the style element to the document? Only
// do this on newly created style elements.
if (append) {
document.head.appendChild(el);
}
};
// //
// This function allows you to run a function once (immediately) // This function allows you to run a function once (immediately)
// Future calls using the same identifier are not run. // Future calls using the same identifier are not run.
@ -10576,15 +10710,22 @@
// @param func function The function to call // @param func function The function to call
// @return The return value of the function // @return The return value of the function
// //
RGraph.runOnce = function (id, func) RGraph.runOnce = function ()
{ {
if (RGraph.Registry.get('rgraph-runonce-functions')[id]) { var args = RGraph.getArgs(arguments, 'id,func,alternative');
if (RGraph.Registry.get('rgraph-runonce-functions')[args.id]) {
if (RGraph.isFunction(args.alternative)) {
(args.alternative)();
}
return; return;
} }
RGraph.Registry.get('rgraph-runonce-functions')[id] = func; RGraph.Registry.get('rgraph-runonce-functions')[args.id] = args.func;
return func(); return args.func();
}; };
@ -10765,6 +10906,587 @@
//
// A generic fade out routine for DOM elements.
//
// @param string selector The DOM selector which
// retrieves the element that
// you want fading out.
// @param number target The target opacity. This is
// a number betwewen 0 and 1.
// @param number frames The number of frames to fade
// out over.
// @param number delay The delay in milliseconds
// that the fade out takes.
// @param function callback A callback function that
// gets called when fading
// has completed.
//
RGraph.fade = function()
{
// Get arguments
var args = RGraph.getArgs(arguments, 'selector,target,frames,delay,callback');
// Defaults
var el = document.querySelector(args.selector);
var style = window.getComputedStyle(el);
var current = RGraph.isNumeric(style.opacity) ? parseFloat(style.opacity) : 1;
var target = RGraph.isNumber(args.target) ? args.target : 1; // Target opacity
var frames = args.frames || 10; // Number of frames
var delay = RGraph.isNumber(args.delay) ? args.delay : 500; // Delay per frame (ms)
// Constrain the target opacity to between 1 and 0
if (target > 1) target = 1;
if (target < 0) target = 0;
// The diff between the target opacity and
// the current opacity
var diff = target - current;
for (var i=0; i<=frames; ++i) {
(function (index)
{
setTimeout(function()
{
el.style.opacity = current + ((diff / frames) * index);
}, (delay / frames) * index);
})(i);
}
if (RGraph.isFunction(args.callback)) {
setTimeout(args.callback, delay);
}
};
RGraph.fade.OUT = 0;
RGraph.fade.IN = 1;
//
// A queuing function. Give this a name of a queue name and a
// function to run and it will run that function when the queue
// is resolved.
//
// @param string queue The queue to add the function to.
// @param function The function that will be queued and
// run when the queue is resolved.
//
RGraph.Queue.add = function (name, func)
{
if (!RGraph.isArray(RGraph.Queue.__store__)) {
RGraph.Queue.__store__ = {};
}
if (!RGraph.Queue.__store__[name]) {
RGraph.Queue.__store__[name] = [];
}
// Add the function to the queue
RGraph.Queue.__store__[name].push(func);
};
//
// Run all the functions in a queue (if there are any) that have
// been added.
//
// @param objec obj The chart object
// @param string name The name of the queue to resolve.
//
RGraph.Queue.resolve = function (name)
{
// Loop through the queue running the functions
if (RGraph.isArray(RGraph.Queue.__store__[name])) {
for (var i=0; i<RGraph.Queue.__store__[name].length; ++i) {
if (RGraph.isFunction(RGraph.Queue.__store__[name][i])) {
(RGraph.Queue.__store__[name][i])();
}
}
}
// Truncate the queue
RGraph.Queue.__store__[name] = [];
};
//
// Converts HTML entities back to their real character
// values.
//
// @param string text The string of text containing entities
// @return string The "unentified" text
//
RGraph.entitiesToText = function ()
{
var args = RGraph.getArgs(arguments, 'text');
var parser = new DOMParser;
var dom = parser.parseFromString(
'<!doctype html><body>' + args.text,
'text/html'
);
return dom.body.textContent;
};
//
// This is an implementation of the PHP date() function
// which came from the phpJS project (phpjs.org - though
// the website seems to be offline at the moment). You
// can use it like this:
// RGraph.PHP.date('jS F Y'); // 16th May 2025
//
// See the API docs for more information on how to use this
// function:
// https://www.rgraph.net/api
//
// @param string format The date format that you want to be
// returned.
//
RGraph.PHP.date = function (format, timestamp)
{
//
// If the modifier is present then use that and pass it
// to the RGraph.PHP.time() function to get the relevant
// unix timestamp.
//
if (RGraph.isString(timestamp) && RGraph.isNumeric(timestamp)) {
timestamp = parseInt(timestamp);
} else if (RGraph.isString(timestamp)) {
timestamp = RGraph.PHP.time(timestamp);
}
var that = this;
var jsdate, f;
// Keep this here (works, but for code commented-out
// below for file size reasons)
// var tal= [];
var txt_words = [
'Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur',
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
// trailing backslash -> (dropped)
// a backslash followed by any character (including
// backslash) -> the character empty string -> empty
// string
var formatChr = /\\?(.?)/gi;
var formatChrCb = function(t, s)
{
return f[t] ? f[t]() : s;
};
var _pad = function(n, c)
{
n = String(n);
while (n.length < c) {
n = '0' + n;
}
return n;
};
f = {
// Day of month w/leading 0; 01..31
d: function()
{
return _pad(f.j(), 2);
},
// Shorthand day name; Mon - Sun
D: function()
{
return f.l().slice(0, 3);
},
// Day of month; 1 - 31
j: function()
{
return jsdate.getDate();
},
// Full day name; Monday...Sunday
l: function()
{
return txt_words[f.w()] + 'day';
},
// ISO-8601 day of week; 1[Mon]..7[Sun]
N: function()
{
return f.w() || 7;
},
// Ordinal suffix for day of month; st, nd, rd, th
S: function()
{
var j = f.j();
var i = j % 10;
if (i <= 3 && parseInt((j % 100) / 10, 10) == 1) {
i = 0;
}
return ['st', 'nd', 'rd'][i - 1] || 'th';
},
// Day of week; 0[Sun]..6[Sat]
w: function()
{
return jsdate.getDay();
},
// Day of year; 0..365
z: function()
{
var a = new Date(f.Y(), f.n() - 1, f.j());
var b = new Date(f.Y(), 0, 1);
return Math.round((a - b) / 864e5);
},
// ISO-8601 week number
W: function()
{
var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3);
var b = new Date(a.getFullYear(), 0, 4);
return _pad(1 + Math.round((a - b) / 864e5 / 7), 2);
},
// Full month name; January...December
F: function()
{
return txt_words[6 + f.n()];
},
// Month w/leading 0; 01...12
m: function()
{
return _pad(f.n(), 2);
},
// Shorthand month name; Jan...Dec
M: function()
{
return f.F().slice(0, 3);
},
// Month; 1...12
n: function()
{
return jsdate.getMonth() + 1;
},
// Days in month; 28...31
t: function()
{
return (new Date(f.Y(), f.n(), 0)).getDate();
},
// Is leap year?; 0 or 1
L: function()
{
var j = f.Y();
return j % 4 === 0 & j % 100 !== 0 | j % 400 === 0;
},
// ISO-8601 year
o: function()
{
var n = f.n();
var W = f.W();
var Y = f.Y();
return Y + (n === 12 && W < 9 ? 1 : n === 1 && W > 9 ? -1 : 0);
},
// Full year; e.g. 1980...2010
Y: function()
{
return jsdate.getFullYear();
},
// Last two digits of year; 00...99
y: function()
{
return f.Y().toString().slice(-2);
},
// am or pm
a: function()
{
return jsdate.getHours() > 11 ? 'pm' : 'am';
},
// AM or PM
A: function()
{
return f.a().toUpperCase();
},
// Swatch Internet time; 000..999
B: function()
{
var H = jsdate.getUTCHours() * 36e2; // Hours
var i = jsdate.getUTCMinutes() * 60; // Minutes
var s = jsdate.getUTCSeconds(); // Seconds
return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3);
},
// 12-Hours; 1..12
g: function()
{
return f.G() % 12 || 12;
},
// 24-Hours; 0..23
G: function()
{
return jsdate.getHours();
},
// 12-Hours w/leading 0; 01..12
h: function()
{
return _pad(f.g(), 2);
},
// 24-Hours w/leading 0; 00..23
H: function()
{
return _pad(f.G(), 2);
},
// Minutes w/leading 0; 00..59
i: function()
{
return _pad(jsdate.getMinutes(), 2);
},
// Seconds w/leading 0; 00..59
s: function()
{
return _pad(jsdate.getSeconds(), 2);
},
// Microseconds; 000000-999000
u: function()
{
return _pad(jsdate.getMilliseconds() * 1000, 6);
},
// Timezone identifier; e.g. Atlantic/Azores, ...
e: function()
{
// The following works, but requires inclusion of
// the very large timezone_abbreviations_list()
// function.
//
// return that.date_default_timezone_get();
//
console.log('Not supported (see source code of date() for timezone on how to add support)');
return '';
},
// DST observed?; 0 or 1
I: function()
{
// Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC.
// If they are not equal, then DST is observed.
var a = new Date(f.Y(), 0);
// Jan 1
var c = Date.UTC(f.Y(), 0);
// Jan 1 UTC
var b = new Date(f.Y(), 6);
// Jul 1
var d = Date.UTC(f.Y(), 6); // Jul 1 UTC
return ((a - c) !== (b - d)) ? 1 : 0;
},
// Difference to GMT in hour format; e.g. +0200
O: function()
{
var tzo = jsdate.getTimezoneOffset();
var a = Math.abs(tzo);
return (tzo > 0 ? '-' : '+') + _pad(Math.floor(a / 60) * 100 + a % 60, 4);
},
// Difference to GMT w/colon; e.g. +02:00
P: function()
{
var O = f.O();
return (O.substr(0, 3) + ':' + O.substr(3, 2));
},
// Timezone abbreviation; e.g. EST, MDT, ...
T: function()
{
// The following works, but requires inclusion of the
// very large timezone_abbreviations_list() function.
//
//var abbr, i, os, _default;
//
//if (!tal.length) {
// tal = that.timezone_abbreviations_list();
//}
//if (that.php_js && that.php_js.default_timezone) {
// _default = that.php_js.default_timezone;
//
// for (abbr in tal) {
// for (i = 0; i < tal[abbr].length; i++) {
// if (tal[abbr][i].timezone_id === _default) {
// return abbr.toUpperCase();
// }
// }
// }
//}
//
//for (abbr in tal) {
// for (i = 0; i < tal[abbr].length; i++) {
// os = -jsdate.getTimezoneOffset() * 60;
//
// if (tal[abbr][i].offset === os) {
// return abbr.toUpperCase();
// }
// }
//}
return 'UTC';
},
// Timezone offset in seconds (-43200...50400)
Z: function()
{
return -jsdate.getTimezoneOffset() * 60;
},
// ISO-8601 date.
c: function()
{
return 'Y-m-d\\TH:i:sP'.replace(formatChr, formatChrCb);
},
// RFC 2822
r: function()
{
return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb);
},
// Seconds since UNIX epoch
U: function()
{
return jsdate / 1000 | 0;
}
};
var date = function(format, timestamp)
{
that = this;
jsdate = (timestamp === undefined
? new Date()
: (timestamp instanceof Date)
? new Date(timestamp)
: new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
);
return format.replace(formatChr, formatChrCb);
};
return date(format, timestamp);
};
//
// Returns the current number of seconds since the UNIX epoch
//
// @return number Seconds
//
// @param string modifier You can optionally supply a string
// that will be used to modify the
// timestamp, for example:
//
// var timestamp = RGraph.PHP.time('now + 1 day 6 hours')
// var timestamp = RGraph.PHP.time('now - 90 minutes')
//
// See the API docs on the website for more
// modifiers that you can use.
//
RGraph.PHP.time = function (modifier = null)
{
// Get the time ine seconds - not milloseconds
var timestamp = Math.floor(Date.now() / 1000);
if (RGraph.isString(modifier)) {
modifier = modifier.toLowerCase();
modifier = modifier.replace('now', timestamp);
modifier = modifier.replace(/([.0-9]+) *y(ear)?s?/g, '($1 * 31536000)');
modifier = modifier.replace(/([.0-9]+) *d(ay)?s?/g, '($1 * 86400)');
modifier = modifier.replace(/([.0-9]+) *w(eek)?s?/g, '($1 * 86400 * 7)');
modifier = modifier.replace(/([.0-9]+) *h(our)?s?/g, '($1 * 3600)');
modifier = modifier.replace(/([.0-9]+) *m(in)?(?:ute)?(?:s)?/g, '($1 * 60)');
modifier = modifier.replace(/([.0-9]+) *s(ec)?(?:ond)?(?:s)?/g, '($1 * 1)');
return parseInt(eval(modifier));
} else {
return Math.floor(Date.now() / 1000);
}
};
// Some utility functions that help identify the type of an object // Some utility functions that help identify the type of an object
// //
// Note that isUndefined() should be used like this or you'll get an // Note that isUndefined() should be used like this or you'll get an
@ -10775,9 +11497,11 @@
RGraph.isString = function(obj){return typeof obj === 'string';}; RGraph.isString = function(obj){return typeof obj === 'string';};
RGraph.isNumber = function(obj){return typeof obj === 'number';}; RGraph.isNumber = function(obj){return typeof obj === 'number';};
RGraph.isTextual = function(obj){return (typeof obj === 'string' || typeof obj === 'number');}; RGraph.isTextual = function(obj){return (typeof obj === 'string' || typeof obj === 'number');};
RGraph.isNumeric = function(value){value=String(value);return Boolean(value.match(/^[-.0-9]+$/))||Boolean(value.match(/^[-.0-9]+e[-0-9]+$/))||(value==='Infinity')||(value==='-Infinity')||Boolean(value.match(/^[-.0-9]+x[0-9a-f]+$/i));}; RGraph.isNumeric = function(value){if(RGraph.isArray(value)){return false;}value=String(value);return Boolean(value.match(/^-?[0-9]+(?:.[0-9]+)?$/))|| Boolean(value.match(/^-?[0-9]+(?:.[0-9+])?e-?[0-9]+$/))|| (value==='Infinity')|| (value==='-Infinity')|| !RGraph.isNullish(value.match(/^[0-9]+(?:.[0-9]+)?x[0-9a-f]+$/i));};
RGraph.isBool = RGraph.isBool =
RGraph.isBoolean = function(obj){return typeof obj === 'boolean';}; RGraph.isBoolean = function(obj){return typeof obj === 'boolean';};
RGraph.isRegex =
RGraph.isRegexp = function (obj){return obj.constructor.toString().toLowerCase().indexOf('regex') > 0;};
//RGraph.isArray Defined above //RGraph.isArray Defined above
RGraph.isObject = function(obj){return (obj && typeof obj === 'object' && obj.constructor.toString().toLowerCase().indexOf('object') > 0) ? true : false;}; RGraph.isObject = function(obj){return (obj && typeof obj === 'object' && obj.constructor.toString().toLowerCase().indexOf('object') > 0) ? true : false;};
//RGraph.isNull Defined above //RGraph.isNull Defined above

View File

@ -1,4 +1,4 @@
'version:2024-12-01 (6.20)'; 'version:2025-06-24 (6.22)';
// //
// o---------------------------------------------------------------------------------o // o---------------------------------------------------------------------------------o
// | This file is part of the RGraph package - you can learn more at: | // | This file is part of the RGraph package - you can learn more at: |
@ -138,7 +138,9 @@
clearto: 'rgba(0,0,0,0)', clearto: 'rgba(0,0,0,0)',
clip: null clip: null,
events: {}
} }
// //

View File

@ -1,4 +1,4 @@
'version:2024-12-01 (6.20)'; 'version:2025-06-24 (6.22)';
// //
// o---------------------------------------------------------------------------------o // o---------------------------------------------------------------------------------o
// | This file is part of the RGraph package - you can learn more at: | // | This file is part of the RGraph package - you can learn more at: |
@ -209,7 +209,9 @@
shadowOffsety: 0, shadowOffsety: 0,
shadowBlur: 15, shadowBlur: 15,
clearto: 'rgba(0,0,0,0)' clearto: 'rgba(0,0,0,0)',
events: {}
} }

View File

@ -1,4 +1,4 @@
'version:2024-12-01 (6.20)'; 'version:2025-06-24 (6.22)';
// //
// o---------------------------------------------------------------------------------o // o---------------------------------------------------------------------------------o
// | This file is part of the RGraph package - you can learn more at: | // | This file is part of the RGraph package - you can learn more at: |
@ -199,7 +199,9 @@
adjustable: false, adjustable: false,
clearto: 'rgba(0,0,0,0)' clearto: 'rgba(0,0,0,0)',
events: {}
} }

View File

@ -1,4 +1,4 @@
'version:2024-12-01 (6.20)'; 'version:2025-06-24 (6.22)';
// //
// o---------------------------------------------------------------------------------o // o---------------------------------------------------------------------------------o
// | This file is part of the RGraph package - you can learn more at: | // | This file is part of the RGraph package - you can learn more at: |

View File

@ -339,7 +339,6 @@ async function mostrarEstados (EstadoSensores) {
async function RegistroActual (barratermino) async function RegistroActual (barratermino)
{ {
//console.log('ENTRO REGISTRO ACTUAL');
if (configGeneralEMA.ConfGeneral.Modo === 'Recolector') if (configGeneralEMA.ConfGeneral.Modo === 'Recolector')
{ // se comprueba el modo se encuentra en Recolector { // se comprueba el modo se encuentra en Recolector

View File

@ -36,7 +36,7 @@
<h1><b>Contáctenos</b></h1> <h1><b>Contáctenos</b></h1>
<p style="text-align: justify">Si deseas realizar consultas, sugerencias o simplemente tenes alguna duda sobre nuestros productos/servicios, podes comunicarte con nosotros a través de los siguientes medios:</p> <p style="text-align: justify">Si deseas realizar consultas, sugerencias o simplemente tenes alguna duda sobre nuestros productos/servicios, podes comunicarte con nosotros a través de los siguientes medios:</p>
<h4><img src="img/ok.webp" height="25" width="25"><strong>Telefono: </strong>(0054 -0343) - 4975044 - Interno 119</h4> <h4><img src="img/ok.webp" height="25" width="25"><strong>Telefono: </strong>(0054 -0343) - 4975044 - Interno 119</h4>
<h4><img src="img/ok.webp" height="25" width="25"><strong>Correo Electronico: </strong>contacto@gugler.com.ar</h4> <h4><img src="img/ok.webp" height="25" width="25"><strong>Correo Electronico: </strong>gugler_contacto@uader.edu.ar</h4>
<h4><img src="img/ok.webp" height="25" width="25"><strong>Sitio Oficial: </strong> <a style="color: #1155cc;">https://www.gugler.com.ar</a></h4> <h4><img src="img/ok.webp" height="25" width="25"><strong>Sitio Oficial: </strong> <a style="color: #1155cc;">https://www.gugler.com.ar</a></h4>
</div> </div>
</div> </div>

View File

@ -0,0 +1 @@
[]

14488
src/logs/debug.log Normal file

File diff suppressed because it is too large Load Diff

9216
src/logs/registro_diario.log Normal file

File diff suppressed because it is too large Load Diff

4439
src/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@
"name": "emalibre", "name": "emalibre",
"description": "EMA Libre Cliente (Carpincho)", "description": "EMA Libre Cliente (Carpincho)",
"main": "gui/controlador/inicio.js", "main": "gui/controlador/inicio.js",
"version": "1.35.0", "version": "1.36.0",
"author": "Laboratorio de Investigacion Gugler", "author": "Laboratorio de Investigacion Gugler",
"homepage": "https://www.gugler.com.ar", "homepage": "https://www.gugler.com.ar",
"chromium-args": "--enable-speech-dispatcher", "chromium-args": "--enable-speech-dispatcher",
@ -38,25 +38,25 @@
"reporte": "node core/reporte.js", "reporte": "node core/reporte.js",
"cleanBuild": "nw-gyp clean --directory=node_modules/node-hid", "cleanBuild": "nw-gyp clean --directory=node_modules/node-hid",
"postLINUX": "nw-gyp rebuild --target=0.94.0 --verbose --arch=x64 --directory=node_modules/node-hid", "postLINUX": "nw-gyp rebuild --target=0.94.0 --verbose --arch=x64 --directory=node_modules/node-hid",
"postARM": "nw-gyp rebuild --target=0.28.3 --verbose --arch=arm --directory=node_modules/node-hid", "postWIN": "nw-gyp rebuild --target=0.94.0 --verbose --arch=x64 --directory=node_modules/node-hid",
"postWIN": "nw-gyp rebuild --target=0.94.0 --verbose --arch=x64 --directory=node_modules/node-hid" "postARM": "nw-gyp rebuild --target=0.28.3 --verbose --arch=arm --directory=node_modules/node-hid"
}, },
"dependencies": { "dependencies": {
"bootstrap": "^4.6.0", "bootstrap": "4.6.2",
"bootstrap-select": "^1.13.18", "bootstrap-select": "1.13.18",
"chart.js": "^2.9.4", "chart.js": "^2.9.4",
"datatables": "^1.10.18", "datatables": "1.10.18",
"datatables-buttons": "^1.0.3", "datatables-buttons": "1.0.3",
"express": "^4.17.1", "express": "5.1.0",
"forever": "^3.0.4", "forever": "^4.0.3",
"jquery": "^3.6.0", "jquery": "3.7.1",
"node": "15.10.0", "node": "24.4.0",
"node-hid": "^2.1.1", "node-hid": "^2.2.0",
"nodemailer": "^6.5.0", "nodemailer": "7.0.5",
"notify-js-lib": "^1.0.0", "notify-js-lib": "1.0.0",
"nprogress": "^0.2.0", "nprogress": "0.2.0",
"popper.js": "^1.16.1", "popper.js": "1.16.1",
"targz": "^1.0.1", "targz": "1.0.1",
"terminal-kit": "^2.0.6" "terminal-kit": "3.1.2"
} }
} }

53
test/Send_GET.py Normal file
View File

@ -0,0 +1,53 @@
import requests
import time
# Configuración: IP y puerto del servidor
ip_destino = '192.168.1.220'
puerto = 5000 # Cambialo por el puerto que necesites
# Intervalo de envío en segundos
intervalo_segundos = 10
# Construcción del URL base con puerto incluido
url_base = f'http://{ip_destino}:{puerto}/datos'
# Parámetros del GET
params = {
'ID': '1',
'PASSWORD': '1111',
'tempf': '63.5',
'humidity': '56',
'dewptf': '47.7',
'windchillf': '63.5',
'winddir': '68',
'windspeedmph': '0.00',
'windgustmph': '0.00',
'rainin': '0.000',
'dailyrainin': '0.000',
'weeklyrainin': '0.000',
'monthlyrainin': '0.000',
'yearlyrainin': '0.020',
'totalrainin': '0.020',
'solarradiation': '0.00',
'UV': '0',
'indoortempf': '67.8',
'indoorhumidity': '70',
'absbaromin': '29.831',
'baromin': '29.908',
'lowbatt': '0',
'dateutc': 'now',
'softwaretype': 'EasyWeatherPro_V5.2.2',
'action': 'updateraw',
'realtime': '1',
'rtfreq': '5'
}
# Bucle infinito que envía el GET cada X segundos
while True:
try:
response = requests.get(url_base, params=params)
print(f"[{time.strftime('%H:%M:%S')}] Status {response.status_code} - {response.url}")
except Exception as e:
print(f"❌ Error enviando request: {e}")
time.sleep(intervalo_segundos)