Compare commits

..

6 Commits

Author SHA1 Message Date
Exequiel Aramburu
2e2af3e169 Cambios 2026-09-27 20:04:22 -03:00
Exequiel Aramburu
2d4c7b5f36 save 2025-11-16 19:35:43 -03:00
Exequiel Aramburu
ed11169f36 Dejo de trackear carpetas ignoradas 2025-11-16 18:06:19 -03:00
Exequiel Aramburu
1c8c9a36bb Se modifica el correo. 2025-05-31 15:44:47 -03:00
920fff635b Actualizar src/gui/view/modelo_contacto.html
Se actualiza el correo
2024-12-10 10:22:14 -03:00
Exequiel Aramburu
d5f99dfd65 Se sube el codigo al nuevo repositorio. 2024-12-10 10:03:23 -03:00
60 changed files with 53423 additions and 3351 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
node_modules/
cache/
build/tmp/emalibre_nogui/
build/debs/*
!build/debs/readme.md

View File

@ -12,15 +12,26 @@ printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;4m5) Se actualizan las reglas de udev..\033[0m" printf "\033[1;4m5) Se actualizan las reglas de udev..\033[0m"
udevadm control --reload-rules udevadm control --reload-rules
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
if [ -f "/tmp/ConfiguracionGeneral.js" ]; then if [ -f "/tmp/ConfiguracionGeneral.js" ]; then
printf "\033[1;4m6) Se restaura el archivo de configuracion.\033[0m" printf "\033[1;4m6) Se restaura el archivo de configuracion.\033[0m"
mv -f /tmp/ConfiguracionGeneral.js /usr/share/emalibre/conf/ || true if [ -d "/usr/share/emalibre/conf/" ]; then
chmod 777 /usr/share/emalibre/conf/ConfiguracionGeneral.js mv -f /tmp/ConfiguracionGeneral.js /usr/share/emalibre/conf/
printf "\033[1;32m --> OK. \033[0m\n" chmod 777 /usr/share/emalibre/conf/ConfiguracionGeneral.js || true
else printf "\033[1;32m --> OK. \033[0m\n"
echo "" elif [ -d "/usr/share/emalibre/package.nw/conf/" ]; then
echo "IMPORTANTE: Archivo de configuracion por defecto. Por favor configurelo antes de comenzar: " mv -f /tmp/ConfiguracionGeneral.js /usr/share/emalibre/package.nw/conf/
printf "\033[1;36m --> /usr/share/emalibre/conf/ConfiguracionGeneral.js. \033[0m\n" chmod 777 /usr/share/emalibre/package.nw/conf/ConfiguracionGeneral.js || true
echo "" printf "\033[1;32m --> OK. \033[0m\n"
else
echo ""
echo "IMPORTANTE: No se encontró directorio de configuración. Por favor configurelo antes de comenzar: "
printf "\033[1;36m --> /usr/share/emalibre/conf/ConfiguracionGeneral.js. \033[0m\n"
echo ""
fi
else
echo ""
echo "IMPORTANTE: Archivo de configuracion por defecto. Por favor configurelo antes de comenzar: "
printf "\033[1;36m --> /usr/share/emalibre/conf/ConfiguracionGeneral.js. \033[0m\n"
echo ""
fi fi
exit 0 exit 0

View File

@ -10,7 +10,7 @@ pidFile="/var/run/emalibre.pid"
pidMonitorFile="/var/run/monitor_emalibre.pid" pidMonitorFile="/var/run/monitor_emalibre.pid"
echo "" echo ""
printf "\033[1;35m***************************************************************\n" printf "\033[1;35m***************************************************************\n"
printf "Estimado, gracias por instalar EMA Libre Cliente (Carpincho)!!.\n" printf "Gracias por instalar EMA Libre Cliente (Carpincho)!!.\n"
printf '***************************************************************\033[0m\n' printf '***************************************************************\033[0m\n'
echo "" echo ""
printf "\033[1;4m1) Comenzamos por verificar si ya existe configuracion personal...\033[0m\n" printf "\033[1;4m1) Comenzamos por verificar si ya existe configuracion personal...\033[0m\n"
@ -30,14 +30,18 @@ case "$1" in
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
# 1. Se consulta si existe el archivo de configuracion # 1. Se consulta si existe el archivo de configuracion
if [ -f "/usr/share/emalibre/conf/ConfiguracionGeneral.js" ]; then if [ -f "/usr/share/emalibre/conf/ConfiguracionGeneral.js" ]; then
printf "\033[1;10m * 1.1) Existe un archivo de configuracion, se realiza backups.\033[0m" printf "\033[1;10m * 1.1) Existe un archivo de configuración en conf/, se realiza backup.\033[0m"
cp -f /usr/share/emalibre/conf/ConfiguracionGeneral.js /tmp || true cp -f /usr/share/emalibre/conf/ConfiguracionGeneral.js /tmp || true
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
else elif [ -f "/usr/share/emalibre/package.nw/conf/ConfiguracionGeneral.js" ]; then
printf "\033[1;10m * 1.1) Es una instalación nueva, no existe archivo de configuracion.\033[0m" printf "\033[1;10m * 1.1) Existe un archivo de configuración en package.nw/conf/, se realiza backup.\033[0m"
printf "\033[1;32m --> OK. \033[0m\n" cp -f /usr/share/emalibre/package.nw/conf/ConfiguracionGeneral.js /tmp || true
printf "\033[1;32m --> OK. \033[0m\n"
else
printf "\033[1;10m * 1.1) Es una instalación nueva, no existe archivo de configuración.\033[0m"
printf "\033[1;32m --> OK. \033[0m\n"
fi fi
printf "\033[1;4m2) Comienza la instalacion:\033[0m\n" printf "\033[1;4m2) Comienza la instalación:\033[0m\n"
;; ;;
abort-upgrade) abort-upgrade)
printf "\033[1;31m Opps... ocurrio un error!!. \033[0m\n" printf "\033[1;31m Opps... ocurrio un error!!. \033[0m\n"

View File

@ -24,7 +24,6 @@ appFilePath="/usr/share/emalibre"
# Archivo de Inicio. # Archivo de Inicio.
web="gui_web/express.js" web="gui_web/express.js"
console="core/ema.js"
### END CONFIG ZONE ### END CONFIG ZONE
@ -46,23 +45,18 @@ export PATH=$PATH:$nodemodule
start() { start() {
if [ ! -f /etc/emalibre_modo ] if [ ! -f /etc/emalibre_modo ]
then then
`echo "consola" > /etc/emalibre_modo` `echo "web" > /etc/emalibre_modo`
fi fi
MODO=`cat /etc/emalibre_modo` MODO=`cat /etc/emalibre_modo`
if [ -f $pidFile ]; then if [ -f $pidFile ]; then
log_daemon_msg "EMA libre Carpincho se encuentra corriendo." log_daemon_msg "EMA libre Carpincho se encuentra corriendo."
RETVAL=$? RETVAL=$?
else else
if [ $MODO = 'consola' ] if [ $MODO = 'web' ]
then then
log_daemon_msg "Comenzando EMA Libre Carpincho en modo consola"
echo "$(date '+%d/%m/%Y %H:%M:%S') - 0|SERVICIO|Inicio el servicio en modo consola." >> $emaLogs
$foreverApp start --uid "EMA_Consola" --id "EMA_Consola" --minUptime 5000 --spinSleepTime 5000 --sourceDir $appFilePath --workingDir $appFilePath --pidFile $pidFile -l $logFile -a -d -c node "$console" console
RETVAL=$?
else
log_daemon_msg "Comenzando EMA Libre Carpincho en modo web" log_daemon_msg "Comenzando EMA Libre Carpincho en modo web"
echo "$(date '+%d/%m/%Y %H:%M:%S') - 0|SERVICIO|Inicio el servicio en modo web." >> $emaLogs echo "$(date '+%d/%m/%Y %H:%M:%S') - 0|SERVICIO|Inicio el servicio en modo web." >> $emaLogs
$foreverApp start --uid "EMA_Web" --id "EMA_Web" --minUptime 5000 --spinSleepTime 5000 --sourceDir $appFilePath --workingDir $appFilePath --pidFile $pidFile -l $logFile -a -d -c node "$web" encender $foreverApp start --uid "EMA_Web" --id "EMA_Web" --minUptime 5000 --spinSleepTime 5000 --sourceDir $appFilePath --workingDir $appFilePath --pidFile $pidFile -l $logFile -a -d -c node "$web" iniciar
RETVAL=$? RETVAL=$?
fi fi
fi fi
@ -103,8 +97,8 @@ uptime() {
reporte() { reporte() {
echo "$(date '+%d/%m/%Y %H:%M:%S') - 0|SERVICIO|Mostrando el reporte de consola." >> $emaLogs echo "$(date '+%d/%m/%Y %H:%M:%S') - 0|SERVICIO|Mostrando el reporte de consola." >> $emaLogs
pushd "$appFilePath/core" pushd "$appFilePath"
node reporte.js "$nodemodule/node" core/reporte.js
RETVAL=$? RETVAL=$?
} }
@ -135,30 +129,40 @@ then
uptime) uptime)
uptime uptime
;;
set-web)
log_daemon_msg "Se configuró EMA Libre en modo web."
`echo "web" > /etc/emalibre_modo`
;;
set-consola)
log_daemon_msg "Se configuró EMA Libre en modo consola."
`echo "consola" > /etc/emalibre_modo`
;; ;;
set-inicio-enabled) set-inicio-enabled)
log_daemon_msg "Se Habilito el servicio para inicio automatico." log_daemon_msg "Se Habilito el servicio para inicio automatico."
systemctl enable emalibre systemctl enable emalibre
"$nodemodule/node" -e "
const fs = require('fs');
const cfgPath = '/usr/share/emalibre/conf/ConfiguracionGeneral.js';
const cfg = require(cfgPath);
cfg.ConfGeneral.inicio_automatico = true;
fs.writeFileSync(
cfgPath,
'module.exports = ' + JSON.stringify(cfg, null, 2) + ';\n'
);
"
;; ;;
set-inicio-disable) set-inicio-disable)
log_daemon_msg "Se Deshabilito el inicio automatico del servicio." log_daemon_msg "Se Deshabilito el inicio automatico del servicio."
systemctl disable emalibre systemctl disable emalibre
"$nodemodule/node" -e "
const fs = require('fs');
const cfgPath = '/usr/share/emalibre/conf/ConfiguracionGeneral.js';
const cfg = require(cfgPath);
cfg.ConfGeneral.inicio_automatico = false;
fs.writeFileSync(
cfgPath,
'module.exports = ' + JSON.stringify(cfg, null, 2) + ';\n'
);
"
;; ;;
view-conf) view-conf)
log_daemon_msg "Configuración de EMA Libre Carpincho" log_daemon_msg "Configuración de EMA Libre Carpincho"
log_daemon_msg "-------------------------------------" log_daemon_msg "-------------------------------------"
CFG=/usr/share/emalibre/conf/ConfiguracionGeneral.js
if [ -f /etc/emalibre_modo ] if [ -f /etc/emalibre_modo ]
then then
log_daemon_msg "Modo actual: `cat /etc/emalibre_modo` " log_daemon_msg "Modo actual: `cat /etc/emalibre_modo` "
@ -175,77 +179,22 @@ then
log_daemon_msg "----------------------" log_daemon_msg "----------------------"
log_daemon_msg "Configuracion General:" log_daemon_msg "Configuracion General:"
log_daemon_msg "" log_daemon_msg ""
log_daemon_msg "-> Tiempo de Recolección: `sed -E 's/.*"Tiempo_de_Recoleccion":"?([^,"]*)"?.*/\1/' /usr/share/emalibre/conf/ConfiguracionGeneral.js |sed '1d' | sed '/^$/d'`" CFG=/usr/share/emalibre/conf/ConfiguracionGeneral.js
log_daemon_msg "-> UTC: `sed -E 's/.*"UTC":"?([^,"]*)"?.*/\1/' /usr/share/emalibre/conf/ConfiguracionGeneral.js |sed '1d' | sed '/^$/d'`" log_daemon_msg "-> Tiempo de Recolección: $(sed -nE 's/^[[:space:]]*"Tiempo_de_Recoleccion"[[:space:]]*:[[:space:]]*([0-9]+),?/\1/p' $CFG)"
log_daemon_msg "-> Nivel Debug: `sed -E 's/.*"debug":"?([^,"]*)"?.*/\1/' /usr/share/emalibre/conf/ConfiguracionGeneral.js |sed '1d' | sed '/^$/d'`" log_daemon_msg "-> UTC: $(sed -nE 's/^[[:space:]]*"UTC"[[:space:]]*:[[:space:]]*(-?[0-9]+),?/\1/p' $CFG)"
log_daemon_msg "-> Sistema Métrico: $(sed -nE 's/^[[:space:]]*"SistemaMetrico"[[:space:]]*:[[:space:]]*"([^"]+)",?/\1/p' $CFG)"
;; log_daemon_msg "-> Nivel Debug: $(sed -nE 's/^[[:space:]]*"debug"[[:space:]]*:[[:space:]]*([0-9]+),?/\1/p' $CFG)"
*) log_daemon_msg "-> Tamaño Debug: $(sed -nE 's/^[[:space:]]*"debugTamanio"[[:space:]]*:[[:space:]]*([0-9]+),?/\1/p' $CFG)"
echo "Utilice: {start|stop|status|restart|set-web|set-consola|set-inicio-enabled|set-inicio-disable|view-conf|reporte|uptime}" log_daemon_msg "-> Nombre Estación: $(sed -nE 's/^[[:space:]]*"NombreEstacion"[[:space:]]*:[[:space:]]*"([^"]+)",?/\1/p' $CFG)"
exit 1 log_daemon_msg "-> Modo: $(sed -nE 's/^[[:space:]]*"Modo"[[:space:]]*:[[:space:]]*"([^"]+)",?/\1/p' $CFG)"
log_daemon_msg "-> Llave R: $(sed -nE 's/^[[:space:]]*"Llave_R"[[:space:]]*:[[:space:]]*"([^"]+)",?/\1/p' $CFG)"
;; log_daemon_msg "-> Inicio automático: $(sed -nE 's/^[[:space:]]*"inicio_automatico"[[:space:]]*:[[:space:]]*(true|false),?/\1/p' $CFG)"
esac log_daemon_msg "-> Audio: $(sed -nE 's/^[[:space:]]*"Audio"[[:space:]]*:[[:space:]]*(true|false),?/\1/p' $CFG)"
else log_daemon_msg "-> Notificar cambios: $(sed -nE 's/^[[:space:]]*"notificar_cambios"[[:space:]]*:[[:space:]]*(true|false),?/\1/p' $CFG)"
# SI NO EXISTE EL MODULO GUI_WEB se habilitan solo modo consola log_daemon_msg "-> Audio Voces: $(sed -nE 's/^[[:space:]]*"audioVoces"[[:space:]]*:[[:space:]]*"([^"]+)",?/\1/p' $CFG)"
case "$1" in log_daemon_msg "-> IP: $(sed -nE 's/^[[:space:]]*"IP"[[:space:]]*:[[:space:]]*"([^"]+)",?/\1/p' $CFG)"
start) log_daemon_msg "-> Puerto: $(sed -nE 's/^[[:space:]]*"Puerto"[[:space:]]*:[[:space:]]*"([^"]+)",?/\1/p' $CFG)"
start log_daemon_msg "-> Ruta: $(sed -nE 's/^[[:space:]]*"Ruta"[[:space:]]*:[[:space:]]*"([^"]+)",?/\1/p' $CFG)"
;;
stop)
stop
;;
status)
status
;;
restart)
restart
;;
reporte)
reporte
;;
uptime)
uptime
;;
set-inicio-enabled)
log_daemon_msg "Se Habilito el servicio para inicio automatico."
systemctl enable emalibre
;;
set-inicio-disable)
log_daemon_msg "Se Deshabilito el inicio automatico del servicio."
systemctl disable emalibre
;;
view-conf)
log_daemon_msg "Configuración de EMA Libre Carpincho"
log_daemon_msg "-------------------------------------"
if [ -f /etc/emalibre_modo ]
then
log_daemon_msg "Modo actual: `cat /etc/emalibre_modo` "
else
`echo "consola" > /etc/emalibre_modo`
log_daemon_msg "Modo actual: `cat /etc/emalibre_modo` "
fi
log_daemon_msg "Inicio Automatico (servicio): `systemctl is-enabled emalibre 2> echo`"
log_daemon_msg ""
log_daemon_msg "----------------------"
log_daemon_msg "Configuracion Global:"
log_daemon_msg "->`grep "Version" /usr/share/emalibre/conf/ConfiguracionGlobal.js`"
log_daemon_msg "->`grep "Nombre" /usr/share/emalibre/conf/ConfiguracionGlobal.js`"
log_daemon_msg "----------------------"
log_daemon_msg "Configuracion General:"
log_daemon_msg ""
log_daemon_msg "-> Tiempo de Recolección: `sed -E 's/.*"Tiempo_de_Recoleccion":"?([^,"]*)"?.*/\1/' /usr/share/emalibre/conf/ConfiguracionGeneral.js |sed '1d' | sed '/^$/d'`"
log_daemon_msg "-> UTC: `sed -E 's/.*"UTC":"?([^,"]*)"?.*/\1/' /usr/share/emalibre/conf/ConfiguracionGeneral.js |sed '1d' | sed '/^$/d'`"
log_daemon_msg "-> Nivel Debug: `sed -E 's/.*"debug":"?([^,"]*)"?.*/\1/' /usr/share/emalibre/conf/ConfiguracionGeneral.js |sed '1d' | sed '/^$/d'`"
;; ;;
*) *)
echo "Utilice: {start|stop|status|restart|set-inicio-enabled|set-inicio-disable|view-conf|reporte|uptime}" echo "Utilice: {start|stop|status|restart|set-inicio-enabled|set-inicio-disable|view-conf|reporte|uptime}"

View File

@ -2,7 +2,7 @@
module.exports = { module.exports = {
"ConfGeneral": { "ConfGeneral": {
"Tiempo_de_Recoleccion": 40, "Tiempo_de_Recoleccion": 60,
"UTC": -3, "UTC": -3,
"SistemaMetrico": "SI", "SistemaMetrico": "SI",
"debug": 3, "debug": 3,
@ -11,13 +11,16 @@ module.exports = {
"Modo": "Recolector", "Modo": "Recolector",
"Llave_R": "e5303ab3-2a8b-4d42-90ab-1c8367d8521d", "Llave_R": "e5303ab3-2a8b-4d42-90ab-1c8367d8521d",
"inicio_automatico": false, "inicio_automatico": false,
"Audio": true, "Audio": false,
"notificar_cambios": true, "notificar_cambios": false,
"audioVoces": "Spanish_(Latin_America) espeak-ng" "audioVoces": "Spanish_(Latin_America) espeak-ng",
"IP": "",
"Puerto": "",
"Ruta": ""
}, },
"ConfEmail": { "ConfEmail": {
"ActivarCorreos": false, "ActivarCorreos": false,
"ReceptorEmail": "-", "ReceptorEmail": "",
"Servicio": "Deshabilitado", "Servicio": "Deshabilitado",
"Usuario": "", "Usuario": "",
"Password": "", "Password": "",

View File

@ -1,15 +0,0 @@
Package: emalibre-console
Architecture: armhf
Version: 1.30
Priority: optional
Section: application
Maintainer: Laboratorio de Investigacion Gugler <contacto@gugler.com.ar>
Homepage: https://ema.gugler.com.ar
Depends:
Conflicts: emalibre-gui, emalibre-web
Description: EMA Libre Cliente (Carpincho) - Software Libre en modo consola para Estaciones Meteorológica Automáticas.
EMA Libre es Libre y Gratuito desarrollado por el Laboratorio de Investigación Gugler
perteneciente a la Facultad de Ciencia y Tecnología de la Universidad
Autónoma de Entre Ríos, con el objetivo de recolectar, registrar y publicar
información meteorológica a través de los diferentes sensores de una estación USB compatible
(ej: ws1080, wh3101, wh3104 y otras).

View File

@ -1,15 +1,15 @@
Package: emalibre-gui Package: emalibre-gui
Architecture: armhf Architecture: armhf
Version: 1.30 Version: 1.36
Priority: optional Priority: optional
Section: application Section: application
Maintainer: Laboratorio de Investigacion Gugler <contacto@gugler.com.ar> Maintainer: Laboratorio de Investigacion Gugler <gugler_contacto@uader.edu.ar>
Homepage: https://ema.gugler.com.ar Homepage: https://ema.gugler.com.ar
Depends: Depends:
Conflicts: emalibre-console, emalibre-web Conflicts: emalibre-web
Description: EMA Libre Cliente (Carpincho) - Software Libre en modo GUI (desktop) para Estaciones Meteorológica Automáticas. Description: EMA Libre Cliente (Carpincho) - Software Libre en modo GUI (desktop) para Estaciones Meteorológica Automáticas.
EMA Libre es Libre y Gratuito desarrollado por el Laboratorio de Investigación Gugler EMA Libre es Libre y Gratuito desarrollado por el Laboratorio de Investigación Gugler
perteneciente a la Facultad de Ciencia y Tecnología de la Universidad perteneciente a la Facultad de Ciencia y Tecnología de la Universidad
Autónoma de Entre Ríos, con el objetivo de recolectar, registrar y publicar Autónoma de Entre Ríos, con el objetivo de recolectar, registrar y publicar
información meteorológica a través de los diferentes sensores de una estación USB compatible información meteorológica a través de los diferentes sensores de una estación USB y/o IP compatible
(ej: ws1080, wh3101, wh3104 y otras). (ej: ws1080, wh3101, wh3104 y otras).

View File

@ -1,15 +1,17 @@
Package: emalibre-web Package: emalibre-web
Architecture: armhf Architecture: arm64
Version: 1.30 Version: 1.36
Priority: optional Priority: optional
Section: application Section: utils
Maintainer: Laboratorio de Investigacion Gugler <contacto@gugler.com.ar> Maintainer: Laboratorio de Investigacion Gugler <gugler_contacto@uader.edu.ar>
Homepage: https://ema.gugler.com.ar Homepage: https://ema.gugler.com.ar
Depends: Depends: nodejs (>= 14), libusb-1.0-0, libudev1
Conflicts: emalibre-gui, emalibre-console Conflicts: emalibre-gui
Description: EMA Libre Cliente (Carpincho) - Software Libre en modo web y consola para Estaciones Meteorológica Automáticas. Description: EMA Libre Cliente (Carpincho)
EMA Libre es Libre y Gratuito desarrollado por el Laboratorio de Investigación Gugler Software Libre en modo web y consola para Estaciones Meteorológicas Automáticas.
perteneciente a la Facultad de Ciencia y Tecnología de la Universidad EMA Libre es software libre y gratuito desarrollado por el Laboratorio de
Autónoma de Entre Ríos, con el objetivo de recolectar, registrar y publicar Investigación Gugler perteneciente a la Facultad de Ciencia y Tecnología de la
información meteorológica a través de los diferentes sensores de una estación USB compatible Universidad Autónoma de Entre Ríos, con el objetivo de recolectar, registrar y
(ej: ws1080, wh3101, wh3104 y otras). publicar información meteorológica a través de sensores USB y/o IP compatibles
(ej: ws1080, wh3101, wh3104 y otros).
Diseñado para Raspberry Pi OS 64-bit.

View File

@ -1,15 +0,0 @@
Package: emalibre-console
Architecture: amd64
Version: 1.30
Priority: optional
Section: application
Maintainer: Laboratorio de Investigacion Gugler <contacto@gugler.com.ar>
Homepage: https://ema.gugler.com.ar
Depends:
Conflicts: emalibre-gui, emalibre-web
Description: EMA Libre Cliente (Carpincho) - Software Libre en modo consola para Estaciones Meteorológica Automáticas.
EMA Libre es Libre y Gratuito desarrollado por el Laboratorio de Investigación Gugler
perteneciente a la Facultad de Ciencia y Tecnología de la Universidad
Autónoma de Entre Ríos, con el objetivo de recolectar, registrar y publicar
información meteorológica a través de los diferentes sensores de una estación USB compatible
(ej: ws1080, wh3101, wh3104 y otras).

View File

@ -1,15 +1,15 @@
Package: emalibre-gui Package: emalibre-gui
Architecture: amd64 Architecture: amd64
Version: 1.30 Version: 1.36
Priority: optional Priority: optional
Section: application Section: application
Maintainer: Laboratorio de Investigacion Gugler <contacto@gugler.com.ar> Maintainer: Laboratorio de Investigacion Gugler <gugler_contacto@uader.edu.ar>
Homepage: https://ema.gugler.com.ar Homepage: https://ema.gugler.com.ar
Depends: Depends:
Conflicts: emalibre-console, emalibre-web Conflicts: emalibre-web
Description: EMA Libre Cliente (Carpincho) - Software Libre en modo GUI (desktop) para Estaciones Meteorológica Automáticas. Description: EMA Libre Cliente (Carpincho) - Software Libre en modo GUI (desktop) para Estaciones Meteorológica Automáticas.
EMA Libre es Libre y Gratuito desarrollado por el Laboratorio de Investigación Gugler EMA Libre es Libre y Gratuito desarrollado por el Laboratorio de Investigación Gugler
perteneciente a la Facultad de Ciencia y Tecnología de la Universidad perteneciente a la Facultad de Ciencia y Tecnología de la Universidad
Autónoma de Entre Ríos, con el objetivo de recolectar, registrar y publicar Autónoma de Entre Ríos, con el objetivo de recolectar, registrar y publicar
información meteorológica a través de los diferentes sensores de una estación USB compatible información meteorológica a través de los diferentes sensores de una estación USB y/o IP compatible
(ej: ws1080, wh3101, wh3104 y otras). (ej: ws1080, wh3101, wh3104 y otras).

View File

@ -1,15 +1,15 @@
Package: emalibre-web Package: emalibre-web
Architecture: amd64 Architecture: amd64
Version: 1.30 Version: 1.36
Priority: optional Priority: optional
Section: application Section: application
Maintainer: Laboratorio de Investigacion Gugler <contacto@gugler.com.ar> Maintainer: Laboratorio de Investigacion Gugler <gugler_contacto@uader.edu.ar>
Homepage: https://ema.gugler.com.ar Homepage: https://ema.gugler.com.ar
Depends: Depends:
Conflicts: emalibre-gui, emalibre-console Conflicts: emalibre-gui
Description: EMA Libre Cliente (Carpincho) - Software Libre en modo web y consola para Estaciones Meteorológica Automáticas. Description: EMA Libre Cliente (Carpincho) - Software Libre en modo web y consola para Estaciones Meteorológica Automáticas.
EMA Libre es Libre y Gratuito desarrollado por el Laboratorio de Investigación Gugler EMA Libre es Libre y Gratuito desarrollado por el Laboratorio de Investigación Gugler
perteneciente a la Facultad de Ciencia y Tecnología de la Universidad perteneciente a la Facultad de Ciencia y Tecnología de la Universidad
Autónoma de Entre Ríos, con el objetivo de recolectar, registrar y publicar Autónoma de Entre Ríos, con el objetivo de recolectar, registrar y publicar
información meteorológica a través de los diferentes sensores de una estación USB compatible información meteorológica a través de los diferentes sensores de una estación USB y/o IP compatible
(ej: ws1080, wh3101, wh3104 y otras). (ej: ws1080, wh3101, wh3104 y otras).

View File

@ -1 +0,0 @@
En este directorio quedan los debs, al compilar

View File

@ -1 +0,0 @@
Directorio temporal para la compilacion.

View File

@ -1,22 +1,18 @@
// Libreria import nwbuild from 'nw-builder';
var NwBuilder = require('nw-builder');
// Definiciones
var nw = new NwBuilder({ // 3. Configurar nw-builder para usar el directorio temporal como appDir
appDir: './src', // COMPILADOR: Directorio de la Aplicacion await nwbuild({
files: ['./src/**', '!./src/node_module/mocha/**', '!./src/node_module/chai/**', '!./src/package-lock.json'], // COMPILADOR: Directorio de Codigo Fuente a compilar srcDir: './src', // Usamos el directorio temporal como fuente
platforms: ['linux64'], // COMPILADOR: Plataformas Linux a compilar file: './src/package.json',
version: '0.94.0', // COMPILADOR: Version del Compilador platforms: ['linux64'],
flavor: 'normal', // opciones sdk, normal glob: false,
buildDir: 'build', // COMPILADOR: Destino de la compilacion. version: '0.94.0',
zip: false, // COMPILADOR: No comprimir (False) flavor: 'normal',
appName: 'emalibre' // APLICACION: Nombre de la aplicacion. buildDir: './build/emalibre',
}); outDir: './build/emalibre',
// Logs zip: false,
//nw.on('log', console.log); appName: 'emalibre'
nw.onLog = console.log;
// Construir
nw.build().then(function () {
console.log('Correcto!');
}).catch(function (error) {
console.error(error);
}); });
console.log('Correcto!');

View File

@ -1,16 +1,33 @@
#!/bin/bash #!/bin/bash
set -e
#PARAMETRIA # Pide la contraseña de sudo al principio (si no tiene permisos)
VERSION=`grep Version src/conf/ConfiguracionGlobal.js | sed -e "s/'Version': //g" | sed -e "s/,//g" | sed -e "s/^[ \t]*//"` if ! sudo -v; then
NWJS_VERSION='0.94.0' echo "Este script requiere permisos de sudo para algunas operaciones."
exit 1
fi
# DEPENDENCIAS # Refresca el tiempo de sudo mientras el script corre
NW_GYP_INST=`npm list -g | grep nw-gyp@ | grep -v deduped | wc -l` while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &
NW_BUILDER_INST=`npm list | grep nw-builder@ | grep -v deduped | wc -l`
node=`node -v | wc -l` # =======================
npm=`npm -v | wc -l` # VARIABLES Y FUNCIONES
# =======================
BUILD_DIR="build"
DEB_DIR="$BUILD_DIR/Deb64"
DEBS_OUT="$BUILD_DIR/debs"
TMP_DIR="$BUILD_DIR/tmp"
EMALIBRE_DIR="$BUILD_DIR/emalibre"
EMALIBRE_NOGUI="$TMP_DIR/emalibre_nogui"
CONTROL_DEB="$BUILD_DIR/controlDeb"
LOG_FILE="/tmp/ema.log"
function log_info() { printf "\033[1;10m$1\033[0m"; }
function log_ok() { printf "\033[1;32m$1\033[0m\n"; }
function log_warn() { printf "\033[1;33m$1\033[0m\n"; }
function log_error() { printf "\033[1;31m$1\033[0m\n"; }
function log_final() { printf "\033[5;10m$1\033[0m\n"; }
# Metodo Spinner
function spinner() { function spinner() {
local info="$1" local info="$1"
local pid=$! local pid=$!
@ -29,250 +46,242 @@ function spinner() {
done done
printf " \b\b\b\b" printf " \b\b\b\b"
} }
# ***********************************************************
# EJECUCION DE CODIGO -- LIMPIA Y VERIFICA ENTORNO # =======================
# *********************************************************** # VERSIONES
# =======================
VERSION=$(grep Version src/conf/ConfiguracionGlobal.js | sed -e "s/'Version': //g" | sed -e "s/,//g" | sed -e "s/^[ \t]*//")
NWJS_VERSION='0.94.0'
# =======================
# INICIO
# =======================
echo "" echo ""
echo "*************************************************" echo "*************************************************"
echo "* Comprobando y preparando el entorno ***" echo "* Comprobando y preparando el entorno ***"
echo "*************************************************" echo "*************************************************"
echo "" echo ""
printf "\033[1;4m--->Version de EmaL: $VERSION \033[0m\n" log_info "--->Versión de EmaLibre: $VERSION \n"
printf "\033[1;4m--->Version de NWJs: $NWJS_VERSION \033[0m\n" log_info "----- >Versión de NW.Js: $NWJS_VERSION \n"
echo "" echo ""
printf "\033[1;10m1) Limpiando compilacion anterior. \033[0m"
sudo mkdir build/Deb64/usr/bin 2> /dev/null # =======================
sudo mkdir build/Deb64/usr/share/emalibre 2> /dev/null # LIMPIEZA Y PREPARACIÓN
sudo rm -fr build/emalibre/linux64 # =======================
sudo rm -fr build/Deb64/usr/bin/* log_info "1) Limpiando compilación anterior."
sudo rm -fr build/Deb64/usr/share/emalibre/* mkdir -p "$DEB_DIR/usr/bin" "$DEB_DIR/usr/share/emalibre" "$DEBS_OUT"
printf "\033[1;32m --> OK. \033[0m\n" sudo rm -rf "$EMALIBRE_DIR"/* "$TMP_DIR/emalibre_nogui" "$DEB_DIR/usr/bin/"* "$DEB_DIR/usr/share/emalibre/"*
printf "\033[1;10m2) Instalando/comprobando paquetes con APT necesarios. \033[0m" log_ok " --> OK."
# =======================
# DEPENDENCIAS DEL SISTEMA
# =======================
log_info "2) Instalando/comprobando paquetes con APT necesarios."
sudo apt-get -y -qq install build-essential git wget libusb-1.0-0 libusb-1.0-0-dev libudev-dev sudo apt-get -y -qq install build-essential git wget libusb-1.0-0 libusb-1.0-0-dev libudev-dev
sudo chmod -R 777 build/Deb64 sudo chmod -R 755 "$DEB_DIR"
printf "\033[1;32m --> OK. \033[0m\n" log_ok " --> OK."
printf "\033[1;10m3) Verificando node y dependencias: \033[0m\n"
printf "\033[1;10m 3.1) Comprobando si esta node global. \033[0m" # =======================
if [ $node -eq 1 ] # DEPENDENCIAS NODE/NPM
then # =======================
printf "\033[1;32m --> OK. \033[0m\n" log_info "3) Verificando node y dependencias:\n"
else
printf "\033[1;31m --> NO. \033[0m" if ! command -v node >/dev/null 2>&1; then
printf "\033[1;32m --> Se sale, por favor instale manualmente. \033[0m\n" log_error " --> Node.js no está instalado. Instálelo manualmente."
exit 0 exit 1
else
log_ok " 3.1) Node.js OK."
fi fi
printf "\033[1;10m 3.2) Comprobando si esta npm global. \033[0m"
if [ $npm -eq 1 ] if ! command -v npm >/dev/null 2>&1; then
then log_error " --> npm no está instalado. Instálelo manualmente."
printf "\033[1;32m --> OK. \033[0m\n" exit 1
else else
printf "\033[1;31m --> NO. \033[0m" log_ok " 3.2) npm OK."
printf "\033[1;32m --> Se sale, por favor instale manualmente. \033[0m\n"
exit 0
fi fi
printf "\033[1;10m 3.3) Comprobando si esta nw-gyp como global. \033[0m"
if [ $NW_GYP_INST -eq 1 ] if ! npm list -g --depth=0 | grep -q nw-gyp@; then
then log_warn " 3.3) nw-gyp no encontrado globalmente. Instalando..."
printf "\033[1;32m --> OK. \033[0m\n" npm install -g nw-gyp --no-audit --silent 2>>"$LOG_FILE" 1>/dev/null
else log_ok " --> nw-gyp instalado."
printf "\033[1;31m --> NO. \033[0m" else
npm install -g nw-gyp -no-audit -silent 2> /tmp/ema.log 1> /dev/null log_ok " 3.3) nw-gyp OK."
printf "\033[1;32m --> Se instalo. \033[0m\n"
fi fi
printf "\033[1;10m 3.4) Comprobando si nw-builder localmente. \033[0m"
if [ $NW_BUILDER_INST -eq 1 ] if ! npm list --depth=0 | grep -q nw-builder@; then
then log_warn " 3.4) nw-builder no encontrado localmente. Instalando..."
printf "\033[1;32m --> OK. \033[0m\n" npm install --no-audit --silent 2>>"$LOG_FILE" 1>/dev/null
else log_ok " --> nw-builder instalado."
printf "\033[1;31m --> NO. \033[0m" else
npm install -no-audit -silent 2> /tmp/ema.log 1> /dev/null log_ok " 3.4) nw-builder OK."
printf "\033[1;32m --> Se instalo. \033[0m\n"
fi fi
printf "\033[1;10m4) Empaquetando el proyecto emalibre. \033[0m"
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 # EMPAQUETADO
printf "\033[1;10m5) Aplicando Permisos al proyecto. \033[0m" # =======================
sudo chmod -R 777 build/emalibre/linux64 & spinner "Procesando..." log_info "4) Empaquetando el proyecto emalibre."
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m6) Eliminando node_modules del proyecto. \033[0m" if node empaquetarLinux.js | grep -q "Correcto!"; then
sudo rm -fr build/emalibre/linux64/node_modules & spinner "Procesando..." log_ok " --> OK. "
printf "\033[1;32m --> OK. \033[0m\n" else
printf "\033[1;10m7) Generando node_modules con NPM del proyecto. \033[0m" log_error " --> ERROR. Problema empaquetando con nw-builder."
cd build/emalibre/linux64 exit 1
npm install ---production -no-audit -silent 2> /tmp/ema.log 1> /dev/null fi
printf "\033[1;32m --> OK. \033[0m\n";
printf "\033[1;10m8) Se purgan los tanques y logs. \033[0m" # =======================
sudo echo "" > logs/debug.log # PERMISOS Y NODE_MODULES
sudo echo "[]" > logs/TanquePendientes.log # =======================
sudo echo "[]" > logs/registro_diario.log log_info "5) Aplicando Permisos al proyecto."
printf "\033[1;32m --> OK. \033[0m\n"; sudo chmod -R 755 "$EMALIBRE_DIR/package.nw"
printf "\033[1;10m9) Se blanquea el archivo de Configuracion General. \033[0m" log_ok " --> OK."
sudo cp ../../conf/ConfiguracionGeneral.js conf/ConfiguracionGeneral.js
printf "\033[1;32m --> OK. \033[0m\n"; log_info "6) Eliminando node_modules del proyecto."
cd .. rm -rf "$EMALIBRE_DIR/package.nw/node_modules"
sudo cp -R linux64 Linux64_nogui # Se copia antes del postLINUX (que implementa NWJS) para el modo consola y web log_ok " --> OK."
sudo chmod -R 777 Linux64_nogui
cd linux64 log_info "7) Generando node_modules con NPM del proyecto."
npm run postLINUX -no-audit -silent 2> /tmp/ema.log 1> /dev/null & spinner "Procesando..." cd "$EMALIBRE_DIR/package.nw"
CHECK_NW_NODE_BUILD=`cat /tmp/ema.log | grep "gyp info ok" | wc -l` npm ci --only=production --no-audit --silent 2>>"$LOG_FILE" 1>/dev/null
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 log_ok " --> OK."
# =======================
# LIMPIEZA DE LOGS Y CONFIG
# =======================
log_info "8) Se purgan los tanques y logs."
: > logs/debug.log
echo "[]" > logs/TanquePendientes.log
echo "[]" > logs/registro_diario.log
log_ok " --> OK."
log_info "9) Se blanquea el archivo de Configuracion General."
cp ../../conf/ConfiguracionGeneral.js conf/ConfiguracionGeneral.js
log_ok " --> OK."
cd ../../.. cd ../../..
# ************************************************************** log_info "9.1) Se copia emalibre antes de implementar el módulo node-hid con NWJS."
# Compilar EMA Libre Cliente (Carpincho) en modo GRAFICO Desktop cp -R "$EMALIBRE_DIR" "$TMP_DIR/emalibre_nogui"
# ************************************************************** chmod -R 755 "$TMP_DIR/emalibre_nogui"
echo "" cd "$EMALIBRE_DIR/package.nw"
echo "" log_ok " --> OK."
echo "*************************************************"
echo "* Build EMA Libre Cliente Grafico - GNU/Linux *" log_info "10) Corriendo el post-script para el rebuild del módulo node-hid en i64."
echo "*************************************************" npm run postLINUX --no-audit --silent 2>>"$LOG_FILE" 1>/dev/null & spinner "Procesando..."
echo "" if grep -q "gyp info ok" "$LOG_FILE"; then
printf "\033[1;10m1) Limpiando archivos temporales. \033[0m" log_ok " --> OK. "
sudo rm -f build/Deb64/DEBIAN/control else
sudo rm -fr build/Deb64/usr/bin/* log_error " --> ERROR. Verifique el módulo NW con node-hid."
sudo rm -fr build/Deb64/usr/share/emalibre/* exit 1
printf "\033[1;32m --> OK. \033[0m\n" fi
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/
printf "\033[1;32m --> OK. \033[0m\n"
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..."
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m4) Aplicando permisos necesarios. \033[0m"
sudo chmod +x build/Deb64/usr/share/emalibre/emalibre
sudo chmod 0755 build/Deb64/DEBIAN
sudo chmod 0755 build/Deb64/DEBIAN/postrm
sudo chmod 0755 build/Deb64/DEBIAN/postinst
sudo chmod 0755 build/Deb64/DEBIAN/preinst
sudo chown -R root:root build/Deb64
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m5) Generando enlaces simbolicos del binario. \033[0m"
cd build/Deb64/usr/bin/
sudo ln -s ../share/emalibre/emalibre emalibre
cd ../../.. cd ../../..
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m6) Eliminando node/web/express/forever/servicio para modo GUI y la intefaz para consola/web. \033[0m"
# se mueve el servicio desde al temporal
sudo mv Deb64/etc/init.d tmp
sudo mv Deb64/etc/emalibre_modo tmp
sudo rm -fr Deb64/usr/share/emalibre/node_modules/node
sudo rm -fr Deb64/usr/share/emalibre/node_modules/express
sudo rm -fr Deb64/usr/share/emalibre/node_modules/forever
sudo rm -fr Deb64/usr/share/emalibre/node_modules/forever-agent
sudo rm -fr Deb64/usr/share/emalibre/node_modules/forever-monitor
sudo rm -fr Deb64/usr/share/emalibre/gui_web
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m7) Generando Paquete Deb para GUI 64bit Linux. \033[0m\n"
sudo dpkg -b Deb64 debs/"emalibre-gui-linux_$VERSION.deb"
# se vuelve el servicio desde el temporal
sudo mv tmp/init.d Deb64/etc
sudo mv tmp/emalibre_modo Deb64/etc/emalibre_modo
printf "\033[5;10m Finalizo con exito, build/debs/emalibre-gui-linux_$VERSION.deb. \033[0m"
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m8) Limpiando archivos temporales. \033[0m"
cd ..
sudo rm -f build/Deb64/DEBIAN/control
sudo rm -fr build/Deb64/usr/bin/*
sudo rm -fr build/Deb64/usr/share/emalibre/*
printf "\033[1;32m --> OK. \033[0m\n"
# *********************************************************** # =======================
# Compilar EMA Libre Cliente (Carpincho) en modo CONSOLA # BUILD GUI DESKTOP
# *********************************************************** # =======================
echo ""
echo "" echo ""
echo "*************************************************" echo "*************************************************"
echo "* Build EMA Libre Cliente Consola - GNU/Linux *" echo "* Build EMA Libre Cliente Gráfico - GNU/Linux *"
echo "*************************************************" echo "*************************************************"
echo "" echo ""
printf "\033[1;10m1) Limpiando archivos temporales. \033[0m" log_info "1) Limpiando archivos temporales."
sudo rm -f build/Deb64/DEBIAN/control sudo rm -f "$DEB_DIR/DEBIAN/control"
sudo rm -fr build/Deb64/usr/bin/* sudo rm -rf "$DEB_DIR/usr/bin/"* "$DEB_DIR/usr/share/emalibre/"*
sudo rm -fr build/Deb64/usr/share/emalibre/* log_ok " --> OK."
printf "\033[1;32m --> OK. \033[0m\n"
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/Linux64_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/Linux64_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/Linux64_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/Linux64_nogui/AUTHORS build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/package.json build/Deb64/usr/share/emalibre/
printf "\033[1;32m --> OK. \033[0m\n"
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..."
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m4) Aplicando permisos necesarios. \033[0m"
sudo chmod 0755 build/Deb64/DEBIAN
sudo chmod 0755 build/Deb64/DEBIAN/postrm
sudo chmod 0755 build/Deb64/DEBIAN/postinst
sudo chmod 0755 build/Deb64/DEBIAN/preinst
sudo chown -R root:root build/Deb64
printf "\033[1;32m --> OK. \033[0m\n"
cd build
printf "\033[1;10m7) Generando Paquete Deb para Consola 64bit Linux. \033[0m\n"
sudo dpkg -b Deb64 debs/"emalibre-consola-linux_$VERSION.deb"
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;10m8) Limpiando archivos temporales. \033[0m"
cd ..
sudo rm -f build/Deb64/DEBIAN/control
sudo rm -fr build/Deb64/usr/bin/*
sudo rm -fr build/Deb64/usr/share/emalibre/*
printf "\033[1;32m --> OK. \033[0m\n"
echo ""
# *********************************************************** log_info "2) Copiando los fuentes de EMA Libre para 64 bits."
# Compilar EMA Libre Cliente (Carpincho) en modo CONSOLA/WEB sudo cp -R "$EMALIBRE_DIR/"* "$DEB_DIR/usr/share/emalibre/"
# *********************************************************** log_ok " --> OK."
echo ""
log_info "3) Reemplazando el archivo de control DEB."
sudo cp -f "$CONTROL_DEB/control_linux_gui" "$DEB_DIR/DEBIAN/control"
log_ok " --> OK."
log_info "4) Aplicando permisos necesarios."
sudo chmod +x "$DEB_DIR/usr/share/emalibre/emalibre"
sudo chmod 0755 "$DEB_DIR/DEBIAN" "$DEB_DIR/DEBIAN/postrm" "$DEB_DIR/DEBIAN/postinst" "$DEB_DIR/DEBIAN/preinst"
sudo chown -R root:root "$DEB_DIR"
log_ok " --> OK."
log_info "5) Generando enlaces simbólicos del binario."
cd "$DEB_DIR/usr/bin/"
sudo ln -sf ../share/emalibre/emalibre emalibre
cd ../../..
log_ok " --> OK."
log_info "6) Eliminando node/web/express/forever/servicio para modo GUI y la interfaz para el modo web."
sudo mv "$DEB_DIR/etc/init.d" "$TMP_DIR" 2>/dev/null || true
sudo mv "$DEB_DIR/etc/emalibre_modo" "$TMP_DIR" 2>/dev/null || true
sudo rm -rf "$DEB_DIR/usr/share/emalibre/node_modules/node" \
"$DEB_DIR/usr/share/emalibre/node_modules/express" \
"$DEB_DIR/usr/share/emalibre/node_modules/forever" \
"$DEB_DIR/usr/share/emalibre/node_modules/forever-agent" \
"$DEB_DIR/usr/share/emalibre/node_modules/forever-monitor" \
"$DEB_DIR/usr/share/emalibre/gui_web"
log_ok " --> OK."
log_info "7) Generando Paquete DEB para GUI 64 bits Linux."
#sudo dpkg -b Deb64 debs/"emalibre-gui-linux_$VERSION.deb"
sudo dpkg-deb -Zxz -b Deb64 debs/"emalibre-gui-linux_$VERSION.deb"
cd ..
mv "$TMP_DIR/init.d" "$DEB_DIR/etc" 2>/dev/null || true
mv "$TMP_DIR/emalibre_modo" "$DEB_DIR/etc/emalibre_modo" 2>/dev/null || true
log_final " Finalizó con éxito, build/debs/emalibre-gui-linux_$VERSION.deb."
log_ok " --> OK."
log_info "8) Limpiando archivos temporales."
sudo rm -f "$DEB_DIR/DEBIAN/control"
sudo rm -rf "$DEB_DIR/usr/bin/"* "$DEB_DIR/usr/share/emalibre/"*
log_ok " --> OK."
# =======================
# BUILD CONSOLA/WEB
# =======================
echo "" echo ""
echo "*************************************************" echo "*************************************************"
echo "* Build EMA Libre Cliente Web - GNU/Linux *" echo "* Build EMA Libre Cliente Web - GNU/Linux *"
echo "*************************************************" echo "*************************************************"
echo "" echo ""
printf "\033[1;10m1) Limpiando archivos temporales. \033[0m" log_info "1) Limpiando archivos temporales."
sudo rm -f build/Deb64/DEBIAN/control rm -f "$DEB_DIR/DEBIAN/control"
sudo rm -fr build/Deb64/usr/bin/* rm -rf "$DEB_DIR/usr/bin/"* "$DEB_DIR/usr/share/emalibre/"*
sudo rm -fr build/Deb64/usr/share/emalibre/* log_ok " --> OK."
printf "\033[1;32m --> OK. \033[0m\n" log_info "2) Copiando los fuentes de EMA Libre para 64bit."
printf "\033[1;10m2) Copiando los fuentes de EMA Libre para 64bit. \033[0m" sudo cp -R "$TMP_DIR/emalibre_nogui/package.nw/core" "$DEB_DIR/usr/share/emalibre/"
sudo cp -R build/emalibre/Linux64_nogui/core build/Deb64/usr/share/emalibre/ sudo cp -R "$TMP_DIR/emalibre_nogui/package.nw/logs" "$DEB_DIR/usr/share/emalibre/"
sudo cp -R build/emalibre/Linux64_nogui/logs build/Deb64/usr/share/emalibre/ sudo cp -R "$TMP_DIR/emalibre_nogui/package.nw/conf" "$DEB_DIR/usr/share/emalibre/"
sudo cp -R build/emalibre/Linux64_nogui/conf build/Deb64/usr/share/emalibre/ sudo cp -R "$TMP_DIR/emalibre_nogui/package.nw/gui_web" "$DEB_DIR/usr/share/emalibre/"
sudo cp -R build/emalibre/Linux64_nogui/gui_web build/Deb64/usr/share/emalibre/ sudo cp -R "$TMP_DIR/emalibre_nogui/package.nw/gui_common" "$DEB_DIR/usr/share/emalibre/"
sudo cp -R build/emalibre/Linux64_nogui/gui_common build/Deb64/usr/share/emalibre/ sudo cp -R "$TMP_DIR/emalibre_nogui/package.nw/node_modules" "$DEB_DIR/usr/share/emalibre/"
sudo cp -R build/emalibre/Linux64_nogui/tmp build/Deb64/usr/share/emalibre/ sudo cp -R "$TMP_DIR/emalibre_nogui/package.nw/CHANGELOG" "$DEB_DIR/usr/share/emalibre/"
sudo cp -R build/emalibre/Linux64_nogui/node_modules build/Deb64/usr/share/emalibre/ sudo cp -R "$TMP_DIR/emalibre_nogui/package.nw/COPYING" "$DEB_DIR/usr/share/emalibre/"
sudo cp -R build/emalibre/Linux64_nogui/CHANGELOG build/Deb64/usr/share/emalibre/ sudo cp -R "$TMP_DIR/emalibre_nogui/package.nw/AUTHORS" "$DEB_DIR/usr/share/emalibre/"
sudo cp -R build/emalibre/Linux64_nogui/COPYING build/Deb64/usr/share/emalibre/ sudo cp -R "$TMP_DIR/emalibre_nogui/package.nw/package.json" "$DEB_DIR/usr/share/emalibre/"
sudo cp -R build/emalibre/Linux64_nogui/AUTHORS build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/Linux64_nogui/package.json build/Deb64/usr/share/emalibre/ log_ok " --> OK."
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m3) Remplazando el archivo de control DEB. \033[0m" log_info "3) Remplazando el archivo de control DEB."
sudo cp -f build/controlDeb/control_linux_web build/Deb64/DEBIAN/control & spinner "Procesando..." sudo cp -f "$CONTROL_DEB/control_linux_web" "$DEB_DIR/DEBIAN/control"
printf "\033[1;32m --> OK. \033[0m\n" log_ok " --> OK."
printf "\033[1;10m4) Aplicando permisos necesarios. \033[0m"
sudo echo "web" > build/Deb64/etc/emalibre_modo log_info "4) Aplicando permisos necesarios."
sudo chmod 0755 build/Deb64/DEBIAN sudo chmod 0755 "$DEB_DIR/DEBIAN" "$DEB_DIR/DEBIAN/postrm" "$DEB_DIR/DEBIAN/postinst" "$DEB_DIR/DEBIAN/preinst"
sudo chmod 0755 build/Deb64/DEBIAN/postrm sudo chown -R root:root "$DEB_DIR"
sudo chmod 0755 build/Deb64/DEBIAN/postinst log_ok " --> OK."
sudo chmod 0755 build/Deb64/DEBIAN/preinst
sudo chown -R root:root build/Deb64 cd "$BUILD_DIR"
printf "\033[1;32m --> OK. \033[0m\n" log_info "7) Generando Paquete DEB para Web 64bit Linux."
cd build #sudo dpkg -b Deb64 debs/"emalibre-web-linux_$VERSION.deb"
printf "\033[1;10m7) Generando Paquete Deb para Web 64bit Linux. \033[0m\n" sudo dpkg-deb -Zxz -b Deb64 debs/"emalibre-web-linux_$VERSION.deb"
sudo dpkg -b Deb64 debs/"emalibre-web-linux_$VERSION.deb"
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;10m8) Limpiando archivos temporales. \033[0m"
cd .. cd ..
sudo rm -f build/Deb64/DEBIAN/control log_final " Finalizó con éxito, build/debs/emalibre-web-linux_$VERSION.deb."
sudo rm -fr build/Deb64/usr/bin/* log_ok " --> OK."
sudo rm -fr build/Deb64/usr/share/emalibre/*
sudo rm -fr build/emalibre log_info "8) Limpiando archivos temporales."
printf "\033[1;32m --> OK. \033[0m\n" sudo rm -f "$DEB_DIR/DEBIAN/control"
sudo rm -rf "$DEB_DIR/usr/bin/"* "$DEB_DIR/usr/share/emalibre/"*
sudo rm -rf "$EMALIBRE_DIR"
log_ok " --> OK."
echo "" echo ""
exit 0

View File

@ -4,9 +4,11 @@
VERSION=`grep Version src/conf/ConfiguracionGlobal.js | sed -e "s/'Version': //g" | sed -e "s/,//g" | sed -e "s/^[ \t]*//"` VERSION=`grep Version src/conf/ConfiguracionGlobal.js | sed -e "s/'Version': //g" | sed -e "s/,//g" | sed -e "s/^[ \t]*//"`
NWJS_VERSION='0.28.4' # Es la ultima compilada para ARM, siempre mirar la url https://github.com/LeonardLaszlo/nw.js-armv7-binaries/releases NWJS_VERSION='0.28.4' # Es la ultima compilada para ARM, siempre mirar la url https://github.com/LeonardLaszlo/nw.js-armv7-binaries/releases
#NWJS_ARM='https://github.com/LeonardLaszlo/nw.js-armv7-binaries/releases/download/v' Se comenta se copio el tar al server de gugler por velocidad- #NWJS_ARM='https://github.com/LeonardLaszlo/nw.js-armv7-binaries/releases/download/v' Se comenta se copio el tar al server de gugler por velocidad-
NODE_CONSOLE='https://nodejs.org/dist/v14.4.0/node-v14.14.0-linux-armv7l.tar.xz' # Version node, siempre mirar la url NODE_CONSOLE='https://nodejs.org/dist/v14.4.0/node-v14.14.0-linux-armv7l.tar.xz' # Version node, siempre mirar la url
NODE_NOMBRE='node-v14.14.0-linux-armv7l' NODE_NOMBRE='node-v14.14.0-linux-armv7l'
DESCARGA_NWJS='https://nube.gugler.com.ar/index.php/s/iznYtBE7aBtXYdN/download' #server de gugler nwjs 28.4 #DESCARGA_NWJS='https://nube.gugler.com.ar/index.php/s/iznYtBE7aBtXYdN/download' #server de gugler nwjs 28.4
DESCARGA_NWJS='https://github.com/LeonardLaszlo/nw.js-armv7-binaries/releases/download/nw60_2022-01-07/nw60_2022-01-07.tar.gz'
# DEPENDENCIAS # DEPENDENCIAS
NW_GYP_INST=`npm list -g | grep nw-gyp@ | wc -l` NW_GYP_INST=`npm list -g | grep nw-gyp@ | wc -l`
@ -164,7 +166,7 @@ printf "\033[1;10m2) Copiando los fuentes de EMA Libre para 64bit. \033[0m"
sudo cp -R build/emalibre/arm/* build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/arm/* 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_arm_gui build/Deb64/DEBIAN/control & spinner "Procesando..." sudo cp -f build/controlDeb/control_arm_gui build/Deb64/DEBIAN/control
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m4) Aplicando permisos necesarios. \033[0m" printf "\033[1;10m4) Aplicando permisos necesarios. \033[0m"
sudo chmod +x build/Deb64/usr/share/emalibre/emalibre sudo chmod +x build/Deb64/usr/share/emalibre/emalibre
@ -204,55 +206,6 @@ 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"
# ***********************************************************
# Compilar EMA Libre Cliente (Carpincho) en modo CONSOLA
# ***********************************************************
echo ""
echo ""
echo "*************************************************"
echo "* Build EMA Libre Cliente Consola - ARM *"
echo "*************************************************"
echo ""
printf "\033[1;10m1) Limpiando archivos temporales. \033[0m"
sudo rm -f build/Deb64/DEBIAN/control
sudo rm -fr build/Deb64/usr/bin/*
sudo rm -fr build/Deb64/usr/share/emalibre/*
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m2) Copiando los fuentes de EMA Libre para ARM. \033[0m"
sudo cp -R build/emalibre/arm/core build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/arm/logs build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/arm/conf build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/arm/tmp build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/arm/node_modules build/Deb64/usr/share/emalibre/
sudo rm -fr build/Deb64/usr/share/emalibre/node_modules/node-hid
sudo cp -R build/emalibre/node-hid build/Deb64/usr/share/emalibre/node_modules
sudo cp -R build/emalibre/arm/CHANGELOG build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/arm/COPYING build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/arm/AUTHORS build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/arm/package.json build/Deb64/usr/share/emalibre/
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m3) Remplazando el archivo de control DEB. \033[0m"
sudo cp -f build/controlDeb/control_arm_console build/Deb64/DEBIAN/control & spinner "Procesando..."
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m4) Aplicando permisos necesarios. \033[0m"
sudo chmod 0755 build/Deb64/DEBIAN
sudo chmod 0755 build/Deb64/DEBIAN/postrm
sudo chmod 0755 build/Deb64/DEBIAN/postinst
sudo chmod 0755 build/Deb64/DEBIAN/preinst
sudo chown -R root:root build/Deb64
printf "\033[1;32m --> OK. \033[0m\n"
cd build
printf "\033[1;10m7) Generando Paquete Deb para Consola ARM. \033[0m\n"
sudo dpkg -b Deb64 debs/"emalibre-consola-arm_$VERSION.deb"
printf "\033[5;10m Finalizo con exito, build/debs/emalibre-console-arm_$VERSION.deb. \033[0m"
printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m8) Limpiando archivos temporales. \033[0m"
cd ..
sudo rm -f build/Deb64/DEBIAN/control
sudo rm -fr build/Deb64/usr/bin/*
sudo rm -fr build/Deb64/usr/share/emalibre/*
printf "\033[1;32m --> OK. \033[0m\n"
echo ""
# *********************************************************** # ***********************************************************
# Compilar EMA Libre Cliente (Carpincho) en modo CONSOLA/WEB # Compilar EMA Libre Cliente (Carpincho) en modo CONSOLA/WEB
@ -284,7 +237,7 @@ sudo cp -R build/emalibre/arm/AUTHORS build/Deb64/usr/share/emalibre/
sudo cp -R build/emalibre/arm/package.json build/Deb64/usr/share/emalibre/ sudo cp -R build/emalibre/arm/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_arm_web build/Deb64/DEBIAN/control & spinner "Procesando..." sudo cp -f build/controlDeb/control_arm_web build/Deb64/DEBIAN/control
printf "\033[1;32m --> OK. \033[0m\n" printf "\033[1;32m --> OK. \033[0m\n"
printf "\033[1;10m4) Aplicando permisos necesarios. \033[0m" printf "\033[1;10m4) Aplicando permisos necesarios. \033[0m"
sudo chmod 0755 build/Deb64/DEBIAN sudo chmod 0755 build/Deb64/DEBIAN

3586
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,24 @@
** Versión 1.36: (Enero 10 , 2026)
+ Se incorporó recolectar por WIFI/IP.
+ Mejoras menores de estilo(ej:iconos en logs).
+ Mejoras en el empaquetador.
+ 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 incorporó la opcion para ir al sitio oficial de la red, en el menu de redes.
+ Se actualizó la versión de :
RGraph 6.20 → 7.01
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
+ Se realizo un fix a la red WINDY(https://stations.windy.com/) para su publicación.
-Usuario/ID: es la API KEY del usuario.
-Password: Es numero de estaciones dada de alta en windy(ej: la primera->0, la segunda->1, la X->X).
** 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,32 @@
// Configuraciones generales de EMA RECOLECTOR
module.exports = {
"ConfGeneral": {
"Tiempo_de_Recoleccion": 40,
"UTC": -3,
"SistemaMetrico": "SI",
"debug": 3,
"debugTamanio": 10,
"NombreEstacion": "-",
"Modo": "Recolector",
"Llave_R": "e5303ab3-2a8b-4d42-90ab-1c8367d8521d",
"inicio_automatico": false,
"Audio": true,
"notificar_cambios": true,
"audioVoces": "Spanish_(Latin_America) espeak-ng",
"IP": "192.168.1.220",
"Puerto": "5000",
"Ruta": "/datos"
},
"ConfEmail": {
"ActivarCorreos": false,
"ReceptorEmail": "-",
"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,38 +138,55 @@ 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|🔴 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.Configuracion.RepeticionesConError = 0;
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;
recolector.conf.debug = configGeneralEMA.ConfGeneral.debug; recolector.conf.debug = configGeneralEMA.ConfGeneral.debug;
APP.Configuracion.Puerto = configGeneralEMA.ConfGeneral.Puerto;
APP.Configuracion.IP = configGeneralEMA.ConfGeneral.IP;
APP.Configuracion.Patch = configGeneralEMA.ConfGeneral.Ruta;
}, },
Iniciar: function () { Iniciar: function () {
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.');
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,12 +207,13 @@ 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);
} }
}); });
}, },
TiempoActualRecolector: function () { TiempoActualRecolector: function (ahora = false) {
if(ahora) {return [100,100]; }
// APP.RegistrarLog(APP.Configuracion.IdsSetTimeouts); // APP.RegistrarLog(APP.Configuracion.IdsSetTimeouts);
var fechaTiempo = APP.Configuracion.FechaLanzadoTimeout; var fechaTiempo = APP.Configuracion.FechaLanzadoTimeout;
var tiempoC = APP.Configuracion.TiempoContinuo; var tiempoC = APP.Configuracion.TiempoContinuo;
@ -199,11 +230,12 @@ 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 {
return false; return false;
} }
}, },
EstadoSensores: function () { EstadoSensores: function () {
if (typeof APP.Configuracion.EstadoSensores !== 'undefined' && APP.Configuracion.EstadoSensores !== '') { if (typeof APP.Configuracion.EstadoSensores !== 'undefined' && APP.Configuracion.EstadoSensores !== '') {
@ -230,57 +262,422 @@ 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 {
APP.RegistrarLog('0|CORE|Estableciendo Time Zone UTC ' + configGeneralEMA.ConfGeneral.UTC);
APP.RegistrarLog('0|CORE|Verificando Estado de la EMA...'); if(APP.Configuracion.Modo === 'Recolector_IP'){
APP.Configuracion.TiempoContinuo = configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion; APP.RegistrarLog('0|CORE|🔧 Estableciendo Time Zone UTC ' + configGeneralEMA.ConfGeneral.UTC);
APP.Configuracion.debug = configGeneralEMA.ConfGeneral.debug; APP.RegistrarLog('0|CORE|🔧 Verificando Estado de la EMA...');
recolector.conf.debug = configGeneralEMA.ConfGeneral.debug; APP.RegistrarLog('0|CORE|🟢 Iniciando el Modo Recolector por IP/WIFI.');
if (recolector.status() === true || APP.Configuracion.Run === 0) { APP.Configuracion.TiempoContinuo = configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion;
// Verifica la plataforma donde esta corriendo APP.Configuracion.debug = configGeneralEMA.ConfGeneral.debug;
if (APP.Configuracion.Run === 0) {
station = recolector.open(); // No puedo poner var station = -> no funciona ver. // se levanta el puerto para escuchar las peticiones al puerto indicado.
APP.RegistrarLog('0|CORE|Conectando..'); const PORT = APP.Configuracion.Puerto;
} // solo si es la primera vez, genera el recolector. const HOST = APP.Configuracion.IP;
if (station === null || station === false) { const RUTA = APP.Configuracion.Patch; // e.g., "/datos"
if (station === false) {
APP.Configuracion.Errores = 'Problemas con el USB, por favor desconecte y conecte el mismo'; const server = http.createServer((req, res) => {
APP.Configuracion.Run = 0; const base = `http://${HOST}:${PORT}`;
throw new Error('Problemas con el USB, por favor desconecte y conecte el mismo.'); let urlRaw = req.url;
} else { // Si la ruta empieza con "/xxxx" y no tiene "?" pero sí "&", agregamos "?"
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|Info de Estado: Fuera de Linea.'); if (urlRaw.startsWith(RUTA) && !urlRaw.includes('?') && urlRaw.includes('&')) {
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|Info de Detalle: EMA no conectada.'); urlRaw = urlRaw.replace(RUTA, RUTA + '?');
if (APP.Configuracion.debug > -1) 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.'; const myURL = new URL(urlRaw, base);
throw new Error('Problemas con la lectura USB'); const pathname = myURL.pathname.toLowerCase();
} const method = req.method.toUpperCase();
} else { const ip = req.socket.remoteAddress.replace('::ffff:', '');
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|ESTADO: Online'); APP.RegistrarLog('6|REGISTRO|📥 Recepcion IP: ' + ip + ' por ' + method + ' ruta ' + pathname);
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|PLATAFORMA: ' + recolector.conf.plataforma);
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|AUTOR:Gugler Lab'); //Para detener el servidor
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|VERSION:' + configGlobalEMA.ConfGlobal.Version); if (pathname === '/detener_servidor') {
if (APP.Configuracion.Run === 0) { res.writeHead(200, { 'Content-Type': 'text/plain' });
if (APP.Configuracion.debug > -1) APP.RegistrarLog('0|CORE|INICIAR: Se inicio el motor de EMA LIBRE.'); res.end('Servidor detenido');
APP.Configuracion.Errores = 'CORE: INICIAR-> Se inicio el motor de EMA LIBRE.'; APP.RegistrarLog('0|CORE| 🔴 Servidor detenido por botón');
server.close(() => {
});
return false;
}
//Para recibir la información de la estacion WIFI/IP
if (pathname === RUTA) {
// Comunes para ambos metodos
// 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;
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 (mm)',
'Punto de rocío (°C)',
'Fecha UTC',
'Batería Baja (0-No/1-Si)'
];
if (method === 'GET') {
let Vector = Object.fromEntries(myURL.searchParams.entries());
//APP.RegistrarLog(`5|VECTOR|${JSON.stringify(Vector)}`);
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).toFixed(2);
let rafagaEnKm = (parseFloat(Vector['windgustmph']) * 1.60934).toFixed(2);
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);
// calculo del punto de rocio
let punto_de_rocio = ((parseFloat(Vector['dewptf']) - 32) * 5 / 9).toFixed(2);
punto_de_rocio = (Math.round(punto_de_rocio * 100)) / 100;
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 lluviaTotalmm = (parseFloat(Vector['totalrainin']) * 25.4).toFixed(2);; // conversion a mm
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
parseFloat(vientoEnKm), // *8: Velocidad viento
parseFloat(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(lluviaTotalmm), // *14: Lluvia acumulada mm
punto_de_rocio, // *15: Punto de rocío
fechaUTC, // *16: UTC desde 'dateutc'
Vector['lowbatt'] // *17: Estado batería
];
// 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.
TiempoActualRecolector(true); // para reiniciar el tiempo y sincronizar.
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Datos GET recibidos');
//TERMINA EL METODO GET
} else if (method === 'POST' || method === 'PATCH') {
// COMIENZA EL MOTODO POST
let body = '';
req.on('data', chunk => { body += chunk.toString(); });
req.on('end', () => {
// APP.RegistrarLog('5|REGISTRO|Datos formulario:'+body);
const params = new URLSearchParams(body);
const data = Object.fromEntries(params.entries());
// Se convierten las unidades necesarias
let TemperaturaExternaC = ((parseFloat(data['tempf']) - 32) * 5 / 9).toFixed(2);
let TemperaturaInternaC = ((parseFloat(data['tempinf']) - 32) * 5 / 9).toFixed(2);
let luxerIntencidad = params.get("solarradiation") * 683; // luxerIntencidad en Luxer
let vientoEnKm = (params.get('windspeedmph') * 1.60934).toFixed(2);;
let rafagaEnKm = (params.get('windgustmph') * 1.60934).toFixed(2);;
let PresionR = (parseFloat(params.get('baromabsin')) * 33.8639).toFixed(2);
let PresionA = (parseFloat(params.get('baromrelin')) * 33.8639).toFixed(2);
// calculo del punto de rocio
var punto_de_rocio = (Math.pow((params.get("humidity") / 100), 0.125)) * (112 - (-(0.9 * TemperaturaExternaC))) - (-(0.1 * TemperaturaExternaC)) - 112;
punto_de_rocio = (Math.round(punto_de_rocio * 100)) / 100;
let x = params.get("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 lluviaTotalmm = (parseFloat(params.get('totalrainin')) * 25.4).toFixed(2); // conversion a mm
let DatosRecolectados = [
fecha, // *0: Fecha local
fechaISO, // *1: Fecha ISO
parseFloat(TemperaturaExternaC), // *2: Temperatura exterior
parseFloat(TemperaturaInternaC), // *3: Temperatura interior
parseFloat(params.get("humidity")), // *4: Humedad exterior
parseFloat(params.get("humidityin")), // *5: Humedad interior
luxerIntencidad, // *6: Luz Intencidad en Klux
parseFloat(params.get("uv")), // *7: Radiación UV
parseFloat(vientoEnKm), // *8: Velocidad viento
parseFloat(rafagaEnKm), // *9: Ráfaga
parseFloat(params.get("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(lluviaTotalmm), // *14: Lluvia acumulada
punto_de_rocio, // *15: Punto de rocío
fechaUTC, // *16: UTC desde 'dateutc'
params.get('wh65batt') // *17: Estado batería
];
// 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.
APP.TiempoActualRecolector(true); // para reiniciar el tiempo y sincronizar.
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Datos POST/PATCH recibidos');
});
} else {
APP.RegistrarLog('0|RECOLETOR_IP|⚠️ Dato Recibido pero metodo no encontrada: ' + method);
}
} else {
APP.RegistrarLog('0|RECOLETOR_IP|⚠️ Dato Recibido pero ruta no encontrada: ' + pathname);
}
});
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.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.';
} }
APP.Configuracion.TiempoMaximo = 0;
APP.Iniciar(); // Se llama a la funcion INICIO });
}
} else { }else{ // RECOLECTOR USB
if (recolector.status() === false && APP.Configuracion.Run === 0) {
throw new Error('Conexión usb no detectada, por favor verifique el cable.'); APP.RegistrarLog('0|CORE|Estableciendo Time Zone UTC ' + configGeneralEMA.ConfGeneral.UTC);
} APP.RegistrarLog('0|CORE|Verificando Estado de la EMA...');
if (recolector.status() === false && APP.Configuracion.Run === 1) { APP.Configuracion.TiempoContinuo = configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion;
APP.Configuracion.Run = 0; APP.Configuracion.debug = configGeneralEMA.ConfGeneral.debug;
throw new Error('Conexión usb no detectada, se desconectó en funcionamiento.'); recolector.conf.debug = configGeneralEMA.ConfGeneral.debug;
} if (recolector.status() === true || APP.Configuracion.Run === 0) {
// Verifica la plataforma donde esta corriendo
if (APP.Configuracion.Run === 0) {
station = recolector.open(); // No puedo poner var station = -> no funciona ver.
APP.RegistrarLog('0|CORE|Conectando..');
} // solo si es la primera vez, genera el recolector.
if (station === null || station === false) {
if (station === false) {
APP.Configuracion.Errores = 'Problemas con el USB, por favor desconecte y conecte el mismo';
APP.Configuracion.Run = 0;
throw new Error('Problemas con el USB, por favor desconecte y conecte el mismo.');
} else {
APP.RegistrarLog('0|CORE|Info de Estado: Fuera de Linea.');
APP.RegistrarLog('0|CORE|Info de Detalle: EMA no conectada.');
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.';
throw new Error('Problemas con la lectura USB');
}
} else {
APP.RegistrarLog('0|CORE|ESTADO: Online');
APP.RegistrarLog('0|CORE|PLATAFORMA: ' + recolector.conf.plataforma);
APP.RegistrarLog('0|CORE|AUTOR:Gugler Lab');
APP.RegistrarLog('0|CORE|VERSION:' + configGlobalEMA.ConfGlobal.Version);
if (APP.Configuracion.Run === 0) {
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.Run = 1;
}
APP.Configuracion.TiempoMaximo = 0;
APP.Iniciar(); // Se llama a la funcion INICIO
}
} else {
if (recolector.status() === false && APP.Configuracion.Run === 0) {
throw new Error('Conexión usb no detectada, por favor verifique el cable.');
}
if (recolector.status() === false && APP.Configuracion.Run === 1) {
APP.Configuracion.Run = 0;
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 +699,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 +711,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.');
try { try {
fs.readFile('./logs/TanquePendientes.log', { fs.readFile('./logs/TanquePendientes.log', {
encoding: 'utf8', encoding: 'utf8',
@ -322,13 +719,13 @@ APP = module.exports = {
}, function (err, data) { }, function (err, data) {
try { try {
if (err) { if (err) {
APP.RegistrarLog('1|ERROR: Intentando destanquear los registros prendientes:'); APP.RegistrarLog('1|ERROR|🛢️🔴 Intentando destanquear los registros.');
APP.Configuracion.BanderaPendientes = 0; APP.Configuracion.BanderaPendientes = 0;
} }
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 vacio.');
} else { } else {
Guardar = []; Guardar = [];
var EnviarPendientes = []; var EnviarPendientes = [];
@ -336,7 +733,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 +743,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],
@ -366,7 +763,7 @@ APP = module.exports = {
if (APP.Configuracion.CantidadPendientes < 0) { if (APP.Configuracion.CantidadPendientes < 0) {
APP.Configuracion.CantidadPendientes = 0; APP.Configuracion.CantidadPendientes = 0;
} }
APP.RegistrarLog('0|PENDIENTE_PUB|Fecha Registro:' + RegistroEnviado[1].fecha + ' - Red Publicada: ' + red + ' - Estado:' + estadored); APP.RegistrarLog('0|RED|🌐🛢️ Red Publicada Tanque:' + red + '- Fecha Registro:' + RegistroEnviado[1].fecha + ' - Estado:' + estadored);
} }
}); // CALLBACK ENVIAR RED }); // CALLBACK ENVIAR RED
} else { } else {
@ -378,7 +775,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 +783,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);
} }
}); });
} }
@ -421,7 +818,7 @@ 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);
} }
}); });
} else { } else {
@ -430,12 +827,12 @@ 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. 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,9 +870,9 @@ 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|🛢️ Se almaceno registro en el tanque de pendientes: ' + RegistroEnviado[0][7]);
RegistroEnviado[1].tanque = true; RegistroEnviado[1].tanque = true;
var PendienteTemp = { var PendienteTemp = {
idRed: RegistroEnviado[2], idRed: RegistroEnviado[2],
@ -524,7 +921,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 +951,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 +959,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 +972,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 +1032,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('8|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 +1133,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 +1166,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 +1283,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 +1320,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;
@ -933,7 +1328,7 @@ APP = module.exports = {
}); });
Datos = null; Datos = null;
} else { } else {
APP.RegistrarLog('0|CORE|Sincronizando.'); APP.RegistrarLog('0|CORE|⏳ Sincronizando.');
APP.Configuracion.Repeticiones = 0; APP.Configuracion.Repeticiones = 0;
APP.Configuracion.RepeticionesConError = 0; APP.Configuracion.RepeticionesConError = 0;
APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Continuo, 1000)); APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Continuo, 1000));
@ -945,15 +1340,15 @@ APP = module.exports = {
APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Continuo, 5000)); APP.Configuracion.IdsSetTimeouts.push(setTimeout(APP.Continuo, 5000));
} }
} else { } else {
APP.RegistrarLog('0|CORE|Recolector detenido.'); APP.RegistrarLog('0|CORE|⏹️ Recolector detenido.');
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;
} }
@ -965,9 +1360,9 @@ APP = module.exports = {
var parametros = process.argv; // Se lee el parametro var parametros = process.argv; // Se lee el parametro
if (parametros.indexOf('console') === -1) { if (parametros.indexOf('console') === -1) {
// No se realiza nada ya que se tiene que iniciar desde el aplicativo // No se realiza nada ya que se tiene que iniciar desde el aplicativo
APP.RegistrarLog('0|CORE|Se inició el aplicativo EmaLibre gráfico o Web.'); APP.RegistrarLog('0|CORE|⏳ Iniciando Ema Libre en Modo gráfico o Web.');
} else { } else {
APP.Conectar(); APP.Conectar();
APP.RegistrarLog('0|CORE|Iniciando Ema Libre en Modo Consola!!!.'); APP.RegistrarLog('0|CORE|⏳ Iniciando Ema Libre en Modo Consola!!!.');
} }

View File

@ -82,11 +82,11 @@ function RegistrarLog (reg, depurar) {
try { try {
RegistrarLog('0|CORE|Buscando Modulo USB para el S.O - ' + PlataformaFinal); RegistrarLog('0|CORE|🕵️. Buscando Modulo USB para el S.O - ' + PlataformaFinal);
var HID = require('node-hid'); var HID = require('node-hid');
RegistrarLog("0|CORE|Modulo node-hid cargado correctamente."); RegistrarLog("0|CORE|✅ Modulo node-hid cargado correctamente.");
} catch (e) { } catch (e) {
RegistrarLog('0|ERROR|No se pudo levantar el modulo node hid para su plataforma. ' + PlataformaFinal); RegistrarLog('0|ERROR|⚠️ No se pudo levantar el modulo node hid para su plataforma. ' + PlataformaFinal);
} }
// CODIGO DEL RECOLECTOR DE DATOS // CODIGO DEL RECOLECTOR DE DATOS

View File

@ -73,7 +73,7 @@ var FechaUltimoPublicadoWindy = "S/D";
if (!(this instanceof WINDY)) return new WINDY(ID, PASSWORD); if (!(this instanceof WINDY)) return new WINDY(ID, PASSWORD);
var payload = { var payload = {
station: PASSWORD || '' station: PASSWORD || 0
}; };
this.setObservations = function () { this.setObservations = function () {
@ -191,32 +191,48 @@ var FechaUltimoPublicadoWindy = "S/D";
}); });
server.path = server.fijo; server.path = server.fijo;
server.path += '?' + queryString.join('&'); server.path += '?' + queryString.join('&');
//APP.RegistrarLog('5|WINDY| GET:'+server.path);
var request = http.request(server, function (response) { var request = http.request(server, function (response) {
var message = ''; var message = '';
response.on('data', function (chunk) { response.on('data', function (chunk) {
message += chunk; message += chunk;
}); });
response.on('end', function () { response.on('end', function () {
var result = message.trim(); var result = message.trim(); // cuerpo de respuesta (texto)
if (result === 'SUCCESS') { var status = response.statusCode; // código HTTP real
// Registro publicado correctamente //APP.RegistrarLog(`5|WINDY| RESPUESTA [${status}]: ${result}`);
FechaUltimoPublicadoWindy = fecha; // ✅ Caso 200: todo OK
that.resetObservations(); if (status === 200) {
callback(null, result); FechaUltimoPublicadoWindy = fecha;
} else { that.resetObservations();
callback(null, result);
return;
}
// ⚠️ Caso 400: congestión (Windy busy)
if (status === 400) {
// Verificamos si la respuesta incluye "error" o algo similar
let detalle = "";
try {
const parsed = JSON.parse(result);
detalle = parsed.error || parsed.message || result;
} catch (e) {
detalle = result;
}
// APP.RegistrarLog(`5|WINDY| CONGESTION: ${detalle}`);
that.resetObservations();
callback(null, [429, FechaUltimoPublicadoWindy]);
return;
}
// ❌ Otros errores
var detalle_error = result.substring(0, 200);
//APP.RegistrarLog(`5|WINDY| ERROR (${status}): ${detalle_error}`);
callback(new Error(detalle_error), null);
});
if (result.substr(result, 8) == 'SUCCESS ' )
{ // Esta Congestionada
that.resetObservations();
callback(null, [429, FechaUltimoPublicadoWindy]);
} else {
// Otro error.
var detalle_error = result.substr(result, 100);
callback(new Error(detalle_error), null);
}
}
});
}); });
request.on('socket', function (socket) { request.on('socket', function (socket) {

View File

@ -257,7 +257,7 @@ function MostrarUltimoRegistro(modo)
}); });
}); });
//Ultimo Registro REDES ENVIADAS //Ultimo Registro REDES ENVIADAS
http.get('http://127.0.0.1:8080/UltimoRegistro', (res) => { http.get('http://127.0.0.1:8080/UltimoPublicado', (res) => {
const { statusCode } = res; const { statusCode } = res;
term.moveTo( 1 , 19 , '' ) ; term.moveTo( 1 , 19 , '' ) ;
term.wrapColumn( { x: 2 , width: 80, height: 50, offset: 0, continue:true } ); term.wrapColumn( { x: 2 , width: 80, height: 50, offset: 0, continue:true } );

View File

@ -1,740 +0,0 @@
/**
* Archivo principal de la administracion grafica de la aplicacion EMA Libre.
*
* Archivo de inicio el entorno grafico GUI del sistema EMA Libre que nos
* brinda una pantalla con las opciones: Configuracion general del sistema,
* ABM de Redes Meteorologicas,Visualizacion del sensores e informacion enviadas a la redes y
* reportes de log, como historicos registrados.
*
* LICENSE: This file is part of EMA Libre.
* EMA Libre is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EMA Libre is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EMA Libre. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright Copyright (c) 2019 GUGLER (http://www.gugler.com.ar)
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL License
* @version 3.0
* @link http://www.gugler.com.ar
* @since File available since Release 3.0
*/
// **********************Dependencias **************************
const configGeneralEMA = require('./../conf/ConfiguracionGeneral.js'); // Configuracion General
const configGlobalEMA = require('./../conf/ConfiguracionGlobal.js'); // Configuracion Global
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 gui = require('nw.gui'); // Libreria Grafica
// **********************Vairales Generales*********************
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 iconoPublicado = './gui_common/iconos/icono_pub.png'; // Imagen del Icono Prublicado --> no utilizada
const iconoNeutro = '../gui_common/img/neutro.webp'; // Imagen del Icono Neutro
const iconoControlTrue = '../gui_common/img/ok.webp'; // Imagen de Control TRUE
const iconoControlFalse = '../gui_common/img/no.webp'; // Imagen de Control FALSE
//var tray = null;
var UltimoReg;
var Ant_UltimoReg;
var ModeloVisor; // Variables Generales - Registros recolectados
var destanqueo = 0;
var intervaloBarra = 0;
var cant = 0;
var tiempovisor=99;
// **********************Iconizado / Menu Superior *********************************************************
gui.App.clearCache(); // Se limpia cache
win = gui.Window.get(); // Se obtiene la ventana actual
menuItems = new gui.Menu();
menuItems.append(new gui.MenuItem({ label: 'Iniciar', click: function () { INICIAR(); } }));
menuItems.append(new gui.MenuItem({ label: 'Detener', click: function () { DETENER(); } }));
menu = new gui.Menu({ type: 'menubar' });
menu.append(new gui.MenuItem({ label: 'EMA CONTROL', submenu: menuItems }));
menu.append(new gui.MenuItem({ label: 'Mostrar', click: function () { win.setShowInTaskbar(true); } }));
menu.append(new gui.MenuItem({ label: 'Ocultar', click: function () { win.setShowInTaskbar(false); } }));
menu.append(new gui.MenuItem({ label: 'Salir', click: function () { EMA.Salir(); gui.App.closeAllWindows();win.close(true); } }));
// se crea el tray icon
tray = new gui.Tray ({title : ' EmaLibre Carpincho ' , icon : iconoApagado });
tray.tooltip = 'Ema Libre Carpincho';
tray.menu = menu;
tray.on('click', function () { win.show(true); MuestraRegistroActual(false); Graficos(); ClimaActual(); });
//new gui.Shortcut({ key: 'F11', active: function () { win.toggleFullscreen(); } })
// **********************Funciones Principales de la GUI *****************************************************
const esperar = ms => new Promise(function(resolve){setTimeout(resolve, ms);});
// Captura el redimencionamiento de la ventana
win.on('resize', (width, height) => {
if (width < 775 && height < 555) { win.zoomLevel = -2.4; }
if (width > 775 && height > 555) { win.zoomLevel = -1.8; }
if (width > 800 && height > 600) { win.zoomLevel = -1.5; }
if (width > 850 && height > 690) { win.zoomLevel = -0.6; }
if (width > 1000 && height > 800) { win.zoomLevel = 0; }
if (width > 1200 && height > 820) { win.zoomLevel = 0.3; }
if (width > 1200 && height > 900) { win.zoomLevel = 0.9; }
if (width > 1400 && height > 1000) { win.zoomLevel = 1.2; }
});
function INICIAR () {
if (configGeneralEMA.ConfGeneral.Modo === 'Visor') { // se comprueba el modo
HABLA(0, 'Se inicio en modo Visor', 'success');
$('#signal').addClass('parpadea');
} else {
EMA.Conectar();
HABLA(0, 'Se inicio en modo Recolector', 'success');
$('#signal').addClass('parpadea');
}
tray.icon = iconoEncendido;
$('td#barralateral').css('background-color', '#11881161');
$('#estado').html('En Linea');
$('#mensaje').html('Encendido');
$('#botoniniciar').attr('disabled', true);
$('#botondetener').attr('disabled', false);
RegistroActual();
clearInterval(intervaloBarra);
intervaloBarra = window.setInterval(function () { BarradeProgreso();}, 200);
//console.log('Nuevo IntervaloId: '+ intervaloBarra);
}
async function iniciarAutomaticamente () {
EstadoMenuInicio();
if (configGeneralEMA.ConfGeneral.inicio_automatico) {
await esperar(4000);
HABLA(0, 'Iniciando Automaticamente..', 'info');
if ($('#mensaje').html() === 'Encienda EMA Libre') {
await esperar(5000);
INICIAR();
} else {
HABLA(0, 'No se pudo iniciar automaticamente, verifique el error', 'info');
}
}
}
function DETENER () {
clearInterval(intervaloBarra);
tray.icon = iconoApagado;
$('td#barralateral').css('background-color', '#ff000030');
$('#estado').html('Fuera de Linea');
$('#img_estado').attr('src', iconoNeutro);
$('#mensaje').html('EMA Libre se encuentra detenida');
$('#mensajedetalle').html('Se detuvo manualmente.');
$('#img_detalle').attr('src', iconoNeutro);
$('#img_mensaje').attr('src', iconoNeutro);
$('#botoniniciar').attr('disabled', false);
$('#botondetener').attr('disabled', true);
if (configGeneralEMA.ConfGeneral.Modo === 'Visor') { // se comprueba el modo
HABLA(0, 'Modo visor detenido', 'error');
$('#signal').removeClass('parpadea');
} else {
EMA.Detener();
HABLA(0, 'Modo Recolector detenido', 'error');
$('#signal').removeClass('parpadea');
}
}
async function redimensionarInicio ()
{
$('#loadinicio').attr('src', '../gui_common/iconos/icono_app_guina.webp');
await esperar(500);
$('#loadinicio').attr('src', '../gui_common/iconos/icono_app.webp');
await esperar(600);
$('#cargador').empty();
$('#cargador').remove();
$('#principal').show();
win.setMinimumSize(700, 500);
win.setMaximumSize(4000, 2000);
win.maximize();
HABLA(0, '...', 'info');
await esperar(1000);
HABLA(0, 'Bienvenido a Ema Libre Cliente, me llaman Carpincho.', 'info');
iniciarAutomaticamente();
}
async function Actualizar () {
var plataforma = process.platform;
var SO_WIN = plataforma.indexOf('win');
if (SO_WIN === 0) {
funcionesActualizar.Control(function (resultado, VersionActual, nueva) {
$('#botonactualizar').attr('disabled', true);
if (resultado && VersionActual) {
DETENER();
HABLA(0, 'Descargando nueva versión de Carpincho: ' + nueva, 'info');
NProgress.set(0);
$('#mensajebarra').html('Descargando nueva versión, espere ....');
funcionesActualizar.Descargar(nueva, function (resultadoact, avance, porcentaje) {
NProgress.set(porcentaje/100);
$('#mensajebarra').html(avance);
if (resultadoact && avance) {
NProgress.set(1);
$('#mensajebarra').html('Descomprimiendo la nueva versión, espere ....');
HABLA(0, 'Descomprimiendo la nueva versión, espere ....', 'info');
funcionesActualizar.Descomprimir(function (resultadoact) {
if (resultadoact) {
$('#mensajebarra').html('Borrado del archivo descargado, espere ....');
funcionesActualizar.Desplegar(function (resultado) {
if (resultado) {
HABLA(0, 'Ejecutando App de Actualizacion, espere...', 'info');
setTimeout(funcionesActualizar.LanzarAplicativoIndependiente, 9000);
} else {
HABLA(0, 'Ocurrio un problema en el despliege, intente mas tarde', 'error');
}
});
} else {
HABLA(0, 'Ocurrio un problema descomprimiendo, intente mas tarde', 'error');
}
});
}
if (!resultadoact && !avance) {
HABLA(0, 'Ocurrio un problema en la descarga, intente mas tarde', 'error');
}
});
}
if (!resultado && VersionActual) {
HABLA(0, 'No hay versiones nuevas disponibles', 'success');
}
if (!resultado && !VersionActual) {
HABLA(0, 'No se pudo conectar al servidor de versiones,pruebe mas tarde...', 'error');
}
});
} else {
HABLA(0, 'Esta opción solo es válida para sistemas operativos Windows.', 'warn');
await esperar(4000);
HABLA(0, 'Pero usted puede actualizar EMA Libre con su sistema de paquetes nativo.', 'info');
await esperar(4000);
HABLA(0, 'O puede ingresar a https://ema.gugler.com.ar para más información. ', 'info');
}
$('#botonactualizar').attr('disabled', false);
}
async function HABLA (num, mesg, tipo) {
var tamañomsg = mesg.length;
if (num === 0) {
$('#carpincho_img').notify(mesg, {
className: tipo,
position: 'right middle',
autoHideDelay: (tamañomsg * 90)
});
if (configGeneralEMA.ConfGeneral.Audio) {
window.speechSynthesis.cancel();
var voices = window.speechSynthesis.getVoices();
var cantidadVoces = voices.length;
//console.log(cantidadVoces);
if( cantidadVoces > 0){
var seleccionada = voices.filter(function (voice) { return voice.name === configGeneralEMA.ConfGeneral.audioVoces; })[0];
//console.log(seleccionada);
var msg = new SpeechSynthesisUtterance (mesg);
msg.voice = seleccionada;
msg.rate = 1.2;
msg.pitch = 1;
window.speechSynthesis.speak(msg);
msg=null;seleccionada=null;voices=null;cantidadVoces=null;
}
}
}
if ($('#carpincho_img').attr('src') === '../gui_common/iconos/icono_app.webp') {
$('#carpincho_img').attr('src', '../gui_common/iconos/icono_app_habla.webp');
} else {
$('#carpincho_img').attr('src', '../gui_common/iconos/icono_app.webp');
}
num++;
if (num < tamañomsg) {
await esperar(90);
HABLA(num ,mesg ,0);
} else {
$('#carpincho_img').attr('src', '../gui_common/iconos/icono_app.webp');
//LimpiarMemoria(true);
}
num=null;tamañomsg = null;
}
async function GUIÑA (num)
{
if ($('#carpincho_img').attr('src') === '../gui_common/iconos/icono_app.webp') {
$('#carpincho_img').attr('src', '../gui_common/iconos/icono_app_guina.webp');
} else {
$('#carpincho_img').attr('src', '../gui_common/iconos/icono_app.webp');
}
num++;
if (num < 2) {
await esperar(400);
GUIÑA(num);
} else {
$('#carpincho_img').attr('src', '../gui_common/iconos/icono_app.webp');
}
num =null;
}
async function controlPendientes () {
var pendientes = EMA.HayPendientes();
var DIVPENDIENTE = document.getElementById('DIVPendientes');
var SPANTANQUE = document.getElementById('Destanqueo');
var DIVModo = document.getElementById('DIVModo');
if (pendientes !== false)
{
DIVPENDIENTE.style.visibility = 'visible';
if ((pendientes < destanqueo)) {SPANTANQUE.style.visibility = 'visible'; } else {SPANTANQUE.style.visibility = 'hidden'; }
destanqueo = pendientes;
$('#Pendientes').html("<span class='label label-warning' title='Pendientes'> Cantidad: " + pendientes + '</span><br>');
} else {
destanqueo = 0;
DIVPENDIENTE.style.visibility = 'hidden';
SPANTANQUE.style.visibility = 'hidden';
DIVModo.style.visibility = 'hidden';
}
pendientes = null;
DIVPENDIENTE = null;
SPANTANQUE = null;
DIVModo = null;
return true;
}
async function mostrarEstados (EstadoSensores) {
// Se consulta por los sensores
var Resultado = !((EstadoSensores.lost_sensor_contact) || (EstadoSensores.rain_overflow));
if (Resultado && (configGeneralEMA.ConfGeneral.Modo !== 'Visor')) {
$('#signal').attr('src', '../gui_common/img/signal.webp');
$('#signal').addClass('parpadea');
} else {
if (!EstadoSensores.lost_sensor_contact) {
HABLA(0, 'Perdida de la señal de Radio Frecuencia', 'warn');
}
if (!EstadoSensores.rain_overflow) {
HABLA(0, 'Sensor de lluvia externo sobrecargado', 'warn');
}
$('#signal').attr('src', '../gui_common/img/no_signal.webp');
$('#signal').addClass('parpadea');
win.requestAttention(3);
}
EstadoSensores = null;
Resultado = null;
}
async function RegistroActual (barratermino)
{
//console.log('ENTRO REGISTRO ACTUAL');
if (configGeneralEMA.ConfGeneral.Modo === 'Recolector')
{ // se comprueba el modo se encuentra en Recolector
if(barratermino == true){
//BARRA TERMINO
//console.log('ENTRO AL BARRA TERMINO RECOLECTOR');
await esperar(100);
EstadoMenuInicio();
await esperar(100);
if (win.x > -10000) MuestraRegistroActual(true);
await esperar(100);
if (win.x > -10000) Graficos();
await esperar(100);
if (win.x > -10000) ClimaActual();
await esperar(1500);
if (win.x > -10000) RegistroPublicado();
cant=0;
}
var EstadoEMA = EMA.Estado();
if (EstadoEMA[0] === true)
{
$('#mensaje').html('Recolectando.');
$('#img_mensaje').attr('src', iconoControlTrue);
$('#mensajedetalle').html('Operando.');
$('#img_detalle').attr('src', iconoControlTrue);
controlPendientes();
UltimoReg = EMA.UltimoRegistro();
var EstadoSensores = EMA.EstadoSensores();
if(EstadoSensores !== false)
{
mostrarEstados(EstadoSensores);
}else{EstadoSensores=null;}
if (UltimoReg == false) {
// Se consulta por la cantidad de errores
if (EMA.RepeticionesConError() > 2) {
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');
await esperar(15000);
DETENER();
await esperar(5000);
INICIAR();
return false;
} else {
$('#mensaje').html('(' + EMA.RepeticionesConError() + ') Sincronizando ...');
$('#img_mensaje').attr('src', iconoNeutro);
await esperar(200);
RegistroActual();
return false;
}
}
} else {
$('#mensaje').html('EmaLibre detenida.');
$('#img_mensaje').attr('src', iconoControlFalse);
$('#mensajedetalle').html(EstadoEMA[1]);
$('#img_detalle').attr('src', iconoControlFalse);
await esperar(5000);
RegistroActual();
return false;
}
} else { // Modo visor
if(barratermino == true){
//BARRA TERMINO
await esperar(100);
EstadoMenuInicio();
await esperar(100);
if (win.x > -10000) MuestraRegistroActual(true);
await esperar(100);
if (win.x > -10000) Graficos();
await esperar(100);
if (win.x > -10000) ClimaActual();
cant=0;
}
$('#signal').attr('src', '../gui_common/img/visor.webp');
var cantreg = 1;
EMA.Visor(cantreg, function (error, datos) {
if (error != null) {
HABLA(0, 'No se pueden obtener datos del servidor. ' + error, 'info');
$('#signal').removeClass('parpadea');
setTimeout(function(){RegistroActual();}, 10000);
} else {
$('#signal').addClass('parpadea');
var DIVModo = document.getElementById('DIVModo');
DIVModo.style.visibility = 'visible';
document.getElementById('DIVModo').innerHTML = "<span class='badge badge-primary' title='Modo Visor'> Modo Visor </span><br><span class='badge badge-primary' >" + datos.pais + ', ' + datos.ciudad + "</span><br><span class='badge badge-primary' >" + datos.modelo + '</span>';
UltimoReg = datos.registros[0];
ModeloVisor = datos.nombre;
// se convierte la fecha
var db = new Date(datos.registros[0].fecha);
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;
UltimoReg.fecha = fecha;
fecha=null;dia=null;mes=null;segundo=null;minutos=null;hora=null;db=null;
// ver acumulados de lluvia
UltimoReg.lloviendo = datos.registros[0].lluvia_actual;
UltimoReg.lluvia_acu_hora = datos.registros[0].lluvia_acumulado_hora;
UltimoReg.lluvia_acu_diaria = datos.registros[0].lluvia_acumulado_diario;
UltimoReg.lluvia_acumulado_total = datos.registros[0].lluvia_acumulado_total;
// Maximas y minimas, no llegan de EMACENTER, por el momento se setean en 0.
UltimoReg.temperatura_externa_max_dia = 0;
UltimoReg.temperatura_externa_min_dia = 0;
UltimoReg.temperatura_interna_max_dia = 0;
UltimoReg.temperatura_interna_min_dia = 0;
UltimoReg.punto_de_rocio_max_dia = 0;
UltimoReg.punto_de_rocio_min_dia = 0;
UltimoReg.humedad_externa_max_dia = 0;
UltimoReg.humedad_externa_min_dia = 0;
UltimoReg.humedad_interna_max_dia = 0;
UltimoReg.humedad_interna_min_dia = 0;
UltimoReg.luxer_intencidad_max_dia = 0;
UltimoReg.luxer_intencidad_min_dia = 0;
UltimoReg.luxer_uv_max_dia = 0;
UltimoReg.luxer_uv_min_dia = 0;
UltimoReg.presion_relativa_max_dia = 0;
UltimoReg.presion_relativa_min_dia = 0;
tiempovisor = tiempovisor - 0.2;
}
});
}
EstadoEMA = null;
}
async function BarradeProgreso () {
// const startTime = performance.now();
// Se consulta el tiempo actual del recolector
if (configGeneralEMA.ConfGeneral.Modo === 'Recolector')
{ // EN MODO RECOLECTOR
var tiempoActualRecolector;
tiempoActualRecolector = EMA.TiempoActualRecolector();
if(tiempoActualRecolector[0] !== false || tiempoActualRecolector[1] > 0)
{
if ((tiempoActualRecolector[0] < 98 && tiempoActualRecolector[1] > 0.39) )
{
// CONTINUA ADENTRO
if (win.x > -10000)
{ // Solo si no esta minimizado
NProgress.set(tiempoActualRecolector[0]/100);
return false;
}
} else {
// Cuando termine cada barra, publica y luego vuelve al leer el registro actual
cant++;
if(cant == 1){ RegistroActual(true);} else{return true;};
// 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 (win.x > -10000)
{ // Solo si no esta minimizado
NProgress.done();
}
}
}else{ if(cant > 0){return false;}
if (win.x > -10000)
{ // Solo si no esta minimizado
NProgress.done();
}
}
} else { // MODO VISOR
if( tiempovisor != 99)
{
if( tiempovisor >= configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion)
{
tiempovisor = 0;
RegistroActual(true);
if (win.x > -10000) NProgress.done();
}else{
tiempovisor = tiempovisor + 0.2; // se le suma el tiempo del intervalo
var tiempo_barra = ((tiempovisor * 100) / configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion)/100;
if (win.x > -10000) NProgress.set(tiempo_barra);
}
}
}
UltimoPub = null;aux=null;tiempoActualRecolector = null; tiempo_barra = null;
/* const duration = performance.now() - startTime;
console.log(` Tiempo barra: ${duration}ms`);*/
}
// ********************** Menu Acciones *******************************************************************
function MenuConfig () {
if ($('#Modo').val() === 'Recolector') {
$('#LlaveR').attr('disabled', true);
$('#LlaveR').val('');
$('#LlaveR').hide();
} else {
$('#LlaveR').attr('disabled', false);
$('#LlaveR').show();
$('#Llave_R').val(configGeneralEMA.ConfGeneral.Llave_R);
}
if ($('#Tipo_SMTP').val() === 'Deshabilitado') {
$('#Usuario_SMTP').attr('disabled', true);
$('#Contrasenia_SMTP').attr('disabled', true);
$('#Puerto_SMTP').attr('disabled', true);
$('#Server_SMTP').attr('disabled', true);
$('#Puerto_SMTP').val('');
$('#puerto').hide();
$('#Server_SMTP').val('');
$('#Server').hide();
} else {
$('#Usuario_SMTP').attr('disabled', false);
$('#Contrasenia_SMTP').attr('disabled', false);
if ($('#Tipo_SMTP').val() === 'Manual') {
$('#Puerto_SMTP').attr('disabled', false);
$('#puerto').show();
$('#Server_SMTP').attr('disabled', false);
$('#Server').show();
} else {
$('#Puerto_SMTP').attr('disabled', true);
$('#puerto').hide();
$('#Server_SMTP').attr('disabled', true);
$('#Server').hide();
}
$('#Usuario_SMTP').val(configGeneralEMA.ConfEmail.Usuario);
$('#Contrasenia_SMTP').val(configGeneralEMA.ConfEmail.Password);
$('#Server_SMTP').val(configGeneralEMA.ConfEmail.Server);
$('#Puerto_SMTP').val(configGeneralEMA.ConfEmail.Puerto);
}
if ($('#audio').val() === 'Desactivado') {
$('#vocesAudioDiv').attr('disabled', true);
$('#vocesAudioDiv').val('');
$('#vocesAudioDiv').hide();
} else {
$('#vocesAudioDiv').attr('disabled', false);
$('#vocesAudioDiv').show();
$('#vocesAudio').val(configGeneralEMA.ConfGeneral.audioVoces);
$('#vocesAudio').selectpicker('render');
}
}
async function MenuGUI (elemento) {
try {
document.getElementById("actualizando_inicio").hidden = false;
document.getElementById("actualizando_inicio").style.display = "block";
var seleccion;
if (elemento === 'logs') {seleccion = document.getElementById('configuracion');}
else {seleccion = document.getElementById(elemento);}
$(seleccion).empty();
$(seleccion).hide();
$(seleccion).load('./view/modelo_' + elemento + '.html', function (datosArchivo) {
switch (elemento) {
case 'logs':
VerRegistrosLog();
$('#interior').empty();$('#exterior').empty();$('#inicio').empty();$('#contacto').empty();$('#inicio').empty();$('#estadisticas').empty();
break;
case 'redes':
ListarRedes();
$('#interior').empty();$('#exterior').empty();$('#contacto').empty();$('#configuracion').empty();$('#inicio').empty();$('#estadisticas').empty();
break;
case 'redes_alta':
MenuSelectRed();
break;
case 'inicio':
$('#node_pid').html(process.pid);
$('#node_ppid').html(process.ppid);
$('#versiones').attr('title', versiones);
$('#nwjs_v').html(version_nwjs);
EstadoMenuInicio();
$('#interior').empty();$('#exterior').empty();$('#contacto').empty();$('#configuracion').empty();$('#redes').empty();$('#estadisticas').empty();
break;
case 'interior':
MuestraRegistroActual(false,'interior');
Graficos('interior');
$('#inicio').empty();$('#exterior').empty();$('#contacto').empty();$('#configuracion').empty();$('#redes').empty();$('#estadisticas').empty();
break;
case 'exterior':
MuestraRegistroActual(false,'exterior');
Graficos('exterior');
$('#interior').empty();$('#inicio').empty();$('#contacto').empty();$('#configuracion').empty();$('#redes').empty();$('#estadisticas').empty();
break;
case 'estadisticas':
graficoEstadisticas();
$('#interior').empty();$('#exterior').empty();$('#inicio').empty();$('#contacto').empty();$('#configuracion').empty();$('#redes').empty();
break;
case 'contacto':
var NombreVersion = ' v' + configGlobalEMA.ConfGlobal.Version;
$('#versioncontacto').html(NombreVersion);
$('#interior').empty();$('#exterior').empty();$('#inicio').empty();$('#configuracion').empty();$('#redes').empty();$('#estadisticas').empty();
break;
case 'configuracion':
$('#interior').empty();$('#exterior').empty();$('#contacto').empty();$('#inicio').empty();$('#redes').empty();$('#estadisticas').empty();
// Se obtienen las voces del sistema
var synth = window.speechSynthesis;
const voice = synth.getVoices();
var voiceSelect = document.getElementById('vocesAudio');
var cantidadVoces = voice.length;
if( cantidadVoces > 0){
for (var i = 0; i < cantidadVoces; i++)
{
var option = document.createElement('option');
option.textContent = voice[i].name;
option.setAttribute('value', voice[i].name);
voiceSelect.appendChild(option);
}
}else{
var option = document.createElement('option');
voice[0] = 'Sin Voces';
option.textContent = 'Sin voces, verifique el SO';
option.setAttribute('value', 'Sin Voces');
voiceSelect.appendChild(option);
voiceSelect.selectedIndex = "0";
}
$('#NombreEstacion').val(configGeneralEMA.ConfGeneral.NombreEstacion);
$('#Modo').val(configGeneralEMA.ConfGeneral.Modo);
$('#Modo').selectpicker('render');
$('#SistemaMetrico').val(configGeneralEMA.ConfGeneral.SistemaMetrico);
$('#SistemaMetrico').selectpicker('render');
$('#Llave_R').val(configGeneralEMA.ConfGeneral.Llave_R);
$('#Tiempo_de_Recoleccion').val(configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion);
$('#Email_receptor').val(configGeneralEMA.ConfEmail.ReceptorEmail);
$('#Tipo_SMTP').val(configGeneralEMA.ConfEmail.Servicio);
$('#Tipo_SMTP').selectpicker('render');
$('#Tiempo_de_Recoleccion').selectpicker('render');
$('#Debug').val(configGeneralEMA.ConfGeneral.debug);
$('#debugMB').val(configGeneralEMA.ConfGeneral.debugTamanio);
$('#Debug').selectpicker('render');
var automatico;
if (configGeneralEMA.ConfGeneral.inicio_automatico) { automatico = 'Activado'; } else { automatico = 'Desactivado'; }
$('#inicio_auto').val(automatico);
$('#inicio_auto').selectpicker('render');
var cambios;
if (configGeneralEMA.ConfGeneral.notificar_cambios) { cambios = 'Activado'; } else { cambios = 'Desactivado'; }
$('#notificar_cambios').val(cambios);
$('#notificar_cambios').selectpicker('render');
var Audio;
if (configGeneralEMA.ConfGeneral.Audio) { Audio = 'Activado'; } else { Audio = 'Desactivado'; }
$('#audio').val(Audio);
$('#audio').selectpicker('render');
$('#utc').val(configGeneralEMA.ConfGeneral.UTC);
$('#utc').selectpicker('render');
// Control para el audio
if (configGeneralEMA.ConfGeneral.Audio === false) {
$('#vocesAudioDiv').attr('disabled', true);
$('#vocesAudioDiv').val('');
$('#vocesAudioDiv').hide();
} else {
$('#vocesAudioDiv').attr('disabled', false);
$('#vocesAudioDiv').show();
if (configGeneralEMA.ConfGeneral.audioVoces === null || typeof configGeneralEMA.ConfGeneral.audioVoces === 'undefined') { $('#vocesAudio').val(voice[0].name); } else { $('#vocesAudio').val(configGeneralEMA.ConfGeneral.audioVoces); }
}
$('#vocesAudio').selectpicker('render');
// Control para el modo
if ($('#Modo').val() === 'Recolector') {
$('#LlaveR').attr('disabled', true);
$('#LlaveR').val('');
$('#LlaveR').hide();
} else {
$('#LlaveR').attr('disabled', false);
$('#LlaveR').show();
$('#Llave_R').val(configGeneralEMA.ConfGeneral.Llave_R);
}
// Control para el SMTP
if ($('#Tipo_SMTP').val() === 'Deshabilitado') {
$('#Usuario_SMTP').attr('disabled', true);
$('#Contrasenia_SMTP').attr('disabled', true);
$('#Puerto_SMTP').attr('disabled', true);
$('#Server_SMTP').attr('disabled', true);
$('#Server').hide();
$('#puerto').hide();
} else {
$('#Usuario_SMTP').attr('disabled', false);
$('#Contrasenia_SMTP').attr('disabled', false);
$('#Server_SMTP').attr('disabled', false);
$('#Puerto_SMTP').attr('disabled', false);
$('#Usuario_SMTP').val(configGeneralEMA.ConfEmail.Usuario);
$('#Contrasenia_SMTP').val(configGeneralEMA.ConfEmail.Password);
$('#Server_SMTP').val(configGeneralEMA.ConfEmail.Server);
$('#Puerto_SMTP').val(configGeneralEMA.ConfEmail.Puerto);
if ($('#Tipo_SMTP').val() === 'Manual') {
$('#Server_SMTP').attr('disabled', false);
$('#Puerto_SMTP').attr('disabled', false);
$('#puerto').show();
$('#Server').show();
} else {
$('#puerto').hide();
$('#Server').hide();
}
}
break;
default:
console.log('No existe el menu seleccionado: ' + elemento);
}
setTimeout(function(){ document.getElementById("actualizando_inicio").style.display = "none";
document.getElementById("actualizando_inicio").hidden = false;
$(seleccion).show();
}, 200);
});
} catch (e) { // Si falla se informa y se vuelve a cargar el modelo interior
HABLA(0, 'Se realizó un reload de la libreria grafica interior', 'info');
}
}
async function autoLoad ()
{
await esperar(6000);
var plataforma = process.platform;
var SO_WIN = plataforma.indexOf('win');
if (SO_WIN === 0) { funcionesActualizar.Control(function (resultado, VersionActual, nueva) { if (resultado) { HABLA(0, 'Hay una nueva version de Carpincho. Versión ' + nueva, 'error'); } }); }
}
autoLoad();

View File

@ -106,46 +106,68 @@ async function EstadoMenuInicio()
$('#inombre').html(configGeneralEMA.ConfGeneral.NombreEstacion); $('#inombre').html(configGeneralEMA.ConfGeneral.NombreEstacion);
$('#botoniniciar').attr("disabled",true); $('#botoniniciar').attr("disabled",true);
$('#botondetener').attr("disabled",true) $('#botondetener').attr("disabled",true)
if(configGeneralEMA.ConfGeneral.NombreEstacion != ''){$("#img_nombre").attr("src",icono_control_true);}else{$("#img_nombre").attr("src",icono_control_neutro);}
$('#iso').html(plataforma + " (" + arquitectura + ")"); $('#iso').html(plataforma + " (" + arquitectura + ")");
if(plataforma != ''){$("#img_so").attr("src",icono_control_true);}else{$("#img_so").attr("src",icono_control_false);}
$('#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 != 'Visor') // Se consulta el modo (Recolector o Visor) if(configGeneralEMA.ConfGeneral.Modo != 'Visor') // Se consulta el modo (Recolector o Visor)
{ {
EMA.EstadoUSB(function(EstadoUSB) if(configGeneralEMA.ConfGeneral.Modo === 'Recolector_USB') // Modo Recolector USB
{ {
EstadoEMA_Control = EMA.Estado(); EMA.EstadoUSB(function(EstadoUSB)
if(EstadoEMA_Control[0])
{ {
$("#img_estado").attr("src",icono_control_true);$('#estado').html("En Linea"); EstadoEMA_Control = EMA.Estado();
$('#botoniniciar').attr("disabled",true); if(EstadoEMA_Control[0])
$('#botondetener').attr("disabled",false); {
if(EstadoUSB){ $("#img_estado").attr("src",icono_control_true);$('#estado').html("En Linea");
$('#iusb').html("USB conectado");$("#img_estacion").attr("src",icono_control_true); $('#botoniniciar').attr("disabled",true);
$("#img_detalle").attr("src",icono_control_true);$("#img_mensaje").attr("src",icono_control_true); $('#botondetener').attr("disabled",false);
}
else{$("#img_estacion").attr("src",icono_control_false);$('#iusb').html("USB no conectado");
$("#img_mensaje").attr("src",icono_control_false);$('#mensaje').html("Conecte el USB.");
$("#img_detalle").attr("src",icono_control_false);$('#mensajedetalle').html("Verifique / Conecte la estacion USB.");
}
}else{
$("#img_estado").attr("src",icono_control_neutro);$('#estado').html("Fuera de Linea");
if(EstadoUSB){ if(EstadoUSB){
$('#iusb').html("USB conectado");$("#img_estacion").attr("src",icono_control_true); $('#iusb').html("USB conectado");$("#img_estacion").attr("src",icono_control_true);
$("#img_detalle").attr("src",icono_control_true);$("#img_mensaje").attr("src",icono_control_true); $("#img_detalle").attr("src",icono_control_true);$("#img_mensaje").attr("src",icono_control_true);
$('#mensaje').html("Encienda EMA Libre"); }
$('#botoniniciar').attr("disabled",false);
}
else{$("#img_estacion").attr("src",icono_control_false);$('#iusb').html("USB no conectado"); else{$("#img_estacion").attr("src",icono_control_false);$('#iusb').html("USB no conectado");
$('#botoniniciar').attr("disabled",true);
$("#img_mensaje").attr("src",icono_control_false);$('#mensaje').html("Conecte el USB."); $("#img_mensaje").attr("src",icono_control_false);$('#mensaje').html("Conecte el USB.");
$("#img_detalle").attr("src",icono_control_false);$('#mensajedetalle').html(EstadoEMA_Control[1]); $("#img_detalle").attr("src",icono_control_false);$('#mensajedetalle').html("Verifique / Conecte la estacion USB.");
} }
}
EstadoUSB=null; }else{
}); $("#img_estado").attr("src",icono_control_neutro);$('#estado').html("Fuera de Linea");
if(EstadoUSB){
$('#iusb').html("USB conectado");$("#img_estacion").attr("src",icono_control_true);
$("#img_detalle").attr("src",icono_control_true);$("#img_mensaje").attr("src",icono_control_true);
$('#mensaje').html("Encienda EMA Libre");
$('#botoniniciar').attr("disabled",false);
}
else{$("#img_estacion").attr("src",icono_control_false);$('#iusb').html("USB no conectado");
$('#botoniniciar').attr("disabled",true);
$("#img_mensaje").attr("src",icono_control_false);$('#mensaje').html("Conecte el USB.");
$("#img_detalle").attr("src",icono_control_false);$('#mensajedetalle').html(EstadoEMA_Control[1]);
}
}
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" ))
@ -323,7 +345,8 @@ async function ClimaActual()
{ {
// Se obtiene el estado actual del clima // Se obtiene el estado actual del clima
var SALIDA_ENTRADA = "";var LLUEVE = 0; var NOCHE_DIA = 1; var SALIDA_ENTRADA = "";var LLUEVE = 0; var NOCHE_DIA = 1;
if( UltimoReg.lloviendo > 0){LLUEVE = '1'; }else{LLUEVE = '0';} // LLUEVE? //if( UltimoReg.lloviendo > 0){LLUEVE = '1'; }else{LLUEVE = '0';} // LLUEVE?
LLUEVE = (UltimoReg?.lloviendo ?? 0) > 0 ? '1' : '0';
if( UltimoReg.luxer_intencidad > 0){ NOCHE_DIA = '1'; }else{NOCHE_DIA = '0';} // DIA o NOCHE? if( UltimoReg.luxer_intencidad > 0){ NOCHE_DIA = '1'; }else{NOCHE_DIA = '0';} // DIA o NOCHE?
if( (UltimoReg.luxer_intencidad > UltimoReg.luxer_intencidad_1hs) && (UltimoReg.luxer_intencidad > 0 && UltimoReg.luxer_intencidad < 800)){ SALIDA_ENTRADA = '_1.gif';} // ALBA? if( (UltimoReg.luxer_intencidad > UltimoReg.luxer_intencidad_1hs) && (UltimoReg.luxer_intencidad > 0 && UltimoReg.luxer_intencidad < 800)){ SALIDA_ENTRADA = '_1.gif';} // ALBA?
if( (UltimoReg.luxer_intencidad < UltimoReg.luxer_intencidad_1hs) && (UltimoReg.luxer_intencidad > 0 && UltimoReg.luxer_intencidad < 800)){ SALIDA_ENTRADA = '_0.gif';} // OCASO? if( (UltimoReg.luxer_intencidad < UltimoReg.luxer_intencidad_1hs) && (UltimoReg.luxer_intencidad > 0 && UltimoReg.luxer_intencidad < 800)){ SALIDA_ENTRADA = '_0.gif';} // OCASO?
@ -340,14 +363,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;
@ -574,12 +600,12 @@ function ListarRedes()
{ {
TablaHTML += "<tr><td><b>"+Publicar[i].Nombre+"</b></td><td>"+Publicar[i].TipoRed+"</td><td><span class='badge badge-success'>SI</span></td><td><span class='badge badge-danger'>NO</span></td><td><span class='badge badge-default'>N/A</span></td><td>"+publicar+"</td><td><select onchange='MenuRedes("+i+")' title='Accion' id='Red_activa_"+i+"' name='Red_activa' class='selectpicker show-tick' data-width='fit' data-style='btn-primary'>"; TablaHTML += "<tr><td><b>"+Publicar[i].Nombre+"</b></td><td>"+Publicar[i].TipoRed+"</td><td><span class='badge badge-success'>SI</span></td><td><span class='badge badge-danger'>NO</span></td><td><span class='badge badge-default'>N/A</span></td><td>"+publicar+"</td><td><select onchange='MenuRedes("+i+")' title='Accion' id='Red_activa_"+i+"' name='Red_activa' class='selectpicker show-tick' data-width='fit' data-style='btn-primary'>";
if(Publicar[i].Publicar == true) {TablaHTML += "<option value='NoPublicar'>No Publicar</option>"}else{TablaHTML += "<option value='Publicar'>Publicar</option>"}; if(Publicar[i].Publicar == true) {TablaHTML += "<option value='NoPublicar'>No Publicar</option>"}else{TablaHTML += "<option value='Publicar'>Publicar</option>"};
TablaHTML += "<option value='Modificar'>Modificar</option><option value='Eliminar'>Eliminar</option></select></td></tr>"; TablaHTML += "<option value='Modificar'>Modificar</option><option value='Eliminar'>Eliminar</option><option value='SitioOficial'>Sitio Oficial</option></select></td></tr>";
}else{ }else{
if(Publicar[i].Llave_W != ''){var tienellave = "SI";}else{var tienellave ="NO";} if(Publicar[i].Llave_W != ''){var tienellave = "SI";}else{var tienellave ="NO";}
TablaHTML += "<tr><td><b>"+Publicar[i].Nombre+"</b></td><td>"+Publicar[i].TipoRed+"</td><td><span class='badge badge-default'>N/A</span></td><td><span class='badge badge-success'>"+tienellave+"</span></td><td><span class='badge badge-default'>"+(Publicar[i].Puerto || "N/A")+"</span></td><td>"+publicar+"</td><td><select onchange='MenuRedes("+i+")' title='Accion' id='Red_activa_"+i+"' name='Red_activa' class='selectpicker show-tick' data-width='fit' data-style='btn-primary'>"; TablaHTML += "<tr><td><b>"+Publicar[i].Nombre+"</b></td><td>"+Publicar[i].TipoRed+"</td><td><span class='badge badge-default'>N/A</span></td><td><span class='badge badge-success'>"+tienellave+"</span></td><td><span class='badge badge-default'>"+(Publicar[i].Puerto || "N/A")+"</span></td><td>"+publicar+"</td><td><select onchange='MenuRedes("+i+")' title='Accion' id='Red_activa_"+i+"' name='Red_activa' class='selectpicker show-tick' data-width='fit' data-style='btn-primary'>";
if(Publicar[i].Publicar == true) {TablaHTML += "<option value='NoPublicar'>No Publicar</option>"}else{TablaHTML += "<option value='Publicar'>Publicar</option>"}; if(Publicar[i].Publicar == true) {TablaHTML += "<option value='NoPublicar'>No Publicar</option>"}else{TablaHTML += "<option value='Publicar'>Publicar</option>"};
TablaHTML += "<option value='Modificar'>Modificar</option><option value='Eliminar'>Eliminar</option></select></td></tr>"; TablaHTML += "<option value='Modificar'>Modificar</option><option value='Eliminar'>Eliminar</option><option value='SitioOficial'>Sitio Oficial</option></select></td></tr>";
} }
} }
TablaHTML += "</table>"; TablaHTML += "</table>";
@ -629,28 +655,32 @@ function MenuRedes(red)
switch ($('#Red_activa_'+red).val()) { switch ($('#Red_activa_'+red).val()) {
case 'Eliminar': case 'Eliminar':
// SE PREGUNTA SI ESTA SEGURO // SE PREGUNTA SI ESTA SEGURO
HABLA(0,'¿Esta seguro de eliminar<br> la red <b>'+ configGeneralEMA.ConfPublicador[red].Nombre +'</b>?',"success");
$(document).off('click', '.notifyjs-foo-base .no'); // Se elimina el evento si existe $(document).off('click', '.notifyjs-foo-base .no'); // Se elimina el evento si existe
$(document).off('click', '.notifyjs-foo-base .yes'); // Se elimina el evento si existe $(document).off('click', '.notifyjs-foo-base .yes'); // Se elimina el evento si existe
HABLA(0,'¿Esta seguro de eliminar<br> la red <b>'+ configGeneralEMA.ConfPublicador[red].Nombre +'</b>?',"success"); $.notify.addStyle('foo', {
$.notify.addStyle('foo', { html:
html: "<div style='background:#ff00003b;'>" +
"<div class='clearfix'>" + "<div class='clearfix'>" +
"<div class='title' data-notify-html='title'/>" + "<div class='title' data-notify-html='title'></div>" +
"<div class='buttons'>" + "<div class='buttons' style='margin-top:10px; text-align:center;width:100%;'>" +
"<button class='no'>NO</button><button class='yes' data-notify-text='button'></button>" + "<button class='btn btn-secondary btn-sm no'>Cancelar</button> " +
"<button class='btn btn-danger btn-sm yes'>Confirmar</button>" +
"</div>" + "</div>" +
"</div>" "</div>" +
"</div>"
}); });
//PREGUNTA
// --- Mostrar notificación ---
$("#carpincho_img").notify({ $("#carpincho_img").notify({
title: '¿Esta seguro de eliminar la red '+ configGeneralEMA.ConfPublicador[red].Nombre +'?', title: '¿Está seguro de eliminar la red <b>' + configGeneralEMA.ConfPublicador[red].Nombre + '</b>?'
button: 'SI'
}, { }, {
position:"right middle", position: "right middle",
style: 'foo', style: 'foo',
autoHide: false, autoHide: false,
clickToHide: false clickToHide: false
}); });
$(document).on('click', '.notifyjs-foo-base .no', function() { $(document).on('click', '.notifyjs-foo-base .no', function() {
//RESPONDE NO //RESPONDE NO
ListarRedes(); ListarRedes();
@ -678,6 +708,51 @@ function MenuRedes(red)
break; break;
case 'Modificar': FormModificar(red); case 'Modificar': FormModificar(red);
break; break;
case 'SitioOficial':
let tipored = configGeneralEMA.ConfPublicador[red].TipoRed;
tipored = tipored.toLowerCase();
let url = '';
switch (tipored) {
case 'openweathermap':
url = 'https://openweathermap.org/';
break;
case 'wow':
url = 'https://wow.metoffice.gov.uk/';
break;
case 'windguru':
url = 'https://www.windguru.cz/';
break;
case 'windy':
url = 'https://www.windy.com/';
break;
case 'awekas':
url = 'https://www.awekas.at/';
break;
case 'wunderground':
url = 'https://www.wunderground.com/';
break;
case 'pws':
url = 'https://www.pwsweather.com/';
break;
case 'emacenter':
url = 'https://emacenter.gugler.com.ar/';
break;
case 'emacentergugler':
url = 'https://emacenter.gugler.com.ar/';
break;
default:
HABLA(0, "No se encontró el sitio oficial para la red '" + tipored + "'", "warn");
return;
}
if (url !== '') {
const openExternal = require('nw.gui').Shell.openExternal;
openExternal(url);
HABLA(0, "Abriendo sitio oficial de '" + tipored + "'.", "info");
}
ListarRedes();
break;
} }
} }
@ -874,6 +949,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 +1008,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 +1307,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 +1328,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"}
}); });
@ -1258,21 +1346,21 @@ async function MostrarTabla(DATOS,DIV,TABLA)
async function graficoEstadisticas() async function graficoEstadisticas()
{ {
// GRAFICO DEL TIEMPO CHARTJS
document.getElementById("grafico").style.display = "none";
document.getElementById("actualizando").style.display = "block";
// GRAFICO DEL TIEMPO CHARTJS //Se genera el grafico normal
document.getElementById("grafico").style.display = "none"; if(['Recolector_USB', 'Recolector_IP'].includes(configGeneralEMA.ConfGeneral.Modo)) // se comprueba el modo se encuentra en Recolector
document.getElementById("actualizando").style.display = "block"; {
//Se genera el grafico
if(configGeneralEMA.ConfGeneral.Modo == 'Recolector') // se comprueba el modo se encuentra en Recolector
{
fsconf.readFile('./logs/registro_diario.log', { fsconf.readFile('./logs/registro_diario.log', {
encoding: 'utf8', encoding: 'utf8',
autoClose: true autoClose: true
}, (err, data) => { }, (err, data) => {
if (err) { if (err) {
EMA.RegistrarLog("1|ERROR|Error al intentar leer el registro diario para generar el grafico estadistico."); EMA.RegistrarLog("1|ERROR|Error al intentar leer el registro diario para generar el grafico estadistico.");
} else { } else {
var db = new Date(); var db = new Date();
var mes = db.getMonth() + 1; if(mes <= 9) {mes = '0'+ mes}; var mes = db.getMonth() + 1; if(mes <= 9) {mes = '0'+ mes};
var dia= db.getDate();if(dia <= 9) {dia = '0'+ dia}; var dia= db.getDate();if(dia <= 9) {dia = '0'+ dia};
@ -1288,8 +1376,8 @@ async function graficoEstadisticas()
var RegistroDiarioTmp = JSON.parse(data); var RegistroDiarioTmp = JSON.parse(data);
var CantRegistros = RegistroDiarioTmp.length; var CantRegistros = RegistroDiarioTmp.length;
// console.log(CantRegistros); // console.log(CantRegistros);
if(CantRegistros > 1) if(CantRegistros > 1)
{ {
delete RegistroDiarioTmp['fechaISO']; delete RegistroDiarioTmp['fechaISO'];
delete RegistroDiarioTmp['fechaUTC']; delete RegistroDiarioTmp['fechaUTC'];
delete RegistroDiarioTmp['luxer_intencidad_1hs']; delete RegistroDiarioTmp['luxer_intencidad_1hs'];
@ -1335,266 +1423,60 @@ async function graficoEstadisticas()
var presionRel = RegistroDiarioConCambios.map(function(e) { return e.presion_relativa || 0;}); var presionRel = RegistroDiarioConCambios.map(function(e) { return e.presion_relativa || 0;});
var validacion = RegistroDiarioConCambios.map(function(e) { return (e.estado_validacion_ant) || 0;}); var validacion = RegistroDiarioConCambios.map(function(e) { return (e.estado_validacion_ant) || 0;});
var puntorocio = RegistroDiarioConCambios.map(function(e) { return e.punto_de_rocio || 0;}); var puntorocio = RegistroDiarioConCambios.map(function(e) { return e.punto_de_rocio || 0;});
// GRAFICO RESUMEN CON RGRAPH
var resumenLabels = [
'Temp.Ext', 'Hum.Ext', 'Temp.Int', 'Hum.Int', 'Viento', 'Lluvia', 'Pres.Rel', 'UV', 'Luxer', 'Pto.Rocío', 'Valid.'
];
var resumenData = [
tmp_Ext[tmp_Ext.length-1] || 0,
hum_Ext[hum_Ext.length-1] || 0,
tmp_Int[tmp_Int.length-1] || 0,
hum_Int[hum_Int.length-1] || 0,
vientos[vientos.length-1] || 0,
Lluvia[Lluvia.length-1] || 0,
presionRel[presionRel.length-1] || 0,
UV[UV.length-1] || 0,
Luxer[Luxer.length-1] || 0,
puntorocio[puntorocio.length-1] || 0,
validacion[validacion.length-1] || 0
];
//console.log(validacion); window._GraphInicioChart = new RGraph.Bar({
var totalErrores = 0; id: 'graph_inicio',
for(var i=0;i<validacion.length;i++) data: resumenData,
{ if(!isNaN(parseInt(validacion[i]),10)) totalErrores += parseInt(validacion[i],10);};
// Se genera grafico de resumen
new Chart(document.getElementById("graph_inicio"), {
type: 'bar',
data: {
labels: ["Registros Totales \n "+ CantRegistros, "Registros Distintos", "Pendientes Almacenado","Pendientes Publicados","Errores Detectados"],
datasets: [
{
label: "Resumen de Estadisticas",
backgroundColor: ["#3e95cd", "#28a745","#c45850","#48a745","#c42850"],
data: [CantRegistros,RegistroDiarioConCambios.length,CantiddPendientesAlmacenados, CantiddPendientesPublicados, totalErrores]
}
]
},
options: { options: {
showAllTooltips: true, colors: ['#1e90ff','#00b894','#fdcb6e','#e17055','#636e72','#00bfff','#6c5ce7','#fd79a8','#ffeaa7','#fab1a0','#636e72'],
hover: { backgroundGrid: true,
animationDuration: 0 xaxisLabels: resumenLabels,
}, yaxis: true,
animation: { yaxisLabelsCount: 5,
duration: 1, marginLeft: 50,
onComplete: function () { marginBottom: 60,
var chartInstance = this.chart, marginTop: 40,
ctx = chartInstance.ctx; marginRight: 20,
ctx.font = Chart.helpers.fontString('14', 'normal', Chart.defaults.global.defaultFontFamily); title: 'Resumen Últimos Valores',
ctx.fillStyle = 'white'; titleBold: true
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
ctx.fontColor = 'white';
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
},
legend: {
display: false,
labels: {
display: false
}
},
title: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
fontColor: 'white'
},
}],
xAxes: [{
ticks: {
fontColor: 'white'
},
}]
}
} }
}); }).draw();
// document.getElementById("actualizando").style.display = "none";
//console.log("Grafico resumen generado con RGraph.");
//console.table(resumenLabels);
// console.table(resumenData);
}else{
RegistroDiarioTmp = null;CantRegistros=null;CantiddPendientesAlmacenados=null; CantiddPendientesPublicados = null;RegistroDiarioConCambios = null; return false
//Se genera el grafico //document.getElementById("inicio_estadisticas").innerHTML = "<h2> No hay registros para procesar .. </h2>";
//document.getElementById("grafico").innerHTML = "<h2> No hay registros para procesar .. </h2>";
Grafico = new Chart(document.getElementById("graph"), { //document.getElementById("actualizando").style.display = "none";
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Temp.Ext',
data: tmp_Ext,
pointRadius:1,
// backgroundColor: ['rgba(200, 0, 0, 0.8)'],
borderColor: ['rgba(200,0,0,1)'],
borderWidth: 3
},
{
label: 'Hum.Ext',
data: hum_Ext,
pointRadius:0.2,
// backgroundColor: ['rgba(100,0,0, 0.8)'],
borderColor: ['rgba(100,0,100,1)'],
borderWidth: 3,
hidden: true,
},
{
label: 'Pto.Rocio',
data: puntorocio,
pointRadius:0.2,
// backgroundColor: ['rgba(100,100,0, 0.8)'],
borderColor: ['rgba(100,100,0,1)'],
borderWidth: 3,
hidden: true,
},
{
label: 'Temp.Int',
data: tmp_Int,
pointRadius:0.2,
//backgroundColor: ['rgba(100,100,100, 0.8)'],
borderColor: ['rgba(100,100,255,1)'],
borderWidth: 3,
hidden: true,
},
{
label: 'Hum.Int',
data: hum_Int,
pointRadius:0.2,
backgroundColor: ['rgba(100,180,0, 0.8)'],
borderColor: ['rgba(100,190,0,1)'],
borderWidth: 2,
hidden: true,
},
{
label: 'V.Raf',
data: vinetosRaf,
pointRadius:0.2,
// backgroundColor: ['rgba(255,80,220, 0.8)'],
borderColor: ['rgba(100,90,0,1)'],
borderWidth: 3,
hidden: true,
},
{
label: 'V.Vel',
data: vientos,
pointRadius:0.2,
backgroundColor: ['rgba(100,80,0, 1)'],
borderColor: ['rgba(100,90,0,1)'],
borderWidth: 0.2,
hidden: true,
},
{
label: 'UV',
data: UV,
pointRadius:0.2,
backgroundColor: ['rgba(97, 42, 154, 0.9)'],
borderColor: ['rgba(97, 42, 154,1)'],
borderWidth: 2,
hidden: true,
},
{
label: 'L.Intec',
data: Luxer,
pointRadius:0.2,
backgroundColor: ['rgba(255,255,0, 0.9)'],
borderColor: ['rgba(255,255,0,1)'],
borderWidth: 2,
hidden: true,
},
{
label: 'Lluvia',
data: Lluvia,
pointRadius:0.2,
backgroundColor: ['rgba(100,80,100, 0.9)'],
borderColor: ['rgba(100,90,0,1)'],
borderWidth: 2,
hidden: true,
},
{
label: 'Valid.',
data: validacion,
pointRadius:0.2,
backgroundColor: ['rgba(220,53,69, 1)'],
borderColor: ['rgba(220,60,69,1)'],
borderWidth: 2,
},
{
label: 'Pre.R',
data: presionRel,
pointRadius:0.2,
//backgroundColor: ['rgba(100,80,100, 0.8)'],
borderColor: ['rgba(255,255,255,1)'],
borderWidth: 2,
hidden: true,
}
]
},
options: {
showAllTooltips: true,
//elements: { point: { hitRadius: 5, hoverRadius: 5 }},
tooltips: {
backgroundColor: 'white',
titleFontColor: 'black',
callbacks: {
labelColor: function(tooltipItem, chart) {
var datos = chart.config.data.datasets[tooltipItem.datasetIndex];
if(typeof datos.backgroundColor === 'undefined') { var colorfondo = 'white';}else{var colorfondo= datos.backgroundColor[0];}
return {
backgroundColor : colorfondo,
borderColor : datos.borderColor[0],
borderWidth: 5,
labelTextColor: 'black'
};
},
labelTextColor: function(tooltipItem, chart) {
return 'black';
}
}
},
legend: {
labels: {
fontColor: 'white'
}
},
scales: {
yAxes: [{
ticks: {
autoSkip: true,
maxTicksLimit: 30,
showXLabels: 10,
beginAtZero:true,
fontColor: 'white'
},
gridLines: {
display: false,
drawBorder: true,
color: "white",
}
}],
xAxes: [{
ticks: {
beginAtZero:true,
fontColor: 'white'
},
gridLines: {
display: false,
drawBorder: true,
color: "white",
}
}]
},
title: {
display: true,
fontColor: 'white',
text: 'Estadísticas del dia hasta '+fecha_maxima
}
}
});
document.getElementById("actualizando").style.display = "none";
}else{
document.getElementById("inicio_estadisticas").innerHTML = "<h2> No hay registros para procesar .. </h2>";
document.getElementById("grafico").innerHTML = "<h2> No hay registros para procesar .. </h2>";
document.getElementById("actualizando").style.display = "none";
}
} }
});
}else{ //MODO Visor
document.getElementById("inicio_estadisticas").innerHTML = "<h2> Las estadisticas solo en modo recolector. </h2>";
document.getElementById("grafico").innerHTML = "<h2> Gráficos de estadisticas solo en modo recolector. </h2>";
document.getElementById("actualizando").style.display = "none";
} }
});
}else{ //MODO Visor
return false;
//document.getElementById("inicio_estadisticas").innerHTML = "<h2> Las estadisticas solo en modo recolector. </h2>";
//document.getElementById("grafico").innerHTML = "<h2> Gráficos de estadisticas solo en modo recolector. </h2>";
//document.getElementById("actualizando").style.display = "none";
} }
}

View File

@ -52,22 +52,45 @@ 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: 350,
width: 450, height: 200
height: 200, }, function(win) {
min_width: 450, gui.Screen.Init();
min_height: 200, setTimeout(function() {
max_width: 450, const screens = gui.Screen.screens;
max_height: 200 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>
@ -30,22 +32,30 @@
<script src="../gui_common/libs/RGraph/RGraph.thermometer.js"></script> <script src="../gui_common/libs/RGraph/RGraph.thermometer.js"></script>
<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.bar.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>
<!-- 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 -->
<script src="../node_modules/notify-js-lib/dist/notify.js"></script> <script src="../node_modules/notify-js-lib/dist/notify.js"></script>
<!-- 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="../gui_common/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">
<!-- Pantalla de Carga --> <!-- Pantalla de Carga -->
<div id="cargador" class="d-flex justify-content-center align-items-center" style="background-color: #567d3d;"> <div id="cargador" class="d-flex justify-content-center align-items-center" style="background-color: #042507;">
<div class="progressinicio"> <div class="progressinicio">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="background-color: #567d3d; width: 100%"> <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="background-color: #30511b; width: 100%">
<img id="loadinicio" class="mx-auto d-block" src="../gui_common/iconos/icono_app.webp" height="120px" width="140px"> <img id="loadinicio" class="mx-auto d-block" src="../gui_common/iconos/icono_app.webp" height="120px" width="140px">
<p class="text-center text-white">EMA Libre Cliente <br> (Carpincho) <br> Licencia GPLv3</p> <p class="text-center text-white">EMA Libre Cliente <br> (Carpincho) <br> Licencia GPLv3</p>
</div> </div>
@ -73,29 +83,33 @@
<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>
</div> </div>
</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">
@ -108,9 +122,9 @@
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" id="exterior-tab" data-toggle="tab" data-target="#exterior" role="tab" aria-controls="exterior" aria-selected="false"><img height="24px" width="24px" src="../gui_common/img/exterior.webp" aria-controls="exterior"> EXTERIOR</a> <a class="nav-link" id="exterior-tab" data-toggle="tab" data-target="#exterior" role="tab" aria-controls="exterior" aria-selected="false"><img height="24px" width="24px" src="../gui_common/img/exterior.webp" aria-controls="exterior"> EXTERIOR</a>
</li> </li>
<li class="nav-item"> <!-- <li class="nav-item">
<a class="nav-link" id="estadisticas-tab" data-toggle="tab" data-target="#estadisticas" role="tab" aria-controls="estadisticas" aria-selected="false"><img height="24px" width="24px" src="../gui_common/img/estadistica.png" aria-controls="estadisticas"> ESTADISTICAS</a> <a class="nav-link" id="estadisticas-tab" data-toggle="tab" data-target="#estadisticas" role="tab" aria-controls="estadisticas" aria-selected="false"><img height="24px" width="24px" src="../gui_common/img/estadistica.png" aria-controls="estadisticas"> ESTADISTICAS</a>
</li> </li> -->
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" id="redes-tab" data-toggle="tab" data-target="#redes" role="tab" aria-controls="redes" aria-selected="false"><img height="24px" width="24px" src="../gui_common/img/redes.webp" aria-controls="redes"> REDES</a> <a class="nav-link" id="redes-tab" data-toggle="tab" data-target="#redes" role="tab" aria-controls="redes" aria-selected="false"><img height="24px" width="24px" src="../gui_common/img/redes.webp" aria-controls="redes"> REDES</a>
</li> </li>
@ -122,11 +136,11 @@
</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>
<div class="tab-pane fade text-center" id="estadisticas" role="tabpanel" aria-badgeledby="estadisticas-tab"></div> <!-- <div class="tab-pane fade text-center" id="estadisticas" role="tabpanel" aria-badgeledby="estadisticas-tab"></div>-->
<div class="tab-pane fade text-center" id="configuracion" role="tabpanel" aria-badgeledby="configuracion-tab"></div> <div class="tab-pane fade text-center" id="configuracion" role="tabpanel" aria-badgeledby="configuracion-tab"></div>
<div class="tab-pane fade text-center" id="redes" role="tabpanel" aria-badgeledby="redes-tab"></div> <div class="tab-pane fade text-center" id="redes" role="tabpanel" aria-badgeledby="redes-tab"></div>
<div class="tab-pane fade" id="contacto" role="tabpanel" aria-badgeledby="contacto-tab"></div> <div class="tab-pane fade" id="contacto" role="tabpanel" aria-badgeledby="contacto-tab"></div>
@ -145,6 +159,22 @@
$('.menu').on('click', function(evnt) { $('.menu').on('click', function(evnt) {
var obj = $(evnt.target); var obj = $(evnt.target);
$('#' + obj.attr('aria-controls')).empty(); $('#' + obj.attr('aria-controls')).empty();
let screens = gui.Screen.screens;
let winX = win.x;
let 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;
}
}
//nw.Window.get().moveTo(0);
switch (obj.attr('id')) { switch (obj.attr('id')) {
case 'Wzoomin': case 'Wzoomin':
win.zoomLevel += 0.3; win.zoomLevel += 0.3;
@ -153,16 +183,21 @@
win.zoomLevel -= 0.3; win.zoomLevel -= 0.3;
break; break;
case 'Wfull': case 'Wfull':
win.toggleFullscreen(); nw.Window.get().moveTo(currentScreen.bounds.x, currentScreen.bounds.y);
nw.Window.get().resizeTo(currentScreen.bounds.width, currentScreen.bounds.height);
break; break;
case 'Wmin': case 'Wmin':
win.minimize(); nw.Window.get().minimize();
//win.hide(); // Oculta completamente la ventana
//win.setShowInTaskbar(false); // Quita el icono del taskbar
break; break;
case 'Wmax': case 'Wmax':
win.maximize(); nw.Window.get().moveTo(currentScreen.bounds.x, currentScreen.bounds.y);
nw.Window.get().resizeTo(currentScreen.bounds.width, currentScreen.bounds.height);
break; break;
case 'Wmaxun': case 'Wmaxun':
win.unmaximize() nw.Window.get().moveTo(currentScreen.bounds.x, currentScreen.bounds.y);
nw.Window.get().resizeTo(currentScreen.bounds.width/2, currentScreen.bounds.height/2);
break; break;
case 'Wclo': case 'Wclo':
EMA.Salir(); EMA.Salir();

View File

@ -1,211 +1,264 @@
<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="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 class="row">
<div class="col-4 col-centered">
<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">
<optgroup label="Recolector">
<option value="Recolector_USB">Recolector USB</option>
<option value="Recolector_IP">Recolector IP/WIFI</option>
</optgroup>
<optgroup label="Visor">
<option value="Visor">Visor Llave</option>
</optgroup>
</select>
</div>
<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>
<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">
<option value="Activado">Activado</option>
<option value="Desactivado">Desactivado</option>
</optgroup>
</select>
</div>
<div class="col-2 col-centered">
<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">
<optgroup label="Notificar de carpincho">
<option value="Activado">Activado</option>
<option value="Desactivado">Desactivado</option>
</optgroup>
</select>
</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 class="col-3 col-centered" id="vocesAudioDiv">
<label class="control-label">Voz del Audio</label></br>
<select id='vocesAudio' name="vocesAudio" class="selectpicker show-tick" data-width="fit" data-style="btn-primary" size="100">
<optgroup label="Lista de Voces">
</optgroup>
</select>
</div>
</div>
<hr class="hr-suave">
<div class="row">
<div class="col-2 col-centered">
<label class="control-label">Recolección</label><br>
<select id='Tiempo_de_Recoleccion' name="Tiempo_de_Recoleccion" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Muy Rapido">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</optgroup>
<optgroup label="Medio">
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
</optgroup>
<optgroup label="Normal">
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</optgroup>
<optgroup label="Despacio">
<option value="110">110</option>
<option value="120">120</option>
<option value="130">130</option>
<option value="140">140</option>
</optgroup>
</select>
</div>
<div class="col-3 col-centered">
<label class="control-label">Debug y Tamaño</label><br>
<select id='Debug' name="Debug" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Normal">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</optgroup>
<optgroup label="Alto">
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</optgroup>
<optgroup label="Muy Alto">
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</optgroup>
</select>
<input type="text" class="btn btn-primary" id="debugMB" placeholder="MB Debug" maxlength="4" size="5">
<label class="control-label">MB</label>
</div>
<div class="col-1 col-centered">
<label class="control-label">UTC</label><br>
<select id='utc' name="utc" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Negativo">
<option value="-1">-1</option>
<option value="-2">-2</option>
<option value="-3">-3</option>
<option value="-4">-4</option>
<option value="-5">-5</option>
<option value="-6">-6</option>
<option value="-7">-7</option>
<option value="-8">-8</option>
<option value="-9">-9</option>
<option value="-10">-10</option>
<option value="-11">-11</option>
<option value="-12">-12</option>
</optgroup>
<optgroup label="Neutro">
<option value="0">0</option>
</optgroup>
<optgroup label="Positivo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</optgroup>
</select>
</div>
<div class="col-2 col-centered">
<label class="control-label">Unidades</label><br>
<select id='SistemaMetrico' name="SistemaMetrico" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Sistema Internacional de Unidades(SI)">
<option value="SI">º C</option>
</optgroup>
<optgroup label="Sistema Anglosajón de Unidades(SA)">
<option value="SA">º F</option>
</optgroup>
</select>
</div>
</div>
<hr class="hr-suave">
<div class="row">
<div class="col-3 col-centered">
<label class="control-label">SMTP TIPO</label><br>
<select id='Tipo_SMTP' name="Tipo_SMTP" onchange="MenuConfig();" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="SMTP Deshabilitado">
<option value="Deshabilitado">Deshabilitado</option>
</optgroup>
<optgroup label="SMTP Proveedor">
<option value="Gmail">GMAIL</option>
<option value="Yahoo">YAHOO</option>
<option value="Hotmail">OUTLOOK</option>
</optgroup>
<optgroup label="SMTP Manual">
<option value="Manual">SMTP CONFIG</option>
</select>
</div>
<div class="col-3 col-centered">
<label class="control-label">Cuenta</label><br>
<input type="email" class="btn btn-primary" id="Usuario_SMTP" placeholder="Cuenta" maxlength="40" size="16">
</div>
<div class="col-3 col-centered">
<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">
</div>
<div class="col-2 col-centered" id="Server">
<label class="control-label">Server</label><br>
<input type="text" class="btn btn-primary" id="Server_SMTP" placeholder="Server" maxlength="40" size="15">
</div>
<div class="col-1 col-centered" id="puerto">
<label class="control-label">Puerto</label><br>
<input type="text" class="btn btn-primary" id="Puerto_SMTP" placeholder="Puerto" maxlength="4" size="5">
</div>
</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="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-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 class="row">
<div class="col-3" align="left" style="vertical-align:top;"></div> </div>
<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> <div id="bloque_por_IP_WIFI" class="row">
<input type="text" class="btn btn-primary" id="NombreEstacion" autocomplete='name' placeholder="Ingrese el nombre" maxlength="20" size="25"></br></br>
<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>
</div>
<div class="row">
<div class="col-3 col-centered">
<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">
<optgroup label="Recolector USB">
<option value="Recolector">Recolector</option>
</optgroup>
<optgroup label="Visor por Llave">
<option value="Visor">Visor</option>
</optgroup>
</select>
</div>
<div class="col-3 col-centered">
<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">
<optgroup label="Iniciar el recolector/visor con el aplicativo">
<option value="Activado">Activado</option>
<option value="Desactivado">Desactivado</option>
</optgroup>
</select>
</div>
<div class="col-3 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>
<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">
<option value="Activado">Activado</option>
<option value="Desactivado">Desactivado</option>
</optgroup>
</select>
</div>
</div>
<hr>
<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 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">
<optgroup label="Lista de Voces">
</optgroup>
</select>
</div>
</div>
<hr>
<div class="row">
<div class="col-2 col-centered">
<label class="control-label">Recolección</label><br>
<select id='Tiempo_de_Recoleccion' name="Tiempo_de_Recoleccion" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Muy Rapido">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</optgroup>
<optgroup label="Medio">
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
</optgroup>
<optgroup label="Normal">
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</optgroup>
<optgroup label="Despacio">
<option value="110">110</option>
<option value="120">120</option>
<option value="130">130</option>
<option value="140">140</option>
</optgroup>
</select>
</div>
<div class="col-3 col-centered">
<label class="control-label">Debug y Tamaño</label><br>
<select id='Debug' name="Debug" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Normal">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</optgroup>
<optgroup label="Alto">
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</optgroup>
<optgroup label="Muy Alto">
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</optgroup>
</select>
<input type="text" class="btn btn-primary" id="debugMB" placeholder="MB Debug" maxlength="4" size="5">
<label class="control-label">MB</label>
</div>
<div class="col-1 col-centered">
<label class="control-label">UTC</label><br>
<select id='utc' name="utc" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Negativo">
<option value="-1">-1</option>
<option value="-2">-2</option>
<option value="-3">-3</option>
<option value="-4">-4</option>
<option value="-5">-5</option>
<option value="-6">-6</option>
<option value="-7">-7</option>
<option value="-8">-8</option>
<option value="-9">-9</option>
<option value="-10">-10</option>
<option value="-11">-11</option>
<option value="-12">-12</option>
</optgroup>
<optgroup label="Neutro">
<option value="0">0</option>
</optgroup>
<optgroup label="Positivo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</optgroup>
</select>
</div>
<div class="col-2 col-centered">
<label class="control-label">Unidades</label><br>
<select id='SistemaMetrico' name="SistemaMetrico" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Sistema Internacional de Unidades(SI)">
<option value="SI">º C</option>
</optgroup>
<optgroup label="Sistema Anglosajón de Unidades(SA)">
<option value="SA">º F</option>
</optgroup>
</select>
</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>
<hr>
<div class="row">
<div class="col-3 col-centered">
<label class="control-label">SMTP TIPO</label><br>
<select id='Tipo_SMTP' name="Tipo_SMTP" onchange="MenuConfig();" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="SMTP Deshabilitado">
<option value="Deshabilitado">Deshabilitado</option>
</optgroup>
<optgroup label="SMTP Proveedor">
<option value="Gmail">GMAIL</option>
<option value="Yahoo">YAHOO</option>
<option value="Hotmail">OUTLOOK</option>
</optgroup>
<optgroup label="SMTP Manual">
<option value="Manual">SMTP CONFIG</option>
</select>
</div>
<div class="col-3 col-centered">
<label class="control-label">Cuenta</label><br>
<input type="email" class="btn btn-primary" id="Usuario_SMTP" placeholder="Cuenta" maxlength="40" size="16">
</div>
<div class="col-3 col-centered">
<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="-">
</div>
<div class="col-2 col-centered" id="Server">
<label class="control-label">Server</label><br>
<input type="text" class="btn btn-primary" id="Server_SMTP" placeholder="Server" maxlength="40" size="15">
</div>
<div class="col-1 col-centered" id="puerto">
<label class="control-label">Puerto</label><br>
<input type="text" class="btn btn-primary" id="Puerto_SMTP" placeholder="Puerto" maxlength="4" size="5">
</div>
</div><br>
<div class="row">
<div class="col-12 col-centered">
<button type="button" id="botonguardar" class="btn btn-sm btn-success" onclick="GuardarConf('conf')" role="button">Guardar</button>
</div>
</div> </div>
</div> </div>
<hr class="hr-suave">
<div class="row">
<div class="col-12 col-centered">
<button type="button" id="botonguardar" class="btn btn-sm btn-success" onclick="GuardarConf('conf')" role="button">Guardar</button>
</div>
</div>
</body>

View File

@ -26,7 +26,7 @@
<div class="col-8"> <div class="col-8">
<h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Software:</strong> EMA Libre Cliente (Carpincho)</h4> <h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Software:</strong> EMA Libre Cliente (Carpincho)</h4>
<h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Versión:</strong> <span id="versioncontacto">-</span></h4> <h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Versión:</strong> <span id="versioncontacto">-</span></h4>
<h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Sitio Oficial:</strong> <a href="https://ema.gugler.com.ar" class="text-primary">ema.gugler.com.ar</a></h4> <h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Sitio Oficial:</strong> <a href="https://ema.gugler.com.ar" class="text-success">https://ema.gugler.com.ar</a></h4>
<h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Licencia:</strong> GPLv3</h4> <h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Licencia:</strong> GPLv3</h4>
</div> </div>
@ -53,9 +53,8 @@
Si deseas realizar consultas, sugerencias o tienes alguna duda sobre nuestros productos/servicios, puedes comunicarte con nosotros a través de los siguientes medios: Si deseas realizar consultas, sugerencias o tienes alguna duda sobre nuestros productos/servicios, puedes comunicarte con nosotros a través de los siguientes medios:
</p> </p>
<h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Teléfono:</strong> (0054 - 0343) 4975044 - Interno 119</h4> <h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Teléfono:</strong> (0054 - 0343) 4975044 - Interno 119</h4>
<h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Correo Electrónico:</strong> <a href="mailto:gugler_contacto@uader.edu.ar" class="text-primary">gugler_contacto@uader.edu.ar</a></h4> <h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Correo Electrónico:</strong> <a href="mailto:gugler_contacto@uader.edu.ar" class="text-success">gugler_contacto@uader.edu.ar</a></h4>
<h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Sitio Oficial:</strong> <a href="https://www.gugler.com.ar" class="text-primary">gugler.com.ar</a></h4> <h4><img src="../gui_common/img/ok.webp" height="25" width="25" alt="Check"> <strong>Sitio Oficial:</strong> <a href="https://www.gugler.com.ar" class="text-success">https://www.gugler.com.ar</a></h4>
</div> </div>
</div> </div>
</div> </div>

View File

@ -7,19 +7,18 @@
<br><br> <img src='../gui_common/img/animadas/cargando2.gif' width='40' height='40' /> <br> <small>Cargando Gráfico...</small> <br><br> <img src='../gui_common/img/animadas/cargando2.gif' width='40' height='40' /> <br> <small>Cargando Gráfico...</small>
</div> </div>
<div id="inicio_estadisticas"> <div id="inicio_estadisticas">
<canvas id="graph_inicio" style="height:50vh; width:80vw" ></canvas> <canvas id="graph_inicio" width="800" height="400" style="width:100%; height:400px; max-width:80vw; max-height:50vh;"></canvas>
</div> </div>
<div id="grafico" style="background-color:#182c3e00; display:none" > <div id="grafico" style="background-color:#182c3e00; " >
<canvas id="graph" style="height:50vh; width:80vw" ></canvas> <canvas id="graph" style="height:50vh; width:80vw" ></canvas>
</div> </div>
<div> <div>
<script> <script>
function Mostrar() function Mostrar()
{ {
document.getElementById("grafico").style.display = "block"; document.getElementById("grafico").style.display = "block";
document.getElementById("inicio_estadisticas").style.display = "hidden"; document.getElementById("inicio_estadisticas").style.display = "none";
document.getElementById("inicio_estadisticas").hidden = true; document.getElementById("inicio_estadisticas").hidden = true;
document.getElementById("boton_grafico").hidden = true; document.getElementById("boton_grafico").hidden = true;
document.getElementById("boton_volver").hidden = false; document.getElementById("boton_volver").hidden = false;

View File

@ -10,10 +10,10 @@
<!-- Información General --> <!-- Información General -->
<td> <td>
<h5><b>Información General</b></h5> <h5><b>Información General</b></h5>
<p><img id="img_nombre" height="25" width="25" alt="Nombre"> Nombre: <span class="badge bg-info text-dark" id="inombre">-</span></p> <p><img src="../gui_common/img/informacion.png" id="img_nombre" height="25" width="25" alt="Nombre"> Nombre: <span class="badge bg-info text-dark" id="inombre">-</span></p>
<p><img id="img_so" height="25" width="25" alt="S.O"> S.O: <span class="badge bg-info text-dark" id="iso">-</span></p> <p><img src="../gui_common/img/informacion.png" id="img_so" height="25" width="25" alt="S.O"> S.O: <span class="badge bg-info text-dark" id="iso">-</span></p>
<p><img id="img_modo" height="25" width="25" alt="Modo"> Modo: <span class="badge bg-info text-dark" id="imodo">-</span></p> <p><img src="../gui_common/img/informacion.png" id="img_modo" height="25" width="25" alt="Modo"> Modo: <span class="badge bg-info text-dark" id="imodo">-</span></p>
<p><img src="../gui_common/img/ok.webp" height="25" width="25" alt="NW.js"> NW.js: <p><img src="../gui_common/img/informacion.png" height="25" width="25" alt="NW.js"> NW.js:
<span class="badge bg-info text-dark" id="nwjs_v" data-bs-toggle="tooltip" data-bs-placement="right" title="-">-</span> <span class="badge bg-info text-dark" id="nwjs_v" data-bs-toggle="tooltip" data-bs-placement="right" title="-">-</span>
</p> </p>
</td> </td>

File diff suppressed because it is too large Load Diff

View File

@ -150,28 +150,28 @@
body.dia { body.dia {
font-family: monospace !important; font-family: monospace !important;
background-image: url('../img/fondo/dia.webp'); background-image: url('/gui_common/img/fondo/dia.webp');
background-repeat: no-repeat; background-repeat: no-repeat;
background-size: cover; background-size: cover;
} }
body.dia_lluvia { body.dia_lluvia {
font-family: monospace !important; font-family: monospace !important;
background-image: url('../img/fondo/lluvia_dia.webp'); background-image: url('/gui_common/img/fondo/lluvia_dia.webp');
background-repeat: no-repeat; background-repeat: no-repeat;
background-size: cover; background-size: cover;
} }
body.noche { body.noche {
font-family: monospace !important; font-family: monospace !important;
background-image: url('../img/fondo/noche.webp'); background-image: url('/gui_common/img/fondo/noche.webp');
background-repeat: no-repeat; background-repeat: no-repeat;
background-size: cover; background-size: cover;
} }
body.noche_lluvia { body.noche_lluvia {
font-family: monospace !important; font-family: monospace !important;
background-image: url('../img/fondo/lluvia_noche.webp'); background-image: url('/gui_common/img/fondo/lluvia_noche.webp');
background-repeat: no-repeat; background-repeat: no-repeat;
background-size: cover; background-size: cover;
} }
@ -254,15 +254,14 @@ h6,
width: 150px; width: 150px;
float: center; float: center;
text-align: center; text-align: center;
margin: 20px 0 0 40px; margin: 20px 0 0 0px;
font-size: 8px; font-size: 10px;
} }
.notifyjs-foo-base button { .notifyjs-foo-base button {
font-size: 10px; font-size: 12px;
padding: 1px; padding: 1px;
margin: 2px; margin: 2px;
width: 40px;
} }
.texttanque { .texttanque {

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
'version:2024-12-01 (6.20)'; 'version:2025-10-08 (7.01)';
// //
// 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: |
@ -80,7 +80,7 @@
// //
// Some example background properties // Some example properties
// //
this.properties = this.properties =
{ {
@ -136,10 +136,53 @@
text: null, text: null,
clearto: 'rgba(0,0,0,0)', clearto: 'rgba(0,0,0,0)',
clip: null,
events: {},
scale: true,
scaleFactor: 2,
antialiasTranslate: false
};
//
// These are the properties that get scaled up if the
// scale option is enabled.
//
this.properties_scale = [
'width',
'height',
'marginLeft',
'marginRight',
'marginBottom',
'marginTop',
'marginInner',
'textSize',
'shadowOffsetx',
'shadowOffsety',
'shadowBlur',
'linewidth',
'borderLinewidth',
'borderRadius'
];
clip: null
}
// //
// Add the reverse look-up table for property names // Add the reverse look-up table for property names
@ -263,11 +306,26 @@
// //
this.draw = function () this.draw = function ()
{ {
// MUST be the first thing that's done - but only
// once!!
RGraph.runOnce(`scale-up-the-canvas-once-in-the-draw-function-${this.id}-${this.uid}`, () =>
{
// Note that we're in an arrow function so the
// 'this' variable is OK to be used and refers
// to the RGraph Line chart object.
RGraph.scale(this);
});
// //
// Fire the onbeforedraw event // Fire the onbeforedraw event
// //
RGraph.fireCustomEvent(this, 'onbeforedraw'); RGraph.fireCustomEvent(this, 'onbeforedraw');
var scaleFactor = RGraph.getScaleFactor(this);
@ -287,12 +345,15 @@
// Translate half a pixel for antialiasing purposes - but only if it hasn't been // Translate half a pixel for antialiasing purposes - but
// done already // only if it hasn't been done already
// //
// MUST be the first thing done! // The old style antialias fix
// //
if (!this.canvas.__rgraph_aa_translated__) { if ( !this.properties.scale
&& this.properties.antialiasTranslate
&& !this.canvas.__rgraph_aa_translated__) {
this.context.translate(0.5,0.5); this.context.translate(0.5,0.5);
this.canvas.__rgraph_aa_translated__ = true; this.canvas.__rgraph_aa_translated__ = true;
@ -324,22 +385,23 @@
if (!obj.alignmentProcessed) { if (!obj.alignmentProcessed) {
var customWidthHeight = (typeof obj.properties.width == 'number' && typeof obj.properties.width == 'number'); var customWidthHeight = (RGraph.isNumber(obj.properties.width) && RGraph.isNumber(obj.properties.width));
// Horizontal alignment // Horizontal alignment
if (obj.properties.halign === 'center') { if (obj.properties.halign === 'center') {
obj.x -= customWidthHeight ? (obj.properties.width / 2) : (this.width / 2); obj.x = obj.x - (customWidthHeight ? (obj.properties.width / 2) : (this.width / 2));
} else if (obj.properties.halign == 'right') { } else if (obj.properties.halign == 'right') {
obj.x -= customWidthHeight ? obj.properties.width : this.width; obj.x = obj.x - (customWidthHeight ? obj.properties.width : this.width);
} }
// Vertical alignment // Vertical alignment
if (obj.properties.valign === 'center') { if (obj.properties.valign === 'center') {
obj.y -= customWidthHeight ? (obj.properties.height / 2) : (this.height / 2); obj.y = obj.y - (customWidthHeight ? (obj.properties.height / 2) : (this.height / 2));
} else if (obj.properties.valign == 'bottom') { } else if (obj.properties.valign === 'bottom') {
obj.y -= customWidthHeight ? obj.properties.height : this.height; obj.y = obj.y - (customWidthHeight ? obj.properties.height : this.height);
} }
// Don't do this again // Don't do this again
obj.alignmentProcessed = true; obj.alignmentProcessed = true;
} }
@ -382,6 +444,7 @@
// //
// Draw a border around the image // Draw a border around the image
// //
/// !!!!!!
if (properties.border) { if (properties.border) {
this.context.strokeStyle = properties.borderColor; this.context.strokeStyle = properties.borderColor;
@ -409,12 +472,12 @@
this.roundedRect( this.roundedRect(
Math.round(this.x) - Math.round(this.context.lineWidth / 2), Math.round(this.x) - Math.round(this.context.lineWidth / 2),
Math.round(this.y) - Math.round(this.context.lineWidth / 2), Math.round(this.y) - Math.round(this.context.lineWidth / 2),
(properties.width || this.img.width) + this.context.lineWidth, (((properties.width)|| this.img.width)) + this.context.lineWidth,
(properties.height || this.img.height) + this.context.lineWidth, (((properties.height)|| this.img.height)) + this.context.lineWidth,
borderRadius borderRadius
); );
} }
this.context.stroke();
if (borderRadius) { if (borderRadius) {
@ -432,8 +495,8 @@
this.roundedRect( this.roundedRect(
Math.round(this.x) - Math.round(this.context.lineWidth / 2), Math.round(this.x) - Math.round(this.context.lineWidth / 2),
Math.round(this.y) - Math.round(this.context.lineWidth / 2), Math.round(this.y) - Math.round(this.context.lineWidth / 2),
(properties.width || this.img.width) + this.context.lineWidth, (((properties.width) || this.img.width)) + this.context.lineWidth,
(properties.height || this.img.height) + this.context.lineWidth, (((properties.height) || this.img.height)) + this.context.lineWidth,
borderRadius borderRadius
); );
this.context.clip(); this.context.clip();
@ -446,25 +509,37 @@
if (typeof properties.height === 'number' || typeof properties.width === 'number') { if (typeof properties.height === 'number' || typeof properties.width === 'number') {
this.context.drawImage( this.context.drawImage(
this.img, this.img,
Math.round(this.x), Math.round(this.x),
Math.round(this.y), Math.round(this.y),
properties.width || this.width, (properties.width || this.width),
properties.height || this.height (properties.height || this.height)
); );
} else { } else {
// Add the image to the document so that the
// width/height can be ascertained
document.body.appendChild(this.img);
this.img.style.position = 'absolute';
this.img.style.top = '-1000px';
this.img.style.left = '-1000px';
this.context.drawImage( this.context.drawImage(
this.img, this.img,
Math.round(this.x), Math.round(this.x),
Math.round(this.y) Math.round(this.y),
this.img.offsetWidth,
this.img.offsetHeight
); );
} }
// If borderRadius is enabled restore the canvas to it's pre-clipped state // If borderRadius is enabled restore the canvas to it's
// pre-clipped state
if (borderRadius) { if (borderRadius) {
this.context.restore(); this.context.restore();
} }
@ -657,10 +732,20 @@
if (typeof properties.highlightStyle === 'function') { if (typeof properties.highlightStyle === 'function') {
(properties.highlightStyle)(shape); (properties.highlightStyle)(shape);
} else { } else {
this.path('b');
this.roundedRect(
this.coords[0][0],
this.coords[0][1],
this.coords[0][2],
this.coords[0][3],
this.properties.borderRadius
);
this.path( this.path(
'b r % % % % f % s %', 'f % s %',
this.coords[0][0],this.coords[0][1],this.coords[0][2],this.coords[0][3], properties.highlightFill,
properties.highlightFill, properties.highlightStroke properties.highlightStroke
); );
} }
} }
@ -838,13 +923,17 @@
// //
this.drawBackgroundColor = function (borderRadius) this.drawBackgroundColor = function (borderRadius)
{ {
var scaleFactor = RGraph.getScaleFactor(this);
this.context.beginPath(); this.context.beginPath();
this.context.fillStyle = properties.backgroundColor; this.context.strokeStyle = 'transparent';
this.context.fillStyle = properties.backgroundColor;
this.roundedRect( this.roundedRect(
Math.round(this.x) - Math.round(this.context.lineWidth / 2), Math.round(this.x) - Math.round(this.context.lineWidth / 2),
Math.round(this.y) - Math.round(this.context.lineWidth / 2), Math.round(this.y) - Math.round(this.context.lineWidth / 2),
(properties.width || this.img.width) + this.context.lineWidth, (((properties.width) || this.img.width)) + this.context.lineWidth,
(properties.height || this.img.height) + this.context.lineWidth, (((properties.height) || this.img.height)) + this.context.lineWidth,
borderRadius borderRadius
); );
this.context.fill(); this.context.fill();
@ -886,24 +975,46 @@
e = args.event, e = args.event,
tooltip = args.tooltip, tooltip = args.tooltip,
index = args.index, index = args.index,
canvasXY = RGraph.getCanvasXY(obj.canvas); canvasXY = RGraph.getCanvasXY(obj.canvas),
scaleFactor = RGraph.getScaleFactor(obj);
// Position the tooltip in the X direction // Position the tooltip in the X direction
args.tooltip.style.left = ( if (scaleFactor === 1) {
canvasXY[0] // The X coordinate of the canvas args.tooltip.style.left = (
+ this.x // The X coordinate of the image canvasXY[0] // The X coordinate of the canvas
+ ((properties.width || this.img.width) / 2) // Add half of the image width + this.x // The X coordinate of the image
- (tooltip.offsetWidth / 2) // Subtract half of the tooltip width + ((properties.width || this.img.width) / 2) // Add half of the image width
+ obj.properties.tooltipsOffsetx // Add any user defined offset - (tooltip.offsetWidth / 2) // Subtract half of the tooltip width
) + 'px'; + obj.properties.tooltipsOffsetx // Add any user defined offset
) + 'px';
} else {
args.tooltip.style.left = (
canvasXY[0] // The X coordinate of the canvas
+ (this.x / scaleFactor) // The X coordinate of the image
+ ((properties.width || this.img.width) / 4) // Add half of the image width
- (tooltip.offsetWidth / 2) // Subtract half of the tooltip width
+ obj.properties.tooltipsOffsetx // Add any user defined offset
) + 'px';
}
args.tooltip.style.top = ( // Positon the tooltip in the vertical direction
canvasXY[1] // The Y coordinate of the canvas if (scaleFactor === 1) {
- tooltip.offsetHeight // The height of the tooltip args.tooltip.style.top = (
+ obj.properties.tooltipsOffsety // Add any user defined offset canvasXY[1] // The Y coordinate of the canvas
+ this.y // Add the Y coordinate - tooltip.offsetHeight // The height of the tooltip
- 10 // An arbitrary amount + obj.properties.tooltipsOffsety // Add any user defined offset
) + 'px'; + this.y // Add the Y coordinate
- (12 - properties.borderLinewidth) // An arbitrary amount
) + 'px';
} else {
args.tooltip.style.top = (
canvasXY[1] // The Y coordinate of the canvas
- tooltip.offsetHeight // The height of the tooltip
+ obj.properties.tooltipsOffsety // Add any user defined offset
+ (this.y / scaleFactor) // Add the Y coordinate
- ((7 * scaleFactor) - properties.borderLinewidth) // An arbitrary amount
) + 'px';
}
}; };

View File

@ -1,4 +1,4 @@
'version:2024-12-01 (6.20)'; 'version:2025-10-08 (7.01)';
// //
// 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: |
@ -168,12 +168,12 @@
colorsRedStart: 0.9 * this.max, colorsRedStart: 0.9 * this.max,
colorsRedColor: '#DC3912', colorsRedColor: '#DC3912',
colorsRedWidth: 10, colorsRedWidth: 5,
colorsYellowColor: '#FF9900', colorsYellowColor: '#FF9900',
colorsYellowWidth: 10, colorsYellowWidth: 5,
colorsGreenEnd: 0.7 * this.max, colorsGreenEnd: 0.7 * this.max,
colorsGreenColor: 'rgba(0,0,0,0)', colorsGreenColor: 'rgba(0,0,0,0)',
colorsGreenWidth: 10, colorsGreenWidth: 5,
colorsRanges: null, colorsRanges: null,
needleSize: null, needleSize: null,
@ -209,8 +209,80 @@
shadowOffsety: 0, shadowOffsety: 0,
shadowBlur: 15, shadowBlur: 15,
clearto: 'rgba(0,0,0,0)' clearto: 'rgba(0,0,0,0)',
}
events: {},
scale: true,
scaleFactor: 2,
antialiasTranslate: false
};
//
// These are the properties that get scaled up if the
// scale option is enabled.
//
this.properties_scale = [
'centerx',
'centery',
'radius',
'marginLeft',
'marginRight',
'marginTop',
'marginBottom',
'borderWidth',
'textSize',
'titleTopSize',
'titleTopOffsetx',
'titleTopOffsety',
'titleTopSubtitleSize',
'titleTopSubtitleOffsetx',
'titleTopSubtitleOffsety',
'titleBottomSize',
'titleBottomOffsetx',
'titleBottomOffsety',
'labelsOffsetRadius',
'labelsOffsetx',
'labelsOffsety',
'labelsSize',
'labelsValueSize',
'colorsRedWidth',
'colorsYellowWidth',
'colorsGreenWidth',
'needleSize',
'needleWidth',
'centerpinRadius',
'annotatableLinewidth',
'shadowOffsetx',
'shadowOffsety',
'shadowBlur'
];
// //
@ -332,6 +404,23 @@
// //
this.draw = function () this.draw = function ()
{ {
// MUST be the first thing that's done - but only
// once!!
RGraph.runOnce(`scale-up-the-canvas-once-in-the-draw-function-${this.id}-${this.uid}`, () =>
{
// Note that we're in an arrow function so the
// 'this' variable is OK to be used and refers
// to the RGraph Line chart object.
RGraph.scale(this);
});
// //
// Fire the onbeforedraw event // Fire the onbeforedraw event
// //
@ -342,12 +431,15 @@
// Translate half a pixel for antialiasing purposes - but only if it hasn't been // Translate half a pixel for antialiasing purposes - but
// done already // only if it hasn't been done already
// //
// MUST be the first thing done! // The old style antialias fix
// //
if (!this.canvas.__rgraph_aa_translated__) { if ( !this.properties.scale
&& this.properties.antialiasTranslate
&& !this.canvas.__rgraph_aa_translated__) {
this.context.translate(0.5,0.5); this.context.translate(0.5,0.5);
this.canvas.__rgraph_aa_translated__ = true; this.canvas.__rgraph_aa_translated__ = true;
@ -395,9 +487,11 @@
// //
// Allow the centerx/centery/radius to be a plus/minus // Allow the centerx/centery/radius to be a plus/minus
// //
if (typeof properties.radius === 'string' && properties.radius.match(/^\+|-\d+$/) ) this.radius += parseFloat(properties.radius); var scaleFactor = RGraph.getScaleFactor(this);
if (typeof properties.centerx === 'string' && properties.centerx.match(/^\+|-\d+$/) ) this.centerx += parseFloat(properties.centerx);
if (typeof properties.centery === 'string' && properties.centery.match(/^\+|-\d+$/) ) this.centery += parseFloat(properties.centery); if (typeof properties.radius === 'string' && properties.radius.match(/^\+|-\d+$/) ) this.radius += parseFloat(properties.radius) * scaleFactor;
if (typeof properties.centerx === 'string' && properties.centerx.match(/^\+|-\d+$/) ) this.centerx += parseFloat(properties.centerx) * scaleFactor;
if (typeof properties.centery === 'string' && properties.centery.match(/^\+|-\d+$/) ) this.centery += parseFloat(properties.centery) * scaleFactor;
// //
// Parse the colors. This allows for simple gradient syntax // Parse the colors. This allows for simple gradient syntax
@ -580,6 +674,8 @@
// //
this.drawBackGround = function () this.drawBackGround = function ()
{ {
var scaleFactor = RGraph.getScaleFactor(this);
// Shadow ////////////////////////////////////////////// // Shadow //////////////////////////////////////////////
if (properties.shadow) { if (properties.shadow) {
RGraph.setShadow( RGraph.setShadow(
@ -626,7 +722,14 @@
// //
this.context.beginPath(); this.context.beginPath();
this.context.fillStyle = properties.borderInner; this.context.fillStyle = properties.borderInner;
this.context.arc(this.centerx, this.centery, this.radius - borderWidth, 0, RGraph.TWOPI, 0); this.context.arc(
this.centerx,
this.centery,
this.radius - borderWidth,
0,
RGraph.TWOPI,
0
);
this.context.fill(); this.context.fill();
@ -671,7 +774,15 @@
// Draw a black border around the chart // Draw a black border around the chart
this.context.beginPath(); this.context.beginPath();
this.context.strokeStyle = properties.borderOutline; this.context.strokeStyle = properties.borderOutline;
this.context.arc(this.centerx, this.centery, this.radius, 0, RGraph.TWOPI, 0); this.context.lineWidth = 1 * scaleFactor;
this.context.arc(
this.centerx,
this.centery,
this.radius,
0,
RGraph.TWOPI,
0
);
this.context.stroke(); this.context.stroke();
}; };
@ -687,15 +798,31 @@
// //
this.drawSmallTickmarks = function () this.drawSmallTickmarks = function ()
{ {
var numTicks = properties.tickmarksSmall; var numTicks = properties.tickmarksSmall;
var scaleFactor = RGraph.getScaleFactor(this);
this.context.lineWidth = 1; this.context.lineWidth = 1;
for (var i=0; i<=numTicks; ++i) { for (var i=0; i<=numTicks; ++i) {
this.context.beginPath(); this.context.beginPath();
this.context.strokeStyle = properties.tickmarksSmallColor; this.context.strokeStyle = properties.tickmarksSmallColor;
var a = (((this.endAngle - this.startAngle) / numTicks) * i) + this.startAngle; var a = (((this.endAngle - this.startAngle) / numTicks) * i) + this.startAngle;
this.context.arc(this.centerx, this.centery, this.radius - properties.borderWidth - 10, a, a + 0.00001, 0); this.context.arc(
this.context.arc(this.centerx, this.centery, this.radius - properties.borderWidth - 10 - 5, a, a + 0.00001, 0); this.centerx,
this.centery,
this.radius - properties.borderWidth - (10 * scaleFactor),
a,
a + 0.00001,
0
);
this.context.arc(
this.centerx,
this.centery,
this.radius - properties.borderWidth - (10 * scaleFactor) - (5 * scaleFactor),
a,
a + 0.00001,
0
);
this.context.stroke(); this.context.stroke();
} }
}; };
@ -714,7 +841,9 @@
{ {
if (properties.tickmarksMedium) { if (properties.tickmarksMedium) {
var numTicks = properties.tickmarksMedium; var numTicks = properties.tickmarksMedium;
var scaleFactor = RGraph.getScaleFactor(this);
this.context.lineWidth = 3; this.context.lineWidth = 3;
this.context.lineCap = 'round'; this.context.lineCap = 'round';
this.context.strokeStyle = properties.tickmarksMediumColor; this.context.strokeStyle = properties.tickmarksMediumColor;
@ -724,8 +853,22 @@
var a = (((this.endAngle - this.startAngle) / numTicks) * i) + this.startAngle + (((this.endAngle - this.startAngle) / (2 * numTicks))); var a = (((this.endAngle - this.startAngle) / numTicks) * i) + this.startAngle + (((this.endAngle - this.startAngle) / (2 * numTicks)));
if (a > this.startAngle && a< this.endAngle) { if (a > this.startAngle && a< this.endAngle) {
this.context.arc(this.centerx, this.centery, this.radius - properties.borderWidth - 10, a, a + 0.00001, 0); this.context.arc(
this.context.arc(this.centerx, this.centery, this.radius - properties.borderWidth - 10 - 6, a, a + 0.00001, 0); this.centerx,
this.centery,
this.radius - properties.borderWidth - (10 * scaleFactor),
a,
a + 0.00001,
0
);
this.context.arc(
this.centerx,
this.centery,
this.radius - properties.borderWidth - (10 * scaleFactor) - (6 * scaleFactor),
a,
a + 0.00001,
0
);
} }
this.context.stroke(); this.context.stroke();
} }
@ -744,17 +887,32 @@
// //
this.drawLargeTickmarks = function () this.drawLargeTickmarks = function ()
{ {
var numTicks = properties.tickmarksLarge; var numTicks = properties.tickmarksLarge;
var scaleFactor = RGraph.getScaleFactor(this);
this.context.lineWidth = 3; this.context.lineWidth = 3 * scaleFactor;
this.context.lineCap = 'round'; this.context.lineCap = 'round';
for (var i=0; i<=numTicks; ++i) { for (var i=0; i<=numTicks; ++i) {
this.context.beginPath(); this.context.beginPath();
this.context.strokeStyle = properties.tickmarksLargeColor; this.context.strokeStyle = properties.tickmarksLargeColor;
var a = (((this.endAngle - this.startAngle) / numTicks) * i) + this.startAngle; var a = (((this.endAngle - this.startAngle) / numTicks) * i) + this.startAngle;
this.context.arc(this.centerx, this.centery, this.radius - properties.borderWidth - 10, a, a + 0.00001, 0); this.context.arc(
this.context.arc(this.centerx, this.centery, this.radius - properties.borderWidth - 10 - 10, a, a + 0.00001, 0); this.centerx,
this.centery,
this.radius - properties.borderWidth - (10 * scaleFactor),
a,
a + 0.00001,
0
);
this.context.arc(
this.centerx,
this.centery,
this.radius - properties.borderWidth - (10 * scaleFactor) - (10 * scaleFactor),
a,
a + 0.00001,
0
);
this.context.stroke(); this.context.stroke();
} }
}; };
@ -771,15 +929,31 @@
// //
this.drawCenterpin = function () this.drawCenterpin = function ()
{ {
var offset = 6; var scaleFactor = RGraph.getScaleFactor(this);
var grad = this.context.createRadialGradient(this.centerx + offset, this.centery - offset, 0, this.centerx + offset, this.centery - offset, 25); var offset = (6 * scaleFactor);
var grad = this.context.createRadialGradient(
this.centerx + offset,
this.centery - offset,
0,
this.centerx + offset,
this.centery - offset,
(25 * scaleFactor)
);
grad.addColorStop(0, '#ddf'); grad.addColorStop(0, '#ddf');
grad.addColorStop(1, properties.centerpinColor); grad.addColorStop(1, properties.centerpinColor);
this.context.beginPath(); this.context.beginPath();
this.context.fillStyle = grad; this.context.fillStyle = grad;
this.context.arc(this.centerx, this.centery, this.centerpinRadius, 0, RGraph.TWOPI, 0); this.context.arc(
this.centerx,
this.centery,
this.centerpinRadius,
0,
RGraph.TWOPI,
0
);
this.context.fill(); this.context.fill();
}; };
@ -853,10 +1027,13 @@
var scaleFactor = RGraph.getScaleFactor(this);
this.context.beginPath(); this.context.beginPath();
if (num) { if (num) {
for (var i=0; i<=num; ++i) { for (var i=0; i<=num; ++i) {
var hyp = (this.radius - 25 - properties.borderWidth) - properties.labelsOffsetRadius; var hyp = (this.radius - (25 * scaleFactor) - properties.borderWidth) - properties.labelsOffsetRadius;
var a = (this.endAngle - this.startAngle) / num var a = (this.endAngle - this.startAngle) / num
a = this.startAngle + (i * a); a = this.startAngle + (i * a);
a -= RGraph.HALFPI; a -= RGraph.HALFPI;
@ -1016,8 +1193,10 @@
// //
this.drawTopTitle = function () this.drawTopTitle = function ()
{ {
var scaleFactor = RGraph.getScaleFactor(this);
var x = this.centerx; var x = this.centerx;
var y = this.centery - 25; var y = this.centery - (25 * scaleFactor);
if (typeof properties.titleTopSubtitle === 'string') { if (typeof properties.titleTopSubtitle === 'string') {
y -= 20. y -= 20.
@ -1120,8 +1299,10 @@
// //
this.drawBottomTitle = function () this.drawBottomTitle = function ()
{ {
var scaleFactor = RGraph.getScaleFactor(this);
var x = this.centerx; var x = this.centerx;
var y = this.centery + this.centerpinRadius + 10; var y = this.centery + this.centerpinRadius + (10 * scaleFactor);
// Totally override the calculated positioning // Totally override the calculated positioning
if (typeof properties.titleBottomPos == 'number') { if (typeof properties.titleBottomPos == 'number') {
@ -1259,6 +1440,8 @@
// //
this.drawColorBands = function () this.drawColorBands = function ()
{ {
var scaleFactor = RGraph.getScaleFactor(this);
if (RGraph.isArray(properties.colorsRanges)) { if (RGraph.isArray(properties.colorsRanges)) {
var ranges = properties.colorsRanges; var ranges = properties.colorsRanges;
@ -1272,7 +1455,7 @@
this.context.arc( this.context.arc(
this.centerx, this.centerx,
this.centery, this.centery,
this.radius - 10 - properties.borderWidth, this.radius - (10 * scaleFactor) - properties.borderWidth,
(((ranges[i][0] - this.min) / (this.max - this.min)) * (this.endAngle - this.startAngle)) + this.startAngle, (((ranges[i][0] - this.min) / (this.max - this.min)) * (this.endAngle - this.startAngle)) + this.startAngle,
(((ranges[i][1] - this.min) / (this.max - this.min)) * (this.endAngle - this.startAngle)) + this.startAngle, (((ranges[i][1] - this.min) / (this.max - this.min)) * (this.endAngle - this.startAngle)) + this.startAngle,
false false
@ -1281,7 +1464,7 @@
this.context.arc( this.context.arc(
this.centerx, this.centerx,
this.centery, this.centery,
this.radius - 10 - properties.borderWidth - (typeof ranges[i][3] === 'number' ? ranges[i][3] : 10), this.radius - (10 * scaleFactor) - properties.borderWidth - (typeof ranges[i][3] === 'number' ? ranges[i][3] : (10 * scaleFactor)),
(((ranges[i][1] - this.min) / (this.max - this.min)) * (this.endAngle - this.startAngle)) + this.startAngle, (((ranges[i][1] - this.min) / (this.max - this.min)) * (this.endAngle - this.startAngle)) + this.startAngle,
(((ranges[i][0] - this.min) / (this.max - this.min)) * (this.endAngle - this.startAngle)) + this.startAngle, (((ranges[i][0] - this.min) / (this.max - this.min)) * (this.endAngle - this.startAngle)) + this.startAngle,
true true
@ -1297,14 +1480,29 @@
// Draw the GREEN region // Draw the GREEN region
// //
this.context.strokeStyle = properties.colorsGreenColor; this.context.strokeStyle = properties.colorsGreenColor;
this.context.fillStyle = properties.colorsGreenColor; this.context.fillStyle = properties.colorsGreenColor;
var greenStart = this.startAngle; var greenStart = this.startAngle;
var greenEnd = this.startAngle + (this.endAngle - this.startAngle) * ((properties.colorsGreenEnd - this.min) / (this.max - this.min)) var greenEnd = this.startAngle + (this.endAngle - this.startAngle) * ((properties.colorsGreenEnd - this.min) / (this.max - this.min))
var greenOuterRadius = this.radius - (10 * scaleFactor) - properties.borderWidth;
this.context.beginPath(); this.context.beginPath();
this.context.arc(this.centerx, this.centery, this.radius - 10 - properties.borderWidth, greenStart, greenEnd, false); this.context.arc(
this.context.arc(this.centerx, this.centery, this.radius - (10 + properties.colorsGreenWidth) - properties.borderWidth, greenEnd, greenStart, true); this.centerx,
this.centery,
greenOuterRadius,
greenStart,
greenEnd,
false
);
this.context.arc(
this.centerx,
this.centery,
greenOuterRadius - (this.properties.colorsGreenWidth * 2),
greenEnd,
greenStart,
true
);
this.context.fill(); this.context.fill();
@ -1317,12 +1515,20 @@
this.context.strokeStyle = properties.colorsYellowColor; this.context.strokeStyle = properties.colorsYellowColor;
this.context.fillStyle = properties.colorsYellowColor; this.context.fillStyle = properties.colorsYellowColor;
var yellowStart = greenEnd; var yellowStart = greenEnd;
var yellowEnd = this.startAngle + (this.endAngle - this.startAngle) * ((properties.colorsRedStart - this.min) / (this.max - this.min)) var yellowEnd = this.startAngle + (this.endAngle - this.startAngle) * ((properties.colorsRedStart - this.min) / (this.max - this.min))
var yellowOuterRadius = this.radius - (10 * scaleFactor) - properties.borderWidth;
this.context.beginPath(); this.context.beginPath();
this.context.arc(this.centerx, this.centery, this.radius - 10 - properties.borderWidth, yellowStart, yellowEnd, false); this.context.arc(this.centerx, this.centery, yellowOuterRadius, yellowStart, yellowEnd, false);
this.context.arc(this.centerx, this.centery, this.radius - (10 + properties.colorsYellowWidth) - properties.borderWidth, yellowEnd, yellowStart, true); this.context.arc(
this.centerx,
this.centery,
yellowOuterRadius - (this.properties.colorsYellowWidth * 2),
yellowEnd,
yellowStart,
true
);
this.context.fill(); this.context.fill();
@ -1335,12 +1541,20 @@
this.context.strokeStyle = properties.colorsRedColor; this.context.strokeStyle = properties.colorsRedColor;
this.context.fillStyle = properties.colorsRedColor; this.context.fillStyle = properties.colorsRedColor;
var redStart = yellowEnd; var redStart = yellowEnd;
var redEnd = this.startAngle + (this.endAngle - this.startAngle) * ((this.max - this.min) / (this.max - this.min)) var redEnd = this.startAngle + (this.endAngle - this.startAngle) * ((this.max - this.min) / (this.max - this.min))
var redOuterRadius = this.radius - (10 * scaleFactor) - properties.borderWidth;
this.context.beginPath(); this.context.beginPath();
this.context.arc(this.centerx, this.centery, this.radius - 10 - properties.borderWidth, redStart, redEnd, false); this.context.arc(this.centerx, this.centery, redOuterRadius, redStart, redEnd, false);
this.context.arc(this.centerx, this.centery, this.radius - (10 + properties.colorsRedWidth) - properties.borderWidth, redEnd, redStart, true); this.context.arc(
this.centerx,
this.centery,
yellowOuterRadius - (this.properties.colorsRedWidth * 2),
redEnd,
redStart,
true
);
this.context.fill(); this.context.fill();
}; };
@ -1880,6 +2094,35 @@
//
// Scale worker function that increases the size of
// properties as required. Called by the RGraph.scale()
// function.
//
// @param string name The name of the property
// @param mixed value The value of the property
//
this.scalePropertiesWorker = function (name, value)
{
var scaleFactor = RGraph.getScaleFactor(this);
if (name === 'titleY') {
value = String(parseFloat(value) * scaleFactor);
} else if (name === 'titleX') {
value = String(parseFloat(value) * scaleFactor);
}
return value;
};
// //
// Register the object // Register the object
// //

View File

@ -1,4 +1,4 @@
'version:2024-12-01 (6.20)'; 'version:2025-10-08 (7.01)';
// //
// 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: |
@ -76,6 +76,7 @@
labelsValueOffsetx: 0, labelsValueOffsetx: 0,
labelsValueOffsety: 0, labelsValueOffsety: 0,
needleExtra: [],
needleColor: 'black', needleColor: 'black',
needleLength: null, needleLength: null,
needleWidth: 2, needleWidth: 2,
@ -95,10 +96,10 @@
text: null, text: null,
colorsGreenMax: max * 0.75, colorsGreenMax: max * 0.75,
colorsGreenColor: 'Gradient(white:#0c0)', colorsGreenColor: '#0c0',
colorsYellowColor: 'Gradient(white:#ff0)', colorsYellowColor: '#cc0',
colorsRedMin: max * 0.9, colorsRedMin: max * 0.9,
colorsRedColor: 'Gradient(white:#f00)', colorsRedColor: '#c00',
marginLeft: 35, marginLeft: 35,
marginRight: 35, marginRight: 35,
@ -107,7 +108,7 @@
title: '', title: '',
titleFont: null, titleFont: null,
titleBold: null, titleBold: true,
titleItalic: null, titleItalic: null,
titleSize: null, titleSize: null,
titleColor: null, titleColor: null,
@ -151,10 +152,6 @@
scaleUnitsPost: '', scaleUnitsPost: '',
scaleZerostart: false, scaleZerostart: false,
resizable: false,
resizableHandleAdjust: [0,0],
resizableHandleBackground: null,
border: true, border: true,
borderColor1: '#BEBCB0', borderColor1: '#BEBCB0',
borderColor2: '#F0EFEA', borderColor2: '#F0EFEA',
@ -199,8 +196,69 @@
adjustable: false, adjustable: false,
clearto: 'rgba(0,0,0,0)' clearto: 'rgba(0,0,0,0)',
}
events: {},
scale: true,
scaleFactor: 2,
antialiasTranslate: false
};
this.properties_scale = [
'centerx',
'centery',
'radius',
'labelsMargin',
'labelsSize',
'labelsValueSize',
'labelsValueOffsetx',
'labelsValueOffsety',
'needleWidth',
'needleLength',
'textSize',
'marginLeft',
'marginRight',
'marginTop',
'marginBottom',
'titleSize',
'titleX',
'titleY',
'titleOffsetx',
'titleOffsety',
'titleSubtitleSize',
'titleSubtitleOffsetx',
'titleSubtitleOffsety',
'linewidth',
'shadowInnerOffsetx',
'shadowInnerOffsety',
'shadowInnerBlur',
'shadowOuterOffsetx',
'shadowOuterOffsety',
'shadowOuterBlur',
'keyShadowBlur',
'keyShadowOffsetx',
'keyShadowOffsety',
'keyPositionMarginHSpace',
'keyPositionX',
'keyPositionY',
'keyLabelsSize',
'keyLabelsOffsetx',
'keyLabelsOffsety',
'annotatableLinewidth'
];
// //
@ -307,6 +365,19 @@
// //
this.draw = function () this.draw = function ()
{ {
// MUST be the first thing that's done - but only
// once!!
RGraph.runOnce(`scale-up-the-canvas-once-in-the-draw-function-${this.id}-${this.uid}`, () =>
{
// Note that we're in an arrow function so the
// 'this' variable is OK to be used and refers
// to the RGraph Line chart object.
RGraph.scale(this);
});
var scaleFactor = RGraph.getScaleFactor(this);
// //
// Fire the onbeforedraw event // Fire the onbeforedraw event
// //
@ -314,12 +385,15 @@
// Translate half a pixel for antialiasing purposes - but only if it hasn't been // Translate half a pixel for antialiasing purposes - but
// done already // only if it hasn't been done already
// //
// MUST be the first thing done! // The old style antialias fix
// //
if (!this.canvas.__rgraph_aa_translated__) { if ( !this.properties.scale
&& this.properties.antialiasTranslate
&& !this.canvas.__rgraph_aa_translated__) {
this.context.translate(0.5,0.5); this.context.translate(0.5,0.5);
this.canvas.__rgraph_aa_translated__ = true; this.canvas.__rgraph_aa_translated__ = true;
@ -374,9 +448,11 @@
// //
// Allow the centerx/centery/radius to be a plus/minus // Allow the centerx/centery/radius to be a plus/minus
// //
if (typeof properties.radius === 'string' && properties.radius.match(/^\+|-\d+$/) ) this.radius += parseFloat(properties.radius); var scaleFactor = RGraph.getScaleFactor(this);
if (typeof properties.centerx === 'string' && properties.centerx.match(/^\+|-\d+$/) ) this.centerx += parseFloat(properties.centerx);
if (typeof properties.centery === 'string' && properties.centery.match(/^\+|-\d+$/) ) this.centery += parseFloat(properties.centery); if (typeof properties.radius === 'string' && properties.radius.match(/^\+|-\d+$/) ) this.radius += parseFloat(properties.radius) * scaleFactor;
if (typeof properties.centerx === 'string' && properties.centerx.match(/^\+|-\d+$/) ) this.centerx += parseFloat(properties.centerx) * scaleFactor;
if (typeof properties.centery === 'string' && properties.centery.match(/^\+|-\d+$/) ) this.centery += parseFloat(properties.centery) * scaleFactor;
// //
// Allow custom setting of the radius // Allow custom setting of the radius
@ -588,6 +664,8 @@
// //
this.drawBackground = function () this.drawBackground = function ()
{ {
var scaleFactor = RGraph.getScaleFactor(this);
this.context.beginPath(); this.context.beginPath();
// //
@ -610,7 +688,7 @@
this.context.arc( this.context.arc(
this.centerx, this.centerx,
this.centery, this.centery,
this.radius + (properties.border ? 20 : 0), this.radius + (properties.border ? (20 * scaleFactor) : 0),
0.0001, 0.0001,
RGraph.TWOPI, RGraph.TWOPI,
false false
@ -625,10 +703,17 @@
// Draw a circle // Draw a circle
this.context.strokeStyle = '#666'; this.context.strokeStyle = '#666';
this.context.arc(this.centerx, this.centery, this.radius, 0, RGraph.TWOPI, false); this.context.arc(
this.centerx,
this.centery,
this.radius,
0,
RGraph.TWOPI,
false
);
// Now draw a big white circle to make the lines appear as tick marks // Now draw a big white circle to make the lines appear
// This is solely for Chrome // as tick marks. This is solely for Chrome.
this.context.fillStyle = backgroundColor; this.context.fillStyle = backgroundColor;
this.context.arc(this.centerx, this.centery, this.radius, 0, RGraph.TWOPI, false); this.context.arc(this.centerx, this.centery, this.radius, 0, RGraph.TWOPI, false);
this.context.fill(); this.context.fill();
@ -703,7 +788,7 @@
// Draw the "tick highlight" // Draw the "tick highlight"
if (properties.tickmarksHighlighted) { if (properties.tickmarksHighlighted) {
this.context.beginPath(); this.context.beginPath();
this.context.lineWidth = 5; this.context.lineWidth = 5 * scaleFactor;
this.context.strokeStyle = greengrad; this.context.strokeStyle = greengrad;
this.context.arc(this.centerx, this.centery, this.radius - 2.5, this.context.arc(this.centerx, this.centery, this.radius - 2.5,
@ -739,7 +824,7 @@
// Draw the "tick highlight" // Draw the "tick highlight"
if (properties.tickmarksHighlighted) { if (properties.tickmarksHighlighted) {
this.context.beginPath(); this.context.beginPath();
this.context.lineWidth = 5; this.context.lineWidth = 5 * scaleFactor;
this.context.strokeStyle = yellowgrad; this.context.strokeStyle = yellowgrad;
this.context.arc(this.centerx, this.centery, this.radius - 2.5, ( this.context.arc(this.centerx, this.centery, this.radius - 2.5, (
@ -774,7 +859,7 @@
// Draw the "tick highlight" // Draw the "tick highlight"
if (properties.tickmarksHighlighted) { if (properties.tickmarksHighlighted) {
this.context.beginPath(); this.context.beginPath();
this.context.lineWidth = 5; this.context.lineWidth = 5 * scaleFactor;
this.context.strokeStyle = redgrad; this.context.strokeStyle = redgrad;
this.context.arc(this.centerx, this.centery, this.radius - 2.5,(((properties.colorsRedMin - this.min) / (this.max - this.min)) * RGraph.TWOPI) - RGraph.HALFPI,RGraph.TWOPI - RGraph.HALFPI,0); this.context.arc(this.centerx, this.centery, this.radius - 2.5,(((properties.colorsRedMin - this.min) / (this.max - this.min)) * RGraph.TWOPI) - RGraph.HALFPI,RGraph.TWOPI - RGraph.HALFPI,0);
this.context.stroke(); this.context.stroke();
@ -803,18 +888,38 @@
// //
if (properties.border) { if (properties.border) {
var grad = this.context.createRadialGradient(this.centerx, this.centery, this.radius, this.centerx, this.centery, this.radius + 20); var grad = this.context.createRadialGradient(
this.centerx,
this.centery,
this.radius,
this.centerx,
this.centery,
this.radius + (20 * scaleFactor)
);
grad.addColorStop(0, properties.borderColor1); grad.addColorStop(0, properties.borderColor1);
grad.addColorStop(0.5, properties.borderColor2); grad.addColorStop(0.5, properties.borderColor2);
grad.addColorStop(1, properties.borderColor3); grad.addColorStop(1, properties.borderColor3);
this.context.beginPath(); this.context.beginPath();
this.context.fillStyle = grad; this.context.fillStyle = grad;
this.context.strokeStyle = 'rgba(0,0,0,0)' this.context.strokeStyle = 'rgba(0,0,0,0)'
this.context.lineWidth = 0.001; this.context.lineWidth = 0.001;
this.context.arc(this.centerx, this.centery, this.radius + 20, 0, RGraph.TWOPI, 0); this.context.arc(
this.context.arc(this.centerx, this.centery, this.radius - 2, RGraph.TWOPI, 0, 1); this.centerx,
this.centery,
this.radius + (20 * scaleFactor),
0,
RGraph.TWOPI,
0
);
this.context.arc(
this.centerx,
this.centery,
this.radius - 2,
RGraph.TWOPI,
0,
1
);
this.context.fill(); this.context.fill();
} }
@ -865,6 +970,8 @@
// //
this.drawNeedle = function (opt) this.drawNeedle = function (opt)
{ {
var scaleFactor = RGraph.getScaleFactor(this);
// The optional length of the needle // The optional length of the needle
opt.length = opt.length ? opt.length : this.radius - properties.labelsMargin - 10; opt.length = opt.length ? opt.length : this.radius - properties.labelsMargin - 10;
@ -876,7 +983,7 @@
this.context.moveTo(this.centerx, this.centery); this.context.moveTo(this.centerx, this.centery);
this.context.arc( this.context.arc(
this.centerx, this.centery, this.centerx, this.centery,
10, 10 * scaleFactor,
0, RGraph.TWOPI, 0, RGraph.TWOPI,
false false
); );
@ -892,10 +999,19 @@
this.context.fillStyle = opt.color this.context.fillStyle = opt.color
this.context.strokeStyle = '#666'; this.context.strokeStyle = '#666';
// Draw the centre bit //
// Draw the black centrepin bit
//
this.context.beginPath(); this.context.beginPath();
this.context.moveTo(this.centerx, this.centery); this.context.moveTo(this.centerx, this.centery);
this.context.arc(this.centerx, this.centery, 8, 0, RGraph.TWOPI, false); this.context.arc(
this.centerx,
this.centery,
8 * scaleFactor,
0,
RGraph.TWOPI,
false
);
this.context.fill(); this.context.fill();
this.context.closePath(); this.context.closePath();
@ -912,7 +1028,8 @@
// Draw the needle // Draw the needle
this.context.beginPath(); this.context.beginPath();
// The trailing bit on the opposite side of the dial // The trailing bit on the opposite side of
// the dial.
this.context.beginPath(); this.context.beginPath();
this.context.moveTo( this.context.moveTo(
this.centerx, this.centerx,
@ -924,18 +1041,19 @@
this.context.arc( this.context.arc(
this.centerx, this.centerx,
this.centery, this.centery,
20, 20 * scaleFactor,
(opt.value / this.range) * RGraph.TWOPI + RGraph.HALFPI, (opt.value / this.range) * RGraph.TWOPI + RGraph.HALFPI,
(opt.value / this.range) * RGraph.TWOPI + RGraph.HALFPI, (opt.value / this.range) * RGraph.TWOPI + RGraph.HALFPI,
false false
); );
} }
// Draw the long bit on the opposite side // Draw the long bit on the opposite
// side
this.context.arc( this.context.arc(
this.centerx, this.centerx,
this.centery, this.centery,
opt.length - 20, opt.length - ((0.1 * opt.length) * scaleFactor),
(((opt.value / this.range) * 360) - 90) / (180 / RGraph.PI), (((opt.value / this.range) * 360) - 90) / (180 / RGraph.PI),
(((opt.value / this.range) * 360) - 90 + 0.1 ) / (180 / RGraph.PI), (((opt.value / this.range) * 360) - 90 + 0.1 ) / (180 / RGraph.PI),
false false
@ -953,12 +1071,13 @@
this.context.lineJoin = 'miter'; this.context.lineJoin = 'miter';
// //
// This draws the version of the pointer that becomes the border // This draws the version of the pointer that
// becomes the border.
// //
this.context.beginPath(); this.context.beginPath();
this.context.fillStyle = opt.triangleBorder; this.context.fillStyle = opt.triangleBorder;
this.context.arc(this.centerx, this.centery, 11, (((opt.value / this.range) * 360)) / 57.3, ((((opt.value / this.range) * 360)) + 0.01) / 57.3, 0); this.context.arc(this.centerx, this.centery, 11 * scaleFactor, (((opt.value / this.range) * 360)) / 57.3, ((((opt.value / this.range) * 360)) + 0.01) / 57.3, 0);
this.context.arc(this.centerx, this.centery, 11, (((opt.value / this.range) * 360) + 180) / 57.3, ((((opt.value / this.range) * 360) + 180) + 0.01)/ 57.3, 0); this.context.arc(this.centerx, this.centery, 11 * scaleFactor, (((opt.value / this.range) * 360) + 180) / 57.3, ((((opt.value / this.range) * 360) + 180) + 0.01)/ 57.3, 0);
this.context.arc(this.centerx, this.centery, opt.length - 5, (((opt.value / this.range) * 360) - 90) / 57.3, ((((opt.value / this.range) * 360) - 90) / 57.3) + 0.01, 0); this.context.arc(this.centerx, this.centery, opt.length - 5, (((opt.value / this.range) * 360) - 90) / 57.3, ((((opt.value / this.range) * 360) - 90) / 57.3) + 0.01, 0);
this.context.closePath(); this.context.closePath();
this.context.fill(); this.context.fill();
@ -981,14 +1100,14 @@
this.centerx, this.centerx,
this.centery, this.centery,
7, 7 * scaleFactor,
(((opt.value / this.range) * 360)) / 57.3, (((opt.value / this.range) * 360)) / 57.3,
((((opt.value / this.range) * 360)) + 0.01) / 57.3, ((((opt.value / this.range) * 360)) + 0.01) / 57.3,
this.centerx, this.centerx,
this.centery, this.centery,
7, 7 * scaleFactor,
(((opt.value / this.range) * 360) + 180) / 57.3, (((opt.value / this.range) * 360) + 180) / 57.3,
((((opt.value / this.range) * 360) + 180) + 0.01)/ 57.3 ((((opt.value / this.range) * 360) + 180) + 0.01)/ 57.3
); );
@ -1013,7 +1132,7 @@
this.context.arc( this.context.arc(
this.centerx, this.centerx,
this.centery, this.centery,
opt.type === 'pointer' ? 7 : 12, (opt.type === 'pointer' ? 7 : 12) * scaleFactor,
0.01, 0.01,
RGraph.TWOPI, RGraph.TWOPI,
false false
@ -1042,9 +1161,9 @@
this.context.arc( this.context.arc(
this.centerx, this.centerx,
this.centery, this.centery,
opt.length - 20, opt.length - ((opt.length * 0.1) * scaleFactor),
RGraph.toRadians( ((opt.value / this.range) * 360) - (opt.length < 60 ? 80 : 85) ), RGraph.toRadians( ((opt.value / this.range) * 360) - (this.radius > 300 ? (this.radius > 450 ? 87 : 85) : 82) ),
RGraph.toRadians( ((opt.value / this.range) * 360) - (opt.length < 60 ? 100 : 95) ), RGraph.toRadians( ((opt.value / this.range) * 360) - (this.radius > 300 ? (this.radius > 450 ? 93 : 95) : 97) ),
true true
); );
this.context.closePath(); this.context.closePath();
@ -1554,7 +1673,7 @@
} else { } else {
if (index === 0) { if (index === 0) {
return this.value; return this.value;
} else { } else if (RGraph.isArray(this.properties.needleExtra) && this.properties.needleExtra[index - 1]) {
return this.properties.needleExtra[index - 1][0]; return this.properties.needleExtra[index - 1][0];
} }
} }
@ -1656,6 +1775,43 @@
//
// Scale worker function that increases the size of
// properties as required. Called by the RGraph.scale()
// function.
//
// @param string name The name of the property
// @param mixed value The value of the property
//
this.scalePropertiesWorker = function (name, value)
{
var scaleFactor = RGraph.getScaleFactor(this);
if (name === 'titleY') {
value = String(parseFloat(value) * scaleFactor);
} else if (name === 'titleX') {
value = String(parseFloat(value) * scaleFactor);
} else if (name === 'needleLength' || name === 'needleWidth') {
for (var i=0; i<value.length; ++i) {
if (RGraph.isNumeric(value[i])) {
value[i] *= scaleFactor;
}
}
}
return value;
};
// //
// Register the object // Register the object
// //

View File

@ -1,4 +1,4 @@
'version:2024-12-01 (6.20)'; 'version:2025-10-08 (7.01)';
// //
// 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: |
@ -79,7 +79,7 @@
titleFont: null, titleFont: null,
titleSize: null, titleSize: null,
titleColor: null, titleColor: null,
titleBold: null, titleBold: true,
titleItalic: null, titleItalic: null,
titleHalign: null, titleHalign: null,
titleValign: null, titleValign: null,
@ -178,8 +178,95 @@
clearto: 'rgba(0,0,0,0)', clearto: 'rgba(0,0,0,0)',
bulbBottomRadiusAdjust: 0, bulbBottomRadiusAdjust: 0,
bulbBottomRadius: null bulbBottomRadius: null,
}
events: {},
scale: true,
scaleFactor: 2,
antialiasTranslate: false
};
//
// These are the properties that get scaled up if the
// scale option is enabled.
//
this.properties_scale = [
'linewidth',
'marginLeft',
'marginRight',
'marginTop',
'marginBottom',
'marginInner',
'shadowBlur',
'shadowOffsetx',
'shadowOffsety',
'titleSize',
'titleOffsetx',
'titleOffsety',
'titleSubtitleSize',
'titleSubtitleOffsetx',
'titleSubtitleOffsety',
'titleSideSize',
'titleSideOffsetx',
'titleSideOffsety',
'textSize',
'highlightLinewidth',
'labelsInnerSize',
'labelsInnerBorderLinewidth',
'labelsInnerOffsetx',
'labelsInnerOffsety',
'labelsOffsetx',
'labelsOffsety',
'labelsSize',
'labelsValueSize',
'labelsValueOffsetx',
'labelsValueOffsety',
'keyShadowBlur',
'keyShadowOffsetx',
'keyShadowOffsety',
'keyPositionX',
'keyPositionY',
'keyLinewidth',
'keyInteractiveHighlightChartLinewidth',
'keyLabelsSize',
'keyLabelsOffsetx',
'keyLabelsOffsety'
];
// //
@ -293,17 +380,42 @@
// //
this.draw = function () this.draw = function ()
{ {
// MUST be the first thing that's done - but only
// once!!
RGraph.runOnce(`scale-up-the-canvas-once-in-the-draw-function-${this.id}-${this.uid}`, () =>
{
// Note that we're in an arrow function so the
// 'this' variable is OK to be used and refers
// to the RGraph Line chart object.
RGraph.scale(this);
});
// Fire the custom RGraph onbeforedraw event (which should be fired before the chart is drawn) // Fire the custom RGraph onbeforedraw event (which should be fired before the chart is drawn)
RGraph.fireCustomEvent(this, 'onbeforedraw'); RGraph.fireCustomEvent(this, 'onbeforedraw');
// Translate half a pixel for antialiasing purposes - but only if it hasn't been // Translate half a pixel for antialiasing purposes - but
// done already // only if it hasn't been done already
// //
// MUST be the first thing done! // The old style antialias fix
// //
if (!this.canvas.__rgraph_aa_translated__) { if ( !this.properties.scale
&& this.properties.antialiasTranslate
&& !this.canvas.__rgraph_aa_translated__) {
this.context.translate(0.5,0.5); this.context.translate(0.5,0.5);
this.canvas.__rgraph_aa_translated__ = true; this.canvas.__rgraph_aa_translated__ = true;
@ -1434,27 +1546,28 @@
// //
this.positionTooltipStatic = function (args) this.positionTooltipStatic = function (args)
{ {
var obj = args.object, var obj = args.object,
e = args.event, e = args.event,
tooltip = args.tooltip, tooltip = args.tooltip,
index = args.index, index = args.index,
canvasXY = RGraph.getCanvasXY(obj.canvas) canvasXY = RGraph.getCanvasXY(obj.canvas)
coords = this.coords[args.index]; coords = this.coords[args.index],
scaleFactor = RGraph.getScaleFactor(this);
// Position the tooltip in the X direction // Position the tooltip in the X direction
args.tooltip.style.left = ( args.tooltip.style.left = (
canvasXY[0] // The X coordinate of the canvas canvasXY[0] // The X coordinate of the canvas
+ coords[0] // The X coordinate of the point on the chart + (coords[0]/ scaleFactor) // The X coordinate of the point on the chart
+ (coords[2] / 2) // Add half of the width of the bar + (coords[2] / 2 / scaleFactor) // Add half of the width of the bar
- (tooltip.offsetWidth / 2) // Subtract half of the tooltip width - (tooltip.offsetWidth / 2) // Subtract half of the tooltip width
+ obj.properties.tooltipsOffsetx // Add any user defined offset + obj.properties.tooltipsOffsetx // Add any user defined offset
) + 'px'; ) + 'px';
args.tooltip.style.top = ( args.tooltip.style.top = (
canvasXY[1] // The Y coordinate of the canvas canvasXY[1] // The Y coordinate of the canvas
+ coords[1] // The Y coordinate of the bar on the chart + (coords[1] / scaleFactor) // The Y coordinate of the bar on the chart
- tooltip.offsetHeight // The height of the tooltip - tooltip.offsetHeight // The height of the tooltip
- 10 // An arbitrary amount - (10 * scaleFactor) // An arbitrary amount
+ obj.properties.tooltipsOffsety // Add any user defined offset + obj.properties.tooltipsOffsety // Add any user defined offset
) + 'px'; ) + 'px';
@ -1558,6 +1671,35 @@
//
// Scale worker function that increases the size of
// properties as required. Called by the RGraph.scale()
// function.
//
// @param string name The name of the property
// @param mixed value The value of the property
//
this.scalePropertiesWorker = function (name, value)
{
var scaleFactor = this.properties.scaleFactor;
if (name === 'titleY') {
value = String(parseFloat(value) * scaleFactor);
} else if (name === 'titleX') {
value = String(parseFloat(value) * scaleFactor);
}
return value;
};
// //
// Now, because canvases can support multiple charts, canvases must always be registered // Now, because canvases can support multiple charts, canvases must always be registered
// //

View File

@ -1,744 +0,0 @@
/**
* Archivo principal de la administracion grafica de la aplicacion EMA Libre.
*
* Archivo de inicio el entorno grafico GUI del sistema EMA Libre que nos
* brinda una pantalla con las opciones: Configuracion general del sistema,
* ABM de Redes Meteorologicas,Visualizacion del sensores e informacion enviadas a la redes y
* reportes de log, como historicos registrados.
*
* LICENSE: This file is part of EMA Libre.
* EMA Libre is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EMA Libre is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EMA Libre. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright Copyright (c) 2019 GUGLER (http://www.gugler.com.ar)
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL License
* @version 3.0
* @link http://www.gugler.com.ar
* @since File available since Release 3.0
*/
// **********************Dependencias **************************
//const configGeneralEMA = require('./../conf/ConfiguracionGeneral.js'); // Configuracion General
//const configGlobalEMA = require('./../conf/ConfiguracionGlobal.js'); // Configuracion Global
//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 gui = require('nw.gui'); // Libreria Grafica
//gui.App.clearCache(); // Se limpia cache
//win = gui.Window.get(); // Se obtiene la ventana actual
var configGeneralEMA;
var configGlobalEMA;
$.get("/configGeneralEMA", function(data, status){configGeneralEMA = data;});
$.get("/configGlobalEMA", function(data, status){configGlobalEMA = data; });
// **********************Vairales Generales*********************
const iconoEncendido = '/iconos/icono_enc.png'; // Imagen del Icono Encendido
const iconoApagado = '/iconos/icono_off.png'; // Imagen del Icono Apagado
const iconoPublicado = '/iconos/icono_pub.png'; // Imagen del Icono Apagado
const iconoNeutro = '/img/neutro.webp'; // Imagen del Icono Neutro
const iconoControlTrue = '/img/ok.webp'; // Imagen de Control TRUE
const iconoControlFalse = '/img/no.webp'; // Imagen de Control FALSE
var UltimoReg;
var Ant_UltimoReg;
var ModeloVisor; // Variables Generales - Registros recolectados
var destanqueo = 0;
var intervaloBarra = 0;
var cant = 0;
var tiempovisor=99;
// **********************Funciones Principales de la GUI *****************************************************
const esperar = ms => new Promise(function(resolve){setTimeout(resolve, ms);});
// Captura el redimencionamiento de la ventana
$(window).on('resize', function () {
var zoomLevel=0;
var width = $(window).width();
var height = $(window).height();
if (width < 300 && height < 300) { zoomLevel = 0.6; }
if (width > 300 && height > 300) { zoomLevel = 0.5; }
if (width > 350 && height > 350) { zoomLevel = 0.4; }
if (width > 800 && height > 600) { zoomLevel = 0; }
if (width > 850 && height > 690) { zoomLevel = 0; }
if (width > 1000 && height > 800) { zoomLevel = 0; }
if (width > 1200 && height > 820) { zoomLevel = 1.2; }
if (width > 1200 && height > 900) { zoomLevel = 1.3; }
if (width > 1400 && height > 1000) { zoomLevel = 1.4; }
// console.log(zoomLevel);
$('html').css({zoom: zoomLevel});
});
function ComprobarEstado () {
$.get("/EMA_estado", function(data, status){
var EstadoEMA_Control = data;
if(EstadoEMA_Control[0])
{
HABLA(0, 'Ya me encuentro recolectando ..', 'success');
$('#signal').addClass('parpadea');
$('td#barralateral').css('background-color', '#11881161');
$('#estado').html('En Linea');
$('#mensaje').html('Encendido');
$('#botoniniciar').attr('disabled', true);
$('#botondetener').attr('disabled', false);
RegistroActual();
clearInterval(intervaloBarra);
intervaloBarra = window.setInterval(function () { BarradeProgreso();}, 200);
}
});
}
function INICIAR () {
if (configGeneralEMA.ConfGeneral.Modo === 'Visor') { // se comprueba el modo
HABLA(0, 'Se inicio en modo Visor', 'success');
$('#signal').addClass('parpadea');
} else {
$.get("/iniciar", function(data, status){console.log('inicio');});
HABLA(0, 'Se inicio en modo Recolector', 'success');
$('#signal').addClass('parpadea');
}
$('td#barralateral').css('background-color', '#11881161');
$('#estado').html('En Linea');
$('#mensaje').html('Encendido');
$('#botoniniciar').attr('disabled', true);
$('#botondetener').attr('disabled', false);
RegistroActual();
clearInterval(intervaloBarra);
intervaloBarra = window.setInterval(function () { BarradeProgreso();}, 200);
}
async function iniciarAutomaticamente () {
EstadoMenuInicio();
if (configGeneralEMA.ConfGeneral.inicio_automatico) {
await esperar(4000);
HABLA(0, 'Iniciando Automaticamente..', 'info');
if ($('#mensaje').html() === 'Encienda EMA Libre') {
await esperar(5000);
INICIAR();
} else {
HABLA(0, 'No se pudo iniciar automaticamente, verifique el error', 'info');
}
}
}
function DETENER () {
clearInterval(intervaloBarra);
$('td#barralateral').css('background-color', '#ff000030');
$('#estado').html('Fuera de Linea');
$('#img_estado').attr('src', iconoNeutro);
$('#mensaje').html('EMA Libre se encuentra detenida');
$('#mensajedetalle').html('Se detuvo manualmente.');
$('#img_detalle').attr('src', iconoNeutro);
$('#img_mensaje').attr('src', iconoNeutro);
$('#botoniniciar').attr('disabled', false);
$('#botondetener').attr('disabled', true);
if (configGeneralEMA.ConfGeneral.Modo === 'Visor') { // se comprueba el modo
HABLA(0, 'Modo visor detenido', 'error');
$('#signal').removeClass('parpadea');
} else {
$.get("/detener", function(data, status){console.log('detener');});
HABLA(0, 'Modo Recolector detenido', 'error');
$('#signal').removeClass('parpadea');
}
}
async function redimensionarInicio ()
{
$('#loadinicio').attr('src', 'iconos/icono_app_guina.webp');
await esperar(500);
$('#loadinicio').attr('src', 'iconos/icono_app.webp');
await esperar(600);
$('#cargador').empty();
$('#cargador').remove();
$('#principal').show();
//win.setMinimumSize(700, 500);
// win.setMaximumSize(4000, 2000);
// win.maximize();
HABLA(0, '...', 'info');
await esperar(1000);
HABLA(0, 'Bienvenido a Ema Libre Cliente, me llaman Carpincho Web.', 'info');
iniciarAutomaticamente();
}
async function Actualizar () {
var SO_WIN = plataforma.indexOf('win');
if (SO_WIN === 0) {
funcionesActualizar.Control(function (resultado, VersionActual, nueva) {
$('#botonactualizar').attr('disabled', true);
if (resultado && VersionActual) {
DETENER();
HABLA(0, 'Descargando nueva versión de Carpincho: ' + nueva, 'info');
NProgress.set(0);
$('#mensajebarra').html('Descargando nueva versión, espere ....');
funcionesActualizar.Descargar(nueva, function (resultadoact, avance, porcentaje) {
NProgress.set(porcentaje/100);
$('#mensajebarra').html(avance);
if (resultadoact && avance) {
NProgress.set(1);
$('#mensajebarra').html('Descomprimiendo la nueva versión, espere ....');
HABLA(0, 'Descomprimiendo la nueva versión, espere ....', 'info');
funcionesActualizar.Descomprimir(function (resultadoact) {
if (resultadoact) {
$('#mensajebarra').html('Borrado del archivo descargado, espere ....');
funcionesActualizar.Desplegar(function (resultado) {
if (resultado) {
HABLA(0, 'Ejecutando App de Actualizacion, espere...', 'info');
setTimeout(funcionesActualizar.LanzarAplicativoIndependiente, 9000);
} else {
HABLA(0, 'Ocurrio un problema en el despliege, intente mas tarde', 'error');
}
});
} else {
HABLA(0, 'Ocurrio un problema descomprimiendo, intente mas tarde', 'error');
}
});
}
if (!resultadoact && !avance) {
HABLA(0, 'Ocurrio un problema en la descarga, intente mas tarde', 'error');
}
});
}
if (!resultado && VersionActual) {
HABLA(0, 'No hay versiones nuevas disponibles', 'success');
}
if (!resultado && !VersionActual) {
HABLA(0, 'No se pudo conectar al servidor de versiones,pruebe mas tarde...', 'error');
}
});
} else {
HABLA(0, 'Esta opción solo es válida para sistemas operativos Windows.', 'warn');
await esperar(4000);
HABLA(0, 'Pero usted puede actualizar EMA Libre con su sistema de paquetes nativo.', 'info');
await esperar(4000);
HABLA(0, 'O puede ingresar a https://ema.gugler.com.ar para más información. ', 'info');
}
$('#botonactualizar').attr('disabled', false);
}
async function HABLA (num, mesg, tipo) {
var tamañomsg = mesg.length;
if (num === 0) {
$('#carpincho_img').notify(mesg, {
className: tipo,
position: 'right middle',
autoHideDelay: (tamañomsg * 90)
});
if (configGeneralEMA.ConfGeneral.Audio) {
window.speechSynthesis.cancel();
var voices = window.speechSynthesis.getVoices();
var cantidadVoces = voices.length;
//console.log(cantidadVoces);
if( cantidadVoces > 0){
var seleccionada = voices.filter(function (voice) { return voice.name === configGeneralEMA.ConfGeneral.audioVoces; })[0];
//console.log(seleccionada);
var msg = new SpeechSynthesisUtterance (mesg);
msg.voice = seleccionada;
msg.rate = 1.2;
msg.pitch = 1;
window.speechSynthesis.speak(msg);
msg=null;seleccionada=null;voices=null;cantidadVoces=null;
}
}
}
if ($('#carpincho_img').attr('src') === 'iconos/icono_app.webp') {
$('#carpincho_img').attr('src', 'iconos/icono_app_habla.webp');
} else {
$('#carpincho_img').attr('src', 'iconos/icono_app.webp');
}
num++;
if (num < tamañomsg) {
await esperar(90);
HABLA(num ,mesg ,0);
} else {
$('#carpincho_img').attr('src', 'iconos/icono_app.webp');
//LimpiarMemoria(true);
}
num=null;tamañomsg = null;
}
async function GUIÑA (num)
{
if ($('#carpincho_img').attr('src') === 'iconos/icono_app.webp') {
$('#carpincho_img').attr('src', 'iconos/icono_app_guina.webp');
} else {
$('#carpincho_img').attr('src', 'iconos/icono_app.webp');
}
num++;
if (num < 2) {
await esperar(400);
GUIÑA(num);
} else {
$('#carpincho_img').attr('src', 'iconos/icono_app.webp');
}
num =null;
}
async function controlPendientes () {
//var pendientes = EMA.HayPendientes();
$.get("/HayPendientes", function(data, status)
{
var pendientes = data;
var DIVPENDIENTE = document.getElementById('DIVPendientes');
var SPANTANQUE = document.getElementById('Destanqueo');
var DIVModo = document.getElementById('DIVModo');
if (pendientes !== false)
{
DIVPENDIENTE.style.visibility = 'visible';
if ((pendientes < destanqueo)) {SPANTANQUE.style.visibility = 'visible'; } else {SPANTANQUE.style.visibility = 'hidden'; }
destanqueo = pendientes;
$('#Pendientes').html("<span class='label label-warning' title='Pendientes'> Cantidad: " + pendientes + '</span><br>');
} else {
destanqueo = 0;
DIVPENDIENTE.style.visibility = 'hidden';
SPANTANQUE.style.visibility = 'hidden';
DIVModo.style.visibility = 'hidden';
}
pendientes = null;
DIVPENDIENTE = null;
SPANTANQUE = null;
DIVModo = null;
});
return true;
}
async function mostrarEstados (EstadoSensores) {
// Se consulta por los sensores
var Resultado = !((EstadoSensores.lost_sensor_contact) || (EstadoSensores.rain_overflow));
if (Resultado && (configGeneralEMA.ConfGeneral.Modo !== 'Visor')) {
$('#signal').attr('src', 'img/signal.webp');
$('#signal').addClass('parpadea');
} else {
if (!EstadoSensores.lost_sensor_contact) {
HABLA(0, 'Perdida de la señal de Radio Frecuencia', 'warn');
}
if (!EstadoSensores.rain_overflow) {
HABLA(0, 'Sensor de lluvia externo sobrecargado', 'warn');
}
$('#signal').attr('src', 'img/no_signal.webp');
$('#signal').addClass('parpadea');
// win.requestAttention(3);
}
EstadoSensores = null;
Resultado = null;
}
async function RegistroActual (barratermino)
{
//console.log('ENTRO REGISTRO ACTUAL');
if (configGeneralEMA.ConfGeneral.Modo === 'Recolector')
{ // se comprueba el modo se encuentra en Recolector
if(barratermino == true){
//BARRA TERMINO
//console.log('ENTRO AL BARRA TERMINO RECOLECTOR');
await esperar(100);
EstadoMenuInicio();
await esperar(100);
MuestraRegistroActual(true);
await esperar(100);
Graficos();
await esperar(100);
ClimaActual();
await esperar(1500);
RegistroPublicado();
cant=0;
}
$.get("/EMA_estado", async function(data, status){
var EstadoEMA = data;
if (EstadoEMA[0] === true)
{
$('#mensaje').html('Recolectando.');
$('#img_mensaje').attr('src', iconoControlTrue);
$('#mensajedetalle').html('Operando.');
$('#img_detalle').attr('src', iconoControlTrue);
controlPendientes();
$.get("/EstadoSensores", function(data, status){
var EstadoSensores = data;
if(EstadoSensores !== false)
{
mostrarEstados(EstadoSensores);
}else{EstadoSensores=null;}
});
$.get("/UltimoRegistro", function(data, status){
UltimoReg = data;
if (UltimoReg == false) {
// Se consulta por la cantidad de errores
//await esperar(10000);
HABLA(0, 'No se pueden obtener registros. Desconecte y vuelva a conectar el USB. Se prueba reiniciar el servicio.', 'error');
} else {
// $('#mensaje').html(' Sincronizando ...');
// $('#img_mensaje').attr('src', iconoNeutro);
//await esperar(200);
// RegistroActual();
return false;
}
});
} else {
$('#mensaje').html('EmaLibre detenida.');
$('#img_mensaje').attr('src', iconoControlFalse);
$('#mensajedetalle').html(EstadoEMA[1]);
$('#img_detalle').attr('src', iconoControlFalse);
await esperar(5000);
RegistroActual();
return false;
}
});
} else { // Modo visor
if(barratermino == true){
//BARRA TERMINO
await esperar(100);
EstadoMenuInicio();
await esperar(100);
MuestraRegistroActual(true);
await esperar(100);
Graficos();
await esperar(100);
ClimaActual();
cant=0;
}
$('#signal').attr('src', 'img/visor.webp');
$.get("/Visor", function(data, status){
if (data[0] != null) {
HABLA(0, 'No se pueden obtener datos del servidor. ' + data[0], 'info');
$('#signal').removeClass('parpadea');
setTimeout(function(){RegistroActual();}, 10000);
} else {
$('#signal').addClass('parpadea');
var DIVModo = document.getElementById('DIVModo');
DIVModo.style.visibility = 'visible';
document.getElementById('DIVModo').innerHTML = "<span class='badge badge-primary' title='Modo Visor'> Modo Visor </span><br><span class='badge badge-primary' >" + data[1].pais + ', ' + data[1].ciudad + "</span><br><span class='badge badge-primary' >" + data[1].modelo + '</span>';
UltimoReg = data[1].registros[0];
ModeloVisor = data[1].nombre;
// se convierte la fecha
var db = new Date(data[1].registros[0].fecha);
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;
UltimoReg.fecha = fecha;
fecha=null;dia=null;mes=null;segundo=null;minutos=null;hora=null;db=null;
// ver acumulados de lluvia
UltimoReg.lloviendo = data[1].registros[0].lluvia_actual;
UltimoReg.lluvia_acu_hora = data[1].registros[0].lluvia_acumulado_hora;
UltimoReg.lluvia_acu_diaria = data[1].registros[0].lluvia_acumulado_diario;
UltimoReg.lluvia_acumulado_total = data[1].registros[0].lluvia_acumulado_total;
// Maximas y minimas, no llegan de EMACENTER, por el momento se setean en 0.
UltimoReg.temperatura_externa_max_dia = 0;
UltimoReg.temperatura_externa_min_dia = 0;
UltimoReg.temperatura_interna_max_dia = 0;
UltimoReg.temperatura_interna_min_dia = 0;
UltimoReg.punto_de_rocio_max_dia = 0;
UltimoReg.punto_de_rocio_min_dia = 0;
UltimoReg.humedad_externa_max_dia = 0;
UltimoReg.humedad_externa_min_dia = 0;
UltimoReg.humedad_interna_max_dia = 0;
UltimoReg.humedad_interna_min_dia = 0;
UltimoReg.luxer_intencidad_max_dia = 0;
UltimoReg.luxer_intencidad_min_dia = 0;
UltimoReg.luxer_uv_max_dia = 0;
UltimoReg.luxer_uv_min_dia = 0;
UltimoReg.presion_relativa_max_dia = 0;
UltimoReg.presion_relativa_min_dia = 0;
tiempovisor = tiempovisor - 0.2;
}
});
}
EstadoEMA = null;
}
async function BarradeProgreso () {
if (configGeneralEMA.ConfGeneral.Modo === 'Recolector')
{ // EN MODO RECOLECTOR
$.get("/TiempoActualRecolector", function(data, status){
tiempoActualRecolector = data;
if(tiempoActualRecolector[0] !== false || tiempoActualRecolector[1] > 0)
{
if ((tiempoActualRecolector[0] < 98 && tiempoActualRecolector[1] > 0.39) )
{
// CONTINUA ADENTRO
NProgress.set(tiempoActualRecolector[0]/100);
return false;
} else {
// Cuando termine cada barra, publica y luego vuelve al leer el registro actual
cant++;
if(cant == 1){ RegistroActual(true);} else{return true;};
// 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>';}
NProgress.done();
}
}else{ if(cant > 0){return false;}
NProgress.done();
}
});
} else { // MODO VISOR
if( tiempovisor != 99)
{
if( tiempovisor >= configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion)
{
tiempovisor = 0;
RegistroActual(true);
NProgress.done();
}else{
tiempovisor = tiempovisor + 0.2; // se le suma el tiempo del intervalo
var tiempo_barra = ((tiempovisor * 100) / configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion)/100;
NProgress.set(tiempo_barra);
}
}
}
UltimoPub = null;aux=null;tiempoActualRecolector = null; tiempo_barra = null;
}
// ********************** Menu Acciones *******************************************************************
function MenuConfig () {
if ($('#Modo').val() === 'Recolector') {
$('#LlaveR').attr('disabled', true);
$('#LlaveR').val('');
$('#LlaveR').hide();
} else {
$('#LlaveR').attr('disabled', false);
$('#LlaveR').show();
$('#Llave_R').val(configGeneralEMA.ConfGeneral.Llave_R);
}
if ($('#Tipo_SMTP').val() === 'Deshabilitado') {
$('#Usuario_SMTP').attr('disabled', true);
$('#Contrasenia_SMTP').attr('disabled', true);
$('#Puerto_SMTP').attr('disabled', true);
$('#Server_SMTP').attr('disabled', true);
$('#Puerto_SMTP').val('');
$('#puerto').hide();
$('#Server_SMTP').val('');
$('#Server').hide();
} else {
$('#Usuario_SMTP').attr('disabled', false);
$('#Contrasenia_SMTP').attr('disabled', false);
if ($('#Tipo_SMTP').val() === 'Manual') {
$('#Puerto_SMTP').attr('disabled', false);
$('#puerto').show();
$('#Server_SMTP').attr('disabled', false);
$('#Server').show();
} else {
$('#Puerto_SMTP').attr('disabled', true);
$('#puerto').hide();
$('#Server_SMTP').attr('disabled', true);
$('#Server').hide();
}
$('#Usuario_SMTP').val(configGeneralEMA.ConfEmail.Usuario);
$('#Contrasenia_SMTP').val(configGeneralEMA.ConfEmail.Password);
$('#Server_SMTP').val(configGeneralEMA.ConfEmail.Server);
$('#Puerto_SMTP').val(configGeneralEMA.ConfEmail.Puerto);
}
if ($('#audio').val() === 'Desactivado') {
$('#vocesAudioDiv').attr('disabled', true);
$('#vocesAudioDiv').val('');
$('#vocesAudioDiv').hide();
} else {
$('#vocesAudioDiv').attr('disabled', false);
$('#vocesAudioDiv').show();
$('#vocesAudio').val(configGeneralEMA.ConfGeneral.audioVoces);
$('#vocesAudio').selectpicker('render');
}
}
async function MenuGUI (elemento) {
try {
document.getElementById("actualizando_inicio").hidden = false;
document.getElementById("actualizando_inicio").style.display = "block";
var seleccion;
if (elemento === 'logs') {seleccion = document.getElementById('configuracion');}
else {seleccion = document.getElementById(elemento);}
$(seleccion).empty();
$(seleccion).hide();
$(seleccion).load('./view/modelo_' + elemento + '.html', function (datosArchivo) {
switch (elemento) {
case 'logs':
VerRegistrosLog();
$('#interior').empty();$('#exterior').empty();$('#inicio').empty();$('#contacto').empty();$('#inicio').empty();$('#estadisticas').empty();
break;
case 'redes':
ListarRedes();
$('#interior').empty();$('#exterior').empty();$('#contacto').empty();$('#configuracion').empty();$('#inicio').empty();$('#estadisticas').empty();
break;
case 'redes_alta':
MenuSelectRed();
break;
case 'inicio':
$('#node_pid').html(pid);
$('#node_ppid').html(ppid);
$('#nwjs_v').html(version_node);
EstadoMenuInicio();
$('#interior').empty();$('#exterior').empty();$('#contacto').empty();$('#configuracion').empty();$('#redes').empty();$('#estadisticas').empty();
break;
case 'interior':
MuestraRegistroActual(false,'interior');
Graficos('interior');
$('#inicio').empty();$('#exterior').empty();$('#contacto').empty();$('#configuracion').empty();$('#redes').empty();$('#estadisticas').empty();
break;
case 'exterior':
MuestraRegistroActual(false,'exterior');
Graficos('exterior');
$('#interior').empty();$('#inicio').empty();$('#contacto').empty();$('#configuracion').empty();$('#redes').empty();$('#estadisticas').empty();
break;
case 'estadisticas':
graficoEstadisticas();
$('#interior').empty();$('#exterior').empty();$('#inicio').empty();$('#contacto').empty();$('#configuracion').empty();$('#redes').empty();
break;
case 'contacto':
var NombreVersion = ' v' + configGlobalEMA.ConfGlobal.Version;
$('#versioncontacto').html(NombreVersion);
$('#interior').empty();$('#exterior').empty();$('#inicio').empty();$('#configuracion').empty();$('#redes').empty();$('#estadisticas').empty();
break;
case 'configuracion':
$('#interior').empty();$('#exterior').empty();$('#contacto').empty();$('#inicio').empty();$('#redes').empty();$('#estadisticas').empty();
// Se obtienen las voces del sistema
var synth = window.speechSynthesis;
const voice = synth.getVoices();
var voiceSelect = document.getElementById('vocesAudio');
var cantidadVoces = voice.length;
if( cantidadVoces > 0){
for (var i = 0; i < cantidadVoces; i++)
{
var option = document.createElement('option');
option.textContent = voice[i].name;
option.setAttribute('value', voice[i].name);
voiceSelect.appendChild(option);
}
}else{
var option = document.createElement('option');
voice[0] = 'Sin Voces';
option.textContent = 'Sin voces, verifique el SO';
option.setAttribute('value', 'Sin Voces');
voiceSelect.appendChild(option);
voiceSelect.selectedIndex = "0";
}
$('#NombreEstacion').val(configGeneralEMA.ConfGeneral.NombreEstacion);
$('#Modo').val(configGeneralEMA.ConfGeneral.Modo);
$('#Modo').selectpicker('render');
$('#SistemaMetrico').val(configGeneralEMA.ConfGeneral.SistemaMetrico);
$('#SistemaMetrico').selectpicker('render');
$('#Llave_R').val(configGeneralEMA.ConfGeneral.Llave_R);
$('#Tiempo_de_Recoleccion').val(configGeneralEMA.ConfGeneral.Tiempo_de_Recoleccion);
$('#Email_receptor').val(configGeneralEMA.ConfEmail.ReceptorEmail);
$('#Tipo_SMTP').val(configGeneralEMA.ConfEmail.Servicio);
$('#Tipo_SMTP').selectpicker('render');
$('#Tiempo_de_Recoleccion').selectpicker('render');
$('#Debug').val(configGeneralEMA.ConfGeneral.debug);
$('#debugMB').val(configGeneralEMA.ConfGeneral.debugTamanio);
$('#Debug').selectpicker('render');
var automatico;
if (configGeneralEMA.ConfGeneral.inicio_automatico) { automatico = 'Activado'; } else { automatico = 'Desactivado'; }
$('#inicio_auto').val(automatico);
$('#inicio_auto').selectpicker('render');
var cambios;
if (configGeneralEMA.ConfGeneral.notificar_cambios) { cambios = 'Activado'; } else { cambios = 'Desactivado'; }
$('#notificar_cambios').val(cambios);
$('#notificar_cambios').selectpicker('render');
var Audio;
if (configGeneralEMA.ConfGeneral.Audio) { Audio = 'Activado'; } else { Audio = 'Desactivado'; }
$('#audio').val(Audio);
$('#audio').selectpicker('render');
$('#utc').val(configGeneralEMA.ConfGeneral.UTC);
$('#utc').selectpicker('render');
// Control para el audio
if (configGeneralEMA.ConfGeneral.Audio === false) {
$('#vocesAudioDiv').attr('disabled', true);
$('#vocesAudioDiv').val('');
$('#vocesAudioDiv').hide();
} else {
$('#vocesAudioDiv').attr('disabled', false);
$('#vocesAudioDiv').show();
if (configGeneralEMA.ConfGeneral.audioVoces === null || typeof configGeneralEMA.ConfGeneral.audioVoces === 'undefined') { $('#vocesAudio').val(voice[0].name); } else { $('#vocesAudio').val(configGeneralEMA.ConfGeneral.audioVoces); }
}
$('#vocesAudio').selectpicker('render');
// Control para el modo
if ($('#Modo').val() === 'Recolector') {
$('#LlaveR').attr('disabled', true);
$('#LlaveR').val('');
$('#LlaveR').hide();
} else {
$('#LlaveR').attr('disabled', false);
$('#LlaveR').show();
$('#Llave_R').val(configGeneralEMA.ConfGeneral.Llave_R);
}
// Control para el SMTP
if ($('#Tipo_SMTP').val() === 'Deshabilitado') {
$('#Usuario_SMTP').attr('disabled', true);
$('#Contrasenia_SMTP').attr('disabled', true);
$('#Puerto_SMTP').attr('disabled', true);
$('#Server_SMTP').attr('disabled', true);
$('#Server').hide();
$('#puerto').hide();
} else {
$('#Usuario_SMTP').attr('disabled', false);
$('#Contrasenia_SMTP').attr('disabled', false);
$('#Server_SMTP').attr('disabled', false);
$('#Puerto_SMTP').attr('disabled', false);
$('#Usuario_SMTP').val(configGeneralEMA.ConfEmail.Usuario);
$('#Contrasenia_SMTP').val(configGeneralEMA.ConfEmail.Password);
$('#Server_SMTP').val(configGeneralEMA.ConfEmail.Server);
$('#Puerto_SMTP').val(configGeneralEMA.ConfEmail.Puerto);
if ($('#Tipo_SMTP').val() === 'Manual') {
$('#Server_SMTP').attr('disabled', false);
$('#Puerto_SMTP').attr('disabled', false);
$('#puerto').show();
$('#Server').show();
} else {
$('#puerto').hide();
$('#Server').hide();
}
}
break;
default:
console.log('No existe el menu seleccionado: ' + elemento);
}
setTimeout(function(){ document.getElementById("actualizando_inicio").style.display = "none";
document.getElementById("actualizando_inicio").hidden = false;
$(seleccion).show();
}, 200);
});
} catch (e) { // Si falla se informa y se vuelve a cargar el modelo interior
HABLA(0, 'Se realizó un reload de la libreria grafica interior', 'info');
}
}
async function autoLoad ()
{
await esperar(6000);
ComprobarEstado();
//var plataforma = process.platform;
//var SO_WIN = plataforma.indexOf('win');
//if (SO_WIN === 0) { funcionesActualizar.Control(function (resultado, VersionActual, nueva) { if (resultado) { HABLA(0, 'Hay una nueva version de Carpincho. Versión ' + nueva, 'error'); } }); }
}
autoLoad();

View File

@ -26,12 +26,12 @@
// VARIABLES GENERALES // VARIABLES GENERALES
var Sube = "<img src='img/clima/sube.webp' title='"; // Imagen cuando sube una lectura, la misma se completa con la tendencia. var Sube = "<img src='gui_common/img/clima/sube.webp' title='"; // Imagen cuando sube una lectura, la misma se completa con la tendencia.
var Baja = "<img src='img/clima/baja.webp' title='"; // Imagen cuando baja una lectura, la misma se completa con la tendencia. var Baja = "<img src='gui_common/img/clima/baja.webp' title='"; // Imagen cuando baja una lectura, la misma se completa con la tendencia.
var Igual = "<img src='img/clima/igual.webp'>"; // Imagen cuando no hay cambios. var Igual = "<img src='gui_common/img/clima/igual.webp'>"; // Imagen cuando no hay cambios.
var icono_control_true = 'img/ok.webp'; // Imagen de Control TRUE var icono_control_true = 'gui_common/img/ok.webp'; // Imagen de Control TRUE
var icono_control_false = 'img/no.webp'; // Imagen de Control FALSE var icono_control_false = 'gui_common/img/no.webp'; // Imagen de Control FALSE
var icono_control_neutro = 'img/neutro.webp'; // Imagen de Control NEUTRO - ALERT var icono_control_neutro = 'gui_common/img/neutro.webp'; // Imagen de Control NEUTRO - ALERT
var pid,ppid,plataforma,arquitectura,version_node='-'; var pid,ppid,plataforma,arquitectura,version_node='-';
// Se obtienen los datos de la plataforma // Se obtienen los datos de la plataforma
$.get("/plataforma", function(data, status) $.get("/plataforma", function(data, status)
@ -93,15 +93,15 @@ async function EstadoMenuInicio()
$('#inombre').html(configGeneralEMA.ConfGeneral.NombreEstacion); $('#inombre').html(configGeneralEMA.ConfGeneral.NombreEstacion);
$('#botoniniciar').attr("disabled",true); $('#botoniniciar').attr("disabled",true);
$('#botondetener').attr("disabled",true) $('#botondetener').attr("disabled",true)
if(configGeneralEMA.ConfGeneral.NombreEstacion != ''){$("#img_nombre").attr("src",icono_control_true);}else{$("#img_nombre").attr("src",icono_control_neutro);}
$('#iso').html(plataforma + " (" + arquitectura + ")"); $('#iso').html(plataforma + " (" + arquitectura + ")");
if(plataforma != ''){$("#img_so").attr("src",icono_control_true);}else{$("#img_so").attr("src",icono_control_false);}
$('#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 != 'Visor') // Se consulta el modo (Recolector o Visor) if(configGeneralEMA.ConfGeneral.Modo != 'Visor') // Se consulta el modo (Recolector o Visor)
{ {
$.get("/EMA_estado", function(data, status){ $.get("/EMA_estado", function(data, status){
var EstadoEMA_Control = data; var EstadoEMA_Control = data;
if(configGeneralEMA.ConfGeneral.Modo === 'Recolector_USB') // Modo Recolector USB
{
if(EstadoEMA_Control[0]) if(EstadoEMA_Control[0])
{ {
$("#img_estado").attr("src",icono_control_true);$('#estado').html("En Linea"); $("#img_estado").attr("src",icono_control_true);$('#estado').html("En Linea");
@ -135,7 +135,30 @@ async function EstadoMenuInicio()
} }
}); });
} }
});
}else{ // Modo Recolector por IP/WIFI
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" ))
@ -192,16 +215,16 @@ async function EstadoMenuInicio()
//Muestra Interior (Temperatura y Humedad) //Muestra Interior (Temperatura y Humedad)
if(($('#interior').hasClass('active') && typeof click === "undefined") || (click === 'interior')) if(($('#interior').hasClass('active') && typeof click === "undefined") || (click === 'interior'))
{ {
//***Temperatura Interna // ***Temperatura Interna
if (UltimoReg.temperatura_interna != Ant_UltimoReg.temperatura_interna){ if (UltimoReg.temperatura_interna > Ant_UltimoReg.temperatura_interna ) {tendenciaTI = Sube + (Ant_UltimoReg.temperatura_interna*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S +"|| Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Sube+"'>";}else{tendenciaTI = Baja+(Ant_UltimoReg.temperatura_interna*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S + " || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Baja+"'>";}}else {result = Igual;} if (UltimoReg.temperatura_interna != Ant_UltimoReg.temperatura_interna){ if (UltimoReg.temperatura_interna > Ant_UltimoReg.temperatura_interna ) {tendenciaTI = Sube + (Ant_UltimoReg.temperatura_interna*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S +"|| Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Sube+"'>";}else{tendenciaTI = Baja+(Ant_UltimoReg.temperatura_interna*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S + " || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Baja+"'>";}}else {result = Igual;}
$('#temp_int').html((UltimoReg.temperatura_interna*TEMP_MULT+TEMP_POND).toFixed(1) + TEMP_S + tendenciaTI);$('#temp_int_img').html(result); $('#temp_int').html((UltimoReg.temperatura_interna*TEMP_MULT+TEMP_POND).toFixed(1) + TEMP_S + tendenciaTI);$('#temp_int_img').html(result);
//*** Maximos y Minimos // *** Maximos y Minimos
$('#temp_int_max').html((UltimoReg.temperatura_interna_max_dia*TEMP_MULT+TEMP_POND).toFixed(1) + TEMP_S); $('#temp_int_max').html((UltimoReg.temperatura_interna_max_dia*TEMP_MULT+TEMP_POND).toFixed(1) + TEMP_S);
$('#temp_int_min').html((UltimoReg.temperatura_interna_min_dia*TEMP_MULT+TEMP_POND).toFixed(1) + TEMP_S); $('#temp_int_min').html((UltimoReg.temperatura_interna_min_dia*TEMP_MULT+TEMP_POND).toFixed(1) + TEMP_S);
//*** humedad interna // *** humedad interna
if (UltimoReg.humedad_interna != Ant_UltimoReg.humedad_interna){ if (UltimoReg.humedad_interna > Ant_UltimoReg.humedad_interna ) {tendenciaHI = Sube + Ant_UltimoReg.humedad_interna+"% || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Sube+"'>";}else{tendenciaHI = Baja+Ant_UltimoReg.humedad_interna+"% || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Baja+"'>";}}else {result = Igual;} if (UltimoReg.humedad_interna != Ant_UltimoReg.humedad_interna){ if (UltimoReg.humedad_interna > Ant_UltimoReg.humedad_interna ) {tendenciaHI = Sube + Ant_UltimoReg.humedad_interna+"% || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Sube+"'>";}else{tendenciaHI = Baja+Ant_UltimoReg.humedad_interna+"% || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Baja+"'>";}}else {result = Igual;}
$('#hum_int').html(UltimoReg.humedad_interna + " % " + tendenciaHI);$('#hum_int_img').html(result); $('#hum_int').html(UltimoReg.humedad_interna + " % " + tendenciaHI);$('#hum_int_img').html(result);
//*** Maximos y Minimos // *** Maximos y Minimos
$('#hum_int_max').html(UltimoReg.humedad_interna_max_dia + " %" ); $('#hum_int_max').html(UltimoReg.humedad_interna_max_dia + " %" );
$('#hum_int_min').html(UltimoReg.humedad_interna_min_dia + " %" ); $('#hum_int_min').html(UltimoReg.humedad_interna_min_dia + " %" );
} }
@ -209,31 +232,31 @@ async function EstadoMenuInicio()
if(($('#exterior').hasClass('active') && typeof click === "undefined") || (click === 'exterior')) if(($('#exterior').hasClass('active') && typeof click === "undefined") || (click === 'exterior'))
{ {
//CALCULO DE TENDENCIAS Y MUESTRA REGISTRO //CALCULO DE TENDENCIAS Y MUESTRA REGISTRO
//***Temperatura Externa // ***Temperatura Externa
if (UltimoReg.temperatura_externa != Ant_UltimoReg.temperatura_externa){ if (UltimoReg.temperatura_externa > Ant_UltimoReg.temperatura_externa ) {tendenciaTE = Sube + (Ant_UltimoReg.temperatura_externa*TEMP_MULT+TEMP_POND).toFixed(2)+ TEMP_S +" || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Sube+"'>";}else{tendenciaTE = Baja+(Ant_UltimoReg.temperatura_externa*TEMP_MULT+TEMP_POND).toFixed(2)+ TEMP_S +" || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Baja+"'>";}}else {result = Igual;} if (UltimoReg.temperatura_externa != Ant_UltimoReg.temperatura_externa){ if (UltimoReg.temperatura_externa > Ant_UltimoReg.temperatura_externa ) {tendenciaTE = Sube + (Ant_UltimoReg.temperatura_externa*TEMP_MULT+TEMP_POND).toFixed(2)+ TEMP_S +" || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Sube+"'>";}else{tendenciaTE = Baja+(Ant_UltimoReg.temperatura_externa*TEMP_MULT+TEMP_POND).toFixed(2)+ TEMP_S +" || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Baja+"'>";}}else {result = Igual;}
$('#temp_ext').html((UltimoReg.temperatura_externa*TEMP_MULT+TEMP_POND).toFixed(1)+ TEMP_S + tendenciaTE);$('#temp_ext_img').html(result); $('#temp_ext').html((UltimoReg.temperatura_externa*TEMP_MULT+TEMP_POND).toFixed(1)+ TEMP_S + tendenciaTE);$('#temp_ext_img').html(result);
//*** Maximos y Minimos //*** Maximos y Minimos
$('#temp_ext_max').html((UltimoReg.temperatura_externa_max_dia *TEMP_MULT+TEMP_POND).toFixed(1) + TEMP_S); $('#temp_ext_max').html((UltimoReg.temperatura_externa_max_dia *TEMP_MULT+TEMP_POND).toFixed(1) + TEMP_S);
$('#temp_ext_min').html((UltimoReg.temperatura_externa_min_dia *TEMP_MULT+TEMP_POND).toFixed(1) + TEMP_S); $('#temp_ext_min').html((UltimoReg.temperatura_externa_min_dia *TEMP_MULT+TEMP_POND).toFixed(1) + TEMP_S);
//*** Punto de Rocio // *** Punto de Rocio
if (UltimoReg.punto_de_rocio != Ant_UltimoReg.punto_de_rocio){ if(UltimoReg.punto_de_rocio > Ant_UltimoReg.punto_de_rocio ) {tendenciaPDR = Sube + (Ant_UltimoReg.punto_de_rocio*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S +"|| Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Sube;}else{tendenciaPDR = Baja + (Ant_UltimoReg.punto_de_rocio*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S +" || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Baja +"'>";}}else {result = Igual;} if (UltimoReg.punto_de_rocio != Ant_UltimoReg.punto_de_rocio){ if(UltimoReg.punto_de_rocio > Ant_UltimoReg.punto_de_rocio ) {tendenciaPDR = Sube + (Ant_UltimoReg.punto_de_rocio*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S +"|| Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Sube;}else{tendenciaPDR = Baja + (Ant_UltimoReg.punto_de_rocio*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S +" || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Baja +"'>";}}else {result = Igual;}
$('#punto_ext').html((UltimoReg.punto_de_rocio*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S + tendenciaPDR);$('#punto_ext_img').html(result); $('#punto_ext').html((UltimoReg.punto_de_rocio*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S + tendenciaPDR);$('#punto_ext_img').html(result);
//*** Maximos y Minimos //*** Maximos y Minimos
$('#punto_ext_max').html((UltimoReg.punto_de_rocio_max_dia*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S); $('#punto_ext_max').html((UltimoReg.punto_de_rocio_max_dia*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S);
$('#punto_ext_min').html((UltimoReg.punto_de_rocio_min_dia*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S); $('#punto_ext_min').html((UltimoReg.punto_de_rocio_min_dia*TEMP_MULT+TEMP_POND).toFixed(2) + TEMP_S);
//*** humedad Externa // *** humedad Externa
if (UltimoReg.humedad_externa != Ant_UltimoReg.humedad_externa){ if (UltimoReg.humedad_externa > Ant_UltimoReg.humedad_externa ) {tendenciaHE = Sube + Ant_UltimoReg.humedad_externa+"% || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Sube+"'>";}else{tendenciaHE = Baja+Ant_UltimoReg.humedad_externa+"% || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Baja+"'>";}}else {result = Igual;} if (UltimoReg.humedad_externa != Ant_UltimoReg.humedad_externa){ if (UltimoReg.humedad_externa > Ant_UltimoReg.humedad_externa ) {tendenciaHE = Sube + Ant_UltimoReg.humedad_externa+"% || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Sube+"'>";}else{tendenciaHE = Baja+Ant_UltimoReg.humedad_externa+"% || Fecha: "+ Ant_UltimoReg.fecha +"'>";result = Baja+"'>";}}else {result = Igual;}
$('#hum_ext').html(UltimoReg.humedad_externa + " % " + tendenciaHE);$('#hum_ext_img').html(result); $('#hum_ext').html(UltimoReg.humedad_externa + " % " + tendenciaHE);$('#hum_ext_img').html(result);
//*** Maximos y Minimos // *** Maximos y Minimos
$('#hum_ext_max').html(UltimoReg.humedad_externa_max_dia + " %" ); $('#hum_ext_max').html(UltimoReg.humedad_externa_max_dia + " %" );
$('#hum_ext_min').html(UltimoReg.humedad_externa_min_dia + " %" ); $('#hum_ext_min').html(UltimoReg.humedad_externa_min_dia + " %" );
//*** Intenciadad Luz // *** Intenciadad Luz
if(UltimoReg.luxer_intencidad != null) if(UltimoReg.luxer_intencidad != null)
{ {
if (UltimoReg.luxer_intencidad != Ant_UltimoReg.luxer_intencidad){ if (UltimoReg.luxer_intencidad > Ant_UltimoReg.luxer_intencidad ) {tendenciaLI = Sube + Ant_UltimoReg.luxer_intencidad + " Lux || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Sube;}else{tendenciaLI = Baja + Ant_UltimoReg.luxer_intencidad+" Lux || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Baja +"'>";}}else {result = Igual;} if (UltimoReg.luxer_intencidad != Ant_UltimoReg.luxer_intencidad){ if (UltimoReg.luxer_intencidad > Ant_UltimoReg.luxer_intencidad ) {tendenciaLI = Sube + Ant_UltimoReg.luxer_intencidad + " Lux || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Sube;}else{tendenciaLI = Baja + Ant_UltimoReg.luxer_intencidad+" Lux || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Baja +"'>";}}else {result = Igual;}
$('#luxer_ext').html(UltimoReg.luxer_intencidad + " lux " + tendenciaLI);$('#luxer_ext_img').html(result); $('#luxer_ext').html(UltimoReg.luxer_intencidad + " lux " + tendenciaLI);$('#luxer_ext_img').html(result);
//*** Maximos y Minimos // *** Maximos y Minimos
$('#luxer_ext_max').html((UltimoReg.luxer_intencidad_max_dia*0.001).toFixed(2) + " Klux" ); $('#luxer_ext_max').html((UltimoReg.luxer_intencidad_max_dia*0.001).toFixed(2) + " Klux" );
$('#luxer_ext_min').html((UltimoReg.luxer_intencidad_min_dia*0.001).toFixed(2) + " Klux" ); $('#luxer_ext_min').html((UltimoReg.luxer_intencidad_min_dia*0.001).toFixed(2) + " Klux" );
}else{ }else{
@ -241,12 +264,12 @@ async function EstadoMenuInicio()
$('#luxer_ext_min').html('S/D'); $('#luxer_ext_min').html('S/D');
$('#luxer_ext_max').html('S/D'); $('#luxer_ext_max').html('S/D');
} }
//*** Rayos UV // *** Rayos UV
if(UltimoReg.luxer_uv != null) if(UltimoReg.luxer_uv != null)
{ {
if (UltimoReg.luxer_uv != Ant_UltimoReg.luxer_uv){ if(UltimoReg.luxer_uv > Ant_UltimoReg.luxer_uv ) {tendenciaR = Sube + Ant_UltimoReg.luxer_uv +" UV || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Sube;}else{tendenciaR = Baja + Ant_UltimoReg.luxer_uv+" UV || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Baja +"'>";}}else {result = Igual;} if (UltimoReg.luxer_uv != Ant_UltimoReg.luxer_uv){ if(UltimoReg.luxer_uv > Ant_UltimoReg.luxer_uv ) {tendenciaR = Sube + Ant_UltimoReg.luxer_uv +" UV || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Sube;}else{tendenciaR = Baja + Ant_UltimoReg.luxer_uv+" UV || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Baja +"'>";}}else {result = Igual;}
$('#rayos_ext').html(UltimoReg.luxer_uv + " uv / " +texto_uv + " " + tendenciaR);$('#rayos_img').html(result); $('#rayos_ext').html(UltimoReg.luxer_uv + " uv / " +texto_uv + " " + tendenciaR);$('#rayos_img').html(result);
//*** Maximos y Minimos // *** Maximos y Minimos
$('#rayos_ext_max').html(UltimoReg.luxer_uv_max_dia + " uv" ); $('#rayos_ext_max').html(UltimoReg.luxer_uv_max_dia + " uv" );
$('#rayos_ext_min').html(UltimoReg.luxer_uv_min_dia + " uv" ); $('#rayos_ext_min').html(UltimoReg.luxer_uv_min_dia + " uv" );
}else{ }else{
@ -254,16 +277,16 @@ async function EstadoMenuInicio()
$('#rayos_ext_min').html('S/D'); $('#rayos_ext_min').html('S/D');
$('#rayos_ext_max').html('S/D'); $('#rayos_ext_max').html('S/D');
} }
//*** Presion Absoluta // *** Presion Absoluta
if (UltimoReg.presion_absoluta != Ant_UltimoReg.presion_absoluta){ if(UltimoReg.presion_absoluta > Ant_UltimoReg.presion_absoluta ) {tendenciaPA = Sube + Ant_UltimoReg.presion_absoluta +" hpa || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Sube;}else{tendenciaPA = Baja + Ant_UltimoReg.presion_absoluta+" hpa || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Baja +"'>";}}else {result = Igual;} if (UltimoReg.presion_absoluta != Ant_UltimoReg.presion_absoluta){ if(UltimoReg.presion_absoluta > Ant_UltimoReg.presion_absoluta ) {tendenciaPA = Sube + Ant_UltimoReg.presion_absoluta +" hpa || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Sube;}else{tendenciaPA = Baja + Ant_UltimoReg.presion_absoluta+" hpa || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Baja +"'>";}}else {result = Igual;}
$('#presiona_ext').html(UltimoReg.presion_absoluta + " hpa " +tendenciaPA);$('#presiona_ext_img').html(result); $('#presiona_ext').html(UltimoReg.presion_absoluta + " hpa " +tendenciaPA);$('#presiona_ext_img').html(result);
//*** Presion Relativa // *** Presion Relativa
if (UltimoReg.presion_relativa != Ant_UltimoReg.presion_relativa){ if(UltimoReg.presion_relativa > Ant_UltimoReg.presion_relativa ) {tendenciaPR = Sube + Ant_UltimoReg.presion_relativa +" hpa || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Sube;}else{tendenciaPR = Baja + Ant_UltimoReg.presion_relativa+" hpa || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Baja +"'>";}}else {result = Igual;} if (UltimoReg.presion_relativa != Ant_UltimoReg.presion_relativa){ if(UltimoReg.presion_relativa > Ant_UltimoReg.presion_relativa ) {tendenciaPR = Sube + Ant_UltimoReg.presion_relativa +" hpa || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Sube;}else{tendenciaPR = Baja + Ant_UltimoReg.presion_relativa+" hpa || Fecha: "+ Ant_UltimoReg.fecha +"'>";result=Baja +"'>";}}else {result = Igual;}
$('#presionr_ext').html(UltimoReg.presion_relativa + " hpa " + tendenciaPR);$('#presionr_ext_img').html(result); $('#presionr_ext').html(UltimoReg.presion_relativa + " hpa " + tendenciaPR);$('#presionr_ext_img').html(result);
//*** Maximos y Minimos // *** Maximos y Minimos
$('#presionr_ext_max').html(UltimoReg.presion_relativa_max_dia + " hpa" ); $('#presionr_ext_max').html(UltimoReg.presion_relativa_max_dia + " hpa" );
$('#presionr_ext_min').html(UltimoReg.presion_relativa_min_dia + " hpa" ); $('#presionr_ext_min').html(UltimoReg.presion_relativa_min_dia + " hpa" );
//*** Acumulados Lluvia ----> No tiene tendencias. // *** Acumulados Lluvia ----> No tiene tendencias.
$('#lloviendo_ext').html(UltimoReg.lloviendo + "mm"); $('#lloviendo_ext').html(UltimoReg.lloviendo + "mm");
$('#totalacuhora_ext').html(UltimoReg.lluvia_acu_hora + "mm"); $('#totalacuhora_ext').html(UltimoReg.lluvia_acu_hora + "mm");
$('#totalacudia_ext').html(UltimoReg.lluvia_acu_diaria + "mm"); $('#totalacudia_ext').html(UltimoReg.lluvia_acu_diaria + "mm");
@ -321,8 +344,8 @@ async function ClimaActual()
if( (UltimoReg.luxer_intencidad < UltimoReg.luxer_intencidad_1hs) && (UltimoReg.luxer_intencidad > 0 && UltimoReg.luxer_intencidad < 800)){ SALIDA_ENTRADA = '_0.gif';} // OCASO? if( (UltimoReg.luxer_intencidad < UltimoReg.luxer_intencidad_1hs) && (UltimoReg.luxer_intencidad > 0 && UltimoReg.luxer_intencidad < 800)){ SALIDA_ENTRADA = '_0.gif';} // OCASO?
//Icono central //Icono central
var image = document.createElement("IMG");image.alt = "Clima Actual";image.setAttribute("height", "96px");image.setAttribute("width", "96px");image.setAttribute('class', 'photo'); var image = document.createElement("IMG");image.alt = "Clima Actual";image.setAttribute("height", "96px");image.setAttribute("width", "96px");image.setAttribute('class', 'photo');
if(SALIDA_ENTRADA != ""){image.src="img/clima/1_0_clima" + SALIDA_ENTRADA; //ver de agregar ALBA Y OCASO con lluvia if(SALIDA_ENTRADA != ""){image.src="gui_common/img/clima/1_0_clima" + SALIDA_ENTRADA; //ver de agregar ALBA Y OCASO con lluvia
}else{image.src="img/clima/" + NOCHE_DIA +"_" + LLUEVE + "_clima" + SALIDA_ENTRADA +".webp";} }else{image.src="gui_common/img/clima/" + NOCHE_DIA +"_" + LLUEVE + "_clima" + SALIDA_ENTRADA +".webp";}
$('#clima').html(image); $('#clima').html(image);
//Fondo de la aplicacion //Fondo de la aplicacion
if( LLUEVE == 1){HABLA(0,"Se registra lluvia","info"); if( LLUEVE == 1){HABLA(0,"Se registra lluvia","info");
@ -332,12 +355,14 @@ 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"); if(cambiosCarpincho != '') HABLA(0, 'Hay cambios de ' + cambiosCarpincho ,"info");
} }
@ -474,7 +499,7 @@ async function Graficos(click)
id: 'gviento_dir', id: 'gviento_dir',
x: 15, x: 15,
y: 15, y: 15,
src: './img/brujula.webp', src: './gui_common/img/brujula.webp',
options: { options: {
width: 200, width: 200,
height: 200 height: 200
@ -565,12 +590,12 @@ function ListarRedes()
{ {
TablaHTML += "<tr><td><b>"+Publicar[i].Nombre+"</b></td><td>"+Publicar[i].TipoRed+"</td><td><span class='badge badge-success'>SI</span></td><td><span class='badge badge-danger'>NO</span></td><td><span class='badge badge-default'>N/A</span></td><td>"+publicar+"</td><td><select onchange='MenuRedes("+i+")' title='Accion' id='Red_activa_"+i+"' name='Red_activa' class='selectpicker show-tick' data-width='fit' data-style='btn-primary'>"; TablaHTML += "<tr><td><b>"+Publicar[i].Nombre+"</b></td><td>"+Publicar[i].TipoRed+"</td><td><span class='badge badge-success'>SI</span></td><td><span class='badge badge-danger'>NO</span></td><td><span class='badge badge-default'>N/A</span></td><td>"+publicar+"</td><td><select onchange='MenuRedes("+i+")' title='Accion' id='Red_activa_"+i+"' name='Red_activa' class='selectpicker show-tick' data-width='fit' data-style='btn-primary'>";
if(Publicar[i].Publicar == true) {TablaHTML += "<option value='NoPublicar'>No Publicar</option>"}else{TablaHTML += "<option value='Publicar'>Publicar</option>"}; if(Publicar[i].Publicar == true) {TablaHTML += "<option value='NoPublicar'>No Publicar</option>"}else{TablaHTML += "<option value='Publicar'>Publicar</option>"};
TablaHTML += "<option value='Modificar'>Modificar</option><option value='Eliminar'>Eliminar</option></select></td></tr>"; TablaHTML += "<option value='Modificar'>Modificar</option><option value='Eliminar'>Eliminar</option><option value='SitioOficial'>Sitio Oficial</option></select></td></tr>";
}else{ }else{
if(Publicar[i].Llave_W != ''){var tienellave = "SI";}else{var tienellave ="NO";} if(Publicar[i].Llave_W != ''){var tienellave = "SI";}else{var tienellave ="NO";}
TablaHTML += "<tr><td><b>"+Publicar[i].Nombre+"</b></td><td>"+Publicar[i].TipoRed+"</td><td><span class='badge badge-default'>N/A</span></td><td><span class='badge badge-success'>"+tienellave+"</span></td><td><span class='badge badge-default'>"+(Publicar[i].Puerto || "N/A")+"</span></td><td>"+publicar+"</td><td><select onchange='MenuRedes("+i+")' title='Accion' id='Red_activa_"+i+"' name='Red_activa' class='selectpicker show-tick' data-width='fit' data-style='btn-primary'>"; TablaHTML += "<tr><td><b>"+Publicar[i].Nombre+"</b></td><td>"+Publicar[i].TipoRed+"</td><td><span class='badge badge-default'>N/A</span></td><td><span class='badge badge-success'>"+tienellave+"</span></td><td><span class='badge badge-default'>"+(Publicar[i].Puerto || "N/A")+"</span></td><td>"+publicar+"</td><td><select onchange='MenuRedes("+i+")' title='Accion' id='Red_activa_"+i+"' name='Red_activa' class='selectpicker show-tick' data-width='fit' data-style='btn-primary'>";
if(Publicar[i].Publicar == true) {TablaHTML += "<option value='NoPublicar'>No Publicar</option>"}else{TablaHTML += "<option value='Publicar'>Publicar</option>"}; if(Publicar[i].Publicar == true) {TablaHTML += "<option value='NoPublicar'>No Publicar</option>"}else{TablaHTML += "<option value='Publicar'>Publicar</option>"};
TablaHTML += "<option value='Modificar'>Modificar</option><option value='Eliminar'>Eliminar</option></select></td></tr>"; TablaHTML += "<option value='Modificar'>Modificar</option><option value='Eliminar'>Eliminar</option><option value='SitioOficial'>Sitio Oficial</option></select></td></tr>";
} }
} }
TablaHTML += "</table>"; TablaHTML += "</table>";
@ -620,28 +645,32 @@ function MenuRedes(red)
switch ($('#Red_activa_'+red).val()) { switch ($('#Red_activa_'+red).val()) {
case 'Eliminar': case 'Eliminar':
// SE PREGUNTA SI ESTA SEGURO // SE PREGUNTA SI ESTA SEGURO
HABLA(0,'¿Esta seguro de eliminar<br> la red <b>'+ configGeneralEMA.ConfPublicador[red].Nombre +'</b>?',"success");
$(document).off('click', '.notifyjs-foo-base .no'); // Se elimina el evento si existe $(document).off('click', '.notifyjs-foo-base .no'); // Se elimina el evento si existe
$(document).off('click', '.notifyjs-foo-base .yes'); // Se elimina el evento si existe $(document).off('click', '.notifyjs-foo-base .yes'); // Se elimina el evento si existe
HABLA(0,'¿Esta seguro de eliminar<br> la red <b>'+ configGeneralEMA.ConfPublicador[red].Nombre +'</b>?',"success"); $.notify.addStyle('foo', {
$.notify.addStyle('foo', { html:
html: "<div style='background:#ff00003b;'>" +
"<div class='clearfix'>" + "<div class='clearfix'>" +
"<div class='title' data-notify-html='title'/>" + "<div class='title' data-notify-html='title'></div>" +
"<div class='buttons'>" + "<div class='buttons' style='margin-top:10px; text-align:center;width:100%;'>" +
"<button class='no'>NO</button><button class='yes' data-notify-text='button'></button>" + "<button class='btn btn-secondary btn-sm no'>Cancelar</button> " +
"<button class='btn btn-danger btn-sm yes'>Confirmar</button>" +
"</div>" + "</div>" +
"</div>" "</div>" +
"</div>"
}); });
//PREGUNTA
// --- Mostrar notificación ---
$("#carpincho_img").notify({ $("#carpincho_img").notify({
title: '¿Esta seguro de eliminar la red '+ configGeneralEMA.ConfPublicador[red].Nombre +'?', title: '¿Está seguro de eliminar la red <b>' + configGeneralEMA.ConfPublicador[red].Nombre + '</b>?'
button: 'SI'
}, { }, {
position:"right middle", position: "right middle",
style: 'foo', style: 'foo',
autoHide: false, autoHide: false,
clickToHide: false clickToHide: false
}); });
$(document).on('click', '.notifyjs-foo-base .no', function() { $(document).on('click', '.notifyjs-foo-base .no', function() {
//RESPONDE NO //RESPONDE NO
ListarRedes(); ListarRedes();
@ -669,6 +698,50 @@ function MenuRedes(red)
break; break;
case 'Modificar': FormModificar(red); case 'Modificar': FormModificar(red);
break; break;
case 'SitioOficial':
let tipored = configGeneralEMA.ConfPublicador[red].TipoRed;
tipored = tipored.toLowerCase();
let url = '';
switch (tipored) {
case 'openweathermap':
url = 'https://openweathermap.org/';
break;
case 'wow':
url = 'https://wow.metoffice.gov.uk/';
break;
case 'windguru':
url = 'https://www.windguru.cz/';
break;
case 'windy':
url = 'https://www.windy.com/';
break;
case 'awekas':
url = 'https://www.awekas.at/';
break;
case 'wunderground':
url = 'https://www.wunderground.com/';
break;
case 'pws':
url = 'https://www.pwsweather.com/';
break;
case 'emacenter':
url = 'https://emacenter.gugler.com.ar/';
break;
case 'emacentergugler':
url = 'https://emacenter.gugler.com.ar/';
break;
default:
HABLA(0, "No se encontró el sitio oficial para la red '" + tipored + "'", "warn");
return;
}
if (url !== '') {
window.open(url, '_blank');
HABLA(0, "Abriendo sitio oficial de '" + tipored + "'.", "info");
}
ListarRedes();
break;
} }
} }
@ -865,6 +938,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;}
@ -904,7 +980,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
{ {
$.get("/verHistorico", function(data, status){ $.get("/verHistorico", function(data, status){
var TablaHTML = ''; var TablaHTML = '';

View File

@ -34,8 +34,11 @@ const express = require('express');
const fsconf = require('fs'); const fsconf = require('fs');
const EMA = require('../core/ema.js'); // Core de EMA. const EMA = require('../core/ema.js'); // Core de EMA.
const PORT = process.env.PORT || 8080; // Puerto por defecto. const PORT = process.env.PORT || 8080; // Puerto por defecto.
const os = require('os');
var app = express(); var app = express();
var server; var server;
app.use(express.json());
@ -91,6 +94,7 @@ app.get('/tamanioArchivos', function (req, res)
res.json([TamanioenMegaTD.toFixed(2),TamanioenMegaTP.toFixed(2),TamanioenMegaD.toFixed(2)]) res.json([TamanioenMegaTD.toFixed(2),TamanioenMegaTP.toFixed(2),TamanioenMegaD.toFixed(2)])
}); });
// EMA_ESTADO si es [true,''] esta encendida, si no [false,'Motivo del error']
app.get('/EMA_Estado', (req, res) => res.json(EMA.Estado())); app.get('/EMA_Estado', (req, res) => res.json(EMA.Estado()));
app.get('/EMA_EstadoUSB', function (req, res) { app.get('/EMA_EstadoUSB', function (req, res) {
EMA.EstadoUSB(function(EstadoUSB) EMA.EstadoUSB(function(EstadoUSB)
@ -99,6 +103,9 @@ app.get('/EMA_EstadoUSB', function (req, res) {
}); });
}); });
app.get('/RepeticionesConError', function (req, res) {res.json(EMA.RepeticionesConError());});
app.get('/TiempoActualRecolector', function (req, res) {res.json(EMA.TiempoActualRecolector());}); app.get('/TiempoActualRecolector', function (req, res) {res.json(EMA.TiempoActualRecolector());});
app.get('/Visor', function (req, res) { app.get('/Visor', function (req, res) {
@ -112,12 +119,23 @@ app.get('/Visor', function (req, res) {
}); });
}); });
app.get('/IncrementarRepeticionesConError', function (req, res) {
EMA.Configuracion.RepeticionesConError += 1; // Reinicio el contador de errores al iniciar el servidor web
res.json('');
});
app.get('/UltimoPublicado', function (req, res) {res.json(EMA.UltimoPublicado());}); app.get('/UltimoPublicado', function (req, res) {res.json(EMA.UltimoPublicado());});
app.get('/UltimoRegistro', function (req, res) {res.json(EMA.UltimoRegistro());}); app.get('/UltimoRegistro', function (req, res) {res.json(EMA.UltimoRegistro());});
app.get('/HayPendientes', function (req, res) {res.json(EMA.HayPendientes());}); app.get('/HayPendientes', function (req, res) {res.json(EMA.HayPendientes());});
app.get('/EstadoSensores', function (req, res) {res.json(EMA.EstadoSensores());}); app.get('/EstadoSensores', function (req, res) {res.json(EMA.EstadoSensores());});
app.get('/iniciar', function (req, res) {EMA.Conectar();res.json('ok'); }); app.get('/iniciar', function (req, res) {EMA.Conectar();res.json('ok'); });
app.get('/detener', function (req, res) {EMA.Detener();res.json('ok'); }); app.get('/detener', function (req, res) {EMA.Detener(); ;res.json('ok'); });
app.get('/purgarDebug', function (req, res) app.get('/purgarDebug', function (req, res)
{ {
fsconf.writeFile('logs/debug.log', '',{encoding: 'utf8', autoClose: true}, function(err) fsconf.writeFile('logs/debug.log', '',{encoding: 'utf8', autoClose: true}, function(err)
@ -154,6 +172,30 @@ app.get('/GuardarConf/:configuracion_nueva', function (req, res)
res.json('ok'); res.json('ok');
}); });
app.post('/GuardarConf', function (req, res) {
if (!req.body || !req.body.configuracion) {
return res.status(400).json({ ok: false, error: 'Configuración no recibida' });
}
const configuracion_nueva =
'// Configuraciones generales de EMA RECOLECTOR\n\n' +
'module.exports = ' +
JSON.stringify(req.body.configuracion, null, 2) +
';\n';
fsconf.writeFile('./conf/ConfiguracionGeneral.js', configuracion_nueva, function (err) {
if (err) {
EMA.RegistrarLog("0|CORE|❌ Error al guardar configuración");
return res.status(500).json({ ok: false });
}
EMA.Reconfigurar();
EMA.RegistrarLog("0|CORE|✅ Configuración guardada correctamente");
res.json({ ok: true });
});
});
app.get('/VerHistorico', function (req, res) app.get('/VerHistorico', function (req, res)
{ {
var Archivo = fsconf.readFileSync('./logs/registro_diario.log', {encoding: 'utf8', autoClose: true}); var Archivo = fsconf.readFileSync('./logs/registro_diario.log', {encoding: 'utf8', autoClose: true});
@ -166,6 +208,11 @@ app.get('/verLogs', function (req, res)
res.json(Archivo); res.json(Archivo);
}) })
app.get('/interfaces', (req, res) => {
const interfaces = os.networkInterfaces();
res.json(interfaces);
});
app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); next();}); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); next();});
app.use(express.static('gui_web')); app.use(express.static('gui_web'));
@ -179,21 +226,19 @@ app.use('/css', express.static(__dirname + '/../gui_common/css'));
// IMG // IMG
app.use('/images', express.static(__dirname + '/../node_modules/datatables/media/images')); app.use('/images', express.static(__dirname + '/../node_modules/datatables/media/images'));
app.use('/iconos', express.static(__dirname + '/../gui_common/iconos')); app.use('/gui_common/iconos', express.static(__dirname + '/../gui_common/iconos'));
app.use('/img', express.static(__dirname + '/../gui_common/img')); app.use('/gui_common/img', express.static(__dirname + '/../gui_common/img'));
// JS // JS
app.use('/js', express.static(__dirname + '/../node_modules/jquery/dist')); app.use('/js', express.static(__dirname + '/../node_modules/jquery/dist'));
app.use('/js', express.static(__dirname + '/../node_modules/popper.js/dist/umd')); app.use('/js', express.static(__dirname + '/../node_modules/popper.js/dist/umd'));
app.use('/js', express.static(__dirname + '/../node_modules/bootstrap/dist/js')); app.use('/js', express.static(__dirname + '/../node_modules/bootstrap/dist/js'));
app.use('/js', express.static(__dirname + '/../node_modules/bootstrap-select/dist/js')); app.use('/js', express.static(__dirname + '/../node_modules/bootstrap-select/dist/js'));
app.use('/js', express.static(__dirname + '/../node_modules/datatables/media/js')); app.use('/js', express.static(__dirname + '/../node_modules/datatables/media/js'));
app.use('/js', express.static(__dirname + '/../node_modules/chart.js/dist'));
app.use('/js', express.static(__dirname + '/../node_modules/notify-js-lib/dist')); app.use('/js', express.static(__dirname + '/../node_modules/notify-js-lib/dist'));
app.use('/js', express.static(__dirname + '/../node_modules/nprogress')); app.use('/js', express.static(__dirname + '/../node_modules/nprogress'));
app.use('/js', express.static(__dirname + '/../node_modules/datatables-buttons/js')); app.use('/js', express.static(__dirname + '/../node_modules/datatables-buttons/js'));
app.use('/js', express.static(__dirname + '/../gui_common/libs/RGraph')); app.use('/js', express.static(__dirname + '/../gui_common/libs/RGraph'));
app.use('/controlador', express.static(__dirname + '/../gui_common/controlador'));
app.get('/', function (req, res) {res.sendFile(__dirname + "/index.html");}); app.get('/', function (req, res) {res.sendFile(__dirname + "/index.html");});
@ -202,25 +247,54 @@ app.get('/', function (req, res) {res.sendFile(__dirname + "/index.html");});
function EncenderServidoreIniciar() { function EncenderServidoreIniciar() {
// Se espera 5 segundo y se inicia el recolector en modo web // Se espera 5 segundo y se inicia el recolector en modo web
server = app.listen(PORT); server = app.listen(PORT, () => {
console.log('Ingrese al sistema por su navegador 127.0.0.1:'+PORT+' o IP:'+PORT); // Obtener todas las interfaces de red
const interfaces = os.networkInterfaces();
console.log("\nServidor disponible en las siguientes direcciones:");
// Recorrer todas las interfaces e IPs
for (const interfaceName in interfaces) {
interfaces[interfaceName].forEach((interface) => {
// Mostrar solo IPv4 y omitir direcciones internas
if (interface.family === 'IPv4') {
console.log(`http://${interface.address}:${PORT}`);
}
});
}
});
setTimeout(function(){console.log("Se inicio el recolector automaticamente.");EMA.Conectar();}, 5000); setTimeout(function(){console.log("Se inicio el recolector automaticamente.");EMA.Conectar();}, 5000);
} }
function EncenderServidor() { function EncenderServidor() {
// Se inicia el servidor solamente // Se inicia el servidor solamente
server = app.listen(PORT); server = app.listen(PORT, () => {
// Se consulta si esta activado el iniciar automaticamente y si es asi, se prende el recolector // Obtener todas las interfaces de red
const interfaces = os.networkInterfaces();
console.log("\nServidor disponible en las siguientes direcciones:");
// Recorrer todas las interfaces e IPs
for (const interfaceName in interfaces) {
interfaces[interfaceName].forEach((interface) => {
// Mostrar solo IPv4 y omitir direcciones internas
if (interface.family === 'IPv4') {
console.log(`http://${interface.address}:${PORT}`);
}
});
}
});
// Se consulta si esta activado el iniciar automaticamente y si es asi, se prende el recolector
var configGeneralEMA = null; var configGeneralEMA = null;
configGeneralEMA = eval(fsconf.readFileSync('conf/ConfiguracionGeneral.js')+''); configGeneralEMA = eval(fsconf.readFileSync('conf/ConfiguracionGeneral.js')+'');
IniciarAutomaticamente = configGeneralEMA.ConfGeneral.inicio_automatico; IniciarAutomaticamente = configGeneralEMA.ConfGeneral.inicio_automatico;
console.log(""); console.log("");
if(IniciarAutomaticamente) if(IniciarAutomaticamente) {
{console.log("Configuración de Inicio: "+ IniciarAutomaticamente + " --> Se esta iniciando el recolector automaticamente en 5 segundos...");setTimeout(function(){EMA.Conectar();}, 5000) console.log("Configuración de Inicio: "+ IniciarAutomaticamente + " --> Se esta iniciando el recolector automaticamente en 5 segundos...");
}else{ console.log("Configuración de Inicio: "+ IniciarAutomaticamente);} setTimeout(function(){EMA.Conectar();}, 5000);
console.log(""); } else {
console.log('Ingrese al sistema por su navegador 127.0.0.1:'+PORT+' o IP:'+PORT); console.log("Configuración de Inicio: "+ IniciarAutomaticamente);
}
} }
function DetenerServidor() {server.close();} function DetenerServidor() {server.close();}

View File

@ -5,7 +5,7 @@
<meta CHARSET="UTF-8"> <meta CHARSET="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EMA Libre Cliente (Carpincho)</title> <title>EMA Libre Cliente (Carpincho)</title>
<link rel="icon" type="image/png" href="iconos/icono_app.png" sizes="16x16"> <link rel="icon" type="image/png" href="gui_common/iconos/icono_app.png" sizes="16x16">
<!-- Estilos varios css --> <!-- Estilos varios css -->
<link rel="stylesheet" type="text/css" href="/css/jquery.dataTables.min.css" /> <link rel="stylesheet" type="text/css" href="/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
@ -36,7 +36,6 @@
<script type="text/javascript" src="js/RGraph.gauge.js"></script> <script type="text/javascript" src="js/RGraph.gauge.js"></script>
<script type="text/javascript" src="js/RGraph.odo.js"></script> <script type="text/javascript" src="js/RGraph.odo.js"></script>
<script type="text/javascript" src="js/RGraph.drawing.image.js"></script> <script type="text/javascript" src="js/RGraph.drawing.image.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<!-- Barra de progreso --> <!-- Barra de progreso -->
<script type="text/javascript" src="js/nprogress.js"></script> <script type="text/javascript" src="js/nprogress.js"></script>
<!-- Libreria Notificaciones emergentes --> <!-- Libreria Notificaciones emergentes -->
@ -51,7 +50,7 @@
<div class="progressinicio"> <div class="progressinicio">
<div style="width:100%"> <div style="width:100%">
</br> </br> </br> </br> </br> </br> </br> </br> </br> </br>
<img id="loadinicio" align="center" src="iconos/icono_app.webp" height="120px" width="140px"> <img id="loadinicio" align="center" src="gui_common/iconos/icono_app.webp" height="120px" width="140px">
</br></br> <h1><b> EMA Libre Cliente</b> </br> (Carpincho)</br>Licencia GPLv3</h1> </br></br> <h1><b> EMA Libre Cliente</b> </br> (Carpincho)</br>Licencia GPLv3</h1>
</div> </div>
</div> </div>
@ -59,12 +58,12 @@
<div id="principal" style="display: none;"> <div id="principal" style="display: none;">
<nav style="-webkit-app-region: drag;cursor: all-scroll" class="navbar stylish-color fixed-top scrolling-navbar "> <nav style="-webkit-app-region: drag;cursor: all-scroll" class="navbar stylish-color fixed-top scrolling-navbar ">
<span style="-webkit-app-region: no-drag;color: #ffffff;" data-toggle="tooltip" data-placement="bottom" style="font-size: 15px;"><img id="signal" class="" src="img/signal.webp" height="16px" width="16px" data-toggle="tooltip" <span style="-webkit-app-region: no-drag;color: #ffffff;" data-toggle="tooltip" data-placement="bottom" style="font-size: 15px;"><img id="signal" class="" src="gui_common/img/signal.webp" height="16px" width="16px" data-toggle="tooltip"
data-placement="right" data-html="true" title="Señal RF de la estación"> EMA Libre Cliente </span> data-placement="right" data-html="true" title="Señal RF de la estación"> EMA Libre Cliente </span>
<spam id="mensajebarra" class="float-center" style="color:white"></spam> <spam id="mensajebarra" class="float-center" style="color:white"></spam>
<span style="-webkit-app-region: no-drag" class="float-right"> <span style="-webkit-app-region: no-drag" class="float-right">
<i class="custom-controls menu" data-toggle="tooltip" data-placement="bottom" role="menusup" aria-controls="Wzoomout" style="font-size: 15px;" title="Disminuir"><img id="Wzoomout" height="16px" width="16px" src="iconos/zoomout.webp"></i> <i class="custom-controls menu" data-toggle="tooltip" data-placement="bottom" role="menusup" aria-controls="Wzoomout" style="font-size: 15px;" title="Disminuir"><img id="Wzoomout" height="16px" width="16px" src="gui_common/iconos/zoomout.webp"></i>
<i class="custom-controls menu" data-toggle="tooltip" data-placement="bottom" role="menusup" aria-controls="Wzoomin" style="font-size: 15px;" title="Aumentar" ><img id="Wzoomin" height="16px" width="16px" src="iconos/zoomin.webp"></i> <i class="custom-controls menu" data-toggle="tooltip" data-placement="bottom" role="menusup" aria-controls="Wzoomin" style="font-size: 15px;" title="Aumentar" ><img id="Wzoomin" height="16px" width="16px" src="gui_common/iconos/zoomin.webp"></i>
</span> </span>
</nav> </nav>
<br><br> <br><br>
@ -75,7 +74,7 @@
<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="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-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>
</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>
@ -99,33 +98,33 @@
<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">
<li class="nav-item active "> <li class="nav-item active ">
<a class="nav-link active show" id="inicio-tab" data-toggle="tab" data-target="#inicio" role="tab" aria-controls="inicio" aria-selected="true"><img height="24px" width="24px" src="img/home.webp" aria-controls="inicio"> INICIO</a> <a class="nav-link active show" id="inicio-tab" data-toggle="tab" data-target="#inicio" role="tab" aria-controls="inicio" aria-selected="true"><img height="24px" width="24px" src="gui_common/img/home.webp" aria-controls="inicio"> INICIO</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" id="interior-tab" data-toggle="tab" data-target="#interior" role="tab" aria-controls="interior" aria-selected="false"><img height="24px" width="24px" src="img/interior.webp" aria-controls="interior"> INTERIOR</a> <a class="nav-link" id="interior-tab" data-toggle="tab" data-target="#interior" role="tab" aria-controls="interior" aria-selected="false"><img height="24px" width="24px" src="gui_common/img/interior.webp" aria-controls="interior"> INTERIOR</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" id="exterior-tab" data-toggle="tab" data-target="#exterior" role="tab" aria-controls="exterior" aria-selected="false"><img height="24px" width="24px" src="img/exterior.webp" aria-controls="exterior"> EXTERIOR</a> <a class="nav-link" id="exterior-tab" data-toggle="tab" data-target="#exterior" role="tab" aria-controls="exterior" aria-selected="false"><img height="24px" width="24px" src="gui_common/img/exterior.webp" aria-controls="exterior"> EXTERIOR</a>
</li> </li>
<li class="nav-item"> <!-- <li class="nav-item">
<a class="nav-link" id="estadisticas-tab" data-toggle="tab" data-target="#estadisticas" role="tab" aria-controls="estadisticas" aria-selected="false"><img height="24px" width="24px" src="img/estadistica.png" aria-controls="estadisticas"> ESTADISTICAS</a> <a class="nav-link" id="estadisticas-tab" data-toggle="tab" data-target="#estadisticas" role="tab" aria-controls="estadisticas" aria-selected="false"><img height="24px" width="24px" src="img/estadistica.png" aria-controls="estadisticas"> ESTADISTICAS</a>
</li> -->
<li class="nav-item">
<a class="nav-link" id="redes-tab" data-toggle="tab" data-target="#redes" role="tab" aria-controls="redes" aria-selected="false"><img height="24px" width="24px" src="gui_common/img/redes.webp" aria-controls="redes"> REDES</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" id="redes-tab" data-toggle="tab" data-target="#redes" role="tab" aria-controls="redes" aria-selected="false"><img height="24px" width="24px" src="img/redes.webp" aria-controls="redes"> REDES</a> <a class="nav-link" id="configuracion-tab" data-toggle="tab" data-target="#configuracion" role="tab" aria-controls="configuracion" aria-selected="false"><img height="24px" width="24px" src="gui_common/img/config.webp" aria-controls="configuracion"> CONFIGURACIÓN</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" id="configuracion-tab" data-toggle="tab" data-target="#configuracion" role="tab" aria-controls="configuracion" aria-selected="false"><img height="24px" width="24px" src="img/config.webp" aria-controls="configuracion"> CONFIGURACIÓN</a> <a class="nav-link" id="contacto-tab" data-toggle="tab" data-target="#contacto" target="_self" role="tab" aria-controls="contacto" aria-selected="false"><img height="24px" width="24px" src="gui_common/img/about.webp" aria-controls="contacto"> CONTACTO</a>
</li>
<li class="nav-item">
<a class="nav-link" id="contacto-tab" data-toggle="tab" data-target="#contacto" target="_self" role="tab" aria-controls="contacto" aria-selected="false"><img height="24px" width="24px" src="img/about.webp" aria-controls="contacto"> CONTACTO</a>
</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='./img/animadas/cargando2.gif' width='100' height='100' /> <br><br><br><br> </div> <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 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>
<div class="tab-pane fade text-center" id="estadisticas" role="tabpanel" aria-badgeledby="estadisticas-tab"></div> <!-- <div class="tab-pane fade text-center" id="estadisticas" role="tabpanel" aria-badgeledby="estadisticas-tab"></div>-->
<div class="tab-pane fade text-center" id="configuracion" role="tabpanel" aria-badgeledby="configuracion-tab"></div> <div class="tab-pane fade text-center" id="configuracion" role="tabpanel" aria-badgeledby="configuracion-tab"></div>
<div class="tab-pane fade text-center" id="redes" role="tabpanel" aria-badgeledby="redes-tab"></div> <div class="tab-pane fade text-center" id="redes" role="tabpanel" aria-badgeledby="redes-tab"></div>
<div class="tab-pane fade" id="contacto" role="tabpanel" aria-badgeledby="contacto-tab"></div> <div class="tab-pane fade" id="contacto" role="tabpanel" aria-badgeledby="contacto-tab"></div>
@ -179,6 +178,19 @@
MenuGUI('inicio'); MenuGUI('inicio');
}); });
window.onload = function() {redimensionarInicio(); NProgress.configure({ showSpinner: false });NProgress.done(); }; window.onload = function() {
$.get("/EMA_estado", async function(data, status){
if(data[0]===true){
console.log("EMA Libre Cliente ya esta recolectando...");
INICIAR();
} else {
//console.error("EMA Libre no esta recolectado ");
}
});
redimensionarInicio();
NProgress.configure({ showSpinner: false });
NProgress.done();
};
</script> </script>

View File

@ -1,211 +1,239 @@
<div class="col-centered"> <div class="col-centered">
<h1>Configuración General</h1> <h1>Configuración General</h1>
<div class="row">
<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 class="row">
<div class="col-4 col-centered">
<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">
<optgroup label="Recolector">
<option value="Recolector_USB">Recolector USB</option>
<option value="Recolector_IP">Recolector IP/WIFI</option>
</optgroup>
<optgroup label="Visor">
<option value="Visor">Visor Llave</option>
</optgroup>
</select>
</div>
<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>
<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">
<option value="Activado">Activado</option>
<option value="Desactivado">Desactivado</option>
</optgroup>
</select>
</div>
<div class="col-2 col-centered">
<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">
<optgroup label="Notificar de carpincho">
<option value="Activado">Activado</option>
<option value="Desactivado">Desactivado</option>
</optgroup>
</select>
</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 class="col-3 col-centered" id="vocesAudioDiv">
<label class="control-label">Voz del Audio</label></br>
<select id='vocesAudio' name="vocesAudio" class="selectpicker show-tick" data-width="fit" data-style="btn-primary" size="100">
<optgroup label="Lista de Voces">
</optgroup>
</select>
</div>
</div>
<hr class="hr-suave">
<div class="row">
<div class="col-2 col-centered">
<label class="control-label">Recolección</label><br>
<select id='Tiempo_de_Recoleccion' name="Tiempo_de_Recoleccion" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Muy Rapido">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</optgroup>
<optgroup label="Medio">
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
</optgroup>
<optgroup label="Normal">
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</optgroup>
<optgroup label="Despacio">
<option value="110">110</option>
<option value="120">120</option>
<option value="130">130</option>
<option value="140">140</option>
</optgroup>
</select>
</div>
<div class="col-3 col-centered">
<label class="control-label">Debug y Tamaño</label><br>
<select id='Debug' name="Debug" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Normal">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</optgroup>
<optgroup label="Alto">
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</optgroup>
<optgroup label="Muy Alto">
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</optgroup>
</select>
<input type="text" class="btn btn-primary" id="debugMB" placeholder="MB Debug" maxlength="4" size="5">
<label class="control-label">MB</label>
</div>
<div class="col-1 col-centered">
<label class="control-label">UTC</label><br>
<select id='utc' name="utc" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Negativo">
<option value="-1">-1</option>
<option value="-2">-2</option>
<option value="-3">-3</option>
<option value="-4">-4</option>
<option value="-5">-5</option>
<option value="-6">-6</option>
<option value="-7">-7</option>
<option value="-8">-8</option>
<option value="-9">-9</option>
<option value="-10">-10</option>
<option value="-11">-11</option>
<option value="-12">-12</option>
</optgroup>
<optgroup label="Neutro">
<option value="0">0</option>
</optgroup>
<optgroup label="Positivo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</optgroup>
</select>
</div>
<div class="col-2 col-centered">
<label class="control-label">Unidades</label><br>
<select id='SistemaMetrico' name="SistemaMetrico" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Sistema Internacional de Unidades(SI)">
<option value="SI">º C</option>
</optgroup>
<optgroup label="Sistema Anglosajón de Unidades(SA)">
<option value="SA">º F</option>
</optgroup>
</select>
</div>
</div>
<hr class="hr-suave">
<div class="row">
<div class="col-3 col-centered">
<label class="control-label">SMTP TIPO</label><br>
<select id='Tipo_SMTP' name="Tipo_SMTP" onchange="MenuConfig();" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="SMTP Deshabilitado">
<option value="Deshabilitado">Deshabilitado</option>
</optgroup>
<optgroup label="SMTP Proveedor">
<option value="Gmail">GMAIL</option>
<option value="Yahoo">YAHOO</option>
<option value="Hotmail">OUTLOOK</option>
</optgroup>
<optgroup label="SMTP Manual">
<option value="Manual">SMTP CONFIG</option>
</select>
</div>
<div class="col-3 col-centered">
<label class="control-label">Cuenta</label><br>
<input type="email" class="btn btn-primary" id="Usuario_SMTP" placeholder="Cuenta" maxlength="40" size="16">
</div>
<div class="col-3 col-centered">
<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">
</div>
<div class="col-2 col-centered" id="Server">
<label class="control-label">Server</label><br>
<input type="text" class="btn btn-primary" id="Server_SMTP" placeholder="Server" maxlength="40" size="15">
</div>
<div class="col-1 col-centered" id="puerto">
<label class="control-label">Puerto</label><br>
<input type="text" class="btn btn-primary" id="Puerto_SMTP" placeholder="Puerto" maxlength="4" size="5">
</div>
</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="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-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 class="row">
<div class="col-3" align="left" style="vertical-align:top;"></div> </div>
<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> <div id="bloque_por_IP_WIFI" class="row">
<input type="text" class="btn btn-primary" id="NombreEstacion" autocomplete='name' placeholder="Ingrese el nombre" maxlength="20" size="25"></br></br>
<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>
</div>
<div class="row">
<div class="col-3 col-centered">
<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">
<optgroup label="Recolector USB">
<option value="Recolector">Recolector</option>
</optgroup>
<optgroup label="Visor por Llave">
<option value="Visor">Visor</option>
</optgroup>
</select>
</div>
<div class="col-3 col-centered">
<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">
<optgroup label="Iniciar el recolector/visor con el aplicativo">
<option value="Activado">Activado</option>
<option value="Desactivado">Desactivado</option>
</optgroup>
</select>
</div>
<div class="col-3 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>
<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">
<option value="Activado">Activado</option>
<option value="Desactivado">Desactivado</option>
</optgroup>
</select>
</div>
</div>
<hr>
<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 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">
<optgroup label="Lista de Voces">
</optgroup>
</select>
</div>
</div>
<hr>
<div class="row">
<div class="col-2 col-centered">
<label class="control-label">Recolección</label><br>
<select id='Tiempo_de_Recoleccion' name="Tiempo_de_Recoleccion" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Muy Rapido">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</optgroup>
<optgroup label="Medio">
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
</optgroup>
<optgroup label="Normal">
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</optgroup>
<optgroup label="Despacio">
<option value="110">110</option>
<option value="120">120</option>
<option value="130">130</option>
<option value="140">140</option>
</optgroup>
</select>
</div>
<div class="col-3 col-centered">
<label class="control-label">Debug y Tamaño</label><br>
<select id='Debug' name="Debug" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Normal">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</optgroup>
<optgroup label="Alto">
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</optgroup>
<optgroup label="Muy Alto">
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</optgroup>
</select>
<input type="text" class="btn btn-primary" id="debugMB" placeholder="MB Debug" maxlength="4" size="5">
<label class="control-label">MB</label>
</div>
<div class="col-1 col-centered">
<label class="control-label">UTC</label><br>
<select id='utc' name="utc" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Negativo">
<option value="-1">-1</option>
<option value="-2">-2</option>
<option value="-3">-3</option>
<option value="-4">-4</option>
<option value="-5">-5</option>
<option value="-6">-6</option>
<option value="-7">-7</option>
<option value="-8">-8</option>
<option value="-9">-9</option>
<option value="-10">-10</option>
<option value="-11">-11</option>
<option value="-12">-12</option>
</optgroup>
<optgroup label="Neutro">
<option value="0">0</option>
</optgroup>
<optgroup label="Positivo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</optgroup>
</select>
</div>
<div class="col-2 col-centered">
<label class="control-label">Unidades</label><br>
<select id='SistemaMetrico' name="SistemaMetrico" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="Sistema Internacional de Unidades(SI)">
<option value="SI">º C</option>
</optgroup>
<optgroup label="Sistema Anglosajón de Unidades(SA)">
<option value="SA">º F</option>
</optgroup>
</select>
</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>
<hr>
<div class="row">
<div class="col-3 col-centered">
<label class="control-label">SMTP TIPO</label><br>
<select id='Tipo_SMTP' name="Tipo_SMTP" onchange="MenuConfig();" class="selectpicker show-tick" data-width="fit" data-style="btn-primary">
<optgroup label="SMTP Deshabilitado">
<option value="Deshabilitado">Deshabilitado</option>
</optgroup>
<optgroup label="SMTP Proveedor">
<option value="Gmail">GMAIL</option>
<option value="Yahoo">YAHOO</option>
<option value="Hotmail">OUTLOOK</option>
</optgroup>
<optgroup label="SMTP Manual">
<option value="Manual">SMTP CONFIG</option>
</select>
</div>
<div class="col-3 col-centered">
<label class="control-label">Cuenta</label><br>
<input type="email" class="btn btn-primary" id="Usuario_SMTP" placeholder="Cuenta" maxlength="40" size="16">
</div>
<div class="col-3 col-centered">
<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="-">
</div>
<div class="col-2 col-centered" id="Server">
<label class="control-label">Server</label><br>
<input type="text" class="btn btn-primary" id="Server_SMTP" placeholder="Server" maxlength="40" size="15">
</div>
<div class="col-1 col-centered" id="puerto">
<label class="control-label">Puerto</label><br>
<input type="text" class="btn btn-primary" id="Puerto_SMTP" placeholder="Puerto" maxlength="4" size="5">
</div>
</div><br>
<div class="row">
<div class="col-12 col-centered">
<button type="button" id="botonguardar" class="btn btn-sm btn-success" onclick="GuardarConf('conf')" role="button">Guardar</button>
</div>
</div> </div>
</div> </div>
<hr class="hr-suave">
<div class="row">
<div class="col-12 col-centered">
<button type="button" id="botonguardar" class="btn btn-sm btn-success" onclick="GuardarConf('conf')" role="button">Guardar</button>
</div>
</div>

View File

@ -2,8 +2,8 @@
<div class="row"> <div class="row">
<div class="col-3 col-centered "> <div class="col-3 col-centered ">
<br> <br><br> <br> <br><br>
<img src="img/icono_inicio.webp" onclick="HABLA(0,'Porque me estas tocando?','info');" onmouseover="GUIÑA(0);"></br></br></br> <img src="gui_common/img/icono_inicio.webp" onclick="HABLA(0,'Porque me estas tocando?','info');" onmouseover="GUIÑA(0);"></br></br></br>
<img src="img/LogoLGPLv3.webp"> <img src="gui_common/img/LogoLGPLv3.webp">
</div> </div>
<div class="col-9"> <div class="col-9">
<div class="row"> <div class="row">
@ -17,10 +17,10 @@
</div> </div>
<div class="row"> <div class="row">
<div class="col-8"> <div class="col-8">
<h4><img src="img/ok.webp" height="25" width="25"><strong>Software: </strong>EMA Libre Cliente (Carpincho)</h4> <h4><img src="gui_common/img/ok.webp" height="25" width="25"><strong>Software: </strong>EMA Libre Cliente (Carpincho)</h4>
<h4><img src="img/ok.webp" height="25" width="25"><strong>Versión: </strong><span id="versioncontacto">-</span></h4> <h4><img src="gui_common/img/ok.webp" height="25" width="25"><strong>Versión: </strong><span id="versioncontacto">-</span></h4>
<h4><img src="img/ok.webp" height="25" width="25"><strong>Sitio Oficial: </strong> <a style="color: #1155cc;">https://ema.gugler.com.ar</a> </h4> <h4><img src="gui_common/img/ok.webp" height="25" width="25"><strong>Sitio Oficial: </strong> <a style="color: #1155cc;">https://ema.gugler.com.ar</a> </h4>
<h4><img src="img/ok.webp" height="25" width="25"><strong>Licencia: </strong>GPLv3</h4> <h4><img src="gui_common/img/ok.webp" height="25" width="25"><strong>Licencia: </strong>GPLv3</h4>
</div> </div>
<div class="col-4 col-centered"><br><br><br> <div class="col-4 col-centered"><br><br><br>
<button id="botonactualizar" class="btn btn-sm btn-success" onclick="Actualizar()" role="button">Actualizar</button> <button id="botonactualizar" class="btn btn-sm btn-success" onclick="Actualizar()" role="button">Actualizar</button>
@ -31,12 +31,12 @@
</div> </div>
<hr> <hr>
<div class="row"> <div class="row">
<div class="d-block d-md-none d-lg-block col-3 col-centered"><img src="img/logo_gugler_lab.webp"> </div> <div class="d-block d-md-none d-lg-block col-3 col-centered"><img src="gui_common/img/logo_gugler_lab.webp"> </div>
<div class="d-block d-md-none d-lg-block col-9" style="height:10"> <div class="d-block d-md-none d-lg-block col-9" style="height:10">
<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="gui_common/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="gui_common/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="gui_common/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

@ -7,8 +7,11 @@
<br><br> <img src='./img/animadas/cargando2.gif' width='40' height='40' /> <br> <small>Cargando Gráfico...</small> <br><br> <img src='./img/animadas/cargando2.gif' width='40' height='40' /> <br> <small>Cargando Gráfico...</small>
</div> </div>
<div id="inicio_estadisticas"> <div id="inicio_estadisticas">
<canvas id="graph_inicio" style="height:50vh; width:80vw" ></canvas> <canvas id="graph_inicio" style="width:100%; height:400px; max-width:80vw; max-height:50vh;"></canvas>
</div> </div>
<button id="diag_toggle_canvas" class="btn btn-sm btn-warning" onclick="(function(){var c=document.getElementById('graph_inicio'); if(c.style.display==='none'){c.style.display='block';} else {c.style.display='none';}})()">Toggle Canvas</button>
<button id="diag_enable_graphs" class="btn btn-sm btn-success" onclick="(function(){ try { window._ENABLE_GRAPHICS = true; console.log('Graphics enabled'); graficoEstadisticas(); } catch(e){console.error(e);} })()">Enable Graphs</button>
<button id="diag_paint_test" class="btn btn-sm btn-info" onclick="(function(){ try { if(window._testCanvasPaint){ window._testCanvasPaint(); } else { console.warn('_testCanvasPaint no disponible'); } } catch(e){console.error(e);} })()">Canvas Paint Test</button>
<div id="grafico" style="background-color:#182c3e00; display:none" > <div id="grafico" style="background-color:#182c3e00; display:none" >
<canvas id="graph" style="height:50vh; width:80vw" ></canvas> <canvas id="graph" style="height:50vh; width:80vw" ></canvas>
@ -19,7 +22,7 @@
function Mostrar() function Mostrar()
{ {
document.getElementById("grafico").style.display = "block"; document.getElementById("grafico").style.display = "block";
document.getElementById("inicio_estadisticas").style.display = "hidden"; document.getElementById("inicio_estadisticas").style.display = "none";
document.getElementById("inicio_estadisticas").hidden = true; document.getElementById("inicio_estadisticas").hidden = true;
document.getElementById("boton_grafico").hidden = true; document.getElementById("boton_grafico").hidden = true;
document.getElementById("boton_volver").hidden = false; document.getElementById("boton_volver").hidden = false;

View File

@ -17,7 +17,7 @@
</div> </div>
<div class="col-6 col-centered align-self-center "> <div class="col-6 col-centered align-self-center ">
<div class="short-div col-centered "> <div class="short-div col-centered ">
<h3 align="center"><img src="img/clima/temperatura.webp" width="13" height="13"> Temperatura</h3> <h3 align="center"><img src="gui_common/img/clima/temperatura.webp" width="13" height="13"> Temperatura</h3>
<div class="zoom"> <div class="zoom">
<h1><span id='temp_ext' class="badge badge-success">- </span></h1> <h1><span id='temp_ext' class="badge badge-success">- </span></h1>
<h4><span id='temp_ext_max' class="badge badge-danger" title="Maxíma Diaria">-</span> <h4><span id='temp_ext_max' class="badge badge-danger" title="Maxíma Diaria">-</span>
@ -25,7 +25,7 @@
</div> </div>
</div> </div>
<div class="short-div col-centered "><br> <div class="short-div col-centered "><br>
<h4 align="center"><img src="img/clima/luxer.webp" width="13" height="13"> Iluminancia </h4> <h4 align="center"><img src="gui_common/img/clima/luxer.webp" width="13" height="13"> Iluminancia </h4>
<div class="zoom"> <div class="zoom">
<h1><span id='luxer_ext' class="badge badge-primary">-</span></h1> <h1><span id='luxer_ext' class="badge badge-primary">-</span></h1>
<h4><span id='luxer_ext_max' class="badge badge-danger" title="Maxíma Diaria">-</span> <h4><span id='luxer_ext_max' class="badge badge-danger" title="Maxíma Diaria">-</span>
@ -35,7 +35,7 @@
</div> </div>
<div class="col-6 col-centered align-self-center "> <div class="col-6 col-centered align-self-center ">
<div class="short-div col-centered"> <div class="short-div col-centered">
<h3 align="center"><img src="img/clima/humedad.webp" width="13" height="13">Humedad</h3> <h3 align="center"><img src="gui_common/img/clima/humedad.webp" width="13" height="13">Humedad</h3>
<div class="zoom"> <div class="zoom">
<h1><span id='hum_ext' class="badge badge-success">-</span></h1> <h1><span id='hum_ext' class="badge badge-success">-</span></h1>
<h4> <h4>
@ -46,7 +46,7 @@
</div> </div>
<div class="short-div col-centered"> <div class="short-div col-centered">
<br> <br>
<h4 align="center"><img src="img/clima/rocio.webp" width="13" height="13">Pto. de Rocio</h4> <h4 align="center"><img src="gui_common/img/clima/rocio.webp" width="13" height="13">Pto. de Rocio</h4>
<div class="zoom"> <div class="zoom">
<h1><span id='punto_ext' class="badge badge-primary">-</span></h1> <h1><span id='punto_ext' class="badge badge-primary">-</span></h1>
<h4> <h4>
@ -81,7 +81,7 @@
</div> </div>
</div> </div>
<div class="col-2 col-centered"> <div class="col-2 col-centered">
<h4 align="center"><img src="img/clima/uv2.webp" width="13" height="13"> Rayos UV </h4> <h4 align="center"><img src="gui_common/img/clima/uv2.webp" width="13" height="13"> Rayos UV </h4>
<div class="zoom"> <div class="zoom">
<h1><span id='rayos_ext' class="badge badge-primary">-</span></h1> <h1><span id='rayos_ext' class="badge badge-primary">-</span></h1>
<h4> <h4>
@ -91,7 +91,7 @@
</div> </div>
</div> </div>
<div class="col-2 col-centered"> <div class="col-2 col-centered">
<h4 align="center"><img src="img/clima/presion.webp" width="13" height="13"> Presión R. </h4> <h4 align="center"><img src="gui_common/img/clima/presion.webp" width="13" height="13"> Presión R. </h4>
<div class="zoom"> <div class="zoom">
<h1><span id='presionr_ext' class="badge badge-primary">-</span></h1> <h1><span id='presionr_ext' class="badge badge-primary">-</span></h1>
<h4> <h4>
@ -116,25 +116,25 @@
<div class="col-3 col-centered" title="Lluvia acumulada en 10 minutos"> <div class="col-3 col-centered" title="Lluvia acumulada en 10 minutos">
<h4 align="center">Lluvia Actual</h4> <h4 align="center">Lluvia Actual</h4>
<div class="zoom"> <div class="zoom">
<h1><img src="img/clima/lluvia.webp"> <span id='lloviendo_ext' class="badge badge-info">-</span><br><span id="lloviendo_ext_img" class="small"></span></h1> <h1><img src="gui_common/img/clima/lluvia.webp"> <span id='lloviendo_ext' class="badge badge-info">-</span><br><span id="lloviendo_ext_img" class="small"></span></h1>
</div> </div>
</div> </div>
<div class="col-3 col-centered" title="Lluvia acumulada en la hora actual"> <div class="col-3 col-centered" title="Lluvia acumulada en la hora actual">
<h4 align="center">Lluvia Hora</h4> <h4 align="center">Lluvia Hora</h4>
<div class="zoom"> <div class="zoom">
<h1><img src="img/clima/lluvia.webp"> <span id='totalacuhora_ext' class="badge badge-info">-</span><br><span id="totalacuhora_ext_img" class="small"></span></h1> <h1><img src="gui_common/img/clima/lluvia.webp"> <span id='totalacuhora_ext' class="badge badge-info">-</span><br><span id="totalacuhora_ext_img" class="small"></span></h1>
</div> </div>
</div> </div>
<div class="col-3 col-centered" title="Lluvia acumulada en el día actual"> <div class="col-3 col-centered" title="Lluvia acumulada en el día actual">
<h4 align="center">Lluvia Día</h4> <h4 align="center">Lluvia Día</h4>
<div class="zoom"> <div class="zoom">
<h1><img src="img/clima/lluvia.webp"> <span id='totalacudia_ext' class="badge badge-info">-</span><br><span id="totalacudia_ext_img" class="small"></span></h1> <h1><img src="gui_common/img/clima/lluvia.webp"> <span id='totalacudia_ext' class="badge badge-info">-</span><br><span id="totalacudia_ext_img" class="small"></span></h1>
</div> </div>
</div> </div>
<div class="col-3 col-centered" title="Lluvia acumulada total"> <div class="col-3 col-centered" title="Lluvia acumulada total">
<h4 align="center">Lluvia Total</h4> <h4 align="center">Lluvia Total</h4>
<div class="zoom"> <div class="zoom">
<h1><img src="img/clima/lluvia.webp"><span id='totalL_ext' class="badge badge-info">-</span><br><span id="totalacudia_ext_img" class="small"></span></h1> <h1><img src="gui_common/img/clima/lluvia.webp"><span id='totalL_ext' class="badge badge-info">-</span><br><span id="totalacudia_ext_img" class="small"></span></h1>
</div> </div>
</div> </div>
</div> </div>

View File

@ -25,7 +25,7 @@
</div> </div>
</div> </div>
<div align="right"> <div align="right">
<label id="actualizando" style="display:none" align="center"> <br><br><br><br><img src="./img/animadas/cargando2.gif" width='60' height='60'></label> <label id="actualizando" style="display:none" align="center"> <br><br><br><br><img src="./gui_common/img/animadas/cargando2.gif" width='60' height='60'></label>
</div> </div>
<div id="mostrarregistrosH" style="color:white;text-align:left;" width="100%"> </div> <div id="mostrarregistrosH" style="color:white;text-align:left;" width="100%"> </div>
</div> </div>

View File

@ -6,18 +6,18 @@
<td rowspan="2" id="barralateral" style="background-color: rgba(251, 251, 251, 0.15)"></td> <td rowspan="2" id="barralateral" style="background-color: rgba(251, 251, 251, 0.15)"></td>
<td> <td>
<h5><b>Información General<b><h5> <h5><b>Información General<b><h5>
<h5><img id="img_nombre" height="25" width="25"> Nombre: <span class="badge badge-info" style="font-size:small" id="inombre">-</span></h5> <h5><img src="gui_common/img/informacion.png" id="img_nombre" height="25" width="25"> Nombre: <span class="badge badge-info" style="font-size:small" id="inombre">-</span></h5>
<h5><img id="img_so" height="25" width="25"> S.O: <span class="badge badge-info" style="font-size:small" id="iso">-</span></h5> <h5><img src="gui_common/img/informacion.png" id="img_so" height="25" width="25"> S.O: <span class="badge badge-info" style="font-size:small" id="iso">-</span></h5>
<h5><img id="img_modo" height="25" width="25"> Modo: <span class="badge badge-info" style="font-size:small" id="imodo">-</span></h5> <h5><img src="gui_common/img/informacion.png" id="img_modo" height="25" width="25"> Modo: <span class="badge badge-info" style="font-size:small" id="imodo">-</span></h5>
<h5><img src="img/ok.webp" height="25" width="25"> Node.js: <span id='versiones' class="badge badge-info" style="font-size:small" data-toggle="tooltip" data-placement="right" data-html="true" title="-"><span id="nwjs_v">-</span></h5> <h5><img src="gui_common/img/informacion.png" height="25" width="25"> Node.js: <span id='versiones' class="badge badge-info" style="font-size:small" data-toggle="tooltip" data-placement="right" data-html="true" title="-"><span id="nwjs_v">-</span></h5>
</td> </td>
<td WIDTH = "1%" rowspan="2"></td> <td WIDTH = "1%" rowspan="2"></td>
<td> <td>
<h5><b>Tanques del Sistema</b></h5> <h5><b>Tanques del Sistema</b></h5>
<h5><img src="img/archive.webp" height="25" width="25"><b>Diario: </b> <span class="badge badge-info" style="font-size:small" id="tamanio_diario">-</span> </h5> <h5><img src="gui_common/img/archive.webp" height="25" width="25"><b>Diario: </b> <span class="badge badge-info" style="font-size:small" id="tamanio_diario">-</span> </h5>
<h5><img src="img/archive.webp" height="25" width="25"><b>Pendiente:</b> <span class="badge badge-info" style="font-size:small" id="tamanio_pendiente">-</span> <button type="button" class="w3-tiny" onclick="PurgarP()" data-toggle="tooltip" data-placement="right" title="Si presiona este botón de purgar, usted vaciará el archivo que almacena los registros pendientes de enviar, esto solo aplica para registros pendientes de enviar de redes de tipo 'emacenter'.">Purgar</button ></h5> <h5><img src="gui_common/img/archive.webp" height="25" width="25"><b>Pendiente:</b> <span class="badge badge-info" style="font-size:small" id="tamanio_pendiente">-</span> <button type="button" class="btn btn-sm btn-warning" onclick="PurgarP()" data-toggle="tooltip" data-placement="right" title="Si presiona este botón de purgar, usted vaciará el archivo que almacena los registros pendientes de enviar, esto solo aplica para registros pendientes de enviar de redes de tipo 'emacenter'.">Purgar</button ></h5>
<h5><img src="img/archive.webp" height="25" width="25"><b>Debug: </b> <span class="badge badge-info" style="font-size:small" id="tamanio_debug">-</span> <button type="button" class="w3-tiny" onclick="PurgarD()" data-toggle="tooltip" data-placement="right" title="Si presiona este botón de purgar, usted vaciará el archivo que almacena los registros de logs del sistema." >Purgar</button > </h5> <h5><img src="gui_common/img/archive.webp" height="25" width="25"><b>Debug: </b> <span class="badge badge-info" style="font-size:small" id="tamanio_debug">-</span> <button type="button" class="btn btn-sm btn-warning" onclick="PurgarD()" data-toggle="tooltip" data-placement="right" title="Si presiona este botón de purgar, usted vaciará el archivo que almacena los registros de logs del sistema." >Purgar</button > </h5>
</td> </td>
@ -36,10 +36,10 @@
</td> </td>
<td> <td>
<h5><b>Información de Ejecución</b> </h5> <h5><b>Información de Ejecución</b> </h5>
<h5><img src="img/sistema.webp" height="25" width="25"><b>Audio: </b> <span class="badge badge-info" id="audiomenu" data-toggle="tooltip" data-placement="right" title="Indica si esta activado el audio" style="font-size:small">-</span> </h5> <h5><img src="gui_common/img/sistema.webp" height="25" width="25"><b>Audio: </b> <span class="badge badge-info" id="audiomenu" data-toggle="tooltip" data-placement="right" title="Indica si esta activado el audio" style="font-size:small">-</span> </h5>
<h5><img src="img/sistema.webp" height="25" width="25"><b>AutoInicio: </b> <span class="badge badge-info" id="autoactivado" data-toggle="tooltip" data-placement="right" title="Indica si el inicio automatico esta activado." style="font-size:small">-</span> </h5> <h5><img src="gui_common/img/sistema.webp" height="25" width="25"><b>AutoInicio: </b> <span class="badge badge-info" id="autoactivado" data-toggle="tooltip" data-placement="right" title="Indica si el inicio automatico esta activado." style="font-size:small">-</span> </h5>
<h5><img src="img/sistema.webp" height="25" width="25"><b>PID: </b> <span class="badge badge-info" id="node_pid" data-toggle="tooltip" data-placement="right" title="Numero del Identificado de Proceso (PID) de la aplicación Ema Libre." style="font-size:small">-</span> </h5> <h5><img src="gui_common/img/sistema.webp" height="25" width="25"><b>PID: </b> <span class="badge badge-info" id="node_pid" data-toggle="tooltip" data-placement="right" title="Numero del Identificado de Proceso (PID) de la aplicación Ema Libre." style="font-size:small">-</span> </h5>
<h5><img src="img/sistema.webp" height="25" width="25"><b>PPID: </b> <span class="badge badge-info" id="node_ppid" data-toggle="tooltip" data-placement="right" title="Numero del Identificado de Proceso Padre (PPID) de la aplicación Ema Libre." style="font-size:small">-</span> </h5> <h5><img src="gui_common/img/sistema.webp" height="25" width="25"><b>PPID: </b> <span class="badge badge-info" id="node_ppid" data-toggle="tooltip" data-placement="right" title="Numero del Identificado de Proceso Padre (PPID) de la aplicación Ema Libre." style="font-size:small">-</span> </h5>
</td> </td>
<td style="display:table-cell; vertical-align:middle; text-align:center"> <td style="display:table-cell; vertical-align:middle; text-align:center">
<button id="botondetener" class="btn btn-lg btn-danger" onclick="DETENER()" role="button">Detener</button > <button id="botondetener" class="btn btn-lg btn-danger" onclick="DETENER()" role="button">Detener</button >

View File

@ -11,7 +11,7 @@
</div> </div>
</div> </div>
<div align="right"> <div align="right">
<label id="actualizando" style="display:none" align="center"> <br><br><br><br><img src="./img/animadas/cargando2.gif" width='60' height='60'></label> <label id="actualizando" style="display:none" align="center"> <br><br><br><br><img src="./gui_common/img/animadas/cargando2.gif" width='60' height='60'></label>
</div> </div>
<div id="mostrarregistrosLogs" style="color:white;text-align:left;"></div> <div id="mostrarregistrosLogs" style="color:white;text-align:left;"></div>

View File

@ -0,0 +1 @@
[]

26782
src/logs/debug.log Normal file

File diff suppressed because it is too large Load Diff

7221
src/logs/registro_diario.log Normal file

File diff suppressed because it is too large Load Diff

4404
src/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,10 +2,10 @@
"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 --disable-logging --disable-gpu --disable-gpu-compositing --no-sandbox --ignore-gpu-blacklist --disable-dev-shm-usage --disable-accelerated-2d-canvas --disable-accelerated-compositing --disable-gpu-rasterization",
"keywords": [ "keywords": [
"ema", "ema",
"estacion", "estacion",
@ -32,31 +32,29 @@
"url": "https://ema.gugler.com.ar" "url": "https://ema.gugler.com.ar"
}, },
"scripts": { "scripts": {
"desktop": "nw .", "desktop": "nw . --disable-logging",
"web": "node gui_web/express.js iniciar", "web": "node gui_web/express.js iniciar",
"consola": "node core/ema.js console",
"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", "datatables": "1.10.18",
"datatables": "^1.10.18", "datatables-buttons": "1.0.3",
"datatables-buttons": "^1.0.3", "express": "5.1.0",
"express": "^4.17.1", "forever": "^4.0.3",
"forever": "^3.0.4", "jquery": "3.7.1",
"jquery": "^3.6.0", "node": "^24.11.0",
"node": "15.10.0", "node-hid": "^2.2.0",
"node-hid": "^2.1.1", "nodemailer": "7.0.5",
"nodemailer": "^6.5.0", "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": "3.1.2"
"terminal-kit": "^2.0.6"
} }
} }

57
test/Send_GET.py Normal file
View File

@ -0,0 +1,57 @@
import requests
import time
# Requiere instalar requests: pip install requests
# 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, timeout=5)
print(f"✅ [{time.strftime('%H:%M:%S')}] Status {response.status_code} - {response.url}")
except requests.exceptions.Timeout:
print(f"⏰ Timeout: el servidor no respondió en 5 segundos.")
except requests.exceptions.ConnectionError:
print(f"🔌 Error de conexión: el puerto {puerto} no está abierto o el servidor no responde.")
except Exception as e:
print(f"❌ Error enviando request: {e}")
time.sleep(intervalo_segundos)