no message

This commit is contained in:
mh
2026-04-21 10:40:32 +02:00
parent 6037ade2cc
commit 6ea256910d
2 changed files with 13 additions and 238 deletions
+2 -2
View File
@@ -104,8 +104,8 @@
"type": "NumberSpinner", "type": "NumberSpinner",
"name": "UpdateInterval", "name": "UpdateInterval",
"caption": "Neuberechnung alle", "caption": "Neuberechnung alle",
"suffix": "Miliskeunden", "suffix": "Sekunden",
"minimum": 200, "minimum": 0,
"maximum": 100000 "maximum": 100000
} }
] ]
+7 -232
View File
@@ -1,28 +1,23 @@
<?php
<?php
class Bat_EV_SDL_V3_Beta extends IPSModule class Bat_EV_SDL_V3_Beta extends IPSModule
{ {
private const HOURS = 0.5; // 30 Minuten private const HOURS = 0.5; // 30 Minuten
public function Create() public function Create()
{ {
parent::Create(); parent::Create();
// Properties // Properties
$this->RegisterPropertyString("Batteries", "[]"); $this->RegisterPropertyString("Batteries", "[]");
//$this->RegisterPropertyInteger("$upKWh + $underKWh)", 0); //$this->RegisterPropertyInteger("$upKWh + $underKWh)", 0);
$this->RegisterPropertyInteger("SDL_Leistung_Laden", 0); $this->RegisterPropertyInteger("SDL_Leistung_Laden", 0);
$this->RegisterPropertyInteger("SDL_Leistung_Entladen", 0); // W $this->RegisterPropertyInteger("SDL_Leistung_Entladen", 0); // W
$this->RegisterPropertyInteger("UpdateInterval", 2000); // Minuten $this->RegisterPropertyInteger("UpdateInterval", 5); // Minuten
// Status // Status
$this->RegisterVariableBoolean("State", "Aktiv", "~Switch", 1); $this->RegisterVariableBoolean("State", "Aktiv", "~Switch", 1);
$this->EnableAction("State"); $this->EnableAction("State");
// Prozentwerte // Prozentwerte
$this->RegisterVariableFloat("SDL_Pos", "SDL Energie verfügbar (%)", "", 10); $this->RegisterVariableFloat("SDL_Pos", "SDL Energie verfügbar (%)", "", 10);
$this->RegisterVariableFloat("SoC_EV", "EV Energie verfügbar (%)", "", 11); $this->RegisterVariableFloat("SoC_EV", "EV Energie verfügbar (%)", "", 11);
// Variablen // Variablen
$this->RegisterVariableFloat("Nennleistung_Soll_EV", "Nennleistung Soll EV", "", 2); $this->RegisterVariableFloat("Nennleistung_Soll_EV", "Nennleistung Soll EV", "", 2);
$this->RegisterVariableFloat("Nennleistung_Soll_SDL", "Nennleistung Soll SDL", "", 3); $this->RegisterVariableFloat("Nennleistung_Soll_SDL", "Nennleistung Soll SDL", "", 3);
@@ -32,27 +27,20 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
$this->RegisterVariableFloat("P_SDL_entladen", "P SDL entladen max (W)", "", 22); $this->RegisterVariableFloat("P_SDL_entladen", "P SDL entladen max (W)", "", 22);
$this->RegisterVariableFloat("P_EV_laden", "P EV laden max (W)", "", 31); $this->RegisterVariableFloat("P_EV_laden", "P EV laden max (W)", "", 31);
$this->RegisterVariableFloat("P_EV_entladen", "P EV entladen max (W)", "", 32); $this->RegisterVariableFloat("P_EV_entladen", "P EV entladen max (W)", "", 32);
// Debug // Debug
$this->RegisterVariableString("CalcJSON", "Berechnung (JSON)", "", 99); $this->RegisterVariableString("CalcJSON", "Berechnung (JSON)", "", 99);
// Timer: wichtig -> Prefix muss passen // Timer: wichtig -> Prefix muss passen
$this->RegisterTimer("UpdateTimer", 0, 'GEF_Update($_IPS["TARGET"]);'); $this->RegisterTimer("UpdateTimer", 0, 'GEF_Update($_IPS["TARGET"]);');
} }
public function ApplyChanges() public function ApplyChanges()
{ {
parent::ApplyChanges(); parent::ApplyChanges();
$intervalSec = (int)$this->ReadPropertyInteger("UpdateInterval"); $intervalSec = (int)$this->ReadPropertyInteger("UpdateInterval");
$this->SetTimerInterval("UpdateTimer", ($intervalSec > 0) ? $intervalSec : 0); $this->SetTimerInterval("UpdateTimer", ($intervalSec > 0) ? $intervalSec * 1000 : 0);
// Cache neu bauen (force) // Cache neu bauen (force)
$this->BuildBatteryCache(true); $this->BuildBatteryCache(true);
$this->Update(); $this->Update();
} }
public function RequestAction($Ident, $Value) public function RequestAction($Ident, $Value)
{ {
if ($Ident === "State") { if ($Ident === "State") {
@@ -62,79 +50,52 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
} }
return; return;
} }
throw new Exception("Invalid Ident: " . $Ident); throw new Exception("Invalid Ident: " . $Ident);
} }
public function Update() public function Update()
{ {
// Reentranzschutz verhindert parallele Update()-Läufe // Reentranzschutz verhindert parallele Update()-Läufe
$semKey = 'BatEVSDL_Update_' . $this->InstanceID; $semKey = 'BatEVSDL_Update_' . $this->InstanceID;
if (!IPS_SemaphoreEnter($semKey, 5000)) { if (!IPS_SemaphoreEnter($semKey, 5000)) {
$this->SendDebug("Update", "SKIP (Semaphore locked)", 0); $this->SendDebug("Update", "SKIP (Semaphore locked)", 0);
return; return;
} }
try { try {
if (!GetValue($this->GetIDForIdent("State"))) { if (!GetValue($this->GetIDForIdent("State"))) {
return; return;
} }
// Cache nur neu bauen, wenn nötig // Cache nur neu bauen, wenn nötig
$this->BuildBatteryCache(false); $this->BuildBatteryCache(false);
$cache = json_decode($this->GetBufferSafe("BatCacheJSON"), true); $cache = json_decode($this->GetBufferSafe("BatCacheJSON"), true);
if (!is_array($cache) || empty($cache["bats"])) { if (!is_array($cache) || empty($cache["bats"])) {
$this->WriteAllZero("cache empty/invalid"); $this->WriteAllZero("cache empty/invalid");
return; return;
} }
// ===================== // =====================
// Integrator: State laden // Integrator: State laden
// ===================== // =====================
// Optional für 2s besser: microtime(true) statt time() verwenden // Optional für 2s besser: microtime(true) statt time() verwenden
$now = time();
// Millisekunden-genau: microtime(true) liefert Sekunden als Float $lastTs = (int)$this->GetBufferSafe("Int_LastTs");
$now = microtime(true);
// Timestamp als Float aus Buffer lesen (nicht int!)
$lastTs = (float)$this->GetBufferSafe("Int_LastTs");
// Leistungen / Konten wie gehabt
$lastPEV = (float)$this->GetBufferSafe("Int_LastP_EV_W"); // W (+ laden, - entladen) $lastPEV = (float)$this->GetBufferSafe("Int_LastP_EV_W"); // W (+ laden, - entladen)
$lastPSDL = (float)$this->GetBufferSafe("Int_LastP_SDL_W"); // W (+ laden, - entladen) $lastPSDL = (float)$this->GetBufferSafe("Int_LastP_SDL_W"); // W (+ laden, - entladen)
$Eev = (float)$this->GetBufferSafe("Int_E_EV_kWh"); // kWh-Konto EV $Eev = (float)$this->GetBufferSafe("Int_E_EV_kWh"); // kWh-Konto EV
$Esdl = (float)$this->GetBufferSafe("Int_E_SDL_kWh"); // kWh-Konto SDL $Esdl = (float)$this->GetBufferSafe("Int_E_SDL_kWh"); // kWh-Konto SDL
if ($lastTs <= 0) {
if ($lastTs <= 0.0) {
$lastTs = $now; $lastTs = $now;
$lastPEV = 0.0; $lastPEV = 0.0;
$lastPSDL = 0.0; $lastPSDL = 0.0;
$Eev = 0.0; $Eev = 0.0;
$Esdl = 0.0; $Esdl = 0.0;
} }
$dtH = ($now - $lastTs) / 3600.0; // Stunden
// dt in Sekunden (Float) und Stunden
$dtSec = $now - $lastTs;
if ($dtSec < 0.0) $dtSec = 0.0;
// Sicherheitskappe bei Aussetzern (optional: z.B. max 10s)
if ($dtSec > 10.0) $dtSec = 10.0;
$dtH = $dtSec / 3600.0;
if ($dtH < 0) $dtH = 0.0; if ($dtH < 0) $dtH = 0.0;
if ($dtH > 1.0) $dtH = 1.0; // Sicherheitskappe if ($dtH > 1.0) $dtH = 1.0; // Sicherheitskappe
$calc = [ $calc = [
"inputs" => $cache["inputs"] ?? [], "inputs" => $cache["inputs"] ?? [],
"batteries" => [], "batteries" => [],
"total" => [] "total" => []
]; ];
// ===================== // =====================
// Summen // Summen
// ===================== // =====================
@@ -142,60 +103,45 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
$evDisKW_ges = 0.0; $evDisKW_ges = 0.0;
$sdlChKW_ges = 0.0; $sdlChKW_ges = 0.0;
$evChKW_ges = 0.0; $evChKW_ges = 0.0;
$real_kWh_ev_ges = 0.0; $real_kWh_ev_ges = 0.0;
$real_kWh_sdl_ges = 0.0; $real_kWh_sdl_ges = 0.0;
$SDL_kWh_ges = 0.0; $SDL_kWh_ges = 0.0;
$EV_kWh_ges = 0.0; $EV_kWh_ges = 0.0;
$totalCapKWh = 0.0; $totalCapKWh = 0.0;
// Für Reset bei SoC=50% (mehrere Batterien): kapazitätsgewichteter Durchschnitt // Für Reset bei SoC=50% (mehrere Batterien): kapazitätsgewichteter Durchschnitt
$socCapSum = 0.0; $socCapSum = 0.0;
$socWeighted = 0.0; $socWeighted = 0.0;
foreach ($cache["bats"] as $i => $c) { foreach ($cache["bats"] as $i => $c) {
$capKWh = (float)($c["capKWh"] ?? 0.0); $capKWh = (float)($c["capKWh"] ?? 0.0);
if ($capKWh <= 0.0) { if ($capKWh <= 0.0) {
continue; continue;
} }
// dynamisch: SoC lesen // dynamisch: SoC lesen
$socVarId = (int)($c["socVarId"] ?? 0); $socVarId = (int)($c["socVarId"] ?? 0);
$socPct = $this->ReadSocPercent($socVarId); $socPct = $this->ReadSocPercent($socVarId);
$real_kWh = $capKWh / 100.0 * $socPct; $real_kWh = $capKWh / 100.0 * $socPct;
// SoC für Reset mitteln (gewichtet) // SoC für Reset mitteln (gewichtet)
$socWeighted += $socPct * $capKWh; $socWeighted += $socPct * $capKWh;
$socCapSum += $capKWh; $socCapSum += $capKWh;
// vorkalkuliert: // vorkalkuliert:
$typ = (string)($c["typ"] ?? ("Bat " . ($i + 1))); $typ = (string)($c["typ"] ?? ("Bat " . ($i + 1)));
$underKWh = (float)($c["underKWh"] ?? 0.0); $underKWh = (float)($c["underKWh"] ?? 0.0);
$upKWh = (float)($c["upKWh"] ?? 0.0); $upKWh = (float)($c["upKWh"] ?? 0.0);
$SDL_kWh = (float)($c["SDL_kWh_total"] ?? 0.0); $SDL_kWh = (float)($c["SDL_kWh_total"] ?? 0.0);
$EV_kWh = (float)($c["EV_kWh_total"] ?? 0.0); $EV_kWh = (float)($c["EV_kWh_total"] ?? 0.0);
$sdlShareKW_laden = (float)($c["sdlShareKW_laden"] ?? 0.0); $sdlShareKW_laden = (float)($c["sdlShareKW_laden"] ?? 0.0);
$sdlShareKW_entladen = (float)($c["sdlShareKW_entladen"] ?? 0.0); $sdlShareKW_entladen = (float)($c["sdlShareKW_entladen"] ?? 0.0);
$evShareKW_laden = (float)($c["evShareKW_laden"] ?? 0.0); $evShareKW_laden = (float)($c["evShareKW_laden"] ?? 0.0);
$evShareKW_entladen = (float)($c["evShareKW_entladen"] ?? 0.0); $evShareKW_entladen = (float)($c["evShareKW_entladen"] ?? 0.0);
// Defaults // Defaults
$EV_SOC = 0.0; $EV_SOC = 0.0;
$SDL_SOC = 0.0; $SDL_SOC = 0.0;
$sdlDisKW = 0.0; $evDisKW = 0.0; $sdlDisKW = 0.0; $evDisKW = 0.0;
$sdlChKW = 0.0; $evChKW = 0.0; $sdlChKW = 0.0; $evChKW = 0.0;
$real_kWh_ev = 0.0; $real_kWh_ev = 0.0;
$real_kWh_sdl = 0.0; $real_kWh_sdl = 0.0;
// --- 3 Fälle --- // --- 3 Fälle ---
if ($underKWh <= $real_kWh && $upKWh >= $real_kWh) { if ($underKWh <= $real_kWh && $upKWh >= $real_kWh) {
// SDL_SOC im Fenster dynamisch (0..100) // SDL_SOC im Fenster dynamisch (0..100)
$win = ($upKWh - $underKWh); $win = ($upKWh - $underKWh);
if ($win > 0.0) { if ($win > 0.0) {
@@ -204,7 +150,6 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
$SDL_SOC = 0.0; $SDL_SOC = 0.0;
} }
$SDL_SOC = is_finite($SDL_SOC) ? max(0.0, min(100.0, $SDL_SOC)) : 0.0; $SDL_SOC = is_finite($SDL_SOC) ? max(0.0, min(100.0, $SDL_SOC)) : 0.0;
// EV_SOC im Fenster dynamisch // EV_SOC im Fenster dynamisch
if ($EV_kWh > 0.0) { if ($EV_kWh > 0.0) {
$EV_SOC = 100.0 * ($real_kWh - $underKWh) / $EV_kWh; $EV_SOC = 100.0 * ($real_kWh - $underKWh) / $EV_kWh;
@@ -212,54 +157,40 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
$EV_SOC = 0.0; $EV_SOC = 0.0;
} }
$EV_SOC = is_finite($EV_SOC) ? max(0.0, min(100.0, $EV_SOC)) : 0.0; $EV_SOC = is_finite($EV_SOC) ? max(0.0, min(100.0, $EV_SOC)) : 0.0;
$sdlDisKW = $sdlShareKW_entladen; $sdlDisKW = $sdlShareKW_entladen;
$evDisKW = $evShareKW_entladen; $evDisKW = $evShareKW_entladen;
$sdlChKW = $sdlShareKW_laden; $sdlChKW = $sdlShareKW_laden;
$evChKW = $evShareKW_laden; $evChKW = $evShareKW_laden;
$real_kWh_ev = $real_kWh - $underKWh; $real_kWh_ev = $real_kWh - $underKWh;
$real_kWh_sdl = $underKWh; $real_kWh_sdl = $underKWh;
} elseif ($upKWh < $real_kWh) { } elseif ($upKWh < $real_kWh) {
$EV_SOC = 100.0; $EV_SOC = 100.0;
$den1 = ($capKWh - $real_kWh + $underKWh); $den1 = ($capKWh - $real_kWh + $underKWh);
$den2 = (2.0 * $underKWh); $den2 = (2.0 * $underKWh);
if ($den1 > 0.0 && $den2 > 0.0) { if ($den1 > 0.0 && $den2 > 0.0) {
$SDL_SOC = min(100.0, ($den1 / $den2) * 100.0); $SDL_SOC = min(100.0, ($den1 / $den2) * 100.0);
} else { } else {
$SDL_SOC = 0.0; $SDL_SOC = 0.0;
} }
$SDL_SOC = is_finite($SDL_SOC) ? max(0.0, min(100.0, $SDL_SOC)) : 0.0; $SDL_SOC = is_finite($SDL_SOC) ? max(0.0, min(100.0, $SDL_SOC)) : 0.0;
$sdlDisKW = $sdlShareKW_entladen; $sdlDisKW = $sdlShareKW_entladen;
$evDisKW = $evShareKW_entladen; $evDisKW = $evShareKW_entladen;
$sdlChKW = $sdlShareKW_laden; $sdlChKW = $sdlShareKW_laden;
$evChKW = 0.0; $evChKW = 0.0;
$real_kWh_ev = $capKWh - ($capKWh - $upKWh + $underKWh); $real_kWh_ev = $capKWh - ($capKWh - $upKWh + $underKWh);
$real_kWh_sdl = ($capKWh - $upKWh + $underKWh) - ($capKWh - $real_kWh); $real_kWh_sdl = ($capKWh - $upKWh + $underKWh) - ($capKWh - $real_kWh);
} elseif ($underKWh > $real_kWh) { } elseif ($underKWh > $real_kWh) {
$EV_SOC = 0.0; $EV_SOC = 0.0;
$den = $upKWh + $underKWh; $den = $upKWh + $underKWh;
$SDL_SOC = ($den > 0.0) ? ($real_kWh * 100.0 / $den) : 0.0; $SDL_SOC = ($den > 0.0) ? ($real_kWh * 100.0 / $den) : 0.0;
$SDL_SOC = is_finite($SDL_SOC) ? max(0.0, min(100.0, $SDL_SOC)) : 0.0; $SDL_SOC = is_finite($SDL_SOC) ? max(0.0, min(100.0, $SDL_SOC)) : 0.0;
$sdlDisKW = $sdlShareKW_entladen; $sdlDisKW = $sdlShareKW_entladen;
$evDisKW = 0.0; $evDisKW = 0.0;
$sdlChKW = $sdlShareKW_laden; $sdlChKW = $sdlShareKW_laden;
$evChKW = $evShareKW_laden; $evChKW = $evShareKW_laden;
$real_kWh_ev = 0.0; $real_kWh_ev = 0.0;
$real_kWh_sdl = $real_kWh; $real_kWh_sdl = $real_kWh;
} }
// Null/Full // Null/Full
if ($real_kWh <= 0.0) { if ($real_kWh <= 0.0) {
$sdlDisKW = 0.0; $sdlDisKW = 0.0;
@@ -270,60 +201,45 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
$real_kWh_ev = $EV_kWh; $real_kWh_ev = $EV_kWh;
$real_kWh_sdl = $SDL_kWh; $real_kWh_sdl = $SDL_kWh;
} }
$real_kWh_ev = max(0.0, $real_kWh_ev); $real_kWh_ev = max(0.0, $real_kWh_ev);
$real_kWh_sdl = max(0.0, $real_kWh_sdl); $real_kWh_sdl = max(0.0, $real_kWh_sdl);
// Summen // Summen
$totalCapKWh += $capKWh; $totalCapKWh += $capKWh;
$sdlDisKW_ges += $sdlDisKW; $sdlDisKW_ges += $sdlDisKW;
$evDisKW_ges += $evDisKW; $evDisKW_ges += $evDisKW;
$sdlChKW_ges += $sdlChKW; $sdlChKW_ges += $sdlChKW;
$evChKW_ges += $evChKW; $evChKW_ges += $evChKW;
$real_kWh_ev_ges += $real_kWh_ev; $real_kWh_ev_ges += $real_kWh_ev;
$real_kWh_sdl_ges += $real_kWh_sdl; $real_kWh_sdl_ges += $real_kWh_sdl;
$SDL_kWh_ges += $SDL_kWh; $SDL_kWh_ges += $SDL_kWh;
$EV_kWh_ges += $EV_kWh; $EV_kWh_ges += $EV_kWh;
$calc["batteries"][] = [ $calc["batteries"][] = [
"idx" => $c["idx"] ?? $i, "idx" => $c["idx"] ?? $i,
"typ" => $typ, "typ" => $typ,
"SoC_varId" => $socVarId, "SoC_varId" => $socVarId,
"SoC_pct" => round($socPct, 3), "SoC_pct" => round($socPct, 3),
"Effektive kWh" => round($real_kWh, 3), "Effektive kWh" => round($real_kWh, 3),
"EV_SOC" => round($EV_SOC, 3), "EV_SOC" => round($EV_SOC, 3),
"SDL_SOC" => round($SDL_SOC, 3), "SDL_SOC" => round($SDL_SOC, 3),
"EV_kWh" => round($real_kWh_ev, 3), "EV_kWh" => round($real_kWh_ev, 3),
"SDL_kWh" => round($real_kWh_sdl, 3), "SDL_kWh" => round($real_kWh_sdl, 3),
"under_grenze_kWh" => round($underKWh, 3), "under_grenze_kWh" => round($underKWh, 3),
"up_grenze_kWh" => round($upKWh, 3), "up_grenze_kWh" => round($upKWh, 3),
"SDL_Charge_kW" => round($sdlChKW, 3), "SDL_Charge_kW" => round($sdlChKW, 3),
"SDL_Discharge_kW" => round($sdlDisKW, 3), "SDL_Discharge_kW" => round($sdlDisKW, 3),
"EV_Charge_kW" => round($evChKW, 3), "EV_Charge_kW" => round($evChKW, 3),
"EV_Discharge_kW" => round($evDisKW, 3), "EV_Discharge_kW" => round($evDisKW, 3),
]; ];
} }
// ===================== // =====================
// Nach foreach: Durchschnitts-SoC + Reset-Logik // Nach foreach: Durchschnitts-SoC + Reset-Logik
// ===================== // =====================
$socAvg = ($socCapSum > 0.0) ? ($socWeighted / $socCapSum) : 0.0; $socAvg = ($socCapSum > 0.0) ? ($socWeighted / $socCapSum) : 0.0;
$resetTarget = 50.0; $resetTarget = 50.0;
$resetTol = 0.5; // bei 2s Update: 0.2..0.5 je nach SoC-Auflösung $resetTol = 0.5; // bei 2s Update: 0.2..0.5 je nach SoC-Auflösung
$inWindow = (abs($socAvg - $resetTarget) <= $resetTol); $inWindow = (abs($socAvg - $resetTarget) <= $resetTol);
$armedStr = $this->GetBufferSafe("Int_ResetArmed"); $armedStr = $this->GetBufferSafe("Int_ResetArmed");
$armed = ($armedStr === "") ? true : ($armedStr === "1"); $armed = ($armedStr === "") ? true : ($armedStr === "1");
$doReset = false; $doReset = false;
if ($armed && $inWindow) { if ($armed && $inWindow) {
$doReset = true; $doReset = true;
@@ -333,14 +249,12 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
$armed = true; $armed = true;
} }
$this->SetBuffer("Int_ResetArmed", $armed ? "1" : "0"); $this->SetBuffer("Int_ResetArmed", $armed ? "1" : "0");
// ===================== // =====================
// EV-Zone (oben/unten) erkennen und EV-Konto beim Zonenwechsel hart setzen // EV-Zone (oben/unten) erkennen und EV-Konto beim Zonenwechsel hart setzen
// Ziel: Wenn obere Grenze erreicht -> SoC_EV = 100% (Eev = EV_total) // Ziel: Wenn obere Grenze erreicht -> SoC_EV = 100% (Eev = EV_total)
// Wenn untere Grenze erreicht -> SoC_EV = 0% (Eev = 0) // Wenn untere Grenze erreicht -> SoC_EV = 0% (Eev = 0)
// ===================== // =====================
$epsKWh = 0.001; $epsKWh = 0.001;
// ZoneNow aus EV-Referenz ableiten: // ZoneNow aus EV-Referenz ableiten:
// -1 = EV leer (untere Zone), 0 = Fenster, +1 = EV voll (obere Zone) // -1 = EV leer (untere Zone), 0 = Fenster, +1 = EV voll (obere Zone)
$zoneNow = 0; $zoneNow = 0;
@@ -349,11 +263,9 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
} elseif ($EV_kWh_ges > 0.0 && $real_kWh_ev_ges >= ($EV_kWh_ges - $epsKWh)) { } elseif ($EV_kWh_ges > 0.0 && $real_kWh_ev_ges >= ($EV_kWh_ges - $epsKWh)) {
$zoneNow = 1; $zoneNow = 1;
} }
// Vorherige Zone aus Buffer // Vorherige Zone aus Buffer
$zonePrevStr = $this->GetBufferSafe("EV_Zone"); $zonePrevStr = $this->GetBufferSafe("EV_Zone");
$zonePrev = ($zonePrevStr === "") ? $zoneNow : (int)$zonePrevStr; $zonePrev = ($zonePrevStr === "") ? $zoneNow : (int)$zonePrevStr;
// Nur beim Zonenwechsel hart setzen (Edge-Trigger) // Nur beim Zonenwechsel hart setzen (Edge-Trigger)
if ($zoneNow !== $zonePrev) { if ($zoneNow !== $zonePrev) {
if ($zoneNow === 1) { if ($zoneNow === 1) {
@@ -364,101 +276,79 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
$Eev = 0.0; $Eev = 0.0;
} }
} }
// Zone speichern // Zone speichern
$this->SetBuffer("EV_Zone", (string)$zoneNow); $this->SetBuffer("EV_Zone", (string)$zoneNow);
// =================================================== // ===================================================
// Integrator: NUR integrieren wenn Soll != 0W // Integrator: NUR integrieren wenn Soll != 0W
// Angleichen ist raus: wir setzen bei Soll=0 hart auf Referenz // Angleichen ist raus: wir setzen bei Soll=0 hart auf Referenz
// =================================================== // ===================================================
$pEvSoll = (float)GetValue($this->GetIDForIdent("Nennleistung_Soll_EV")); $pEvSoll = (float)GetValue($this->GetIDForIdent("Nennleistung_Soll_EV"));
$pSdlSoll = (float)GetValue($this->GetIDForIdent("Nennleistung_Soll_SDL")); $pSdlSoll = (float)GetValue($this->GetIDForIdent("Nennleistung_Soll_SDL"));
$eps = 1.0; $eps = 1.0;
$evActive = (abs($pEvSoll) > $eps); $evActive = (abs($pEvSoll) > $eps);
$sdlActive = (abs($pSdlSoll) > $eps); $sdlActive = (abs($pSdlSoll) > $eps);
// Initialisierung beim ersten Mal // Initialisierung beim ersten Mal
if ($this->GetBufferSafe("Int_Init") !== "1") { if ($this->GetBufferSafe("Int_Init") !== "1") {
$Eev = $real_kWh_ev_ges; $Eev = $real_kWh_ev_ges;
$Esdl = $real_kWh_sdl_ges; $Esdl = $real_kWh_sdl_ges;
$this->SetBuffer("Int_Init", "1"); $this->SetBuffer("Int_Init", "1");
} }
// Reset bei SoC~50%: hart auf Referenz (du akzeptierst Sprung) // Reset bei SoC~50%: hart auf Referenz (du akzeptierst Sprung)
if ($doReset) { if ($doReset) {
$Eev = $real_kWh_ev_ges; $Eev = $real_kWh_ev_ges;
$Esdl = $real_kWh_sdl_ges; $Esdl = $real_kWh_sdl_ges;
} }
// Integration nur wenn aktiv, sonst hart auf Referenz // Integration nur wenn aktiv, sonst hart auf Referenz
if ($evActive) { if ($evActive) {
$Eev += (($lastPEV / 1000.0) * $dtH); $Eev += (($lastPEV / 1000.0) * $dtH);
} else { } else {
$Eev = $real_kWh_ev_ges; $Eev = $real_kWh_ev_ges;
} }
if ($sdlActive) { if ($sdlActive) {
$Esdl += (($lastPSDL / 1000.0) * $dtH); $Esdl += (($lastPSDL / 1000.0) * $dtH);
} else { } else {
$Esdl = $real_kWh_sdl_ges; $Esdl = $real_kWh_sdl_ges;
} }
// Clamp: Grenzen strikt einhalten (SDL reserviert!) // Clamp: Grenzen strikt einhalten (SDL reserviert!)
$Eev = ($EV_kWh_ges > 0.0) ? max(0.0, min($EV_kWh_ges, $Eev)) : 0.0; $Eev = ($EV_kWh_ges > 0.0) ? max(0.0, min($EV_kWh_ges, $Eev)) : 0.0;
$Esdl = ($SDL_kWh_ges > 0.0) ? max(0.0, min($SDL_kWh_ges, $Esdl)) : 0.0; $Esdl = ($SDL_kWh_ges > 0.0) ? max(0.0, min($SDL_kWh_ges, $Esdl)) : 0.0;
// Prozentwerte aus den Konten // Prozentwerte aus den Konten
$evPosPct = ($EV_kWh_ges > 0.0) ? ($Eev / $EV_kWh_ges * 100.0) : 0.0; $evPosPct = ($EV_kWh_ges > 0.0) ? ($Eev / $EV_kWh_ges * 100.0) : 0.0;
$sdlPosPct = ($SDL_kWh_ges > 0.0) ? ($Esdl / $SDL_kWh_ges * 100.0) : 0.0; $sdlPosPct = ($SDL_kWh_ges > 0.0) ? ($Esdl / $SDL_kWh_ges * 100.0) : 0.0;
// Output setzen // Output setzen
$this->SetIdentValue("SDL_Pos", round($sdlPosPct, 3)); $this->SetIdentValue("SDL_Pos", round($sdlPosPct, 3));
$this->SetIdentValue("SoC_EV", round($evPosPct, 3)); $this->SetIdentValue("SoC_EV", round($evPosPct, 3));
// Maximalleistungen setzen (wie gehabt) // Maximalleistungen setzen (wie gehabt)
$this->SetIdentValue("P_SDL_laden", round($sdlChKW_ges * 1000.0, 0)); $this->SetIdentValue("P_SDL_laden", round($sdlChKW_ges * 1000.0, 0));
$this->SetIdentValue("P_SDL_entladen", round($sdlDisKW_ges * 1000.0, 0)); $this->SetIdentValue("P_SDL_entladen", round($sdlDisKW_ges * 1000.0, 0));
$this->SetIdentValue("P_EV_laden", round($evChKW_ges * 1000.0, 0)); $this->SetIdentValue("P_EV_laden", round($evChKW_ges * 1000.0, 0));
$this->SetIdentValue("P_EV_entladen", round($evDisKW_ges * 1000.0, 0)); $this->SetIdentValue("P_EV_entladen", round($evDisKW_ges * 1000.0, 0));
$calc["total"] = [ $calc["total"] = [
"SDL_SoC_pct" => round($sdlPosPct, 3), "SDL_SoC_pct" => round($sdlPosPct, 3),
"EV_SoC_pct" => round($evPosPct, 3), "EV_SoC_pct" => round($evPosPct, 3),
"SDL_kWh_total" => round($SDL_kWh_ges, 3), "SDL_kWh_total" => round($SDL_kWh_ges, 3),
"EV_kWh_total" => round($EV_kWh_ges, 3), "EV_kWh_total" => round($EV_kWh_ges, 3),
"SDL_Charge_kW" => round($sdlChKW_ges, 3), "SDL_Charge_kW" => round($sdlChKW_ges, 3),
"SDL_Discharge_kW" => round($sdlDisKW_ges, 3), "SDL_Discharge_kW" => round($sdlDisKW_ges, 3),
"EV_Charge_kW" => round($evChKW_ges, 3), "EV_Charge_kW" => round($evChKW_ges, 3),
"EV_Discharge_kW" => round($evDisKW_ges, 3), "EV_Discharge_kW" => round($evDisKW_ges, 3),
"totalCap_kWh" => round($totalCapKWh, 3), "totalCap_kWh" => round($totalCapKWh, 3),
"socAvg" => round($socAvg, 3), "socAvg" => round($socAvg, 3),
"doReset" => $doReset ? 1 : 0 "doReset" => $doReset ? 1 : 0
]; ];
$this->SetIdentValue("CalcJSON", json_encode($calc, JSON_PRETTY_PRINT)); $this->SetIdentValue("CalcJSON", json_encode($calc, JSON_PRETTY_PRINT));
// Setpoints schreiben // Setpoints schreiben
$this->ApplySetpoints(); $this->ApplySetpoints();
// ================================== // ==================================
// Integrator: neue LastP für nächstes Intervall speichern // Integrator: neue LastP für nächstes Intervall speichern
// ================================== // ==================================
$aktEV = (float)GetValue($this->GetIDForIdent("Aktuelle_Leistung_EV")); $aktEV = (float)GetValue($this->GetIDForIdent("Aktuelle_Leistung_EV"));
$aktSDL = (float)GetValue($this->GetIDForIdent("Aktuelle_Leistung_SDL")); $aktSDL = (float)GetValue($this->GetIDForIdent("Aktuelle_Leistung_SDL"));
$this->SetBuffer("Int_LastP_EV_W", (string)$aktEV); $this->SetBuffer("Int_LastP_EV_W", (string)$aktEV);
$this->SetBuffer("Int_LastP_SDL_W", (string)$aktSDL); $this->SetBuffer("Int_LastP_SDL_W", (string)$aktSDL);
$this->SetBuffer("Int_LastTs", (string)$now); $this->SetBuffer("Int_LastTs", (string)$now);
$this->SetBuffer("Int_E_EV_kWh", (string)$Eev); $this->SetBuffer("Int_E_EV_kWh", (string)$Eev);
$this->SetBuffer("Int_E_SDL_kWh", (string)$Esdl); $this->SetBuffer("Int_E_SDL_kWh", (string)$Esdl);
} catch (Throwable $e) { } catch (Throwable $e) {
$this->SendDebug("Update ERROR", $e->getMessage() . " @ " . $e->getFile() . ":" . $e->getLine(), 0); $this->SendDebug("Update ERROR", $e->getMessage() . " @ " . $e->getFile() . ":" . $e->getLine(), 0);
$this->WriteAllZero("Exception: " . $e->getMessage()); $this->WriteAllZero("Exception: " . $e->getMessage());
@@ -466,7 +356,6 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
IPS_SemaphoreLeave($semKey); IPS_SemaphoreLeave($semKey);
} }
} }
private function BuildBatteryCache(bool $force): void private function BuildBatteryCache(bool $force): void
{ {
$batteriesRaw = $this->ReadPropertyString("Batteries"); $batteriesRaw = $this->ReadPropertyString("Batteries");
@@ -474,28 +363,23 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
$sdlTotalW_laden = max(0, (int)$this->ReadPropertyInteger("SDL_Leistung_Laden")); $sdlTotalW_laden = max(0, (int)$this->ReadPropertyInteger("SDL_Leistung_Laden"));
$sdlTotalW_entladen = max(0, (int)$this->ReadPropertyInteger("SDL_Leistung_Entladen")); $sdlTotalW_entladen = max(0, (int)$this->ReadPropertyInteger("SDL_Leistung_Entladen"));
$hours = self::HOURS; $hours = self::HOURS;
$hash = md5(json_encode([ $hash = md5(json_encode([
"Batteries" => $batteriesRaw, "Batteries" => $batteriesRaw,
"SDL_W_Laden" => $sdlTotalW_laden, "SDL_W_Laden" => $sdlTotalW_laden,
"SDL_W_Entladen" => $sdlTotalW_entladen, "SDL_W_Entladen" => $sdlTotalW_entladen,
"hours" => $hours "hours" => $hours
])); ]));
$oldHash = $this->GetBufferSafe("BatCacheHash"); $oldHash = $this->GetBufferSafe("BatCacheHash");
if (!$force && $oldHash === $hash) { if (!$force && $oldHash === $hash) {
return; return;
} }
$batteries = json_decode($batteriesRaw, true); $batteries = json_decode($batteriesRaw, true);
if (!is_array($batteries)) $batteries = []; if (!is_array($batteries)) $batteries = [];
$sumBatPowerW = 0.0; $sumBatPowerW = 0.0;
foreach ($batteries as $b) { foreach ($batteries as $b) {
$p = (float)($b["powerbat"] ?? 0); $p = (float)($b["powerbat"] ?? 0);
if ($p > 0) $sumBatPowerW += $p; if ($p > 0) $sumBatPowerW += $p;
} }
$cache = [ $cache = [
"inputs" => [ "inputs" => [
"SDL_Leistung_W_laden" => $sdlTotalW_laden, "SDL_Leistung_W_laden" => $sdlTotalW_laden,
@@ -505,93 +389,70 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
], ],
"bats" => [] "bats" => []
]; ];
if ($sumBatPowerW <= 0.0) { if ($sumBatPowerW <= 0.0) {
$this->SetBuffer("BatCacheHash", $hash); $this->SetBuffer("BatCacheHash", $hash);
$this->SetBuffer("BatCacheJSON", json_encode($cache)); $this->SetBuffer("BatCacheJSON", json_encode($cache));
$this->SendDebug("Cache", "sumBatPowerW=0 -> empty cache", 0); $this->SendDebug("Cache", "sumBatPowerW=0 -> empty cache", 0);
return; return;
} }
$sumBatPowerkW = $sumBatPowerW / 1000.0; $sumBatPowerkW = $sumBatPowerW / 1000.0;
//$sdlTotalkW = $sdlTotalW / 1000.0; //$sdlTotalkW = $sdlTotalW / 1000.0;
$sdlTotalkW_laden = $sdlTotalW_laden / 1000.0; $sdlTotalkW_laden = $sdlTotalW_laden / 1000.0;
$sdlTotalkW_entladen = $sdlTotalW_entladen / 1000.0; $sdlTotalkW_entladen = $sdlTotalW_entladen / 1000.0;
foreach ($batteries as $idx => $b) { foreach ($batteries as $idx => $b) {
$pBatW = max(0.0, (float)($b["powerbat"] ?? 0)); $pBatW = max(0.0, (float)($b["powerbat"] ?? 0));
$pBatkW = $pBatW / 1000.0; $pBatkW = $pBatW / 1000.0;
$capKWh = max(0.0, (float)($b["capazity"] ?? 0)); $capKWh = max(0.0, (float)($b["capazity"] ?? 0));
if ($capKWh <= 0.0) continue; if ($capKWh <= 0.0) continue;
$socVarId = (int)($b["soc"] ?? 0); $socVarId = (int)($b["soc"] ?? 0);
$typ = (string)($b["typ"] ?? ("Bat " . ($idx + 1))); $typ = (string)($b["typ"] ?? ("Bat " . ($idx + 1)));
// Mit laden und entladen unterschiedlich // Mit laden und entladen unterschiedlich
//---------------------------------------------------- //----------------------------------------------------
$sdlShareKW_laden = ($sumBatPowerkW > 0.0) ? ($sdlTotalkW_laden / $sumBatPowerkW * $pBatkW) : 0.0; $sdlShareKW_laden = ($sumBatPowerkW > 0.0) ? ($sdlTotalkW_laden / $sumBatPowerkW * $pBatkW) : 0.0;
$evShareKW_laden = $pBatkW - $sdlShareKW_laden; $evShareKW_laden = $pBatkW - $sdlShareKW_laden;
$upKWh = $capKWh - $sdlShareKW_laden * 0.5; $upKWh = $capKWh - $sdlShareKW_laden * 0.5;
$sdlShareKW_entladen = ($sumBatPowerkW > 0.0) ? ($sdlTotalkW_entladen / $sumBatPowerkW * $pBatkW) : 0.0; $sdlShareKW_entladen = ($sumBatPowerkW > 0.0) ? ($sdlTotalkW_entladen / $sumBatPowerkW * $pBatkW) : 0.0;
$evShareKW_entladen = $pBatkW - $sdlShareKW_entladen; $evShareKW_entladen = $pBatkW - $sdlShareKW_entladen;
$underKWh = $sdlShareKW_entladen * 0.5; $underKWh = $sdlShareKW_entladen * 0.5;
$SDL_kWh = $underKWh + ($capKWh -$upKWh); $SDL_kWh = $underKWh + ($capKWh -$upKWh);
$EV_kWh = $capKWh - $SDL_kWh; $EV_kWh = $capKWh - $SDL_kWh;
//---------------------------------------------------- //----------------------------------------------------
$cache["bats"][] = [ $cache["bats"][] = [
"idx" => $idx, "idx" => $idx,
"typ" => $typ, "typ" => $typ,
"socVarId" => $socVarId, "socVarId" => $socVarId,
"capKWh" => $capKWh, "capKWh" => $capKWh,
"pBatW" => $pBatW, "pBatW" => $pBatW,
"sdlShareKW_laden" => $sdlShareKW_laden, "sdlShareKW_laden" => $sdlShareKW_laden,
"sdlShareKW_entladen" => $sdlShareKW_entladen, "sdlShareKW_entladen" => $sdlShareKW_entladen,
"evShareKW_laden" => $evShareKW_laden, "evShareKW_laden" => $evShareKW_laden,
"evShareKW_entladen" => $evShareKW_entladen, "evShareKW_entladen" => $evShareKW_entladen,
"underKWh" => $underKWh, "underKWh" => $underKWh,
"upKWh" => $upKWh, "upKWh" => $upKWh,
"SDL_kWh_total" => $SDL_kWh, "SDL_kWh_total" => $SDL_kWh,
"EV_kWh_total" => $EV_kWh "EV_kWh_total" => $EV_kWh
]; ];
} }
$this->SetBuffer("BatCacheHash", $hash); $this->SetBuffer("BatCacheHash", $hash);
$this->SetBuffer("BatCacheJSON", json_encode($cache)); $this->SetBuffer("BatCacheJSON", json_encode($cache));
$this->SendDebug("Cache", "Battery cache rebuilt (" . count($cache["bats"]) . " bats)", 0); $this->SendDebug("Cache", "Battery cache rebuilt (" . count($cache["bats"]) . " bats)", 0);
} }
private function GetBufferSafe(string $name): string private function GetBufferSafe(string $name): string
{ {
$v = $this->GetBuffer($name); $v = $this->GetBuffer($name);
return is_string($v) ? $v : ""; return is_string($v) ? $v : "";
} }
private function WriteAllZero(string $reason): void private function WriteAllZero(string $reason): void
{ {
$this->SetIdentValue("SDL_Pos", 0.0); $this->SetIdentValue("SDL_Pos", 0.0);
$this->SetIdentValue("SoC_EV", 0.0); $this->SetIdentValue("SoC_EV", 0.0);
$this->SetIdentValue("P_SDL_laden", 0.0); $this->SetIdentValue("P_SDL_laden", 0.0);
$this->SetIdentValue("P_SDL_entladen", 0.0); $this->SetIdentValue("P_SDL_entladen", 0.0);
$this->SetIdentValue("P_EV_laden", 0.0); $this->SetIdentValue("P_EV_laden", 0.0);
$this->SetIdentValue("P_EV_entladen", 0.0); $this->SetIdentValue("P_EV_entladen", 0.0);
$this->SetIdentValue("CalcJSON", json_encode(["error" => $reason], JSON_PRETTY_PRINT)); $this->SetIdentValue("CalcJSON", json_encode(["error" => $reason], JSON_PRETTY_PRINT));
} }
private function SetIdentValue(string $ident, $value): void private function SetIdentValue(string $ident, $value): void
{ {
$id = @$this->GetIDForIdent($ident); $id = @$this->GetIDForIdent($ident);
@@ -601,48 +462,38 @@ class Bat_EV_SDL_V3_Beta extends IPSModule
} }
SetValue($id, $value); SetValue($id, $value);
} }
private function ReadSocPercent(int $varId): float private function ReadSocPercent(int $varId): float
{ {
// Falls jemand statt Variable direkt 0..100 einträgt // Falls jemand statt Variable direkt 0..100 einträgt
if ($varId >= 0 && $varId <= 100 && !IPS_VariableExists($varId)) { if ($varId >= 0 && $varId <= 100 && !IPS_VariableExists($varId)) {
return (float)$varId; return (float)$varId;
} }
if ($varId <= 0 || !IPS_VariableExists($varId)) { if ($varId <= 0 || !IPS_VariableExists($varId)) {
return 0.0; return 0.0;
} }
$v = GetValue($varId); $v = GetValue($varId);
if (!is_numeric($v)) { if (!is_numeric($v)) {
return 0.0; return 0.0;
} }
$soc = (float)$v; $soc = (float)$v;
if ($soc < 0.0) $soc = 0.0; if ($soc < 0.0) $soc = 0.0;
if ($soc > 100.0) $soc = 100.0; if ($soc > 100.0) $soc = 100.0;
return $soc; return $soc;
} }
public function ApplySetpoints(): void public function ApplySetpoints(): void
{ {
$pEvW = (float) GetValue($this->GetIDForIdent("Nennleistung_Soll_EV")); $pEvW = (float) GetValue($this->GetIDForIdent("Nennleistung_Soll_EV"));
$pSdlW = (float) GetValue($this->GetIDForIdent("Nennleistung_Soll_SDL")); $pSdlW = (float) GetValue($this->GetIDForIdent("Nennleistung_Soll_SDL"));
//Diverenz zwischen EV und SDl berechnen //Diverenz zwischen EV und SDl berechnen
// Methode für priorisierung // Methode für priorisierung
$distribution = $this->CalculateBatteryDistribution($pEvW,$pSdlW); $distribution = $this->CalculateBatteryDistribution($pEvW,$pSdlW);
$this->WriteBatteryPowerSetpoints($distribution); $this->WriteBatteryPowerSetpoints($distribution);
} }
private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
{ {
$calcJsonId = $this->GetIDForIdent("CalcJSON"); $calcJsonId = $this->GetIDForIdent("CalcJSON");
@@ -656,7 +507,6 @@ private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
} }
$calc = json_decode($rawJson, true); $calc = json_decode($rawJson, true);
$batteries = $calc['batteries'] ?? []; $batteries = $calc['batteries'] ?? [];
// --------------------------------------------------------- // ---------------------------------------------------------
// Hilfsfunktion: Verteilungslogik (Closure) // Hilfsfunktion: Verteilungslogik (Closure)
// --------------------------------------------------------- // ---------------------------------------------------------
@@ -666,18 +516,15 @@ private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
foreach ($batteries as $bat) { foreach ($batteries as $bat) {
$result[$bat['idx']] = 0.0; $result[$bat['idx']] = 0.0;
} }
if (abs($targetPower) < 0.01) { if (abs($targetPower) < 0.01) {
return $result; // Nichts zu tun return $result; // Nichts zu tun
} }
$isCharge = ($targetPower > 0); $isCharge = ($targetPower > 0);
$absPower = abs($targetPower); $absPower = abs($targetPower);
// Relevante Keys basierend auf Modus (EV oder SDL) und Richtung (Laden/Entladen) // Relevante Keys basierend auf Modus (EV oder SDL) und Richtung (Laden/Entladen)
$socKey = ($mode === 'EV') ? 'EV_SOC' : 'SDL_SOC'; $socKey = ($mode === 'EV') ? 'EV_SOC' : 'SDL_SOC';
// Achtung: JSON Limits sind in kW, wir rechnen in Watt -> * 1000 // Achtung: JSON Limits sind in kW, wir rechnen in Watt -> * 1000
$limitKey = $isCharge ? $mode . '_Charge_kW' : $mode . '_Discharge_kW'; $limitKey = $isCharge ? $mode . '_Charge_kW' : $mode . '_Discharge_kW';
// 1. Batterien vorbereiten und gruppieren nach gerundetem SoC // 1. Batterien vorbereiten und gruppieren nach gerundetem SoC
$groups = []; $groups = [];
foreach ($batteries as $bat) { foreach ($batteries as $bat) {
@@ -688,7 +535,6 @@ private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
'maxW' => $maxW 'maxW' => $maxW
]; ];
} }
// 2. Sortieren der Gruppen // 2. Sortieren der Gruppen
// Laden: Wenig SoC zuerst (ASC) -> leere füllen // Laden: Wenig SoC zuerst (ASC) -> leere füllen
// Entladen: Viel SoC zuerst (DESC) -> volle leeren // Entladen: Viel SoC zuerst (DESC) -> volle leeren
@@ -697,23 +543,18 @@ private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
} else { } else {
krsort($groups); krsort($groups);
} }
// 3. Verteilung // 3. Verteilung
$remainingNeeded = $absPower; $remainingNeeded = $absPower;
foreach ($groups as $soc => $groupBatteries) { foreach ($groups as $soc => $groupBatteries) {
if ($remainingNeeded <= 0.01) break; if ($remainingNeeded <= 0.01) break;
// Gesamte verfügbare Leistung in dieser SoC-Gruppe ermitteln // Gesamte verfügbare Leistung in dieser SoC-Gruppe ermitteln
$groupTotalCapacity = 0.0; $groupTotalCapacity = 0.0;
foreach ($groupBatteries as $gb) { foreach ($groupBatteries as $gb) {
$groupTotalCapacity += $gb['maxW']; $groupTotalCapacity += $gb['maxW'];
} }
// Wie viel können wir dieser Gruppe zuteilen? // Wie viel können wir dieser Gruppe zuteilen?
// Entweder alles was die Gruppe kann, oder den Restbedarf // Entweder alles was die Gruppe kann, oder den Restbedarf
$powerForThisGroup = min($remainingNeeded, $groupTotalCapacity); $powerForThisGroup = min($remainingNeeded, $groupTotalCapacity);
// Proportionale Aufteilung innerhalb der Gruppe // Proportionale Aufteilung innerhalb der Gruppe
// Falls Gruppe Kapazität 0 hat (Defekt/Voll), verhindern wir DivByZero // Falls Gruppe Kapazität 0 hat (Defekt/Voll), verhindern wir DivByZero
if ($groupTotalCapacity > 0) { if ($groupTotalCapacity > 0) {
@@ -723,48 +564,38 @@ private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
$result[$gb['idx']] = $assigned; $result[$gb['idx']] = $assigned;
} }
} }
$remainingNeeded -= $powerForThisGroup; $remainingNeeded -= $powerForThisGroup;
} }
// Wenn wir entladen, müssen die Werte negativ sein // Wenn wir entladen, müssen die Werte negativ sein
if (!$isCharge) { if (!$isCharge) {
foreach ($result as $idx => $val) { foreach ($result as $idx => $val) {
$result[$idx] = -$val; $result[$idx] = -$val;
} }
} }
return $result; return $result;
}; };
// --------------------------------------------------------- // ---------------------------------------------------------
// Hauptablauf // Hauptablauf
// --------------------------------------------------------- // ---------------------------------------------------------
// 1. Berechnung für EV und SDL getrennt durchführen // 1. Berechnung für EV und SDL getrennt durchführen
$evDistribution = $distributePower($pEvW, 'EV'); $evDistribution = $distributePower($pEvW, 'EV');
$sdlDistribution = $distributePower($pSdlW, 'SDL'); $sdlDistribution = $distributePower($pSdlW, 'SDL');
// 2. Ergebnisse zusammenführen und Output formatieren // 2. Ergebnisse zusammenführen und Output formatieren
$finalOutput = []; $finalOutput = [];
foreach ($batteries as $bat) { foreach ($batteries as $bat) {
$idx = $bat['idx']; $idx = $bat['idx'];
// Summe der beiden Anforderungen (kann sich gegenseitig aufheben) // Summe der beiden Anforderungen (kann sich gegenseitig aufheben)
$valEv = $evDistribution[$idx] ?? 0.0; $valEv = $evDistribution[$idx] ?? 0.0;
$valSdl = $sdlDistribution[$idx] ?? 0.0; $valSdl = $sdlDistribution[$idx] ?? 0.0;
$totalW = $valEv + $valSdl; $totalW = $valEv + $valSdl;
// Aufteilen in Charge / Discharge für das Return-Format // Aufteilen in Charge / Discharge für das Return-Format
$chargeW = 0.0; $chargeW = 0.0;
$dischargeW = 0.0; $dischargeW = 0.0;
if ($totalW > 0) { if ($totalW > 0) {
$chargeW = abs($totalW); $chargeW = abs($totalW);
} else { } else {
$dischargeW = abs($totalW); $dischargeW = abs($totalW);
} }
// JSON Objekt erstellen // JSON Objekt erstellen
$finalOutput[] = [ $finalOutput[] = [
"idx" => $idx, "idx" => $idx,
@@ -773,35 +604,26 @@ private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
"dischargeW" => round($dischargeW, 0) "dischargeW" => round($dischargeW, 0)
]; ];
} }
$batteriesRaw = json_decode($this->ReadPropertyString("Batteries")); $batteriesRaw = json_decode($this->ReadPropertyString("Batteries"));
$totalPower_ist = 0; $totalPower_ist = 0;
foreach ($batteriesRaw as $bat) { foreach ($batteriesRaw as $bat) {
$totalPower_ist += (-1)*GetValue($bat->register_bat_power); $totalPower_ist += (-1)*GetValue($bat->register_bat_power);
} }
// ---------------------------- // ----------------------------
// ALT (nicht mehr gebraucht) -> AUSKOMMENTIERT // ALT (nicht mehr gebraucht) -> AUSKOMMENTIERT
// ---------------------------- // ----------------------------
/* /*
$sumReq = (abs($pEvW) + abs($pSdlW)); $sumReq = (abs($pEvW) + abs($pSdlW));
$sumReqRel = ($pEvW + $pSdlW); $sumReqRel = ($pEvW + $pSdlW);
if($sumReq==0){ if($sumReq==0){
$this->SetValue("Aktuelle_Leistung_EV", $totalPower_ist / 2); $this->SetValue("Aktuelle_Leistung_EV", $totalPower_ist / 2);
$this->SetValue("Aktuelle_Leistung_SDL", $totalPower_ist / 2); $this->SetValue("Aktuelle_Leistung_SDL", $totalPower_ist / 2);
}else{ }else{
if($pEvW>=0){ if($pEvW>=0){
$this->SetValue("Aktuelle_Leistung_EV",((1+($totalPower_ist-$sumReqRel) / $sumReq)) * $pEvW); $this->SetValue("Aktuelle_Leistung_EV",((1+($totalPower_ist-$sumReqRel) / $sumReq)) * $pEvW);
}else{ }else{
$this->SetValue("Aktuelle_Leistung_EV",((1-($totalPower_ist-$sumReqRel) / $sumReq)) * $pEvW); $this->SetValue("Aktuelle_Leistung_EV",((1-($totalPower_ist-$sumReqRel) / $sumReq)) * $pEvW);
} }
if($pSdlW>=0){ if($pSdlW>=0){
$this->SetValue("Aktuelle_Leistung_SDL",((1+($totalPower_ist-$sumReqRel) / $sumReq)) * $pSdlW); $this->SetValue("Aktuelle_Leistung_SDL",((1+($totalPower_ist-$sumReqRel) / $sumReq)) * $pSdlW);
}else{ }else{
@@ -809,7 +631,6 @@ private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
} }
} }
*/ */
// ---------------------------- // ----------------------------
// NEU (genau deine gewünschte Logik) // NEU (genau deine gewünschte Logik)
// aktuelle - EV_SOLL = aktuelle SDL // aktuelle - EV_SOLL = aktuelle SDL
@@ -818,38 +639,26 @@ private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
/* /*
$eps = 0.01; $eps = 0.01;
$aktEV = 0.0; $aktEV = 0.0;
$aktSDL = 0.0; $aktSDL = 0.0;
// Optional: Wenn einer 0 ist -> aktiver Kanal bekommt totalPower_ist // Optional: Wenn einer 0 ist -> aktiver Kanal bekommt totalPower_ist
if (abs($pEvW) < $eps && abs($pSdlW) < $eps) { if (abs($pEvW) < $eps && abs($pSdlW) < $eps) {
$aktEV = 0.0; $aktEV = 0.0;
$aktSDL = 0.0; $aktSDL = 0.0;
} elseif (abs($pEvW) < $eps) { } elseif (abs($pEvW) < $eps) {
$aktEV = 0.0; $aktEV = 0.0;
$aktSDL = $totalPower_ist; $aktSDL = $totalPower_ist;
} elseif (abs($pSdlW) < $eps) { } elseif (abs($pSdlW) < $eps) {
$aktEV = $totalPower_ist; $aktEV = $totalPower_ist;
$aktSDL = 0.0; $aktSDL = 0.0;
} else { } else {
// Beide aktiv // Beide aktiv
$sameDirection = (($pEvW > 0 && $pSdlW > 0) || ($pEvW < 0 && $pSdlW < 0)); $sameDirection = (($pEvW > 0 && $pSdlW > 0) || ($pEvW < 0 && $pSdlW < 0));
if ($sameDirection) { if ($sameDirection) {
// Regel A: gleiche Richtung -> Ist proportional nach |Soll| aufteilen // Regel A: gleiche Richtung -> Ist proportional nach |Soll| aufteilen
$sumAbs = abs($pEvW) + abs($pSdlW); $sumAbs = abs($pEvW) + abs($pSdlW);
if ($sumAbs < $eps) { if ($sumAbs < $eps) {
// Fallback // Fallback
$aktEV = $totalPower_ist / 2.0; $aktEV = $totalPower_ist / 2.0;
@@ -858,29 +667,22 @@ private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
$aktEV = $totalPower_ist * (abs($pEvW) / $sumAbs); $aktEV = $totalPower_ist * (abs($pEvW) / $sumAbs);
$aktSDL = $totalPower_ist - $aktEV; // Summe bleibt exakt totalPower_ist $aktSDL = $totalPower_ist - $aktEV; // Summe bleibt exakt totalPower_ist
} }
} else { } else {
// Regel B: gegensätzliche Richtung -> Sollwerte anzeigen // Regel B: gegensätzliche Richtung -> Sollwerte anzeigen
$aktEV = $pEvW; $aktEV = $pEvW;
$aktSDL = $pSdlW; $aktSDL = $pSdlW;
} }
} }
$this->SetValue("Aktuelle_Leistung_EV", (float)$aktEV); $this->SetValue("Aktuelle_Leistung_EV", (float)$aktEV);
$this->SetValue("Aktuelle_Leistung_SDL", (float)$aktSDL); $this->SetValue("Aktuelle_Leistung_SDL", (float)$aktSDL);
*/ */
$eps = 0.01; $eps = 0.01;
$sumSoll = (float)($pEvW + $pSdlW); $sumSoll = (float)($pEvW + $pSdlW);
if (abs($sumSoll) > $eps) { if (abs($sumSoll) > $eps) {
// Normalfall: wir skalieren so, dass EV+SDL genau totalPower_ist ergibt // Normalfall: wir skalieren so, dass EV+SDL genau totalPower_ist ergibt
$factor = (float)($totalPower_ist / $sumSoll); $factor = (float)($totalPower_ist / $sumSoll);
$aktEV = (float)($pEvW * $factor); $aktEV = (float)($pEvW * $factor);
$aktSDL = (float)($pSdlW * $factor); $aktSDL = (float)($pSdlW * $factor);
} else { } else {
// Sonderfall: Soll hebt sich nahezu auf (sumSoll ~ 0) // Sonderfall: Soll hebt sich nahezu auf (sumSoll ~ 0)
// -> wenn Ist ebenfalls ~0: Soll anzeigen // -> wenn Ist ebenfalls ~0: Soll anzeigen
@@ -896,67 +698,51 @@ private function CalculateBatteryDistribution(float $pEvW, float $pSdlW): array
// $aktEV = (float)($totalPower_ist - $aktSDL); // $aktEV = (float)($totalPower_ist - $aktSDL);
} }
} }
$this->SetValue("Aktuelle_Leistung_EV", $aktEV); $this->SetValue("Aktuelle_Leistung_EV", $aktEV);
$this->SetValue("Aktuelle_Leistung_SDL", $aktSDL); $this->SetValue("Aktuelle_Leistung_SDL", $aktSDL);
return $finalOutput; return $finalOutput;
} }
private function WriteBatteryPowerSetpoints(array $distribution): void private function WriteBatteryPowerSetpoints(array $distribution): void
{ {
IPS_LogMessage( IPS_LogMessage(
__FUNCTION__, __FUNCTION__,
"distribution=" . json_encode($distribution, JSON_PRETTY_PRINT) "distribution=" . json_encode($distribution, JSON_PRETTY_PRINT)
); );
$batteriesCfg = json_decode($this->ReadPropertyString("Batteries"), true); $batteriesCfg = json_decode($this->ReadPropertyString("Batteries"), true);
if (!is_array($batteriesCfg) || empty($batteriesCfg)) { if (!is_array($batteriesCfg) || empty($batteriesCfg)) {
return; return;
} }
foreach ($distribution as $d) { foreach ($distribution as $d) {
$idx = (int)($d["idx"] ?? -1); $idx = (int)($d["idx"] ?? -1);
if ($idx < 0 || !isset($batteriesCfg[$idx])) { if ($idx < 0 || !isset($batteriesCfg[$idx])) {
continue; continue;
} }
$cfg = $batteriesCfg[$idx]; $cfg = $batteriesCfg[$idx];
$typ = (string)($d["typ"] ?? ($cfg["typ"] ?? ("Bat " . ($idx + 1)))); $typ = (string)($d["typ"] ?? ($cfg["typ"] ?? ("Bat " . ($idx + 1))));
// ✅ immer positiv // ✅ immer positiv
$chargeW = max(0.0, (float)($d["chargeW"] ?? 0.0)); $chargeW = max(0.0, (float)($d["chargeW"] ?? 0.0));
$dischargeW = max(0.0, (float)($d["dischargeW"] ?? 0.0)); $dischargeW = max(0.0, (float)($d["dischargeW"] ?? 0.0));
// nie gleichzeitig // nie gleichzeitig
if ($chargeW > 0.0 && $dischargeW > 0.0) { if ($chargeW > 0.0 && $dischargeW > 0.0) {
$this->SendDebug("WriteBatteryPowerSetpoints", "WARN: both >0 for $typ (idx=$idx) -> set 0", 0); $this->SendDebug("WriteBatteryPowerSetpoints", "WARN: both >0 for $typ (idx=$idx) -> set 0", 0);
$chargeW = 0.0; $chargeW = 0.0;
$dischargeW = 0.0; $dischargeW = 0.0;
} }
$this->WriteByVendorRegistersSingleMode($typ, $cfg, $chargeW, $dischargeW); $this->WriteByVendorRegistersSingleMode($typ, $cfg, $chargeW, $dischargeW);
$this->SendDebug("Setpoints", "$typ (idx=$idx) charge={$chargeW}W discharge={$dischargeW}W", 0); $this->SendDebug("Setpoints", "$typ (idx=$idx) charge={$chargeW}W discharge={$dischargeW}W", 0);
} }
} }
private function WriteByVendorRegistersSingleMode(string $typ, array $cfg, float $chargeW, float $dischargeW): void private function WriteByVendorRegistersSingleMode(string $typ, array $cfg, float $chargeW, float $dischargeW): void
{ {
$t = mb_strtolower($typ); $t = mb_strtolower($typ);
// Leistungs-Variablen // Leistungs-Variablen
$varPowerCharge = (int)($cfg["powerbat_laden"] ?? 0); $varPowerCharge = (int)($cfg["powerbat_laden"] ?? 0);
$varPowerDisch = (int)($cfg["powerbat_entladen"] ?? 0); $varPowerDisch = (int)($cfg["powerbat_entladen"] ?? 0);
// ✅ EIN Modus-Register // ✅ EIN Modus-Register
$varMode = (int)($cfg["register_ladenentladen_modus"] ?? 0); $varMode = (int)($cfg["register_ladenentladen_modus"] ?? 0);
// sichere Writer // sichere Writer
$setInt = function(int $varId, int $value): void { $setInt = function(int $varId, int $value): void {
if ($varId > 0 && IPS_VariableExists($varId)) { if ($varId > 0 && IPS_VariableExists($varId)) {
@@ -968,7 +754,6 @@ private function WriteByVendorRegistersSingleMode(string $typ, array $cfg, float
RequestAction($varId, (int)round(max(0.0, $w), 0)); // ✅ niemals negativ RequestAction($varId, (int)round(max(0.0, $w), 0)); // ✅ niemals negativ
} }
}; };
// Moduscodes je Typ // Moduscodes je Typ
$modeCharge = 1; $modeDisch = 2; // Default $modeCharge = 1; $modeDisch = 2; // Default
if (strpos($t, "goodwe") !== false) { if (strpos($t, "goodwe") !== false) {
@@ -976,49 +761,40 @@ private function WriteByVendorRegistersSingleMode(string $typ, array $cfg, float
} elseif (strpos($t, "solaredge") !== false) { } elseif (strpos($t, "solaredge") !== false) {
$modeCharge = 3; $modeDisch = 4; $modeCharge = 3; $modeDisch = 4;
} }
// ========================= // =========================
// Laden // Laden
// ========================= // =========================
if ($chargeW > 0.0) { if ($chargeW > 0.0) {
// Modus setzen (ein Register) // Modus setzen (ein Register)
$setInt($varMode, $modeCharge); $setInt($varMode, $modeCharge);
// GoodWe: nur powerbat_laden // GoodWe: nur powerbat_laden
if (strpos($t, "goodwe") !== false) { if (strpos($t, "goodwe") !== false) {
$setW($varPowerCharge, (int)$chargeW); $setW($varPowerCharge, (int)$chargeW);
$setW($varPowerDisch, (int)0); $setW($varPowerDisch, (int)0);
return; return;
} }
// SolarEdge + Default: zwei Leistungsregister // SolarEdge + Default: zwei Leistungsregister
$setW($varPowerCharge, $chargeW); $setW($varPowerCharge, $chargeW);
$setW($varPowerDisch, 0.0); $setW($varPowerDisch, 0.0);
return; return;
} }
// ========================= // =========================
// Entladen // Entladen
// ========================= // =========================
if ($dischargeW > 0.0) { if ($dischargeW > 0.0) {
// Modus setzen (ein Register) // Modus setzen (ein Register)
$setInt($varMode, $modeDisch); $setInt($varMode, $modeDisch);
// GoodWe: Entladen nutzt trotzdem powerbat_laden (immer positiv) // GoodWe: Entladen nutzt trotzdem powerbat_laden (immer positiv)
if (strpos($t, "goodwe") !== false) { if (strpos($t, "goodwe") !== false) {
$setW($varPowerCharge, (int)$dischargeW); $setW($varPowerCharge, (int)$dischargeW);
$setW($varPowerDisch, (int)0); $setW($varPowerDisch, (int)0);
return; return;
} }
// SolarEdge + Default: Entladen in powerbat_entladen // SolarEdge + Default: Entladen in powerbat_entladen
$setW($varPowerDisch, $dischargeW); $setW($varPowerDisch, $dischargeW);
$setW($varPowerCharge, 0.0); $setW($varPowerCharge, 0.0);
return; return;
} }
// ========================= // =========================
// Stop / Neutral // Stop / Neutral
// ========================= // =========================
@@ -1028,6 +804,5 @@ private function WriteByVendorRegistersSingleMode(string $typ, array $cfg, float
// $setInt($varMode, 0); // $setInt($varMode, 0);
} }
} }
?> ?>