diff --git a/services/delete-info-db.html b/services/delete-info-db.html
index 1e8688a..11d0c62
--- a/services/delete-info-db.html
+++ b/services/delete-info-db.html
@@ -1,20 +1,146 @@
diff --git a/services/delete-info-db.js b/services/delete-info-db.js
index c348f0b..19719c1
--- a/services/delete-info-db.js
+++ b/services/delete-info-db.js
@@ -2,7 +2,281 @@ var mysql = require('mysql');
module.exports = function(RED) {
var log = RED.log;
-
+
+ // ---------------------------------------------------------------------------------------
+ // DelInfoDB v2 (version "v2"): purga periodica de mqtt_lecturas con temporizador propio.
+ //
+ // La v1 solo borra cuando le llega un mensaje y compara `time` como si fueran milisegundos
+ // (FROM_UNIXTIME(time * 0.001)); con `time` en segundos (end_range) nunca alcanza la
+ // fecha de corte. La v2 no necesita mensaje, borra en tandas con LIMIT (de una en una: la conexion
+ // es unica y compartida con SaveDB y Sender, con una pausa entre sentencias) y se configura con
+ // reglas: [{ "column": "status", "states": [2], "by": "time", "days": 7,
+ // "per_device": true, "index": "idx_status_device_time" }]
+ // column columna de estado: status (cola del capturador) o restful (estado de entrega)
+ // states valores que se pueden borrar; el 0 (pendiente) no se borra nunca
+ // by con que fecha se mide la antiguedad: time (epoch en segundos guardado como texto,
+ // se compara como cadena de 10 cifras), restful_at, sent_time o aswered_time
+ // days antiguedad minima en dias
+ // index (opcional) indice que se fuerza para localizar las filas. MariaDB no admite
+ // FORCE INDEX en DELETE: con `index` o `per_device` cada tanda son dos sentencias,
+ // un SELECT de ids (covering, con FORCE INDEX) y un DELETE por clave primaria
+ // per_device (opcional) purga dispositivo a dispositivo: primero los pares (estado, device)
+ // con filas en esos estados (solo indice) y luego, de uno en uno, status = ? AND
+ // device = ? AND time < ?. Con un indice (column, device, time) lee solo las
+ // filas que va a borrar y ninguna de otro estado, sin depender del optimizador
+ // Sin reglas se usa [{ column: status, states: [2], by: time, days: interval }]: del capturador
+ // solo se borra lo que el concentrador ya acuso (status 2), nunca lo pendiente (0) ni lo
+ // enviado sin acuse (3). En el receptor: restful 1 con mas de 7 dias y restful 9 con mas de 30,
+ // por restful_at (idx_purga da un rango exacto sin dispositivo).
+ // ---------------------------------------------------------------------------------------
+ var PURGA_COLUMNAS = ["status", "restful"];
+ var PURGA_FECHAS = ["time", "restful_at", "sent_time", "aswered_time"];
+
+ function reglasDePurga(config) {
+ var crudas = config.rules;
+ if (typeof crudas === "string") crudas = crudas.trim() === "" ? null : JSON.parse(crudas);
+ if (crudas === null || crudas === undefined) {
+ crudas = [{ column: "status", states: [2], by: "time", days: parseFloat(config.interval) || 7 }];
+ }
+ if (!Array.isArray(crudas) || crudas.length === 0) throw new Error("rules debe ser una lista de reglas");
+ return crudas.map(function (r, i) {
+ var donde = "regla " + (i + 1) + ": ";
+ var estados = Array.isArray(r.states) ? r.states.map(Number) : [];
+ if (PURGA_COLUMNAS.indexOf(r.column) === -1) throw new Error(donde + "column debe ser " + PURGA_COLUMNAS.join(" o "));
+ if (PURGA_FECHAS.indexOf(r.by) === -1) throw new Error(donde + "by debe ser " + PURGA_FECHAS.join(", "));
+ if (estados.length === 0 || estados.some(function (e) { return !(e >= 1 && e <= 255) || Math.floor(e) !== e; })) {
+ throw new Error(donde + "states: enteros de 1 a 255; el 0 (pendiente) no se borra nunca");
+ }
+ var dias = Number(r.days);
+ if (!(dias > 0)) throw new Error(donde + "days debe ser mayor que 0");
+ if (r.index !== undefined && r.index !== null && r.index !== "" && !/^[A-Za-z0-9_]{1,64}$/.test(String(r.index))) {
+ throw new Error(donde + "index debe ser el nombre de un indice (letras, cifras y _)");
+ }
+ return {
+ column: r.column, states: estados, by: r.by, days: dias,
+ index: r.index ? String(r.index) : null, perDevice: r.per_device === true
+ };
+ });
+ }
+
+ function crearPurga(node, config) {
+ var periodo = 60000 * (parseFloat(config.period) || 60);
+ var tanda = Math.max(1, Math.min(parseInt(config.batch, 10) || 1000, 50000));
+ // Pausa entre dos sentencias de borrado consecutivas de una pasada (no antes de la primera):
+ // da paso a SaveDB y Sender en la conexion unica. 0 la desactiva.
+ var pausa = config.pause === undefined || config.pause === "" || isNaN(parseInt(config.pause, 10)) ? 100 : Math.max(0, parseInt(config.pause, 10));
+ var reglas = reglasDePurga(config);
+ var temporizador = null;
+ var corriendo = false;
+ var cerrado = false;
+ var total = 0;
+
+ function consulta(sql, parametros, hecho) {
+ node.mydbConfig.connection.query(sql, parametros, hecho);
+ }
+
+ // Condicion de antiguedad (sin funciones sobre la columna indexada) y sus parametros.
+ function antiguedad(regla, ahora) {
+ var corte = Math.floor(ahora / 1000 - regla.days * 86400);
+ if (regla.by === "time") {
+ return { sql: "`time` < ?", parametros: [String(Math.max(0, corte)).padStart(10, "0")] };
+ }
+ return {
+ sql: "`" + regla.by + "` IS NOT NULL AND `" + regla.by + "` < FROM_UNIXTIME(?)",
+ parametros: [Math.max(0, corte)]
+ };
+ }
+
+ var forzar = function (regla) { return regla.index ? " FORCE INDEX (`" + regla.index + "`)" : ""; };
+
+ // Indices de las reglas: se comprueban una vez, antes de la primera purga. El de una regla tiene que
+ // existir en mqtt_lecturas y empezar por (column, device, by) si purga por dispositivo, o por
+ // (column, by) si no. Si no, esa regla se purga sin FORCE INDEX ni por dispositivo (DELETE directo
+ // en tandas con LIMIT), con log y estado amarillo.
+ var indicesComprobados = !reglas.some(function (r) { return r.index; });
+ var avisoIndices = "";
+
+ function comprobarIndices(hecho) {
+ var conIndice = reglas.filter(function (r) { return r.index; });
+ var malos = [];
+ var siguiente = function () {
+ if (conIndice.length === 0) {
+ indicesComprobados = true;
+ if (malos.length) {
+ avisoIndices = "indice no valido: " + malos.join(", ");
+ node.status({ fill: "yellow", shape: "ring", text: avisoIndices });
+ }
+ return hecho(null);
+ }
+ var regla = conIndice.shift();
+ consulta("SELECT column_name AS columna FROM information_schema.statistics WHERE table_schema = DATABASE()"
+ + " AND table_name = 'mqtt_lecturas' AND index_name = ? ORDER BY seq_in_index", [regla.index], function (err, filas) {
+ // Sin poder comprobarlo se purga como esta y se vuelve a intentar en la pasada siguiente.
+ if (err) { log.error(err); return hecho(err); }
+ var columnas = (filas || []).map(function (f) { return String(f.columna).toLowerCase(); });
+ var esperadas = regla.perDevice ? [regla.column, "device", regla.by] : [regla.column, regla.by];
+ var vale = esperadas.every(function (c, i) { return columnas[i] === c; });
+ if (!vale) {
+ log.warn("DelInfoDB: el indice " + regla.index + (columnas.length ? " es (" + columnas.join(", ") + ")" : " no existe en mqtt_lecturas")
+ + " y la regla de " + regla.column + " por " + regla.by + " necesita (" + esperadas.join(", ") + "): se purga sin FORCE INDEX, en tandas con LIMIT");
+ malos.push(regla.index);
+ regla.index = null;
+ regla.perDevice = false;
+ }
+ siguiente();
+ });
+ };
+ siguiente();
+ }
+
+ // Una tanda. Devuelve por callback cuantas filas borro. Sin `index` ni `per_device`, un DELETE
+ // directo; con alguno, un SELECT de ids (covering) y un DELETE por clave primaria.
+ function tandaDe(regla, ahora, par, hecho) {
+ var edad = antiguedad(regla, ahora);
+ if (!regla.index && !regla.perDevice) {
+ var sql = "DELETE FROM mqtt_lecturas WHERE `" + regla.column + "` IN (" + regla.states.map(function () { return "?"; }).join(",") + ") AND " + edad.sql + " LIMIT ?";
+ return consulta(sql, regla.states.concat(edad.parametros, [tanda]), function (err, res) {
+ hecho(err, res && res.affectedRows ? res.affectedRows : 0);
+ });
+ }
+ var donde;
+ var parametros;
+ if (par) {
+ donde = "`" + regla.column + "` = ? AND device = ? AND " + edad.sql;
+ parametros = [par.estado, par.device].concat(edad.parametros);
+ } else {
+ donde = "`" + regla.column + "` IN (" + regla.states.map(function () { return "?"; }).join(",") + ") AND " + edad.sql;
+ parametros = regla.states.concat(edad.parametros);
+ }
+ consulta("SELECT id FROM mqtt_lecturas" + forzar(regla) + " WHERE " + donde + " ORDER BY `" + regla.by + "` LIMIT ?", parametros.concat([tanda]), function (err, ids) {
+ if (err) return hecho(err, 0);
+ if (!ids || ids.length === 0) return hecho(null, 0);
+ var lista = ids.map(function (f) { return f.id; });
+ // Se repite la condicion de estado: una fila que cambio de estado entre las dos sentencias no se borra.
+ consulta("DELETE FROM mqtt_lecturas WHERE id IN (" + lista.map(function () { return "?"; }).join(",") + ") AND `" + regla.column + "` IN ("
+ + regla.states.map(function () { return "?"; }).join(",") + ")", lista.concat(regla.states), function (err2, res) {
+ hecho(err2, res && res.affectedRows ? res.affectedRows : 0);
+ });
+ });
+ }
+
+ // Pares (estado, device) con filas en los estados de la regla: solo indice.
+ function paresDe(regla, hecho) {
+ consulta("SELECT DISTINCT `" + regla.column + "` AS estado, device FROM mqtt_lecturas" + forzar(regla) + " WHERE `" + regla.column + "` IN ("
+ + regla.states.map(function () { return "?"; }).join(",") + ")", regla.states, function (err, filas) {
+ hecho(err, filas || []);
+ });
+ }
+
+ function contarPendientes(hecho) {
+ var columnas = reglas.map(function (r) { return r.column; }).filter(function (c, i, todas) { return todas.indexOf(c) === i; });
+ var pendientes = {};
+ var siguiente = function () {
+ if (columnas.length === 0) return hecho(pendientes);
+ var columna = columnas.shift();
+ consulta("SELECT COUNT(*) AS n FROM mqtt_lecturas WHERE `" + columna + "` = 0", [], function (err, filas) {
+ if (err) log.error(err);
+ else pendientes[columna] = Number(filas && filas[0] ? filas[0].n : 0);
+ siguiente();
+ });
+ };
+ siguiente();
+ }
+
+ function ejecutar(hecho, sinComprobar) {
+ if (corriendo || cerrado || !node.mydbConfig.connected) return hecho && hecho();
+ if (!indicesComprobados && !sinComprobar) {
+ corriendo = true;
+ return comprobarIndices(function () { corriendo = false; ejecutar(hecho, true); });
+ }
+ corriendo = true;
+ var purgadas = 0;
+ var porRegla = reglas.slice();
+ var haBorrado = false; // ya hubo una sentencia de borrado en esta pasada: hay que esperar la pausa
+ var terminar = function () {
+ contarPendientes(function (pendientes) {
+ corriendo = false;
+ total += purgadas;
+ var primera = Object.keys(pendientes)[0];
+ if (!cerrado) {
+ node.status({
+ fill: avisoIndices ? "yellow" : "green", shape: avisoIndices ? "ring" : "dot",
+ text: (avisoIndices ? avisoIndices + " · " : "") + "purgadas " + purgadas + " (total " + total + ")" + (primera ? " · pendientes " + pendientes[primera] : "")
+ });
+ node.send({ payload: { msg: "Number of records deleted: " + purgadas, deleted: purgadas, total: total, pending: pendientes } });
+ }
+ if (hecho) hecho();
+ });
+ };
+ // Espera la pausa (salvo antes de la primera sentencia de la pasada) y ejecuta `accion`.
+ var conPausa = function (accion) {
+ if (!haBorrado || pausa <= 0) { haBorrado = true; return accion(); }
+ haBorrado = true;
+ var t = setTimeout(accion, pausa);
+ if (t.unref) t.unref();
+ };
+ // Una regla: tandas seguidas, de una en una, hasta que una no salga llena. Con `per_device`, para cada par.
+ var purgarRegla = function (regla, pares, terminadaRegla) {
+ var par = pares ? pares.shift() : null;
+ if (pares && !par) return terminadaRegla();
+ var tandas = function () {
+ if (cerrado) return terminar();
+ conPausa(function () {
+ if (cerrado) return terminar();
+ tandaDe(regla, Date.now(), par, function (err, n) {
+ if (err) {
+ // Se registra y se sigue con la siguiente regla: la purga se reintenta en el proximo periodo.
+ log.error(err);
+ return terminadaRegla();
+ }
+ purgadas += n;
+ if (n >= tanda) return tandas();
+ if (pares) return purgarRegla(regla, pares, terminadaRegla);
+ terminadaRegla();
+ });
+ });
+ };
+ tandas();
+ };
+ var siguienteRegla = function () {
+ if (porRegla.length === 0 || cerrado) return terminar();
+ var regla = porRegla.shift();
+ if (!regla.perDevice) return purgarRegla(regla, null, siguienteRegla);
+ paresDe(regla, function (err, filas) {
+ if (err) {
+ log.error(err);
+ return siguienteRegla();
+ }
+ purgarRegla(regla, filas.map(function (f) { return { estado: f.estado, device: f.device }; }), siguienteRegla);
+ });
+ };
+ siguienteRegla();
+ }
+
+ // La primera purga, 30 s despues de arrancar (o de que la base este disponible); despues,
+ // una por periodo. Un mensaje de entrada tambien la dispara, pero no hace falta.
+ function programar(ms) {
+ if (cerrado) return;
+ temporizador = setTimeout(function () {
+ temporizador = null;
+ if (!node.mydbConfig.connected) return programar(30000);
+ ejecutar(function () { programar(periodo); });
+ }, ms);
+ if (temporizador.unref) temporizador.unref();
+ }
+
+ programar(30000);
+
+ return {
+ ejecutar: function () { ejecutar(); },
+ cerrar: function () {
+ cerrado = true;
+ if (temporizador) clearTimeout(temporizador);
+ temporizador = null;
+ }
+ };
+ }
+
function Node(config) {
RED.nodes.createNode(this, config);
var node = this;
@@ -11,6 +285,11 @@ module.exports = function(RED) {
this.interval = config.interval;
+ // "v2": purga periodica con temporizador propio (ver crearPurga). Por defecto v1, que
+ // borra al recibir un mensaje y compara `time` en milisegundos, como siempre.
+ this.version = config.version || 'v1';
+ var purga = null;
+
this.mentor = RED.nodes.getNode(config.mentor);
this.mentor_id = 0;
@@ -21,7 +300,8 @@ module.exports = function(RED) {
var node = this;
var busy = false;
var status = {};
- node.mydbConfig.on("state", function(info) {
+ // Se guarda el manejador para quitar solo el propio al cerrar: el config node MySQLdb lo comparten varios nodos.
+ var alCambiarEstadoBd = function (info) {
if (info === "connecting") { node.status({fill:"grey",shape:"ring",text:info}); }
else if (info === "connected") { node.status({fill:"green",shape:"dot",text:info}); }
else {
@@ -29,9 +309,22 @@ module.exports = function(RED) {
if (info === "PROTOCOL_CONNECTION_LOST") { info = "connection lost"; }
node.status({fill:"red",shape:"ring",text:info});
}
- });
+ };
+ node.mydbConfig.on("state", alCambiarEstadoBd);
+ if (node.version.indexOf("v2") > -1) {
+ try {
+ purga = crearPurga(node, config);
+ } catch (e) {
+ node.error("DelInfoDB v2: " + e.message);
+ node.status({fill:"red",shape:"ring",text:"reglas no validas"});
+ }
+ }
node.on("input", function(msg) {
+ if (node.version.indexOf("v2") > -1) {
+ if (purga) purga.ejecutar();
+ return;
+ }
if (node.mydbConfig.connected) {
var obj = JSON.parse(msg.payload);
msg.code = obj.code;
@@ -53,7 +346,8 @@ module.exports = function(RED) {
node.on('close', function () {
if (node.tout) { clearTimeout(node.tout); }
- node.mydbConfig.removeAllListeners();
+ if (purga) purga.cerrar();
+ node.mydbConfig.removeListener("state", alCambiarEstadoBd);
node.status({});
});
}
diff --git a/services/mysql-db.js b/services/mysql-db.js
index f6b35ae..231c1b8
--- a/services/mysql-db.js
+++ b/services/mysql-db.js
@@ -16,13 +16,44 @@ module.exports = function(RED) {
this.setMaxListeners(0);
var node = this;
+ // Una conexion muerta (el servidor la cerro, un corte de red) no siempre emite 'error': si habia una
+ // consulta en curso, el error fatal le llega solo a su callback y la conexion queda inservible
+ // («Cannot enqueue Query after invoking quit», PROTOCOL_ENQUEUE_AFTER_QUIT) para SaveDB, Sender,
+ // DelInfoDB y Alarms hasta el siguiente ping (290 s). Cualquier error fatal de una consulta da la
+ // conexion por perdida: se destruye (no vuelve al pool) y se pide otra.
+ function perder(conexion, err) {
+ if (node.cerrado || node.connection !== conexion || !node.connected) return;
+ node.connected = false;
+ try { conexion.destroy(); } catch (e) { /* ya estaba cerrada */ }
+ var codigo = err && err.code ? err.code : "PROTOCOL_CONNECTION_LOST";
+ node.emit("state", codigo);
+ if (codigo !== 'PROTOCOL_CONNECTION_LOST' && codigo !== 'ECONNRESET') node.error(err);
+ if (!node.connecting) doConnect();
+ }
+
+ function vigilar(conexion) {
+ var consultar = conexion.query;
+ conexion.query = function () {
+ var args = Array.prototype.slice.call(arguments);
+ var ultimo = args.length - 1;
+ if (typeof args[ultimo] === "function") {
+ var callback = args[ultimo];
+ args[ultimo] = function (err) {
+ if (err && (err.fatal || err.code === 'PROTOCOL_ENQUEUE_AFTER_QUIT')) perder(conexion, err);
+ return callback.apply(this, arguments);
+ };
+ }
+ return consultar.apply(conexion, args);
+ };
+ }
+
function checkVer() {
- node.connection.query("SELECT version();", [], function(err, rows) {
+ var conexion = node.connection;
+ conexion.query("SELECT version();", [], function(err, rows) {
if (err) {
- node.connection.release();
- node.error(err);
node.status({fill:"red",shape:"ring",text:"Bad Ping"});
- doConnect();
+ // Si fue fatal, vigilar() ya la dio por perdida; si no, se da aqui.
+ perder(conexion, err);
}
});
}
@@ -38,8 +69,15 @@ module.exports = function(RED) {
password : node.credentials.password,
database : node.dbname,
timezone : node.tz,
+ // concentrador-receptor: el driver usa por defecto UTF8_GENERAL_CI
+ // (utf8mb3). Un carácter de 4 bytes en el content se rechazaría o
+ // se sustituiría, rompiendo la copia byte a byte (CR1, C4 I2).
+ charset : 'UTF8MB4_BIN',
insecureAuth: true,
- multipleStatements: true,
+ // concentrador-receptor: sin sentencias múltiples. Con parámetros
+ // enlazados no hacen falta y amplían el daño de cualquier
+ // concatenación que quede (S5).
+ multipleStatements: false,
connectionLimit: 25
});
}
@@ -52,23 +90,13 @@ module.exports = function(RED) {
node.tick = setTimeout(doConnect, reconnect);
}
else {
+ vigilar(connection);
node.connection = connection;
node.connected = true;
node.emit("state","connected");
- node.connection.on('error', function(err) {
- node.connected = false;
- node.connection.release();
- node.emit("state",err.code);
- if (err.code === 'PROTOCOL_CONNECTION_LOST') {
- doConnect(); // silently reconnect...
- }
- else if (err.code === 'ECONNRESET') {
- doConnect(); // silently reconnect...
- }
- else {
- node.error(err);
- doConnect();
- }
+ connection.on('error', function(err) {
+ // PROTOCOL_CONNECTION_LOST y ECONNRESET reconectan en silencio; el resto, con error.
+ perder(connection, err);
});
if (!node.check) { node.check = setInterval(checkVer, 290000); }
}
@@ -82,6 +110,7 @@ module.exports = function(RED) {
}
this.on('close', function (done) {
+ node.cerrado = true;
if (this.tick) { clearTimeout(this.tick); }
if (this.check) { clearInterval(this.check); }
node.connected = false;
diff --git a/services/receiver.js b/services/receiver.js
index 474cc29..b2356ff
--- a/services/receiver.js
+++ b/services/receiver.js
@@ -1,156 +1,553 @@
-module.exports = function(RED) {
- var log = RED.log;
- function Node(config) {
+/**
+ * Receiver — node-red-contrib-services-mentor@0.0.45, CORREGIDO.
+ *
+ * Corrección versionada con patch-package por concentrador-receptor
+ * (docs/REUTILIZACION_RECEIVER.md, docs/PARCHE_RECEIVER.md). Conserva la idea del
+ * nodo publicado —suscribirse a `mentor_data`, guardar el sobre en
+ * `mqtt_lecturas` sin interpretar el `content` y acusar en
+ * `mentor_answer_`— y corrige los defectos RD1–RD8:
+ *
+ * RD1 Solo se acusa tras un INSERT confirmado o un duplicado verificado. Un
+ * fallo de base no acusa ni pierde: el mensaje espera (G1, G3).
+ * RD2 Todas las sentencias usan parámetros enlazados (S5).
+ * RD3 El parseo del sobre está protegido; lo malformado va a cuarentena (S6, G5).
+ * RD4 Modo estricto: sin variables globales implícitas.
+ * RD5 Topic y datos del acuse ligados a cada mensaje, no al nodo (C2).
+ * RD6 (device, time) existente: contenido idéntico = duplicado con acuse;
+ * distinto = conflicto a cuarentena (G5, C4 I3). La hora de envío del
+ * capturador (`sent_at`) no cuenta: cambia en cada reenvío (spec 005).
+ * RD7 mentor_id y alarm con valor por defecto 0 y validados (C1).
+ * RD8 Se apoya en UNIQUE (device, time): INSERT y, si choca, comparación.
+ *
+ * Además, y es lo que cierra el riesgo RN4 de la spec 001: **el PUBACK al broker
+ * se envía después de persistir**, no al recibir. MQTT.js procesa los paquetes
+ * entrantes de uno en uno y solo confirma un PUBLISH QoS 1 cuando
+ * `client.handleMessage(packet, callback)` llama a su callback (punto de
+ * extensión documentado de MQTT.js para contrapresión). Este nodo lo sustituye
+ * para retener la confirmación hasta que el mensaje está en `mqtt_lecturas` o en
+ * `mqtt_cuarentena`. Si la base no está, no se confirma nada, el broker conserva
+ * el mensaje en la sesión persistente y no entrega más hasta que se libere.
+ */
+module.exports = function (RED) {
+ "use strict";
+
+ var TextDecoder = require("util").TextDecoder;
+
+ var TOPIC_DATOS = "mentor_data";
+ var PREFIJO_ACUSE = "mentor_answer_";
+ // QoS 1 y no 2: con QoS 2 el broker da el mensaje por entregado en el PUBREC,
+ // que MQTT.js envía antes de emitir el mensaje, es decir, antes de persistir.
+ var QOS_SUSCRIPCION = 1;
+ var QOS_ACUSE = 1;
+ var TAMANO_MAXIMO = 1048576; // 1 MiB (S6)
+ var MAX_EXTRACTO_LOG = 512; // S12
+ var MAX_DETALLE = 512; // columna mqtt_cuarentena.detail
+ var ESPERA_MIN_MS = 1000;
+ var ESPERA_MAX_MS = 15000;
+ var MAX_MENTOR_ID = 4294967295; // int unsigned
+
+ // Errores de la base que indican que ESTA fila no cabe (dato), no que la base
+ // no esté disponible. Todo lo demás se trata como transitorio: se reintenta.
+ // 1048 ER_BAD_NULL_ERROR · 1264 ER_WARN_DATA_OUT_OF_RANGE · 1265 WARN_DATA_TRUNCATED
+ // 1292 ER_TRUNCATED_WRONG_VALUE · 1300 ER_INVALID_CHARACTER_STRING
+ // 1366 ER_TRUNCATED_WRONG_VALUE_FOR_FIELD · 1406 ER_DATA_TOO_LONG
+ var ERRNO_DE_DATO = [1048, 1264, 1265, 1292, 1300, 1366, 1406];
+ var ERRNO_DUPLICADO = 1062; // ER_DUP_ENTRY
+
+ var SQL_INSERTAR =
+ "INSERT INTO mqtt_lecturas (time, device, content, status, mentor_id, alarm) VALUES (?, ?, ?, 2, ?, ?)";
+ var SQL_EXISTENTE = "SELECT id, content FROM mqtt_lecturas WHERE device = ? AND time = ? LIMIT 1";
+ var SQL_CUARENTENA =
+ "INSERT INTO mqtt_cuarentena (topic, reason, detail, device, time, mentor_id, lectura_id, payload_bytes, payload) " +
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
+
+ var CLAVE_CONTROL = "__mentorReceiverControlAcuse";
+
+ // ---------------------------------------------------------------------------
+ // Utilidades puras
+ // ---------------------------------------------------------------------------
+
+ function truncar(texto, maximo) {
+ texto = String(texto);
+ return texto.length > maximo ? texto.slice(0, maximo) + "…[truncado]" : texto;
+ }
+
+ function extracto(payload) {
+ // Para logs: nunca el payload completo (S12). JSON.stringify escapa saltos
+ // de línea y caracteres de control, para que no puedan falsear líneas de log.
+ var texto = Buffer.isBuffer(payload) ? payload.toString("utf8", 0, Math.min(payload.length, MAX_EXTRACTO_LOG)) : String(payload);
+ return JSON.stringify(truncar(texto, MAX_EXTRACTO_LOG));
+ }
+
+ function describirError(err) {
+ // Nunca err.sql: contiene los valores enlazados (el content completo).
+ if (!err) return "error desconocido";
+ var partes = [];
+ if (err.code) partes.push(err.code);
+ if (err.errno) partes.push("errno=" + err.errno);
+ partes.push(truncar(err.sqlMessage || err.message || String(err), 300));
+ return partes.join(" ");
+ }
+
+ function rechazo(motivo, detalle) {
+ return { valido: false, motivo: motivo, detalle: truncar(detalle, MAX_DETALLE - 20) };
+ }
+
+ function normalizarMentorId(valor) {
+ if (valor === undefined || valor === null) return { valor: 0, sufijo: "0" };
+ if (typeof valor === "number" && Number.isInteger(valor) && valor >= 0 && valor <= MAX_MENTOR_ID) {
+ return { valor: valor, sufijo: String(valor) };
+ }
+ // Tolerancia: el mentor_id sale de la configuración del capturador y puede
+ // llegar como cadena de dígitos. Se usa literal en el topic (C2).
+ if (typeof valor === "string" && /^[0-9]{1,10}$/.test(valor) && Number(valor) <= MAX_MENTOR_ID) {
+ return { valor: Number(valor), sufijo: valor };
+ }
+ return null;
+ }
+
+ function normalizarAlarm(valor) {
+ if (valor === undefined || valor === null) return 0;
+ if (valor === 0 || valor === 1) return valor;
+ if (valor === "0" || valor === "1") return Number(valor);
+ return null;
+ }
+
+ /**
+ * Valida el sobre contra C1 sin interpretar el paquete (CR2). Devuelve
+ * { valido: true, sobre } o { valido: false, motivo, detalle }.
+ */
+ function validarSobre(payload) {
+ if (!Buffer.isBuffer(payload)) payload = Buffer.from(String(payload), "utf8");
+ if (payload.length > TAMANO_MAXIMO) {
+ return rechazo("TAMANO_EXCEDIDO", payload.length + " bytes > " + TAMANO_MAXIMO);
+ }
+ var texto;
+ try {
+ texto = new TextDecoder("utf-8", { fatal: true }).decode(payload);
+ } catch (e) {
+ return rechazo("NO_UTF8", "el payload no es UTF-8 válido");
+ }
+ var obj;
+ try {
+ obj = JSON.parse(texto);
+ } catch (e) {
+ return rechazo("NO_JSON", "el payload no es JSON: " + e.message);
+ }
+ if (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
+ return rechazo("NO_OBJETO", "el sobre JSON no es un objeto");
+ }
+ if (typeof obj.device !== "string") {
+ return rechazo("DEVICE_INVALIDO", "device ausente o no es cadena");
+ }
+ var caracteres = Array.from(obj.device).length;
+ if (caracteres < 1 || caracteres > 50) {
+ return rechazo("DEVICE_INVALIDO", "device mide " + caracteres + " caracteres (se admiten 1..50)");
+ }
+ if (typeof obj.time !== "string" || !/^[0-9]{10}$/.test(obj.time)) {
+ return rechazo("TIME_INVALIDO", "time ausente o no es una cadena de 10 dígitos");
+ }
+ if (typeof obj.content !== "string" || obj.content.length < 2) {
+ return rechazo("CONTENT_INVALIDO", "content ausente, no es cadena o mide menos de 2 caracteres");
+ }
+ var mentor = normalizarMentorId(obj.mentor_id);
+ if (!mentor) return rechazo("MENTOR_ID_INVALIDO", "mentor_id no es un entero >= 0");
+ var alarm = normalizarAlarm(obj.alarm);
+ if (alarm === null) return rechazo("ALARM_INVALIDO", "alarm no es 0 ni 1");
+
+ return {
+ valido: true,
+ sobre: {
+ device: obj.device, // literal (C1.1)
+ time: obj.time, // literal, como cadena (C1.1)
+ content: obj.content, // literal (CR1)
+ mentorId: mentor.valor,
+ sufijoAcuse: mentor.sufijo,
+ alarm: alarm
+ }
+ };
+ }
+
+ function mismoContenido(guardado, recibido) {
+ if (Buffer.isBuffer(guardado)) {
+ if (guardado.equals(Buffer.from(recibido, "utf8"))) return true;
+ guardado = guardado.toString("utf8");
+ } else if (guardado === recibido) {
+ return true;
+ }
+ return mismoSalvoHoraDeEnvio(guardado, recibido);
+ }
+
+ /**
+ * Spec 005: el capturador pone en cada publicación la hora de su reloj (`sent_at`, spec 021
+ * del capturador), así que un reenvío del mismo paquete trae otro `sent_at`. No es un
+ * conflicto: se compara el paquete sin ese campo. Cualquier otra diferencia sí lo es.
+ */
+ function mismoSalvoHoraDeEnvio(guardado, recibido) {
+ if (typeof guardado !== "string" || typeof recibido !== "string") return false;
+ if (guardado.indexOf('"sent_at"') === -1 && recibido.indexOf('"sent_at"') === -1) return false;
+ var a, b;
+ try {
+ a = JSON.parse(guardado);
+ b = JSON.parse(recibido);
+ } catch (e) {
+ return false;
+ }
+ if (!esObjeto(a) || !esObjeto(b)) return false;
+ delete a.sent_at;
+ delete b.sent_at;
+ return JSON.stringify(a) === JSON.stringify(b);
+ }
+
+ function esObjeto(v) {
+ return v !== null && typeof v === "object" && !Array.isArray(v);
+ }
+
+ function dormir(ms) {
+ return new Promise(function (resolve) {
+ setTimeout(resolve, ms);
+ });
+ }
+
+ function abandono() {
+ var e = new Error("procesamiento abandonado: la conexión MQTT cambió o el nodo se cerró");
+ e.abandono = true;
+ return e;
+ }
+
+ /**
+ * Instala, una vez por cliente MQTT.js, la retención del PUBACK. Los paquetes
+ * que no ha reclamado este nodo siguen el camino normal.
+ */
+ function controlDeAcuse(client) {
+ if (client[CLAVE_CONTROL]) return client[CLAVE_CONTROL];
+ var control = { tareas: new WeakMap() };
+ var original = client.handleMessage;
+ client.handleMessage = function (packet, callback) {
+ var tarea = packet ? control.tareas.get(packet) : undefined;
+ if (!tarea) return original.call(client, packet, callback);
+ control.tareas.delete(packet);
+ tarea.then(function (confirmar) {
+ // Solo se confirma si el mensaje quedó persistido y la conexión por la que
+ // llegó sigue siendo la actual. Si no, el broker lo reentregará.
+ if (confirmar === true) callback();
+ });
+ };
+ Object.defineProperty(client, CLAVE_CONTROL, { value: control, enumerable: false });
+ return control;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Nodo
+ // ---------------------------------------------------------------------------
+ function Node(config) {
RED.nodes.createNode(this, config);
var node = this;
- this.mqtt = RED.nodes.getNode(config.mqtt);
-
- this.broker = config.mqtt;
- this.brokerConn = RED.nodes.getNode(this.broker);
+ node.brokerConn = RED.nodes.getNode(config.mqtt);
+ node.mydbConfig = RED.nodes.getNode(config.mysql);
+ var cerrado = false;
+ var contadores = { guardados: 0, duplicados: 0, conflictos: 0, cuarentena: 0 };
+ var bdCaida = false;
- this.mydb = config.mysql;
- this.mydbConfig = RED.nodes.getNode(this.mydb);
+ function consultar(sql, parametros) {
+ return new Promise(function (resolve, reject) {
+ var pool = node.mydbConfig && node.mydbConfig.pool;
+ if (!pool) {
+ var e = new Error("el pool de la base de recepción aún no está inicializado");
+ e.code = "POOL_NO_INICIALIZADO";
+ return reject(e);
+ }
+ pool.query(sql, parametros, function (err, resultado) {
+ if (err) reject(err);
+ else resolve(resultado);
+ });
+ });
+ }
- this.channel = 0;
- this.qos = 2;
+ function actualizarEstado() {
+ if (bdCaida) {
+ node.status({ fill: "red", shape: "ring", text: "base de recepción no disponible: reteniendo" });
+ return;
+ }
+ var texto = contadores.guardados + " guardados · " + contadores.duplicados + " duplicados";
+ if (contadores.cuarentena || contadores.conflictos) {
+ texto += " · " + (contadores.cuarentena + contadores.conflictos) + " en cuarentena";
+ node.status({ fill: "yellow", shape: "dot", text: texto });
+ } else {
+ node.status({ fill: "green", shape: "dot", text: texto });
+ }
+ }
- if (this.mydbConfig) {
- this.mydbConfig.connect();
- var busy = false;
- var status = {};
- node.mydbConfig.on("state", function(info) {
- if (info === "connecting") { node.status({fill:"grey",shape:"ring",text:info}); }
- else if (info === "connected") { node.status({fill:"green",shape:"dot",text:info}); }
- else {
- if (info === "ECONNREFUSED") { info = "connection refused"; }
- if (info === "PROTOCOL_CONNECTION_LOST") { info = "connection lost"; }
- node.status({fill:"red",shape:"ring",text:info});
+ /**
+ * Ejecuta `operacion` hasta que tenga éxito. Cualquier rechazo que llegue
+ * aquí es transitorio (base caída, permisos, tabla ausente…): se espera con
+ * backoff y se reintenta, sin acusar ni confirmar (G1, G3).
+ */
+ function conReintentos(etapa, operacion, vigente) {
+ var intentos = 0;
+ function paso() {
+ if (!vigente()) return Promise.reject(abandono());
+ return operacion().catch(function (err) {
+ if (err && err.abandono) throw err;
+ intentos++;
+ if (!bdCaida || intentos === 1 || intentos % 20 === 0) {
+ node.warn(
+ "ALERTA base de recepción no disponible en '" + etapa + "' (intento " + intentos + "): " +
+ describirError(err) + ". El mensaje no se acusa ni se confirma al broker; se reintenta."
+ );
+ }
+ bdCaida = true;
+ actualizarEstado();
+ var espera = Math.min(ESPERA_MAX_MS, ESPERA_MIN_MS * Math.pow(2, Math.min(intentos - 1, 10)));
+ return dormir(espera).then(paso);
+ });
+ }
+ return paso().then(function (resultado) {
+ if (bdCaida) {
+ bdCaida = false;
+ node.log("base de recepción disponible de nuevo tras " + intentos + " reintentos en '" + etapa + "'");
}
- });
+ return resultado;
+ });
+ }
- node.on('close', function () {
- if (node.tout) { clearTimeout(node.tout); }
- node.mydbConfig.removeAllListeners();
- node.status({});
- });
- } else {
- this.error("MySQL database not configured");
- }
-
- if (this.brokerConn) {
- this.status({fill:"red",shape:"ring",text:"node-red:common.status.disconnected"});
- node.brokerConn.register(this);
- this.brokerConn.subscribe('mentor_data',this.qos,function(topic,msg,packet) {
- switch (topic)
- {
- case "mentor_data":
- var obj = JSON.parse(msg.toString());
- var mentor_id = obj.mentor_id;
- node.channel = "mentor_answer_" + mentor_id;
- obj.alarm = obj.alarm || 0;
- node.alarm = obj.alarm;
-
- existRecord(node, obj, function (exist, err) {
- if (err) { log.error(err); }
- else
- {
- if (!exist)
- { saveRecord(node, obj, mentor_id, function (r, err) {
- if (err) { log.error(err); }
- else
- {
- getAndSendRecord(obj, node);
- }
- });
- }
- else
- {node.send({payload: {msg:"Record already found ", data: obj}}); getAndSendRecord(obj, node);}
- }
+ function guardarCuarentena(topic, motivo, detalle, payload, clave) {
+ clave = clave || {};
+ var bytes = Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload), "utf8");
+ return consultar(SQL_CUARENTENA, [
+ topic,
+ motivo,
+ truncar(detalle, MAX_DETALLE - 20),
+ clave.device === undefined ? null : clave.device,
+ clave.time === undefined ? null : clave.time,
+ clave.mentorId === undefined ? null : clave.mentorId,
+ clave.lecturaId === undefined ? null : clave.lecturaId,
+ bytes.length,
+ bytes
+ ]).then(function (r) {
+ return r.insertId;
+ });
+ }
+
+ /**
+ * INSERT con UNIQUE (device, time) como árbitro (RD8). Devuelve el desenlace;
+ * rechaza solo con errores transitorios.
+ */
+ function persistirSobre(topic, sobre, payload) {
+ var clave = { device: sobre.device, time: sobre.time, mentorId: sobre.mentorId };
+ return consultar(SQL_INSERTAR, [sobre.time, sobre.device, sobre.content, sobre.mentorId, sobre.alarm]).then(
+ function (r) {
+ return { tipo: "guardado", id: r.insertId };
+ },
+ function (err) {
+ if (err && err.errno === ERRNO_DUPLICADO) {
+ return consultar(SQL_EXISTENTE, [sobre.device, sobre.time]).then(function (filas) {
+ if (!filas || filas.length === 0) {
+ // Chocó la clave pero la fila no aparece: estado inesperado. Se trata
+ // como transitorio para no acusar sin haber verificado nada.
+ var e = new Error("ER_DUP_ENTRY sin fila existente para la clave");
+ e.code = "DUPLICADO_SIN_FILA";
+ throw e;
+ }
+ var existente = filas[0];
+ if (mismoContenido(existente.content, sobre.content)) {
+ return { tipo: "duplicado", id: existente.id };
+ }
+ clave.lecturaId = existente.id;
+ return guardarCuarentena(
+ topic,
+ "CONFLICTO_CONTENIDO",
+ "(device, time) ya existe en mqtt_lecturas.id=" + existente.id + " con content distinto",
+ payload,
+ clave
+ ).then(function (idCuarentena) {
+ return { tipo: "conflicto", id: existente.id, cuarentena: idCuarentena };
+ });
+ });
+ }
+ if (err && ERRNO_DE_DATO.indexOf(err.errno) !== -1) {
+ return guardarCuarentena(topic, "ERROR_BD_PERMANENTE", describirError(err), payload, clave).then(
+ function (idCuarentena) {
+ return { tipo: "error_dato", cuarentena: idCuarentena, error: err };
}
);
- break;
- default:
- log.error(topic);
- break;
+ }
+ throw err;
}
- }, this.id);
- if (this.brokerConn.connected) {
- node.status({fill:"green",shape:"dot",text:"node-red:common.status.connected"});
+ );
+ }
+
+ function publicarAcuse(sobre) {
+ // RD5: todo lo del acuse sale del sobre de ESTE mensaje.
+ var mensaje = {
+ topic: PREFIJO_ACUSE + sobre.sufijoAcuse,
+ payload: JSON.stringify({ device: sobre.device, time: sobre.time, status: 2 }),
+ qos: QOS_ACUSE,
+ retain: false
+ };
+ if (!node.brokerConn || !node.brokerConn.connected) {
+ node.warn(
+ "acuse no publicado (broker desconectado) device=" + JSON.stringify(sobre.device) + " time=" + sobre.time +
+ ": el mensaje no se confirma y el broker lo reentregará"
+ );
+ return false;
}
- this.on('close', function(done) {
- node.brokerConn.deregister(node,done);
+ // No se espera el PUBACK del acuse: llega por el mismo flujo de entrada que
+ // está retenido hasta que este mensaje termine, y esperarlo sería un
+ // bloqueo mutuo. MQTT.js lo guarda en su almacén de salida y lo reenvía.
+ node.brokerConn.publish(mensaje, function (err) {
+ if (err) {
+ node.warn("fallo al publicar el acuse en " + mensaje.topic + ": " + describirError(err));
+ }
});
+ return true;
}
- }
-
- function saveRecord(node, obj, mentor_id, callback)
- {
- if (node.mydbConfig.connected) {
- var sql = "INSERT INTO mqtt_lecturas(time, device, content, status, mentor_id, alarm) VALUES ('"+ obj.time +"','"+obj.device+"','"+obj.content+"', 2, "+mentor_id+",'"+obj.alarm+"');";
- node.mydbConfig.connection.query(sql, [], function(err, rows) {
- if (err) { log.error(err); callback(null, err); }
- else
- {
- node.send({payload: {msg:rows.insertId + " Inserted.", data: obj}});
- callback (true, null);
+ /**
+ * Procesa un mensaje de mentor_data. Resuelve true si se puede confirmar al
+ * broker (persistido en lecturas o en cuarentena y conexión vigente).
+ */
+ function procesar(topic, payload, vigente) {
+ var validacion = validarSobre(payload);
+ var bytes = Buffer.isBuffer(payload) ? payload.length : Buffer.byteLength(String(payload));
+
+ if (!validacion.valido) {
+ return conReintentos("cuarentena", function () {
+ return guardarCuarentena(topic, validacion.motivo, validacion.detalle, payload);
+ }, vigente).then(function (idCuarentena) {
+ contadores.cuarentena++;
+ node.warn(
+ "cuarentena id=" + idCuarentena + " motivo=" + validacion.motivo + " bytes=" + bytes + " detalle=" +
+ JSON.stringify(validacion.detalle) + " extracto=" + extracto(payload) + " (sin acuse)"
+ );
+ node.send({ payload: { resultado: "cuarentena", motivo: validacion.motivo, cuarentena: idCuarentena } });
+ actualizarEstado();
+ return vigente();
+ });
+ }
+
+ var sobre = validacion.sobre;
+ return conReintentos("guardar", function () {
+ return persistirSobre(topic, sobre, payload);
+ }, vigente).then(function (desenlace) {
+ var clave = "device=" + JSON.stringify(sobre.device) + " time=" + sobre.time;
+ if (desenlace.tipo === "guardado") {
+ contadores.guardados++;
+ publicarAcuse(sobre);
+ } else if (desenlace.tipo === "duplicado") {
+ contadores.duplicados++;
+ node.log("duplicado idéntico " + clave + " (mqtt_lecturas.id=" + desenlace.id + "): se acusa sin fila nueva");
+ publicarAcuse(sobre);
+ } else if (desenlace.tipo === "conflicto") {
+ contadores.conflictos++;
+ node.error(
+ "CONFLICTO " + clave + ": ya existe mqtt_lecturas.id=" + desenlace.id + " con content distinto; " +
+ "el nuevo queda en mqtt_cuarentena.id=" + desenlace.cuarentena + " (se acusa: persistido en cuarentena)"
+ );
+ publicarAcuse(sobre);
+ } else {
+ contadores.cuarentena++;
+ node.error(
+ "cuarentena id=" + desenlace.cuarentena + " motivo=ERROR_BD_PERMANENTE " + clave + ": " +
+ describirError(desenlace.error) + " (sin acuse)"
+ );
}
+ node.send({
+ payload: {
+ resultado: desenlace.tipo,
+ device: sobre.device,
+ time: sobre.time,
+ id: desenlace.id,
+ cuarentena: desenlace.cuarentena
+ }
+ });
+ actualizarEstado();
+ return vigente();
});
}
- else {
- node.error("Database not connected",msg);
- status = {fill:"red",shape:"ring",text:"not yet connected"};
- callback(null, null);
- }
-
- }
- function existRecord(node,obj,callback)
- {
- if (node.mydbConfig.connected) {
- var sql = "SELECT count(*) as _count FROM mqtt_lecturas WHERE device='"+obj.device+"' AND time*1="+ obj.time;
- node.mydbConfig.connection.query(sql, [], function(err, rows) {
- if (err) { log.error(err); callback(null, err); }
- else
- {
- if (rows[0]._count > 0 )
- callback (true, null);
- else
- callback(false, null);
+ function alRecibir(topic, payload, packet) {
+ if (topic !== TOPIC_DATOS) {
+ node.warn("topic inesperado ignorado: " + truncar(topic, 100));
+ return;
+ }
+ var client = node.brokerConn && node.brokerConn.client;
+ var stream = client ? client.stream : null;
+ function vigente() {
+ return (
+ !cerrado &&
+ !!client &&
+ node.brokerConn.client === client &&
+ client.stream === stream &&
+ client.connected === true
+ );
+ }
+ var tarea;
+ try {
+ tarea = procesar(topic, payload, vigente);
+ } catch (err) {
+ tarea = Promise.reject(err);
+ }
+ tarea = tarea.catch(function (err) {
+ if (!(err && err.abandono)) {
+ node.error("fallo inesperado procesando mentor_data (no se confirma al broker): " + describirError(err));
}
+ return false;
});
+ // Síncrono: Node-RED invoca este callback durante el evento 'message', y
+ // MQTT.js llama a handleMessage justo después, en el mismo turno.
+ if (client && packet) controlDeAcuse(client).tareas.set(packet, tarea);
}
- else {
- node.error("Database not connected",null);
- status = {fill:"red",shape:"ring",text:"not yet connected"};
- callback(null, null);
+
+ function alCambiarBd(info) {
+ if (info === "connected") {
+ if (!bdCaida) actualizarEstado();
+ } else if (info === "connecting") {
+ node.status({ fill: "grey", shape: "ring", text: "conectando a la base de recepción" });
+ } else if (info && String(info).trim()) {
+ node.status({ fill: "red", shape: "ring", text: "base de recepción: " + truncar(info, 40) });
+ }
}
- }
- function getAndSendRecord(obj, node)
- {
- var _msg = {};
- _msg.device = obj.device;
- _msg.time = obj.time;
- _msg.status = 2;
- if (node.brokerConn) {
- msg = {};
- msg.qos = 2;
- msg.retain = false;
- msg.payload = JSON.stringify(_msg);
- msg.topic = node.channel;
- msg.alarm = node.alarm;
- node.brokerConn.publish(msg);
- node.status({fill:"red",shape:"ring",text:"node-red:common.status.disconnected"});
- if (node.brokerConn.connected) {
- node.status({fill:"green",shape:"dot",text:"node-red:common.status.connected"});
- }
+ if (!node.mydbConfig) {
+ // Sin base no se suscribe: suscribirse sería consumir sin poder persistir.
+ node.error("Receiver sin base de datos configurada: no se suscribe a " + TOPIC_DATOS);
+ return;
}
+ node.mydbConfig.on("state", alCambiarBd);
+ node.mydbConfig.connect();
+ if (!node.brokerConn) {
+ node.error("Receiver sin broker MQTT configurado");
+ } else {
+ node.status({ fill: "red", shape: "ring", text: "node-red:common.status.disconnected" });
+ node.brokerConn.register(node);
+ node.brokerConn.subscribe(TOPIC_DATOS, { qos: QOS_SUSCRIPCION }, alRecibir, node.id);
+ if (node.brokerConn.connected) {
+ node.status({ fill: "green", shape: "dot", text: "node-red:common.status.connected" });
+ }
+ }
+
+ node.on("close", function (removed, done) {
+ cerrado = true;
+ // Solo los listeners propios: el config node es compartido.
+ node.mydbConfig.removeListener("state", alCambiarBd);
+ node.status({});
+ // Sin unsubscribe: la suscripción de la sesión persistente debe sobrevivir
+ // al cierre y al redespliegue (G2; además autoUnsubscribe: false).
+ if (node.brokerConn) {
+ node.brokerConn.deregister(node, done);
+ } else {
+ done();
+ }
+ });
}
RED.nodes.registerType("Receiver", Node);
+
+ // Expuesto solo para las pruebas del receptor; no forma parte de la API del nodo.
+ Node._paraPruebas = { validarSobre: validarSobre, normalizarMentorId: normalizarMentorId, normalizarAlarm: normalizarAlarm };
};
diff --git a/services/save-db.html b/services/save-db.html
index e0e1f16..1b25ba0
--- a/services/save-db.html
+++ b/services/save-db.html
@@ -14,6 +14,18 @@
icon: "service.png",
label: function() {
return this.name||"SaveDB";
+ },
+ oneditprepare: function () {
+ // Antes era texto libre: un valor que no sea v1 ni v2 se conserva como opcion.
+ var v = this.version;
+ if (!v) $("#node-input-version").val("v1");
+ if (v && !$("#node-input-version option[value='" + v + "']").length) {
+ $("#node-input-version").append($("").val(v).text(v)).val(v);
+ }
+ },
+ oneditsave: function () {
+ // Sin version guardada y sin tocarla, el nodo queda igual (el editor no escribe la propiedad).
+ if (this.version === undefined && $("#node-input-version").val() === "v1") $("#node-input-version").remove();
}
});
@@ -36,8 +48,11 @@
-
-
+
+
diff --git a/services/save-db.js b/services/save-db.js
index d71ce8b..3401b13
--- a/services/save-db.js
+++ b/services/save-db.js
@@ -2,8 +2,10 @@ module.exports = function (RED) {
var log = RED.log;
function UpdateLastReading(node, msg) {
- var sql = "UPDATE mqtt_snapshot SET content = '" + msg.payload + "', time = '" + msg.time + "' WHERE device='" + msg.code + "'";
- node.mydbConfig.connection.query(sql, [], function (err, rows) {
+ // Parametrizado (spec 020): un apostrofe en el contenido (p. ej. un nombre de variable)
+ // rompia la sentencia y la lectura se perdia sin aviso.
+ var sql = "UPDATE mqtt_snapshot SET content = ?, time = ? WHERE device = ?";
+ node.mydbConfig.connection.query(sql, [msg.payload, String(msg.time), msg.code], function (err, rows) {
//node.pool.query(sql, function (err, rows, fields) {
if (err) {
log.error(err);
@@ -19,6 +21,10 @@ module.exports = function (RED) {
if (err) {
log.error(err);
callback(null, err);
+ } else if (!rows || rows.length === 0) {
+ // Sin fila en mqtt_snapshot (primera lectura del dispositivo): rows[0] no existe y
+ // el acceso lanzaba dentro del callback del driver. Se informa y no se inserta.
+ callback(null, new Error("no hay lectura previa en mqtt_snapshot para " + msg.code));
} else {
var content = JSON.parse(rows[0].content);
content.time = msg.time;
@@ -45,12 +51,26 @@ module.exports = function (RED) {
});
}
- function insertMysql(node, msg, table) {
- var sql = "INSERT INTO " + table + "(mentor_id, time, device, content, result) VALUES ('" + msg.mentor_id + "','" + msg.time + "','" + msg.code + "','" + msg.payload + "','" + msg.result + "')";
- //node.pool.query(sql, function (err, rows, fields) {
- node.mydbConfig.connection.query(sql, [], function (err, rows) {
+ // Spec 020 (3). Errores que no son de la sentencia sino del momento (bloqueo, caida de la
+ // conexion, MariaDB lenta): la lectura se conserva en memoria y se reintenta.
+ var REINTENTABLES = ["ER_LOCK_DEADLOCK", "ER_LOCK_WAIT_TIMEOUT", "ER_QUERY_INTERRUPTED",
+ "PROTOCOL_CONNECTION_LOST", "PROTOCOL_SEQUENCE_TIMEOUT", "ECONNRESET", "ECONNREFUSED",
+ "ETIMEDOUT", "EPIPE", "ER_CON_COUNT_ERROR", "ER_SERVER_SHUTDOWN"];
+ var MAX_PENDIENTES = 2000;
+
+ // Una sola sentencia INSERT (autocommit): sin transaccion larga ni SELECT ... FOR UPDATE, no
+ // compite con el UPDATE del Sender mas alla de la cola de la conexion. Parametrizado.
+ // `reintento` recibe el mensaje si el error es reintentable.
+ function insertMysql(node, msg, table, reintento) {
+ var sql = "INSERT INTO " + table + "(mentor_id, time, device, content, result) VALUES (?, ?, ?, ?, ?)";
+ node.mydbConfig.connection.query(sql, [String(msg.mentor_id), String(msg.time), msg.code, msg.payload, String(msg.result)], function (err, rows) {
if (err) {
+ if (err.code === "ER_DUP_ENTRY") {
+ // Ya estaba (reintento tras una respuesta perdida): idempotente.
+ return;
+ }
log.error(err);
+ if (reintento && (err.fatal || REINTENTABLES.indexOf(err.code) > -1)) reintento(msg);
} else
node.send({payload: {msg: rows.affectedRows + " record(s) inserted", data: msg}});
});
@@ -61,10 +81,57 @@ module.exports = function (RED) {
this.mydb = n.mysql;
this.mydbConfig = RED.nodes.getNode(this.mydb);
this.mentor = RED.nodes.getNode(n.mentor);
- this.version = n.version;
+ this.version = n.version || 'v1';
var node = this;
var busy = false;
var status = {};
+ var pendientes = [];
+ var crudos = [];
+ var temporizador = null;
+ var intentos = 0;
+
+ // Lecturas que no se pudieron insertar (BD desconectada o error reintentable). Se
+ // conservan en memoria hasta MAX_PENDIENTES y se reinsertan al reconectar, en la
+ // siguiente entrada o por temporizador con espera creciente (2 s ... 30 s).
+ function encolar(msg) {
+ if (pendientes.length >= MAX_PENDIENTES) {
+ var perdida = pendientes.shift();
+ log.error("SaveDB: cola de reintento llena, se descarta la lectura " + perdida.code + " " + perdida.time);
+ }
+ pendientes.push({ mentor_id: msg.mentor_id, time: msg.time, code: msg.code, payload: msg.payload, result: msg.result });
+ programar();
+ }
+
+ function programar() {
+ if (temporizador || (pendientes.length === 0 && crudos.length === 0)) return;
+ intentos++;
+ temporizador = setTimeout(function () {
+ temporizador = null;
+ vaciar();
+ }, Math.min(30000, 1000 * Math.pow(2, intentos)));
+ if (temporizador.unref) temporizador.unref();
+ }
+
+ function vaciar() {
+ if (pendientes.length === 0 && crudos.length === 0) {
+ intentos = 0;
+ return;
+ }
+ if (!node.mydbConfig.connected) {
+ programar();
+ return;
+ }
+ var lote = pendientes;
+ pendientes = [];
+ lote.forEach(function (m) {
+ insertMysql(node, m, "mqtt_lecturas", encolar);
+ });
+ var sinProcesar = crudos;
+ crudos = [];
+ sinProcesar.forEach(function (m) {
+ procesar(m);
+ });
+ }
this.interval = 1000 * 60 * n.interval;
@@ -73,7 +140,9 @@ module.exports = function (RED) {
if (this.mydbConfig) {
this.mydbConfig.connect();
- node.mydbConfig.on("state", function (info) {
+ // Se guarda el manejador para quitar solo el propio al cerrar: el config node MySQLdb lo comparten varios nodos.
+ var alCambiarEstadoBd = function (info) {
+ if (info === "connected") vaciar();
if (info === "connecting") {
node.status({fill: "grey", shape: "ring", text: info});
} else if (info === "connected") {
@@ -87,44 +156,74 @@ module.exports = function (RED) {
}
node.status({fill: "red", shape: "ring", text: info});
}
- });
-
- node.on("input", function (msg) {
+ };
+ node.mydbConfig.on("state", alCambiarEstadoBd);
+ var procesar = function (msg) {
if (node.mydbConfig.connected) {
node.status({});
+ if (pendientes.length > 0 || crudos.length > 0) vaciar();
+ var obj;
if (node.version.indexOf("v2") > -1) {
- var obj = msg.payload;
- msg.payload.code = obj.device_uuid;
- msg.payload.time = obj.start_range;
- msg.payload.mentor_id = node.device_uuid;
- msg.payload.result = 1;
- msg.payload = JSON.stringify(msg.payload);
- }
- var obj = JSON.parse(msg.payload);
- msg.code = obj.code;
- msg.time = Date.now();
- msg.mentor_id = node.mentor_id;
- msg.result = 1;
- msg.version = node.version;
-
- if (node.version.indexOf("v2") > -1) {
- var payload = JSON.stringify(msg.payload);
+ // El informe llega en msg.payload (reporters 1.1.1 o posterior), como objeto
+ // o como cadena JSON. Sin informe se registra el error en vez de lanzar.
+ obj = msg.payload;
+ if (typeof obj === "string") {
+ try {
+ obj = JSON.parse(obj);
+ } catch (e) {}
+ }
+ if (!obj || typeof obj !== "object" || obj.device_uuid === undefined) {
+ node.error("msg.payload has no report (device_uuid missing)", msg);
+ return;
+ }
+ msg.code = obj.device_uuid;
+ // El cierre del intervalo, no la hora de escritura: la columna time
+ // es la que usa el concentrador para reagregar por hora y por dia,
+ // y end_range dice hasta cuando se tiene el conjunto de datos.
+ msg.time = obj.end_range;
+ msg.mentor_id = node.mentor_id;
+ msg.result = 1;
+ // El contenido se guarda tal y como llego, sin inyectarle
+ // code/time/result: es el contrato acordado con el concentrador.
+ msg.payload = JSON.stringify(obj);
} else {
- var payload = msg.payload;
+ try {
+ obj = typeof msg.payload === "string" ? JSON.parse(msg.payload) : msg.payload;
+ } catch (e) {
+ node.error("JSON parse error: " + e.message, msg);
+ return;
+ }
+ if (!obj) {
+ node.error("msg.payload is empty", msg);
+ return;
+ }
+ msg.code = obj.code;
+ // v1 legado (Mentor 1.0): la hora es la del propio mensaje, como hasta la
+ // 0.0.42. Desde la 0.0.43 era Date.now() y, al no ser multiplo del
+ // intervalo, v1 dejo de insertar en mqtt_lecturas.
+ msg.time = obj.time;
+ msg.mentor_id = node.mentor_id;
+ msg.result = 1;
+ if (typeof msg.payload !== "string") {
+ msg.payload = JSON.stringify(obj);
+ }
}
+ msg.version = node.version;
- if (msg.payload.indexOf("Timeout") > -1 || msg.payload.indexOf("NaN") > -1) {
+ // El atajo del ultimo valor conocido es de v1. En v2 miraba la cadena
+ // completa y un nombre con "NaN" o "Timeout" sustituia el informe por el anterior.
+ if (node.version.indexOf("v2") === -1 && typeof msg.payload === "string" && (msg.payload.indexOf("Timeout") > -1 || msg.payload.indexOf("NaN") > -1)) {
getLastReading(node, msg, function (data, err) {
if (err)
log.error(err);
else {
msg = data;
- insertMysql(node, msg, "mqtt_lecturas");
+ insertMysql(node, msg, "mqtt_lecturas", encolar);
}
});
} else {
- if (node.interval > 0 && msg.time * 1 % node.interval == 0 || node.version.indexOf("v2") > -1)
- insertMysql(node, msg, "mqtt_lecturas");
+ if ((node.interval > 0 && msg.time * 1 % node.interval == 0) || (node.version.indexOf("v2") > -1))
+ insertMysql(node, msg, "mqtt_lecturas", encolar);
existLastReading(node, msg, function (exist, err) {
if (err)
@@ -143,6 +242,10 @@ module.exports = function (RED) {
} else {
node.error("Database not connected", msg);
status = {fill: "red", shape: "ring", text: "not yet connected"};
+ // Spec 020 (3): no se pierde el resumen del intervalo; se reprocesa al reconectar.
+ if (crudos.length >= MAX_PENDIENTES) crudos.shift();
+ crudos.push(msg);
+ programar();
}
if (!busy) {
busy = true;
@@ -152,15 +255,18 @@ module.exports = function (RED) {
node.status(status);
}, 500);
}
- }
- )
- ;
+ };
+ node.on("input", procesar);
node.on('close', function () {
if (node.tout) {
clearTimeout(node.tout);
}
- node.mydbConfig.removeAllListeners();
+ if (temporizador) {
+ clearTimeout(temporizador);
+ temporizador = null;
+ }
+ node.mydbConfig.removeListener("state", alCambiarEstadoBd);
node.status({});
});
} else {
diff --git a/services/sender.html b/services/sender.html
index d43f5f1..6727653
--- a/services/sender.html
+++ b/services/sender.html
@@ -8,14 +8,52 @@
mysql: {value: "", type: "MySQLdb"},
mqtt: {value: "", type: "mqtt-broker"},
url: {value: ""},
+ token: {value: ""},
url_alarm: {value: ""},
- priority: {value: "0"}
+ priority: {value: "0"},
+ version: {value: "v1"},
+ encode: {value: false}
},
inputs:1,
outputs:1,
icon: "service.png",
label: function() {
return this.name||"Sender";
+ },
+ oneditprepare: function () {
+ // Solo se ven los campos que usa la combinacion de Priority y Data Version:
+ // MQTT (0, 2): ninguna URL ni token; el aviso de Mentor Id solo con v2.
+ // v1 REST (1, 3, 4): las dos URL y Encode body; sin token (v1 no lo manda).
+ // v2 REST (1, 3, 4): URL de datos y token (X-Mentor-Token); la de alarmas no se usa.
+ function avisar() {
+ var v2 = $("#node-input-version").val() === "v2";
+ var prioridad = $("#node-input-priority").val();
+ var mqtt = ["0", "2"].indexOf(prioridad) !== -1;
+ $("#sender-v2-mqtt-tip").toggle(v2 && mqtt);
+ $(".sender-url").toggle(!mqtt);
+ $(".sender-token").toggle(!mqtt && v2);
+ $(".sender-encode").toggle(!mqtt && !v2);
+ $(".sender-url-alarm").toggle(!mqtt && !v2);
+ }
+ // «Restful v2» (priority 4, solo en la 0.0.47) no tiene comportamiento propio: envia como Restful.
+ // Se quita del desplegable; un nodo que ya la tenga la conserva como opcion.
+ if (String(this.priority) === "4") {
+ $("#node-input-priority").append($("").val("4").text("Restful v2 (same as Restful)")).val("4");
+ }
+ // Sin version guardada el nodo funciona como v1: se muestra asi.
+ if (!this.version) $("#node-input-version").val("v1");
+ $("#node-input-version, #node-input-priority").on("change", avisar);
+ avisar();
+ },
+ oneditsave: function () {
+ // Un nodo guardado sin estos campos (anterior al parche) queda igual si se acepta sin tocarlos:
+ // sin el campo en el formulario, el editor no escribe la propiedad.
+ var nodo = this;
+ [["version", "v1"], ["token", ""]].forEach(function (campo) {
+ var control = $("#node-input-" + campo[0]);
+ if (nodo[campo[0]] === undefined && control.val() === campo[1]) control.remove();
+ });
+ if (nodo.encode === undefined && !$("#node-input-encode").is(":checked")) $("#node-input-encode").remove();
}
});
@@ -37,15 +75,19 @@
-
+
-
+
-
+
+
+
+
+
@@ -56,13 +98,34 @@
-
-
+
+
+
+
+
With v2 over MQTT, leave the Mentor Id at 0 (or empty): acknowledgements arrive on mentor_answer_0.
+
diff --git a/services/sender.js b/services/sender.js
index 9b6e719..3d47359
--- a/services/sender.js
+++ b/services/sender.js
@@ -28,13 +28,41 @@ module.exports = function (RED) {
this.priority = parseInt(config.priority, 10) || 0;
+ // "v2" en un canal REST (priority distinto de 0 y 2): contrato C3 del concentrador. Con
+ // MQTT la version no cambia nada. Por defecto v1, el REST de Mentor 1.0.
+ this.version = config.version || 'v1';
+ var esRestC3 = !(this.priority === 0 || this.priority === 2) && this.version.indexOf("v2") > -1;
+
+ // El token solo lo usa v2 (X-Mentor-Token de C3). v1 no manda cabecera de token: el X-Token de
+ // la 0.0.47 nunca llego a salir (desde la 0.0.41 la peticion no lee node.opts.headers).
this.token = config.token;
+ // REST v1: cuerpo codificado como lo espera el servidor de Mentor 1.0 (la 0.0.38: utils.encode del
+ // content, texto plano y sin verificar el certificado). Desactivado por defecto: entonces sale como
+ // en la 0.0.41 a 0.0.47, el msg en JSON, para no cambiar lo que ya funcionaba con esas versiones.
+ this.encode = config.encode === true || config.encode === "true";
+
this.mentor_id = 0;
if (this.mentor) this.mentor_id = this.mentor.mentor_id;
var channel = "mentor_answer_" + this.mentor_id;
+ // Aviso (solo version v2 por MQTT): en Mentor 1.5 el mentor_id es 0 para todos los capturadores, un
+ // solo topic mentor_answer_0, y el acuse ya identifica la fila por device y time. Con otro valor el
+ // broker del concentrador solo deja acusar a los mentor_id de su MQTT_MENTOR_IDS. En v1 (Mentor 1.0)
+ // el mentor_id tiene su propio sentido y no se avisa.
+ var idNumerico = Number(this.mentor_id);
+ var avisoMentorId = this.version.indexOf("v2") > -1 && (this.priority === 0 || this.priority === 2)
+ && !isNaN(idNumerico) && idNumerico !== 0;
+ var estadoBase = {};
+ if (avisoMentorId) {
+ log.warn("Sender: mentor_id = " + this.mentor_id + ": el concentrador debe tener " + this.mentor_id + " en MQTT_MENTOR_IDS. "
+ + "Coordine con administracion: hay que cambiar el inventario de fleet y redesplegar el concentrador. "
+ + "Si no, los acuses no llegan, las filas se quedan en status 3, se reenvian cada 5 minutos y la purga no las borra");
+ estadoBase = { fill: "yellow", shape: "dot", text: "mentor_id = " + this.mentor_id + ": coordinar con administracion" };
+ node.status(estadoBase);
+ }
+
if (node.url !== "" || node.url_alarm !== "") {
this.opts = {
method: 'POST',
@@ -42,7 +70,7 @@ module.exports = function (RED) {
timeout: node.reqTimeout,
//followRedirect: nodeFollowRedirects,
//forever: nodePersistentHTTP,
- headers: node.token !== "" ? { "X-Token": node.token } : {},
+ headers: {},
encoding: null,
strictSSL: false
};
@@ -64,8 +92,20 @@ module.exports = function (RED) {
node.brokerConn.subscribe(channel, 2, function (topic, msg, packet) {
switch (topic) {
case channel:
- var msg = JSON.parse(msg.toString());
- saveMysql(node, msg);
+ // El REST v2 se resuelve por el codigo de la respuesta: un acuse MQTT no marca.
+ if (esRestC3) break;
+ var acuse;
+ try {
+ acuse = JSON.parse(msg.toString());
+ } catch (e) {
+ log.warn("Sender: acuse ignorado, no es JSON: " + e.message);
+ break;
+ }
+ if (!acuse || typeof acuse !== "object" || acuse.device === undefined || acuse.time === undefined || acuse.status === undefined) {
+ log.warn("Sender: acuse ignorado, le falta device, time o status");
+ break;
+ }
+ saveMysql(node, acuse);
break;
default:
log.error(topic);
@@ -73,7 +113,7 @@ module.exports = function (RED) {
}
}, this.id);
if (this.brokerConn.connected) {
- node.status({ fill: "green", shape: "dot", text: "node-red:common.status.connected" });
+ node.status(avisoMentorId ? estadoBase : { fill: "green", shape: "dot", text: "node-red:common.status.connected" });
}
this.on('close', function (done) {
node.brokerConn.deregister(node, done);
@@ -83,12 +123,28 @@ module.exports = function (RED) {
if (this.mydbConfig) {
this.mydbConfig.connect();
var busy = false;
- var status = {};
- node.mydbConfig.on("state", function (info) {
+ var consultando = false;
+ // Spec 020. Filas pendientes que se despachan por dispositivo y tick (el tick es el
+ // Interval del flujo, 5 s): con paquetes de 1 min, 20 recupera 1 h de atraso en 3
+ // ticks por dispositivo. Configurable: propiedad `lote` del nodo o SENDER_LOTE.
+ var lote = parseInt(config.lote, 10) || parseInt(process.env.SENDER_LOTE, 10) || 20;
+ lote = Math.max(1, Math.min(lote, 500));
+ // Plazo (s) para que el broker confirme (PUBACK) y la marca llegue a la BD antes de
+ // volver a considerar la fila: evita reenviar lo que sigue en vuelo.
+ var plazoPuback = 1000 * (parseInt(process.env.SENDER_PLAZO_PUBACK, 10) || 30);
+ // Plazo (s) sin acuse del concentrador para que una fila en status 3 vuelva a 0.
+ var plazoAck = parseInt(process.env.SENDER_PLAZO_ACK, 10) || 300;
+ var ultimoReintento = 0;
+ var enVuelo = {};
+ var reenvioC3 = esRestC3 ? crearReenvioC3(node, lote) : null;
+ if (esRestC3 && !node.url) this.error("Sender v2: falta la URL de /telemetry");
+ var status = estadoBase;
+ // Se guarda el manejador para quitar solo el propio al cerrar: el config node MySQLdb lo comparten varios nodos.
+ var alCambiarEstadoBd = function (info) {
if (info === "connecting") {
node.status({ fill: "grey", shape: "ring", text: info });
} else if (info === "connected") {
- node.status({ fill: "green", shape: "dot", text: info });
+ node.status(avisoMentorId ? estadoBase : { fill: "green", shape: "dot", text: info });
} else {
if (info === "ECONNREFUSED") {
info = "connection refused";
@@ -98,44 +154,149 @@ module.exports = function (RED) {
}
node.status({ fill: "red", shape: "ring", text: info });
}
- });
-
+ };
+ node.mydbConfig.on("state", alCambiarEstadoBd);
node.on("input", function (msg) {
if (node.mydbConfig.connected) {
- node.status({});
+ node.status(estadoBase);
+ status = estadoBase;
var where = (node.priority === 0 || node.priority === 2) ? " status=0 " : " restful=0 ";
- var sql = "SELECT t1.device, t1.time, t1.content, t1.alarm FROM mqtt_lecturas t1 JOIN ( SELECT MIN(TIME) AS min_value, device FROM mqtt_lecturas WHERE " + where + " GROUP BY device ) AS t2 ON t1.device = t2.device AND t1.time = t2.min_value WHERE t1." + where;
- node.mydbConfig.connection.query(sql, [], function (err, rows) {
- if (err) {
- log.error(err);
- return;
- } else
- for (var item in rows) {
- rows[item].mentor_id = node.mentor_id;
- node.send({ "payload": rows[item].content });
- msg.alarm = rows[item].alarm;
- msg.data = rows[item].content;
- if (node.priority === 0 || node.priority === 2) {
- if (node.brokerConn.connected != null && node.brokerConn.connected) {
- msg.qos = 0;
- msg.retain = false;
- msg.payload = JSON.stringify(rows[item]);
- msg.topic = "mentor_data";
- node.brokerConn.publish(msg);
- // log.error("mqtt");
- }
- } else {
- if (msg.alarm === 1)
- node.opts.url = node.url_alarm;
- else
- node.opts.url = node.url;
-
- msg.payload = utils.encode(rows[item].content);
- node.opts.body = msg.payload;
- sendRestFul(node, msg);
- // log.error(node.opts.url);
+ var esMqtt = (node.priority === 0 || node.priority === 2);
+ // Sin broker no hay nada que despachar: se evita ademas cargar la conexion
+ // compartida con consultas que no pueden terminar en un envio.
+ if (esMqtt && !(node.brokerConn && node.brokerConn.connected)) return;
+ if (esRestC3) {
+ if (!node.url) return;
+ status = {};
+ return reenvioC3.ciclo();
+ }
+ // Un solo ciclo a la vez: la conexion MySQL es unica y compartida con SaveDB;
+ // si el ciclo tarda mas que el intervalo, los siguientes se apilarian
+ // delante de los INSERT (spec 019).
+ if (consultando) return;
+ consultando = true;
+ var ahora = Date.now();
+ Object.keys(enVuelo).forEach(function (clave) {
+ if (enVuelo[clave] <= ahora) delete enVuelo[clave];
+ });
+ // Spec 020 (1): despacho por lotes. Primero se averiguan los dispositivos con
+ // pendientes (indice idx_status_device_time, solo indice) y luego, de uno en
+ // uno, hasta `lote` filas por dispositivo en orden de time ascendente.
+ var reintentos = function (siguiente) {
+ // Spec 020 (2): una fila en status 3 que no recibe el acuse del
+ // concentrador (status 2) en `plazoAck` s vuelve a 0 y se reenvia; el
+ // concentrador es idempotente por (device,time). Como mucho una vez por
+ // minuto: aswered_time cambia solo con cada UPDATE de la fila.
+ if (!esMqtt || ahora - ultimoReintento < 60000) return siguiente();
+ ultimoReintento = ahora;
+ node.mydbConfig.connection.query(
+ "UPDATE mqtt_lecturas SET status=0, restful_tries=LEAST(restful_tries+1,100) WHERE status=3 AND aswered_time < DATE_SUB(NOW(), INTERVAL ? SECOND) LIMIT 500",
+ [plazoAck],
+ function (err, res) {
+ if (err) log.error(err);
+ else if (res && res.affectedRows > 0)
+ log.warn("Sender: " + res.affectedRows + " fila(s) en status 3 sin acuse tras " + plazoAck + " s, vuelven a pendiente");
+ siguiente();
+ });
+ };
+ var despachar = function (registro) {
+ registro.mentor_id = node.mentor_id;
+ node.send({ "payload": registro.content });
+ msg.alarm = registro.alarm;
+ msg.data = registro.content;
+ var clave = registro.device + "|" + registro.time;
+ enVuelo[clave] = Date.now() + plazoPuback;
+ if (esMqtt) {
+ // Mensaje propio por registro: el broker
+ // lo serializa al publicar, pero aqui se
+ // marca en la BD al confirmarse, y para
+ // entonces un objeto compartido ya
+ // apuntaria al ultimo del lote.
+ // Spec 021: el paquete sale con la hora del reloj del
+ // capturador en el instante de publicar (sent_at), en
+ // cada envio y en cada reenvio. La fila de la cola no
+ // cambia: solo la copia que se publica.
+ var sobre = Object.assign({}, registro, {
+ content: conHoraDeEnvio(registro.content, Math.floor(Date.now() / 1000))
+ });
+ var envio = {
+ topic: "mentor_data",
+ payload: JSON.stringify(sobre),
+ qos: 1,
+ retain: false,
+ alarm: registro.alarm,
+ data: registro.content
+ };
+
+ // QoS 1: el callback se dispara con el
+ // PUBACK del broker. Sin confirmacion no
+ // se marca nada y el registro se reintenta
+ // cuando vence el plazo en vuelo.
+ node.brokerConn.publish(envio, function (err) {
+ if (err) {
+ log.error(err);
+ delete enVuelo[clave];
+ return;
}
+ // Solo si sigue pendiente: si el acuse del concentrador (2)
+ // llego antes que este callback, no se degrada a 3.
+ saveMysql(node, {
+ device: registro.device,
+ time: registro.time,
+ status: 3,
+ soloPendiente: true
+ }, function () { delete enVuelo[clave]; });
+ });
+ } else {
+ if (msg.alarm === 1)
+ node.opts.url = node.url_alarm;
+ else
+ node.opts.url = node.url;
+
+ msg.payload = utils.encode(registro.content);
+ node.opts.body = msg.payload;
+ // REST v1: la fila sale hasta que la respuesta la marca (o falla), no
+ // por plazo, y de una en una por dispositivo como en la 0.0.38.
+ sendRestFul(node, msg, function () { delete enVuelo[clave]; });
+ // log.error(node.opts.url);
+ }
+ };
+ reintentos(function () {
+ node.mydbConfig.connection.query("SELECT DISTINCT device FROM mqtt_lecturas WHERE" + where, [], function (err, dispositivos) {
+ if (err) {
+ consultando = false;
+ log.error(err);
+ return;
}
+ var cola = dispositivos.map(function (d) { return d.device; });
+ var siguiente = function () {
+ if (cola.length === 0 || (esMqtt && !node.brokerConn.connected)) {
+ consultando = false;
+ return;
+ }
+ var dispositivo = cola.shift();
+ var propios = Object.keys(enVuelo).filter(function (c) { return c.indexOf(dispositivo + "|") === 0; }).length;
+ if (!esMqtt && propios > 0) return siguiente();
+ var porTick = esMqtt ? lote : 1;
+ node.mydbConfig.connection.query(
+ "SELECT device, time, content, alarm FROM mqtt_lecturas WHERE" + where + "AND device=? ORDER BY time ASC LIMIT ?",
+ [dispositivo, porTick + propios],
+ function (err, rows) {
+ if (err) {
+ log.error(err);
+ } else {
+ // forEach y no for..in: cada registro necesita su
+ // propio ambito, porque el callback del PUBACK se
+ // resuelve despues de que el bucle haya terminado.
+ rows.filter(function (r) { return !enVuelo[r.device + "|" + r.time]; })
+ .slice(0, porTick)
+ .forEach(despachar);
+ }
+ siguiente();
+ });
+ };
+ siguiente();
+ });
});
} else {
node.error("Database not connected", msg);
@@ -155,7 +316,8 @@ module.exports = function (RED) {
if (node.tout) {
clearTimeout(node.tout);
}
- node.mydbConfig.removeAllListeners();
+ if (reenvioC3) reenvioC3.cerrar();
+ node.mydbConfig.removeListener("state", alCambiarEstadoBd);
node.status({});
});
} else {
@@ -164,57 +326,527 @@ module.exports = function (RED) {
}
- function sendRestFul(node, msg) {
- request
- .post(node.opts.url)
- .set('Content-Type', 'application/json')
- .send(msg)
- .end(function (err, response) {
+ // ---------------------------------------------------------------------------------------
+ // REST v2 (version "v2" con un canal REST): contrato C3 del concentrador, POST /telemetry.
+ //
+ // El cuerpo es el `content` de la fila tal como esta guardado, sin codificar ni
+ // reserializar (a diferencia del REST v1, que lo ofusca con utils.encode). Una peticion en
+ // vuelo como maximo por dispositivo, en orden time ASC, id ASC; los dispositivos no se
+ // retienen entre si. Decide por el codigo de la respuesta:
+ // 202 entregada (restful=1)
+ // 400, 413 rechazada (restful=9) con codigo y respuesta; sigue la siguiente
+ // 401, 403, 404, 405, 415 configuracion: se detiene TODO el reenvio y se sondea con una
+ // sola peticion cada 60 s; la fila sigue pendiente
+ // 408, 429, 5xx, red transitorio: ese dispositivo espera 1 s, 2 s ... 60 s
+ // cualquier otro codigo tambien transitorio, con aviso (un 200 no es un 202)
+ // content mayor de 1 MiB: se rechaza sin enviar. Nunca se escribe `status`: no es del
+ // reenvio. Todos los UPDATE llevan `AND restful = 0`: una fila resuelta a mano mientras
+ // estaba en vuelo no se pisa. Las columnas restful_code, restful_response y restful_at y
+ // un restful_tries de al menos 16 bits son del esquema de recepcion del concentrador.
+ // ---------------------------------------------------------------------------------------
+ var C3_MAX_CUERPO = 1048576;
+ var C3_ESPERA_INICIAL = 1000;
+ var C3_ESPERA_MAXIMA = 60000;
+ var C3_SONDEO = 60000;
+ var C3_RESPUESTA_MAX = 1024;
+ var C3_CONFIGURACION = [401, 403, 404, 405, 415];
+
+ function clasificarC3(codigo) {
+ if (codigo === null || codigo === undefined) return "transitorio";
+ if (codigo === 202) return "entregado";
+ if (codigo === 400 || codigo === 413) return "rechazado";
+ if (C3_CONFIGURACION.indexOf(codigo) > -1) return "configuracion";
+ if (codigo === 408 || codigo === 429 || (codigo >= 500 && codigo <= 599)) return "transitorio";
+ return "desconocido";
+ }
+
+ function truncarC3(texto, max) {
+ if (texto === null || texto === undefined) return null;
+ texto = String(texto);
+ if (texto.length <= max) return texto;
+ texto = texto.slice(0, max);
+ var ultimo = texto.charCodeAt(texto.length - 1);
+ // sin dejar media pareja sustituta al cortar
+ return (ultimo >= 0xD800 && ultimo <= 0xDBFF) ? texto.slice(0, -1) : texto;
+ }
+
+ // Entero de una variable de entorno; 0 es un valor valido (desactiva). null si no es entero.
+ function enteroDeEntorno(nombre, defecto) {
+ var crudo = process.env[nombre];
+ if (crudo === undefined || String(crudo).trim() === "") return defecto;
+ return /^\d+$/.test(String(crudo).trim()) ? parseInt(crudo, 10) : null;
+ }
+
+ function crearReenvioC3(node, lote) {
+ var plazo = 1000 * (parseInt(process.env.SENDER_TIMEOUT_REST, 10) || 30);
+ // Fila venenosa: con un codigo HTTP transitorio (5xx, 408 o no contemplado, nunca 429 ni
+ // fallos de red ni el sondeo) y restful_tries, contando ese intento, >= tope, la fila pasa a
+ // rechazada (restful = 9, ATASCADA) y el dispositivo avanza. 0 desactiva. 1440 son unas 24 h
+ // con la espera maxima de 60 s. Un contador persistido (no la antiguedad) sobrevive a los
+ // reinicios y no retira una fila tras otra despues de una caida larga.
+ var maxIntentos = enteroDeEntorno("SENDER_MAX_INTENTOS_TRANSITORIOS", 1440);
+ // Dispositivo atascado: racha de fallos transitorios de al menos N s (por defecto 1800). 0 desactiva.
+ var segAtascado = enteroDeEntorno("SENDER_ALERTA_DISPOSITIVO_ATASCADO", 1800);
+ var configuracionInvalida = maxIntentos === null || maxIntentos > 65535 || segAtascado === null;
+ if (configuracionInvalida) {
+ node.error("Sender REST v2: SENDER_MAX_INTENTOS_TRANSITORIOS debe estar entre 0 y 65535 y SENDER_ALERTA_DISPOSITIVO_ATASCADO ser un entero de segundos; el reenvio no arranca");
+ }
+ var umbralAtascado = 1000 * (segAtascado || 0);
+ var ultimaProcesada = 0;
+ var ultimaComprobacion = 0;
+ var atascados = [];
+ var maxPendientes = parseInt(process.env.SENDER_ALERTA_PENDIENTES, 10) || 10000;
+ var maxAntiguedad = parseInt(process.env.SENDER_ALERTA_ANTIGUEDAD, 10) || 3600;
+ var enVuelo = {};
+ var esperas = {};
+ var parada = null;
+ var sondeando = false;
+ var consultando = false;
+ var cerrado = false;
+ var ultimaMedida = 0;
+ var medida = null;
+ var alertaActiva = false;
+
+ function consulta(sql, parametros, hecho) {
+ node.mydbConfig.connection.query(sql, parametros, hecho);
+ }
+
+ function describirFallo(err) {
+ if (err && (err.timeout || err.code === "ECONNABORTED" || err.code === "ETIMEDOUT")) {
+ return "timeout tras " + (plazo / 1000) + " s";
+ }
+ var texto = err ? ((err.code ? err.code + ": " : "") + (err.message || "")) : "sin respuesta";
+ return truncarC3(texto, 256);
+ }
+
+ // Una sola peticion. El cuerpo va como cadena: superagent serializa con JSON.stringify todo lo que
+ // no sea cadena cuando el Content-Type es JSON (un Buffer saldria como {"type":"Buffer"...}). Llama a `hecho({codigo, respuesta})`; codigo es null si no hubo
+ // respuesta HTTP (red, DNS, tiempo agotado). El token solo va en la cabecera y no se
+ // registra jamas.
+ function enviar(contenido, recibido, hecho) {
+ var terminado = false;
+ var fin = function (resultado) {
+ if (terminado) return;
+ terminado = true;
+ hecho(resultado);
+ };
+ try {
+ var peticion = request.post(node.url)
+ .set("Content-Type", "application/json; charset=utf-8")
+ .set("X-Mentor-Token", String(node.token || ""));
+ if (recibido !== null && recibido !== undefined) peticion = peticion.set("X-Mentor-Received-At", String(recibido));
+ peticion
+ .timeout({ response: plazo, deadline: plazo })
+ .ok(function () { return true; })
+ .buffer(true)
+ .send(contenido)
+ .end(function (err, respuesta) {
+ var res = respuesta || (err && err.response);
+ if (res && typeof res.status === "number") {
+ fin({ codigo: res.status, respuesta: truncarC3(res.text, C3_RESPUESTA_MAX) });
+ } else {
+ fin({ codigo: null, respuesta: describirFallo(err) });
+ }
+ });
+ } catch (e) {
+ fin({ codigo: null, respuesta: describirFallo(e) });
+ }
+ }
+
+ function marcarEntregada(fila, codigo, hecho) {
+ consulta("UPDATE mqtt_lecturas SET restful = 1, restful_code = ?, restful_response = NULL, restful_at = NOW(), "
+ + "restful_tries = LEAST(restful_tries + 1, 65535) WHERE id = ? AND restful = 0", [codigo, fila.id], hecho);
+ }
+
+ function marcarRechazada(fila, codigo, motivo, hecho) {
+ consulta("UPDATE mqtt_lecturas SET restful = 9, restful_code = ?, restful_response = ?, restful_at = NOW(), "
+ + "restful_tries = LEAST(restful_tries + 1, 65535) WHERE id = ? AND restful = 0", [codigo, truncarC3(motivo, C3_RESPUESTA_MAX), fila.id], hecho);
+ }
+
+ function registrarIntento(fila, codigo, respuesta, hecho) {
+ consulta("UPDATE mqtt_lecturas SET restful_tries = LEAST(restful_tries + 1, 65535), restful_code = ?, restful_response = ? "
+ + "WHERE id = ? AND restful = 0", [codigo, truncarC3(respuesta, C3_RESPUESTA_MAX), fila.id], hecho);
+ }
+
+ // Una fila que ya no esta pendiente (resuelta a mano mientras estaba en vuelo) no se pisa.
+ function alResolver(fila, descripcion) {
+ return function (err, res) {
if (err) {
- console.log("unable to complete request, something went wrong: " + err);
- if (error.code === 'ETIMEDOUT') {
- node.error(RED._("common.notification.errors.no-response"), msg);
- setTimeout(function () {
- node.status({
- fill: "red",
- shape: "ring",
- text: "common.notification.errors.no-response"
- });
- }, 10);
+ log.error(err);
+ } else if (res && res.affectedRows === 0) {
+ log.warn("Sender REST v2: la fila id=" + fila.id + " ya no estaba pendiente al marcarla " + descripcion);
+ } else {
+ node.send({ payload: { msg: "record " + descripcion, data: { device: fila.device, time: fila.time, id: fila.id } } });
+ }
+ };
+ }
+
+ function levantarParada() {
+ if (parada) {
+ log.warn("Sender REST v2: reenvio REANUDADO, el backend vuelve a aceptar peticiones autenticadas");
+ parada = null;
+ sondeando = false;
+ }
+ }
+
+ // Entrega una fila. `seguir(true)` si se puede continuar con la siguiente del dispositivo.
+ function entregar(fila, sondeo, seguir) {
+ var contenido = fila.content;
+ if (contenido === null || contenido === undefined) {
+ marcarRechazada(fila, null, "CONTENT_NULO: la fila no tiene content", function (err, res) {
+ alResolver(fila, "rejected")(err, res);
+ seguir(true);
+ });
+ return;
+ }
+ var bytes = Buffer.byteLength(contenido, "utf8");
+ if (bytes > C3_MAX_CUERPO) {
+ log.warn("Sender REST v2: RECHAZO local id=" + fila.id + " device=" + fila.device + " time=" + fila.time + ": " + bytes + " bytes > " + C3_MAX_CUERPO);
+ marcarRechazada(fila, null, "TAMANO_EXCEDIDO: " + bytes + " bytes > " + C3_MAX_CUERPO + " (C3); no se envia", function (err, res) {
+ alResolver(fila, "rejected")(err, res);
+ seguir(true);
+ });
+ return;
+ }
+ enviar(contenido, fila.recibido, function (resultado) {
+ if (cerrado) return seguir(false);
+ var decision = clasificarC3(resultado.codigo);
+ if (decision === "entregado") {
+ delete esperas[fila.device];
+ ultimaProcesada = Date.now();
+ levantarParada();
+ marcarEntregada(fila, resultado.codigo, function (err, res) {
+ alResolver(fila, "delivered")(err, res);
+ seguir(true);
+ });
+ } else if (decision === "rechazado") {
+ delete esperas[fila.device];
+ ultimaProcesada = Date.now();
+ levantarParada();
+ log.warn("Sender REST v2: RECHAZO del backend codigo=" + resultado.codigo + " id=" + fila.id + " device=" + fila.device
+ + " time=" + fila.time + " respuesta=" + truncarC3(resultado.respuesta, 200));
+ marcarRechazada(fila, resultado.codigo, resultado.respuesta, function (err, res) {
+ alResolver(fila, "rejected")(err, res);
+ seguir(true);
+ });
+ } else if (decision === "configuracion") {
+ var nueva = !parada;
+ parada = { codigo: resultado.codigo, desde: nueva ? Date.now() : parada.desde, hasta: Date.now() + C3_SONDEO };
+ sondeando = false;
+ log.error("Sender REST v2: ALERTA, POST " + node.url + " respondio " + resultado.codigo + "; reenvio "
+ + (nueva ? "DETENIDO" : "sigue detenido") + ", ninguna fila se marca rechazada; proximo sondeo en " + (C3_SONDEO / 1000) + " s");
+ registrarIntento(fila, resultado.codigo, resultado.respuesta, function (err) {
+ if (err) log.error(err);
+ seguir(false);
+ });
+ } else if (!sondeo && resultado.codigo !== null && resultado.codigo !== 429 && maxIntentos > 0
+ && (Number(fila.restful_tries) || 0) + 1 >= maxIntentos) {
+ retirarAtascada(fila, resultado, seguir);
+ } else {
+ var previa = esperas[fila.device] || {};
+ var fallos = (previa.fallos || 0) + 1;
+ var espera = Math.min(C3_ESPERA_MAXIMA, C3_ESPERA_INICIAL * Math.pow(2, Math.min(fallos - 1, 30)));
+ esperas[fila.device] = { fallos: fallos, hasta: Date.now() + espera, desde: previa.desde || Date.now() };
+ // Un sondeo sin respuesta concluyente no levanta la parada: otro periodo.
+ if (sondeo && parada) parada.hasta = Date.now() + C3_SONDEO;
+ if (decision === "desconocido") {
+ log.error("Sender REST v2: ALERTA, codigo no contemplado en C3 (" + resultado.codigo + "), se trata como transitorio. id="
+ + fila.id + " device=" + fila.device + " espera=" + (espera / 1000) + " s");
} else {
- node.error(error, msg);
- msg.payload = error.toString() + " : " + node.opts.url;
- msg.statusCode = error.code;
- node.send(msg);
- node.status({
- fill: "red",
- shape: "ring",
- text: error.code
- });
+ log.warn("Sender REST v2: fallo transitorio id=" + fila.id + " device=" + fila.device + " time=" + fila.time
+ + ": " + (resultado.codigo !== null ? "HTTP " + resultado.codigo : resultado.respuesta)
+ + "; el dispositivo espera " + (espera / 1000) + " s");
}
- } else {
- msg.payload = JSON.stringify(response.body);
- msg.headers = response.headers;
- msg.statusCode = response.statusCode;
-
- var obj = JSON.parse(msg.payload);
-
- msg.payload = obj;
- node.send(msg);
- if (obj.status == 1) {
- obj.device = obj.code;
- saveMysql(node, obj);
- node.status({ fill: "green", shape: "ring", text: "OK" });
+ registrarIntento(fila, resultado.codigo, resultado.respuesta, function (err) {
+ if (err) log.error(err);
+ seguir(false);
+ });
+ }
+ });
+ }
+
+ // La fila lleva demasiados intentos con el backend contestando con un fallo transitorio: se
+ // retira a restful = 9 con el motivo (I5) y el dispositivo sigue con la siguiente.
+ function retirarAtascada(fila, resultado, seguir) {
+ var intentos = (Number(fila.restful_tries) || 0) + 1;
+ var motivo = "ATASCADA: " + intentos + " intentos con fallo transitorio (tope SENDER_MAX_INTENTOS_TRANSITORIOS=" + maxIntentos
+ + "); ultimo HTTP " + resultado.codigo + ": " + (resultado.respuesta || "");
+ marcarRechazada(fila, resultado.codigo, motivo, function (err, res) {
+ alResolver(fila, "rejected")(err, res);
+ delete esperas[fila.device];
+ var recordUuid = "desconocido";
+ try { recordUuid = JSON.parse(fila.content).record_uuid || recordUuid; } catch (e) { /* no es JSON */ }
+ log.error("Sender REST v2: ALERTA fila venenosa id=" + fila.id + " device=" + fila.device + " time=" + fila.time
+ + " record_uuid=" + recordUuid + " retirada tras " + intentos + " intentos (ultimo HTTP " + resultado.codigo
+ + "); queda rechazada (restful = 9) y el dispositivo sigue. Para reintentarla: UPDATE mqtt_lecturas SET restful = 0, restful_tries = 0 WHERE id = " + fila.id + ";");
+ seguir(true);
+ });
+ }
+
+ // Dispositivos con una racha de fallos transitorios de al menos `umbralAtascado`. Distingue
+ // «probable fila venenosa» (el backend proceso algo -202, 400 o 413- despues del primer fallo
+ // de la racha) de «probable caida general». No necesita la base. Una vez por minuto.
+ function comprobarAtascados() {
+ var ahora = Date.now();
+ if (umbralAtascado <= 0 || ahora - ultimaComprobacion < 60000) return;
+ ultimaComprobacion = ahora;
+ var antes = atascados;
+ atascados = Object.keys(esperas)
+ .filter(function (d) { return esperas[d].fallos > 0 && esperas[d].desde && esperas[d].desde <= ahora - umbralAtascado; })
+ .map(function (d) { return { device: d, fallos: esperas[d].fallos, desde: esperas[d].desde, backendAceptaOtros: ultimaProcesada > esperas[d].desde }; })
+ .sort(function (a, b) { return a.desde - b.desde; });
+ atascados.forEach(function (a) {
+ log.error("Sender REST v2: ALERTA dispositivo atascado device=" + a.device + " sin avanzar desde " + new Date(a.desde).toISOString()
+ + " (" + a.fallos + " fallos transitorios seguidos, umbral " + segAtascado + " s). "
+ + (a.backendAceptaOtros
+ ? "El backend sigue procesando peticiones de otros dispositivos: probable fila venenosa; se retirara al alcanzar el tope de intentos"
+ : "El backend no ha procesado ninguna peticion desde entonces: probable caida general"));
+ });
+ if (atascados.length === 0 && antes.length > 0) log.warn("Sender REST v2: fin de la alerta de dispositivos atascados");
+ }
+
+ function procesarDispositivo(dispositivo, sondeo, terminado) {
+ consulta("SELECT id, device, time, content, restful_tries, UNIX_TIMESTAMP(sent_time) AS recibido FROM mqtt_lecturas "
+ + "WHERE restful = 0 AND device = ? ORDER BY time ASC, id ASC LIMIT ?", [dispositivo, sondeo ? 1 : lote], function (err, filas) {
+ if (err) {
+ log.warn("Sender REST v2: base de recepcion no disponible atendiendo " + dispositivo + ": " + (err.code || err.message));
+ return terminado();
+ }
+ var i = 0;
+ var siguiente = function (continuar) {
+ if (!continuar || cerrado || i >= filas.length || (!sondeo && parada)) return terminado();
+ var fila = filas[i++];
+ fila.recibido = Number(fila.recibido) > 0 ? Math.floor(Number(fila.recibido)) : null;
+ entregar(fila, sondeo, siguiente);
+ };
+ siguiente(true);
+ });
+ }
+
+ // Alerta por acumulacion de pendientes: mas de `maxPendientes` filas, o la mas antigua con
+ // mas de `maxAntiguedad` s. Se mide como mucho una vez por minuto, sin leer filas.
+ function medirPendientes(hecho) {
+ var ahora = Date.now();
+ if (cerrado || ahora - ultimaMedida < 60000) return hecho();
+ ultimaMedida = ahora;
+ var concluir = function () {
+ var antes = alertaActiva;
+ alertaActiva = medida.pendientes > maxPendientes || (medida.pendientes > 0 && medida.antiguedad > maxAntiguedad);
+ if (alertaActiva) {
+ log.error("Sender REST v2: ALERTA de pendientes, " + medida.pendientes + " filas (umbral " + maxPendientes
+ + "), la mas antigua de hace " + medida.antiguedad + " s (umbral " + maxAntiguedad + " s). Nada pendiente se borra solo");
+ } else if (antes) {
+ log.warn("Sender REST v2: fin de la alerta de pendientes, " + medida.pendientes + " filas");
+ }
+ hecho();
+ };
+ consulta("SELECT COUNT(*) AS pendientes, MIN(id) AS primero FROM mqtt_lecturas WHERE restful = 0", [], function (err, filas) {
+ if (err || !filas || !filas[0]) {
+ if (err) log.warn("Sender REST v2: no se pudo medir los pendientes: " + (err.code || err.message));
+ return hecho();
+ }
+ var pendientes = Number(filas[0].pendientes) || 0;
+ if (!pendientes) {
+ medida = { pendientes: 0, antiguedad: 0 };
+ return concluir();
+ }
+ consulta("SELECT UNIX_TIMESTAMP(sent_time) AS recibido FROM mqtt_lecturas WHERE id = ?", [filas[0].primero], function (err2, primera) {
+ var recibido = (!err2 && primera && primera[0]) ? Number(primera[0].recibido) : 0;
+ medida = { pendientes: pendientes, antiguedad: recibido > 0 ? Math.max(0, Math.floor(Date.now() / 1000) - recibido) : 0 };
+ concluir();
+ });
+ });
+ }
+
+ function mostrarEstado() {
+ if (cerrado) return;
+ if (parada) {
+ node.status({ fill: "red", shape: "ring", text: "reenvio detenido (HTTP " + parada.codigo + ")" });
+ } else if (alertaActiva) {
+ node.status({ fill: "yellow", shape: "dot", text: "ALERTA " + medida.pendientes + " pendientes" });
+ } else if (atascados.length > 0) {
+ node.status({ fill: "yellow", shape: "dot", text: "ALERTA " + atascados.length + " dispositivo(s) atascado(s)" });
+ } else if (medida) {
+ node.status({ fill: "green", shape: "dot", text: medida.pendientes + " pendientes" });
+ } else {
+ node.status({ fill: "green", shape: "dot", text: "connected" });
+ }
+ }
+
+ // Un ciclo por tick del nodo. Lanza el trabajo de cada dispositivo y vuelve sin
+ // esperarlo: uno lento o caido no retiene a los demas.
+ function ciclo() {
+ if (cerrado) return;
+ if (configuracionInvalida) return node.status({ fill: "red", shape: "ring", text: "configuracion no valida" });
+ comprobarAtascados();
+ if (consultando) return;
+ // Parado, un sondeo en vuelo decide por su cuenta; si no, se sigue consultando los pendientes (solo
+ // indice) para saber si queda algo que probar.
+ if (parada && sondeando) return mostrarEstado();
+ consultando = true;
+ consulta("SELECT DISTINCT device FROM mqtt_lecturas WHERE restful = 0", [], function (err, filas) {
+ consultando = false;
+ if (err) {
+ log.warn("Sender REST v2: base de recepcion no disponible, se reintenta en el siguiente ciclo: " + (err.code || err.message));
+ return;
+ }
+ var dispositivos = filas.map(function (f) { return f.device; });
+ var sondeo = false;
+ if (parada) {
+ if (dispositivos.length === 0) {
+ // Sin pendientes no hay peticion que pueda levantar la parada: se da por terminada. La siguiente fila que
+ // entre vuelve a probar el envio y, si el problema sigue (p. ej. el token), vuelve a la parada al instante.
+ log.warn("Sender REST v2: no quedan filas pendientes, se da por terminada la parada (HTTP " + parada.codigo + "); la proxima fila vuelve a probar el envio");
+ parada = null;
+ sondeando = false;
+ medida = { pendientes: 0, antiguedad: 0 };
+ alertaActiva = false;
+ return mostrarEstado();
}
+ if (Date.now() < parada.hasta) return mostrarEstado();
+ sondeo = true;
+ }
+ // Se olvida la espera de los dispositivos sin pendientes (p. ej. resueltos a mano).
+ Object.keys(esperas).forEach(function (d) {
+ if (dispositivos.indexOf(d) === -1 && !enVuelo[d]) delete esperas[d];
+ });
+ var lanzar = function (dispositivo, esSondeo) {
+ enVuelo[dispositivo] = true;
+ procesarDispositivo(dispositivo, esSondeo, function () {
+ delete enVuelo[dispositivo];
+ if (esSondeo) sondeando = false;
+ mostrarEstado();
+ });
+ };
+ var ahora = Date.now();
+ for (var i = 0; i < dispositivos.length; i++) {
+ var d = dispositivos[i];
+ if (enVuelo[d] || (esperas[d] && ahora < esperas[d].hasta)) continue;
+ if (sondeo) {
+ sondeando = true;
+ lanzar(d, true);
+ break; // una sola peticion de sondeo
+ }
+ lanzar(d, false);
+ }
+ medirPendientes(mostrarEstado);
+ });
+ }
+
+ return {
+ ciclo: ciclo,
+ cerrar: function () { cerrado = true; }
+ };
+ }
+
+ // REST v1 (Mentor 1.0), como hasta la 0.0.38: POST con el `content` ofuscado por
+ // utils.encode como cuerpo y la fila se marca si la respuesta trae `status == 1`. Desde la
+ // 0.0.41 usaba superagent pero enviaba el msg entero como JSON y fallaba al manejar un error
+ // (la variable `error` no existe). El paquete `request` de la 0.0.38 ya no se instala:
+ // superagent con el mismo cuerpo. El Content-Type se fija porque sin el superagent manda
+ // application/x-www-form-urlencoded; `text/plain` sin charset, para que el servidor
+ // decodifique el cuerpo igual que cuando no llevaba ninguno. `hecho` se llama siempre, al
+ // terminar la peticion.
+ function sendRestFul(node, msg, hecho) {
+ var url = node.opts.url;
+ var salida = Object.assign({}, msg);
+ var fin = function () { if (hecho) hecho(); };
+ var peticion;
+ try {
+ if (node.encode) {
+ // Encode activado, como la 0.0.38: el content codificado en texto plano y sin verificar el
+ // certificado del servidor de Mentor 1.0 (strictSSL: false). El REST v2 (C3) si lo verifica.
+ peticion = request
+ .post(url)
+ .set("Content-Type", "text/plain");
+ if (typeof peticion.disableTLSCerts === "function") peticion = peticion.disableTLSCerts();
+ peticion = peticion.send(node.opts.body);
+ } else {
+ // Por defecto, como la 0.0.41 a 0.0.47: el msg en JSON (payload codificado, data en claro y
+ // alarm), con el certificado verificado. Copia: el msg se reutiliza para la fila siguiente.
+ peticion = request
+ .post(url)
+ .set("Content-Type", "application/json")
+ .send(JSON.parse(JSON.stringify(msg)));
+ }
+ peticion = peticion
+ .timeout(node.reqTimeout)
+ .ok(function () { return true; })
+ .buffer(true);
+ } catch (e) {
+ node.error(e, salida);
+ node.status({ fill: "red", shape: "ring", text: e.code || "error" });
+ return fin();
+ }
+ peticion.end(function (error, response) {
+ fin();
+ node.status({});
+ if (error || !response) {
+ error = error || new Error("sin respuesta");
+ if (error.code === 'ETIMEDOUT' || error.code === 'ECONNABORTED' || error.timeout) {
+ node.error(RED._("common.notification.errors.no-response"), salida);
+ node.status({
+ fill: "red",
+ shape: "ring",
+ text: "common.notification.errors.no-response"
+ });
+ } else {
+ node.error(error, salida);
+ salida.payload = error.toString() + " : " + url;
+ salida.statusCode = error.code;
+ node.send(salida);
+ node.status({
+ fill: "red",
+ shape: "ring",
+ text: error.code || "error"
+ });
+ }
+ } else {
+ var obj;
+ try {
+ obj = JSON.parse(response.text);
+ } catch (e) {
+ node.error("Respuesta no valida de " + url + " (HTTP " + response.status + "): " + e.message, salida);
+ return;
+ }
+ salida.headers = response.headers;
+ salida.statusCode = response.status;
+ salida.payload = obj;
+ node.send(salida);
+ if (obj && obj.status == 1) {
+ obj.device = obj.code;
+ saveMysql(node, obj);
+ node.status({ fill: "green", shape: "ring", text: "OK" });
}
}
- );
+ });
+ }
+
+ // Spec 021. Anade "sent_at" (epoch s del reloj del capturador al publicar) al paquete
+ // serializado en content, sin reformatear el resto: se inserta antes de la llave final, asi
+ // que los bytes del paquete original se conservan. Si content no es un objeto JSON, o ya
+ // trae sent_at, sale tal cual (el concentrador aplica entonces su regla antigua).
+ function conHoraDeEnvio(content, ahora) {
+ if (typeof content !== "string") return content;
+ var paquete;
+ try {
+ paquete = JSON.parse(content);
+ } catch (e) {
+ return content;
+ }
+ if (!paquete || typeof paquete !== "object" || Array.isArray(paquete)) return content;
+ if (Object.prototype.hasOwnProperty.call(paquete, "sent_at")) return content;
+ var fin = content.lastIndexOf("}");
+ var campo = '"sent_at":' + ahora;
+ var vacio = Object.keys(paquete).length === 0;
+ return content.slice(0, fin) + (vacio ? "" : ",") + campo + content.slice(fin);
}
- function saveMysql(node, msg) {
+ function saveMysql(node, msg, hecho) {
var update = (node.priority === 0 || node.priority === 2) ? " restful=1, status=" : " status=1, restful=";
- node.mydbConfig.connection.query("UPDATE mqtt_lecturas SET " + update + msg.status + " WHERE time*1=" + msg.time + " And device='" + msg.device + "'", [],
+ node.mydbConfig.connection.query("UPDATE mqtt_lecturas SET " + update + msg.status + " WHERE device='" + msg.device + "' And time='" + String(msg.time).replace(/[^0-9]/g, "") + "'" + (msg.soloPendiente ? " And status=0" : ""), [],
function (err, rows) {
+ if (hecho) hecho();
if (err) {
log.error(err);
} else