-
-
Save Davc0m/dc419aa3147ec3c3d6e7289f89dc0ed8 to your computer and use it in GitHub Desktop.
| /** | |
| * Shelly Pro 3EM - Net Metering (Saldierung) & Home Assistant Auto-Discovery | |
| * Version: 1.2.2 | |
| * | |
| * DISCLAIMER: | |
| * Use this script entirely at your own risk! I assume absolutely no liability | |
| * for any direct, indirect, or consequential damages. This includes, but is | |
| * not limited to, damage to the Shelly device, any connected electrical | |
| * equipment, other devices in your network, data loss, or system malfunctions. | |
| * By using this script, you acknowledge that you alone are responsible for | |
| * your hardware and setup. | |
| * | |
| * CHANGELOG (v1.1.8 -> v1.2.2): | |
| * - Automatic move of the Home Assistant sensors from the old v1.1.0 | |
| * discovery topics to the current ones. Entity IDs, settings and | |
| * statistics are kept (needs a Home Assistant version that supports | |
| * migrate_discovery; see CONFIG.migrateLegacyDiscovery). | |
| * - Counters no longer jump back after a restart: the start value is the | |
| * highest of Script.storage, the KVS backup and the last retained MQTT | |
| * value. Measuring starts immediately, publishing only once the start | |
| * value is known. | |
| * - Counters are saved before planned restarts and firmware updates: | |
| * synchronously to Script.storage (KVS.Set is asynchronous and does not | |
| * finish before the restart), then published via MQTT. | |
| * - KVS is only written when a value has changed; interval in minutes. | |
| * - Energy is integrated over the measured time between two cycles instead | |
| * of assuming exactly 500 ms per cycle. | |
| * - Invalid power readings (NaN, implausible values) are skipped. | |
| * - Synchronous start-up; a missing MQTT topic_prefix falls back to the | |
| * device id. | |
| * - The Home Assistant device name is taken from the Shelly settings. | |
| * - Test mode to run next to the production script with its own MQTT | |
| * topics, KVS keys and Home Assistant entities. | |
| * - getDiagnostics() for troubleshooting via Script.Eval. | |
| */ | |
| let CONFIG = { | |
| testMode: false, // true = run alongside the production script (own topics, KVS keys, HA entities) | |
| updateInterval: 500, // Calculation cycle in ms | |
| enablePersistence: true, // true = back up counter states in flash memory (KVS, Script.storage) | |
| saveIntervalMinutes: 60, // KVS backup interval; only changed values are written | |
| minPublishInterval: 5000, // Minimum time between two MQTT counter updates in ms | |
| restoreTimeout: 5000, // Max. wait for retained MQTT values at start in ms | |
| maxGap: 5000, // Longer pauses between two cycles are capped to this value in ms | |
| migrateLegacyDiscovery: true, // true = move sensors that were registered by v1.1.0 to the current topics | |
| migrationStepDelay: 5000, // Pause between the steps of that move in ms | |
| mqttPrefix: "homeassistant" // Standard HA Discovery Prefix | |
| }; | |
| let VERSION = "1.2.2"; | |
| let SUFFIX = CONFIG.testMode ? "_test" : ""; | |
| let KVS_KEY_C = (CONFIG.testMode ? "Test" : "") + "EnergyConsumedKWh"; | |
| let KVS_KEY_R = (CONFIG.testMode ? "Test" : "") + "EnergyReturnedKWh"; | |
| let STORE_KEY = "wh" + SUFFIX; | |
| let MAX_POWER = 500000; // W; readings beyond this are treated as invalid | |
| let SHELLY_ID = null; | |
| let DEVICE_NAME = "Shelly Pro 3EM"; | |
| let TOPIC_C = ""; | |
| let TOPIC_R = ""; | |
| // Counters in whole Wh: start value + energy measured since script start | |
| let baseWhC = 0; | |
| let baseWhR = 0; | |
| let sessionWhC = 0; | |
| let sessionWhR = 0; | |
| let restWsC = 0.0; | |
| let restWsR = 0.0; | |
| let kvsPending = 0; | |
| let kvsDone = false; | |
| let kvsBlocked = false; | |
| let kvsWhC = null; | |
| let kvsWhR = null; | |
| let savedC = null; | |
| let savedR = null; | |
| let storeWhC = null; | |
| let storeWhR = null; | |
| let retainedStarted = false; | |
| let retainedDone = false; | |
| let retainedTimer = null; | |
| let mqttWhC = null; | |
| let mqttWhR = null; | |
| let gotC = false; | |
| let gotR = false; | |
| let migrationStarted = false; | |
| let legacyTopics = []; | |
| let ready = false; | |
| let pubWhC = -1; | |
| let pubWhR = -1; | |
| let lastPublish = 0; | |
| let lastTick = null; | |
| let diag = { | |
| ticks: 0, | |
| sumDt: 0, | |
| maxDt: 0, | |
| gaps: 0, | |
| invalid: 0, | |
| kvsWrites: 0, | |
| storageWrites: 0, | |
| restore: null | |
| }; | |
| // ───────────────────────────────────────────── | |
| // 1. Helper Functions | |
| // ───────────────────────────────────────────── | |
| function nowMs() { | |
| if (typeof Shelly.getUptimeMs === "function") return Shelly.getUptimeMs(); | |
| return Date.now(); | |
| } | |
| function whToKWh(wh) { | |
| return (wh / 1000).toFixed(3); | |
| } | |
| function kwhToWh(value) { | |
| let n = Number(value); | |
| if (typeof n !== "number" || n !== n || n < 0) return null; | |
| return Math.round(n * 1000); | |
| } | |
| function maxWh(current, candidate) { | |
| if (candidate === null) return current; | |
| return Math.max(current, candidate); | |
| } | |
| function fmtWh(wh) { | |
| if (wh === null) return "-"; | |
| return whToKWh(wh); | |
| } | |
| function validWh(value) { | |
| if (typeof value !== "number" || value !== value || value < 0) return null; | |
| return Math.round(value); | |
| } | |
| function getDiagnostics() { | |
| return JSON.stringify({ | |
| version: VERSION, | |
| testMode: CONFIG.testMode, | |
| ready: ready, | |
| consumed: whToKWh(baseWhC + sessionWhC), | |
| returned: whToKWh(baseWhR + sessionWhR), | |
| published: [pubWhC, pubWhR], | |
| saved: [savedC, savedR], | |
| restore: diag.restore, | |
| ticks: diag.ticks, | |
| avgCycleMs: diag.ticks > 0 ? Math.round(diag.sumDt / diag.ticks * 100) / 100 : null, | |
| maxCycleMs: diag.maxDt, | |
| gaps: diag.gaps, | |
| invalid: diag.invalid, | |
| kvsWrites: diag.kvsWrites, | |
| storageWrites: diag.storageWrites, | |
| kvsBlocked: kvsBlocked | |
| }); | |
| } | |
| // ───────────────────────────────────────────── | |
| // 2. Publish / Save | |
| // ───────────────────────────────────────────── | |
| function publishCounters(force) { | |
| if (!ready || !MQTT.isConnected()) return; | |
| let whC = baseWhC + sessionWhC; | |
| let whR = baseWhR + sessionWhR; | |
| if (!force && whC === pubWhC && whR === pubWhR) return; | |
| let t = nowMs(); | |
| if (!force && t - lastPublish < CONFIG.minPublishInterval) return; | |
| lastPublish = t; | |
| if ((force || whC !== pubWhC) && MQTT.publish(TOPIC_C, whToKWh(whC), 0, true)) pubWhC = whC; | |
| if ((force || whR !== pubWhR) && MQTT.publish(TOPIC_R, whToKWh(whR), 0, true)) pubWhR = whR; | |
| } | |
| function onKvsSet(result, errCode, errMsg, key) { | |
| if (errCode === 0) return; | |
| print("ERROR: KVS.Set " + key + " failed (" + errCode + "): " + errMsg); | |
| if (key === KVS_KEY_C) { | |
| savedC = null; | |
| } else { | |
| savedR = null; | |
| } | |
| } | |
| function saveCounters(reason) { | |
| if (!CONFIG.enablePersistence || !kvsDone || kvsBlocked) return; | |
| let valC = whToKWh(baseWhC + sessionWhC); | |
| let valR = whToKWh(baseWhR + sessionWhR); | |
| let writes = 0; | |
| if (valC !== savedC) { | |
| savedC = valC; | |
| Shelly.call("KVS.Set", { "key": KVS_KEY_C, "value": valC }, onKvsSet, KVS_KEY_C); | |
| writes++; | |
| } | |
| if (valR !== savedR) { | |
| savedR = valR; | |
| Shelly.call("KVS.Set", { "key": KVS_KEY_R, "value": valR }, onKvsSet, KVS_KEY_R); | |
| writes++; | |
| } | |
| if (writes > 0) { | |
| diag.kvsWrites += writes; | |
| print("Counters saved to KVS (" + reason + "): " + valC + " / " + valR + " kWh"); | |
| } | |
| } | |
| function onSaveTimer() { | |
| saveCounters("interval"); | |
| } | |
| // Script.storage writes synchronously, so the value is stored even if the | |
| // device restarts right after the restart announcement. | |
| function hasStorage() { | |
| return CONFIG.enablePersistence && typeof Script !== "undefined" && !!Script.storage; | |
| } | |
| function writeStorage() { | |
| if (!hasStorage()) return false; | |
| try { | |
| Script.storage.setItem(STORE_KEY, JSON.stringify([baseWhC + sessionWhC, baseWhR + sessionWhR])); | |
| diag.storageWrites++; | |
| return true; | |
| } catch (e) { | |
| print("ERROR: Script.storage.setItem failed."); | |
| return false; | |
| } | |
| } | |
| function readStorage() { | |
| if (!hasStorage()) return; | |
| try { | |
| let raw = Script.storage.getItem(STORE_KEY); | |
| if (raw === null || raw === undefined) return; | |
| let values = JSON.parse(raw); | |
| storeWhC = validWh(values[0]); | |
| storeWhR = validWh(values[1]); | |
| } catch (e) { | |
| print("WARNING: Script.storage holds an invalid value."); | |
| } | |
| } | |
| // ───────────────────────────────────────────── | |
| // 3. Restore start values (Script.storage + KVS + retained MQTT) | |
| // ───────────────────────────────────────────── | |
| function tryFinishRestore() { | |
| if (ready || !kvsDone || !retainedDone) return; | |
| ready = true; | |
| diag.restore = { | |
| storage: [storeWhC, storeWhR], | |
| kvs: [kvsWhC, kvsWhR], | |
| mqtt: [mqttWhC, mqttWhR], | |
| start: [baseWhC, baseWhR], | |
| atMs: nowMs() | |
| }; | |
| print("Start values | consumed " + whToKWh(baseWhC) + " kWh (storage " + fmtWh(storeWhC) + ", KVS " + fmtWh(kvsWhC) + | |
| ", MQTT " + fmtWh(mqttWhC) + ") | returned " + whToKWh(baseWhR) + " kWh (storage " + fmtWh(storeWhR) + | |
| ", KVS " + fmtWh(kvsWhR) + ", MQTT " + fmtWh(mqttWhR) + ")"); | |
| publishCounters(true); | |
| } | |
| function onKvsGet(result, errCode, errMsg, key) { | |
| let wh = null; | |
| if (errCode === 0 && result && result.value !== undefined && result.value !== null) { | |
| wh = kwhToWh(result.value); | |
| if (wh === null) print("WARNING: KVS " + key + " holds an invalid value: " + result.value); | |
| } else if (errCode !== 0 && errCode !== -105) { | |
| kvsBlocked = true; | |
| print("ERROR: KVS.Get " + key + " failed (" + errCode + "): " + errMsg + " - KVS writes disabled for this run."); | |
| } | |
| if (key === KVS_KEY_C) { | |
| kvsWhC = wh; | |
| if (wh !== null) savedC = whToKWh(wh); | |
| } else { | |
| kvsWhR = wh; | |
| if (wh !== null) savedR = whToKWh(wh); | |
| } | |
| kvsPending--; | |
| if (kvsPending > 0) return; | |
| kvsDone = true; | |
| baseWhC = maxWh(baseWhC, kvsWhC); | |
| baseWhR = maxWh(baseWhR, kvsWhR); | |
| tryFinishRestore(); | |
| } | |
| function finishRetainedCheck() { | |
| if (retainedDone) return; | |
| retainedDone = true; | |
| if (retainedTimer !== null) { | |
| Timer.clear(retainedTimer); | |
| retainedTimer = null; | |
| } | |
| try { | |
| MQTT.unsubscribe(TOPIC_C); | |
| MQTT.unsubscribe(TOPIC_R); | |
| } catch (e) { | |
| print("WARNING: MQTT.unsubscribe failed."); | |
| } | |
| baseWhC = maxWh(baseWhC, mqttWhC); | |
| baseWhR = maxWh(baseWhR, mqttWhR); | |
| tryFinishRestore(); | |
| } | |
| function onRetained(topic, message, which) { | |
| if (retainedDone) return; | |
| let wh = kwhToWh(message); | |
| if (which === "c") { | |
| mqttWhC = wh; | |
| gotC = true; | |
| } else { | |
| mqttWhR = wh; | |
| gotR = true; | |
| } | |
| if (gotC && gotR) finishRetainedCheck(); | |
| } | |
| function startRetainedCheck() { | |
| if (retainedStarted || retainedDone) return; | |
| retainedStarted = true; | |
| try { | |
| MQTT.subscribe(TOPIC_C, onRetained, "c"); | |
| MQTT.subscribe(TOPIC_R, onRetained, "r"); | |
| } catch (e) { | |
| print("WARNING: MQTT.subscribe failed - continuing without retained values."); | |
| finishRetainedCheck(); | |
| return; | |
| } | |
| retainedTimer = Timer.set(CONFIG.restoreTimeout, false, finishRetainedCheck); | |
| } | |
| // ───────────────────────────────────────────── | |
| // 4. Home Assistant Auto-Discovery | |
| // ───────────────────────────────────────────── | |
| function AnnounceHA() { | |
| let haTopic = CONFIG.mqttPrefix + "/sensor/" + SHELLY_ID + SUFFIX; | |
| let avtyTopic = SHELLY_ID + "/online"; | |
| let dev = { | |
| "ids": [SHELLY_ID + SUFFIX], | |
| "name": DEVICE_NAME, | |
| "mf": "Shelly", | |
| "mdl": "Pro 3EM", | |
| "sw": "Saldierung v" + VERSION | |
| }; | |
| let okImport = MQTT.publish( | |
| haTopic + "-import/config", | |
| JSON.stringify({ | |
| "name": "Saldierend Import", | |
| "uniq_id": SHELLY_ID + "_sald_import" + SUFFIX, | |
| "stat_t": TOPIC_C, | |
| "unit_of_meas": "kWh", | |
| "dev_cla": "energy", | |
| "stat_cla": "total_increasing", | |
| "avty_t": avtyTopic, | |
| "pl_avail": "true", | |
| "pl_not_avail": "false", | |
| "dev": dev | |
| }), | |
| 0, true | |
| ); | |
| let okExport = MQTT.publish( | |
| haTopic + "-export/config", | |
| JSON.stringify({ | |
| "name": "Saldierend Export", | |
| "uniq_id": SHELLY_ID + "_sald_export" + SUFFIX, | |
| "stat_t": TOPIC_R, | |
| "unit_of_meas": "kWh", | |
| "dev_cla": "energy", | |
| "stat_cla": "total_increasing", | |
| "avty_t": avtyTopic, | |
| "pl_avail": "true", | |
| "pl_not_avail": "false", | |
| "dev": dev | |
| }), | |
| 0, true | |
| ); | |
| if (okImport && okExport) { | |
| print("HA Auto-Discovery sent."); | |
| } else { | |
| print("WARNING: HA Discovery publish failed (MQTT not ready?)."); | |
| } | |
| } | |
| // ───────────────────────────────────────────── | |
| // 5. MQTT and System Event Handlers | |
| // ───────────────────────────────────────────── | |
| // v1.1.0 registered the sensors under topics with a doubled device prefix. | |
| // Home Assistant keeps owning the entities through those topics and rejects the | |
| // current registration as a duplicate. migrate_discovery makes HA unload the | |
| // entities but keep their registry entries (entity ID, settings, statistics); | |
| // after the old retained topics are cleared, the current registration attaches | |
| // to the same entries. Without anything on the old topics this does nothing. | |
| function startLegacyMigration() { | |
| migrationStarted = true; | |
| let base = CONFIG.mqttPrefix + "/sensor/shellypro3em-" + SHELLY_ID + SUFFIX; | |
| legacyTopics = [base + "-import/config", base + "-export/config"]; | |
| for (let i = 0; i < legacyTopics.length; i++) { | |
| MQTT.publish(legacyTopics[i], "{\"migrate_discovery\":true}", 0, false); | |
| } | |
| Timer.set(CONFIG.migrationStepDelay, false, clearLegacyDiscovery); | |
| } | |
| function clearLegacyDiscovery() { | |
| for (let i = 0; i < legacyTopics.length; i++) { | |
| MQTT.publish(legacyTopics[i], "", 0, true); | |
| } | |
| Timer.set(CONFIG.migrationStepDelay, false, finishLegacyMigration); | |
| } | |
| function finishLegacyMigration() { | |
| if (MQTT.isConnected()) AnnounceHA(); | |
| // Second registration in case HA was slower than the pause; unchanged ones are ignored. | |
| Timer.set(30000, false, AnnounceHA); | |
| } | |
| function onMqttConnect() { | |
| print("MQTT connected."); | |
| if (CONFIG.migrateLegacyDiscovery && !migrationStarted) { | |
| startLegacyMigration(); | |
| } else { | |
| AnnounceHA(); | |
| } | |
| if (!retainedDone) { | |
| startRetainedCheck(); | |
| } else { | |
| publishCounters(true); | |
| } | |
| } | |
| function onMqttDisconnect() { | |
| // Cannot publish here - connection is already gone. | |
| // HA uses native Shelly LWT on <topic_prefix>/online for offline detection. | |
| print("MQTT disconnected."); | |
| } | |
| function onEvent(ev) { | |
| if (!ev || ev.component !== "sys" || !ev.info) return; | |
| let name = ev.info.event; | |
| if (name === "scheduled_restart" || name === "ota_begin" || name === "ota_success") { | |
| // Synchronous storage first: the device may restart within a second. | |
| let stored = writeStorage(); | |
| publishCounters(true); | |
| saveCounters(name); | |
| print("System event " + name + ": counters stored" + (stored ? "" : " (without Script.storage)") + "."); | |
| } | |
| } | |
| // ───────────────────────────────────────────── | |
| // 6. Main Calculation Loop | |
| // ───────────────────────────────────────────── | |
| function onTick() { | |
| let t = nowMs(); | |
| if (lastTick === null) { | |
| lastTick = t; | |
| return; | |
| } | |
| let dt = t - lastTick; | |
| lastTick = t; | |
| if (dt <= 0) return; | |
| diag.ticks++; | |
| diag.sumDt += dt; | |
| if (dt > diag.maxDt) diag.maxDt = dt; | |
| if (dt > CONFIG.maxGap) { | |
| diag.gaps++; | |
| dt = CONFIG.maxGap; | |
| } | |
| let em = Shelly.getComponentStatus("em", 0); | |
| if (!em) return; | |
| let power = em.total_act_power; | |
| if (typeof power !== "number" || power !== power || power > MAX_POWER || power < -MAX_POWER) { | |
| diag.invalid++; | |
| return; | |
| } | |
| let ws = power * dt / 1000.0; | |
| if (ws >= 0) { | |
| restWsC += ws; | |
| if (restWsC >= 3600) { | |
| let fullC = Math.floor(restWsC / 3600); | |
| sessionWhC += fullC; | |
| restWsC -= fullC * 3600; | |
| } | |
| } else { | |
| restWsR -= ws; | |
| if (restWsR >= 3600) { | |
| let fullR = Math.floor(restWsR / 3600); | |
| sessionWhR += fullR; | |
| restWsR -= fullR * 3600; | |
| } | |
| } | |
| publishCounters(false); | |
| } | |
| // ───────────────────────────────────────────── | |
| // 7. Initialization | |
| // ───────────────────────────────────────────── | |
| function init() { | |
| let info = Shelly.getDeviceInfo(); | |
| let mqttCfg = Shelly.getComponentConfig("mqtt"); | |
| let sysCfg = Shelly.getComponentConfig("sys"); | |
| if (mqttCfg && mqttCfg.topic_prefix) { | |
| SHELLY_ID = mqttCfg.topic_prefix; | |
| } else if (info && info.id) { | |
| SHELLY_ID = info.id; | |
| } | |
| if (!SHELLY_ID) { | |
| print("ERROR: Neither MQTT topic_prefix nor device id available."); | |
| return; | |
| } | |
| if (sysCfg && sysCfg.device && sysCfg.device.name) DEVICE_NAME = sysCfg.device.name; | |
| if (CONFIG.testMode) DEVICE_NAME = DEVICE_NAME + " (Test)"; | |
| TOPIC_C = SHELLY_ID + "/energy_counter" + SUFFIX + "/consumed"; | |
| TOPIC_R = SHELLY_ID + "/energy_counter" + SUFFIX + "/returned"; | |
| print("Saldierung v" + VERSION + (CONFIG.testMode ? " [TEST MODE]" : "") + " | ID: " + SHELLY_ID + " | Name: " + DEVICE_NAME); | |
| if (!Shelly.getComponentStatus("em", 0)) { | |
| print("ERROR: Component em:0 not found. The device must use the triphase profile."); | |
| } | |
| if (CONFIG.enablePersistence) { | |
| readStorage(); | |
| baseWhC = maxWh(baseWhC, storeWhC); | |
| baseWhR = maxWh(baseWhR, storeWhR); | |
| kvsPending = 2; | |
| Shelly.call("KVS.Get", { "key": KVS_KEY_C }, onKvsGet, KVS_KEY_C); | |
| Shelly.call("KVS.Get", { "key": KVS_KEY_R }, onKvsGet, KVS_KEY_R); | |
| } else { | |
| kvsDone = true; | |
| print("Persistence disabled. Start values come from MQTT only."); | |
| } | |
| if (mqttCfg && mqttCfg.enable) { | |
| MQTT.setConnectHandler(onMqttConnect); | |
| MQTT.setDisconnectHandler(onMqttDisconnect); | |
| if (MQTT.isConnected()) onMqttConnect(); | |
| } else { | |
| retainedDone = true; | |
| print("WARNING: MQTT is disabled - counters cannot be published."); | |
| } | |
| Shelly.addEventHandler(onEvent); | |
| Timer.set(CONFIG.updateInterval, true, onTick); | |
| if (CONFIG.enablePersistence && CONFIG.saveIntervalMinutes > 0) { | |
| Timer.set(CONFIG.saveIntervalMinutes * 60000, true, onSaveTimer); | |
| } | |
| tryFinishRestore(); | |
| } | |
| init(); |
Hallo Davc0m,
danke für das Script, läuft bei mir auf einem Pro 3EM am Hausanschluss (v1.1.8) und deckt sich im Oktober bis auf ca. 1 % mit dem iMSys des Netzbetreibers. 👍
Eine Beobachtung zur Last in Home Assistant: PublishCounters(false) sendet bei jeder Änderung des auf 3 Nachkommastellen gerundeten Werts, also bei jeder Wattstunde. Jede Nachricht wird im HA-Recorder zu einer Zeile in states. Bei mir (größere PV-Anlage) sind das:
- Import: ~680 kWh im Oktober → ~680.000 Zeilen/Monat, ca. 22.000/Tag
- Export: an sonnigen Tagen ~3.400 Zeilen/Stunde (ein Wert alle 1–2 s)
- Die Kosten-/Vergütungssensoren des Energie-Dashboards laufen im selben Takt mit
Zusammen mit Folgesensoren waren das bei mir rund 12 % aller Recorder-Zeilen. Für die Langzeitstatistik und das Energie-Dashboard bringt die Wh-Auflösung im Sekundentakt nichts, die arbeiten mit Stundenwerten. Die Live-Leistung kommt ohnehin aus der Shelly-Integration.
Vorschlag: ein optionaler Mindestabstand zwischen zwei Publishes, per Default aus, damit sich für bestehende Nutzer nichts ändert.
// CONFIG
publishMinInterval: 0, // Mindestabstand zwischen zwei MQTT-Publishes in s (0 = bei jeder Wh-Änderung, wie bisher)
// global
let lastPublishMs = 0;
// in PublishCounters(force), direkt nach der bestehenden "unverändert → return"-Prüfung:
let nowMs = Shelly.getUptimeMs();
if (!force && CONFIG.publishMinInterval > 0 &&
nowMs - lastPublishMs < CONFIG.publishMinInterval * 1000) return;
// nach erfolgreichem Publish (dort, wo lastPublishedConsumed/-Returned gesetzt werden):
lastPublishMs = nowMs;Da die Zähler absolut sind, geht dabei keine Energie verloren. Der nächste Publish enthält einfach den aktuellen Stand. Die Force-Publishes nach MQTT-Connect und LoadCounters() bleiben unberührt. Mit z. B. publishMinInterval: 60 wären es max. 1.440 Nachrichten pro Zähler und Tag.
Würde mich freuen, wenn du das aufnimmst. Dann muss man es nicht bei jedem Update selbst nachpflegen.
Grüße
Tobias
@tobias: habe deine Erweiterungen eingebaut. Ich sehe auch, dass die Sensoren nun frühestens nach der eingestellten Zeit aktualisieren. Find ich gut! Eine realisierte Nulleinspeisung wird über die Leistung geregelt, und da die nach wie vor über die Integration kommt, gehen uns auch hier zeitliche Details nicht verloren.
Sehe aber, dass der Client anscheinend trotzdem noch alle 30s eine Verbindung zum Broker aufbaut. Schätze, dass das nicht weiter schlimm ist, da die eigentliche Last im System ja die Aktualisiserung der Energiewerte ist. Evtl. ist das ein alive-Trigger?
Hallo Davc0m,
danke für das Script, läuft bei mir auf einem Pro 3EM am Hausanschluss (v1.1.8) und deckt sich im Oktober bis auf ca. 1 % mit dem iMSys des Netzbetreibers. 👍
Eine Beobachtung zur Last in Home Assistant:
PublishCounters(false)sendet bei jeder Änderung des auf 3 Nachkommastellen gerundeten Werts, also bei jeder Wattstunde. Jede Nachricht wird im HA-Recorder zu einer Zeile instates. Bei mir (größere PV-Anlage) sind das:* Import: ~680 kWh im Oktober → ~680.000 Zeilen/Monat, ca. 22.000/Tag * Export: an sonnigen Tagen ~3.400 Zeilen/Stunde (ein Wert alle 1–2 s) * Die Kosten-/Vergütungssensoren des Energie-Dashboards laufen im selben Takt mitZusammen mit Folgesensoren waren das bei mir rund 12 % aller Recorder-Zeilen. Für die Langzeitstatistik und das Energie-Dashboard bringt die Wh-Auflösung im Sekundentakt nichts, die arbeiten mit Stundenwerten. Die Live-Leistung kommt ohnehin aus der Shelly-Integration.
Vorschlag: ein optionaler Mindestabstand zwischen zwei Publishes, per Default aus, damit sich für bestehende Nutzer nichts ändert.
// CONFIG publishMinInterval: 0, // Mindestabstand zwischen zwei MQTT-Publishes in s (0 = bei jeder Wh-Änderung, wie bisher) // global let lastPublishMs = 0; // in PublishCounters(force), direkt nach der bestehenden "unverändert → return"-Prüfung: let nowMs = Shelly.getUptimeMs(); if (!force && CONFIG.publishMinInterval > 0 && nowMs - lastPublishMs < CONFIG.publishMinInterval * 1000) return; // nach erfolgreichem Publish (dort, wo lastPublishedConsumed/-Returned gesetzt werden): lastPublishMs = nowMs;Da die Zähler absolut sind, geht dabei keine Energie verloren. Der nächste Publish enthält einfach den aktuellen Stand. Die Force-Publishes nach MQTT-Connect und
LoadCounters()bleiben unberührt. Mit z. B.publishMinInterval: 60wären es max. 1.440 Nachrichten pro Zähler und Tag.Würde mich freuen, wenn du das aufnimmst. Dann muss man es nicht bei jedem Update selbst nachpflegen.
Grüße Tobias
@tmooz Hallo Tobias, danke für die Rückmeldung und die genaue Rechnung.
Das ist in der aktuellen Version v1.2.2 schon drin. Dort gibt es im CONFIG-Block eine Einstellung, die genau das macht, was du vorschlägst:
minPublishInterval: 5000, // Mindestabstand zwischen zwei MQTT-Meldungen der Zähler in ms- Der Standard ist 5 Sekunden. Das ist die Einheit Millisekunden, nicht Sekunden wie in deinem Vorschlag.
- Für deinen Wunsch von einer Meldung pro Minute setzt du
minPublishInterval: 60000. Das sind höchstens 1.440 Meldungen pro Tag und Zähler. - Es geht keine Energie verloren. Die Zähler laufen im Script weiter, und die nächste Meldung enthält immer den aktuellen Stand.
- Die erste Meldung nach dem Start und nach einer neuen MQTT-Verbindung wird sofort gesendet, unabhängig vom Abstand.
- Nach dem Ändern den Wert speichern und das Script neu starten.
Bei einem Wechsel von v1.1.8 auf v1.2.2 solltest du Folgendes wissen:
- Der Zähler läuft beim letzten Stand weiter. Das Script nimmt beim Start den höchsten Wert aus Script-Speicher, KVS und dem zuletzt gesendeten MQTT-Wert.
- Zusätzlich werden die Zähler nur noch etwa einmal pro Stunde und nur bei Änderung in den Flash geschrieben.
- Die Sensoren in HA und das Energie-Dashboard bleiben erhalten.
- Mit 60 s Abstand zeigt HA die Zähler bis zu eine Minute verzögert an. Für Statistik und Energie-Dashboard ist das egal, und die Live-Leistung kommt weiter aus der Shelly-Integration.
Viele Grüße
Dav
Ich habe soweit alles intergriert und mir werden auch die zwei Entitäten in HA angezeigt. Nur leider liefern sie, seitdem ich den Shelly Pro 3EM direkt per Netzwerkkabel an meinem verdrahtet habe keine sauberen Werte.
