{ "updatedAt": "2026-07-09T21:45:54.813Z", "createdAt": "2026-04-23T00:41:43.725Z", "id": "yX2j8m04e3pxaoQq", "name": "Water Heater Advisor ECS 6 Nodes + Build + Execute", "description": null, "active": true, "isArchived": false, "nodes": [ { "parameters": { "jsCode": "function num(v, fallback = NaN) {\n const n = Number.parseFloat(v);\n return Number.isFinite(n) ? n : fallback;\n}\n\nfunction low(v) {\n return (v ?? '').toString().trim().toLowerCase();\n}\n\nfunction parseMaybeJson(v) {\n if (typeof v !== 'string') return v;\n try {\n return JSON.parse(v);\n } catch {\n return v;\n }\n}\n\nfunction extractSnapshot(input) {\n if (typeof input === 'string') return parseMaybeJson(input);\n if (input?.data && typeof input.data === 'string') return parseMaybeJson(input.data);\n if (input?.body && typeof input.body === 'string') return parseMaybeJson(input.body);\n if (input?.data && typeof input.data === 'object') return input.data;\n if (input?.body && typeof input.body === 'object') return input.body;\n return input ?? {};\n}\n\nfunction clamp(v, min, max) {\n return Math.min(Math.max(v, min), max);\n}\n\nfunction to2(n) {\n return String(n).padStart(2, '0');\n}\n\nfunction getParisNowParts() {\n const fmt = new Intl.DateTimeFormat('fr-FR', {\n timeZone: 'Europe/Paris',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false,\n });\n\n const parts = Object.fromEntries(\n fmt.formatToParts(new Date())\n .filter(p => p.type !== 'literal')\n .map(p => [p.type, p.value])\n );\n\n const hour = Number(parts.hour) === 24 ? 0 : Number(parts.hour);\n const date = `${parts.year}-${parts.month}-${parts.day}`;\n const stamp = `${date} ${to2(hour)}:${parts.minute}:${parts.second}`;\n\n return {\n year: Number(parts.year),\n month: Number(parts.month),\n day: Number(parts.day),\n hour,\n minute: Number(parts.minute),\n second: Number(parts.second),\n date,\n stamp,\n minNow: hour * 60 + Number(parts.minute),\n };\n}\n\nfunction getTzOffsetMs(utcTs, timeZone = 'Europe/Paris') {\n const dtf = new Intl.DateTimeFormat('en-US', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false,\n });\n\n const parts = Object.fromEntries(\n dtf.formatToParts(new Date(utcTs))\n .filter(p => p.type !== 'literal')\n .map(p => [p.type, p.value])\n );\n\n const asIfUtc = Date.UTC(\n Number(parts.year),\n Number(parts.month) - 1,\n Number(parts.day),\n Number(parts.hour) === 24 ? 0 : Number(parts.hour),\n Number(parts.minute),\n Number(parts.second)\n );\n\n const d = new Date(utcTs);\n const actualUtc = Date.UTC(\n d.getUTCFullYear(),\n d.getUTCMonth(),\n d.getUTCDate(),\n d.getUTCHours(),\n d.getUTCMinutes(),\n d.getUTCSeconds()\n );\n\n return asIfUtc - actualUtc;\n}\n\nfunction parseParisStampToMs(s) {\n const text = (s ?? '').toString().trim();\n const m = text.match(/^(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})$/);\n if (!m) return null;\n\n const y = Number(m[1]);\n const mo = Number(m[2]);\n const d = Number(m[3]);\n const h = Number(m[4]);\n const mi = Number(m[5]);\n const se = Number(m[6]);\n\n if (![y, mo, d, h, mi, se].every(Number.isFinite)) return null;\n\n const guessUtc = Date.UTC(y, mo - 1, d, h, mi, se);\n const off1 = getTzOffsetMs(guessUtc, 'Europe/Paris');\n let ts = guessUtc - off1;\n const off2 = getTzOffsetMs(ts, 'Europe/Paris');\n\n if (off2 !== off1) ts = guessUtc - off2;\n return ts;\n}\n\nfunction cleanStateText(v) {\n const s = (v ?? '').toString().trim();\n const x = s.toLowerCase();\n return ['unknown', 'unavailable', 'none', 'null'].includes(x) ? '' : s;\n}\n\nconst cfg = {\n mobileNotifyDomain: 'notify',\n mobileNotifyService: 'mobile_app_iphone_16_de_tt',\n batteryUsableCapacityKwh: 17.5,\n sampleWindowMinMin: 2,\n sampleWindowMinMax: 15,\n energyByDemandKwh: {\n low: { green: 0.9, auto: 1.4, boost: 2.0 },\n normal: { green: 1.4, auto: 2.2, boost: 3.1 },\n high: { green: 2.2, auto: 3.4, boost: 4.6 },\n three_showers: { green: 3.0, auto: 4.4, boost: 5.8 }\n }\n};\n\nconst raw = $input.first()?.json ?? {};\nconst input = extractSnapshot(raw);\nconst now = getParisNowParts();\nconst nowMs = Date.now();\n\nconst soc = clamp(num(input.soc_percent, 0), 0, 100);\nconst batteryCurrentA = num(input.battery_current_a, 0);\nconst pvPowerW = Math.max(0, num(input.pv_power_w, 0));\nconst pvPowerAvg10mW = Math.max(0, num(input.pv_power_10m_avg_w, pvPowerW));\nconst houseAcPowerW = Math.max(0, num(input.house_ac_power_w, 0));\nconst gridPowerW = num(input.grid_power_w, 0);\nconst gridIsOn = low(input.grid_state || 'off') === 'on';\nconst acInAvailable = num(input.victron_acin1_available, 0) === 1;\nconst gridAvailable = gridIsOn || acInAvailable;\nconst todayRemainingKwh = Math.max(0, num(input.today_remaining_kwh, 0));\nconst tomorrowKwh = Math.max(0, num(input.tomorrow_kwh, 0));\nconst advisorEnabled = low(input.advisor_enabled || 'off') === 'on';\nconst notificationsEnabled = low(input.notifications_enabled || 'off') === 'on';\n\nconst hotWaterDemandRaw = low(input.hot_water_demand || 'normal');\nconst hotWaterDemand = ['low', 'normal', 'high', 'three_showers'].includes(hotWaterDemandRaw)\n ? hotWaterDemandRaw\n : 'normal';\n\nconst greenPowerW = Math.max(0, num(input.green_power_w, 620));\nconst autoPowerW = Math.max(0, num(input.auto_power_w, 1200));\nconst boostPowerW = Math.max(0, num(input.boost_power_w, 2000));\nconst strongForecastKwh = Math.max(0, num(input.strong_forecast_kwh, 18));\nconst mediumForecastKwh = Math.max(0, num(input.medium_forecast_kwh, 10));\nconst strongPvNowW = Math.max(0, num(input.strong_pv_now_w, 2500));\nconst mediumPvNowW = Math.max(0, num(input.medium_pv_now_w, 1500));\nconst boostMinSocStrongForecastPct = clamp(num(input.morning_boost_min_soc_strong_day, 35), 0, 100);\nconst boostMinSocMediumForecastPct = clamp(num(input.boost_min_soc_medium_day, 50), 0, 100);\nconst endOfDaySocGuard = clamp(num(input.end_of_day_soc_guard, 85), 0, 100);\nconst endOfDaySocTarget = clamp(num(input.end_of_day_soc_target, 85), 0, 100);\nconst baseLoadRemainingKwh = Math.max(0, num(input.base_load_remaining_kwh, 0));\nconst flexibleSafetyMarginKwh = Math.max(0, num(input.flexible_safety_margin_kwh, 0));\nconst acLoadsMaxSafeW = Math.max(0, num(input.ac_loads_max_safe_w, 8000));\nconst lastSignature = cleanStateText(input.last_signature);\n// Jour faible (07/10/2026) : decision du bilan, session reseau HC engagee,\n// energie du chauffe-eau sur 24 h (service d'historisation), propriete de la coupure.\nconst ecsNuit = low(input.ecs_nuit) === 'on';\nconst hcSessionCommitted = low(input.hc_session_committed) === 'on';\nconst ecs24hKwh = num(input.ecs_24h_kwh, NaN);\nconst offJourFaiblePrev = low(input.off_jour_faible_prev) === 'on';\nconst forecastSource = cleanStateText(input.forecast_source) || 'forecast_solar';\n\nreturn [{\n json: {\n meta: {\n workflow: 'water_heater_advisor',\n architecture: 'ecs_6nodes_simple_early_boost',\n node: 'ecs_normalize_inputs',\n timestamp_paris: now.stamp\n },\n cfg,\n now,\n nowMs,\n input,\n normalized: {\n soc,\n batteryCurrentA,\n pvPowerW,\n pvPowerAvg10mW,\n houseAcPowerW,\n gridPowerW,\n gridIsOn,\n acInAvailable,\n gridAvailable,\n todayRemainingKwh,\n tomorrowKwh,\n advisorEnabled,\n notificationsEnabled,\n hotWaterDemand,\n greenPowerW,\n autoPowerW,\n boostPowerW,\n strongForecastKwh,\n mediumForecastKwh,\n strongPvNowW,\n mediumPvNowW,\n boostMinSocStrongForecastPct,\n boostMinSocMediumForecastPct,\n endOfDaySocGuard,\n endOfDaySocTarget,\n baseLoadRemainingKwh,\n flexibleSafetyMarginKwh,\n acLoadsMaxSafeW,\n lastSignature,\n ecsNuit,\n hcSessionCommitted,\n ecs24hKwh,\n offJourFaiblePrev,\n forecastSource\n }\n }\n}];" }, "id": "1226082d-222c-4837-99d3-35094bd1c4f1", "name": "ECS Normalize Inputs", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 160, -160 ] }, { "parameters": { "jsCode": "function num(v, fallback = NaN) {\n const n = Number.parseFloat(v);\n return Number.isFinite(n) ? n : fallback;\n}\n\nfunction low(v) {\n return (v ?? '').toString().trim().toLowerCase();\n}\n\nfunction cleanStateText(v) {\n const s = (v ?? '').toString().trim();\n const x = s.toLowerCase();\n return ['unknown', 'unavailable', 'none', 'null'].includes(x) ? '' : s;\n}\n\nfunction getTzOffsetMs(utcTs, timeZone = 'Europe/Paris') {\n const dtf = new Intl.DateTimeFormat('en-US', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false,\n });\n\n const parts = Object.fromEntries(\n dtf.formatToParts(new Date(utcTs))\n .filter(p => p.type !== 'literal')\n .map(p => [p.type, p.value])\n );\n\n const asIfUtc = Date.UTC(\n Number(parts.year),\n Number(parts.month) - 1,\n Number(parts.day),\n Number(parts.hour) === 24 ? 0 : Number(parts.hour),\n Number(parts.minute),\n Number(parts.second)\n );\n\n const d = new Date(utcTs);\n const actualUtc = Date.UTC(\n d.getUTCFullYear(),\n d.getUTCMonth(),\n d.getUTCDate(),\n d.getUTCHours(),\n d.getUTCMinutes(),\n d.getUTCSeconds()\n );\n\n return asIfUtc - actualUtc;\n}\n\nfunction parseParisStampToMs(s) {\n const text = (s ?? '').toString().trim();\n const m = text.match(/^(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})$/);\n if (!m) return null;\n\n const y = Number(m[1]);\n const mo = Number(m[2]);\n const d = Number(m[3]);\n const h = Number(m[4]);\n const mi = Number(m[5]);\n const se = Number(m[6]);\n\n if (![y, mo, d, h, mi, se].every(Number.isFinite)) return null;\n\n const guessUtc = Date.UTC(y, mo - 1, d, h, mi, se);\n const off1 = getTzOffsetMs(guessUtc, 'Europe/Paris');\n let ts = guessUtc - off1;\n const off2 = getTzOffsetMs(ts, 'Europe/Paris');\n\n if (off2 !== off1) ts = guessUtc - off2;\n return ts;\n}\n\nfunction cleanParisStamp(v) {\n const s = cleanStateText(v);\n return parseParisStampToMs(s) !== null ? s : '';\n}\n\nfunction minutesSince(ts, nowMs) {\n if (ts === null || nowMs === null) return null;\n return Math.max(0, (nowMs - ts) / 60000);\n}\n\nconst root = $input.first()?.json ?? {};\nconst cfg = root.cfg ?? {};\nconst now = root.now ?? {};\nconst nowMs = root.nowMs ?? null;\nconst input = root.input ?? {};\nconst normalized = root.normalized ?? {};\n\nconst { greenPowerW, autoPowerW, boostPowerW } = normalized;\n\nconst evcsPriorityActiveRaw = low(input.evcs_priority_active || 'off') === 'on';\nconst energyPriorityMode = cleanStateText(input.energy_priority_mode || 'normal').toLowerCase() || 'normal';\nconst energyPriorityReason = cleanStateText(input.energy_priority_reason);\nconst evcsPriorityUntilAt = cleanParisStamp(input.evcs_priority_until);\nconst evcsPriorityUntilMs = parseParisStampToMs(evcsPriorityUntilAt);\n\nconst evcsPriorityActive =\n evcsPriorityActiveRaw &&\n energyPriorityMode === 'evcs_priority' &&\n (\n evcsPriorityUntilMs === null ||\n (nowMs !== null && evcsPriorityUntilMs > nowMs + 1000)\n );\n\nconst waterHeaterSwitchOn = low(input.water_heater_switch || 'off') === 'on';\nconst waterHeaterEnergyTotalKwh = Math.max(0, num(input.water_heater_energy_total_kwh, 0));\nconst energyPrevKwh = num(input.energy_total_prev_kwh, NaN);\nconst energyPrevAt = cleanParisStamp(input.energy_prev_at);\nconst energyPrevMs = parseParisStampToMs(energyPrevAt);\nconst observedPowerPrevW = Math.max(0, num(input.observed_power_helper_w, 0));\nconst observedRegimePrev = cleanStateText(input.observed_regime_helper).toLowerCase();\nconst mismatchSinceAt = cleanParisStamp(input.mode_mismatch_since);\nconst mismatchSinceMsPrev = parseParisStampToMs(mismatchSinceAt);\nconst forcedOffByAdvisorPrev = low(input.forced_off_by_advisor || 'off') === 'on';\nconst forcedOffReasonPrev = cleanStateText(input.forced_off_reason);\nconst forcedOffAtPrev = cleanParisStamp(input.forced_off_at);\nconst forcedOffAtPrevMs = parseParisStampToMs(forcedOffAtPrev);\nconst pendingUserActionPrev = cleanStateText(input.pending_user_action_prev);\nconst restoreSurplusW = Math.max(0, num(input.restore_surplus_w, 2500));\nconst modeMismatchDelayMin = Math.max(1, num(input.mode_mismatch_delay_min, 15));\n\nconst sampleDurationMin = minutesSince(energyPrevMs, nowMs);\nconst energyDeltaKwh =\n Number.isFinite(energyPrevKwh)\n ? Math.max(0, waterHeaterEnergyTotalKwh - energyPrevKwh)\n : NaN;\n\nconst sampleIsUsable =\n Number.isFinite(sampleDurationMin) &&\n sampleDurationMin >= (cfg.sampleWindowMinMin ?? 2) &&\n sampleDurationMin <= (cfg.sampleWindowMinMax ?? 15) &&\n Number.isFinite(energyDeltaKwh);\n\nlet observedPowerW = 0;\nif (sampleIsUsable) {\n observedPowerW = Math.max(0, (energyDeltaKwh * 60000) / sampleDurationMin);\n} else if (waterHeaterSwitchOn && observedPowerPrevW > 0) {\n observedPowerW = observedPowerPrevW;\n}\n\nconst offThresholdW = Math.max(80, greenPowerW * 0.25);\nconst hpUpperW = (greenPowerW + autoPowerW) / 2;\nconst resistiveUpperW = (autoPowerW + boostPowerW) / 2;\n\nlet observedRegime = 'unknown';\nif (!waterHeaterSwitchOn) {\n observedRegime = 'off';\n} else if (!sampleIsUsable && observedRegimePrev) {\n observedRegime = observedRegimePrev;\n} else if (observedPowerW < offThresholdW) {\n observedRegime = 'off';\n} else if (observedPowerW < hpUpperW) {\n observedRegime = 'hp_low';\n} else if (observedPowerW < resistiveUpperW) {\n observedRegime = 'resistive_mid';\n} else {\n observedRegime = 'boost_high';\n}\n\nreturn [{\n json: {\n ...root,\n meta: {\n ...(root.meta ?? {}),\n node: 'ecs_evcs_and_water_heater_observation'\n },\n observation: {\n evcsPriorityActiveRaw,\n energyPriorityMode,\n energyPriorityReason,\n evcsPriorityUntilAt,\n evcsPriorityUntilMs,\n evcsPriorityActive,\n waterHeaterSwitchOn,\n waterHeaterEnergyTotalKwh,\n energyPrevKwh,\n energyPrevAt,\n energyPrevMs,\n observedPowerPrevW,\n observedRegimePrev,\n mismatchSinceAt,\n mismatchSinceMsPrev,\n forcedOffByAdvisorPrev,\n forcedOffReasonPrev,\n forcedOffAtPrev,\n forcedOffAtPrevMs,\n pendingUserActionPrev,\n restoreSurplusW,\n modeMismatchDelayMin,\n sampleDurationMin,\n energyDeltaKwh,\n sampleIsUsable,\n observedPowerW,\n observedRegime,\n offThresholdW,\n hpUpperW,\n resistiveUpperW\n }\n }\n}];" }, "id": "0979b36d-13b0-492a-bafb-8c99219bbdb5", "name": "ECS EVCS & Water Heater Observation", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 384, -160 ] }, { "parameters": { "jsCode": "function clamp(v, min, max) {\n return Math.min(Math.max(v, min), max);\n}\n\nconst root = $input.first()?.json ?? {};\nconst cfg = root.cfg ?? {};\nconst normalized = root.normalized ?? {};\n\nconst {\n soc,\n batteryCurrentA,\n pvPowerW,\n pvPowerAvg10mW,\n houseAcPowerW,\n todayRemainingKwh,\n tomorrowKwh,\n advisorEnabled,\n hotWaterDemand,\n greenPowerW,\n autoPowerW,\n boostPowerW,\n strongForecastKwh,\n mediumForecastKwh,\n strongPvNowW,\n mediumPvNowW,\n boostMinSocStrongForecastPct,\n boostMinSocMediumForecastPct,\n endOfDaySocGuard,\n endOfDaySocTarget,\n baseLoadRemainingKwh,\n flexibleSafetyMarginKwh,\n acLoadsMaxSafeW\n} = normalized;\n\nconst targetSoc = Math.max(endOfDaySocTarget, endOfDaySocGuard);\nconst batteryCapacityKwh = cfg.batteryUsableCapacityKwh ?? 17.5;\n\nconst energyTable =\n (cfg.energyByDemandKwh && cfg.energyByDemandKwh[hotWaterDemand]) ||\n (cfg.energyByDemandKwh && cfg.energyByDemandKwh.normal) || {\n green: 1.4,\n auto: 2.2,\n boost: 3.1\n };\n\nconst greenEnergyKwh = energyTable.green;\nconst autoEnergyKwh = energyTable.auto;\nconst boostEnergyKwh = energyTable.boost;\n\nconst energyNeededToReachTargetKwh =\n Math.max(0, ((targetSoc - soc) / 100) * batteryCapacityKwh);\n\nfunction projectedEndSocAfterMode(loadKwh) {\n const netKwh =\n todayRemainingKwh -\n baseLoadRemainingKwh -\n flexibleSafetyMarginKwh -\n loadKwh;\n\n const deltaSoc = (netKwh / batteryCapacityKwh) * 100;\n return clamp(soc + deltaSoc, 0, 100);\n}\n\nfunction budgetMarginKwh(loadKwh) {\n return (\n todayRemainingKwh -\n baseLoadRemainingKwh -\n flexibleSafetyMarginKwh -\n loadKwh -\n energyNeededToReachTargetKwh\n );\n}\n\nconst projectedGreenSoc = projectedEndSocAfterMode(greenEnergyKwh);\nconst projectedAutoSoc = projectedEndSocAfterMode(autoEnergyKwh);\nconst projectedBoostSoc = projectedEndSocAfterMode(boostEnergyKwh);\n\nconst greenBudgetMarginKwh = budgetMarginKwh(greenEnergyKwh);\nconst autoBudgetMarginKwh = budgetMarginKwh(autoEnergyKwh);\nconst boostBudgetMarginKwh = budgetMarginKwh(boostEnergyKwh);\n\n// 07/10/2026 : la force de la journee se juge sur le reste du JOUR. Avant, le\n// lendemain suffisait (« || tomorrowKwh ») : le 06/10, journee de 14,5 kWh, le\n// boost etait conseille parce que mercredi etait annonce fort.\nconst strongForecast =\n todayRemainingKwh >= strongForecastKwh;\n\nconst mediumForecast =\n !strongForecast &&\n todayRemainingKwh >= mediumForecastKwh;\n\nconst forecastStrength =\n strongForecast ? 'strong' :\n mediumForecast ? 'medium' :\n 'weak';\n\nconst pv10mW = Number.isFinite(pvPowerAvg10mW) ? pvPowerAvg10mW : pvPowerW;\nconst netPvHeadroomW = Math.round(pv10mW - houseAcPowerW);\nconst pvCoversHouseNow = pvPowerW > houseAcPowerW;\nconst strongPvNow = pv10mW >= strongPvNowW || pvPowerW >= strongPvNowW;\nconst mediumPvNow = pv10mW >= mediumPvNowW || pvPowerW >= mediumPvNowW;\n\nconst pvStartedWell =\n mediumPvNow &&\n pvCoversHouseNow &&\n netPvHeadroomW >= Math.max(300, Math.round(greenPowerW * 0.5));\n\nconst acSafe = acLoadsMaxSafeW <= 0 ? true : houseAcPowerW <= acLoadsMaxSafeW;\nconst batteryNotDrainingHard = batteryCurrentA >= -2;\n\nconst greenAllowed =\n advisorEnabled &&\n acSafe &&\n (\n projectedGreenSoc >= targetSoc - 6 ||\n greenBudgetMarginKwh >= -1.0 ||\n soc >= targetSoc\n );\n\nconst autoAllowed =\n advisorEnabled &&\n acSafe &&\n (\n autoBudgetMarginKwh >= 0 ||\n projectedAutoSoc >= targetSoc ||\n (strongForecast && projectedAutoSoc >= targetSoc - 2)\n );\n\nconst boostAllowedByBudget =\n advisorEnabled &&\n acSafe &&\n (\n projectedBoostSoc >= targetSoc ||\n boostBudgetMarginKwh >= 0 ||\n (strongForecast && projectedBoostSoc >= targetSoc - 5) ||\n (strongForecast && boostBudgetMarginKwh >= -1.0)\n );\n\nconst earlyBoostStrongReady =\n boostAllowedByBudget &&\n soc >= boostMinSocStrongForecastPct &&\n pvStartedWell &&\n (strongForecast || strongPvNow);\n\nconst earlyBoostMediumReady =\n boostAllowedByBudget &&\n mediumForecast &&\n soc >= boostMinSocMediumForecastPct &&\n pvStartedWell &&\n netPvHeadroomW >= greenPowerW;\n\nconst autoReady =\n autoAllowed &&\n mediumPvNow &&\n pvCoversHouseNow &&\n netPvHeadroomW >= 0;\n\nconst greenReady =\n greenAllowed &&\n (\n pv10mW >= greenPowerW ||\n (pvPowerW >= greenPowerW && pvCoversHouseNow)\n );\n\nconst boostAllowed = earlyBoostStrongReady || earlyBoostMediumReady;\n\nreturn [{\n json: {\n ...root,\n meta: {\n ...(root.meta ?? {}),\n node: 'ecs_energy_model_and_early_boost_signals'\n },\n energyModel: {\n targetSoc,\n batteryCapacityKwh,\n greenEnergyKwh,\n autoEnergyKwh,\n boostEnergyKwh,\n energyNeededToReachTargetKwh,\n projectedGreenSoc,\n projectedAutoSoc,\n projectedBoostSoc,\n greenBudgetMarginKwh,\n autoBudgetMarginKwh,\n boostBudgetMarginKwh,\n forecastStrength,\n strongForecast,\n mediumForecast,\n strongPvNow,\n mediumPvNow,\n netPvHeadroomW,\n pvCoversHouseNow,\n pvStartedWell,\n acSafe,\n batteryNotDrainingHard,\n greenAllowed,\n autoAllowed,\n boostAllowedByBudget,\n boostAllowed,\n earlyBoostStrongReady,\n earlyBoostMediumReady,\n autoReady,\n greenReady\n }\n }\n}];" }, "id": "0becfc3a-3305-4a97-95b8-0fe1de446e37", "name": "ECS Energy Model & Early Boost Signals", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 608, -160 ] }, { "parameters": { "jsCode": "const root = $input.first()?.json ?? {};\nconst normalized = root.normalized ?? {};\nconst energyModel = root.energyModel ?? {};\n\nconst {\n advisorEnabled,\n hotWaterDemand,\n soc,\n pvPowerW,\n pvPowerAvg10mW,\n houseAcPowerW,\n acLoadsMaxSafeW\n} = normalized;\n\nconst {\n targetSoc,\n forecastStrength,\n netPvHeadroomW,\n pvCoversHouseNow,\n acSafe,\n greenAllowed,\n earlyBoostStrongReady,\n earlyBoostMediumReady,\n autoReady,\n greenReady,\n projectedGreenSoc,\n projectedAutoSoc,\n projectedBoostSoc,\n greenBudgetMarginKwh,\n autoBudgetMarginKwh,\n boostBudgetMarginKwh\n} = energyModel;\n\nlet recommendedMode = 'off';\nlet adviceColor = 'red';\nlet state = 'off_waiting_pv';\nlet reason = [];\n\nif (!advisorEnabled) {\n recommendedMode = 'off';\n adviceColor = 'red';\n state = 'advisor_disabled';\n reason.push('Advisor chauffe-eau désactivé');\n}\nelse if (!acSafe) {\n recommendedMode = 'off';\n adviceColor = 'red';\n state = 'off_ac_loads_too_high';\n reason.push(`Charges maison trop élevées pour ECS (${Math.round(houseAcPowerW)} W > seuil ${Math.round(acLoadsMaxSafeW)} W)`);\n}\nelse if (earlyBoostStrongReady) {\n recommendedMode = 'boost';\n adviceColor = 'green';\n state = 'boost_early_strong_forecast';\n reason.push('Boost tôt autorisé : forecast fort + SOC suffisant + PV net maison favorable');\n}\nelse if (earlyBoostMediumReady) {\n recommendedMode = 'boost';\n adviceColor = 'orange';\n state = 'boost_early_medium_forecast';\n reason.push('Boost tôt autorisé : forecast moyen + SOC élevé + surplus net maison suffisant');\n}\nelse if (autoReady) {\n recommendedMode = 'auto';\n adviceColor = 'green';\n state = 'auto_from_pv_net';\n reason.push('Mode auto recommandé : le PV couvre déjà la maison');\n}\nelse if (greenReady) {\n recommendedMode = 'green';\n adviceColor = 'green';\n state = 'green_waiting_pv_ramp';\n reason.push('Mode green recommandé : démarrage PV détecté');\n}\nelse {\n recommendedMode = 'off';\n adviceColor = 'red';\n if (!pvCoversHouseNow) {\n state = 'wait_for_pv_to_cover_house';\n reason.push('Attente : le PV ne couvre pas encore la maison');\n } else if (!greenAllowed) {\n state = 'off_budget_guard';\n reason.push('Attente : garde-fou budget / SOC fin de journée');\n } else {\n state = 'wait_for_pv_or_soc';\n reason.push('Attente d\\'un meilleur niveau PV / forecast / SOC');\n }\n}\n\nreason.push(`Demande ECS: ${hotWaterDemand}`);\nreason.push(`Forecast: ${forecastStrength}`);\nreason.push(`SOC: ${Math.round(soc)}%`);\nreason.push(`PV: ${Math.round(pvPowerW)} W | PV10: ${Math.round(pvPowerAvg10mW)} W`);\nreason.push(`Maison: ${Math.round(houseAcPowerW)} W`);\nreason.push(`Surplus net estimé: ${Math.round(netPvHeadroomW)} W`);\n\nif (recommendedMode === 'boost') {\n reason.push(`Boost budget: marge ${boostBudgetMarginKwh.toFixed(2)} kWh | SOC fin ${projectedBoostSoc.toFixed(1)}%`);\n} else if (recommendedMode === 'auto') {\n reason.push(`Auto budget: marge ${autoBudgetMarginKwh.toFixed(2)} kWh | SOC fin ${projectedAutoSoc.toFixed(1)}%`);\n} else if (recommendedMode === 'green') {\n reason.push(`Green budget: marge ${greenBudgetMarginKwh.toFixed(2)} kWh | SOC fin ${projectedGreenSoc.toFixed(1)}%`);\n} else {\n reason.push(`Target fin de jour: ${targetSoc.toFixed(1)}%`);\n}\n\nconst baseRecommendedMode = recommendedMode;\nconst baseAdviceColor = adviceColor;\nconst baseState = state;\n\nreturn [{\n json: {\n ...root,\n meta: {\n ...(root.meta ?? {}),\n node: 'ecs_base_advisor_decision'\n },\n baseDecision: {\n recommendedMode,\n adviceColor,\n state,\n reason,\n baseRecommendedMode,\n baseAdviceColor,\n baseState\n }\n }\n}];" }, "id": "7a862398-6aeb-4720-91ed-fd2eb2cc9d7e", "name": "ECS Base Advisor Decision", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 832, -160 ] }, { "parameters": { "jsCode": "function regimeRank(regime) {\n switch (regime) {\n case 'off': return 0;\n case 'hp_low': return 1;\n case 'resistive_mid': return 2;\n case 'boost_high': return 3;\n default: return -1;\n }\n}\n\nfunction allowedRankForMode(mode) {\n switch (mode) {\n case 'off': return 0;\n case 'green': return 1;\n case 'auto': return 2;\n case 'boost': return 3;\n default: return 0;\n }\n}\n\nfunction round1(v) {\n return Math.round(v * 10) / 10;\n}\n\nconst root = $input.first()?.json ?? {};\nconst now = root.now ?? {};\nconst nowMs = root.nowMs ?? null;\nconst normalized = root.normalized ?? {};\nconst observation = root.observation ?? {};\nconst energyModel = root.energyModel ?? {};\nconst baseDecision = root.baseDecision ?? {};\n\nlet {\n recommendedMode,\n adviceColor,\n state,\n reason,\n baseRecommendedMode,\n baseAdviceColor,\n baseState\n} = baseDecision;\n\nreason = Array.isArray(reason) ? [...reason] : [];\n\nconst {\n advisorEnabled,\n soc,\n batteryCurrentA,\n pvPowerAvg10mW,\n houseAcPowerW,\n todayRemainingKwh,\n tomorrowKwh,\n baseLoadRemainingKwh,\n flexibleSafetyMarginKwh,\n acLoadsMaxSafeW,\n hotWaterDemand,\n gridIsOn,\n acInAvailable,\n gridAvailable\n} = normalized;\n\nconst {\n evcsPriorityActive,\n energyPriorityReason,\n waterHeaterSwitchOn,\n observedPowerW,\n observedRegime,\n mismatchSinceAt,\n mismatchSinceMsPrev,\n forcedOffByAdvisorPrev,\n forcedOffReasonPrev,\n forcedOffAtPrev,\n restoreSurplusW,\n modeMismatchDelayMin,\n sampleDurationMin,\n energyDeltaKwh,\n sampleIsUsable\n} = observation;\n\nconst {\n targetSoc,\n energyNeededToReachTargetKwh,\n greenEnergyKwh,\n autoEnergyKwh,\n boostEnergyKwh,\n projectedGreenSoc,\n projectedAutoSoc,\n projectedBoostSoc,\n greenBudgetMarginKwh,\n autoBudgetMarginKwh,\n boostBudgetMarginKwh,\n forecastStrength,\n netPvHeadroomW,\n pvCoversHouseNow,\n pvStartedWell,\n greenAllowed,\n autoAllowed,\n boostAllowed,\n batteryNotDrainingHard\n} = energyModel;\n\nif (advisorEnabled && evcsPriorityActive) {\n if (recommendedMode === 'boost' || recommendedMode === 'auto') {\n if (greenAllowed && batteryNotDrainingHard) {\n recommendedMode = 'green';\n adviceColor = 'orange';\n state = 'evcs_priority_green_cap';\n reason.push(`Priorité EVCS active : chauffe-eau plafonné à GREEN (${energyPriorityReason || 'raison non précisée'})`);\n } else {\n recommendedMode = 'off';\n adviceColor = 'red';\n state = 'evcs_priority_off_cap';\n reason.push(`Priorité EVCS active : chauffe-eau déconseillé (${energyPriorityReason || 'raison non précisée'})`);\n }\n } else if (recommendedMode === 'green' && (!greenAllowed || !batteryNotDrainingHard)) {\n recommendedMode = 'off';\n adviceColor = 'red';\n state = 'evcs_priority_green_blocked';\n reason.push(`Priorité EVCS active : GREEN devient lui-même trop coûteux (${energyPriorityReason || 'raison non précisée'})`);\n }\n}\n\nconst selectedLoadKwh =\n recommendedMode === 'green' ? greenEnergyKwh :\n recommendedMode === 'auto' ? autoEnergyKwh :\n recommendedMode === 'boost' ? boostEnergyKwh :\n 0;\n\nconst selectedProjectedSoc =\n recommendedMode === 'green' ? projectedGreenSoc :\n recommendedMode === 'auto' ? projectedAutoSoc :\n recommendedMode === 'boost' ? projectedBoostSoc :\n soc;\n\nconst selectedBudgetMarginKwh =\n recommendedMode === 'green' ? greenBudgetMarginKwh :\n recommendedMode === 'auto' ? autoBudgetMarginKwh :\n recommendedMode === 'boost' ? boostBudgetMarginKwh :\n todayRemainingKwh - baseLoadRemainingKwh - flexibleSafetyMarginKwh - energyNeededToReachTargetKwh;\n\nconst legacyAdviceOk = recommendedMode !== 'off';\n\nconst observedRank = regimeRank(observedRegime);\nconst allowedRank = allowedRankForMode(recommendedMode);\n\nconst mismatchActive =\n waterHeaterSwitchOn &&\n observedRank >= 0 &&\n allowedRank >= 0 &&\n observedRank > allowedRank;\n\nlet mismatchSeverity = 'none';\nif (mismatchActive) {\n if (recommendedMode === 'off') {\n mismatchSeverity = 'critical';\n } else if (observedRank - allowedRank >= 2) {\n mismatchSeverity = 'high';\n } else {\n mismatchSeverity = 'medium';\n }\n}\n\nconst mismatchSinceMsEffective = mismatchActive ? (mismatchSinceMsPrev ?? nowMs) : null;\nconst mismatchSinceAtEffective = mismatchActive ? (mismatchSinceMsPrev ? mismatchSinceAt : now.stamp) : '';\nconst mismatchDurationMin = mismatchActive && mismatchSinceMsEffective !== null ? Math.max(0, (nowMs - mismatchSinceMsEffective) / 60000) : 0;\n\nlet pendingUserAction = '';\nif (mismatchActive) {\n if (recommendedMode === 'off') {\n pendingUserAction = evcsPriorityActive\n ? 'Priorité EVCS : coupe temporairement le chauffe-eau ou laisse-le hors tension'\n : 'Le chauffe-eau consomme alors qu\\'il est déconseillé : coupe-le ou attends une meilleure fenêtre';\n } else if (recommendedMode === 'green') {\n pendingUserAction = observedRegime === 'boost_high'\n ? 'Passe le chauffe-eau en GREEN si possible, il semble en régime BOOST/résistance forte'\n : 'Passe le chauffe-eau en GREEN si possible, il semble plus gourmand que prévu';\n } else if (recommendedMode === 'auto') {\n pendingUserAction = 'Le chauffe-eau semble trop gourmand pour AUTO : repasse-le en AUTO modéré ou GREEN si possible';\n }\n}\n\nconst firstMismatchRun = mismatchActive && (mismatchSinceMsPrev === null || mismatchDurationMin < 1);\n\nconst realConflictNow =\n evcsPriorityActive &&\n (\n batteryCurrentA < -1 ||\n pvPowerAvg10mW < restoreSurplusW ||\n houseAcPowerW > acLoadsMaxSafeW ||\n recommendedMode === 'off' ||\n observedRegime === 'boost_high' ||\n (recommendedMode === 'green' && observedRegime === 'resistive_mid')\n );\n\nconst forceOffNow =\n advisorEnabled &&\n waterHeaterSwitchOn &&\n !forcedOffByAdvisorPrev &&\n mismatchActive &&\n mismatchDurationMin >= modeMismatchDelayMin &&\n realConflictNow;\n\nconst restoreEnergyOk =\n pvPowerAvg10mW >= restoreSurplusW &&\n batteryCurrentA >= -1 &&\n houseAcPowerW <= acLoadsMaxSafeW;\n\nconst restoreNow =\n advisorEnabled &&\n forcedOffByAdvisorPrev &&\n !waterHeaterSwitchOn &&\n (\n (!evcsPriorityActive && recommendedMode !== 'off') ||\n restoreEnergyOk\n );\n\nlet forcedOffByAdvisor = forcedOffByAdvisorPrev;\nlet forcedOffReason = forcedOffReasonPrev;\nlet forcedOffAt = forcedOffAtPrev;\nlet protectionState = 'none';\nlet powerSwitchAction = 'none';\nlet powerSwitchDesiredOn = waterHeaterSwitchOn;\n\nif (forceOffNow) {\n powerSwitchAction = 'turn_off';\n powerSwitchDesiredOn = false;\n forcedOffByAdvisor = true;\n forcedOffReason = `Coupure temporaire ECS: priorité EVCS + régime ${observedRegime} trop gourmand`;\n forcedOffAt = now.stamp;\n protectionState = 'forced_off_now_evcs_priority';\n state = 'forced_off_now_evcs_priority';\n adviceColor = 'red';\n reason.push(forcedOffReason);\n}\nelse if (restoreNow) {\n powerSwitchAction = 'turn_on';\n powerSwitchDesiredOn = true;\n forcedOffByAdvisor = false;\n forcedOffReason = '';\n protectionState = 'restored_after_evcs_priority';\n state = 'restored_after_evcs_priority';\n reason.push('Remise sous tension ECS : conflit EVCS terminé ou surplus redevenu suffisant');\n}\nelse if (forcedOffByAdvisorPrev && !waterHeaterSwitchOn) {\n protectionState = 'forced_off_wait_restore';\n state = 'forced_off_wait_restore';\n reason.push(`ECS temporairement coupé par l'advisor (${forcedOffReasonPrev || 'raison non précisée'})`);\n}\nelse if (mismatchActive && evcsPriorityActive) {\n protectionState = 'watch_mismatch_evcs_priority';\n state = 'watch_mismatch_evcs_priority';\n reason.push(`Écart de régime ECS sous priorité EVCS depuis ${round1(mismatchDurationMin)} min`);\n}\n\nif (!forceOffNow && !restoreNow && forcedOffByAdvisorPrev && waterHeaterSwitchOn) {\n forcedOffByAdvisor = false;\n forcedOffReason = '';\n}\n\n// =====================================================\n// JOUR FAIBLE : EAU CHAUDE EN HC DE NUIT (07/10/2026, option b du proprietaire)\n// =====================================================\n// Le bilan decide une fois par jour (input_boolean.evcs_balance_ecs_nuit) : si\n// le solaire prevu ne remplit pas la batterie pour la nuit, EDF sera ferme de\n// toute facon -> le chauffe-eau est COUPE le jour et chauffe pendant une\n// session reseau HC engagee (contacteur ferme), au tarif creux, jamais sur la\n// batterie. Securite eau chaude : moins de ECS_EAU_FROIDE_KWH en 24 h -> il\n// chauffe quand meme. Energie 24 h illisible -> aucune restriction (le\n// comportement d'avant revient, jamais un ballon froid par panne de capteur).\n// Jour normal : le chauffe-eau coupe par cette regle est remis sous tension.\nconst ECS_EAU_FROIDE_KWH = 1.5;\nconst {\n ecsNuit = false, hcSessionCommitted = false, ecs24hKwh = NaN, offJourFaiblePrev = false,\n} = normalized;\nlet offJourFaible = false;\nlet jourFaibleState = 'none';\nif (advisorEnabled && ecsNuit) {\n const energieConnue = Number.isFinite(ecs24hKwh);\n const eauFroide = energieConnue && ecs24hKwh < ECS_EAU_FROIDE_KWH;\n const heuresCreusesEdf = hcSessionCommitted && gridIsOn;\n const veutChauffer = !energieConnue || heuresCreusesEdf || eauFroide;\n offJourFaible = true;\n jourFaibleState = !energieConnue ? 'jour_faible_energie_illisible'\n : heuresCreusesEdf ? 'jour_faible_chauffe_hc_edf'\n : eauFroide ? 'jour_faible_eau_froide'\n : 'jour_faible_coupe';\n if (veutChauffer !== waterHeaterSwitchOn) {\n powerSwitchAction = veutChauffer ? 'turn_on' : 'turn_off';\n powerSwitchDesiredOn = veutChauffer;\n } else {\n powerSwitchAction = 'none';\n powerSwitchDesiredOn = waterHeaterSwitchOn;\n }\n forcedOffByAdvisor = false;\n forcedOffReason = '';\n protectionState = jourFaibleState;\n state = jourFaibleState;\n reason.push(\n jourFaibleState === 'jour_faible_chauffe_hc_edf' ? 'Jour faible : eau chaude en heures creuses sur EDF (session reseau engagee)'\n : jourFaibleState === 'jour_faible_eau_froide' ? `Jour faible mais seulement ${round1(ecs24hKwh)} kWh en 24 h : chauffe pour garantir l eau chaude`\n : jourFaibleState === 'jour_faible_energie_illisible' ? 'Jour faible, energie 24 h illisible : aucune restriction'\n : 'Jour faible : chauffe-eau coupe, il chauffera en heures creuses sur EDF'\n );\n} else if (advisorEnabled && offJourFaiblePrev && !waterHeaterSwitchOn) {\n powerSwitchAction = 'turn_on';\n powerSwitchDesiredOn = true;\n jourFaibleState = 'jour_normal_remise_sous_tension';\n protectionState = jourFaibleState;\n state = jourFaibleState;\n reason.push('Jour normal : chauffe-eau remis sous tension (il chauffe au solaire)');\n}\n\nreturn [{\n json: {\n ...root,\n meta: {\n ...(root.meta ?? {}),\n node: 'ecs_final_arbitration_and_protection'\n },\n finalDecision: {\n recommendedMode,\n adviceColor,\n state,\n reason,\n baseRecommendedMode,\n baseAdviceColor,\n baseState,\n selectedLoadKwh,\n selectedProjectedSoc,\n selectedBudgetMarginKwh,\n legacyAdviceOk,\n mismatchActive,\n mismatchSeverity,\n mismatchSinceAtEffective,\n mismatchSinceMsEffective,\n mismatchDurationMin,\n pendingUserAction,\n firstMismatchRun,\n realConflictNow,\n forceOffNow,\n restoreEnergyOk,\n restoreNow,\n forcedOffByAdvisor,\n forcedOffReason,\n forcedOffAt,\n protectionState,\n powerSwitchAction,\n powerSwitchDesiredOn,\n offJourFaible,\n jourFaibleState\n }\n }\n}];" }, "id": "994b3242-616d-46e7-83ed-d236a117d15c", "name": "ECS Final Arbitration & Protection", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1056, -160 ] }, { "parameters": { "jsCode": "function round1(v) {\n return Math.round(v * 10) / 10;\n}\n\nfunction round2(v) {\n return Math.round(v * 100) / 100;\n}\n\nfunction safeText(v, max = 255) {\n return (v ?? '').toString().slice(0, max);\n}\n\nfunction boolService(flag) {\n return flag ? 'turn_on' : 'turn_off';\n}\n\nfunction getTzOffsetMs(utcTs, timeZone = 'Europe/Paris') {\n const dtf = new Intl.DateTimeFormat('en-US', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false,\n });\n\n const parts = Object.fromEntries(\n dtf.formatToParts(new Date(utcTs))\n .filter(p => p.type !== 'literal')\n .map(p => [p.type, p.value])\n );\n\n const asIfUtc = Date.UTC(\n Number(parts.year),\n Number(parts.month) - 1,\n Number(parts.day),\n Number(parts.hour) === 24 ? 0 : Number(parts.hour),\n Number(parts.minute),\n Number(parts.second)\n );\n\n const d = new Date(utcTs);\n const actualUtc = Date.UTC(\n d.getUTCFullYear(),\n d.getUTCMonth(),\n d.getUTCDate(),\n d.getUTCHours(),\n d.getUTCMinutes(),\n d.getUTCSeconds()\n );\n\n return asIfUtc - actualUtc;\n}\n\nfunction parseParisStampToMs(s) {\n const text = (s ?? '').toString().trim();\n const m = text.match(/^(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})$/);\n if (!m) return null;\n\n const y = Number(m[1]);\n const mo = Number(m[2]);\n const d = Number(m[3]);\n const h = Number(m[4]);\n const mi = Number(m[5]);\n const se = Number(m[6]);\n\n if (![y, mo, d, h, mi, se].every(Number.isFinite)) return null;\n\n const guessUtc = Date.UTC(y, mo - 1, d, h, mi, se);\n const off1 = getTzOffsetMs(guessUtc, 'Europe/Paris');\n let ts = guessUtc - off1;\n const off2 = getTzOffsetMs(ts, 'Europe/Paris');\n\n if (off2 !== off1) ts = guessUtc - off2;\n return ts;\n}\n\nconst root = $input.first()?.json ?? {};\nconst cfg = root.cfg ?? {};\nconst now = root.now ?? {};\nconst input = root.input ?? {};\nconst normalized = root.normalized ?? {};\nconst observation = root.observation ?? {};\nconst energyModel = root.energyModel ?? {};\nconst finalDecision = root.finalDecision ?? {};\n\nconst {\n soc,\n batteryCurrentA,\n pvPowerW,\n pvPowerAvg10mW,\n houseAcPowerW,\n gridPowerW,\n gridIsOn,\n acInAvailable,\n gridAvailable,\n todayRemainingKwh,\n tomorrowKwh,\n advisorEnabled,\n notificationsEnabled,\n hotWaterDemand,\n greenPowerW,\n autoPowerW,\n boostPowerW,\n strongForecastKwh,\n mediumForecastKwh,\n strongPvNowW,\n mediumPvNowW,\n boostMinSocStrongForecastPct,\n boostMinSocMediumForecastPct,\n endOfDaySocGuard,\n endOfDaySocTarget,\n baseLoadRemainingKwh,\n flexibleSafetyMarginKwh,\n acLoadsMaxSafeW,\n lastSignature\n} = normalized;\n\nconst {\n evcsPriorityActive,\n energyPriorityMode,\n energyPriorityReason,\n evcsPriorityUntilAt,\n waterHeaterSwitchOn,\n waterHeaterEnergyTotalKwh,\n restoreSurplusW,\n modeMismatchDelayMin,\n sampleDurationMin,\n energyDeltaKwh,\n sampleIsUsable,\n observedPowerW,\n observedRegime\n} = observation;\n\nconst {\n targetSoc,\n batteryCapacityKwh,\n greenEnergyKwh,\n autoEnergyKwh,\n boostEnergyKwh,\n energyNeededToReachTargetKwh,\n projectedGreenSoc,\n projectedAutoSoc,\n projectedBoostSoc,\n greenBudgetMarginKwh,\n autoBudgetMarginKwh,\n boostBudgetMarginKwh,\n forecastStrength,\n strongForecast,\n mediumForecast,\n strongPvNow,\n mediumPvNow,\n netPvHeadroomW,\n pvCoversHouseNow,\n pvStartedWell,\n acSafe,\n batteryNotDrainingHard,\n greenAllowed,\n autoAllowed,\n boostAllowedByBudget,\n boostAllowed,\n earlyBoostStrongReady,\n earlyBoostMediumReady,\n autoReady,\n greenReady\n} = energyModel;\n\nlet {\n recommendedMode,\n adviceColor,\n state,\n reason,\n baseRecommendedMode,\n baseAdviceColor,\n baseState,\n selectedLoadKwh,\n selectedProjectedSoc,\n selectedBudgetMarginKwh,\n legacyAdviceOk,\n mismatchActive,\n mismatchSeverity,\n mismatchSinceAtEffective,\n mismatchSinceMsEffective,\n mismatchDurationMin,\n pendingUserAction,\n firstMismatchRun,\n realConflictNow,\n forceOffNow,\n restoreEnergyOk,\n restoreNow,\n forcedOffByAdvisor,\n forcedOffReason,\n forcedOffAt,\n protectionState,\n powerSwitchAction,\n powerSwitchDesiredOn,\n offJourFaible = false\n} = finalDecision;\n\nreason = Array.isArray(reason) ? [...reason] : [];\n\nconst forcedOffAtSafe = forcedOffAt && parseParisStampToMs(forcedOffAt) !== null ? forcedOffAt : '';\nconst forcedOffReasonSafe = forcedOffByAdvisor ? safeText(forcedOffReason, 255) : '';\nconst pendingUserActionSafe = safeText(pendingUserAction, 255);\n\nif (reason.length === 0) {\n if (recommendedMode === 'boost') reason.push('Boost recommandé');\n else if (recommendedMode === 'auto') reason.push('Mode auto recommandé');\n else if (recommendedMode === 'green') reason.push('Mode green recommandé');\n else reason.push('Chauffe-eau déconseillé pour le moment');\n}\n\nreason.push(`Demande ECS: ${hotWaterDemand}`);\nreason.push(`Conseil final: ${recommendedMode}`);\nreason.push(`Conseil initial: ${baseRecommendedMode}`);\nreason.push(`Couleur conseil: ${adviceColor}`);\nreason.push(`Forecast du jour: ${round1(todayRemainingKwh)} kWh`);\nreason.push(`Production demain: ${round1(tomorrowKwh)} kWh`);\nreason.push(`Classe forecast: ${forecastStrength}`);\nreason.push(`PV actuel: ${Math.round(pvPowerW)} W | PV10: ${Math.round(pvPowerAvg10mW)} W`);\nreason.push(`Charges AC maison: ${Math.round(houseAcPowerW)} W`);\nreason.push(`Surplus net estimé: ${Math.round(netPvHeadroomW)} W`);\nreason.push(`PV couvre maison: ${pvCoversHouseNow ? 'oui' : 'non'} | PV bien démarré: ${pvStartedWell ? 'oui' : 'non'}`);\nreason.push(`Batterie: SOC ${round1(soc)}% | courant ${round1(batteryCurrentA)} A`);\nreason.push(`Réseau: cmd=${gridIsOn ? 'ON' : 'OFF'} | acin=${acInAvailable ? 'OK' : 'KO'} | dispo=${gridAvailable ? 'oui' : 'non'}`);\nreason.push(`Target fin de jour: ${round1(targetSoc)}%`);\nreason.push(`Base load restante: ${round1(baseLoadRemainingKwh)} kWh`);\nreason.push(`Marge sécurité: ${round1(flexibleSafetyMarginKwh)} kWh`);\nreason.push(`Green ${round1(greenEnergyKwh)}kWh → SOC fin ${round1(projectedGreenSoc)}% | marge ${round1(greenBudgetMarginKwh)}kWh`);\nreason.push(`Auto ${round1(autoEnergyKwh)}kWh → SOC fin ${round1(projectedAutoSoc)}% | marge ${round1(autoBudgetMarginKwh)}kWh`);\nreason.push(`Boost ${round1(boostEnergyKwh)}kWh → SOC fin ${round1(projectedBoostSoc)}% | marge ${round1(boostBudgetMarginKwh)}kWh`);\nreason.push(`Régime observé: ${observedRegime} | puissance ≈ ${Math.round(observedPowerW)} W | delta ${sampleIsUsable ? round2(energyDeltaKwh) : 'n/a'} kWh/${sampleIsUsable ? round1(sampleDurationMin) : 'n/a'} min`);\nreason.push(`Prio EVCS: ${evcsPriorityActive ? 'ON' : 'OFF'}${energyPriorityReason ? ` | ${energyPriorityReason}` : ''}`);\nreason.push(`Mismatch: ${mismatchActive ? 'oui' : 'non'} | sévérité=${mismatchSeverity} | durée=${round1(mismatchDurationMin)} min`);\nreason.push(`Protection ECS: ${protectionState}`);\nif (pendingUserActionSafe) reason.push(`Action attendue: ${pendingUserActionSafe}`);\n\nconst shortReason = reason.join(' | ').slice(0, 255);\n\nconst signature = [\n now.date,\n `d=${hotWaterDemand}`,\n `m=${recommendedMode}`,\n `base=${baseRecommendedMode}`,\n `c=${adviceColor}`,\n `fs=${strongForecast ? '1' : '0'}`,\n `fm=${mediumForecast ? '1' : '0'}`,\n `pb=${pvStartedWell ? '1' : '0'}`,\n `soc=${round1(soc)}`,\n `pv=${Math.round(pvPowerW)}`,\n `pv10=${Math.round(pvPowerAvg10mW)}`,\n `npv=${Math.round(netPvHeadroomW)}`,\n `obs=${observedRegime}`,\n `prio=${evcsPriorityActive ? '1' : '0'}`,\n `cut=${forcedOffByAdvisor ? '1' : '0'}`\n].join('|');\n\nconst signatureChanged = signature !== lastSignature;\n\nlet notifyWanted = false;\nlet notifyTitle = 'Water Heater Advisor';\nlet notifyMessage = '';\n\nif (notificationsEnabled) {\n if (forceOffNow) {\n notifyWanted = true;\n notifyTitle = 'ECS coupé temporairement';\n notifyMessage = forcedOffReasonSafe || 'Le chauffe-eau a été coupé temporairement';\n } else if (restoreNow) {\n notifyWanted = true;\n notifyTitle = 'ECS remis sous tension';\n notifyMessage = 'Le chauffe-eau est réalimenté car la priorité EVCS est terminée ou le surplus est redevenu suffisant.';\n } else if (firstMismatchRun && pendingUserActionSafe) {\n notifyWanted = true;\n notifyTitle = 'Action utilisateur ECS conseillée';\n notifyMessage = pendingUserActionSafe;\n } else if (signatureChanged) {\n notifyWanted = true;\n notifyTitle = `Water Heater Advisor: ${recommendedMode.toUpperCase()} / ${adviceColor.toUpperCase()}`;\n notifyMessage = `Demande=${hotWaterDemand} | régime=${observedRegime} | SOC fin estimé=${round1(selectedProjectedSoc)}% | marge=${round1(selectedBudgetMarginKwh)} kWh`;\n }\n}\nconst BUDGET_MARGIN_MIN = -50;\nconst BUDGET_MARGIN_MAX = 50;\nconst result = {\n timestamp_paris: now.stamp,\n inputs: {\n soc_percent: soc,\n battery_current_a: batteryCurrentA,\n pv_power_w: pvPowerW,\n pv_power_10m_avg_w: pvPowerAvg10mW,\n house_ac_power_w: houseAcPowerW,\n grid_power_w: gridPowerW,\n grid_state: gridIsOn ? 'on' : 'off',\n victron_acin1_available: acInAvailable ? 1 : 0,\n today_remaining_kwh: round2(todayRemainingKwh),\n tomorrow_kwh: round2(tomorrowKwh),\n advisor_enabled: advisorEnabled,\n notifications_enabled: notificationsEnabled,\n hot_water_demand: hotWaterDemand,\n green_power_w: greenPowerW,\n auto_power_w: autoPowerW,\n boost_power_w: boostPowerW,\n strong_forecast_kwh: strongForecastKwh,\n medium_forecast_kwh: mediumForecastKwh,\n strong_pv_now_w: strongPvNowW,\n medium_pv_now_w: mediumPvNowW,\n boost_min_soc_strong_forecast_pct: boostMinSocStrongForecastPct,\n boost_min_soc_medium_forecast_pct: boostMinSocMediumForecastPct,\n end_of_day_soc_guard: endOfDaySocGuard,\n end_of_day_soc_target: endOfDaySocTarget,\n base_load_remaining_kwh: baseLoadRemainingKwh,\n flexible_safety_margin_kwh: flexibleSafetyMarginKwh,\n ac_loads_max_safe_w: acLoadsMaxSafeW,\n water_heater_switch: waterHeaterSwitchOn,\n water_heater_energy_total_kwh: round2(waterHeaterEnergyTotalKwh),\n last_signature: lastSignature || null,\n evcs_priority_active: evcsPriorityActive,\n energy_priority_mode: energyPriorityMode,\n energy_priority_reason: energyPriorityReason || null,\n evcs_priority_until: evcsPriorityUntilAt || null\n },\n computed: {\n forecast_strength: forecastStrength,\n strong_forecast: strongForecast,\n medium_forecast: mediumForecast,\n strong_pv_now: strongPvNow,\n medium_pv_now: mediumPvNow,\n net_pv_headroom_w: Math.round(netPvHeadroomW),\n pv_covers_house_now: pvCoversHouseNow,\n pv_started_well: pvStartedWell,\n battery_usable_capacity_kwh_internal: batteryCapacityKwh,\n energy_needed_to_reach_target_kwh: round2(energyNeededToReachTargetKwh),\n green_energy_kwh: round2(greenEnergyKwh),\n auto_energy_kwh: round2(autoEnergyKwh),\n boost_energy_kwh: round2(boostEnergyKwh),\n projected_green_soc: round1(projectedGreenSoc),\n projected_auto_soc: round1(projectedAutoSoc),\n projected_boost_soc: round1(projectedBoostSoc),\n green_budget_margin_kwh: round2(greenBudgetMarginKwh),\n auto_budget_margin_kwh: round2(autoBudgetMarginKwh),\n boost_budget_margin_kwh: round2(boostBudgetMarginKwh),\n ac_safe: acSafe,\n battery_not_draining_hard: batteryNotDrainingHard,\n green_allowed: greenAllowed,\n auto_allowed: autoAllowed,\n boost_allowed_by_budget: boostAllowedByBudget,\n boost_allowed: boostAllowed,\n early_boost_strong_ready: earlyBoostStrongReady,\n early_boost_medium_ready: earlyBoostMediumReady,\n auto_ready: autoReady,\n green_ready: greenReady,\n base_recommended_mode: baseRecommendedMode,\n base_advice_color: baseAdviceColor,\n base_state: baseState,\n observed_power_w: Math.round(observedPowerW),\n observed_regime: observedRegime,\n sample_duration_min: sampleIsUsable ? round1(sampleDurationMin) : null,\n energy_delta_kwh: sampleIsUsable ? round2(energyDeltaKwh) : null,\n mismatch_active: mismatchActive,\n mismatch_severity: mismatchSeverity,\n mismatch_duration_min: round1(mismatchDurationMin),\n evcs_priority_active: evcsPriorityActive,\n protection_state: protectionState,\n real_conflict_now: realConflictNow,\n restore_energy_ok: restoreEnergyOk,\n restore_surplus_w: restoreSurplusW,\n mode_mismatch_delay_min: modeMismatchDelayMin\n },\n decision: {\n recommended_mode: recommendedMode,\n advice_color: adviceColor,\n state,\n legacy_advice_ok: legacyAdviceOk,\n selected_load_kwh: round2(selectedLoadKwh),\n projected_end_of_day_soc: round1(selectedProjectedSoc),\n budget_margin_kwh: round2(selectedBudgetMarginKwh),\n observed_power_w: Math.round(observedPowerW),\n observed_regime: observedRegime,\n mismatch_active: mismatchActive,\n mismatch_severity: mismatchSeverity,\n mismatch_duration_min: round1(mismatchDurationMin),\n pending_user_action: pendingUserActionSafe,\n power_switch_action: powerSwitchAction,\n power_switch_desired_on: powerSwitchDesiredOn,\n force_off_now: forceOffNow,\n restore_now: restoreNow,\n forced_off_by_advisor: forcedOffByAdvisor,\n forced_off_reason: forcedOffReasonSafe,\n forced_off_at: forcedOffByAdvisor ? forcedOffAtSafe || null : null,\n signature,\n signature_changed: signatureChanged,\n should_notify: notifyWanted,\n reason,\n short_reason: shortReason\n },\n ha_service_calls: {\n helper_recommended_mode: {\n domain: 'input_select',\n service: 'select_option',\n data: {\n entity_id: 'input_select.victron_water_heater_recommended_mode',\n option: recommendedMode\n }\n },\n helper_advice_color: {\n domain: 'input_select',\n service: 'select_option',\n data: {\n entity_id: 'input_select.victron_water_heater_advice_color',\n option: adviceColor\n }\n },\n helper_state: {\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_advice_state',\n value: state\n }\n },\n helper_reason: {\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_advice_reason',\n value: shortReason || 'Aucune raison'\n }\n },\n helper_signature: {\n execute: signatureChanged,\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_advice_last_signature',\n value: signature\n }\n },\n helper_projected_soc: {\n domain: 'input_number',\n service: 'set_value',\n data: {\n entity_id: 'input_number.victron_water_heater_projected_end_of_day_soc',\n value: round1(selectedProjectedSoc)\n }\n },\nhelper_budget_margin: {\n domain: 'input_number',\n service: 'set_value',\n data: {\n entity_id: 'input_number.victron_water_heater_budget_margin_kwh',\n value: Math.max(BUDGET_MARGIN_MIN, Math.min(BUDGET_MARGIN_MAX, round2(selectedBudgetMarginKwh)))\n }\n},\n helper_load_kwh: {\n domain: 'input_number',\n service: 'set_value',\n data: {\n entity_id: 'input_number.victron_load_water_heater_kwh',\n value: round2(selectedLoadKwh)\n }\n },\n helper_legacy_advice_ok: {\n domain: 'input_boolean',\n service: boolService(legacyAdviceOk),\n data: {\n entity_id: 'input_boolean.victron_advice_water_heater_ok'\n }\n },\n helper_green_allowed: {\n domain: 'input_boolean',\n service: boolService(greenAllowed),\n data: {\n entity_id: 'input_boolean.victron_water_heater_green_allowed'\n }\n },\n helper_auto_allowed: {\n domain: 'input_boolean',\n service: boolService(autoAllowed),\n data: {\n entity_id: 'input_boolean.victron_water_heater_auto_allowed'\n }\n },\n helper_boost_allowed: {\n domain: 'input_boolean',\n service: boolService(boostAllowed),\n data: {\n entity_id: 'input_boolean.victron_water_heater_boost_allowed'\n }\n },\n helper_observed_power: {\n domain: 'input_number',\n service: 'set_value',\n data: {\n entity_id: 'input_number.victron_water_heater_observed_power_w',\n value: Math.round(observedPowerW)\n }\n },\n helper_observed_regime: {\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_observed_regime',\n value: observedRegime\n }\n },\n helper_pending_user_action: {\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_pending_user_action',\n value: pendingUserActionSafe\n }\n },\n helper_mismatch_since: {\n execute: mismatchActive && !!mismatchSinceAtEffective,\n domain: 'input_datetime',\n service: 'set_datetime',\n data: {\n entity_id: 'input_datetime.victron_water_heater_mode_mismatch_since',\n datetime: mismatchSinceAtEffective\n }\n },\n helper_energy_prev_kwh: {\n domain: 'input_number',\n service: 'set_value',\n data: {\n entity_id: 'input_number.victron_water_heater_energy_total_prev_kwh',\n value: round2(waterHeaterEnergyTotalKwh)\n }\n },\n helper_energy_prev_at: {\n domain: 'input_datetime',\n service: 'set_datetime',\n data: {\n entity_id: 'input_datetime.victron_water_heater_energy_prev_at',\n datetime: now.stamp\n }\n },\n helper_forced_off_by_advisor: {\n domain: 'input_boolean',\n service: boolService(forcedOffByAdvisor),\n data: {\n entity_id: 'input_boolean.victron_water_heater_forced_off_by_advisor'\n }\n },\n helper_forced_off_reason: {\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_forced_off_reason',\n value: forcedOffReasonSafe\n }\n },\n helper_forced_off_at: {\n execute: forceOffNow && !!forcedOffAtSafe,\n domain: 'input_datetime',\n service: 'set_datetime',\n data: {\n entity_id: 'input_datetime.victron_water_heater_forced_off_at',\n datetime: forcedOffAtSafe\n }\n },\n // Jour faible (07/10/2026) : la coupure appartient a la regle « eau chaude en HC de nuit ».\n helper_off_jour_faible: {\n domain: 'input_boolean',\n service: boolService(offJourFaible),\n data: {\n entity_id: 'input_boolean.victron_water_heater_off_jour_faible'\n }\n },\n water_heater_power_switch: {\n execute: powerSwitchAction !== 'none',\n domain: 'switch',\n service: powerSwitchDesiredOn ? 'turn_on' : 'turn_off',\n data: {\n entity_id: 'switch.tt_chauffe_eau_pleumeur_switch'\n }\n },\n logbook: {\n execute: signatureChanged || forceOffNow || restoreNow,\n domain: 'logbook',\n service: 'log',\n data: {\n name: 'Water Heater Advisor',\n message: `${recommendedMode}/${adviceColor} | regime=${observedRegime} | prioEVCS=${evcsPriorityActive ? 'on' : 'off'} | cut=${forcedOffByAdvisor ? 'on' : 'off'} | ${shortReason}`,\n entity_id: 'switch.tt_chauffe_eau_pleumeur_switch'\n }\n },\n mobile_notification: {\n execute: notifyWanted,\n domain: cfg.mobileNotifyDomain,\n service: cfg.mobileNotifyService,\n data: {\n title: notifyTitle,\n message: notifyMessage,\n data: {\n push: {\n 'interruption-level': 'time-sensitive',\n sound: { name: 'default' }\n },\n ttl: 0,\n priority: 'high'\n }\n }\n }\n }\n};\n\nreturn [{ json: result }];" }, "id": "481de0f8-22a8-4aae-b47d-493098383c6c", "name": "ECS Output Builder", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1280, -160 ] }, { "parameters": { "method": "POST", "url": "={{ 'http://10.10.10.17:8123/api/services/' + $json.domain + '/' + $json.service }}\n", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Authorization", "value": "={{ 'Bearer ' + ($env.HA_TOKEN || '') }}" }, { "name": "Content-Type", "value": "application/json" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ $json.data }}", "options": { "response": { "response": { "responseFormat": "json" } }, "timeout": 10000 } }, "id": "89d75698-da63-4598-a35b-86f0ade8a11c", "name": "Execute HA Service", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 1728, -160 ], "continueOnFail": true }, { "parameters": { "rule": { "interval": [ { "field": "minutes" } ] } }, "id": "edabb941-0e10-429b-bf0e-9af229a08d28", "name": "Schedule Trigger", "type": "n8n-nodes-base.scheduleTrigger", "typeVersion": 1.2, "position": [ -288, -160 ] }, { "parameters": { "method": "POST", "url": "=http://10.10.10.17:8123/api/template\n", "authentication": "genericCredentialType", "genericAuthType": "httpBearerAuth", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Content-Type", "value": "application/json" }, { "name": "Accept", "value": "text/plain" } ] }, "sendBody": true, "bodyParameters": { "parameters": [ { "name": "template", "value": "{#- 07/10/2026 : prevision lue comme le bilan (input_select.evcs_balance_forecast_source).\n VRM : reste du jour = heures restantes de la courbe horaire (heure en cours au\n prorata), demain = somme de la courbe de demain. Courbe absente ou\n malformee -> repli sur Forecast.Solar. -#}\n{%- set src = states('input_select.evcs_balance_forecast_source') -%}\n{%- set vt = states('input_text.evcs_balance_vrm_today').split(',') -%}\n{%- set vd = states('input_text.evcs_balance_vrm_tomorrow').split(',') -%}\n{%- set p = namespace(reste=0, demain=0, ok=(src == 'vrm' and vt | length == 24 and vd | length == 24)) -%}\n{%- if p.ok -%}\n {%- for i in range(now().hour, 24) -%}\n {%- set v = vt[i] | float(0) -%}\n {%- set p.reste = p.reste + (v * (1 - now().minute / 60) if i == now().hour else v) -%}\n {%- endfor -%}\n {%- for v in vd -%}{%- set p.demain = p.demain + (v | float(0)) -%}{%- endfor -%}\n{%- endif -%}\n{{ {\n \"soc_percent\": states(\"sensor.victron_battery_soc\"),\n \"battery_current_a\": states(\"sensor.victron_battery_current\"),\n \"pv_power_w\": states(\"sensor.victron_pv_power_system\"),\n \"pv_power_10m_avg_w\": states(\"sensor.victron_pv_power_10m_avg\"),\n \"house_ac_power_w\": states(\"sensor.victron_consumption_power_l1\"),\n \"grid_power_w\": states(\"sensor.victron_grid_power_l1\"),\n \"grid_state\": states(\"switch.edf_general_ok_switch\"),\n \"victron_acin1_available\": states(\"sensor.victron_ac_in1_available\"),\n\n \"today_remaining_kwh\": (p.reste | round(2)) if p.ok else states(\"sensor.energy_production_today_remaining\"),\n \"tomorrow_kwh\": (p.demain | round(2)) if p.ok else states(\"sensor.energy_production_tomorrow\"),\n \"forecast_source\": \"vrm\" if p.ok else \"forecast_solar\",\n\n \"ecs_nuit\": states(\"input_boolean.evcs_balance_ecs_nuit\"),\n \"ecs_nuit_jour\": states(\"input_text.evcs_balance_ecs_nuit_jour\"),\n \"hc_session_committed\": states(\"input_boolean.victron_evcs_night_grid_session_committed\"),\n \"ecs_24h_kwh\": states(\"sensor.evcs_chauffe_eau_24h_kwh\"),\n \"off_jour_faible_prev\": states(\"input_boolean.victron_water_heater_off_jour_faible\"),\n\n \"advisor_enabled\": states(\"input_boolean.victron_water_heater_advisor_enabled\"),\n \"notifications_enabled\": states(\"input_boolean.victron_water_heater_notifications\"),\n\n \"hot_water_demand\": states(\"input_select.victron_water_heater_hot_water_demand\"),\n \"morning_boost_priority_enabled\": states(\"input_boolean.victron_water_heater_morning_boost_priority_enabled\"),\n \"morning_boost_latest_time\": states(\"input_datetime.victron_water_heater_morning_boost_latest_time\"),\n \"late_red_time\": states(\"input_datetime.victron_water_heater_late_red_time\"),\n\n \"green_power_w\": states(\"input_number.victron_water_heater_green_power_w\"),\n \"auto_power_w\": states(\"input_number.victron_water_heater_auto_power_w\"),\n \"boost_power_w\": states(\"input_number.victron_water_heater_boost_power_w\"),\n\n \"strong_forecast_kwh\": states(\"input_number.victron_water_heater_strong_forecast_kwh\"),\n \"medium_forecast_kwh\": states(\"input_number.victron_water_heater_medium_forecast_kwh\"),\n \"strong_pv_now_w\": states(\"input_number.victron_water_heater_strong_pv_now_w\"),\n \"medium_pv_now_w\": states(\"input_number.victron_water_heater_medium_pv_now_w\"),\n\n \"morning_boost_min_soc_strong_day\": states(\"input_number.victron_water_heater_morning_boost_min_soc_strong_day\"),\n \"boost_min_soc_medium_day\": states(\"input_number.victron_water_heater_boost_min_soc_medium_day\"),\n \"end_of_day_soc_guard\": states(\"input_number.victron_water_heater_end_of_day_soc_guard\"),\n\n \"end_of_day_soc_target\": states(\"input_number.victron_end_of_day_soc_target\"),\n \"base_load_remaining_kwh\": states(\"input_number.victron_base_load_remaining_kwh\"),\n \"flexible_safety_margin_kwh\": states(\"input_number.victron_flexible_safety_margin_kwh\"),\n \"ac_loads_max_safe_w\": states(\"input_number.victron_ac_loads_max_safe_w\"),\n\n \"day_start_time\": states(\"input_datetime.victron_flexible_day_start_time\"),\n \"day_stop_time\": states(\"input_datetime.victron_flexible_day_stop_time\"),\n\n \"last_signature\": states(\"input_text.victron_water_heater_advice_last_signature\"),\n\n \"evcs_priority_active\": states(\"input_boolean.victron_evcs_priority_active\"),\n \"energy_priority_mode\": states(\"input_select.victron_energy_priority_mode\"),\n \"energy_priority_reason\": states(\"input_text.victron_energy_priority_reason\"),\n \"evcs_priority_until\": states(\"input_datetime.victron_evcs_priority_until\"),\n\n \"water_heater_switch\": states(\"switch.tt_chauffe_eau_pleumeur_switch\"),\n \"water_heater_energy_total_kwh\": states(\"sensor.tt_chauffe_eau_pleumeur_energie_totale\"),\n\n \"energy_total_prev_kwh\": states(\"input_number.victron_water_heater_energy_total_prev_kwh\"),\n \"energy_prev_at\": states(\"input_datetime.victron_water_heater_energy_prev_at\"),\n\n \"observed_regime_helper\": states(\"input_text.victron_water_heater_observed_regime\"),\n \"observed_power_helper_w\": states(\"input_number.victron_water_heater_observed_power_w\"),\n\n \"mode_mismatch_since\": states(\"input_datetime.victron_water_heater_mode_mismatch_since\"),\n\n \"forced_off_by_advisor\": states(\"input_boolean.victron_water_heater_forced_off_by_advisor\"),\n \"forced_off_reason\": states(\"input_text.victron_water_heater_forced_off_reason\"),\n \"forced_off_at\": states(\"input_datetime.victron_water_heater_forced_off_at\"),\n\n \"pending_user_action_prev\": states(\"input_text.victron_water_heater_pending_user_action\"),\n\n \"restore_surplus_w\": states(\"input_number.victron_water_heater_restore_surplus_w\"),\n \"mode_mismatch_delay_min\": states(\"input_number.victron_water_heater_mode_mismatch_delay_min\")\n} | tojson }}\n" } ] }, "options": {} }, "id": "264b44f4-227a-482e-b4da-9468855ce429", "name": "HA Snapshot Water Heater Advisor V2", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ -64, -160 ], "credentials": { "httpBearerAuth": { "id": "uv3sknYYigxBkaVN", "name": "Bearer Auth account 2" } } }, { "parameters": { "jsCode": "const root = $input.first()?.json ?? {};\nconst calls = root.ha_service_calls ?? {};\nconst decision = root.decision ?? {};\n\nfunction isObject(v) {\n return v !== null && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction isValidParisDateTime(v) {\n return typeof v === 'string' && /^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/.test(v.trim());\n}\n\nfunction normalizeText(v) {\n return (v ?? '').toString();\n}\n\nfunction shouldExecute(call) {\n if (!isObject(call)) return false;\n return call.execute !== false;\n}\n\nfunction getBaseUrl() {\n return ($env.HA_BASE_URL || 'http://10.10.10.17:8123').replace(/\\/$/, '');\n}\n\nfunction getDebugEntityId(data) {\n if (!isObject(data)) return '';\n if (typeof data.entity_id === 'string' && data.entity_id.trim()) return data.entity_id.trim();\n return '';\n}\n\nfunction sanitizeCall(key, call) {\n if (!isObject(call)) return null;\n if (!shouldExecute(call)) return null;\n\n const domain = normalizeText(call.domain).trim();\n const service = normalizeText(call.service).trim();\n const data = isObject(call.data) ? { ...call.data } : {};\n\n if (!domain || !service) return null;\n\n // Garde-fous ciblés\n if (domain === 'input_datetime' && service === 'set_datetime') {\n if (!isValidParisDateTime(data.datetime)) return null;\n }\n\n if (domain === 'input_text' && service === 'set_value') {\n data.value = normalizeText(data.value);\n }\n\n if (domain === 'input_select' && service === 'select_option') {\n if (!normalizeText(data.option).trim()) return null;\n }\n\n if (domain === 'input_number' && service === 'set_value') {\n const n = Number(data.value);\n if (!Number.isFinite(n)) return null;\n data.value = n;\n }\n\n if ((domain === 'switch' || domain === 'input_boolean') && !data.entity_id) {\n return null;\n }\n\n if (domain === 'notify') {\n data.title = normalizeText(data.title);\n data.message = normalizeText(data.message);\n }\n\n const baseUrl = getBaseUrl();\n const debugEntityId = getDebugEntityId(data);\n const debugUrl = `${baseUrl}/api/services/${domain}/${service}`;\n\n return {\n json: {\n action: key,\n domain,\n service,\n data,\n\n // mini debug demandé\n debug_action: key,\n debug_entity_id: debugEntityId || '(none)',\n debug_url: debugUrl,\n\n meta: {\n source: 'water_heater_advisor',\n timestamp_paris: root.timestamp_paris ?? null,\n recommended_mode: decision.recommended_mode ?? null,\n advice_color: decision.advice_color ?? null,\n state: decision.state ?? null\n }\n }\n };\n}\n\n// Ordre conseillé\nconst orderedKeys = [\n 'helper_recommended_mode',\n 'helper_advice_color',\n 'helper_state',\n 'helper_reason',\n 'helper_signature',\n\n 'helper_projected_soc',\n 'helper_budget_margin',\n 'helper_load_kwh',\n\n 'helper_legacy_advice_ok',\n 'helper_green_allowed',\n 'helper_auto_allowed',\n 'helper_boost_allowed',\n\n 'helper_observed_power',\n 'helper_observed_regime',\n 'helper_pending_user_action',\n 'helper_mismatch_since',\n\n 'helper_energy_prev_kwh',\n 'helper_energy_prev_at',\n\n 'helper_forced_off_by_advisor',\n 'helper_forced_off_reason',\n 'helper_forced_off_at',\n\n 'water_heater_power_switch',\n\n 'logbook',\n 'mobile_notification'\n];\n\nconst actions = [];\nconst alreadySeen = new Set();\n\nfor (const key of orderedKeys) {\n alreadySeen.add(key);\n const built = sanitizeCall(key, calls[key]);\n if (built) actions.push(built);\n}\n\n// Sécurité si de nouveaux appels sont ajoutés plus tard\nfor (const [key, call] of Object.entries(calls)) {\n if (alreadySeen.has(key)) continue;\n const built = sanitizeCall(key, call);\n if (built) actions.push(built);\n}\n\nreturn actions;\n" }, "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1504, -160 ], "id": "3b9b3251-a9ea-4fb4-ba6e-899bc39371e7", "name": "BUILD ECS HA Actions1" } ], "connections": { "ECS Normalize Inputs": { "main": [ [ { "node": "ECS EVCS & Water Heater Observation", "type": "main", "index": 0 } ] ] }, "ECS EVCS & Water Heater Observation": { "main": [ [ { "node": "ECS Energy Model & Early Boost Signals", "type": "main", "index": 0 } ] ] }, "ECS Energy Model & Early Boost Signals": { "main": [ [ { "node": "ECS Base Advisor Decision", "type": "main", "index": 0 } ] ] }, "ECS Base Advisor Decision": { "main": [ [ { "node": "ECS Final Arbitration & Protection", "type": "main", "index": 0 } ] ] }, "ECS Final Arbitration & Protection": { "main": [ [ { "node": "ECS Output Builder", "type": "main", "index": 0 } ] ] }, "ECS Output Builder": { "main": [ [ { "node": "BUILD ECS HA Actions1", "type": "main", "index": 0 } ] ] }, "Schedule Trigger": { "main": [ [ { "node": "HA Snapshot Water Heater Advisor V2", "type": "main", "index": 0 } ] ] }, "HA Snapshot Water Heater Advisor V2": { "main": [ [ { "node": "ECS Normalize Inputs", "type": "main", "index": 0 } ] ] }, "BUILD ECS HA Actions1": { "main": [ [ { "node": "Execute HA Service", "type": "main", "index": 0 } ] ] } }, "settings": { "executionOrder": "v1", "binaryMode": "separate", "availableInMCP": true, "timeSavedMode": "fixed", "callerPolicy": "workflowsFromSameOwner", "saveDataErrorExecution": "all" }, "staticData": { "node:Schedule Trigger": { "recurrenceRules": [ null ], "recurrenceRuleSignatures": [ null ] } }, "meta": null, "nodeGroups": [], "pinData": {}, "versionId": "104ba5d2-fa60-4b6e-9d00-d0b853c79fd4", "activeVersionId": "104ba5d2-fa60-4b6e-9d00-d0b853c79fd4", "versionCounter": 87, "triggerCount": 1, "sourceWorkflowId": null, "shared": [ { "updatedAt": "2026-04-23T00:41:43.730Z", "createdAt": "2026-04-23T00:41:43.730Z", "role": "workflow:owner", "workflowId": "yX2j8m04e3pxaoQq", "projectId": "1q2yd8IyTc8fb25V", "project": { "updatedAt": "2026-02-06T16:27:24.469Z", "createdAt": "2026-02-06T16:23:40.444Z", "id": "1q2yd8IyTc8fb25V", "name": "thierry tallagrand ", "type": "personal", "icon": null, "description": null, "customTelemetryTags": [], "creatorId": "8b9e9552-cd74-4863-82a3-174b3b3befa2" } } ], "tags": [], "activeVersion": { "updatedAt": "2026-06-12T21:11:20.000Z", "createdAt": "2026-05-06T14:58:05.398Z", "versionId": "104ba5d2-fa60-4b6e-9d00-d0b853c79fd4", "workflowId": "yX2j8m04e3pxaoQq", "nodes": [ { "parameters": { "jsCode": "function num(v, fallback = NaN) {\n const n = Number.parseFloat(v);\n return Number.isFinite(n) ? n : fallback;\n}\n\nfunction low(v) {\n return (v ?? '').toString().trim().toLowerCase();\n}\n\nfunction parseMaybeJson(v) {\n if (typeof v !== 'string') return v;\n try {\n return JSON.parse(v);\n } catch {\n return v;\n }\n}\n\nfunction extractSnapshot(input) {\n if (typeof input === 'string') return parseMaybeJson(input);\n if (input?.data && typeof input.data === 'string') return parseMaybeJson(input.data);\n if (input?.body && typeof input.body === 'string') return parseMaybeJson(input.body);\n if (input?.data && typeof input.data === 'object') return input.data;\n if (input?.body && typeof input.body === 'object') return input.body;\n return input ?? {};\n}\n\nfunction clamp(v, min, max) {\n return Math.min(Math.max(v, min), max);\n}\n\nfunction to2(n) {\n return String(n).padStart(2, '0');\n}\n\nfunction getParisNowParts() {\n const fmt = new Intl.DateTimeFormat('fr-FR', {\n timeZone: 'Europe/Paris',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false,\n });\n\n const parts = Object.fromEntries(\n fmt.formatToParts(new Date())\n .filter(p => p.type !== 'literal')\n .map(p => [p.type, p.value])\n );\n\n const hour = Number(parts.hour) === 24 ? 0 : Number(parts.hour);\n const date = `${parts.year}-${parts.month}-${parts.day}`;\n const stamp = `${date} ${to2(hour)}:${parts.minute}:${parts.second}`;\n\n return {\n year: Number(parts.year),\n month: Number(parts.month),\n day: Number(parts.day),\n hour,\n minute: Number(parts.minute),\n second: Number(parts.second),\n date,\n stamp,\n minNow: hour * 60 + Number(parts.minute),\n };\n}\n\nfunction getTzOffsetMs(utcTs, timeZone = 'Europe/Paris') {\n const dtf = new Intl.DateTimeFormat('en-US', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false,\n });\n\n const parts = Object.fromEntries(\n dtf.formatToParts(new Date(utcTs))\n .filter(p => p.type !== 'literal')\n .map(p => [p.type, p.value])\n );\n\n const asIfUtc = Date.UTC(\n Number(parts.year),\n Number(parts.month) - 1,\n Number(parts.day),\n Number(parts.hour) === 24 ? 0 : Number(parts.hour),\n Number(parts.minute),\n Number(parts.second)\n );\n\n const d = new Date(utcTs);\n const actualUtc = Date.UTC(\n d.getUTCFullYear(),\n d.getUTCMonth(),\n d.getUTCDate(),\n d.getUTCHours(),\n d.getUTCMinutes(),\n d.getUTCSeconds()\n );\n\n return asIfUtc - actualUtc;\n}\n\nfunction parseParisStampToMs(s) {\n const text = (s ?? '').toString().trim();\n const m = text.match(/^(\\\\d{4})-(\\\\d{2})-(\\\\d{2}) (\\\\d{2}):(\\\\d{2}):(\\\\d{2})$/);\n if (!m) return null;\n\n const y = Number(m[1]);\n const mo = Number(m[2]);\n const d = Number(m[3]);\n const h = Number(m[4]);\n const mi = Number(m[5]);\n const se = Number(m[6]);\n\n if (![y, mo, d, h, mi, se].every(Number.isFinite)) return null;\n\n const guessUtc = Date.UTC(y, mo - 1, d, h, mi, se);\n const off1 = getTzOffsetMs(guessUtc, 'Europe/Paris');\n let ts = guessUtc - off1;\n const off2 = getTzOffsetMs(ts, 'Europe/Paris');\n\n if (off2 !== off1) ts = guessUtc - off2;\n return ts;\n}\n\nfunction cleanStateText(v) {\n const s = (v ?? '').toString().trim();\n const x = s.toLowerCase();\n return ['unknown', 'unavailable', 'none', 'null'].includes(x) ? '' : s;\n}\n\nconst cfg = {\n mobileNotifyDomain: 'notify',\n mobileNotifyService: 'mobile_app_iphone_16_de_tt',\n batteryUsableCapacityKwh: 17.5,\n sampleWindowMinMin: 2,\n sampleWindowMinMax: 15,\n energyByDemandKwh: {\n low: { green: 0.9, auto: 1.4, boost: 2.0 },\n normal: { green: 1.4, auto: 2.2, boost: 3.1 },\n high: { green: 2.2, auto: 3.4, boost: 4.6 },\n three_showers: { green: 3.0, auto: 4.4, boost: 5.8 }\n }\n};\n\nconst raw = $input.first()?.json ?? {};\nconst input = extractSnapshot(raw);\nconst now = getParisNowParts();\nconst nowMs = Date.now();\n\nconst soc = clamp(num(input.soc_percent, 0), 0, 100);\nconst batteryCurrentA = num(input.battery_current_a, 0);\nconst pvPowerW = Math.max(0, num(input.pv_power_w, 0));\nconst pvPowerAvg10mW = Math.max(0, num(input.pv_power_10m_avg_w, pvPowerW));\nconst houseAcPowerW = Math.max(0, num(input.house_ac_power_w, 0));\nconst gridPowerW = num(input.grid_power_w, 0);\nconst gridIsOn = low(input.grid_state || 'off') === 'on';\nconst acInAvailable = num(input.victron_acin1_available, 0) === 1;\nconst gridAvailable = gridIsOn || acInAvailable;\nconst todayRemainingKwh = Math.max(0, num(input.today_remaining_kwh, 0));\nconst tomorrowKwh = Math.max(0, num(input.tomorrow_kwh, 0));\nconst advisorEnabled = low(input.advisor_enabled || 'off') === 'on';\nconst notificationsEnabled = low(input.notifications_enabled || 'off') === 'on';\n\nconst hotWaterDemandRaw = low(input.hot_water_demand || 'normal');\nconst hotWaterDemand = ['low', 'normal', 'high', 'three_showers'].includes(hotWaterDemandRaw)\n ? hotWaterDemandRaw\n : 'normal';\n\nconst greenPowerW = Math.max(0, num(input.green_power_w, 620));\nconst autoPowerW = Math.max(0, num(input.auto_power_w, 1200));\nconst boostPowerW = Math.max(0, num(input.boost_power_w, 2000));\nconst strongForecastKwh = Math.max(0, num(input.strong_forecast_kwh, 18));\nconst mediumForecastKwh = Math.max(0, num(input.medium_forecast_kwh, 10));\nconst strongPvNowW = Math.max(0, num(input.strong_pv_now_w, 2500));\nconst mediumPvNowW = Math.max(0, num(input.medium_pv_now_w, 1500));\nconst boostMinSocStrongForecastPct = clamp(num(input.morning_boost_min_soc_strong_day, 35), 0, 100);\nconst boostMinSocMediumForecastPct = clamp(num(input.boost_min_soc_medium_day, 50), 0, 100);\nconst endOfDaySocGuard = clamp(num(input.end_of_day_soc_guard, 85), 0, 100);\nconst endOfDaySocTarget = clamp(num(input.end_of_day_soc_target, 85), 0, 100);\nconst baseLoadRemainingKwh = Math.max(0, num(input.base_load_remaining_kwh, 0));\nconst flexibleSafetyMarginKwh = Math.max(0, num(input.flexible_safety_margin_kwh, 0));\nconst acLoadsMaxSafeW = Math.max(0, num(input.ac_loads_max_safe_w, 8000));\nconst lastSignature = cleanStateText(input.last_signature);\n\nreturn [{\n json: {\n meta: {\n workflow: 'water_heater_advisor',\n architecture: 'ecs_6nodes_simple_early_boost',\n node: 'ecs_normalize_inputs',\n timestamp_paris: now.stamp\n },\n cfg,\n now,\n nowMs,\n input,\n normalized: {\n soc,\n batteryCurrentA,\n pvPowerW,\n pvPowerAvg10mW,\n houseAcPowerW,\n gridPowerW,\n gridIsOn,\n acInAvailable,\n gridAvailable,\n todayRemainingKwh,\n tomorrowKwh,\n advisorEnabled,\n notificationsEnabled,\n hotWaterDemand,\n greenPowerW,\n autoPowerW,\n boostPowerW,\n strongForecastKwh,\n mediumForecastKwh,\n strongPvNowW,\n mediumPvNowW,\n boostMinSocStrongForecastPct,\n boostMinSocMediumForecastPct,\n endOfDaySocGuard,\n endOfDaySocTarget,\n baseLoadRemainingKwh,\n flexibleSafetyMarginKwh,\n acLoadsMaxSafeW,\n lastSignature\n }\n }\n}];" }, "id": "1226082d-222c-4837-99d3-35094bd1c4f1", "name": "ECS Normalize Inputs", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 160, -160 ] }, { "parameters": { "jsCode": "function num(v, fallback = NaN) {\n const n = Number.parseFloat(v);\n return Number.isFinite(n) ? n : fallback;\n}\n\nfunction low(v) {\n return (v ?? '').toString().trim().toLowerCase();\n}\n\nfunction cleanStateText(v) {\n const s = (v ?? '').toString().trim();\n const x = s.toLowerCase();\n return ['unknown', 'unavailable', 'none', 'null'].includes(x) ? '' : s;\n}\n\nfunction getTzOffsetMs(utcTs, timeZone = 'Europe/Paris') {\n const dtf = new Intl.DateTimeFormat('en-US', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false,\n });\n\n const parts = Object.fromEntries(\n dtf.formatToParts(new Date(utcTs))\n .filter(p => p.type !== 'literal')\n .map(p => [p.type, p.value])\n );\n\n const asIfUtc = Date.UTC(\n Number(parts.year),\n Number(parts.month) - 1,\n Number(parts.day),\n Number(parts.hour) === 24 ? 0 : Number(parts.hour),\n Number(parts.minute),\n Number(parts.second)\n );\n\n const d = new Date(utcTs);\n const actualUtc = Date.UTC(\n d.getUTCFullYear(),\n d.getUTCMonth(),\n d.getUTCDate(),\n d.getUTCHours(),\n d.getUTCMinutes(),\n d.getUTCSeconds()\n );\n\n return asIfUtc - actualUtc;\n}\n\nfunction parseParisStampToMs(s) {\n const text = (s ?? '').toString().trim();\n const m = text.match(/^(\\\\d{4})-(\\\\d{2})-(\\\\d{2}) (\\\\d{2}):(\\\\d{2}):(\\\\d{2})$/);\n if (!m) return null;\n\n const y = Number(m[1]);\n const mo = Number(m[2]);\n const d = Number(m[3]);\n const h = Number(m[4]);\n const mi = Number(m[5]);\n const se = Number(m[6]);\n\n if (![y, mo, d, h, mi, se].every(Number.isFinite)) return null;\n\n const guessUtc = Date.UTC(y, mo - 1, d, h, mi, se);\n const off1 = getTzOffsetMs(guessUtc, 'Europe/Paris');\n let ts = guessUtc - off1;\n const off2 = getTzOffsetMs(ts, 'Europe/Paris');\n\n if (off2 !== off1) ts = guessUtc - off2;\n return ts;\n}\n\nfunction cleanParisStamp(v) {\n const s = cleanStateText(v);\n return parseParisStampToMs(s) !== null ? s : '';\n}\n\nfunction minutesSince(ts, nowMs) {\n if (ts === null || nowMs === null) return null;\n return Math.max(0, (nowMs - ts) / 60000);\n}\n\nconst root = $input.first()?.json ?? {};\nconst cfg = root.cfg ?? {};\nconst now = root.now ?? {};\nconst nowMs = root.nowMs ?? null;\nconst input = root.input ?? {};\nconst normalized = root.normalized ?? {};\n\nconst { greenPowerW, autoPowerW, boostPowerW } = normalized;\n\nconst evcsPriorityActiveRaw = low(input.evcs_priority_active || 'off') === 'on';\nconst energyPriorityMode = cleanStateText(input.energy_priority_mode || 'normal').toLowerCase() || 'normal';\nconst energyPriorityReason = cleanStateText(input.energy_priority_reason);\nconst evcsPriorityUntilAt = cleanParisStamp(input.evcs_priority_until);\nconst evcsPriorityUntilMs = parseParisStampToMs(evcsPriorityUntilAt);\n\nconst evcsPriorityActive =\n evcsPriorityActiveRaw &&\n energyPriorityMode === 'evcs_priority' &&\n (\n evcsPriorityUntilMs === null ||\n (nowMs !== null && evcsPriorityUntilMs > nowMs + 1000)\n );\n\nconst waterHeaterSwitchOn = low(input.water_heater_switch || 'off') === 'on';\nconst waterHeaterEnergyTotalKwh = Math.max(0, num(input.water_heater_energy_total_kwh, 0));\nconst energyPrevKwh = num(input.energy_total_prev_kwh, NaN);\nconst energyPrevAt = cleanParisStamp(input.energy_prev_at);\nconst energyPrevMs = parseParisStampToMs(energyPrevAt);\nconst observedPowerPrevW = Math.max(0, num(input.observed_power_helper_w, 0));\nconst observedRegimePrev = cleanStateText(input.observed_regime_helper).toLowerCase();\nconst mismatchSinceAt = cleanParisStamp(input.mode_mismatch_since);\nconst mismatchSinceMsPrev = parseParisStampToMs(mismatchSinceAt);\nconst forcedOffByAdvisorPrev = low(input.forced_off_by_advisor || 'off') === 'on';\nconst forcedOffReasonPrev = cleanStateText(input.forced_off_reason);\nconst forcedOffAtPrev = cleanParisStamp(input.forced_off_at);\nconst forcedOffAtPrevMs = parseParisStampToMs(forcedOffAtPrev);\nconst pendingUserActionPrev = cleanStateText(input.pending_user_action_prev);\nconst restoreSurplusW = Math.max(0, num(input.restore_surplus_w, 2500));\nconst modeMismatchDelayMin = Math.max(1, num(input.mode_mismatch_delay_min, 15));\n\nconst sampleDurationMin = minutesSince(energyPrevMs, nowMs);\nconst energyDeltaKwh =\n Number.isFinite(energyPrevKwh)\n ? Math.max(0, waterHeaterEnergyTotalKwh - energyPrevKwh)\n : NaN;\n\nconst sampleIsUsable =\n Number.isFinite(sampleDurationMin) &&\n sampleDurationMin >= (cfg.sampleWindowMinMin ?? 2) &&\n sampleDurationMin <= (cfg.sampleWindowMinMax ?? 15) &&\n Number.isFinite(energyDeltaKwh);\n\nlet observedPowerW = 0;\nif (sampleIsUsable) {\n observedPowerW = Math.max(0, (energyDeltaKwh * 60000) / sampleDurationMin);\n} else if (waterHeaterSwitchOn && observedPowerPrevW > 0) {\n observedPowerW = observedPowerPrevW;\n}\n\nconst offThresholdW = Math.max(80, greenPowerW * 0.25);\nconst hpUpperW = (greenPowerW + autoPowerW) / 2;\nconst resistiveUpperW = (autoPowerW + boostPowerW) / 2;\n\nlet observedRegime = 'unknown';\nif (!waterHeaterSwitchOn) {\n observedRegime = 'off';\n} else if (!sampleIsUsable && observedRegimePrev) {\n observedRegime = observedRegimePrev;\n} else if (observedPowerW < offThresholdW) {\n observedRegime = 'off';\n} else if (observedPowerW < hpUpperW) {\n observedRegime = 'hp_low';\n} else if (observedPowerW < resistiveUpperW) {\n observedRegime = 'resistive_mid';\n} else {\n observedRegime = 'boost_high';\n}\n\nreturn [{\n json: {\n ...root,\n meta: {\n ...(root.meta ?? {}),\n node: 'ecs_evcs_and_water_heater_observation'\n },\n observation: {\n evcsPriorityActiveRaw,\n energyPriorityMode,\n energyPriorityReason,\n evcsPriorityUntilAt,\n evcsPriorityUntilMs,\n evcsPriorityActive,\n waterHeaterSwitchOn,\n waterHeaterEnergyTotalKwh,\n energyPrevKwh,\n energyPrevAt,\n energyPrevMs,\n observedPowerPrevW,\n observedRegimePrev,\n mismatchSinceAt,\n mismatchSinceMsPrev,\n forcedOffByAdvisorPrev,\n forcedOffReasonPrev,\n forcedOffAtPrev,\n forcedOffAtPrevMs,\n pendingUserActionPrev,\n restoreSurplusW,\n modeMismatchDelayMin,\n sampleDurationMin,\n energyDeltaKwh,\n sampleIsUsable,\n observedPowerW,\n observedRegime,\n offThresholdW,\n hpUpperW,\n resistiveUpperW\n }\n }\n}];" }, "id": "0979b36d-13b0-492a-bafb-8c99219bbdb5", "name": "ECS EVCS & Water Heater Observation", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 384, -160 ] }, { "parameters": { "jsCode": "function clamp(v, min, max) {\n return Math.min(Math.max(v, min), max);\n}\n\nconst root = $input.first()?.json ?? {};\nconst cfg = root.cfg ?? {};\nconst normalized = root.normalized ?? {};\n\nconst {\n soc,\n batteryCurrentA,\n pvPowerW,\n pvPowerAvg10mW,\n houseAcPowerW,\n todayRemainingKwh,\n tomorrowKwh,\n advisorEnabled,\n hotWaterDemand,\n greenPowerW,\n autoPowerW,\n boostPowerW,\n strongForecastKwh,\n mediumForecastKwh,\n strongPvNowW,\n mediumPvNowW,\n boostMinSocStrongForecastPct,\n boostMinSocMediumForecastPct,\n endOfDaySocGuard,\n endOfDaySocTarget,\n baseLoadRemainingKwh,\n flexibleSafetyMarginKwh,\n acLoadsMaxSafeW\n} = normalized;\n\nconst targetSoc = Math.max(endOfDaySocTarget, endOfDaySocGuard);\nconst batteryCapacityKwh = cfg.batteryUsableCapacityKwh ?? 17.5;\n\nconst energyTable =\n (cfg.energyByDemandKwh && cfg.energyByDemandKwh[hotWaterDemand]) ||\n (cfg.energyByDemandKwh && cfg.energyByDemandKwh.normal) || {\n green: 1.4,\n auto: 2.2,\n boost: 3.1\n };\n\nconst greenEnergyKwh = energyTable.green;\nconst autoEnergyKwh = energyTable.auto;\nconst boostEnergyKwh = energyTable.boost;\n\nconst energyNeededToReachTargetKwh =\n Math.max(0, ((targetSoc - soc) / 100) * batteryCapacityKwh);\n\nfunction projectedEndSocAfterMode(loadKwh) {\n const netKwh =\n todayRemainingKwh -\n baseLoadRemainingKwh -\n flexibleSafetyMarginKwh -\n loadKwh;\n\n const deltaSoc = (netKwh / batteryCapacityKwh) * 100;\n return clamp(soc + deltaSoc, 0, 100);\n}\n\nfunction budgetMarginKwh(loadKwh) {\n return (\n todayRemainingKwh -\n baseLoadRemainingKwh -\n flexibleSafetyMarginKwh -\n loadKwh -\n energyNeededToReachTargetKwh\n );\n}\n\nconst projectedGreenSoc = projectedEndSocAfterMode(greenEnergyKwh);\nconst projectedAutoSoc = projectedEndSocAfterMode(autoEnergyKwh);\nconst projectedBoostSoc = projectedEndSocAfterMode(boostEnergyKwh);\n\nconst greenBudgetMarginKwh = budgetMarginKwh(greenEnergyKwh);\nconst autoBudgetMarginKwh = budgetMarginKwh(autoEnergyKwh);\nconst boostBudgetMarginKwh = budgetMarginKwh(boostEnergyKwh);\n\nconst strongForecast =\n todayRemainingKwh >= strongForecastKwh ||\n tomorrowKwh >= strongForecastKwh;\n\nconst mediumForecast =\n !strongForecast &&\n (\n todayRemainingKwh >= mediumForecastKwh ||\n tomorrowKwh >= mediumForecastKwh\n );\n\nconst forecastStrength =\n strongForecast ? 'strong' :\n mediumForecast ? 'medium' :\n 'weak';\n\nconst pv10mW = Number.isFinite(pvPowerAvg10mW) ? pvPowerAvg10mW : pvPowerW;\nconst netPvHeadroomW = Math.round(pv10mW - houseAcPowerW);\nconst pvCoversHouseNow = pvPowerW > houseAcPowerW;\nconst strongPvNow = pv10mW >= strongPvNowW || pvPowerW >= strongPvNowW;\nconst mediumPvNow = pv10mW >= mediumPvNowW || pvPowerW >= mediumPvNowW;\n\nconst pvStartedWell =\n mediumPvNow &&\n pvCoversHouseNow &&\n netPvHeadroomW >= Math.max(300, Math.round(greenPowerW * 0.5));\n\nconst acSafe = acLoadsMaxSafeW <= 0 ? true : houseAcPowerW <= acLoadsMaxSafeW;\nconst batteryNotDrainingHard = batteryCurrentA >= -2;\n\nconst greenAllowed =\n advisorEnabled &&\n acSafe &&\n (\n projectedGreenSoc >= targetSoc - 6 ||\n greenBudgetMarginKwh >= -1.0 ||\n soc >= targetSoc\n );\n\nconst autoAllowed =\n advisorEnabled &&\n acSafe &&\n (\n autoBudgetMarginKwh >= 0 ||\n projectedAutoSoc >= targetSoc ||\n (strongForecast && projectedAutoSoc >= targetSoc - 2)\n );\n\nconst boostAllowedByBudget =\n advisorEnabled &&\n acSafe &&\n (\n projectedBoostSoc >= targetSoc ||\n boostBudgetMarginKwh >= 0 ||\n (strongForecast && projectedBoostSoc >= targetSoc - 5) ||\n (strongForecast && boostBudgetMarginKwh >= -1.0)\n );\n\nconst earlyBoostStrongReady =\n boostAllowedByBudget &&\n soc >= boostMinSocStrongForecastPct &&\n pvStartedWell &&\n (strongForecast || strongPvNow);\n\nconst earlyBoostMediumReady =\n boostAllowedByBudget &&\n mediumForecast &&\n soc >= boostMinSocMediumForecastPct &&\n pvStartedWell &&\n netPvHeadroomW >= greenPowerW;\n\nconst autoReady =\n autoAllowed &&\n mediumPvNow &&\n pvCoversHouseNow &&\n netPvHeadroomW >= 0;\n\nconst greenReady =\n greenAllowed &&\n (\n pv10mW >= greenPowerW ||\n (pvPowerW >= greenPowerW && pvCoversHouseNow)\n );\n\nconst boostAllowed = earlyBoostStrongReady || earlyBoostMediumReady;\n\nreturn [{\n json: {\n ...root,\n meta: {\n ...(root.meta ?? {}),\n node: 'ecs_energy_model_and_early_boost_signals'\n },\n energyModel: {\n targetSoc,\n batteryCapacityKwh,\n greenEnergyKwh,\n autoEnergyKwh,\n boostEnergyKwh,\n energyNeededToReachTargetKwh,\n projectedGreenSoc,\n projectedAutoSoc,\n projectedBoostSoc,\n greenBudgetMarginKwh,\n autoBudgetMarginKwh,\n boostBudgetMarginKwh,\n forecastStrength,\n strongForecast,\n mediumForecast,\n strongPvNow,\n mediumPvNow,\n netPvHeadroomW,\n pvCoversHouseNow,\n pvStartedWell,\n acSafe,\n batteryNotDrainingHard,\n greenAllowed,\n autoAllowed,\n boostAllowedByBudget,\n boostAllowed,\n earlyBoostStrongReady,\n earlyBoostMediumReady,\n autoReady,\n greenReady\n }\n }\n}];" }, "id": "0becfc3a-3305-4a97-95b8-0fe1de446e37", "name": "ECS Energy Model & Early Boost Signals", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 608, -160 ] }, { "parameters": { "jsCode": "const root = $input.first()?.json ?? {};\nconst normalized = root.normalized ?? {};\nconst energyModel = root.energyModel ?? {};\n\nconst {\n advisorEnabled,\n hotWaterDemand,\n soc,\n pvPowerW,\n pvPowerAvg10mW,\n houseAcPowerW,\n acLoadsMaxSafeW\n} = normalized;\n\nconst {\n targetSoc,\n forecastStrength,\n netPvHeadroomW,\n pvCoversHouseNow,\n acSafe,\n greenAllowed,\n earlyBoostStrongReady,\n earlyBoostMediumReady,\n autoReady,\n greenReady,\n projectedGreenSoc,\n projectedAutoSoc,\n projectedBoostSoc,\n greenBudgetMarginKwh,\n autoBudgetMarginKwh,\n boostBudgetMarginKwh\n} = energyModel;\n\nlet recommendedMode = 'off';\nlet adviceColor = 'red';\nlet state = 'off_waiting_pv';\nlet reason = [];\n\nif (!advisorEnabled) {\n recommendedMode = 'off';\n adviceColor = 'red';\n state = 'advisor_disabled';\n reason.push('Advisor chauffe-eau désactivé');\n}\nelse if (!acSafe) {\n recommendedMode = 'off';\n adviceColor = 'red';\n state = 'off_ac_loads_too_high';\n reason.push(`Charges maison trop élevées pour ECS (${Math.round(houseAcPowerW)} W > seuil ${Math.round(acLoadsMaxSafeW)} W)`);\n}\nelse if (earlyBoostStrongReady) {\n recommendedMode = 'boost';\n adviceColor = 'green';\n state = 'boost_early_strong_forecast';\n reason.push('Boost tôt autorisé : forecast fort + SOC suffisant + PV net maison favorable');\n}\nelse if (earlyBoostMediumReady) {\n recommendedMode = 'boost';\n adviceColor = 'orange';\n state = 'boost_early_medium_forecast';\n reason.push('Boost tôt autorisé : forecast moyen + SOC élevé + surplus net maison suffisant');\n}\nelse if (autoReady) {\n recommendedMode = 'auto';\n adviceColor = 'green';\n state = 'auto_from_pv_net';\n reason.push('Mode auto recommandé : le PV couvre déjà la maison');\n}\nelse if (greenReady) {\n recommendedMode = 'green';\n adviceColor = 'green';\n state = 'green_waiting_pv_ramp';\n reason.push('Mode green recommandé : démarrage PV détecté');\n}\nelse {\n recommendedMode = 'off';\n adviceColor = 'red';\n if (!pvCoversHouseNow) {\n state = 'wait_for_pv_to_cover_house';\n reason.push('Attente : le PV ne couvre pas encore la maison');\n } else if (!greenAllowed) {\n state = 'off_budget_guard';\n reason.push('Attente : garde-fou budget / SOC fin de journée');\n } else {\n state = 'wait_for_pv_or_soc';\n reason.push('Attente d\\'un meilleur niveau PV / forecast / SOC');\n }\n}\n\nreason.push(`Demande ECS: ${hotWaterDemand}`);\nreason.push(`Forecast: ${forecastStrength}`);\nreason.push(`SOC: ${Math.round(soc)}%`);\nreason.push(`PV: ${Math.round(pvPowerW)} W | PV10: ${Math.round(pvPowerAvg10mW)} W`);\nreason.push(`Maison: ${Math.round(houseAcPowerW)} W`);\nreason.push(`Surplus net estimé: ${Math.round(netPvHeadroomW)} W`);\n\nif (recommendedMode === 'boost') {\n reason.push(`Boost budget: marge ${boostBudgetMarginKwh.toFixed(2)} kWh | SOC fin ${projectedBoostSoc.toFixed(1)}%`);\n} else if (recommendedMode === 'auto') {\n reason.push(`Auto budget: marge ${autoBudgetMarginKwh.toFixed(2)} kWh | SOC fin ${projectedAutoSoc.toFixed(1)}%`);\n} else if (recommendedMode === 'green') {\n reason.push(`Green budget: marge ${greenBudgetMarginKwh.toFixed(2)} kWh | SOC fin ${projectedGreenSoc.toFixed(1)}%`);\n} else {\n reason.push(`Target fin de jour: ${targetSoc.toFixed(1)}%`);\n}\n\nconst baseRecommendedMode = recommendedMode;\nconst baseAdviceColor = adviceColor;\nconst baseState = state;\n\nreturn [{\n json: {\n ...root,\n meta: {\n ...(root.meta ?? {}),\n node: 'ecs_base_advisor_decision'\n },\n baseDecision: {\n recommendedMode,\n adviceColor,\n state,\n reason,\n baseRecommendedMode,\n baseAdviceColor,\n baseState\n }\n }\n}];" }, "id": "7a862398-6aeb-4720-91ed-fd2eb2cc9d7e", "name": "ECS Base Advisor Decision", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 832, -160 ] }, { "parameters": { "jsCode": "function regimeRank(regime) {\n switch (regime) {\n case 'off': return 0;\n case 'hp_low': return 1;\n case 'resistive_mid': return 2;\n case 'boost_high': return 3;\n default: return -1;\n }\n}\n\nfunction allowedRankForMode(mode) {\n switch (mode) {\n case 'off': return 0;\n case 'green': return 1;\n case 'auto': return 2;\n case 'boost': return 3;\n default: return 0;\n }\n}\n\nfunction round1(v) {\n return Math.round(v * 10) / 10;\n}\n\nconst root = $input.first()?.json ?? {};\nconst now = root.now ?? {};\nconst nowMs = root.nowMs ?? null;\nconst normalized = root.normalized ?? {};\nconst observation = root.observation ?? {};\nconst energyModel = root.energyModel ?? {};\nconst baseDecision = root.baseDecision ?? {};\n\nlet {\n recommendedMode,\n adviceColor,\n state,\n reason,\n baseRecommendedMode,\n baseAdviceColor,\n baseState\n} = baseDecision;\n\nreason = Array.isArray(reason) ? [...reason] : [];\n\nconst {\n advisorEnabled,\n soc,\n batteryCurrentA,\n pvPowerAvg10mW,\n houseAcPowerW,\n todayRemainingKwh,\n tomorrowKwh,\n baseLoadRemainingKwh,\n flexibleSafetyMarginKwh,\n acLoadsMaxSafeW,\n hotWaterDemand,\n gridIsOn,\n acInAvailable,\n gridAvailable\n} = normalized;\n\nconst {\n evcsPriorityActive,\n energyPriorityReason,\n waterHeaterSwitchOn,\n observedPowerW,\n observedRegime,\n mismatchSinceAt,\n mismatchSinceMsPrev,\n forcedOffByAdvisorPrev,\n forcedOffReasonPrev,\n forcedOffAtPrev,\n restoreSurplusW,\n modeMismatchDelayMin,\n sampleDurationMin,\n energyDeltaKwh,\n sampleIsUsable\n} = observation;\n\nconst {\n targetSoc,\n energyNeededToReachTargetKwh,\n greenEnergyKwh,\n autoEnergyKwh,\n boostEnergyKwh,\n projectedGreenSoc,\n projectedAutoSoc,\n projectedBoostSoc,\n greenBudgetMarginKwh,\n autoBudgetMarginKwh,\n boostBudgetMarginKwh,\n forecastStrength,\n netPvHeadroomW,\n pvCoversHouseNow,\n pvStartedWell,\n greenAllowed,\n autoAllowed,\n boostAllowed,\n batteryNotDrainingHard\n} = energyModel;\n\nif (advisorEnabled && evcsPriorityActive) {\n if (recommendedMode === 'boost' || recommendedMode === 'auto') {\n if (greenAllowed && batteryNotDrainingHard) {\n recommendedMode = 'green';\n adviceColor = 'orange';\n state = 'evcs_priority_green_cap';\n reason.push(`Priorité EVCS active : chauffe-eau plafonné à GREEN (${energyPriorityReason || 'raison non précisée'})`);\n } else {\n recommendedMode = 'off';\n adviceColor = 'red';\n state = 'evcs_priority_off_cap';\n reason.push(`Priorité EVCS active : chauffe-eau déconseillé (${energyPriorityReason || 'raison non précisée'})`);\n }\n } else if (recommendedMode === 'green' && (!greenAllowed || !batteryNotDrainingHard)) {\n recommendedMode = 'off';\n adviceColor = 'red';\n state = 'evcs_priority_green_blocked';\n reason.push(`Priorité EVCS active : GREEN devient lui-même trop coûteux (${energyPriorityReason || 'raison non précisée'})`);\n }\n}\n\nconst selectedLoadKwh =\n recommendedMode === 'green' ? greenEnergyKwh :\n recommendedMode === 'auto' ? autoEnergyKwh :\n recommendedMode === 'boost' ? boostEnergyKwh :\n 0;\n\nconst selectedProjectedSoc =\n recommendedMode === 'green' ? projectedGreenSoc :\n recommendedMode === 'auto' ? projectedAutoSoc :\n recommendedMode === 'boost' ? projectedBoostSoc :\n soc;\n\nconst selectedBudgetMarginKwh =\n recommendedMode === 'green' ? greenBudgetMarginKwh :\n recommendedMode === 'auto' ? autoBudgetMarginKwh :\n recommendedMode === 'boost' ? boostBudgetMarginKwh :\n todayRemainingKwh - baseLoadRemainingKwh - flexibleSafetyMarginKwh - energyNeededToReachTargetKwh;\n\nconst legacyAdviceOk = recommendedMode !== 'off';\n\nconst observedRank = regimeRank(observedRegime);\nconst allowedRank = allowedRankForMode(recommendedMode);\n\nconst mismatchActive =\n waterHeaterSwitchOn &&\n observedRank >= 0 &&\n allowedRank >= 0 &&\n observedRank > allowedRank;\n\nlet mismatchSeverity = 'none';\nif (mismatchActive) {\n if (recommendedMode === 'off') {\n mismatchSeverity = 'critical';\n } else if (observedRank - allowedRank >= 2) {\n mismatchSeverity = 'high';\n } else {\n mismatchSeverity = 'medium';\n }\n}\n\nconst mismatchSinceMsEffective = mismatchActive ? (mismatchSinceMsPrev ?? nowMs) : null;\nconst mismatchSinceAtEffective = mismatchActive ? (mismatchSinceMsPrev ? mismatchSinceAt : now.stamp) : '';\nconst mismatchDurationMin = mismatchActive && mismatchSinceMsEffective !== null ? Math.max(0, (nowMs - mismatchSinceMsEffective) / 60000) : 0;\n\nlet pendingUserAction = '';\nif (mismatchActive) {\n if (recommendedMode === 'off') {\n pendingUserAction = evcsPriorityActive\n ? 'Priorité EVCS : coupe temporairement le chauffe-eau ou laisse-le hors tension'\n : 'Le chauffe-eau consomme alors qu\\'il est déconseillé : coupe-le ou attends une meilleure fenêtre';\n } else if (recommendedMode === 'green') {\n pendingUserAction = observedRegime === 'boost_high'\n ? 'Passe le chauffe-eau en GREEN si possible, il semble en régime BOOST/résistance forte'\n : 'Passe le chauffe-eau en GREEN si possible, il semble plus gourmand que prévu';\n } else if (recommendedMode === 'auto') {\n pendingUserAction = 'Le chauffe-eau semble trop gourmand pour AUTO : repasse-le en AUTO modéré ou GREEN si possible';\n }\n}\n\nconst firstMismatchRun = mismatchActive && (mismatchSinceMsPrev === null || mismatchDurationMin < 1);\n\nconst realConflictNow =\n evcsPriorityActive &&\n (\n batteryCurrentA < -1 ||\n pvPowerAvg10mW < restoreSurplusW ||\n houseAcPowerW > acLoadsMaxSafeW ||\n recommendedMode === 'off' ||\n observedRegime === 'boost_high' ||\n (recommendedMode === 'green' && observedRegime === 'resistive_mid')\n );\n\nconst forceOffNow =\n advisorEnabled &&\n waterHeaterSwitchOn &&\n !forcedOffByAdvisorPrev &&\n mismatchActive &&\n mismatchDurationMin >= modeMismatchDelayMin &&\n realConflictNow;\n\nconst restoreEnergyOk =\n pvPowerAvg10mW >= restoreSurplusW &&\n batteryCurrentA >= -1 &&\n houseAcPowerW <= acLoadsMaxSafeW;\n\nconst restoreNow =\n advisorEnabled &&\n forcedOffByAdvisorPrev &&\n !waterHeaterSwitchOn &&\n (\n (!evcsPriorityActive && recommendedMode !== 'off') ||\n restoreEnergyOk\n );\n\nlet forcedOffByAdvisor = forcedOffByAdvisorPrev;\nlet forcedOffReason = forcedOffReasonPrev;\nlet forcedOffAt = forcedOffAtPrev;\nlet protectionState = 'none';\nlet powerSwitchAction = 'none';\nlet powerSwitchDesiredOn = waterHeaterSwitchOn;\n\nif (forceOffNow) {\n powerSwitchAction = 'turn_off';\n powerSwitchDesiredOn = false;\n forcedOffByAdvisor = true;\n forcedOffReason = `Coupure temporaire ECS: priorité EVCS + régime ${observedRegime} trop gourmand`;\n forcedOffAt = now.stamp;\n protectionState = 'forced_off_now_evcs_priority';\n state = 'forced_off_now_evcs_priority';\n adviceColor = 'red';\n reason.push(forcedOffReason);\n}\nelse if (restoreNow) {\n powerSwitchAction = 'turn_on';\n powerSwitchDesiredOn = true;\n forcedOffByAdvisor = false;\n forcedOffReason = '';\n protectionState = 'restored_after_evcs_priority';\n state = 'restored_after_evcs_priority';\n reason.push('Remise sous tension ECS : conflit EVCS terminé ou surplus redevenu suffisant');\n}\nelse if (forcedOffByAdvisorPrev && !waterHeaterSwitchOn) {\n protectionState = 'forced_off_wait_restore';\n state = 'forced_off_wait_restore';\n reason.push(`ECS temporairement coupé par l'advisor (${forcedOffReasonPrev || 'raison non précisée'})`);\n}\nelse if (mismatchActive && evcsPriorityActive) {\n protectionState = 'watch_mismatch_evcs_priority';\n state = 'watch_mismatch_evcs_priority';\n reason.push(`Écart de régime ECS sous priorité EVCS depuis ${round1(mismatchDurationMin)} min`);\n}\n\nif (!forceOffNow && !restoreNow && forcedOffByAdvisorPrev && waterHeaterSwitchOn) {\n forcedOffByAdvisor = false;\n forcedOffReason = '';\n}\n\nreturn [{\n json: {\n ...root,\n meta: {\n ...(root.meta ?? {}),\n node: 'ecs_final_arbitration_and_protection'\n },\n finalDecision: {\n recommendedMode,\n adviceColor,\n state,\n reason,\n baseRecommendedMode,\n baseAdviceColor,\n baseState,\n selectedLoadKwh,\n selectedProjectedSoc,\n selectedBudgetMarginKwh,\n legacyAdviceOk,\n mismatchActive,\n mismatchSeverity,\n mismatchSinceAtEffective,\n mismatchSinceMsEffective,\n mismatchDurationMin,\n pendingUserAction,\n firstMismatchRun,\n realConflictNow,\n forceOffNow,\n restoreEnergyOk,\n restoreNow,\n forcedOffByAdvisor,\n forcedOffReason,\n forcedOffAt,\n protectionState,\n powerSwitchAction,\n powerSwitchDesiredOn\n }\n }\n}];" }, "id": "994b3242-616d-46e7-83ed-d236a117d15c", "name": "ECS Final Arbitration & Protection", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1056, -160 ] }, { "parameters": { "jsCode": "function round1(v) {\n return Math.round(v * 10) / 10;\n}\n\nfunction round2(v) {\n return Math.round(v * 100) / 100;\n}\n\nfunction safeText(v, max = 255) {\n return (v ?? '').toString().slice(0, max);\n}\n\nfunction boolService(flag) {\n return flag ? 'turn_on' : 'turn_off';\n}\n\nfunction getTzOffsetMs(utcTs, timeZone = 'Europe/Paris') {\n const dtf = new Intl.DateTimeFormat('en-US', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false,\n });\n\n const parts = Object.fromEntries(\n dtf.formatToParts(new Date(utcTs))\n .filter(p => p.type !== 'literal')\n .map(p => [p.type, p.value])\n );\n\n const asIfUtc = Date.UTC(\n Number(parts.year),\n Number(parts.month) - 1,\n Number(parts.day),\n Number(parts.hour) === 24 ? 0 : Number(parts.hour),\n Number(parts.minute),\n Number(parts.second)\n );\n\n const d = new Date(utcTs);\n const actualUtc = Date.UTC(\n d.getUTCFullYear(),\n d.getUTCMonth(),\n d.getUTCDate(),\n d.getUTCHours(),\n d.getUTCMinutes(),\n d.getUTCSeconds()\n );\n\n return asIfUtc - actualUtc;\n}\n\nfunction parseParisStampToMs(s) {\n const text = (s ?? '').toString().trim();\n const m = text.match(/^(\\\\d{4})-(\\\\d{2})-(\\\\d{2}) (\\\\d{2}):(\\\\d{2}):(\\\\d{2})$/);\n if (!m) return null;\n\n const y = Number(m[1]);\n const mo = Number(m[2]);\n const d = Number(m[3]);\n const h = Number(m[4]);\n const mi = Number(m[5]);\n const se = Number(m[6]);\n\n if (![y, mo, d, h, mi, se].every(Number.isFinite)) return null;\n\n const guessUtc = Date.UTC(y, mo - 1, d, h, mi, se);\n const off1 = getTzOffsetMs(guessUtc, 'Europe/Paris');\n let ts = guessUtc - off1;\n const off2 = getTzOffsetMs(ts, 'Europe/Paris');\n\n if (off2 !== off1) ts = guessUtc - off2;\n return ts;\n}\n\nconst root = $input.first()?.json ?? {};\nconst cfg = root.cfg ?? {};\nconst now = root.now ?? {};\nconst input = root.input ?? {};\nconst normalized = root.normalized ?? {};\nconst observation = root.observation ?? {};\nconst energyModel = root.energyModel ?? {};\nconst finalDecision = root.finalDecision ?? {};\n\nconst {\n soc,\n batteryCurrentA,\n pvPowerW,\n pvPowerAvg10mW,\n houseAcPowerW,\n gridPowerW,\n gridIsOn,\n acInAvailable,\n gridAvailable,\n todayRemainingKwh,\n tomorrowKwh,\n advisorEnabled,\n notificationsEnabled,\n hotWaterDemand,\n greenPowerW,\n autoPowerW,\n boostPowerW,\n strongForecastKwh,\n mediumForecastKwh,\n strongPvNowW,\n mediumPvNowW,\n boostMinSocStrongForecastPct,\n boostMinSocMediumForecastPct,\n endOfDaySocGuard,\n endOfDaySocTarget,\n baseLoadRemainingKwh,\n flexibleSafetyMarginKwh,\n acLoadsMaxSafeW,\n lastSignature\n} = normalized;\n\nconst {\n evcsPriorityActive,\n energyPriorityMode,\n energyPriorityReason,\n evcsPriorityUntilAt,\n waterHeaterSwitchOn,\n waterHeaterEnergyTotalKwh,\n restoreSurplusW,\n modeMismatchDelayMin,\n sampleDurationMin,\n energyDeltaKwh,\n sampleIsUsable,\n observedPowerW,\n observedRegime\n} = observation;\n\nconst {\n targetSoc,\n batteryCapacityKwh,\n greenEnergyKwh,\n autoEnergyKwh,\n boostEnergyKwh,\n energyNeededToReachTargetKwh,\n projectedGreenSoc,\n projectedAutoSoc,\n projectedBoostSoc,\n greenBudgetMarginKwh,\n autoBudgetMarginKwh,\n boostBudgetMarginKwh,\n forecastStrength,\n strongForecast,\n mediumForecast,\n strongPvNow,\n mediumPvNow,\n netPvHeadroomW,\n pvCoversHouseNow,\n pvStartedWell,\n acSafe,\n batteryNotDrainingHard,\n greenAllowed,\n autoAllowed,\n boostAllowedByBudget,\n boostAllowed,\n earlyBoostStrongReady,\n earlyBoostMediumReady,\n autoReady,\n greenReady\n} = energyModel;\n\nlet {\n recommendedMode,\n adviceColor,\n state,\n reason,\n baseRecommendedMode,\n baseAdviceColor,\n baseState,\n selectedLoadKwh,\n selectedProjectedSoc,\n selectedBudgetMarginKwh,\n legacyAdviceOk,\n mismatchActive,\n mismatchSeverity,\n mismatchSinceAtEffective,\n mismatchSinceMsEffective,\n mismatchDurationMin,\n pendingUserAction,\n firstMismatchRun,\n realConflictNow,\n forceOffNow,\n restoreEnergyOk,\n restoreNow,\n forcedOffByAdvisor,\n forcedOffReason,\n forcedOffAt,\n protectionState,\n powerSwitchAction,\n powerSwitchDesiredOn\n} = finalDecision;\n\nreason = Array.isArray(reason) ? [...reason] : [];\n\nconst forcedOffAtSafe = forcedOffAt && parseParisStampToMs(forcedOffAt) !== null ? forcedOffAt : '';\nconst forcedOffReasonSafe = forcedOffByAdvisor ? safeText(forcedOffReason, 255) : '';\nconst pendingUserActionSafe = safeText(pendingUserAction, 255);\n\nif (reason.length === 0) {\n if (recommendedMode === 'boost') reason.push('Boost recommandé');\n else if (recommendedMode === 'auto') reason.push('Mode auto recommandé');\n else if (recommendedMode === 'green') reason.push('Mode green recommandé');\n else reason.push('Chauffe-eau déconseillé pour le moment');\n}\n\nreason.push(`Demande ECS: ${hotWaterDemand}`);\nreason.push(`Conseil final: ${recommendedMode}`);\nreason.push(`Conseil initial: ${baseRecommendedMode}`);\nreason.push(`Couleur conseil: ${adviceColor}`);\nreason.push(`Forecast du jour: ${round1(todayRemainingKwh)} kWh`);\nreason.push(`Production demain: ${round1(tomorrowKwh)} kWh`);\nreason.push(`Classe forecast: ${forecastStrength}`);\nreason.push(`PV actuel: ${Math.round(pvPowerW)} W | PV10: ${Math.round(pvPowerAvg10mW)} W`);\nreason.push(`Charges AC maison: ${Math.round(houseAcPowerW)} W`);\nreason.push(`Surplus net estimé: ${Math.round(netPvHeadroomW)} W`);\nreason.push(`PV couvre maison: ${pvCoversHouseNow ? 'oui' : 'non'} | PV bien démarré: ${pvStartedWell ? 'oui' : 'non'}`);\nreason.push(`Batterie: SOC ${round1(soc)}% | courant ${round1(batteryCurrentA)} A`);\nreason.push(`Réseau: cmd=${gridIsOn ? 'ON' : 'OFF'} | acin=${acInAvailable ? 'OK' : 'KO'} | dispo=${gridAvailable ? 'oui' : 'non'}`);\nreason.push(`Target fin de jour: ${round1(targetSoc)}%`);\nreason.push(`Base load restante: ${round1(baseLoadRemainingKwh)} kWh`);\nreason.push(`Marge sécurité: ${round1(flexibleSafetyMarginKwh)} kWh`);\nreason.push(`Green ${round1(greenEnergyKwh)}kWh → SOC fin ${round1(projectedGreenSoc)}% | marge ${round1(greenBudgetMarginKwh)}kWh`);\nreason.push(`Auto ${round1(autoEnergyKwh)}kWh → SOC fin ${round1(projectedAutoSoc)}% | marge ${round1(autoBudgetMarginKwh)}kWh`);\nreason.push(`Boost ${round1(boostEnergyKwh)}kWh → SOC fin ${round1(projectedBoostSoc)}% | marge ${round1(boostBudgetMarginKwh)}kWh`);\nreason.push(`Régime observé: ${observedRegime} | puissance ≈ ${Math.round(observedPowerW)} W | delta ${sampleIsUsable ? round2(energyDeltaKwh) : 'n/a'} kWh/${sampleIsUsable ? round1(sampleDurationMin) : 'n/a'} min`);\nreason.push(`Prio EVCS: ${evcsPriorityActive ? 'ON' : 'OFF'}${energyPriorityReason ? ` | ${energyPriorityReason}` : ''}`);\nreason.push(`Mismatch: ${mismatchActive ? 'oui' : 'non'} | sévérité=${mismatchSeverity} | durée=${round1(mismatchDurationMin)} min`);\nreason.push(`Protection ECS: ${protectionState}`);\nif (pendingUserActionSafe) reason.push(`Action attendue: ${pendingUserActionSafe}`);\n\nconst shortReason = reason.join(' | ').slice(0, 255);\n\nconst signature = [\n now.date,\n `d=${hotWaterDemand}`,\n `m=${recommendedMode}`,\n `base=${baseRecommendedMode}`,\n `c=${adviceColor}`,\n `fs=${strongForecast ? '1' : '0'}`,\n `fm=${mediumForecast ? '1' : '0'}`,\n `pb=${pvStartedWell ? '1' : '0'}`,\n `soc=${round1(soc)}`,\n `pv=${Math.round(pvPowerW)}`,\n `pv10=${Math.round(pvPowerAvg10mW)}`,\n `npv=${Math.round(netPvHeadroomW)}`,\n `obs=${observedRegime}`,\n `prio=${evcsPriorityActive ? '1' : '0'}`,\n `cut=${forcedOffByAdvisor ? '1' : '0'}`\n].join('|');\n\nconst signatureChanged = signature !== lastSignature;\n\nlet notifyWanted = false;\nlet notifyTitle = 'Water Heater Advisor';\nlet notifyMessage = '';\n\nif (notificationsEnabled) {\n if (forceOffNow) {\n notifyWanted = true;\n notifyTitle = 'ECS coupé temporairement';\n notifyMessage = forcedOffReasonSafe || 'Le chauffe-eau a été coupé temporairement';\n } else if (restoreNow) {\n notifyWanted = true;\n notifyTitle = 'ECS remis sous tension';\n notifyMessage = 'Le chauffe-eau est réalimenté car la priorité EVCS est terminée ou le surplus est redevenu suffisant.';\n } else if (firstMismatchRun && pendingUserActionSafe) {\n notifyWanted = true;\n notifyTitle = 'Action utilisateur ECS conseillée';\n notifyMessage = pendingUserActionSafe;\n } else if (signatureChanged) {\n notifyWanted = true;\n notifyTitle = `Water Heater Advisor: ${recommendedMode.toUpperCase()} / ${adviceColor.toUpperCase()}`;\n notifyMessage = `Demande=${hotWaterDemand} | régime=${observedRegime} | SOC fin estimé=${round1(selectedProjectedSoc)}% | marge=${round1(selectedBudgetMarginKwh)} kWh`;\n }\n}\nconst BUDGET_MARGIN_MIN = -50;\nconst BUDGET_MARGIN_MAX = 50;\nconst result = {\n timestamp_paris: now.stamp,\n inputs: {\n soc_percent: soc,\n battery_current_a: batteryCurrentA,\n pv_power_w: pvPowerW,\n pv_power_10m_avg_w: pvPowerAvg10mW,\n house_ac_power_w: houseAcPowerW,\n grid_power_w: gridPowerW,\n grid_state: gridIsOn ? 'on' : 'off',\n victron_acin1_available: acInAvailable ? 1 : 0,\n today_remaining_kwh: round2(todayRemainingKwh),\n tomorrow_kwh: round2(tomorrowKwh),\n advisor_enabled: advisorEnabled,\n notifications_enabled: notificationsEnabled,\n hot_water_demand: hotWaterDemand,\n green_power_w: greenPowerW,\n auto_power_w: autoPowerW,\n boost_power_w: boostPowerW,\n strong_forecast_kwh: strongForecastKwh,\n medium_forecast_kwh: mediumForecastKwh,\n strong_pv_now_w: strongPvNowW,\n medium_pv_now_w: mediumPvNowW,\n boost_min_soc_strong_forecast_pct: boostMinSocStrongForecastPct,\n boost_min_soc_medium_forecast_pct: boostMinSocMediumForecastPct,\n end_of_day_soc_guard: endOfDaySocGuard,\n end_of_day_soc_target: endOfDaySocTarget,\n base_load_remaining_kwh: baseLoadRemainingKwh,\n flexible_safety_margin_kwh: flexibleSafetyMarginKwh,\n ac_loads_max_safe_w: acLoadsMaxSafeW,\n water_heater_switch: waterHeaterSwitchOn,\n water_heater_energy_total_kwh: round2(waterHeaterEnergyTotalKwh),\n last_signature: lastSignature || null,\n evcs_priority_active: evcsPriorityActive,\n energy_priority_mode: energyPriorityMode,\n energy_priority_reason: energyPriorityReason || null,\n evcs_priority_until: evcsPriorityUntilAt || null\n },\n computed: {\n forecast_strength: forecastStrength,\n strong_forecast: strongForecast,\n medium_forecast: mediumForecast,\n strong_pv_now: strongPvNow,\n medium_pv_now: mediumPvNow,\n net_pv_headroom_w: Math.round(netPvHeadroomW),\n pv_covers_house_now: pvCoversHouseNow,\n pv_started_well: pvStartedWell,\n battery_usable_capacity_kwh_internal: batteryCapacityKwh,\n energy_needed_to_reach_target_kwh: round2(energyNeededToReachTargetKwh),\n green_energy_kwh: round2(greenEnergyKwh),\n auto_energy_kwh: round2(autoEnergyKwh),\n boost_energy_kwh: round2(boostEnergyKwh),\n projected_green_soc: round1(projectedGreenSoc),\n projected_auto_soc: round1(projectedAutoSoc),\n projected_boost_soc: round1(projectedBoostSoc),\n green_budget_margin_kwh: round2(greenBudgetMarginKwh),\n auto_budget_margin_kwh: round2(autoBudgetMarginKwh),\n boost_budget_margin_kwh: round2(boostBudgetMarginKwh),\n ac_safe: acSafe,\n battery_not_draining_hard: batteryNotDrainingHard,\n green_allowed: greenAllowed,\n auto_allowed: autoAllowed,\n boost_allowed_by_budget: boostAllowedByBudget,\n boost_allowed: boostAllowed,\n early_boost_strong_ready: earlyBoostStrongReady,\n early_boost_medium_ready: earlyBoostMediumReady,\n auto_ready: autoReady,\n green_ready: greenReady,\n base_recommended_mode: baseRecommendedMode,\n base_advice_color: baseAdviceColor,\n base_state: baseState,\n observed_power_w: Math.round(observedPowerW),\n observed_regime: observedRegime,\n sample_duration_min: sampleIsUsable ? round1(sampleDurationMin) : null,\n energy_delta_kwh: sampleIsUsable ? round2(energyDeltaKwh) : null,\n mismatch_active: mismatchActive,\n mismatch_severity: mismatchSeverity,\n mismatch_duration_min: round1(mismatchDurationMin),\n evcs_priority_active: evcsPriorityActive,\n protection_state: protectionState,\n real_conflict_now: realConflictNow,\n restore_energy_ok: restoreEnergyOk,\n restore_surplus_w: restoreSurplusW,\n mode_mismatch_delay_min: modeMismatchDelayMin\n },\n decision: {\n recommended_mode: recommendedMode,\n advice_color: adviceColor,\n state,\n legacy_advice_ok: legacyAdviceOk,\n selected_load_kwh: round2(selectedLoadKwh),\n projected_end_of_day_soc: round1(selectedProjectedSoc),\n budget_margin_kwh: round2(selectedBudgetMarginKwh),\n observed_power_w: Math.round(observedPowerW),\n observed_regime: observedRegime,\n mismatch_active: mismatchActive,\n mismatch_severity: mismatchSeverity,\n mismatch_duration_min: round1(mismatchDurationMin),\n pending_user_action: pendingUserActionSafe,\n power_switch_action: powerSwitchAction,\n power_switch_desired_on: powerSwitchDesiredOn,\n force_off_now: forceOffNow,\n restore_now: restoreNow,\n forced_off_by_advisor: forcedOffByAdvisor,\n forced_off_reason: forcedOffReasonSafe,\n forced_off_at: forcedOffByAdvisor ? forcedOffAtSafe || null : null,\n signature,\n signature_changed: signatureChanged,\n should_notify: notifyWanted,\n reason,\n short_reason: shortReason\n },\n ha_service_calls: {\n helper_recommended_mode: {\n domain: 'input_select',\n service: 'select_option',\n data: {\n entity_id: 'input_select.victron_water_heater_recommended_mode',\n option: recommendedMode\n }\n },\n helper_advice_color: {\n domain: 'input_select',\n service: 'select_option',\n data: {\n entity_id: 'input_select.victron_water_heater_advice_color',\n option: adviceColor\n }\n },\n helper_state: {\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_advice_state',\n value: state\n }\n },\n helper_reason: {\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_advice_reason',\n value: shortReason || 'Aucune raison'\n }\n },\n helper_signature: {\n execute: signatureChanged,\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_advice_last_signature',\n value: signature\n }\n },\n helper_projected_soc: {\n domain: 'input_number',\n service: 'set_value',\n data: {\n entity_id: 'input_number.victron_water_heater_projected_end_of_day_soc',\n value: round1(selectedProjectedSoc)\n }\n },\nhelper_budget_margin: {\n domain: 'input_number',\n service: 'set_value',\n data: {\n entity_id: 'input_number.victron_water_heater_budget_margin_kwh',\n value: Math.max(BUDGET_MARGIN_MIN, Math.min(BUDGET_MARGIN_MAX, round2(selectedBudgetMarginKwh)))\n }\n},\n helper_load_kwh: {\n domain: 'input_number',\n service: 'set_value',\n data: {\n entity_id: 'input_number.victron_load_water_heater_kwh',\n value: round2(selectedLoadKwh)\n }\n },\n helper_legacy_advice_ok: {\n domain: 'input_boolean',\n service: boolService(legacyAdviceOk),\n data: {\n entity_id: 'input_boolean.victron_advice_water_heater_ok'\n }\n },\n helper_green_allowed: {\n domain: 'input_boolean',\n service: boolService(greenAllowed),\n data: {\n entity_id: 'input_boolean.victron_water_heater_green_allowed'\n }\n },\n helper_auto_allowed: {\n domain: 'input_boolean',\n service: boolService(autoAllowed),\n data: {\n entity_id: 'input_boolean.victron_water_heater_auto_allowed'\n }\n },\n helper_boost_allowed: {\n domain: 'input_boolean',\n service: boolService(boostAllowed),\n data: {\n entity_id: 'input_boolean.victron_water_heater_boost_allowed'\n }\n },\n helper_observed_power: {\n domain: 'input_number',\n service: 'set_value',\n data: {\n entity_id: 'input_number.victron_water_heater_observed_power_w',\n value: Math.round(observedPowerW)\n }\n },\n helper_observed_regime: {\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_observed_regime',\n value: observedRegime\n }\n },\n helper_pending_user_action: {\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_pending_user_action',\n value: pendingUserActionSafe\n }\n },\n helper_mismatch_since: {\n execute: mismatchActive && !!mismatchSinceAtEffective,\n domain: 'input_datetime',\n service: 'set_datetime',\n data: {\n entity_id: 'input_datetime.victron_water_heater_mode_mismatch_since',\n datetime: mismatchSinceAtEffective\n }\n },\n helper_energy_prev_kwh: {\n domain: 'input_number',\n service: 'set_value',\n data: {\n entity_id: 'input_number.victron_water_heater_energy_total_prev_kwh',\n value: round2(waterHeaterEnergyTotalKwh)\n }\n },\n helper_energy_prev_at: {\n domain: 'input_datetime',\n service: 'set_datetime',\n data: {\n entity_id: 'input_datetime.victron_water_heater_energy_prev_at',\n datetime: now.stamp\n }\n },\n helper_forced_off_by_advisor: {\n domain: 'input_boolean',\n service: boolService(forcedOffByAdvisor),\n data: {\n entity_id: 'input_boolean.victron_water_heater_forced_off_by_advisor'\n }\n },\n helper_forced_off_reason: {\n domain: 'input_text',\n service: 'set_value',\n data: {\n entity_id: 'input_text.victron_water_heater_forced_off_reason',\n value: forcedOffReasonSafe\n }\n },\n helper_forced_off_at: {\n execute: forceOffNow && !!forcedOffAtSafe,\n domain: 'input_datetime',\n service: 'set_datetime',\n data: {\n entity_id: 'input_datetime.victron_water_heater_forced_off_at',\n datetime: forcedOffAtSafe\n }\n },\n water_heater_power_switch: {\n execute: powerSwitchAction !== 'none',\n domain: 'switch',\n service: powerSwitchDesiredOn ? 'turn_on' : 'turn_off',\n data: {\n entity_id: 'switch.tt_chauffe_eau_pleumeur_switch'\n }\n },\n logbook: {\n execute: signatureChanged || forceOffNow || restoreNow,\n domain: 'logbook',\n service: 'log',\n data: {\n name: 'Water Heater Advisor',\n message: `${recommendedMode}/${adviceColor} | regime=${observedRegime} | prioEVCS=${evcsPriorityActive ? 'on' : 'off'} | cut=${forcedOffByAdvisor ? 'on' : 'off'} | ${shortReason}`,\n entity_id: 'switch.tt_chauffe_eau_pleumeur_switch'\n }\n },\n mobile_notification: {\n execute: notifyWanted,\n domain: cfg.mobileNotifyDomain,\n service: cfg.mobileNotifyService,\n data: {\n title: notifyTitle,\n message: notifyMessage,\n data: {\n push: {\n 'interruption-level': 'time-sensitive',\n sound: { name: 'default' }\n },\n ttl: 0,\n priority: 'high'\n }\n }\n }\n }\n};\n\nreturn [{ json: result }];" }, "id": "481de0f8-22a8-4aae-b47d-493098383c6c", "name": "ECS Output Builder", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1280, -160 ] }, { "parameters": { "method": "POST", "url": "={{ 'http://10.10.10.17:8123/api/services/' + $json.domain + '/' + $json.service }}\n", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Authorization", "value": "={{ 'Bearer ' + ($env.HA_TOKEN || '') }}" }, { "name": "Content-Type", "value": "application/json" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ $json.data }}", "options": { "response": { "response": { "responseFormat": "json" } }, "timeout": 10000 } }, "id": "89d75698-da63-4598-a35b-86f0ade8a11c", "name": "Execute HA Service", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 1728, -160 ], "continueOnFail": true }, { "parameters": { "rule": { "interval": [ { "field": "minutes" } ] } }, "id": "edabb941-0e10-429b-bf0e-9af229a08d28", "name": "Schedule Trigger", "type": "n8n-nodes-base.scheduleTrigger", "typeVersion": 1.2, "position": [ -288, -160 ] }, { "parameters": { "method": "POST", "url": "=http://10.10.10.17:8123/api/template\n", "authentication": "genericCredentialType", "genericAuthType": "httpBearerAuth", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Content-Type", "value": "application/json" }, { "name": "Accept", "value": "text/plain" } ] }, "sendBody": true, "bodyParameters": { "parameters": [ { "name": "template", "value": "{{ {\n \"soc_percent\": states(\"sensor.victron_battery_soc\"),\n \"battery_current_a\": states(\"sensor.victron_battery_current\"),\n \"pv_power_w\": states(\"sensor.victron_pv_power_system\"),\n \"pv_power_10m_avg_w\": states(\"sensor.victron_pv_power_10m_avg\"),\n \"house_ac_power_w\": states(\"sensor.victron_consumption_power_l1\"),\n \"grid_power_w\": states(\"sensor.victron_grid_power_l1\"),\n \"grid_state\": states(\"switch.edf_general_ok_switch\"),\n \"victron_acin1_available\": states(\"sensor.victron_ac_in1_available\"),\n\n \"today_remaining_kwh\": states(\"sensor.energy_production_today_remaining\"),\n \"tomorrow_kwh\": states(\"sensor.energy_production_tomorrow\"),\n\n \"advisor_enabled\": states(\"input_boolean.victron_water_heater_advisor_enabled\"),\n \"notifications_enabled\": states(\"input_boolean.victron_water_heater_notifications\"),\n\n \"hot_water_demand\": states(\"input_select.victron_water_heater_hot_water_demand\"),\n \"morning_boost_priority_enabled\": states(\"input_boolean.victron_water_heater_morning_boost_priority_enabled\"),\n \"morning_boost_latest_time\": states(\"input_datetime.victron_water_heater_morning_boost_latest_time\"),\n \"late_red_time\": states(\"input_datetime.victron_water_heater_late_red_time\"),\n\n \"green_power_w\": states(\"input_number.victron_water_heater_green_power_w\"),\n \"auto_power_w\": states(\"input_number.victron_water_heater_auto_power_w\"),\n \"boost_power_w\": states(\"input_number.victron_water_heater_boost_power_w\"),\n\n \"strong_forecast_kwh\": states(\"input_number.victron_water_heater_strong_forecast_kwh\"),\n \"medium_forecast_kwh\": states(\"input_number.victron_water_heater_medium_forecast_kwh\"),\n \"strong_pv_now_w\": states(\"input_number.victron_water_heater_strong_pv_now_w\"),\n \"medium_pv_now_w\": states(\"input_number.victron_water_heater_medium_pv_now_w\"),\n\n \"morning_boost_min_soc_strong_day\": states(\"input_number.victron_water_heater_morning_boost_min_soc_strong_day\"),\n \"boost_min_soc_medium_day\": states(\"input_number.victron_water_heater_boost_min_soc_medium_day\"),\n \"end_of_day_soc_guard\": states(\"input_number.victron_water_heater_end_of_day_soc_guard\"),\n\n \"end_of_day_soc_target\": states(\"input_number.victron_end_of_day_soc_target\"),\n \"base_load_remaining_kwh\": states(\"input_number.victron_base_load_remaining_kwh\"),\n \"flexible_safety_margin_kwh\": states(\"input_number.victron_flexible_safety_margin_kwh\"),\n \"ac_loads_max_safe_w\": states(\"input_number.victron_ac_loads_max_safe_w\"),\n\n \"day_start_time\": states(\"input_datetime.victron_flexible_day_start_time\"),\n \"day_stop_time\": states(\"input_datetime.victron_flexible_day_stop_time\"),\n\n \"last_signature\": states(\"input_text.victron_water_heater_advice_last_signature\"),\n\n \"evcs_priority_active\": states(\"input_boolean.victron_evcs_priority_active\"),\n \"energy_priority_mode\": states(\"input_select.victron_energy_priority_mode\"),\n \"energy_priority_reason\": states(\"input_text.victron_energy_priority_reason\"),\n \"evcs_priority_until\": states(\"input_datetime.victron_evcs_priority_until\"),\n\n \"water_heater_switch\": states(\"switch.tt_chauffe_eau_pleumeur_switch\"),\n \"water_heater_energy_total_kwh\": states(\"sensor.tt_chauffe_eau_pleumeur_energie_totale\"),\n\n \"energy_total_prev_kwh\": states(\"input_number.victron_water_heater_energy_total_prev_kwh\"),\n \"energy_prev_at\": states(\"input_datetime.victron_water_heater_energy_prev_at\"),\n\n \"observed_regime_helper\": states(\"input_text.victron_water_heater_observed_regime\"),\n \"observed_power_helper_w\": states(\"input_number.victron_water_heater_observed_power_w\"),\n\n \"mode_mismatch_since\": states(\"input_datetime.victron_water_heater_mode_mismatch_since\"),\n\n \"forced_off_by_advisor\": states(\"input_boolean.victron_water_heater_forced_off_by_advisor\"),\n \"forced_off_reason\": states(\"input_text.victron_water_heater_forced_off_reason\"),\n \"forced_off_at\": states(\"input_datetime.victron_water_heater_forced_off_at\"),\n\n \"pending_user_action_prev\": states(\"input_text.victron_water_heater_pending_user_action\"),\n\n \"restore_surplus_w\": states(\"input_number.victron_water_heater_restore_surplus_w\"),\n \"mode_mismatch_delay_min\": states(\"input_number.victron_water_heater_mode_mismatch_delay_min\")\n} | tojson }}\n" } ] }, "options": {} }, "id": "264b44f4-227a-482e-b4da-9468855ce429", "name": "HA Snapshot Water Heater Advisor V2", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ -64, -160 ], "credentials": { "httpBearerAuth": { "id": "uv3sknYYigxBkaVN", "name": "Bearer Auth account 2" } } }, { "parameters": { "jsCode": "const root = $input.first()?.json ?? {};\nconst calls = root.ha_service_calls ?? {};\nconst decision = root.decision ?? {};\n\nfunction isObject(v) {\n return v !== null && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction isValidParisDateTime(v) {\n return typeof v === 'string' && /^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/.test(v.trim());\n}\n\nfunction normalizeText(v) {\n return (v ?? '').toString();\n}\n\nfunction shouldExecute(call) {\n if (!isObject(call)) return false;\n return call.execute !== false;\n}\n\nfunction getBaseUrl() {\n return ($env.HA_BASE_URL || 'http://10.10.10.17:8123').replace(/\\/$/, '');\n}\n\nfunction getDebugEntityId(data) {\n if (!isObject(data)) return '';\n if (typeof data.entity_id === 'string' && data.entity_id.trim()) return data.entity_id.trim();\n return '';\n}\n\nfunction sanitizeCall(key, call) {\n if (!isObject(call)) return null;\n if (!shouldExecute(call)) return null;\n\n const domain = normalizeText(call.domain).trim();\n const service = normalizeText(call.service).trim();\n const data = isObject(call.data) ? { ...call.data } : {};\n\n if (!domain || !service) return null;\n\n // Garde-fous ciblés\n if (domain === 'input_datetime' && service === 'set_datetime') {\n if (!isValidParisDateTime(data.datetime)) return null;\n }\n\n if (domain === 'input_text' && service === 'set_value') {\n data.value = normalizeText(data.value);\n }\n\n if (domain === 'input_select' && service === 'select_option') {\n if (!normalizeText(data.option).trim()) return null;\n }\n\n if (domain === 'input_number' && service === 'set_value') {\n const n = Number(data.value);\n if (!Number.isFinite(n)) return null;\n data.value = n;\n }\n\n if ((domain === 'switch' || domain === 'input_boolean') && !data.entity_id) {\n return null;\n }\n\n if (domain === 'notify') {\n data.title = normalizeText(data.title);\n data.message = normalizeText(data.message);\n }\n\n const baseUrl = getBaseUrl();\n const debugEntityId = getDebugEntityId(data);\n const debugUrl = `${baseUrl}/api/services/${domain}/${service}`;\n\n return {\n json: {\n action: key,\n domain,\n service,\n data,\n\n // mini debug demandé\n debug_action: key,\n debug_entity_id: debugEntityId || '(none)',\n debug_url: debugUrl,\n\n meta: {\n source: 'water_heater_advisor',\n timestamp_paris: root.timestamp_paris ?? null,\n recommended_mode: decision.recommended_mode ?? null,\n advice_color: decision.advice_color ?? null,\n state: decision.state ?? null\n }\n }\n };\n}\n\n// Ordre conseillé\nconst orderedKeys = [\n 'helper_recommended_mode',\n 'helper_advice_color',\n 'helper_state',\n 'helper_reason',\n 'helper_signature',\n\n 'helper_projected_soc',\n 'helper_budget_margin',\n 'helper_load_kwh',\n\n 'helper_legacy_advice_ok',\n 'helper_green_allowed',\n 'helper_auto_allowed',\n 'helper_boost_allowed',\n\n 'helper_observed_power',\n 'helper_observed_regime',\n 'helper_pending_user_action',\n 'helper_mismatch_since',\n\n 'helper_energy_prev_kwh',\n 'helper_energy_prev_at',\n\n 'helper_forced_off_by_advisor',\n 'helper_forced_off_reason',\n 'helper_forced_off_at',\n\n 'water_heater_power_switch',\n\n 'logbook',\n 'mobile_notification'\n];\n\nconst actions = [];\nconst alreadySeen = new Set();\n\nfor (const key of orderedKeys) {\n alreadySeen.add(key);\n const built = sanitizeCall(key, calls[key]);\n if (built) actions.push(built);\n}\n\n// Sécurité si de nouveaux appels sont ajoutés plus tard\nfor (const [key, call] of Object.entries(calls)) {\n if (alreadySeen.has(key)) continue;\n const built = sanitizeCall(key, call);\n if (built) actions.push(built);\n}\n\nreturn actions;\n" }, "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1504, -160 ], "id": "3b9b3251-a9ea-4fb4-ba6e-899bc39371e7", "name": "BUILD ECS HA Actions1" } ], "connections": { "ECS Normalize Inputs": { "main": [ [ { "node": "ECS EVCS & Water Heater Observation", "type": "main", "index": 0 } ] ] }, "ECS EVCS & Water Heater Observation": { "main": [ [ { "node": "ECS Energy Model & Early Boost Signals", "type": "main", "index": 0 } ] ] }, "ECS Energy Model & Early Boost Signals": { "main": [ [ { "node": "ECS Base Advisor Decision", "type": "main", "index": 0 } ] ] }, "ECS Base Advisor Decision": { "main": [ [ { "node": "ECS Final Arbitration & Protection", "type": "main", "index": 0 } ] ] }, "ECS Final Arbitration & Protection": { "main": [ [ { "node": "ECS Output Builder", "type": "main", "index": 0 } ] ] }, "ECS Output Builder": { "main": [ [ { "node": "BUILD ECS HA Actions1", "type": "main", "index": 0 } ] ] }, "Schedule Trigger": { "main": [ [ { "node": "HA Snapshot Water Heater Advisor V2", "type": "main", "index": 0 } ] ] }, "HA Snapshot Water Heater Advisor V2": { "main": [ [ { "node": "ECS Normalize Inputs", "type": "main", "index": 0 } ] ] }, "BUILD ECS HA Actions1": { "main": [ [ { "node": "Execute HA Service", "type": "main", "index": 0 } ] ] } }, "nodeGroups": [], "authors": "thierry tallagrand", "name": "Version 104ba5d2", "description": "", "autosaved": true, "workflowPublishHistory": [ { "createdAt": "2026-05-07T12:41:54.515Z", "id": 84, "workflowId": "yX2j8m04e3pxaoQq", "versionId": "104ba5d2-fa60-4b6e-9d00-d0b853c79fd4", "event": "activated", "userId": "8b9e9552-cd74-4863-82a3-174b3b3befa2" }, { "createdAt": "2026-06-12T21:11:20.249Z", "id": 112, "workflowId": "yX2j8m04e3pxaoQq", "versionId": "104ba5d2-fa60-4b6e-9d00-d0b853c79fd4", "event": "activated", "userId": "8b9e9552-cd74-4863-82a3-174b3b3befa2" }, { "createdAt": "2026-06-12T21:11:27.050Z", "id": 114, "workflowId": "yX2j8m04e3pxaoQq", "versionId": "104ba5d2-fa60-4b6e-9d00-d0b853c79fd4", "event": "activated", "userId": "8b9e9552-cd74-4863-82a3-174b3b3befa2" }, { "createdAt": "2026-07-09T21:45:54.876Z", "id": 200, "workflowId": "yX2j8m04e3pxaoQq", "versionId": "104ba5d2-fa60-4b6e-9d00-d0b853c79fd4", "event": "activated", "userId": "8b9e9552-cd74-4863-82a3-174b3b3befa2" }, { "createdAt": "2026-06-12T21:11:16.258Z", "id": 111, "workflowId": "yX2j8m04e3pxaoQq", "versionId": "104ba5d2-fa60-4b6e-9d00-d0b853c79fd4", "event": "deactivated", "userId": "8b9e9552-cd74-4863-82a3-174b3b3befa2" }, { "createdAt": "2026-06-12T21:11:27.017Z", "id": 113, "workflowId": "yX2j8m04e3pxaoQq", "versionId": "104ba5d2-fa60-4b6e-9d00-d0b853c79fd4", "event": "deactivated", "userId": "8b9e9552-cd74-4863-82a3-174b3b3befa2" }, { "createdAt": "2026-07-09T21:45:54.856Z", "id": 199, "workflowId": "yX2j8m04e3pxaoQq", "versionId": "104ba5d2-fa60-4b6e-9d00-d0b853c79fd4", "event": "deactivated", "userId": "8b9e9552-cd74-4863-82a3-174b3b3befa2" } ] } }