From 969fcbcc349607b45a769226026241611fc23a94 Mon Sep 17 00:00:00 2001 From: DanielHaefliger Date: Tue, 19 May 2026 07:33:54 +0200 Subject: [PATCH] =?UTF-8?q?batterie=20und=20manager=20auf=20sch=C3=B6nen?= =?UTF-8?q?=20stand=20gebracht,=20ladestation=20hinzugef=C3=BChgt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Batterie/module.php | 747 ++++++++++++++++++------------------ Ladestation/README.md | 142 +++++++ Ladestation/form.json | 113 ++++++ Ladestation/module.json | 12 + Ladestation/module.php | 821 ++++++++++++++++++++++++++++++++++++++++ Manager/module.php | 588 ++++++++++------------------ 6 files changed, 1660 insertions(+), 763 deletions(-) create mode 100644 Ladestation/README.md create mode 100644 Ladestation/form.json create mode 100644 Ladestation/module.json create mode 100644 Ladestation/module.php diff --git a/Batterie/module.php b/Batterie/module.php index 4c385f2..6446de6 100644 --- a/Batterie/module.php +++ b/Batterie/module.php @@ -1,527 +1,512 @@ RegisterPropertyInteger("MaxBatterieleistung", 0); $this->RegisterPropertyInteger("Batteriespannung", 50); - $this->RegisterPropertyInteger("AufdasNachladen",0); - $this->RegisterPropertyInteger("MinimumEntladen",0); - $this->RegisterPropertyInteger("Batterieladezustand",0); - $this->RegisterPropertyInteger("Batteriemanagement", 1); - $this->RegisterPropertyInteger("Batterietyp", 1); - $this->RegisterPropertyInteger("MaxNachladen",0); - $this->RegisterPropertyInteger("Netzbezug", 0); - $this->RegisterPropertyInteger("AktuelleBatterieleistung", 0);// Initialisierung mit 0 + $this->RegisterPropertyInteger("AufdasNachladen", 0); + $this->RegisterPropertyInteger("MinimumEntladen", 0); + $this->RegisterPropertyInteger("Batterieladezustand", 0); + $this->RegisterPropertyInteger("Batteriemanagement", 1); + $this->RegisterPropertyInteger("Batterietyp", 1); + $this->RegisterPropertyInteger("MaxNachladen", 0); + $this->RegisterPropertyInteger("Netzbezug", 0); + $this->RegisterPropertyInteger("AktuelleBatterieleistung", 0); // Initialisierung mit 0 $this->RegisterPropertyInteger("Interval", 2); // Recheninterval - $this->RegisterVariableInteger("Batteriemanagement_Variabel","Batteriemanagement_Variabel", "",0); - $this->RegisterVariableInteger("Laden_Entladen","Laden_Entladen", "",3); - $this->RegisterVariableBoolean("Hysterese", "Hysterese","",false); - - - + $this->RegisterVariableInteger("Batteriemanagement_Variabel", "Batteriemanagement_Variabel", "", 0); + $this->RegisterVariableInteger("Laden_Entladen", "Laden_Entladen", "", 3); + $this->RegisterVariableBoolean("Hysterese", "Hysterese", "", false); // Variabeln für Kommunkation mit Manager $this->RegisterVariableInteger("Aktuelle_Leistung", "Aktuelle zugeteilte Leistung", "", 0); $this->RegisterVariableString("PowerSteps", "Leistungsschritte"); $this->RegisterVariableBoolean("Idle", "Idle", "", 0); $this->RegisterVariableInteger("Sperre_Prio", "Priorität Peakshaving"); - $this->RegisterVariableInteger("PV_Prio", "Priorität PV"); + $this->RegisterVariableInteger("PV_Prio", "Priorität PV"); $this->RegisterVariableInteger("Power", "Leistung Batterie"); $this->RegisterVariableBoolean("Is_Peak_Shaving", "Peakshavingmodus"); $this->RegisterVariableInteger("Leistung_Delta", "Leistung Delta", "", 0); $this->RegisterVariableFloat("Bezogene_Energie", "Bezogene Energie", "", 0); - // Hilfsvariabeln für Idle zustand $this->RegisterPropertyInteger("IdleCounterMax", 2); $this->RegisterVariableInteger("IdleCounter", "IdleCounter", "", 0); $this->SetValue("IdleCounter", 0); - // Initialisiere Idle - - $this->RegisterTimer("Timer_Do_UserCalc_Battery",$this->ReadPropertyInteger("Interval")*1000,"IPS_RequestAction(" .$this->InstanceID .', "Do_UserCalc", "");'); - - + $this->RegisterTimer("Timer_Do_UserCalc_Battery", $this->ReadPropertyInteger("Interval") * 1000, "IPS_RequestAction(" . $this->InstanceID . ', "Do_UserCalc", "");'); } - public function ApplyChanges() { parent::ApplyChanges(); - $batterieManagement = $this->ReadPropertyInteger("Batteriemanagement"); $this->SetValue("Batteriemanagement_Variabel", $batterieManagement); - $this->SetTimerInterval("Timer_Do_UserCalc_Battery",$this->ReadPropertyInteger("Interval")*1000); - + $this->SetTimerInterval("Timer_Do_UserCalc_Battery", $this->ReadPropertyInteger("Interval") * 1000); $batterietyp = $this->ReadPropertyInteger("Batterietyp"); - // Batterietypabhängige Variabeln Initialisieren - switch ($batterietyp) { + switch ($batterietyp) + { case 0: // Herstellerunabhängig - $this->MaintainVariable("Goodwe_EntLadeleistung", "Goodwe_EntLadeleistung", VARIABLETYPE_FLOAT, "", 10, false); $this->MaintainVariable("Ladeleistung", "Ladeleistung", VARIABLETYPE_FLOAT, "", 11, false); $this->MaintainVariable("Entladeleistung", "Entladeleistung", VARIABLETYPE_FLOAT, "", 13, false); - break; - + break; case 1: // Goodwe $this->MaintainVariable("Goodwe_EntLadeleistung", "Goodwe_EntLadeleistung", VARIABLETYPE_FLOAT, "", 10, true); $this->MaintainVariable("Ladeleistung", "Ladeleistung", VARIABLETYPE_FLOAT, "", 11, false); $this->MaintainVariable("Entladeleistung", "Entladeleistung", VARIABLETYPE_FLOAT, "", 13, false); - break; - + break; case 2: // Solaredge $this->MaintainVariable("Goodwe_EntLadeleistung", "Goodwe_EntLadeleistung", VARIABLETYPE_FLOAT, "", 10, false); $this->MaintainVariable("Ladeleistung", "Ladeleistung", VARIABLETYPE_FLOAT, "", 11, true); $this->MaintainVariable("Entladeleistung", "Entladeleistung", VARIABLETYPE_FLOAT, "", 13, true); - break; - + break; case 3: // SiG Energy $this->MaintainVariable("Goodwe_EntLadeleistung", "Goodwe_EntLadeleistung", VARIABLETYPE_FLOAT, "", 10, false); $this->MaintainVariable("Ladeleistung", "Ladeleistung", VARIABLETYPE_FLOAT, "", 11, true); $this->MaintainVariable("Entladeleistung", "Entladeleistung", VARIABLETYPE_FLOAT, "", 13, true); - break; - + break; default: // Default, werden alle ausgeschaltet $this->MaintainVariable("Goodwe_EntLadeleistung", "Goodwe_EntLadeleistung", VARIABLETYPE_FLOAT, "", 10, false); $this->MaintainVariable("Ladeleistung", "Ladeleistung", VARIABLETYPE_FLOAT, "", 11, false); $this->MaintainVariable("Entladeleistung", "Entladeleistung", VARIABLETYPE_FLOAT, "", 13, false); - break; + break; + } + // + $maxBatVar = $this->ReadPropertyInteger("MaxBatterieleistung"); + $maxNachVar = $this->ReadPropertyInteger("MaxNachladen"); + if ($maxBatVar > 0) + { + $this->RegisterMessage($maxBatVar, VM_UPDATE); + } + if ($maxNachVar > 0) + { + $this->RegisterMessage($maxNachVar, VM_UPDATE); } - - // - $maxBatVar = $this->ReadPropertyInteger("MaxBatterieleistung"); - $maxNachVar = $this->ReadPropertyInteger("MaxNachladen"); - - if ($maxBatVar > 0) { - $this->RegisterMessage($maxBatVar, VM_UPDATE); - } - if ($maxNachVar > 0) { - $this->RegisterMessage($maxNachVar, VM_UPDATE); - } - - } - - -public function RequestAction($Ident, $Value) -{ - switch ($Ident) { - - case "SetAktuelle_Leistung": - $this->SetValue("Power", (int)$Value); + public function RequestAction($Ident, $Value) + { + switch ($Ident) + { + case "SetAktuelle_Leistung": + $this->SetValue("Power", (int)$Value); break; - - case "GetCurrentData": - $this->SetValue("Is_Peak_Shaving", (bool)$Value); + case "GetCurrentData": + $this->SetValue("Is_Peak_Shaving", (bool)$Value); break; - - - case "Do_UserCalc": - - $this->SetAktuelle_Leistung($this->GetValue("Power")); - $this->GetCurrentData($this->GetValue("Is_Peak_Shaving")); - break; - - default: - break; - + case "Do_UserCalc": + $this->SetAktuelle_Leistung($this->GetValue("Power")); + $this->GetCurrentData($this->GetValue("Is_Peak_Shaving")); + break; + default: + break; + } } -} - - // Nach aufruf bei anpassung Batteriewerte, sofort Getcurrentdata aufrufen. + // Nach aufruf bei anpassung Batteriewerte, sofort Getcurrentdata aufrufen. public function MessageSink($TimeStamp, $SenderID, $Message, $Data) -{ - if ($Message !== VM_UPDATE) { - return; + { + if ($Message !== VM_UPDATE) + { + return; + } + $maxBatVar = $this->ReadPropertyInteger("MaxBatterieleistung"); + $maxNachVar = $this->ReadPropertyInteger("MaxNachladen"); + if ($SenderID === $maxBatVar || $SenderID === $maxNachVar) + { + // PowerSteps sofort neu berechnen (mit aktuellem Peak-Status) + $this->GetCurrentData($this->GetValue("Is_Peak_Shaving")); + } } - - $maxBatVar = $this->ReadPropertyInteger("MaxBatterieleistung"); - $maxNachVar = $this->ReadPropertyInteger("MaxNachladen"); - - if ($SenderID === $maxBatVar || $SenderID === $maxNachVar) { - // PowerSteps sofort neu berechnen (mit aktuellem Peak-Status) - $this->GetCurrentData($this->GetValue("Is_Peak_Shaving")); - } -} - - - // Aktuelle Leistung setzen lassen, der Manager vorgibt public function SetAktuelle_Leistung(int $power) - { - - $batterietyp = $this->ReadPropertyInteger("Batterietyp"); - $batterieManagement = $this->ReadPropertyInteger("Batteriemanagement"); - - //Fallunterscheidung, soll Enelix überhaupt steuern? - - // Wechselrichter steuert - // Goodwe, Solaredge WR Modus - if ($batterieManagement == 1 && ($batterietyp == 1 || $batterietyp == 2)) { - $this->SetValue("Entladeleistung", 0); - $this->SetValue("Ladeleistung", 0); - $this->SetValue("Batteriemanagement_Variabel", 1); - return; + { + $batterietyp = $this->ReadPropertyInteger("Batterietyp"); + $batterieManagement = $this->ReadPropertyInteger("Batteriemanagement"); + //Fallunterscheidung, soll Enelix überhaupt steuern? + // Wechselrichter steuert + // Goodwe, Solaredge WR Modus + if ($batterieManagement == 1 && ($batterietyp == 1 || $batterietyp == 2)) + { + $this->SetValue("Entladeleistung", 0); + $this->SetValue("Ladeleistung", 0); + $this->SetValue("Batteriemanagement_Variabel", 1); + return; //Sig Energy, Herstellerunabhänig im WR Modus - } elseif ($batterieManagement == 1 && ($batterietyp == 0 || $batterietyp == 3)) { - $this->SetValue("Entladeleistung", 0); - $this->SetValue("Ladeleistung", 0); - $this->SetValue("Batteriemanagement_Variabel", 0); - return; - + + } + elseif ($batterieManagement == 1 && ($batterietyp == 0 || $batterietyp == 3)) + { + $this->SetValue("Entladeleistung", 0); + $this->SetValue("Ladeleistung", 0); + $this->SetValue("Batteriemanagement_Variabel", 0); + return; // Enelix Steuert // Sig Energy Symcon Modus - } elseif ($batterieManagement == 2 && ($batterietyp == 0 || $batterietyp == 3)) { - $this->SetValue("Batteriemanagement_Variabel", 1); + } + elseif ($batterieManagement == 2 && ($batterietyp == 0 || $batterietyp == 3)) + { + $this->SetValue("Batteriemanagement_Variabel", 1); //Solaredge Symcon Modus - }elseif ($batterieManagement == 2 && $batterietyp == 2) { - $this->SetValue("Batteriemanagement_Variabel", 4); + + } + elseif ($batterieManagement == 2 && $batterietyp == 2) + { + $this->SetValue("Batteriemanagement_Variabel", 4); + } + // Variabeln entsprechend gewältem Batterietyp setzen + $batterietyp = $this->ReadPropertyInteger("Batterietyp"); + if ($batterietyp == 0) + { + //Herstellerunabhängig + if ($this->GetValue("Is_Peak_Shaving") == true) + { + if ($power >= 0) + { + $this->SetValue("Ladeleistung", $power); + $this->SetValue("Entladeleistung", 0); + $this->SetValue("Laden_Entladen", 0); + } + else + { + $this->SetValue("Entladeleistung", abs($power)); + $this->SetValue("Ladeleistung", 0); + $this->SetValue("Laden_Entladen", 1); + } } - - // Variabeln entsprechend gewältem Batterietyp setzen - $batterietyp = $this->ReadPropertyInteger("Batterietyp"); - if ($batterietyp == 0) {//Herstellerunabhängig - - if($this->GetValue("Is_Peak_Shaving")==true){ - - if ($power >= 0) { - $this->SetValue("Ladeleistung", $power); - $this->SetValue("Entladeleistung", 0); - $this->SetValue("Laden_Entladen", 0); - } else { - $this->SetValue("Entladeleistung", abs($power)); - $this->SetValue("Ladeleistung", 0); - $this->SetValue("Laden_Entladen", 1); - } - - }else{ - if ($power >= 0) { - $this->SetValue("Ladeleistung", $power); - $this->SetValue("Entladeleistung", 0); - $this->SetValue("Laden_Entladen", 0); - } else { - $this->SetValue("Entladeleistung", abs($power)); - $this->SetValue("Ladeleistung", 0); - $this->SetValue("Laden_Entladen", 1); + else + { + if ($power >= 0) + { + $this->SetValue("Ladeleistung", $power); + $this->SetValue("Entladeleistung", 0); + $this->SetValue("Laden_Entladen", 0); + } + else + { + $this->SetValue("Entladeleistung", abs($power)); + $this->SetValue("Ladeleistung", 0); + $this->SetValue("Laden_Entladen", 1); + } } } - } - elseif ($batterietyp == 1) {//Goodwe - $this->SetValue("Entladeleistung", 0); - $this->SetValue("Ladeleistung", 0); - if($this->GetValue("Is_Peak_Shaving")==true){ - - if ($power >= 0) { - $this->SetValue("Goodwe_EntLadeleistung", abs($power)); - $this->SetValue("Laden_Entladen", 11); - } else { - $this->SetValue("Goodwe_EntLadeleistung", abs($power)); - $this->SetValue("Laden_Entladen", 12); + elseif ($batterietyp == 1) + { + //Goodwe + $this->SetValue("Entladeleistung", 0); + $this->SetValue("Ladeleistung", 0); + if ($this->GetValue("Is_Peak_Shaving") == true) + { + if ($power >= 0) + { + $this->SetValue("Goodwe_EntLadeleistung", abs($power)); + $this->SetValue("Laden_Entladen", 11); + } + else + { + $this->SetValue("Goodwe_EntLadeleistung", abs($power)); + $this->SetValue("Laden_Entladen", 12); + } } - - }else{ - - if ($power >= 0) { - $this->SetValue("Goodwe_EntLadeleistung", abs($power)); - $this->SetValue("Laden_Entladen", 11); - } else { - $this->SetValue("Goodwe_EntLadeleistung", abs($power)); - $this->SetValue("Laden_Entladen", 12); - } - - } - - }elseif ($batterietyp == 2) {//Solaredge - - if($this->GetValue("Is_Peak_Shaving")==true){ - - if ($power >= 0) { - $this->SetValue("Ladeleistung", $power); - $this->SetValue("Entladeleistung", 0); - $this->SetValue("Laden_Entladen", 3); - } else { - $this->SetValue("Entladeleistung", abs($power)); - $this->SetValue("Ladeleistung", 0); - $this->SetValue("Laden_Entladen", 4); - } - - }else{ - if ($power >= 0) { - $this->SetValue("Ladeleistung", $power); - $this->SetValue("Entladeleistung", 0); - $this->SetValue("Laden_Entladen", 3); - } else { - $this->SetValue("Entladeleistung", abs($power)); - $this->SetValue("Ladeleistung", 0); - $this->SetValue("Laden_Entladen", 4); + else + { + if ($power >= 0) + { + $this->SetValue("Goodwe_EntLadeleistung", abs($power)); + $this->SetValue("Laden_Entladen", 11); + } + else + { + $this->SetValue("Goodwe_EntLadeleistung", abs($power)); + $this->SetValue("Laden_Entladen", 12); + } } } - } elseif ($batterietyp == 3) {//Sig Energy - - if($this->GetValue("Is_Peak_Shaving")==true){ - - if ($power >= 0) { - $this->SetValue("Ladeleistung", $power/1000); - $this->SetValue("Entladeleistung", 0); - $this->SetValue("Laden_Entladen", 3); - } else { - $this->SetValue("Entladeleistung", abs($power)/1000); - $this->SetValue("Ladeleistung", 0); - $this->SetValue("Laden_Entladen", 6); + elseif ($batterietyp == 2) + { + //Solaredge + if ($this->GetValue("Is_Peak_Shaving") == true) + { + if ($power >= 0) + { + $this->SetValue("Ladeleistung", $power); + $this->SetValue("Entladeleistung", 0); + $this->SetValue("Laden_Entladen", 3); + } + else + { + $this->SetValue("Entladeleistung", abs($power)); + $this->SetValue("Ladeleistung", 0); + $this->SetValue("Laden_Entladen", 4); + } } - - }else{ - if ($power >= 0) { - $this->SetValue("Ladeleistung", $power/1000); - $this->SetValue("Entladeleistung", 0); - $this->SetValue("Laden_Entladen", 3); - } else { - $this->SetValue("Entladeleistung", abs($power)/1000); - $this->SetValue("Ladeleistung", 0); - $this->SetValue("Laden_Entladen", 6); + else + { + if ($power >= 0) + { + $this->SetValue("Ladeleistung", $power); + $this->SetValue("Entladeleistung", 0); + $this->SetValue("Laden_Entladen", 3); + } + else + { + $this->SetValue("Entladeleistung", abs($power)); + $this->SetValue("Ladeleistung", 0); + $this->SetValue("Laden_Entladen", 4); + } + } + } + elseif ($batterietyp == 3) + { + //Sig Energy + if ($this->GetValue("Is_Peak_Shaving") == true) + { + if ($power >= 0) + { + $this->SetValue("Ladeleistung", $power / 1000); + $this->SetValue("Entladeleistung", 0); + $this->SetValue("Laden_Entladen", 3); + } + else + { + $this->SetValue("Entladeleistung", abs($power) / 1000); + $this->SetValue("Ladeleistung", 0); + $this->SetValue("Laden_Entladen", 6); + } + } + else + { + if ($power >= 0) + { + $this->SetValue("Ladeleistung", $power / 1000); + $this->SetValue("Entladeleistung", 0); + $this->SetValue("Laden_Entladen", 3); + } + else + { + $this->SetValue("Entladeleistung", abs($power) / 1000); + $this->SetValue("Ladeleistung", 0); + $this->SetValue("Laden_Entladen", 6); + } } } - } - - - - // Prüfe auf Änderung der Leistung im Vergleich zur letzten Einstellung $lastPower = GetValue($this->GetIDForIdent("Aktuelle_Leistung")); - if ($power != $lastPower) { + if ($power != $lastPower) + { $this->SetValue("Idle", false); - $this->SetValue( - "IdleCounter", - $this->ReadPropertyInteger("IdleCounterMax") - ); + $this->SetValue("IdleCounter", $this->ReadPropertyInteger("IdleCounterMax")); } - // Setze die neue aktuelle Leistung $this->SetValue("Aktuelle_Leistung", $power); - $this->SetValue("Bezogene_Energie", ($this->GetValue("Bezogene_Energie") + ($this->GetValue("Aktuelle_Leistung")*($this->ReadPropertyInteger("Interval")/3600)))); - + $this->SetValue("Bezogene_Energie", $this->GetValue("Bezogene_Energie") + $this->GetValue("Aktuelle_Leistung") * ($this->ReadPropertyInteger("Interval") / 3600)); // IdleCounter verarbeiten $this->ProcessIdleCounter(); - - } - - public function GetCurrentData(bool $Peak) { // Aktuelle Daten ausarbeiten und Berechnen $array_powersteps = $this->GeneratePowerSteps(); $aufdasnachladen = $this->ReadPropertyInteger("AufdasNachladen"); $minimumentladen = $this->ReadPropertyInteger("MinimumEntladen"); - $maxleistung = GetValue($this->ReadPropertyInteger("MaxBatterieleistung"));//Ladeleistung - $maxentladeleistung = GetValue($this->ReadPropertyInteger("MaxNachladen"));//Entladeleistung + $maxleistung = GetValue($this->ReadPropertyInteger("MaxBatterieleistung")); //Ladeleistung + $maxentladeleistung = GetValue($this->ReadPropertyInteger("MaxNachladen")); //Entladeleistung $dummy_array = []; $batterieladezustand = GetValue($this->ReadPropertyInteger("Batterieladezustand")); $filtered_powersteps_entladen = []; - if ($this->ReadPropertyInteger("Batteriemanagement") == 1) { + if ($this->ReadPropertyInteger("Batteriemanagement") == 1) + { $dummy_array[] = 0; return $this->SetValue("PowerSteps", json_encode($dummy_array)); } - - $netzbezug = GetValue($this->ReadPropertyInteger("Netzbezug")); $bat_leistung = GetValue($this->ReadPropertyInteger("AktuelleBatterieleistung")); - - - if ($Peak && $netzbezug > 0) { - $netzbezug = -min($netzbezug, $maxentladeleistung) + $bat_leistung; + if ($Peak && $netzbezug > 0) + { + $netzbezug = - min($netzbezug, $maxentladeleistung) + $bat_leistung; } - - if($batterieladezustand>(5+$aufdasnachladen)){ - + if ($batterieladezustand > 5 + $aufdasnachladen) + { $this->SetValue("Hysterese", false); - - }elseif($batterieladezustand<=$aufdasnachladen){ + } + elseif ($batterieladezustand <= $aufdasnachladen) + { $this->SetValue("Hysterese", true); } - $hyst = $this->GetValue("Hysterese"); - - if($Peak){ - - if($batterieladezustand>$aufdasnachladen && $hyst==false){ - + if ($Peak) + { + if ($batterieladezustand > $aufdasnachladen && $hyst == false) + { $dummy_array[] = $netzbezug; $this->SetValue("PowerSteps", json_encode($dummy_array)); - - }elseif($batterieladezustand>$aufdasnachladen && $hyst==true){ - - - $filtered_powersteps = array_filter($array_powersteps, function ($value) { + } + elseif ($batterieladezustand > $aufdasnachladen && $hyst == true) + { + $filtered_powersteps = array_filter($array_powersteps, function ($value) + { return $value <= 0; }); $filtered_powersteps_laden = array_values($filtered_powersteps); $this->SetValue("PowerSteps", json_encode($filtered_powersteps_laden)); - - }elseif($batterieladezustand>$minimumentladen){ - - $this->SetValue("PowerSteps", json_encode($array_powersteps)); } - else{ - - $filtered_powersteps = array_filter($array_powersteps, function ($value) { - return $value >= 0; - }); - $filtered_powersteps_laden = array_values($filtered_powersteps); - $this->SetValue("PowerSteps", json_encode($filtered_powersteps_laden)); - } - - }else{ - - - if($batterieladezustand>99){ - - $filtered_powersteps = array_filter($array_powersteps, function ($value) { - return $value <= 0; - }); - $filtered_powersteps_laden = array_values($filtered_powersteps); - $this->SetValue("PowerSteps", json_encode($filtered_powersteps_laden)); - - }elseif($batterieladezustand>$aufdasnachladen && $hyst==false){ - + elseif ($batterieladezustand > $minimumentladen) + { $this->SetValue("PowerSteps", json_encode($array_powersteps)); - - - }elseif($batterieladezustand>=$aufdasnachladen && $hyst==true){ - - $filtered_powersteps = array_filter($array_powersteps, function ($value) { + } + else + { + $filtered_powersteps = array_filter($array_powersteps, function ($value) + { return $value >= 0; }); $filtered_powersteps_laden = array_values($filtered_powersteps); $this->SetValue("PowerSteps", json_encode($filtered_powersteps_laden)); - - - }elseif($batterieladezustand<$aufdasnachladen){ - + } + } + else + { + if ($batterieladezustand > 99) + { + $filtered_powersteps = array_filter($array_powersteps, function ($value) + { + return $value <= 0; + }); + $filtered_powersteps_laden = array_values($filtered_powersteps); + $this->SetValue("PowerSteps", json_encode($filtered_powersteps_laden)); + } + elseif ($batterieladezustand > $aufdasnachladen && $hyst == false) + { + $this->SetValue("PowerSteps", json_encode($array_powersteps)); + } + elseif ($batterieladezustand >= $aufdasnachladen && $hyst == true) + { + $filtered_powersteps = array_filter($array_powersteps, function ($value) + { + return $value >= 0; + }); + $filtered_powersteps_laden = array_values($filtered_powersteps); + $this->SetValue("PowerSteps", json_encode($filtered_powersteps_laden)); + } + elseif ($batterieladezustand < $aufdasnachladen) + { //$dummy_array[] = GetValue($this->ReadPropertyInteger("MaxNachladen")); $dummy_array[] = GetValue($this->ReadPropertyInteger("MaxBatterieleistung")); $this->SetValue("PowerSteps", json_encode($dummy_array)); - } - - } - - } - - - // Ab hier Hilfsfunktionen - -private function GeneratePowerSteps() -{ - // Hilfsfunktion um die Möglichen Powersteps zu generieren - $maxleistung_raw = GetValue($this->ReadPropertyInteger("MaxBatterieleistung")); - $nachladen_raw = GetValue($this->ReadPropertyInteger("MaxNachladen")); - - $stepSize = 250; // Grobe Schrittgröße - $stepSizeSmall = 50; // Feine Schrittgröße - - // Grenzen auf 50er abrunden (floor) - $maxleistung = (int)(floor($maxleistung_raw / $stepSizeSmall) * $stepSizeSmall); - $minleistung = (int)(-floor($nachladen_raw / $stepSizeSmall) * $stepSizeSmall); // negativ! - - // Sicherheitscheck: falls Werte komisch sind - if ($maxleistung < 0) $maxleistung = 0; - if ($minleistung > 0) $minleistung = 0; - - // Grundarray: von min bis max in 250er Schritten - $neg = ($minleistung < 0) ? range($minleistung, 0, $stepSize) : [0]; - $pos = range(0, $maxleistung, $stepSize); - - $array_powersteps = array_values(array_unique(array_merge($neg, $pos))); - sort($array_powersteps, SORT_NUMERIC); - - // Zusätzlichen Wert auf 50er abrunden - $closestValue = (int)(floor($additionalValue / $stepSizeSmall) * $stepSizeSmall); - - // Clamp in den Bereich - if ($closestValue < $minleistung) $closestValue = $minleistung; - if ($closestValue > $maxleistung) $closestValue = $maxleistung; - - // Prüfen ob der Wert im Array existiert (bei 250er Raster oft NICHT) - $index = array_search($closestValue, $array_powersteps, true); - - // Wenn nicht vorhanden: an der richtigen Stelle einsortieren - if ($index === false) { - $index = 0; - $count = count($array_powersteps); - while ($index < $count && $array_powersteps[$index] < $closestValue) { - $index++; } } - - // Feine Werte um closestValue herum (±4 * 50) - $newValues = []; - for ($i = -4; $i <= 4; $i++) { - $v = $closestValue + ($i * $stepSizeSmall); - if ($v >= $minleistung && $v <= $maxleistung) { - $newValues[] = $v; + // Ab hier Hilfsfunktionen + private function GeneratePowerSteps() + { + // Hilfsfunktion um die Möglichen Powersteps zu generieren + $maxleistung_raw = GetValue($this->ReadPropertyInteger("MaxBatterieleistung")); + $nachladen_raw = GetValue($this->ReadPropertyInteger("MaxNachladen")); + $stepSize = 250; // Grobe Schrittgröße + $stepSizeSmall = 50; // Feine Schrittgröße + // Grenzen auf 50er abrunden (floor) + $maxleistung = (int)(floor($maxleistung_raw / $stepSizeSmall) * $stepSizeSmall); + $minleistung = (int)(-floor($nachladen_raw / $stepSizeSmall) * $stepSizeSmall); // negativ! + // Sicherheitscheck: falls Werte komisch sind + if ($maxleistung < 0) + { + $maxleistung = 0; } + if ($minleistung > 0) + { + $minleistung = 0; + } + // Grundarray: von min bis max in 250er Schritten + $neg = $minleistung < 0 ? range($minleistung, 0, $stepSize) : [0]; + $pos = range(0, $maxleistung, $stepSize); + $array_powersteps = array_values(array_unique(array_merge($neg, $pos))); + sort($array_powersteps, SORT_NUMERIC); + // Zusätzlichen Wert auf 50er abrunden + $closestValue = (int)(floor($additionalValue / $stepSizeSmall) * $stepSizeSmall); + // Clamp in den Bereich + if ($closestValue < $minleistung) + { + $closestValue = $minleistung; + } + if ($closestValue > $maxleistung) + { + $closestValue = $maxleistung; + } + // Prüfen ob der Wert im Array existiert (bei 250er Raster oft NICHT) + $index = array_search($closestValue, $array_powersteps, true); + // Wenn nicht vorhanden: an der richtigen Stelle einsortieren + if ($index === false) + { + $index = 0; + $count = count($array_powersteps); + while ($index < $count && $array_powersteps[$index] < $closestValue) + { + $index++; + } + } + // Feine Werte um closestValue herum (±4 * 50) + $newValues = []; + for ($i = - 4;$i <= 4;$i++) + { + $v = $closestValue + $i * $stepSizeSmall; + if ($v >= $minleistung && $v <= $maxleistung) + { + $newValues[] = $v; + } + } + // Duplikate vermeiden (falls schon Werte vorhanden sind) + $newValues = array_values(array_unique($newValues)); + // Wenn closestValue exakt im Grundarray war: diesen einen ersetzen + // sonst: feinwerte einfach an der Einfügestelle einfügen + if (array_search($closestValue, $array_powersteps, true) !== false) + { + $existingIndex = array_search($closestValue, $array_powersteps, true); + array_splice($array_powersteps, $existingIndex, 1, $newValues); + } + else + { + array_splice($array_powersteps, $index, 0, $newValues); + } + // Am Ende sortieren + $array_powersteps = array_values(array_unique($array_powersteps)); + sort($array_powersteps, SORT_NUMERIC); + return $array_powersteps; } - - // Duplikate vermeiden (falls schon Werte vorhanden sind) - $newValues = array_values(array_unique($newValues)); - - // Wenn closestValue exakt im Grundarray war: diesen einen ersetzen - // sonst: feinwerte einfach an der Einfügestelle einfügen - if (array_search($closestValue, $array_powersteps, true) !== false) { - $existingIndex = array_search($closestValue, $array_powersteps, true); - array_splice($array_powersteps, $existingIndex, 1, $newValues); - } else { - array_splice($array_powersteps, $index, 0, $newValues); - } - - // Am Ende sortieren - $array_powersteps = array_values(array_unique($array_powersteps)); - sort($array_powersteps, SORT_NUMERIC); - - return $array_powersteps; -} - - - - private function CheckIdle($power) - { // Hilfsfunktion zum Prüfen ob die Batterie schon wieder Leistung verändern kann + { + // Hilfsfunktion zum Prüfen ob die Batterie schon wieder Leistung verändern kann $lastpower = GetValue("Aktuelle_Leistung"); - if ($lastpower != GetValue("Aktuelle_Leistung")) { + if ($lastpower != GetValue("Aktuelle_Leistung")) + { $this->SetValue("Idle", false); - $this->SetValue( - "IdleCounter", - $this->ReadPropertyInteger("IdleCounterMax") - ); + $this->SetValue("IdleCounter", $this->ReadPropertyInteger("IdleCounterMax")); } // IdleCounter auslesen und verarbeiten $idleCounter = $this->GetValue("IdleCounter"); - if ($idleCounter > 0) { + if ($idleCounter > 0) + { $this->SetValue("Idle", false); $this->SetValue("IdleCounter", $idleCounter - 1); - } else { + } + else + { $this->SetValue("Idle", true); } } - - private function ProcessIdleCounter() { // IdleCounter auslesen und verarbeiten $idleCounter = $this->GetValue("IdleCounter"); - if ($idleCounter > 0) { + if ($idleCounter > 0) + { $this->SetValue("Idle", false); $this->SetValue("IdleCounter", $idleCounter - 1); - } else { + } + else + { $this->SetValue("Idle", true); } } - } ?> diff --git a/Ladestation/README.md b/Ladestation/README.md new file mode 100644 index 0000000..aa23783 --- /dev/null +++ b/Ladestation/README.md @@ -0,0 +1,142 @@ +# Enelix-Verbrauchermodul Ladestation (EV Charger) + +Dieses Modul integriert smarte Ladestationen (Wallboxen) für Elektroautos als steuerbare Verbraucher in das Belevo Energiemanagement-System (Enelix). Es regelt die Ladeleistung dynamisch, unterstützt verschiedene Hersteller-APIs und optimiert das Laden nach PV-Überschuss oder Peak-Shaving-Vorgaben. + +--- + +## Inhaltsverzeichnis + +1. [Funktionsumfang](#1-funktionsumfang) +2. [Voraussetzungen](#2-voraussetzungen) +3. [Installation](#3-installation) +4. [Instanz anlegen & Konfiguration](#4-instanz-anlegen--konfiguration) +5. [Statusvariablen & Profile](#5-statusvariablen--profile) +6. [WebFront / Bedienung](#6-webfront--bedienung) +7. [Mapping auf Code-Komponenten](#7-mapping-auf-code-komponenten) +8. [Zukünftige Erweiterungen](#8-zukünftige-erweiterungen) + +--- + +## 1. Funktionsumfang + +- **Hersteller-Integration:** Native Unterstützung verschiedener Ladestationen und Cloud-APIs (z.B. Smart-me Pico, Easee, eCarUp, generisches MQTT / REST-API). +- **Phasenerkennung:** Das Modul erkennt automatisch (über Leistungsschwellen, z.B. > 7500W), ob das Fahrzeug 1-phasig oder 3-phasig lädt, und passt die internen Strom-zu-Leistung-Umrechnungen an. +- **PowerSteps-Generierung:** Übersetzt die zulässigen Ladeströme (Ampere) in Watt-Schritte (`PowerSteps`), die dem Enelix-Manager für die Energieverteilung angeboten werden (abhängig vom definierten `Mindestaldestrom`, minimal 6A). +- **Verzögerungs- und Schutzlogiken:** + - `Ein_Zeit` / `Aus_Zeit`: Mindestlaufzeiten und Pausenzeiten, um den Schütz im Auto und in der Wallbox vor zu häufigem Schalten zu schützen (Taktschutz). + - `Zeit_Zwischen_Zustandswechseln`: Dämpfung von Leistungssprüngen. +- **Betriebsmodi:** + - *Solarladen:* Automatische Regelung nach PV-Überschuss. + - *Sperr-Priorität:* Regelung nach Peak-Shaving (Netzbezugsgrenzen). + - *Fahrzeugerkennung:* Freigabe der Ladeleistung nur, wenn ein Auto gesteckt (`Car_detected`) und nicht voll (`Car_is_full`) ist. +- **Token-Management:** Automatischer Login und Token-Refresh für Cloud-basierte Systeme (wie Easee, E-Car-Up). +- **Tarifabhängiges Solarladen** Nutzerbasiertes Solarladen mit unterschiedlichen Tarifen für Solar- und Netzladen. Dieese Funktion ist nur über spezielle Token und kostenpflichtigen Konten von drittfirmen aktivierbar. Für weitere Informationen bitte die Belevo AG kontaktieren. + +--- + +## 2. Voraussetzungen + +- IP-Symcon **≥ 8.0** +- Modul-URL: `https://git.belevo.ch/dh/enelix.git` +- Vorhandener und eingerichteter Enelix Manager. +- Netzwerkzugriff auf die Ladestation (lokale IP) oder aktive Internetverbindung für Cloud-APIs. + +--- + +## 3. Installation + +1. In IP-Symcon **Module Control** öffnen. +2. **Hinzufügen → Git-Repository**. +3. URL eingeben und **Installieren**. +4. IP-Symcon neu starten. + +--- + +## 4. Instanz anlegen & Konfiguration + +### 4.1 Instanz anlegen + +- Rechtsklick **Instanzen** → **Instanz hinzufügen** +- Filter: **Belevo** +- Auswahl: **Ladestation v2 (Verbraucher)** + +### 4.2 Properties + +| Name | Typ | Beschreibung | +|---|---|---| +| **IP_Adresse** | String | Lokale IP-Adresse der Ladestation (für lokale APIs). | +| **Ladestation** | Select/Int | Auswahl des API-/Hardware-Typs (z.B. 1=MQTT, 2=REST, 3=Pico, 5=eCarUp, 6=Easee). | +| **ID** | String | Stations-ID (z.B. für Smart-me Pico oder eCarUp). | +| **Seriennummer** | String | Seriennummer der Station (z.B. für Easee). | +| **Username** | String | Benutzername für Cloud-APIs. | +| **Password** | String | Passwort für Cloud-APIs. | +| **Interval** | NumberSpinner | Berechnungsintervall und Polling-Rate (Sekunden). | +| **Max_Current_abs** | NumberSpinner | Absoluter Maximalstrom der Zuleitung/Station in Ampere (z.B. 16 oder 32). | +| **Zeit_Zwischen_Zustandswechseln**| NumberSpinner | Verzögerungszeit zwischen zwei Leistungsanpassungen (in Minuten). | +| **Ein_Zeit** | NumberSpinner | Mindestlaufzeit, wenn die Ladung gestartet wird (Minuten). | +| **Aus_Zeit** | NumberSpinner | Mindestpausenzeit nach einem Ladeabbruch (Minuten). | +| **Token_Easee** | SelectVariable | Referenz auf das externe Easee-Token (Variable). | +| **Token_ECarUp** | SelectVariable | Referenz auf das externe eCarUp-Token (Variable). | +| **IdleCounterMax**| NumberSpinner | Anzahl Interval-Zyklen zwischen Leistungsänderungen (Modul-Idle). | + +--- + +## 5. Statusvariablen & Profile + +Das Modul verwendet viele interne (versteckte) Variablen für die Manager-Kommunikation. Hier die wichtigsten sichtbaren und steuerbaren Variablen: + +| Ident | Typ | Profil | Beschreibung | +|---|---|---|---| +| **Ladebereit** | Boolean | ~Switch | Hauptschalter: Ladestation generell freigegeben oder blockiert. | +| **Solarladen** | Boolean | ~Switch | Aktiviert den reinen PV-Überschusslade-Modus. | +| **Mindestaldestrom** | Integer | - | Minimaler Ladestrom in Ampere (normalerweise mind. 6A für Typ 2). | +| **Is_1_ph** | Boolean | ~Switch | Anzeige: Das Fahrzeug lädt aktuell nur auf einer Phase. | +| **Car_detected** | Boolean | ~Switch | Status: Ein Fahrzeug ist angesteckt und bereit. | +| **Car_is_full** | Boolean | ~Switch | Status: Fahrzeugakku ist voll (Ladestrom < Schwelle). | +| **Pending_Counter** | Integer | Zähler zum Abwarten des Stationszustandes bei Zustandänderung | +| **Leistung_Delta** | Integer | Leistungsabweichung von vorgegebener Soll- und Istleistung | +| **Idle** | Boolean | Status der Sperrzeit (`true` = bereit für neue Werte, `false` = gesperrt). | +| **Ladeleistung_Effektiv**| Float | - | Aktuell gemessene reale Ladeleistung in Watt. | +| **Bezogene_Energie** | Float | - | Rechnerisch aufsummierte Ladeenergie. | +| **Aktuelle_Leistung** | Integer | Die aktuell von der Station erbrachte Leistung. | +| **PowerSteps** | String | JSON-Array der dem Manager angebotenen Leistungsschritte. | +| **Letzer_User** | String | - | Zuletzt authentifizierter RFID-Nutzer (z.B. via eCarUp). | +| **Bezogene_Energie** | Float | Rechnerisch aufsummierte Energie (Leistung × Zeit). | +| **PV_Prio** | Integer | Priorität des Verbrauchers für PV-Optimierung, Tiefe Nummer = Hohe Priorität | +| **Sperre_Prio** | Integer | Priorität des Verbrauchers für Peak-Optimierung, Tiefe Nummer = Hohe Priorität | +| **PV_Prio** | Integer | Priorität des Verbrauchers für PV-Optimierung, Tiefe Nummer = Hohe Priorität | +| **Sperre_Prio** | Integer | Priorität des Verbrauchers für Peak-Optimierung, Tiefe Nummer = Hohe Priorität | + +--- + +## 6. WebFront / Bedienung + +Im WebFront bietet die Instanz dem Nutzer Eingriffsmöglichkeiten in das Ladeverhalten: +- **Ladebereit:** Kann genutzt werden, um die Wallbox per Knopfdruck komplett zu deaktivieren. +- **Solarladen:** Zwingt das Modul in den Überschuss-Modus (es wird nur geladen, wenn Leistung durch den Manager zugewiesen wird), Andernfalls wird bei verbundenem Auto solange geladen, bis der Peakshaving-Modus die Leistung reduziert. +- **Mindestaldestrom:** Definiert den Einstiegspunkt für die Ladung (z.B. 6A = ~1,4 kW bei 1-phasig / ~4,1 kW bei 3-phasig). + +- **PV_Prio** - Priorität des Verbrauchers für PV-Optimierung, Tiefe Nummer = Hohe Priorität +- **Sperre_Prio** - Priorität des Verbrauchers für Peak-Optimierung, Tiefe Nummer = Hohe Priorität + +Zudem dient die Instanz zur Statuskontrolle (Ist ein Auto verbunden? Lädt es? Ist es voll?). + +--- + +## 7. Mapping auf Code-Komponenten + +| Komponente | Funktion im Code (`module.php`) | +|---|---| +| **API-Schnittstellen** | `Get_Car_Status($carType)` fragt die jeweilige Hardware ab (cURL an REST/MQTT/Easee) und aktualisiert `Ladeleistung_Effektiv` sowie den `Fahrzeugstatus`. | +| **Autodetektion** | `Detect_Car()` prüft den Zustand, zählt `Pending_Counter` hoch und entscheidet über `Is_1_ph` basierend auf Leistungsgrenzen (7500W). | +| **Leistung → Strom** | `Get_Array_From_Current()` und `Get_Current_From_Power()` rechnen Watt in Ampere um ($P = U \cdot I \cdot Phasen$). | +| **Manager-Interface** | `GetCurrentData($Peak)` baut die `PowerSteps` (z.B. [0, 4140, 4830, ...]) und übergibt diese dem Manager. | +| **Stationssteuerung** | `sendPowerToStation($value)` übersetzt den Soll-Strom (Ampere) in API-spezifische Kommandos (z.B. `amp=16` oder `{"amps":16}`). | +| **Taktschutz (Timers)**| `SetTimerNullMindestlast()`, `SetTimerOn()` und die entsprechenden Reset-Methoden sperren Zustandswechsel nach Start/Stopp. | +| **Token-Refresh** | `Refresh_Token()` erneuert zyklisch das Access-Token (z.B. Easee) über die hinterlegten Credentials. | + +--- + +## 8. Zukünftige Erweiterungen + +- **Automatische Phasenumschaltung:** Direkte Ansteuerung von Wallboxen, die eine Umschaltung zwischen 1- und 3-phasigem Laden im laufenden Betrieb unterstützen (zur Erweiterung des Regelbereichs bei wenig Sonne). diff --git a/Ladestation/form.json b/Ladestation/form.json new file mode 100644 index 0000000..0ef4448 --- /dev/null +++ b/Ladestation/form.json @@ -0,0 +1,113 @@ +{ + "elements": [ + { + "type": "Select", + "name": "Ladestation", + "caption": "Ladestation Typ", + "options": [ + + { + "caption": "Herstellerunabhängig (Ohne interne kommunikation mit Station)", + "value": 4 + }, + { + "caption": "Go-E Wallbox (Alte Version)", + "value": 1 + }, + { + "caption": "Go-E Germini / Germini Flex", + "value": 2 + }, + { + "caption": "Smart-Me Pico", + "value": 3 + }, + { + "caption": "Easee", + "value": 6 + }, + { + "caption": "Easee - Nur tarifabhängiges Solarladen", + "value": 5 + } + ] + }, + { + "type": "NumberSpinner", + "name": "IdleCounterMax", + "caption": "Anzahl Interval-Zyklen zwischen zwei Leistungsänderungen", + "suffix": "" + }, + { + "type": "NumberSpinner", + "name": "Interval", + "caption": "Intervall Neuberechnung der Werte", + "suffix": "Sekunden" + }, + { + "type": "NumberSpinner", + "name": "Max_Current_abs", + "caption": "Maximaler Ladestrom der Station", + "suffix": "Ampere" + }, + { + "type": "NumberSpinner", + "name": "Zeit_Zwischen_Zustandswechseln", + "caption": "Mindestlaufzeit des Verbrauchers bei Lastschaltung (Veraltet, auf 0 lassen, wird demnächst entfehrnt, wird ersetzt durch Mindestlaufzeiten)", + "suffix": "" + }, + { + "type": "NumberSpinner", + "name": "Ein_Zeit", + "caption": "Mindestlaufzeit Ladestation wenn Ein", + "suffix": "" + }, + { + "type": "NumberSpinner", + "name": "Aus_Zeit", + "caption": "Mindestlaufzeit Ladestation wenn Aus", + "suffix": "" + }, + { + "type": "ValidationTextBox", + "name": "IP_Adresse", + "caption": "IP-Adresse Ladestation (für Go-E Modelle)" + + }, + { + "type": "ValidationTextBox", + "caption": "Geräte-ID (für Smart-Me / ECarUp / Easee)", + "name": "ID" + + }, + { + "type": "ValidationTextBox", + "caption": "Seriennummer (für Smart-Me / ECarUp / Easee)", + "name": "Seriennummer" + + }, + { + "type": "ValidationTextBox", + "caption": "Username / Benutzernahme (für Easee, Smart-Me, )", + "name": "Username" + + }, + { "type": "PasswordTextBox", + "caption": "Password -> (Smart-Me)", + "name": "Password" + }, + { + "type": "SelectVariable", + "name": "Token_Easee", + "caption": "Variable API-Token für Easee-Solarladen", + "suffix": "" + }, + { + "type": "SelectVariable", + "name": "Token_ECarUp", + "caption": "Variable API-Token für ECarUp (Easee Solarladen)", + "suffix": "" + } + + ] +} \ No newline at end of file diff --git a/Ladestation/module.json b/Ladestation/module.json new file mode 100644 index 0000000..7803342 --- /dev/null +++ b/Ladestation/module.json @@ -0,0 +1,12 @@ +{ + "id": "{51E121F0-E2E9-D0C2-C8BD-92601B143EB8}", + "name": "Ladestation", + "type": 3, + "vendor": "Belevo AG", + "aliases": [], + "parentRequirements": [], + "childRequirements": [], + "implemented": [], + "prefix": "GEF", + "url": "https://git.belevo.ch/dh/Enelix/src/branch/main/Ladestation" +} \ No newline at end of file diff --git a/Ladestation/module.php b/Ladestation/module.php new file mode 100644 index 0000000..d42bbb4 --- /dev/null +++ b/Ladestation/module.php @@ -0,0 +1,821 @@ +RegisterPropertyString("IP_Adresse", "0.0.0.0"); + $this->RegisterPropertyInteger("Ladestation", 2); + $this->RegisterPropertyString("ID", ""); + $this->RegisterPropertyString("Seriennummer", ""); + $this->RegisterPropertyString("Username", ""); + $this->RegisterPropertyString("Password", ""); + $this->RegisterPropertyInteger("Interval", 5); // Recheninterval + $this->RegisterPropertyInteger("Max_Current_abs", 32); // Recheninterval + $this->RegisterPropertyInteger("Zeit_Zwischen_Zustandswechseln", 1); + $this->RegisterPropertyInteger("Ein_Zeit", 0); // Recheninterval + $this->RegisterPropertyInteger("Aus_Zeit", 0); // Recheninterval + $this->RegisterPropertyInteger("Token_Easee", 0); // Recheninterval + $this->RegisterPropertyInteger("Token_ECarUp", 0); // Recheninterval + // Ladestationspezifische Variabeln + $this->RegisterVariableFloat("Max_Current", "Maximaler Ladestrom", "", 0); + IPS_SetHidden($this->GetIDForIdent("Max_Current") , true); + $this->RegisterVariableBoolean("Is_1_ph", "Auto lädt 1-Phasig", "~Switch", false); + $this->RegisterVariableBoolean("Car_detected", "Auto erkannt", "~Switch", false); + $this->RegisterVariableInteger("Pending_Counter", "Pending_Counter", "", 0); + IPS_SetHidden($this->GetIDForIdent("Pending_Counter") , true); + $this->RegisterVariableBoolean("Car_is_full", "Auto fertig geladen", "~Switch", false); + $this->RegisterVariableBoolean("Ladebereit", "Ladestation ein", "~Switch", true); + $this->EnableAction("Ladebereit"); + $this->RegisterVariableBoolean("Solarladen", "Solarladen ein", "~Switch", false); + $this->EnableAction("Solarladen"); + $this->RegisterVariableInteger("Fahrzeugstatus", "Fahrzeugstatus", "", 0); + IPS_SetHidden($this->GetIDForIdent("Fahrzeugstatus") , true); + $this->RegisterVariableFloat("Ladeleistung_Effektiv", "Aktuelle Ladeleistung", "", 0); + $this->RegisterVariableBoolean("Peak", "Peak", "", 0); + IPS_SetHidden($this->GetIDForIdent("Peak") , true); + $this->RegisterVariableBoolean("IsTimerActive", "IsTimerActive", "", false); + IPS_SetHidden($this->GetIDForIdent("IsTimerActive") , true); + $this->RegisterTimer("ZustandswechselTimer", 0, "IPS_RequestAction(" . $this->InstanceID . ', "ResetTimer", "");'); + $this->RegisterVariableBoolean("IsTimerActive_Null_Timer", "IsTimerActive_Null_Timer", "", false); + IPS_SetHidden($this->GetIDForIdent("IsTimerActive_Null_Timer") , true); + $this->RegisterTimer("Null_Timer", 0, "IPS_RequestAction(" . $this->InstanceID . ', "ResetNullTimer", "");'); + $this->RegisterVariableString("Letzer_User", "Letzter registrierter Benutzer"); + IPS_SetHidden($this->GetIDForIdent("Letzer_User") , true); + // Variabeln für Kommunkation mit Manager + $this->RegisterVariableInteger("Sperre_Prio", "Priorität Sperre", "", 0); + $this->EnableAction("Sperre_Prio"); + IPS_SetHidden($this->GetIDForIdent("Sperre_Prio") , true); + $this->RegisterVariableInteger("PV_Prio", "Priorität Solarladen", "", 0); + $this->EnableAction("PV_Prio"); + IPS_SetHidden($this->GetIDForIdent("PV_Prio") , true); + $this->RegisterVariableBoolean("Idle", "Idle", "", 0); + IPS_SetHidden($this->GetIDForIdent("Idle") , true); + $this->RegisterVariableInteger("Aktuelle_Leistung", "Aktuelle_Leistung", "", 0); + IPS_SetHidden($this->GetIDForIdent("Aktuelle_Leistung") , true); + $this->RegisterVariableFloat("Bezogene_Energie", "Gesamter Energiebezug", "", 0); + IPS_SetHidden($this->GetIDForIdent("Bezogene_Energie") , true); + $this->RegisterVariableString("PowerSteps", "Leistungsschritte"); + IPS_SetHidden($this->GetIDForIdent("PowerSteps") , true); + $this->RegisterVariableInteger("Power", "Power"); + IPS_SetHidden($this->GetIDForIdent("Power") , true); + $this->RegisterVariableBoolean("Is_Peak_Shaving", "Is_Peak_Shaving"); + IPS_SetHidden($this->GetIDForIdent("Is_Peak_Shaving") , true); + $this->RegisterVariableInteger("Leistung_Delta", "Leistung_Delta", "", 0); + IPS_SetHidden($this->GetIDForIdent("Leistung_Delta") , true); + $this->RegisterVariableString("Token_Intern", "Internes Token Easee"); + IPS_SetHidden($this->GetIDForIdent("Token_Intern") , true); + // Hilfsvariabeln für Idle zustand + $this->RegisterPropertyInteger("IdleCounterMax", 2); + $this->RegisterVariableInteger("IdleCounter", "IdleCounter", "", 0); + IPS_SetHidden($this->GetIDForIdent("IdleCounter") , true); + $this->SetValue("IdleCounter", 0); + // Initialisiere Idle + $this->SetValue("Idle", true); + $this->RegisterTimer("Timer_Do_UserCalc_EVC", $this->ReadPropertyInteger("Interval") * 1000, "IPS_RequestAction(" . $this->InstanceID . ', "Do_UserCalc", "");'); + $this->RegisterTimer("Timer_Refresh_Token", 0, "IPS_RequestAction(" . $this->InstanceID . ', "Refresh_Token", "");'); + $this->RegisterVariableInteger("Mindestaldestrom", "Mindestaldestrom", "", 0); + $this->EnableAction("Mindestaldestrom"); + } + public function ApplyChanges() + { + parent::ApplyChanges(); + $this->SetTimerInterval("Timer_Do_UserCalc_EVC", $this->ReadPropertyInteger("Interval") * 1000); + // erstelle einen Timer der das Request token aktualisiert wenn die station dies braucht (aktuell nur für Solarladelösung Easee). + if ($this->ReadPropertyInteger("Ladestation") == 6) + { + $this->Refresh_Token(); + $this->SetTimerInterval("Timer_Refresh_Token", 1800000); + } + } + public function RequestAction($Ident, $Value) + { + switch ($Ident) + { + case "SetAktuelle_Leistung": + $this->SetValue("Power", (int)$Value); + break; + case "GetCurrentData": + $this->SetValue("Is_Peak_Shaving", (bool)$Value); + break; + case "Do_UserCalc": // Auto und ladestrom erkennen. + if ($this->Detect_Car($this->ReadPropertyInteger("Ladestation"))) + { + $this->SetAktuelle_Leistung($this->GetValue("Power")); + $this->GetCurrentData($this->GetValue("Is_Peak_Shaving")); + } + else + { + SetValue($this->GetIDForIdent("PowerSteps") , json_encode([0])); + $this->SetValue("PowerSteps", json_encode([0])); + } + break; + case "Sperre_Prio": + $this->SetValue("Sperre_Prio", (bool)$Value); + break; + case "PV_Prio": + $this->SetValue("PV_Prio", (bool)$Value); + break; + case "Solarladen": + $this->SetValue("Solarladen", (bool)$Value); + break; + case "Ladebereit": + $this->SetValue("Ladebereit", (bool)$Value); + break; + case "ResetTimer": + $this->ResetTimer(); + break; + case "ResetNullTimer": + $this->ResetNullTimer(); + break; + case "Refresh_Token": + $this->Refresh_Token(); + break; + case "Mindestaldestrom": + $this->SetValue("Mindestaldestrom", (int)$Value); + break; + default: + break; + } + } + // Erkenne, ob ein auto angeschlossen ist und mit welchem strom es lädt, setzte Statusvariabeln zur Ladestation + public function Detect_Car(int $carType) + { + if ($this->GetValue("Car_detected") == true) + { // Wenn schon auto angeschlossen, schaue ob es noch lädt + if ($this->Get_Car_Status($carType) == true) + { + $this->SetValue("Car_detected", true); + if ($this->GetValue("Max_Current") < 6) + { + $this->SetValue("Car_is_full", true); + $this->ResetTimer(); + $this->ResetNullTimer(); + } + } + else + { + $this->SetValue("Car_detected", false); + $this->SetValue("Pending_Counter", 0); + $this->SetValue("Leistung_Delta", 0); + $this->SetValue("Car_is_full", false); + $this->ResetTimer(); + $this->ResetNullTimer(); + $this->SetValue("Is_1_ph", false); + $this->SetValue("Aktuelle_Leistung", 0); + $this->SetValue("IdleCounter", 0); + $this->SetValue("Idle", true); + } + } + else + { // wenn kein auto angeschlossen schaue ob eines angesteckt wurde + if ($this->Get_Car_Status($carType) == true) + { + $this->sendPowerToStation($this->ReadPropertyInteger("Max_Current_abs")); + $counter = $this->GetValue("Pending_Counter"); + if ($counter > (60 / ($this->ReadPropertyInteger("Interval")))) + { + $this->SetValue("Pending_Counter", 0); + if ($this->GetValue("Ladeleistung_Effektiv") > 7500) + { + $this->SetValue("Is_1_ph", false); + $this->Calc_Max_Current(false); + } + else + { + $this->SetValue("Is_1_ph", true); + $this->Calc_Max_Current(true); + } + $this->SetValue("Car_detected", true); + if ($this->GetValue("Is_1_ph")) + { + $power = $this->GetValue("Mindestaldestrom") * 230; + } + else + { + $power = $this->GetValue("Mindestaldestrom") * 400 * 1.71; + } + $this->SetValue("Power", $power); + } + else + { + $this->SetValue("Pending_Counter", $counter + 1); + $this->SetValue("Car_detected", false); + } + } + else + { + $this->SetValue("Car_detected", false); + $this->SetValue("Leistung_Delta", 0); + $this->sendPowerToStation($this->ReadPropertyInteger("Max_Current_abs")); + } + } + return $this->GetValue("Car_detected"); + } + public function SetTimerOn() + { + // Timer setzen, der nach "Zeit_Zwischen_Zustandswechseln" abläuft, verhindert schnelles Takten + $zeitZwischenZustandswechseln = $this->ReadPropertyInteger("Zeit_Zwischen_Zustandswechseln"); + if ($zeitZwischenZustandswechseln > 0) + { + $this->SetTimerInterval("ZustandswechselTimer", $zeitZwischenZustandswechseln * 60000); // Timer in Millisekunden + // Timer-Status auf true setzen + $this->SetValue("IsTimerActive", true); + } + else + { + $this->SetValue("IsTimerActive", false); + } + } + // Methode zum Setzen eines mindeststromes beim laden, über einen timer + public function SetTimerNullMindestlast($time) + { + if ($time > 0) + { + $this->SetTimerInterval("Null_Timer", $time * 60000); // Timer in Millisekunden + // Timer-Status auf true setzen + $this->SetValue("IsTimerActive_Null_Timer", true); + } + else + { + $this->SetValue("IsTimerActive_Null_Timer", false); + } + } + // Methode zum Zurücksetzen nach Ablauf des Timers + public function ResetTimer() + { + // Timer stoppen + $this->SetTimerInterval("ZustandswechselTimer", 0); + // Timer-Status auf false setzen + $this->SetValue("IsTimerActive", false); + } + // Methode zum Zurücksetzen nach Ablauf des Timers Mindeststroms + public function ResetNullTimer() + { + // Timer stoppen + $this->SetTimerInterval("Null_Timer", 0); + // Timer-Status auf false setzen + $this->SetValue("IsTimerActive_Null_Timer", false); + } + // Erkenne Autostatus (ladestrom, status) auf basis des Typs + public function Get_Car_Status(int $carType) + { + $ch = curl_init(); + $car_on_station = $this->GetValue("Car_detected"); + switch ($carType) + { + case 1: // GO-E alt + curl_setopt($ch, CURLOPT_URL, "http://" . $this->ReadPropertyString("IP_Adresse") . "/mqtt?payload="); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($ch); + curl_close($ch); + $data = json_decode($response, true); + if (json_last_error() === JSON_ERROR_NONE && isset($data["car"])) + { + if ($data["car"] != 1) + { + $car_on_station = true; + } + else + { + $car_on_station = false; + } + $this->SetValue("Ladeleistung_Effektiv", $data["nrg"][11] * 10); + $this->SetValue("Fahrzeugstatus", $data["car"]); + } + break; + case 2: // Go-E Gemini + curl_setopt($ch, CURLOPT_URL, "http://" . $this->ReadPropertyString("IP_Adresse") . "/api/status"); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($ch); + curl_close($ch); + $data = json_decode($response, true); + if (json_last_error() === JSON_ERROR_NONE && isset($data["car"])) + { + if ($data["car"] != 1) + { + $car_on_station = true; + } + else + { + $car_on_station = false; + } + $this->SetValue("Ladeleistung_Effektiv", $data["nrg"][11]); + $this->SetValue("Fahrzeugstatus", $data["car"]); + } + break; + case 3: // Smart-Me Pico + curl_setopt($ch, CURLOPT_URL, "https://api.smart-me.com/pico/charging/" . $this->ReadPropertyString("ID")); + curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_setopt($ch, CURLOPT_USERPWD, $this->ReadPropertyString("Username") . ":" . $this->ReadPropertyString("Password")); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($ch); + curl_close($ch); + $data = json_decode($response, true); + if (json_last_error() === JSON_ERROR_NONE && isset($data["State"])) + { + if ($data["State"] != 1) + { + $car_on_station = true; + } + else + { + $car_on_station = false; + } + $this->SetValue("Ladeleistung_Effektiv", round($data["ActiveChargingPower"] * 1000)); + $this->SetValue("Fahrzeugstatus", $data["State"]); + } + break; + case 4: // Herstellerunabh. + $car_on_station = true; + break; + case 5: // Solarladen E-Car-Up + // Benutzer eCarUp abfragen + $authToken = GetValue($this->ReadPropertyInteger("Token_ECarUp")); + $ID = $this->ReadPropertyString("ID"); + $apiUrl = 'https://public-api.ecarup.com/v1/station/' . $ID . '/conn' . 'ectors/' . $ID . '/active-charging'; + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $apiUrl); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, ['accept: application/json', 'Authorization: Bearer ' . $authToken]); + $response = curl_exec($ch); + $data = json_decode($response, true); + curl_close($ch); + if (json_last_error() === JSON_ERROR_NONE && isset($data["driverIdentifier"])) + { + $this->SetValue("Letzer_User", $data["driverIdentifier"]); + if ($this->ReadPropertyString("Username") === $data["driverIdentifier"]) + { + $this->SetValue("Solarladen", true); + } + else + { + $this->SetValue("Solarladen", false); + } + } + //Aktueller Zustand Ladestation abfragen (Leistung, auto eingesteckt?) + $ch2 = curl_init(); + $url2 = "https://api.easee.com/api/chargers/" . $this->ReadPropertyString("Seriennummer") . "/state"; + curl_setopt_array($ch2, [CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => ["Authorization: Bearer " . GetValue($this->ReadPropertyInteger("Token_Easee")) . "", "content-type: application/*+json"], ]); + curl_setopt($ch2, CURLOPT_URL, $url2); + curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); + $response_easee = curl_exec($ch2); + curl_close($ch2); + $easee_data = json_decode($response_easee, true); + if (json_last_error() === JSON_ERROR_NONE && isset($easee_data["chargerOpMode"])) + { + if ($easee_data["chargerOpMode"] != 1 && (($easee_data["chargerOpMode"] != 6) || ($this->GetValue("Car_detected") == true)) && $easee_data["chargerOpMode"] != 7) + { + $car_on_station = true; + } + else + { + $car_on_station = false; + } + $this->SetValue("Ladeleistung_Effektiv", round($easee_data["totalPower"] * 1000)); + $this->SetValue("Fahrzeugstatus", $easee_data["chargerOpMode"]); + } + break; + case 6: // Easee + //Aktueller Zustand Ladestation abfragen (Leistung, auto eingesteckt?) + $ch2 = curl_init(); + $url2 = "https://api.easee.com/api/chargers/" . $this->ReadPropertyString("Seriennummer") . "/state"; + curl_setopt_array($ch2, [CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $this->GetBuffer("Token_Intern") . "", "content-type: application/*+json"], ]); + curl_setopt($ch2, CURLOPT_URL, $url2); + curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); + $response_easee = curl_exec($ch2); + curl_close($ch2); + $easee_data = json_decode($response_easee, true); + if (json_last_error() === JSON_ERROR_NONE && isset($easee_data["chargerOpMode"])) + { + if ($easee_data["chargerOpMode"] != 1 && (($easee_data["chargerOpMode"] != 6) || ($this->GetValue("Car_detected") == true)) && $easee_data["chargerOpMode"] != 7) + { + $car_on_station = true; + } + else + { + $car_on_station = false; + } + $this->SetValue("Ladeleistung_Effektiv", round($easee_data["totalPower"] * 1000)); + $this->SetValue("Fahrzeugstatus", $easee_data["chargerOpMode"]); + } + break; + default: + $this->SetValue("Car_detected", false); + $this->SetValue("Fahrzeugstatus", -1); + break; + } + return $car_on_station; + } + // Methode zum Berechnen des Maximalen Stroms den eine Ladestation/Auto ziehen kann. + public function Calc_Max_Current(bool $is_1_ph) + { + $maxCurrent = 32; + if ($is_1_ph) + { + $maxCurrent = 2.5 + ($this->GetValue("Ladeleistung_Effektiv") / 230); + } + else + { + $maxCurrent = 2.5 + ($this->GetValue("Ladeleistung_Effektiv") / (1.71 * 400)); + } + if ($maxCurrent > $this->ReadPropertyInteger("Max_Current_abs")) + { + $maxCurrent = $this->ReadPropertyInteger("Max_Current_abs"); + } + $this->SetValue("Max_Current", $maxCurrent); + } + // Mehtohde zum Umrechnen Leistung/Strom + public function Get_Current_From_Power(bool $is_1_ph, int $power) + { + if ($is_1_ph) + { + $current = round($power / 230); + } + else + { + $current = round($power / (400 * 1.71)); + } + return $current; + } + // Methode zum ermitteln aller möglcihen leistungsschritte mit aktuellem Maximalstrom + public function Get_Array_From_Current(bool $is_1_ph, float $current, int $power, bool $timer) + { + $resultArray = []; + if ($timer) + { + // Timer an + if ($power === 0) + { + // power == 0: nur eine 0 zurückgeben + $resultArray[] = 0; + return $resultArray; + } + else + { + for ($i = (max($this->GetValue("Mindestaldestrom") + 1, 6));$i <= $current;$i++) + { + if ($is_1_ph) + { + $resultArray[] = $i * 230; + } + else + { + $resultArray[] = $i * 400 * 1.71; + } + } + } + // power > 0: keine 0 am Anfang, Schleife normal durchlaufen + + } + else + { + if ($is_1_ph) + { + $resultArray[] = $this->GetValue("Mindestaldestrom") * 230; + } + else + { + $resultArray[] = $this->GetValue("Mindestaldestrom") * 400 * 1.71; + } + // Schleife wie gehabt + for ($i = (max($this->GetValue("Mindestaldestrom") + 1, 6));$i <= $current;$i++) + { + if ($is_1_ph) + { + $resultArray[] = $i * 230; + } + else + { + $resultArray[] = $i * 400 * 1.71; + } + } + } + return $resultArray; + } + public function SetAktuelle_Leistung(int $power) + { + // Hier eine Leistungsänderung detektieren für Idle und interne Mindestlaufzeiten + $this->CheckIdle($power); + if ($this->GetValue("Aktuelle_Leistung") != $power) + { + $this->SetTimerOn(); + } + // Leistung nur ändern wenn aktuell kein Timer aktiv ist + if (($this->GetValue("Aktuelle_Leistung") == 0) && ($power > 0)) + { + $this->SetTimerNullMindestlast($this->ReadPropertyInteger("Ein_Zeit")); + } + elseif (($this->GetValue("Aktuelle_Leistung") > 0) && ($power == 0)) + { + $this->SetTimerNullMindestlast($this->ReadPropertyInteger("Aus_Zeit")); + } + $internalPower = GetValue($this->GetIDForIdent("Aktuelle_Leistung")); + // Aktuelle Leistungsvorgabe setzen + SetValue($this->GetIDForIdent("Aktuelle_Leistung") , $power); + if ($power <= 0) + { + $this->SetValue("Pending_Counter", 0); + } + // Bezogene Energie aufintegrieren + $this->SetValue("Bezogene_Energie", ($this->GetValue("Bezogene_Energie") + ($this->GetValue("Aktuelle_Leistung") * ($this->ReadPropertyInteger("Interval") / 3600)))); + if ($power != $internalPower) + { + // Setze die interne Leistungsvorgabe + // Idle für x Zyklen auf false setzen + SetValue($this->GetIDForIdent("Idle") , false); + SetValue($this->GetIDForIdent("IdleCounter") , $this->ReadPropertyInteger("IdleCounterMax")); + } + else + { + // IdleCallCounter herunterzählen, wenn power == interne Leistungsvorgabe + $idleCounter = GetValue($this->GetIDForIdent("IdleCounter")); + if ($idleCounter > 0) + { + $idleCounter--; + $this->SetValue("Pending_Counter", 0); + SetValue($this->GetIDForIdent("IdleCounter") , $idleCounter); + if ($idleCounter == 0) + { + SetValue($this->GetIDForIdent("Idle") , true); + } + } + } + // Ladeleistung setzen + $peak = GetValue($this->GetIDForIdent("Peak")); + $solarladen = GetValue($this->GetIDForIdent("Solarladen")); + $Ladebereit = GetValue($this->GetIDForIdent("Ladebereit")); + if (!$Ladebereit) + { + $this->sendPowerToStation(0); + } + elseif (!$peak && !$solarladen) + { + // Wenn weder Peak noch Solarladen aktiv sind, setze Ladeleistung auf MaxLeistung + $this->sendPowerToStation($this->Get_Current_From_Power($this->GetValue("Is_1_ph") , $power)); + } + else + { + // Ansonsten setze Ladeleistung auf die aktuelle Leistungsvorgabe (Aktuelle_Leistung) + $this->sendPowerToStation($this->Get_Current_From_Power($this->GetValue("Is_1_ph") , $power)); + } + } + // Methode zum Abrufen der aktuellen Daten + public function GetCurrentData(bool $Peak) + { + // Überprüfen, ob der Timer aktiv ist + if ($this->GetValue("IsTimerActive")) + { + // Timer ist aktiv, PowerSteps setzen + $this->SetValue("PowerSteps", json_encode([$this->GetValue("Aktuelle_Leistung") ])); + $this->SetValue("Leistung_Delta", $this->GetValue("Aktuelle_Leistung") - $this->GetValue("Ladeleistung_Effektiv")); + return; + } + else + { + $this->SetValue("Leistung_Delta", 0); + } + // Aktuelle Properties abrufen + $ladebereit = GetValue($this->GetIDForIdent("Ladebereit")); + $solarladen = GetValue($this->GetIDForIdent("Solarladen")); + // Peak-Wert speichern + $this->SetValue("Peak", $Peak); + // Array für die Powersteps initialisieren + $powerSteps = []; + // Konfiguration des powerSteps-Arrays basierend auf den Properties + if (!$ladebereit || $this->GetValue("Car_is_full")) + { + $powerSteps = [0]; + } + elseif (!$Peak && !$solarladen) + { + $powerSteps = [max($this->Get_Array_From_Current($this->GetValue("Is_1_ph") , $this->GetValue("Max_Current") , $this->GetValue("Aktuelle_Leistung") , $this->GetValue("IsTimerActive_Null_Timer"))) ]; + } + elseif (!$Peak && $solarladen) + { + $powerSteps = $this->Get_Array_From_Current($this->GetValue("Is_1_ph") , $this->GetValue("Max_Current") , $this->GetValue("Aktuelle_Leistung") , $this->GetValue("IsTimerActive_Null_Timer")); + } + elseif ($solarladen && $Peak) + { + if ($is_1_ph) + { + $powerSteps = [$this->GetValue("Mindestaldestrom") * 230]; + } + else + { + $powerSteps = [$this->GetValue("Mindestaldestrom") * 400 * 1.71]; + } + } + else + { + $powerSteps = $this->Get_Array_From_Current($this->GetValue("Is_1_ph") , $this->GetValue("Max_Current") , $this->GetValue("Aktuelle_Leistung") , $this->GetValue("IsTimerActive_Null_Timer")); + } + // PowerSteps in der RegisterVariable speichern + SetValue($this->GetIDForIdent("PowerSteps") , json_encode($powerSteps)); + // Rückgabe der Powersteps + $counter = $this->GetValue("Pending_Counter"); + if ($this->GetValue("Aktuelle_Leistung") > (1.11 * $this->GetValue("Ladeleistung_Effektiv"))) + { + $this->SetValue("Pending_Counter", $counter + 1); + } + elseif (max($this->Get_Array_From_Current($this->GetValue("Is_1_ph") , $this->GetValue("Max_Current") , $this->GetValue("Aktuelle_Leistung") , $this->GetValue("IsTimerActive_Null_Timer"))) < (1.11 * $this->GetValue("Ladeleistung_Effektiv"))) + { // diesen elseif ggf wieder rauslöschen + $this->SetValue("Pending_Counter", $counter + 1); + } + else + { + $this->SetValue("Pending_Counter", 0); + } + if ($counter > (90 / ($this->ReadPropertyInteger("Interval")))) + { + $this->SetValue("Pending_Counter", 0); + if ((max(json_decode($this->GetValue("PowerSteps")))) > 0) + { + if ($this->GetValue("Aktuelle_Leistung") > (1.11 * $this->GetValue("Ladeleistung_Effektiv"))) + { + $this->Calc_Max_Current($this->GetValue("Is_1_ph")); + } + } + } + return $powerSteps; + } + // + public function sendPowerToStation(float $value) + { + $baseUrl = ""; + $stationType = $this->ReadPropertyInteger("Ladestation"); + switch ($stationType) + { + case 1: // GO-E alt + $baseUrl = "http://" . $this->ReadPropertyString("IP_Adresse") . "/mqtt?payload="; + break; + case 2: // GO-E Gemini + $baseUrl = "http://" . $this->ReadPropertyString("IP_Adresse") . "/api/set?"; + break; + case 3: // Smart Me Pico + $baseUrl = "https://api.smart-me.com/pico/loadmanagementgroup/current/" . $this->ReadPropertyString("Seriennummer") . "?current="; + break; + case 4: // Dummy + // Nichts zu tun für Dummy station + return; + case 5: // Easee Solar + // Keine base Url nötig + + break; + case 6: // Easee + // Keine base Url nötig + + break; + } + $ch = curl_init(); + IPS_LogMessage("value", "nach konvertierung" . $value); + if ($value == 0) + { + switch ($stationType) + { + case 1: // GO-E alt + $url = $baseUrl . "alw=0"; + break; + case 2: // GO-E Gemini + $url = $baseUrl . "frc=1&sua=false"; + break; + case 3: // Smart Me Pico + $url = $baseUrl . "0"; + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_setopt($ch, CURLOPT_USERPWD, $this->ReadPropertyString("Username") . ":" . $this->ReadPropertyString("Password")); + break; + case 4: // Dummy + // Nichts zu tun für Dummy station + return; + case 5: // Easee Solar + if ($this->ReadPropertyString("Username") != $this->GetValue("Letzer_User")) + { + return; + } + $url = "https://api.easee.com/api/chargers/" . $this->ReadPropertyString("Seriennummer") . "/commands/set_dynamic_charger_current"; + curl_setopt_array($ch, [CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "{\"amps\":" . $value . ",\"minutes\":0}", CURLOPT_HTTPHEADER => ["Authorization: Bearer " . GetValue($this->ReadPropertyInteger("Token_Easee")) . "", "content-type: application/*+json"], ]); + break; + case 6: // Easee + $url = "https://api.easee.com/api/chargers/" . $this->ReadPropertyString("Seriennummer") . "/commands/set_dynamic_charger_current"; + curl_setopt_array($ch, [CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "{\"amps\":" . $value . ",\"minutes\":0}", CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $this->GetBuffer("Token_Intern") . "", "content-type: application/*+json"], ]); + break; + default: + return "Invalid station type."; + } + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $response = curl_exec($ch); + curl_close($ch); + return $response; + } + elseif ($value >= 1 && $value <= 32) + { + switch ($stationType) + { + case 1: // Go-E Alt + $url1 = $baseUrl . "alw=1"; + $url2 = $baseUrl . "amp=$value"; + break; + case 2: // Go-E Gemini + $url1 = $baseUrl . "frc=2"; + $url2 = $baseUrl . "amp=$value"; + break; + case 3: // Pico + $url2 = $baseUrl . ($value * 1000); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_setopt($ch, CURLOPT_USERPWD, $this->ReadPropertyString("Username") . ":" . $this->ReadPropertyString("Password")); + break; + case 4: //Dummy + // Nichts zu tun für Dummy station + return; + case 5: // Easee solar + if ($this->ReadPropertyString("Username") != $this->GetValue("Letzer_User")) + { + return; + } + $url2 = "https://api.easee.com/api/chargers/" . $this->ReadPropertyString("Seriennummer") . "/commands/set_dynamic_charger_current"; + curl_setopt_array($ch, [CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "{\"amps\":" . $value . ",\"minutes\":0}", CURLOPT_HTTPHEADER => ["Authorization: Bearer " . GetValue($this->ReadPropertyInteger("Token_Easee")) . "", "content-type: application/*+json"], ]); + break; + case 6: // Easee + $url2 = "https://api.easee.com/api/chargers/" . $this->ReadPropertyString("Seriennummer") . "/commands/set_dynamic_charger_current"; + curl_setopt_array($ch, [CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "{\"amps\":" . $value . ",\"minutes\":0}", CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $this->GetBuffer("Token_Intern") . "", "content-type: application/*+json"], ]); + break; + default: + return "Invalid station type."; + } + if (isset($url1)) + { + curl_setopt($ch, CURLOPT_URL, $url1); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $response1 = curl_exec($ch); + if (curl_errno($ch)) + { + curl_close($ch); + return "Error:" . curl_error($ch); + } + } + curl_setopt($ch, CURLOPT_URL, $url2); + $response2 = curl_exec($ch); + if (curl_errno($ch)) + { + curl_close($ch); + return "Error:" . curl_error($ch); + } + curl_close($ch); + return; + } + else + { + return "Invalid value. Must be between 0 and 32."; + } + } + // Token für Solarladen Easee neu holen + public function Refresh_Token() + { + $payload = json_encode(['userName' => $this->ReadPropertyString("Username") , 'password' => $this->ReadPropertyString("Password") , ]); + // cURL-Handle initialisieren + $ch = curl_init('https://api.easee.com/api/accounts/login'); + // cURL-Optionen setzen + curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, // Antwort als String zurückgeben + CURLOPT_POST => true, // POST-Methode verwenden + CURLOPT_HTTPHEADER => ['Accept: application/json', 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => $payload, // JSON-Body übergeben + ]); + // Anfrage ausführen und Antwort speichern + $response = curl_exec($ch); + // Auf Fehler prüfen + if ($response === false) + { + echo 'cURL-Fehler: ' . curl_error($ch); + curl_close($ch); + exit; + } + // cURL-Handle schließen + curl_close($ch); + $this->SetBuffer("Token_Intern", (json_decode($response, true) ['accessToken'])); + } + // Intern Idle counter zählen + public function CheckIdle($power) + { + $lastpower = GetValue($this->GetIDForIdent("Aktuelle_Leistung")); + if ($lastpower != $power) + { + $this->SetValue("Idle", false); + $this->SetValue("IdleCounter", $this->ReadPropertyInteger("IdleCounterMax")); + } + // IdleCounter auslesen und verarbeiten + $idleCounter = $this->GetValue("IdleCounter"); + if ($idleCounter > 0) + { + $this->SetValue("Idle", false); + $this->SetValue("IdleCounter", $idleCounter - 1); + } + else + { + $this->SetValue("Idle", true); + } + } +} +?> diff --git a/Manager/module.php b/Manager/module.php index 4c78aa4..9362862 100644 --- a/Manager/module.php +++ b/Manager/module.php @@ -1,11 +1,9 @@ RegisterPropertyInteger("Peakleistung", 0); $this->RegisterPropertyInteger("Ueberschussleistung", 0); @@ -19,461 +17,361 @@ class Manager extends IPSModule $this->RegisterPropertyInteger("DatenHoch", 0); // Initialisierung mit 0 $this->RegisterPropertyInteger("DatenZuruck", 0); // Initialisierung mit 0 $this->RegisterPropertyInteger("Interval", 2); // Recheninterval - $this->RegisterVariableBoolean("Is_Peak_Shaving", false); - // Timer registrieren - - $this->RegisterTimer( - "Timer_DistributeEnergy", - $this->ReadPropertyInteger("Interval") * 1000, - "IPS_RequestAction(" . - $this->InstanceID . - ', "DistributeEnergy", "");' - ); + $this->RegisterTimer("Timer_DistributeEnergy", $this->ReadPropertyInteger("Interval") * 1000, "IPS_RequestAction(" . $this->InstanceID . ', "DistributeEnergy", "");'); } - public function ApplyChanges() { parent::ApplyChanges(); - - $this->SetTimerInterval( - "Timer_DistributeEnergy", - $this->ReadPropertyInteger("Interval") * 1000 - ); + $this->SetTimerInterval("Timer_DistributeEnergy", $this->ReadPropertyInteger("Interval") * 1000); } - public function RequestAction($Ident, $Value) { - switch ($Ident) { + switch ($Ident) + { case "DistributeEnergy": // Fallunterscheidung, ist der Manager stand-alone oder in einem verbund mit Hauptmanager? - if ($this->ReadPropertyBoolean("HauptmanagerAktiv") == true) { + if ($this->ReadPropertyBoolean("HauptmanagerAktiv") == true) + { // Wenn im Verbund, parse die Verbraucherdaten und sende sie dem Hauptmanager, sofern dieser aktiv ist - $data = json_decode( - GetValue($this->ReadPropertyInteger("DatenZuruck")), - true - ); - - if (isset($data["Timestamp"])) { + $data = json_decode(GetValue($this->ReadPropertyInteger("DatenZuruck")) , true); + if (isset($data["Timestamp"])) + { $timestamp = $data["Timestamp"]; $currentTime = time(); - - if ($currentTime - $timestamp < 3600) { + if ($currentTime - $timestamp < 3600) + { $this->DistributeEnergy_Extern(); - } else { - $sendarray = [ - "Netzbezug" => GetValue( - $this->ReadPropertyInteger("Netzbezug") - ), - "Timestamp" => time(), - ]; - - SetValue( - $this->ReadPropertyInteger("DatenHoch"), - json_encode($sendarray) - ); - + } + else + { + $sendarray = ["Netzbezug" => GetValue($this->ReadPropertyInteger("Netzbezug")) , "Timestamp" => time() , ]; + SetValue($this->ReadPropertyInteger("DatenHoch") , json_encode($sendarray)); $this->DistributeEnergy(); } - } else { - $sendarray = [ - "Netzbezug" => GetValue( - $this->ReadPropertyInteger("Netzbezug") - ), - "Timestamp" => time(), - ]; - - SetValue( - $this->ReadPropertyInteger("DatenHoch"), - json_encode($sendarray) - ); - + } + else + { + $sendarray = ["Netzbezug" => GetValue($this->ReadPropertyInteger("Netzbezug")) , "Timestamp" => time() , ]; + SetValue($this->ReadPropertyInteger("DatenHoch") , json_encode($sendarray)); $this->DistributeEnergy(); } - } else { + } + else + { // wenn stand-alone, rufe einfach die Methode zum verteilen auf $this->DistributeEnergy(); } - - break; - + break; case "ApplyChanges": $this->ApplyChanges(); - break; - + break; default: throw new Exception("Invalid Ident"); } } - public function DistributeEnergy() { // Alle Energieverbraucher auslesen und dekodieren - $Verbraucher_Liste = json_decode( - $this->ReadPropertyString("Verbraucher_Liste"), - true - ); - - if (empty($Verbraucher_Liste)) { + $Verbraucher_Liste = json_decode($this->ReadPropertyString("Verbraucher_Liste") , true); + if (empty($Verbraucher_Liste)) + { // Wenn keine Verbruacher angemeldet sind abbrechen return; } - // Hilfsvariabeln initialiseren - $filteredVerbraucher = []; // Array das später mit allen Verbrauchsdaten der Energieverbraucher gefüllt wird $allIdle = true; // Variable zur Überprüfung, ob alle Benutzer Idle = true sind $totalAktuelle_Leistung = 0; // Variable zur Summierung der Aktuelle_Leistung Werte $helpvar_offset_peakermitteln = 0; // Variable zur Summierung der Aktuelle_Leistung Werte - // Fülle das Array mit allen entsprechenden Werten der Verbraucher ab - foreach ($Verbraucher_Liste as $user) { + foreach ($Verbraucher_Liste as $user) + { // Werte direkt von der Verbraucher-Instanz abrufen - $Aktuelle_Leistung = GetValue( - IPS_GetObjectIDByIdent("Power", $user["Verbraucher"]) - ); // Aktuelle Leistung durch Power ersetzt - $Bezogene_Energie = GetValue( - IPS_GetObjectIDByIdent("Bezogene_Energie", $user["Verbraucher"]) - ); - $PV_Prio = GetValue( - IPS_GetObjectIDByIdent("PV_Prio", $user["Verbraucher"]) - ); - $Sperre_Prio = GetValue( - IPS_GetObjectIDByIdent("Sperre_Prio", $user["Verbraucher"]) - ); - $idle = GetValue( - IPS_GetObjectIDByIdent("Idle", $user["Verbraucher"]) - ); - $powerStepsJson = GetValue( - IPS_GetObjectIDByIdent("PowerSteps", $user["Verbraucher"]) - ); + $Aktuelle_Leistung = GetValue(IPS_GetObjectIDByIdent("Power", $user["Verbraucher"])); // Aktuelle Leistung durch Power ersetzt + $Bezogene_Energie = GetValue(IPS_GetObjectIDByIdent("Bezogene_Energie", $user["Verbraucher"])); + $PV_Prio = GetValue(IPS_GetObjectIDByIdent("PV_Prio", $user["Verbraucher"])); + $Sperre_Prio = GetValue(IPS_GetObjectIDByIdent("Sperre_Prio", $user["Verbraucher"])); + $idle = GetValue(IPS_GetObjectIDByIdent("Idle", $user["Verbraucher"])); + $powerStepsJson = GetValue(IPS_GetObjectIDByIdent("PowerSteps", $user["Verbraucher"])); $powerSteps = json_decode($powerStepsJson, true); - $delta = GetValue( - IPS_GetObjectIDByIdent("Leistung_Delta", $user["Verbraucher"]) - ); - + $delta = GetValue(IPS_GetObjectIDByIdent("Leistung_Delta", $user["Verbraucher"])); // Verbraucher-Daten zum gefilterten Array hinzufügen - $filteredVerbraucher[] = [ - "Verbraucher" => $user["Verbraucher"], - "InstanceID" => $user["Verbraucher"], - "Aktuelle_Leistung" => $Aktuelle_Leistung, - "Bezogene_Energie" => $Bezogene_Energie, - "PV_Prio" => $PV_Prio, - "Sperre_Prio" => $Sperre_Prio, - "Idle" => $idle, - "PowerSteps" => $powerSteps, - "Leistung_Delta" => $delta, - ]; - + $filteredVerbraucher[] = ["Verbraucher" => $user["Verbraucher"], "InstanceID" => $user["Verbraucher"], "Aktuelle_Leistung" => $Aktuelle_Leistung, "Bezogene_Energie" => $Bezogene_Energie, "PV_Prio" => $PV_Prio, "Sperre_Prio" => $Sperre_Prio, "Idle" => $idle, "PowerSteps" => $powerSteps, "Leistung_Delta" => $delta, ]; // Überprüfen, ob alle Benutzer Idle = true sind (bereit für eine Leistungsänderung), wenn einer nicht ist, wird später verworfen... - if (!$idle) { + if (!$idle) + { $allIdle = false; } - // Addiere die aktuell bereits verwendete Leistung auf, um sie bei der verteilung zu berücksichtigen $totalAktuelle_Leistung += $Aktuelle_Leistung - $delta; } - // Variante der Leistungsregelung (Überschuss, Peak) ermitteln und aktuellen Netzbezug bereitstellen $Netzbezug = GetValue($this->ReadPropertyInteger("Netzbezug")); $Peakleistung = $this->ReadPropertyInteger("Peakleistung"); - $Ueberschussleistung = $this->ReadPropertyInteger( - "Ueberschussleistung" - ); - + $Ueberschussleistung = $this->ReadPropertyInteger("Ueberschussleistung"); // Dynamische ermittlung der Betriebsart - if ($this->ReadPropertyBoolean("UmschaltpunktStatisch") == false) { + if ($this->ReadPropertyBoolean("UmschaltpunktStatisch") == false) + { // Fallunterscheidung ob auf Solarladen oder Peakshaving gerregelt wird. - if ($Netzbezug < ($Peakleistung + $Ueberschussleistung) / 2) { - $remainingPower = -1 * (-1 * $Ueberschussleistung + $Netzbezug); + if ($Netzbezug < ($Peakleistung + $Ueberschussleistung) / 2) + { + $remainingPower = - 1 * (-1 * $Ueberschussleistung + $Netzbezug); $Is_Peak_Shaving = false; - } else { + } + else + { $remainingPower = $Peakleistung - $Netzbezug; $Is_Peak_Shaving = true; } } // Statische ermittlung der Betriebsart - else { - if ( - $Netzbezug < $this->ReadPropertyInteger("Umschalt_Solarladen") - ) { - $remainingPower = -1 * (-1 * $Ueberschussleistung + $Netzbezug); + else + { + if ($Netzbezug < $this->ReadPropertyInteger("Umschalt_Solarladen")) + { + $remainingPower = - 1 * (-1 * $Ueberschussleistung + $Netzbezug); $Is_Peak_Shaving = false; - } elseif ( - $Netzbezug > $this->ReadPropertyInteger("Umschalt_Peakshaving") - ) { + } + elseif ($Netzbezug > $this->ReadPropertyInteger("Umschalt_Peakshaving")) + { $remainingPower = $Peakleistung - $Netzbezug; $Is_Peak_Shaving = true; - } elseif ($this->GetValue("Is_Peak_Shaving") == false) { - $remainingPower = -1 * (-1 * $Ueberschussleistung + $Netzbezug); + } + elseif ($this->GetValue("Is_Peak_Shaving") == false) + { + $remainingPower = - 1 * (-1 * $Ueberschussleistung + $Netzbezug); $Is_Peak_Shaving = false; - } elseif ($this->GetValue("Is_Peak_Shaving") == true) { + } + elseif ($this->GetValue("Is_Peak_Shaving") == true) + { $remainingPower = $Peakleistung - $Netzbezug; $Is_Peak_Shaving = true; } } - // Aktuelle bereits verwendete Leistung auf die verbleibende Leistung als Offset summieren. $remainingPower += $totalAktuelle_Leistung; - // Frage alle Energieverbraucher ab, was sie für Leistungen benötigen könnten - foreach ($Verbraucher_Liste as $user) { - if (IPS_InstanceExists($user["Verbraucher"])) { - IPS_RequestAction( - $user["Verbraucher"], - "GetCurrentData", - $Is_Peak_Shaving - ); + foreach ($Verbraucher_Liste as $user) + { + if (IPS_InstanceExists($user["Verbraucher"])) + { + IPS_RequestAction($user["Verbraucher"], "GetCurrentData", $Is_Peak_Shaving); } } - // Abbrechen wenn es keine Verbruacher gibt, die verfügbar sind - if (empty($filteredVerbraucher)) { + if (empty($filteredVerbraucher)) + { return; } - // Wenn nicht alle Benutzer Idle = true sind, oder sich der zustand von Is_Peak_shaving gerade verändert hat rufe SetAktuelle_Leistung mit Aktuelle_Leistung Werten auf, (alle Verbraucher behalten die aktuelle Leistung) - if ( - !$allIdle || - $Is_Peak_Shaving != $this->GetValue("Is_Peak_Shaving") - ) { - foreach ($filteredVerbraucher as $user) { - IPS_RequestAction( - $user["InstanceID"], - "SetAktuelle_Leistung", - $user["Aktuelle_Leistung"] - ); + if (!$allIdle || $Is_Peak_Shaving != $this->GetValue("Is_Peak_Shaving")) + { + foreach ($filteredVerbraucher as $user) + { + IPS_RequestAction($user["InstanceID"], "SetAktuelle_Leistung", $user["Aktuelle_Leistung"]); } $this->SetValue("Is_Peak_Shaving", $Is_Peak_Shaving); - return; } - $this->SetValue("Is_Peak_Shaving", $Is_Peak_Shaving); - // Sortiere die Verbruacher nach Priorität entweder der PV_Prio oder der Peak Prio - usort($filteredVerbraucher, function ($a, $b) use ($Is_Peak_Shaving) { + usort($filteredVerbraucher, function ($a, $b) use ($Is_Peak_Shaving) + { $primaryKey = $Is_Peak_Shaving ? "Sperre_Prio" : "PV_Prio"; // Wenn die Prio geleich ist, sortiere danach welcher verbraucher bisher am wenigsten Energie bekommen hat. - if ($a[$primaryKey] == $b[$primaryKey]) { - return round($a["Bezogene_Energie"] / 2000) <=> - round($b["Bezogene_Energie"] / 2000); + if ($a[$primaryKey] == $b[$primaryKey]) + { + return round($a["Bezogene_Energie"] / 2000) <= > round($b["Bezogene_Energie"] / 2000); } - return $a[$primaryKey] <=> $b[$primaryKey]; + return $a[$primaryKey] <= > $b[$primaryKey]; }); - // Primärschlüssel für die Priorität basierend auf dem Parameter auswählen (für sortierung in gruppen anschliessend) $priorityKey = $Is_Peak_Shaving ? "Sperre_Prio" : "PV_Prio"; - // Schleife durch alle Prioritäten - $priorities = array_unique( - array_column($filteredVerbraucher, $priorityKey) - ); + $priorities = array_unique(array_column($filteredVerbraucher, $priorityKey)); $groupedUsers = []; - - foreach ($priorities as $priority) { - $groupedUsers[$priority] = array_filter( - $filteredVerbraucher, - function ($user) use ($priority, $priorityKey) { - return $user[$priorityKey] == $priority; - } - ); + foreach ($priorities as $priority) + { + $groupedUsers[$priority] = array_filter($filteredVerbraucher, function ($user) use ($priority, $priorityKey) + { + return $user[$priorityKey] == $priority; + }); } - // Jetzt werden die energien pro gruppe verteilt (Immer alle pro prio in einer gruppe miteinander) - foreach ($groupedUsers as $priority => $users) { + foreach ($groupedUsers as $priority => $users) + { // Verbraucher mit gleicher Priorität sammeln - $samePriorityUsers = isset($groupedUsers[$priority]) - ? $groupedUsers[$priority] - : []; - + $samePriorityUsers = isset($groupedUsers[$priority]) ? $groupedUsers[$priority] : []; // Wenn keine Verbraucher mit gleicher Priorität vorhanden sind, überspringen - if (empty($samePriorityUsers)) { + if (empty($samePriorityUsers)) + { continue; } $withZero = []; $withoutZeroHigh = []; $withoutZeroLow = []; - // Sammle alle Verbraucher die nicht null als Verbruach annehmen können. (inkl. sortierung in positive und Negative) - foreach ($samePriorityUsers as $entry) { + foreach ($samePriorityUsers as $entry) + { $withZero[] = $entry; - - if (min($entry["PowerSteps"]) > 0) { + if (min($entry["PowerSteps"]) > 0) + { $withoutZeroHigh[] = $entry; } - if (max($entry["PowerSteps"]) < 0) { + if (max($entry["PowerSteps"]) < 0) + { $withoutZeroLow[] = $entry; } } - // positiven Verbrauchern die nicht 0 annhemen können bereits den minimalwert zuteilen - if (!empty($withoutZeroHigh)) { - foreach ($withoutZeroHigh as $entry) { + if (!empty($withoutZeroHigh)) + { + foreach ($withoutZeroHigh as $entry) + { $instanceID = $entry["InstanceID"]; $minPowerStep = min($entry["PowerSteps"]); } } // negativen Verbrauchern die nicht 0 annhemen können bereits den minimalwert zuteilen - if (!empty($withoutZeroLow)) { - foreach ($withoutZeroLow as $entry) { + if (!empty($withoutZeroLow)) + { + foreach ($withoutZeroLow as $entry) + { $instanceID = $entry["InstanceID"]; $minPowerStep = max($entry["PowerSteps"]); } } - // Nun die Verbrucher verteilen, die auch 0 erhalten können. $samePriorityUsers = $withZero; - $userEnergyProv = []; - - foreach ($samePriorityUsers as $entry) { + foreach ($samePriorityUsers as $entry) + { $instanceID = $entry["InstanceID"]; // Schutz: falls PowerSteps nicht gesetzt oder kein Array ist - $steps = - isset($entry["PowerSteps"]) && - is_array($entry["PowerSteps"]) - ? $entry["PowerSteps"] - : [0]; - + $steps = isset($entry["PowerSteps"]) && is_array($entry["PowerSteps"]) ? $entry["PowerSteps"] : [0]; // Wenn 0 als möglicher Step vorhanden ist -> 0 setzen - $minStep = min($steps); $maxStep = max($steps); - - if (in_array(0, $steps, true)) { + if (in_array(0, $steps, true)) + { $userEnergyProv[$instanceID] = 0; continue; - } elseif ($minStep > 0) { + } + elseif ($minStep > 0) + { // nur positive Schritte -> minimalen positiven Wert einsetzen $userEnergyProv[$instanceID] = $minStep; // entspricht deinem vorherigen Verhalten: remainingPower reduzieren $remainingPower -= $minStep; - } elseif ($maxStep < 0) { + } + elseif ($maxStep < 0) + { // nur negative Schritte -> maximalen (am wenigsten negativen) Wert einsetzen $userEnergyProv[$instanceID] = $maxStep; // entspricht deinem vorherigen Verhalten: remainingPower erhöhen (maxStep ist negativ) $remainingPower += $maxStep; - } else { + } + else + { // Mixed (positive & negative) aber kein 0 -> Fallback 0 (ändere wenn nötig) $userEnergyProv[$instanceID] = 0; } } - // Beginne mit aktiver Verteilung - if ($remainingPower >= 0) { + if ($remainingPower >= 0) + { // Alle Schritte der Benutzer in einem Array sammeln $allSteps = []; - foreach ($samePriorityUsers as $user) { - foreach ($user["PowerSteps"] as $step) { - if ($step >= 0) { - $allSteps[] = [ - "user" => $user["InstanceID"], - //"Leistung_Delta" => $user["Leistung_Delta"], - "step" => $step, - ]; + foreach ($samePriorityUsers as $user) + { + foreach ($user["PowerSteps"] as $step) + { + if ($step >= 0) + { + $allSteps[] = ["user" => $user["InstanceID"], + //"Leistung_Delta" => $user["Leistung_Delta"], + "step" => $step, ]; } } } - // Sortiere die Schritte nach Größe - usort($allSteps, function ($a, $b) { - return $a["step"] <=> $b["step"]; + usort($allSteps, function ($a, $b) + { + return $a["step"] <= > $b["step"]; }); - //if remaining power >0 // Iteriere durch alle Schritte - foreach ($allSteps as $entry) { + foreach ($allSteps as $entry) + { $user = $entry["user"]; $powerstep = $entry["step"]; - // Überprüfe, ob noch genügend verbleibende Energie für den nächsten Schritt vorhanden ist - if ( - $remainingPower >= - $powerstep - $userEnergyProv[$user] - ) { + if ($remainingPower >= $powerstep - $userEnergyProv[$user]) + { // oder bedingung testen // Aktualisiere die verbleibende Energie und die bereitgestellte Energie für den Benutzer $remainingPower -= $powerstep - $userEnergyProv[$user]; $userEnergyProv[$user] = $powerstep; } } - // Prüfen, dass jeder User mindestens seinen minimalwert an Leistung bekommt - foreach ($userEnergyProv as $userInstanceID => $leistung) { + foreach ($userEnergyProv as $userInstanceID => $leistung) + { // Innerhalb der Schleife: alle nicht-negativen Leistungen sammeln - $positiveValues = array_filter( - array_column( - $samePriorityUsers, - "PowerSteps", - "InstanceID" - )[$userInstanceID], - function ($l) { - return $l >= 0; - } - ); + $positiveValues = array_filter(array_column($samePriorityUsers, "PowerSteps", "InstanceID") [$userInstanceID], function ($l) + { + return $l >= 0; + }); // Falls keine Werte ≥ 0 vorhanden sind, auf 0 zurückfallen - $fallbackMinimum = empty($positiveValues) - ? max( - array_column( - $samePriorityUsers, - "PowerSteps", - "InstanceID" - )[$userInstanceID] - ) - : min($positiveValues); - + $fallbackMinimum = empty($positiveValues) ? max(array_column($samePriorityUsers, "PowerSteps", "InstanceID") [$userInstanceID]) : min($positiveValues); // minimalleistung = dieser Fallback $minimalleistung = $fallbackMinimum; - //den höheren Wert wählen und für IPS negativieren - - if (abs($leistung) > abs($minimalleistung)) { + if (abs($leistung) > abs($minimalleistung)) + { $schreibleistung = $leistung; - } else { + } + else + { $schreibleistung = $minimalleistung; } - // Die Veteilten Leistungen auf die Verbruacher schreiben - if (IPS_InstanceExists($userInstanceID)) { - IPS_RequestAction( - $userInstanceID, - "SetAktuelle_Leistung", - $schreibleistung - ); + if (IPS_InstanceExists($userInstanceID)) + { + IPS_RequestAction($userInstanceID, "SetAktuelle_Leistung", $schreibleistung); } } - } else { + } + else + { // Alle Schritte der Benutzer in einem Array sammeln $allSteps = []; - foreach ($samePriorityUsers as $user) { - foreach ($user["PowerSteps"] as $step) { - if ($step <= 0) { - $allSteps[] = [ - "user" => $user["InstanceID"], - "step" => -1 * $step, - ]; + foreach ($samePriorityUsers as $user) + { + foreach ($user["PowerSteps"] as $step) + { + if ($step <= 0) + { + $allSteps[] = ["user" => $user["InstanceID"], "step" => - 1 * $step, ]; } } } - // Sortiere die Schritte nach Größe - usort($allSteps, function ($a, $b) { - return $a["step"] <=> $b["step"]; + usort($allSteps, function ($a, $b) + { + return $a["step"] <= > $b["step"]; }); - $remainingPower = $remainingPower * -1; // Iteriere durch alle Schritte - foreach ($allSteps as $entry) { + foreach ($allSteps as $entry) + { $user = $entry["user"]; $powerstep = $entry["step"]; - // Überprüfe, ob noch genügend verbleibende Energie für den nächsten Schritt vorhanden ist - if ( - $remainingPower >= - $powerstep - $userEnergyProv[$user] - ) { + if ($remainingPower >= $powerstep - $userEnergyProv[$user]) + { // oder bedingung testen // Aktualisiere die verbleibende Energie und die bereitgestellte Energie für den Benutzer $remainingPower -= $powerstep - $userEnergyProv[$user]; @@ -481,139 +379,65 @@ class Manager extends IPSModule } } $remainingPower = $remainingPower * -1; - // Prüfen, dass jeder User mindestens seinen minimalwert an Leistung bekommt - foreach ($userEnergyProv as $userInstanceID => $leistung) { + foreach ($userEnergyProv as $userInstanceID => $leistung) + { // Innerhalb der Schleife: alle nicht-negativen Leistungen sammeln - $positiveValues = array_filter( - array_column( - $samePriorityUsers, - "PowerSteps", - "InstanceID" - )[$userInstanceID], - function ($l) { - return $l <= 0; - } - ); + $positiveValues = array_filter(array_column($samePriorityUsers, "PowerSteps", "InstanceID") [$userInstanceID], function ($l) + { + return $l <= 0; + }); // Falls keine Werte ≥ 0 vorhanden sind, auf 0 zurückfallen - $fallbackMinimum = empty($positiveValues) - ? min( - array_column( - $samePriorityUsers, - "PowerSteps", - "InstanceID" - )[$userInstanceID] - ) - : max($positiveValues); - + $fallbackMinimum = empty($positiveValues) ? min(array_column($samePriorityUsers, "PowerSteps", "InstanceID") [$userInstanceID]) : max($positiveValues); // minimalleistung = dieser Fallback $minimalleistung = $fallbackMinimum; - // den höheren Wert wählen und negieren - - if (abs($leistung) > abs($minimalleistung)) { + if (abs($leistung) > abs($minimalleistung)) + { $schreibleistung = $leistung * -1; - } else { + } + else + { $schreibleistung = $minimalleistung; } - // Die Veteilten Leistungen auf die Verbruacher schreiben - if (IPS_InstanceExists($userInstanceID)) { - IPS_RequestAction( - $userInstanceID, - "SetAktuelle_Leistung", - $schreibleistung - ); + if (IPS_InstanceExists($userInstanceID)) + { + IPS_RequestAction($userInstanceID, "SetAktuelle_Leistung", $schreibleistung); } } } } } - public function DistributeEnergy_Extern() { // Systemvariablen abrufen $Netzbezug = GetValue($this->ReadPropertyInteger("Netzbezug")); - - $Verbraucher_Liste = json_decode( - $this->ReadPropertyString("Verbraucher_Liste"), - true - ); + $Verbraucher_Liste = json_decode($this->ReadPropertyString("Verbraucher_Liste") , true); $filteredVerbraucher = []; // Fülle das Array mit allen entsprechenden Werten der Verbraucher ab - foreach ($Verbraucher_Liste as $user) { + foreach ($Verbraucher_Liste as $user) + { // Werte direkt von der Verbraucher-Instanz abrufen - $Aktuelle_Leistung = GetValue( - IPS_GetObjectIDByIdent( - "Aktuelle_Leistung", - $user["Verbraucher"] - ) - ); - $Bezogene_Energie = GetValue( - IPS_GetObjectIDByIdent("Bezogene_Energie", $user["Verbraucher"]) - ); - $PV_Prio = GetValue( - IPS_GetObjectIDByIdent("PV_Prio", $user["Verbraucher"]) - ); - $Sperre_Prio = GetValue( - IPS_GetObjectIDByIdent("Sperre_Prio", $user["Verbraucher"]) - ); - $idle = GetValue( - IPS_GetObjectIDByIdent("Idle", $user["Verbraucher"]) - ); - $powerStepsJson = GetValue( - IPS_GetObjectIDByIdent("PowerSteps", $user["Verbraucher"]) - ); - $delta = GetValue( - IPS_GetObjectIDByIdent("Leistung_Delta", $user["Verbraucher"]) - ); + $Aktuelle_Leistung = GetValue(IPS_GetObjectIDByIdent("Aktuelle_Leistung", $user["Verbraucher"])); + $Bezogene_Energie = GetValue(IPS_GetObjectIDByIdent("Bezogene_Energie", $user["Verbraucher"])); + $PV_Prio = GetValue(IPS_GetObjectIDByIdent("PV_Prio", $user["Verbraucher"])); + $Sperre_Prio = GetValue(IPS_GetObjectIDByIdent("Sperre_Prio", $user["Verbraucher"])); + $idle = GetValue(IPS_GetObjectIDByIdent("Idle", $user["Verbraucher"])); + $powerStepsJson = GetValue(IPS_GetObjectIDByIdent("PowerSteps", $user["Verbraucher"])); + $delta = GetValue(IPS_GetObjectIDByIdent("Leistung_Delta", $user["Verbraucher"])); $powerSteps = json_decode($powerStepsJson, true); - // Verbraucher-Daten zum gefilterten Array hinzufügen - $filteredVerbraucher[] = [ - "Verbraucher" => $user["Verbraucher"], - "InstanceID" => $user["Verbraucher"], - "Aktuelle_Leistung" => $Aktuelle_Leistung, - "Bezogene_Energie" => $Bezogene_Energie, - "PV_Prio" => $PV_Prio, - "Sperre_Prio" => $Sperre_Prio, - "Idle" => $idle, - "PowerSteps" => $powerSteps, - "Leistung_Delta" => $delta, - "ParentManager" => $this->ReadPropertyInteger("ManagerID"), - ]; + $filteredVerbraucher[] = ["Verbraucher" => $user["Verbraucher"], "InstanceID" => $user["Verbraucher"], "Aktuelle_Leistung" => $Aktuelle_Leistung, "Bezogene_Energie" => $Bezogene_Energie, "PV_Prio" => $PV_Prio, "Sperre_Prio" => $Sperre_Prio, "Idle" => $idle, "PowerSteps" => $powerSteps, "Leistung_Delta" => $delta, "ParentManager" => $this->ReadPropertyInteger("ManagerID") , ]; } - $sendarray = []; - - $sendarray = [ - "User" => $filteredVerbraucher, - "Netzbezug" => $Netzbezug, - "Timestamp" => time(), - ]; - - SetValue( - $this->ReadPropertyInteger("DatenHoch"), - json_encode($sendarray) - ); - - $answerArray = json_decode( - GetValue($this->ReadPropertyInteger("DatenZuruck")), - true - ); - - foreach ($answerArray["User"] as $user) { - IPS_RequestAction( - $user["InstanceID"], - "GetCurrentData", - $answerArray["Is_Peak_Shaving"] - ); - - IPS_RequestAction( - $user["InstanceID"], - "SetAktuelle_Leistung", - $user["Set_Leistung"] - ); + $sendarray = ["User" => $filteredVerbraucher, "Netzbezug" => $Netzbezug, "Timestamp" => time() , ]; + SetValue($this->ReadPropertyInteger("DatenHoch") , json_encode($sendarray)); + $answerArray = json_decode(GetValue($this->ReadPropertyInteger("DatenZuruck")) , true); + foreach ($answerArray["User"] as $user) + { + IPS_RequestAction($user["InstanceID"], "GetCurrentData", $answerArray["Is_Peak_Shaving"]); + IPS_RequestAction($user["InstanceID"], "SetAktuelle_Leistung", $user["Set_Leistung"]); } } }