[
  {
    "id": "k0rr1tab0000001",
    "type": "tab",
    "label": "Korri · SCADA",
    "disabled": false,
    "info": "Envía lecturas a POST /api/v1/signals y alarmas a POST /api/v1/gmao/alarms de Korri.\n\nAntes de usarlo define KORRI_API_KEY (clave korri_… de uso SCADA creada en Korri) como variable de entorno del proceso de Node-RED, o en las propiedades de esta pestaña (Environment variables). KORRI_URL vale https://korri.es salvo que uses otro servidor.\n\nGuía completa: docs/scada/README.md",
    "env": [
      {
        "name": "KORRI_URL",
        "value": "https://korri.es",
        "type": "str"
      },
      {
        "name": "KORRI_MAPPING_JSON",
        "value": "{\"opcua\": [{\"key\": \"ns=2;s=Compresor2.TempAceite\", \"asset\": \"Compresor 2\", \"tag\": \"temperatura\", \"unit\": \"\\u00b0C\"}], \"mqtt\": [{\"key\": \"planta/compresor/presion\", \"asset\": \"Compresor 2\", \"tag\": \"presion\", \"unit\": \"bar\"}], \"modbus\": [{\"index\": 0, \"asset\": \"Compresor 2\", \"tag\": \"temperatura\", \"scale\": 0.1}], \"s7\": [{\"key\": \"DB1,REAL0\", \"asset\": \"Compresor 2\", \"tag\": \"temperatura_s7\", \"unit\": \"\\u00b0C\"}]}",
        "type": "str"
      }
    ]
  },
  {
    "id": "k0rr1cmt000001",
    "type": "comment",
    "z": "k0rr1tab0000001",
    "name": "Lecturas → /api/v1/signals (conecta aquí tus nodos OPC UA, Modbus, S7 o MQTT)",
    "info": "Cada mensaje es una lectura: msg.payload = { asset, tag, value, unit } o un número con msg.asset y msg.topic (tag). Se acumulan y se envían cada 60 s, hasta 200 por petición.",
    "x": 330,
    "y": 40,
    "wires": []
  },
  {
    "id": "k0rr1inj000001",
    "type": "inject",
    "z": "k0rr1tab0000001",
    "name": "Ejemplo: lectura",
    "props": [
      {
        "p": "payload"
      },
      {
        "p": "topic",
        "vt": "str"
      }
    ],
    "repeat": "",
    "crontab": "",
    "once": false,
    "onceDelay": 0.1,
    "topic": "",
    "payload": "{\"asset\":\"Compresor 2\",\"tag\":\"temperatura_aceite\",\"value\":78.4,\"unit\":\"°C\"}",
    "payloadType": "json",
    "x": 150,
    "y": 100,
    "wires": [
      [
        "k0rr1fn0000001"
      ]
    ]
  },
  {
    "id": "k0rr1inj000002",
    "type": "inject",
    "z": "k0rr1tab0000001",
    "name": "Ejemplo: contador de horas",
    "props": [
      {
        "p": "payload"
      },
      {
        "p": "topic",
        "vt": "str"
      }
    ],
    "repeat": "",
    "crontab": "",
    "once": false,
    "onceDelay": 0.1,
    "topic": "horas_funcionamiento",
    "payload": "1520",
    "payloadType": "num",
    "x": 170,
    "y": 140,
    "wires": [
      [
        "k0rr1chg000001"
      ]
    ]
  },
  {
    "id": "k0rr1chg000001",
    "type": "change",
    "z": "k0rr1tab0000001",
    "name": "máquina y unidad",
    "rules": [
      {
        "t": "set",
        "p": "asset",
        "pt": "msg",
        "to": "Compresor 2",
        "tot": "str"
      },
      {
        "t": "set",
        "p": "unit",
        "pt": "msg",
        "to": "h",
        "tot": "str"
      }
    ],
    "action": "",
    "property": "",
    "from": "",
    "to": "",
    "reg": false,
    "x": 380,
    "y": 140,
    "wires": [
      [
        "k0rr1fn0000001"
      ]
    ]
  },
  {
    "id": "k0rr1inj000003",
    "type": "inject",
    "z": "k0rr1tab0000001",
    "name": "Enviar cada 60 s",
    "props": [
      {
        "p": "payload"
      },
      {
        "p": "topic",
        "vt": "str"
      }
    ],
    "repeat": "60",
    "crontab": "",
    "once": true,
    "onceDelay": "10",
    "topic": "korri/flush",
    "payload": "",
    "payloadType": "date",
    "x": 160,
    "y": 200,
    "wires": [
      [
        "k0rr1fn0000001",
        "k0rr1fn0000002"
      ]
    ]
  },
  {
    "id": "k0rr1fn0000001",
    "type": "function",
    "z": "k0rr1tab0000001",
    "name": "Acumular lecturas",
    "func": "// Korri · acumula lecturas y las envía en bloque a POST /api/v1/signals.\n//\n// Entrada A (una lectura por mensaje, desde OPC UA, Modbus, S7, MQTT…):\n//   msg.payload = { asset, tag, value, unit, message, time }      (objeto completo)\n//   o msg.payload = número, con msg.asset (máquina), msg.topic (tag) y msg.unit opcional.\n//   Un booleano se envía como 0/1. Solo si msg.alarm === true se envía como alarma (alarm: true/false).\n// Entrada B: msg.topic === 'korri/flush' (inject «Enviar cada 60 s») → sale la petición HTTP.\n//\n// Se guarda la última lectura de cada máquina + tag: Korri conserva un punto cada 10 min por variable,\n// así que enviar cada 60 s es suficiente. Para alarmas que no deben perderse usa /api/v1/gmao/alarms.\nconst MAX_PER_REQUEST = 200;            // límite de Korri por petición\nconst MAX_BUFFER = 1000;                // tope de memoria si Korri no responde durante mucho tiempo\nconst buffer = flow.get('korriBuffer') || {};\n\nif (msg.topic === 'korri/flush') {\n    const pending = Object.values(buffer);\n    if (!pending.length) return null;\n    const key = env.get('KORRI_API_KEY');\n    if (!key || !String(key).startsWith('korri_')) {\n        node.status({ fill: 'red', shape: 'ring', text: 'falta KORRI_API_KEY' });\n        node.error('Falta la variable de entorno KORRI_API_KEY (clave korri_… de uso SCADA).', msg);\n        return null;\n    }\n    const batch = pending.slice(0, MAX_PER_REQUEST);\n    const rest = {};\n    for (const reading of pending.slice(MAX_PER_REQUEST)) rest[reading.asset + '|' + reading.tag] = reading;\n    flow.set('korriBuffer', rest);\n    const base = String(env.get('KORRI_URL') || 'https://korri.es').replace(/\\/+$/, '');\n    node.status({ fill: 'blue', shape: 'dot', text: 'enviando ' + batch.length + ' lecturas' });\n    return {\n        url: base + '/api/v1/signals',\n        headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + key },\n        payload: { readings: batch },\n        korri: { kind: 'signals', readings: batch }\n    };\n}\n\n// Lectura → forma de Korri\nlet reading = msg.payload;\nif (reading === null || typeof reading !== 'object' || Array.isArray(reading)) {\n    reading = { asset: msg.asset, tag: msg.topic, unit: msg.unit, message: msg.message };\n    if (msg.alarm === true) reading.alarm = Boolean(msg.payload);\n    else reading.value = msg.payload;\n} else {\n    reading = Object.assign({}, reading);\n}\nif (typeof reading.value === 'boolean') reading.value = reading.value ? 1 : 0;   // bits de estado como 1/0\nif (typeof reading.value === 'string' && !reading.value.trim()) { node.warn('Valor vacío descartado.'); return null; }\nif (typeof reading.value === 'string') reading.value = Number(reading.value.trim().replace(',', '.'));   // Korri no admite coma decimal\nif (reading.value !== undefined && !Number.isFinite(reading.value)) { node.warn('Valor no numérico descartado: ' + JSON.stringify(msg.payload)); return null; }\nif (!reading.asset || !reading.tag) { node.warn('Falta asset (máquina) o tag en la lectura: ' + JSON.stringify(reading)); return null; }\n// Hora de la medida en ISO 8601 (Korri no entiende milisegundos epoch: los cambiaría por la hora de llegada).\nif (typeof reading.time === 'number') { const date = new Date(reading.time); if (!Number.isFinite(date.getTime())) { node.warn('Fecha no válida.'); return null; } reading.time = date.toISOString(); }\nif (!reading.time) reading.time = (msg.sourceTimestamp ? new Date(msg.sourceTimestamp) : new Date()).toISOString();\nfor (const field of ['unit', 'message']) if (reading[field] === undefined || reading[field] === '') delete reading[field];\n\nconst id = reading.asset + '|' + reading.tag;\nif (!buffer[id] && Object.keys(buffer).length >= MAX_BUFFER) { node.warn('Búfer lleno: se descarta ' + id); return null; }\nbuffer[id] = reading;\nflow.set('korriBuffer', buffer);\nnode.status({ fill: 'grey', shape: 'dot', text: Object.keys(buffer).length + ' en espera' });\nreturn null;",
    "outputs": 1,
    "timeout": 0,
    "noerr": 0,
    "initialize": "",
    "finalize": "",
    "libs": [],
    "x": 560,
    "y": 120,
    "wires": [
      [
        "k0rr1http00001"
      ]
    ]
  },
  {
    "id": "k0rr1http00001",
    "type": "http request",
    "z": "k0rr1tab0000001",
    "name": "POST /api/v1/signals",
    "method": "POST",
    "ret": "obj",
    "paytoqs": "ignore",
    "url": "",
    "tls": "",
    "persist": false,
    "proxy": "",
    "insecureHTTPParser": false,
    "authType": "",
    "senderr": false,
    "headers": [],
    "x": 760,
    "y": 120,
    "wires": [
      [
        "k0rr1fn0000003"
      ]
    ]
  },
  {
    "id": "k0rr1cmt000002",
    "type": "comment",
    "z": "k0rr1tab0000001",
    "name": "Alarmas → /api/v1/gmao/alarms (una por mensaje; despejar con state: cleared)",
    "info": "",
    "x": 320,
    "y": 280,
    "wires": []
  },
  {
    "id": "k0rr1inj000004",
    "type": "inject",
    "z": "k0rr1tab0000001",
    "name": "Ejemplo: alarma activa",
    "props": [
      {
        "p": "payload"
      },
      {
        "p": "topic",
        "vt": "str"
      }
    ],
    "repeat": "",
    "crontab": "",
    "once": false,
    "onceDelay": 0.1,
    "topic": "",
    "payload": "{\"asset\":\"Compresor 2\",\"alarmId\":\"CMP2-TEMP-HI\",\"message\":\"Temperatura de aceite alta\",\"severity\":\"high\",\"value\":92.5,\"unit\":\"°C\"}",
    "payloadType": "json",
    "x": 160,
    "y": 340,
    "wires": [
      [
        "k0rr1fn0000002"
      ]
    ]
  },
  {
    "id": "k0rr1inj000005",
    "type": "inject",
    "z": "k0rr1tab0000001",
    "name": "Ejemplo: alarma despejada",
    "props": [
      {
        "p": "payload"
      },
      {
        "p": "topic",
        "vt": "str"
      }
    ],
    "repeat": "",
    "crontab": "",
    "once": false,
    "onceDelay": 0.1,
    "topic": "",
    "payload": "{\"asset\":\"Compresor 2\",\"alarmId\":\"CMP2-TEMP-HI\",\"state\":\"cleared\"}",
    "payloadType": "json",
    "x": 170,
    "y": 380,
    "wires": [
      [
        "k0rr1fn0000002"
      ]
    ]
  },
  {
    "id": "k0rr1inj000006",
    "type": "inject",
    "z": "k0rr1tab0000001",
    "name": "Ejemplo: máquina parada",
    "props": [
      {
        "p": "payload"
      },
      {
        "p": "topic",
        "vt": "str"
      }
    ],
    "repeat": "",
    "crontab": "",
    "once": false,
    "onceDelay": 0.1,
    "topic": "",
    "payload": "{\"asset\":\"Compresor 2\",\"alarmId\":\"CMP2-DISPARO\",\"message\":\"Disparo térmico del motor\",\"severity\":\"critical\",\"machineStopped\":true}",
    "payloadType": "json",
    "x": 160,
    "y": 420,
    "wires": [
      [
        "k0rr1fn0000002"
      ]
    ]
  },
  {
    "id": "k0rr1fn0000002",
    "type": "function",
    "z": "k0rr1tab0000001",
    "name": "Preparar alarma",
    "func": "// Korri · prepara una alarma para POST /api/v1/gmao/alarms (una alarma por petición).\n//\n// Alarma activa:   msg.payload = { asset, alarmId, message, severity, machineStopped, value, unit, detail, occurredAt }\n// Alarma despejada: msg.payload = { asset, alarmId, state: 'cleared' }\n// Con msg.topic === 'korri/flush' reenvía las alarmas que no se pudieron entregar (cola korriAlarmQueue).\nconst key = env.get('KORRI_API_KEY');\nconst base = String(env.get('KORRI_URL') || 'https://korri.es').replace(/\\/+$/, '');\nconst build = alarm => ({\n    url: base + '/api/v1/gmao/alarms',\n    headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + key },\n    payload: alarm,\n    korri: { kind: 'alarm', alarm: alarm }\n});\nconst keyOk = () => {\n    if (key && String(key).startsWith('korri_')) return true;\n    node.status({ fill: 'red', shape: 'ring', text: 'falta KORRI_API_KEY' });\n    node.error('Falta la variable de entorno KORRI_API_KEY (clave korri_… de uso SCADA).', msg);\n    return false;\n};\n\nif (msg.topic === 'korri/flush') {\n    const queue = flow.get('korriAlarmQueue') || [];\n    if (!queue.length || !keyOk()) return null;\n    flow.set('korriAlarmQueue', []);\n    node.status({ fill: 'blue', shape: 'dot', text: 'reenviando ' + queue.length });\n    return [queue.map(build)];\n}\n\nconst alarm = Object.assign({}, msg.payload);\nif (!alarm.asset) { node.warn('Falta asset (id o nombre de la máquina en Korri).'); return null; }\nif (alarm.state === 'cleared') {\n    if (!alarm.alarmId) { node.warn('Para despejar una alarma hace falta su alarmId.'); return null; }\n} else {\n    if (!alarm.message) { node.warn('Falta message (qué ocurre).'); return null; }\n    if (!alarm.occurredAt) alarm.occurredAt = new Date().toISOString();\n}\nif (!keyOk()) return null;\nnode.status({ fill: 'blue', shape: 'dot', text: (alarm.state === 'cleared' ? 'despejada ' : 'activa ') + (alarm.alarmId || alarm.asset) });\nreturn build(alarm);",
    "outputs": 1,
    "timeout": 0,
    "noerr": 0,
    "initialize": "",
    "finalize": "",
    "libs": [],
    "x": 550,
    "y": 360,
    "wires": [
      [
        "k0rr1http00002"
      ]
    ]
  },
  {
    "id": "k0rr1http00002",
    "type": "http request",
    "z": "k0rr1tab0000001",
    "name": "POST /api/v1/gmao/alarms",
    "method": "POST",
    "ret": "obj",
    "paytoqs": "ignore",
    "url": "",
    "tls": "",
    "persist": false,
    "proxy": "",
    "insecureHTTPParser": false,
    "authType": "",
    "senderr": false,
    "headers": [],
    "x": 760,
    "y": 360,
    "wires": [
      [
        "k0rr1fn0000003"
      ]
    ]
  },
  {
    "id": "k0rr1fn0000003",
    "type": "function",
    "z": "k0rr1tab0000001",
    "name": "Comprobar respuesta",
    "func": "// Korri · revisa la respuesta. Errores temporales (sin red, 429, 5xx, servidor despertando) → se vuelve a\n// intentar en el siguiente «Enviar cada 60 s». Errores de configuración (400, 401, 402, 403, 413) → se avisan y no se repiten.\nconst code = Number(msg.statusCode);\nconst kind = msg.korri && msg.korri.kind;\n\nif (code >= 200 && code < 300) {\n    const body = msg.payload || {};\n    if (kind === 'signals') {\n        if (body.rejected) {\n            const errors = (body.results || []).filter(r => !r.ok).map(r => r.error);\n            node.warn('Korri rechazó ' + body.rejected + ' lecturas: ' + errors.slice(0, 5).join(' | '));\n        }\n        node.status({ fill: body.rejected ? 'yellow' : 'green', shape: 'dot', text: 'señales: ' + body.accepted + ' ok, ' + body.rejected + ' rechazadas' });\n    } else {\n        node.status({ fill: 'green', shape: 'dot', text: 'alarma: ' + body.status + (body.assetMatched === false ? ' (máquina no encontrada)' : '') });\n        if (body.assetMatched === false) node.warn('Alarma registrada, pero la máquina no coincide con ninguna de Korri: ' + JSON.stringify(msg.korri.alarm.asset));\n    }\n    return msg;\n}\n\nconst temporary = !Number.isFinite(code) || code === 0 || code === 429 || code >= 500;\nconst reason = (msg.payload && msg.payload.error) || msg.payload;\nif (temporary && kind === 'signals') {\n    // Devuelve las lecturas al búfer sin pisar las que hayan llegado después.\n    const buffer = flow.get('korriBuffer') || {};\n    for (const reading of msg.korri.readings) {\n        const id = reading.asset + '|' + reading.tag;\n        if (!buffer[id]) buffer[id] = reading;\n    }\n    flow.set('korriBuffer', buffer);\n} else if (temporary && kind === 'alarm') {\n    const queue = flow.get('korriAlarmQueue') || [];\n    if (queue.length < 100) queue.push(msg.korri.alarm);\n    flow.set('korriAlarmQueue', queue);\n}\nconst text = (temporary ? 'reintento: ' : 'error: ') + (msg.statusCode || 'sin respuesta');\nnode.status({ fill: temporary ? 'yellow' : 'red', shape: 'ring', text: text });\nif (temporary) node.warn('Korri no disponible (' + msg.statusCode + '); se reintentará. ' + JSON.stringify(reason));\nelse node.error('Korri respondió ' + code + ': ' + JSON.stringify(reason), msg);\nreturn msg;",
    "outputs": 1,
    "timeout": 0,
    "noerr": 0,
    "initialize": "",
    "finalize": "",
    "libs": [],
    "x": 1000,
    "y": 240,
    "wires": [
      [
        "k0rr1dbg000001"
      ]
    ]
  },
  {
    "id": "k0rr1dbg000001",
    "type": "debug",
    "z": "k0rr1tab0000001",
    "name": "Respuesta de Korri",
    "active": true,
    "tosidebar": true,
    "console": false,
    "tostatus": false,
    "complete": "true",
    "targetType": "full",
    "statusVal": "",
    "statusType": "auto",
    "x": 1210,
    "y": 240,
    "wires": []
  },
  {
    "id": "korriadapter0",
    "type": "function",
    "z": "k0rr1tab0000001",
    "name": "Adaptar OPC UA",
    "func": "// Configure KORRI_MAPPING_JSON in the tab (mapping only, never credentials).\nconst source = \"opcua\";\nlet mappings;\ntry { mappings = JSON.parse(env.get('KORRI_MAPPING_JSON') || '{}')[source] || []; }\ncatch { node.error('KORRI_MAPPING_JSON no es JSON válido.'); return null; }\nconst readings = [], alarms = [];\nfor (const m of mappings) {\n    if (['opcua', 'mqtt'].includes(source) && m.key !== msg.topic) continue;\n    if (source === 'opcua' && msg.statusCode && msg.statusCode.value !== undefined && msg.statusCode.value !== 0) { node.warn('Lectura OPC UA de mala calidad.'); continue; }\n    let data = msg.payload;\n    if (source === 'mqtt') { try { data = JSON.parse(String(data)); } catch { data = String(data); } }\n    if (source === 'modbus') data = (Array.isArray(data) ? data : data?.data)?.[m.index || 0];\n    else if (source === 's7') data = data && typeof data === 'object' ? data[m.key] : (msg.topic === m.key ? data : undefined);\n    else if (data && typeof data === 'object' && !Array.isArray(data)) data = data.value;\n    if (data === null || data === undefined || String(data).trim() === '') continue;\n    const value = typeof data === 'boolean' ? Number(data) : Number(String(data).replace(',', '.'));\n    if (!Number.isFinite(value) || !m.asset || !m.tag) { node.warn('Mapping o valor no válido.'); continue; }\n    if (m.kind === 'alarm') {\n        const id = JSON.stringify([source, m.asset, m.alarmId || m.tag]);\n        const states = flow.get('korriAdapterStates') || {};\n        const active = value !== 0;\n        if (states[id] === active || (states[id] === undefined && !active)) continue;\n        states[id] = active; flow.set('korriAdapterStates', states);\n        alarms.push({payload: active ? { asset:m.asset, alarmId:m.alarmId || m.tag, message:m.message || m.tag, severity:m.severity || 'high', machineStopped:m.machineStopped === true } : {asset:m.asset, alarmId:m.alarmId || m.tag, state:'cleared'}});\n    } else {\n        const date = new Date(msg.sourceTimestamp || Date.now());\n        if (!Number.isFinite(date.getTime())) { node.warn('Fecha no válida.'); continue; }\n        readings.push({payload:{asset:m.asset, tag:m.tag, value:value * (m.scale ?? 1) + (m.offset ?? 0), unit:m.unit || '', time:date.toISOString()}});\n    }\n}\nreturn [readings, alarms];",
    "outputs": 2,
    "timeout": 0,
    "noerr": 0,
    "initialize": "",
    "finalize": "",
    "libs": [],
    "x": 200,
    "y": 740,
    "wires": [
      [
        "k0rr1fn0000001"
      ],
      [
        "k0rr1fn0000002"
      ]
    ]
  },
  {
    "id": "korriadapter1",
    "type": "function",
    "z": "k0rr1tab0000001",
    "name": "Adaptar MQTT",
    "func": "// Configure KORRI_MAPPING_JSON in the tab (mapping only, never credentials).\nconst source = \"mqtt\";\nlet mappings;\ntry { mappings = JSON.parse(env.get('KORRI_MAPPING_JSON') || '{}')[source] || []; }\ncatch { node.error('KORRI_MAPPING_JSON no es JSON válido.'); return null; }\nconst readings = [], alarms = [];\nfor (const m of mappings) {\n    if (['opcua', 'mqtt'].includes(source) && m.key !== msg.topic) continue;\n    if (source === 'opcua' && msg.statusCode && msg.statusCode.value !== undefined && msg.statusCode.value !== 0) { node.warn('Lectura OPC UA de mala calidad.'); continue; }\n    let data = msg.payload;\n    if (source === 'mqtt') { try { data = JSON.parse(String(data)); } catch { data = String(data); } }\n    if (source === 'modbus') data = (Array.isArray(data) ? data : data?.data)?.[m.index || 0];\n    else if (source === 's7') data = data && typeof data === 'object' ? data[m.key] : (msg.topic === m.key ? data : undefined);\n    else if (data && typeof data === 'object' && !Array.isArray(data)) data = data.value;\n    if (data === null || data === undefined || String(data).trim() === '') continue;\n    const value = typeof data === 'boolean' ? Number(data) : Number(String(data).replace(',', '.'));\n    if (!Number.isFinite(value) || !m.asset || !m.tag) { node.warn('Mapping o valor no válido.'); continue; }\n    if (m.kind === 'alarm') {\n        const id = JSON.stringify([source, m.asset, m.alarmId || m.tag]);\n        const states = flow.get('korriAdapterStates') || {};\n        const active = value !== 0;\n        if (states[id] === active || (states[id] === undefined && !active)) continue;\n        states[id] = active; flow.set('korriAdapterStates', states);\n        alarms.push({payload: active ? { asset:m.asset, alarmId:m.alarmId || m.tag, message:m.message || m.tag, severity:m.severity || 'high', machineStopped:m.machineStopped === true } : {asset:m.asset, alarmId:m.alarmId || m.tag, state:'cleared'}});\n    } else {\n        const date = new Date(msg.sourceTimestamp || Date.now());\n        if (!Number.isFinite(date.getTime())) { node.warn('Fecha no válida.'); continue; }\n        readings.push({payload:{asset:m.asset, tag:m.tag, value:value * (m.scale ?? 1) + (m.offset ?? 0), unit:m.unit || '', time:date.toISOString()}});\n    }\n}\nreturn [readings, alarms];",
    "outputs": 2,
    "timeout": 0,
    "noerr": 0,
    "initialize": "",
    "finalize": "",
    "libs": [],
    "x": 200,
    "y": 810,
    "wires": [
      [
        "k0rr1fn0000001"
      ],
      [
        "k0rr1fn0000002"
      ]
    ]
  },
  {
    "id": "korriadapter2",
    "type": "function",
    "z": "k0rr1tab0000001",
    "name": "Adaptar Modbus",
    "func": "// Configure KORRI_MAPPING_JSON in the tab (mapping only, never credentials).\nconst source = \"modbus\";\nlet mappings;\ntry { mappings = JSON.parse(env.get('KORRI_MAPPING_JSON') || '{}')[source] || []; }\ncatch { node.error('KORRI_MAPPING_JSON no es JSON válido.'); return null; }\nconst readings = [], alarms = [];\nfor (const m of mappings) {\n    if (['opcua', 'mqtt'].includes(source) && m.key !== msg.topic) continue;\n    if (source === 'opcua' && msg.statusCode && msg.statusCode.value !== undefined && msg.statusCode.value !== 0) { node.warn('Lectura OPC UA de mala calidad.'); continue; }\n    let data = msg.payload;\n    if (source === 'mqtt') { try { data = JSON.parse(String(data)); } catch { data = String(data); } }\n    if (source === 'modbus') data = (Array.isArray(data) ? data : data?.data)?.[m.index || 0];\n    else if (source === 's7') data = data && typeof data === 'object' ? data[m.key] : (msg.topic === m.key ? data : undefined);\n    else if (data && typeof data === 'object' && !Array.isArray(data)) data = data.value;\n    if (data === null || data === undefined || String(data).trim() === '') continue;\n    const value = typeof data === 'boolean' ? Number(data) : Number(String(data).replace(',', '.'));\n    if (!Number.isFinite(value) || !m.asset || !m.tag) { node.warn('Mapping o valor no válido.'); continue; }\n    if (m.kind === 'alarm') {\n        const id = JSON.stringify([source, m.asset, m.alarmId || m.tag]);\n        const states = flow.get('korriAdapterStates') || {};\n        const active = value !== 0;\n        if (states[id] === active || (states[id] === undefined && !active)) continue;\n        states[id] = active; flow.set('korriAdapterStates', states);\n        alarms.push({payload: active ? { asset:m.asset, alarmId:m.alarmId || m.tag, message:m.message || m.tag, severity:m.severity || 'high', machineStopped:m.machineStopped === true } : {asset:m.asset, alarmId:m.alarmId || m.tag, state:'cleared'}});\n    } else {\n        const date = new Date(msg.sourceTimestamp || Date.now());\n        if (!Number.isFinite(date.getTime())) { node.warn('Fecha no válida.'); continue; }\n        readings.push({payload:{asset:m.asset, tag:m.tag, value:value * (m.scale ?? 1) + (m.offset ?? 0), unit:m.unit || '', time:date.toISOString()}});\n    }\n}\nreturn [readings, alarms];",
    "outputs": 2,
    "timeout": 0,
    "noerr": 0,
    "initialize": "",
    "finalize": "",
    "libs": [],
    "x": 200,
    "y": 880,
    "wires": [
      [
        "k0rr1fn0000001"
      ],
      [
        "k0rr1fn0000002"
      ]
    ]
  },
  {
    "id": "korriadapter3",
    "type": "function",
    "z": "k0rr1tab0000001",
    "name": "Adaptar Siemens S7",
    "func": "// Configure KORRI_MAPPING_JSON in the tab (mapping only, never credentials).\nconst source = \"s7\";\nlet mappings;\ntry { mappings = JSON.parse(env.get('KORRI_MAPPING_JSON') || '{}')[source] || []; }\ncatch { node.error('KORRI_MAPPING_JSON no es JSON válido.'); return null; }\nconst readings = [], alarms = [];\nfor (const m of mappings) {\n    if (['opcua', 'mqtt'].includes(source) && m.key !== msg.topic) continue;\n    if (source === 'opcua' && msg.statusCode && msg.statusCode.value !== undefined && msg.statusCode.value !== 0) { node.warn('Lectura OPC UA de mala calidad.'); continue; }\n    let data = msg.payload;\n    if (source === 'mqtt') { try { data = JSON.parse(String(data)); } catch { data = String(data); } }\n    if (source === 'modbus') data = (Array.isArray(data) ? data : data?.data)?.[m.index || 0];\n    else if (source === 's7') data = data && typeof data === 'object' ? data[m.key] : (msg.topic === m.key ? data : undefined);\n    else if (data && typeof data === 'object' && !Array.isArray(data)) data = data.value;\n    if (data === null || data === undefined || String(data).trim() === '') continue;\n    const value = typeof data === 'boolean' ? Number(data) : Number(String(data).replace(',', '.'));\n    if (!Number.isFinite(value) || !m.asset || !m.tag) { node.warn('Mapping o valor no válido.'); continue; }\n    if (m.kind === 'alarm') {\n        const id = JSON.stringify([source, m.asset, m.alarmId || m.tag]);\n        const states = flow.get('korriAdapterStates') || {};\n        const active = value !== 0;\n        if (states[id] === active || (states[id] === undefined && !active)) continue;\n        states[id] = active; flow.set('korriAdapterStates', states);\n        alarms.push({payload: active ? { asset:m.asset, alarmId:m.alarmId || m.tag, message:m.message || m.tag, severity:m.severity || 'high', machineStopped:m.machineStopped === true } : {asset:m.asset, alarmId:m.alarmId || m.tag, state:'cleared'}});\n    } else {\n        const date = new Date(msg.sourceTimestamp || Date.now());\n        if (!Number.isFinite(date.getTime())) { node.warn('Fecha no válida.'); continue; }\n        readings.push({payload:{asset:m.asset, tag:m.tag, value:value * (m.scale ?? 1) + (m.offset ?? 0), unit:m.unit || '', time:date.toISOString()}});\n    }\n}\nreturn [readings, alarms];",
    "outputs": 2,
    "timeout": 0,
    "noerr": 0,
    "initialize": "",
    "finalize": "",
    "libs": [],
    "x": 200,
    "y": 950,
    "wires": [
      [
        "k0rr1fn0000001"
      ],
      [
        "k0rr1fn0000002"
      ]
    ]
  },
  {
    "id": "korricatch",
    "type": "catch",
    "z": "k0rr1tab0000001",
    "name": "Error de transporte HTTP",
    "scope": [
      "k0rr1http00001",
      "k0rr1http00002"
    ],
    "uncaught": false,
    "x": 730,
    "y": 1050,
    "wires": [
      [
        "korrinetworkerror"
      ]
    ]
  },
  {
    "id": "korrinetworkerror",
    "type": "function",
    "z": "k0rr1tab0000001",
    "name": "Marcar fallo de red",
    "func": "msg.statusCode = 0; msg.payload = {error: \"Sin conexión con Korri\"}; return msg;",
    "outputs": 1,
    "x": 990,
    "y": 1050,
    "wires": [
      [
        "k0rr1fn0000003"
      ]
    ]
  }
]
