Files
Symcon_Belevo_Energiemanage…/Ladestation/module.php
T
2026-08-25 14:43:45 +02:00

1998 lines
70 KiB
PHP

<?php
class Ladestation extends IPSModule
{
private const EASEE_GATEWAY_MODULE_ID = "{7A1F1D4B-3E7D-4A3B-9E54-61C8C3B7F201}";
private const EASEE_GATEWAY_REQUEST_ID = "{BC4E9B83-9C9B-44C3-A902-5CEB45B0E5B1}";
private const EASEE_GATEWAY_EVENT_ID = "{A8EF2E37-6B35-4E92-A7D1-4F8172790BA2}";
private const ADAPTIVE_MODEL_VERSION = "5";
private const ADAPTIVE_MISMATCH_FACTOR = 1.11;
private const ADAPTIVE_CONFIRMATION_SECONDS = 90;
private const PHASE_CONFIRMATION_SECONDS = 60;
public function Create()
{
parent::Create();
// Ladestationspezifische Properties
$this->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
// Nur für die fehlerfreie Übernahme bestehender Ladestation-Instanzen.
// Die Easee-Zugangsdaten werden nicht mehr aus dieser Property gelesen.
$this->RegisterPropertyInteger("Token_Easee", 0);
$this->RegisterPropertyInteger("Token_ECarUp", 0); // Recheninterval
$this->RegisterPropertyInteger("EaseeGatewayID", 0);
// Ladestationspezifische Variabeln
$this->RegisterVariableFloat("Max_Current","Maximaler Ladestrom","", 0);
IPS_SetHidden($this->GetIDForIdent("Max_Current"), true);
$this->SetValue("Max_Current", (float)$this->ReadPropertyInteger("Max_Current_abs"));
$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->RegisterVariableBoolean(
"Easee_Gateway_Connected",
"Easee Gateway verbunden",
"~Switch",
false
);
IPS_SetHidden($this->GetIDForIdent("Easee_Gateway_Connected"), true);
$this->SetBuffer("EaseeGatewayState", "{}");
$this->SetBuffer(
"AdaptiveReferenceMaxCurrent",
(string)$this->ReadPropertyInteger("Max_Current_abs")
);
$this->SetBuffer("AdaptiveLearnedMaxCurrent", "0");
$this->SetBuffer("AdaptiveMeasurementTimestamp", "0");
$this->SetBuffer("AdaptivePhaseKnown", "0");
$this->SetBuffer("AdaptivePhaseCounter", "0");
$this->SetBuffer(
"AdaptiveStationType",
(string)$this->ReadPropertyInteger("Ladestation")
);
$this->SetBuffer("AdaptiveModelVersion", self::ADAPTIVE_MODEL_VERSION);
// Kompatibilität mit bestehenden Instanzen der ursprünglichen Version.
// Der Inhalt wird nicht mehr verwendet; die Easee-Anmeldung übernimmt
// ausschließlich das SignalR-Gateway.
$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 GetConfigurationForm()
{
$form = json_decode(file_get_contents(__DIR__ . "/form.json"), true);
$fieldConfiguration = $this->GetStationFormConfiguration(
$this->ReadPropertyInteger("Ladestation")
);
foreach ($form["elements"] as &$element) {
$name = (string)($element["name"] ?? "");
if (!isset($fieldConfiguration[$name])) {
continue;
}
foreach ($fieldConfiguration[$name] as $parameter => $value) {
$element[$parameter] = $value;
}
}
unset($element);
return json_encode($form);
}
private function GetStationFormConfiguration(int $stationType): array
{
$configuration = [
"IP_Adresse" => [
"visible" => false,
"caption" => "IP-Adresse",
],
"ID" => [
"visible" => false,
"caption" => "Geräte-ID",
],
"Seriennummer" => [
"visible" => false,
"caption" => "Seriennummer",
],
"Username" => [
"visible" => false,
"caption" => "Benutzername",
],
"Password" => [
"visible" => false,
"caption" => "Passwort",
],
"Token_ECarUp" => [
"visible" => false,
"caption" => "Variable mit eCarUp API-Token",
],
"EaseeGatewayID" => [
"visible" => false,
],
"EaseeGatewayHint" => [
"visible" => false,
],
];
switch ($stationType) {
case 1:
$configuration["IP_Adresse"] = [
"visible" => true,
"caption" => "IP-Adresse der Go-E Wallbox",
];
break;
case 2:
$configuration["IP_Adresse"] = [
"visible" => true,
"caption" => "IP-Adresse der Go-E Gemini / Gemini Flex",
];
break;
case 3:
$configuration["ID"] = [
"visible" => true,
"caption" => "Smart-Me Geräte-ID",
];
$configuration["Seriennummer"] = [
"visible" => true,
"caption" => "Smart-Me Seriennummer",
];
$configuration["Username"] = [
"visible" => true,
"caption" => "Smart-Me Benutzername",
];
$configuration["Password"] = [
"visible" => true,
"caption" => "Smart-Me Passwort",
];
break;
case 5:
$configuration["ID"] = [
"visible" => true,
"caption" => "eCarUp Stations-/Connector-ID",
];
$configuration["Seriennummer"] = [
"visible" => true,
"caption" => "Easee Seriennummer",
];
$configuration["Username"] = [
"visible" => true,
"caption" => "eCarUp Benutzerkennung für Solarladen",
];
$configuration["Token_ECarUp"]["visible"] = true;
$configuration["EaseeGatewayID"]["visible"] = true;
$configuration["EaseeGatewayHint"]["visible"] = true;
break;
case 6:
$configuration["Seriennummer"] = [
"visible" => true,
"caption" => "Easee Seriennummer",
];
$configuration["EaseeGatewayID"]["visible"] = true;
$configuration["EaseeGatewayHint"]["visible"] = true;
break;
}
return $configuration;
}
private function UpdateStationForm(int $stationType)
{
foreach ($this->GetStationFormConfiguration($stationType) as $field => $parameters) {
foreach ($parameters as $parameter => $value) {
$this->UpdateFormField($field, $parameter, $value);
}
}
}
public function ApplyChanges()
{
parent::ApplyChanges();
// Bei aktualisierten Bestandsinstanzen die in Version 1.1 neue Variable
// sofort anlegen; RegisterVariableBoolean ist idempotent.
$this->RegisterVariableBoolean(
"Easee_Gateway_Connected",
"Easee Gateway verbunden",
"~Switch",
false
);
$this->SetTimerInterval("Timer_Do_UserCalc_EVC",$this->ReadPropertyInteger("Interval")*1000);
// Einen noch vorhandenen Token-Timer aus Altinstanzen sicher stilllegen.
$this->SetTimerInterval("Timer_Refresh_Token", 0);
$stationType = $this->ReadPropertyInteger("Ladestation");
// Einmalige Migration aus den bisherigen stationsspezifischen
// Lernalgorithmen in das gemeinsame Soll-/Ist-Modell.
if (
$this->GetBuffer("AdaptiveModelVersion") !== self::ADAPTIVE_MODEL_VERSION ||
(int)$this->GetBuffer("AdaptiveStationType") !== $stationType
) {
$this->SetValue("Car_detected", false);
$this->SetValue("Car_is_full", false);
$this->SetValue("Is_1_ph", false);
$this->SetValue("Pending_Counter", 0);
$this->SetValue(
"Max_Current",
(float)$this->ReadPropertyInteger("Max_Current_abs")
);
$this->SetBuffer(
"AdaptiveReferenceMaxCurrent",
(string)$this->ReadPropertyInteger("Max_Current_abs")
);
$this->SetBuffer("AdaptiveLearnedMaxCurrent", "0");
$this->SetBuffer("AdaptiveMeasurementTimestamp", "0");
$this->SetBuffer("AdaptivePhaseKnown", "0");
$this->SetBuffer("AdaptivePhaseCounter", "0");
$this->SetBuffer("AdaptiveStationType", (string)$stationType);
$this->SetBuffer("SmartMeChargingEnabled", "0");
$this->SetBuffer("SmartMeMinStationCurrent", "6");
$this->SetBuffer("AdaptiveModelVersion", self::ADAPTIVE_MODEL_VERSION);
}
if (!$this->GetValue("Car_detected")) {
$configuredMaxCurrent = (float)$this->ReadPropertyInteger(
"Max_Current_abs"
);
$this->SetBuffer(
"AdaptiveReferenceMaxCurrent",
(string)$configuredMaxCurrent
);
$this->SetValue("Max_Current", $configuredMaxCurrent);
}
$usesEaseeGateway = $this->UsesEaseeGateway($stationType);
IPS_SetHidden(
$this->GetIDForIdent("Easee_Gateway_Connected"),
!$usesEaseeGateway
);
if (!$usesEaseeGateway || $this->ReadPropertyInteger("EaseeGatewayID") <= 0) {
$this->SetValue("Easee_Gateway_Connected", false);
}
// erstelle einen Timer der das Request token aktualisiert wenn die station dies braucht.
// Zusätzliche Anpassungen nach Bedarf
}
public function RequestAction($Ident, $Value)
{
switch ($Ident) {
case "UpdateStationForm":
$this->UpdateStationForm((int)$Value);
break;
case "SetAktuelle_Leistung":
$this->SetValue("Power", (int)$Value);
break;
case "GetCurrentData":
$this->SetValue("Is_Peak_Shaving", (bool)$Value);
break;
case "Do_UserCalc":
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:
throw new Exception("Invalid Ident");
}
}
public function ReceiveData($JSONString)
{
$packet = json_decode($JSONString, true);
if (!is_array($packet) || !isset($packet["Buffer"])) {
return;
}
$message = json_decode($packet["Buffer"], true);
if (!is_array($message) || !isset($message["type"])) {
return;
}
if ($message["type"] === "GatewayStatus") {
$this->SetValue(
"Easee_Gateway_Connected",
(bool)($message["connected"] ?? false)
);
return;
}
if (
$message["type"] !== "Observation" ||
strtoupper((string)($message["serialNumber"] ?? "")) !==
strtoupper($this->ReadPropertyString("Seriennummer"))
) {
return;
}
$this->StoreEaseeObservation(
(int)($message["id"] ?? 0),
$message["value"] ?? null,
(int)($message["timestamp"] ?? time())
);
}
private function SubscribeToEaseeGateway()
{
$serialNumber = strtoupper(trim($this->ReadPropertyString("Seriennummer")));
if ($serialNumber === "") {
return;
}
$response = $this->SendEaseeGatewayRequest([
"action" => "Subscribe",
"serialNumber" => $serialNumber,
]);
$this->ApplyEaseeGatewayResponse($response);
}
private function GetEaseeStateFromGateway()
{
$serialNumber = strtoupper(trim($this->ReadPropertyString("Seriennummer")));
if ($serialNumber === "") {
return;
}
$response = $this->SendEaseeGatewayRequest([
"action" => "GetState",
"serialNumber" => $serialNumber,
]);
$this->ApplyEaseeGatewayResponse($response);
}
private function SendEaseeGatewayRequest(array $request)
{
$gatewayID = $this->GetConfiguredEaseeGatewayID();
if ($gatewayID <= 0 || !function_exists("EASEEGW_ProcessStationRequest")) {
$this->SetValue("Easee_Gateway_Connected", false);
return null;
}
$response = EASEEGW_ProcessStationRequest(
$gatewayID,
json_encode($request)
);
if (!is_string($response) || $response === "") {
return null;
}
$decoded = json_decode($response, true);
return is_array($decoded) ? $decoded : null;
}
private function GetConfiguredEaseeGatewayID(): int
{
$gatewayID = $this->ReadPropertyInteger("EaseeGatewayID");
if ($gatewayID <= 0 || !IPS_InstanceExists($gatewayID)) {
return 0;
}
$gateway = IPS_GetInstance($gatewayID);
if ($gateway["ModuleInfo"]["ModuleID"] !== self::EASEE_GATEWAY_MODULE_ID) {
return 0;
}
return $gatewayID;
}
private function IsEaseeGatewayInstance(int $instanceID): bool
{
if ($instanceID <= 0 || !IPS_InstanceExists($instanceID)) {
return false;
}
$instance = IPS_GetInstance($instanceID);
return $instance["ModuleInfo"]["ModuleID"] === self::EASEE_GATEWAY_MODULE_ID;
}
private function UsesEaseeGateway(int $stationType): bool
{
return $stationType === 5 || $stationType === 6;
}
private function UsesAdaptiveCurrentDetection(int $stationType): bool
{
return in_array($stationType, [1, 2, 3, 4, 5, 6], true);
}
private function HasReliableFullStatus(int $stationType): bool
{
// Easee meldet das Ladeende eindeutig über Observation 109.
return in_array($stationType, [5, 6], true);
}
private function SetAdaptiveReferenceMaxCurrent(float $apiMaxCurrent): float
{
$configuredMaxCurrent = max(
0.0,
(float)$this->ReadPropertyInteger("Max_Current_abs")
);
$referenceMaxCurrent = $configuredMaxCurrent;
// Nur plausible statische Stations-/Kabelgrenzen aus einer API dürfen
// die konfigurierte Obergrenze reduzieren.
if ($apiMaxCurrent >= 6.0) {
$referenceMaxCurrent = min($configuredMaxCurrent, $apiMaxCurrent);
}
$this->SetBuffer(
"AdaptiveReferenceMaxCurrent",
(string)$referenceMaxCurrent
);
return $referenceMaxCurrent;
}
private function GetAdaptiveReferenceMaxCurrent(): float
{
$referenceMaxCurrent = (float)$this->GetBuffer(
"AdaptiveReferenceMaxCurrent"
);
if ($referenceMaxCurrent <= 0) {
$referenceMaxCurrent = max(
0.0,
(float)$this->ReadPropertyInteger("Max_Current_abs")
);
}
return min(
$referenceMaxCurrent,
max(0.0, (float)$this->ReadPropertyInteger("Max_Current_abs"))
);
}
private function ResetAdaptiveLearning(float $referenceMaxCurrent)
{
$this->SetBuffer("AdaptiveLearnedMaxCurrent", "0");
$this->SetValue("Pending_Counter", 0);
$this->SetValue("Max_Current", $referenceMaxCurrent);
}
private function StoreAdaptiveMeasurement(int $timestamp = 0)
{
$this->SetBuffer(
"AdaptiveMeasurementTimestamp",
(string)($timestamp > 0 ? $timestamp : time())
);
}
private function HasFreshAdaptiveMeasurement(int $stationType): bool
{
// Der Dummy besitzt keine API-Zeitmarke und verwendet weiterhin den
// direkt gesetzten Istwert.
if ($stationType === 4) {
return true;
}
$timestamp = (int)$this->GetBuffer("AdaptiveMeasurementTimestamp");
$maximumAge = max(
30,
3 * max(1, $this->ReadPropertyInteger("Interval"))
);
return $timestamp > 0 && (time() - $timestamp) <= $maximumAge;
}
private function IsAdaptiveChargingEnabled(int $stationType): bool
{
if ($stationType === 5) {
return $this->ReadPropertyString("Username") ===
$this->GetValue("Letzer_User");
}
// Die verbindliche Freigabe ist die positive Sollleistung des Managers.
// Statusfelder der Station können beim echten Ladeende bereits 0 sein
// und dürfen deshalb die Ladeende-Erkennung nicht blockieren.
return true;
}
private function UpdateFallbackPhaseDetection(
int $stationType,
bool $ladebereit
): bool {
if (
$stationType === 4 ||
$this->GetBuffer("AdaptivePhaseKnown") === "1"
) {
$this->SetBuffer("AdaptivePhaseCounter", "0");
return false;
}
$requestedPower = max(
0.0,
(float)$this->GetValue("Aktuelle_Leistung")
);
$requestedCurrent = $requestedPower / (1.71 * 400.0);
$canEvaluate = $this->UsesAdaptiveCurrentDetection($stationType) &&
$ladebereit &&
$this->GetValue("Car_detected") &&
!$this->GetValue("Car_is_full") &&
$this->GetValue("Idle") &&
$requestedCurrent >= 5.5 &&
$requestedCurrent <= 6.5 &&
$this->IsAdaptiveChargingEnabled($stationType) &&
$this->HasFreshAdaptiveMeasurement($stationType);
if (!$canEvaluate) {
$this->SetBuffer("AdaptivePhaseCounter", "0");
return false;
}
$counter = (int)$this->GetBuffer("AdaptivePhaseCounter") + 1;
$this->SetBuffer("AdaptivePhaseCounter", (string)$counter);
$requiredCycles = max(
1,
(int)ceil(
self::PHASE_CONFIRMATION_SECONDS /
max(1, $this->ReadPropertyInteger("Interval"))
)
);
if ($counter < $requiredCycles) {
return false;
}
$this->SetBuffer("AdaptivePhaseCounter", "0");
$actualPower = abs(
(float)$this->GetValue("Ladeleistung_Effektiv")
);
$onePhaseExpectedPower = $requestedCurrent * 230.0;
$threePhaseExpectedPower = $requestedCurrent * 1.71 * 400.0;
$isOnePhase = $actualPower <
(($onePhaseExpectedPower + $threePhaseExpectedPower) / 2.0);
$this->SetValue("Is_1_ph", $isOnePhase);
$this->SetBuffer("AdaptivePhaseKnown", "1");
$this->ResetAdaptiveLearning($this->GetAdaptiveReferenceMaxCurrent());
$phaseDivisor = $isOnePhase ? 230.0 : 1.71 * 400.0;
$this->SetValue(
"Power",
(int)round($this->GetValue("Mindestaldestrom") * $phaseDivisor)
);
$detectedCurrent = self::ADAPTIVE_MISMATCH_FACTOR *
($actualPower / $phaseDivisor);
if (
$detectedCurrent < 6.0 &&
!$this->HasReliableFullStatus($stationType)
) {
$this->SetBuffer(
"AdaptiveLearnedMaxCurrent",
(string)$detectedCurrent
);
$this->SetValue("Max_Current", $detectedCurrent);
$this->SetValue("Car_is_full", true);
$this->ResetTimer();
$this->ResetNullTimer();
}
return true;
}
private function UpdateAdaptiveCurrentLimit(
int $stationType,
bool $ladebereit
): bool {
$requestedPower = max(
0.0,
(float)$this->GetValue("Aktuelle_Leistung")
);
$canEvaluate = $this->UsesAdaptiveCurrentDetection($stationType) &&
$ladebereit &&
$this->GetValue("Car_detected") &&
!$this->GetValue("Car_is_full") &&
$this->GetValue("Idle") &&
($stationType === 4 ||
$this->GetBuffer("AdaptivePhaseKnown") === "1") &&
$requestedPower > 0 &&
$this->IsAdaptiveChargingEnabled($stationType) &&
$this->HasFreshAdaptiveMeasurement($stationType);
if (!$canEvaluate) {
$this->SetValue("Pending_Counter", 0);
return false;
}
$phaseDivisor = $this->GetValue("Is_1_ph") ? 230.0 : 1.71 * 400.0;
$requestedCurrent = $requestedPower / $phaseDivisor;
$actualCurrent = abs(
(float)$this->GetValue("Ladeleistung_Effektiv")
) / $phaseDivisor;
if (
$requestedCurrent <=
self::ADAPTIVE_MISMATCH_FACTOR * $actualCurrent
) {
$this->SetValue("Pending_Counter", 0);
return false;
}
$counter = $this->GetValue("Pending_Counter") + 1;
$this->SetValue("Pending_Counter", $counter);
$requiredCycles = max(
1,
(int)ceil(
self::ADAPTIVE_CONFIRMATION_SECONDS /
max(1, $this->ReadPropertyInteger("Interval"))
)
);
if ($counter < $requiredCycles) {
return false;
}
$this->SetValue("Pending_Counter", 0);
$learnedMaxCurrent = min(
$this->GetAdaptiveReferenceMaxCurrent(),
self::ADAPTIVE_MISMATCH_FACTOR * $actualCurrent
);
if ($learnedMaxCurrent < 6.0) {
// Bei Easee hat der eindeutige API-Ladeendestatus Vorrang. Ein
// Kommunikations- oder Freigabefehler darf dort kein Ladeende
// simulieren.
if ($this->HasReliableFullStatus($stationType)) {
return false;
}
$this->SetBuffer(
"AdaptiveLearnedMaxCurrent",
(string)$learnedMaxCurrent
);
$this->SetValue("Max_Current", $learnedMaxCurrent);
$this->SetValue("Car_is_full", true);
$this->ResetTimer();
$this->ResetNullTimer();
return true;
}
$this->SetBuffer(
"AdaptiveLearnedMaxCurrent",
(string)$learnedMaxCurrent
);
$this->SetValue("Max_Current", $learnedMaxCurrent);
return true;
}
private function ApplyEaseeGatewayResponse($response)
{
if (!is_array($response)) {
$this->SetValue("Easee_Gateway_Connected", false);
return;
}
if (array_key_exists("connected", $response)) {
$this->SetValue(
"Easee_Gateway_Connected",
(bool)$response["connected"]
);
}
if (!isset($response["state"]) || !is_array($response["state"])) {
return;
}
$updated = (int)($response["state"]["updated"] ?? time());
foreach ([47, 104, 109, 110, 120, 182, 183, 184, 185] as $observationID) {
$key = (string)$observationID;
if (array_key_exists($key, $response["state"])) {
$this->StoreEaseeObservation(
$observationID,
$response["state"][$key],
$updated
);
}
}
}
private function StoreEaseeObservation(int $observationID, $value, int $timestamp)
{
if (!in_array($observationID, [47, 104, 109, 110, 120, 182, 183, 184, 185], true)) {
return;
}
$state = json_decode($this->GetBuffer("EaseeGatewayState"), true);
if (!is_array($state)) {
$state = [];
}
if ($observationID === 109) {
$previousMode = (int)($state["109"] ?? -1);
if ((int)$value === 1 || $previousMode === 1) {
foreach ([110, 182, 183, 184, 185] as $sessionObservationID) {
$state[(string)$sessionObservationID] = 0;
}
}
}
$state[(string)$observationID] = $value;
$state["updated"] = $timestamp;
$this->SetBuffer("EaseeGatewayState", json_encode($state));
if ($observationID === 109) {
$this->SetValue("Fahrzeugstatus", (int)$value);
} elseif ($observationID === 120) {
$this->SetValue("Ladeleistung_Effektiv", round((float)$value * 1000));
$this->StoreAdaptiveMeasurement($timestamp);
}
}
private function GetEaseeCarStatusFromGateway(bool $currentState): bool
{
$this->GetEaseeStateFromGateway();
$state = json_decode($this->GetBuffer("EaseeGatewayState"), true);
if (!is_array($state) || !array_key_exists("109", $state)) {
return $currentState;
}
$chargerOpMode = (int)$state["109"];
$currentState = in_array($chargerOpMode, [2, 3, 4, 6], true);
if (array_key_exists("120", $state)) {
$this->SetValue(
"Ladeleistung_Effektiv",
round((float)$state["120"] * 1000)
);
}
$this->SetValue("Fahrzeugstatus", $chargerOpMode);
return $currentState;
}
private function DetectEaseeCar(int $carType): bool
{
$carDetected = $this->Get_Car_Status($carType);
$state = json_decode($this->GetBuffer("EaseeGatewayState"), true);
if (!is_array($state)) {
$state = [];
}
$isOnePhase = $this->DetectEaseePhases($state);
// Observation 47 ist der nichtflüchtige maximale Ladestrom der
// Station. Die lokal konfigurierte Obergrenze bleibt zusätzlich aktiv.
$maxCurrent = (float)$this->ReadPropertyInteger("Max_Current_abs");
if (array_key_exists("47", $state) && (float)$state["47"] > 0) {
$maxCurrent = min($maxCurrent, (float)$state["47"]);
}
// Observation 104 ist die vom Typ-2-Kabel signalisierte Stromgrenze.
if (array_key_exists("104", $state) && (float)$state["104"] >= 6) {
$maxCurrent = min($maxCurrent, (float)$state["104"]);
}
$chargerOpMode = (int)($state["109"] ?? -1);
if (!$carDetected && $chargerOpMode !== 1) {
// Einen vorübergehenden Fehlerstatus nicht als Ausstecken werten.
$this->SetValue("Car_detected", false);
$this->SetValue("Car_is_full", false);
$this->SetValue("Pending_Counter", 0);
return false;
}
return $this->ApplyDirectStationDetection(
$carDetected,
$chargerOpMode === 4,
$isOnePhase,
$maxCurrent
);
}
private function DetectEaseePhases(array $state)
{
$outputPhase = (int)($state["110"] ?? 0);
// Bei Ladepause bzw. 0 W die zuletzt erkannte Fahrzeugphase behalten.
// Die Phasenvariable darf erst durch eine echte Strommessung wechseln.
if (
array_key_exists("120", $state) &&
abs((float)$state["120"]) < 0.1
) {
return null;
}
$activePhaseConductors = 0;
foreach ([183, 184, 185] as $observationID) {
if (abs((float)($state[(string)$observationID] ?? 0)) >= 1.0) {
$activePhaseConductors++;
}
}
if ($activePhaseConductors === 0) {
return null;
}
// Ein explizit einphasiger Easee-Ausgang ist auch in IT-Netzen
// einphasig, obwohl dort Strom auf zwei Leitern gemessen wird.
if ($outputPhase >= 10 && $outputPhase <= 15) {
return true;
}
// Bei einem dreiphasig freigegebenen Ausgang kann ein einphasiges Auto
// trotzdem nur auf einem Leiter Strom beziehen. Observation 110 allein
// kann diesen Fahrzeugwechsel deshalb nicht erkennen.
if ($activePhaseConductors === 1) {
return true;
} elseif ($activePhaseConductors >= 2) {
return false;
}
return null;
}
private function ReadJsonEndpoint(string $url, bool $useAuthentication = false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
if ($useAuthentication) {
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt(
$ch,
CURLOPT_USERPWD,
$this->ReadPropertyString("Username") . ":" .
$this->ReadPropertyString("Password")
);
}
$response = curl_exec($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (!is_string($response) || $response === "" || $httpCode >= 400) {
return null;
}
$data = json_decode($response, true);
return is_array($data) ? $data : null;
}
private function DetectOnePhaseFromCurrents(array $currents)
{
$activePhases = 0;
$hasMeasurements = false;
foreach ($currents as $current) {
if (!is_numeric($current)) {
continue;
}
$hasMeasurements = true;
if (abs((float)$current) >= 1.0) {
$activePhases++;
}
}
if (!$hasMeasurements || $activePhases === 0) {
return null;
}
return $activePhases === 1;
}
private function ApplyDirectStationDetection(
bool $carDetected,
bool $carIsFull,
$isOnePhase,
float $maxCurrent
): bool {
$wasDetected = $this->GetValue("Car_detected");
$wasOnePhase = $this->GetValue("Is_1_ph");
$wasFull = $this->GetValue("Car_is_full");
$referenceMaxCurrent = $this->SetAdaptiveReferenceMaxCurrent(
$maxCurrent
);
if (!$carDetected) {
$this->ResetAdaptiveLearning($referenceMaxCurrent);
$this->SetBuffer("AdaptivePhaseKnown", "0");
$this->SetBuffer("AdaptivePhaseCounter", "0");
$this->SetValue("Car_detected", false);
$this->SetValue("Car_is_full", false);
$this->SetValue("Leistung_Delta", 0);
$this->ResetTimer();
$this->ResetNullTimer();
$this->SetValue("Is_1_ph", false);
$this->SetValue("Aktuelle_Leistung", 0);
$this->SetValue("IdleCounter", 0);
$this->SetValue("Idle", true);
return false;
}
if (is_bool($isOnePhase)) {
$this->SetValue("Is_1_ph", $isOnePhase);
$this->SetBuffer("AdaptivePhaseKnown", "1");
$this->SetBuffer("AdaptivePhaseCounter", "0");
} elseif (!$wasDetected) {
$this->SetBuffer("AdaptivePhaseKnown", "0");
$this->SetBuffer("AdaptivePhaseCounter", "0");
}
$phaseChanged = $wasDetected &&
is_bool($isOnePhase) &&
$wasOnePhase !== $this->GetValue("Is_1_ph");
if (!$wasDetected || $phaseChanged) {
$this->ResetAdaptiveLearning($referenceMaxCurrent);
} else {
$learnedMaxCurrent = (float)$this->GetBuffer(
"AdaptiveLearnedMaxCurrent"
);
$this->SetValue(
"Max_Current",
$learnedMaxCurrent > 0
? min($referenceMaxCurrent, $learnedMaxCurrent)
: $referenceMaxCurrent
);
}
$this->SetValue("Car_detected", true);
if ($this->HasReliableFullStatus($this->ReadPropertyInteger("Ladestation"))) {
$this->SetValue("Car_is_full", $carIsFull);
} else {
$this->SetValue(
"Car_is_full",
$carIsFull || ($wasDetected && !$phaseChanged && $wasFull)
);
}
if (!$wasDetected || $phaseChanged) {
if ($this->GetValue("Is_1_ph")) {
$power = $this->GetValue("Mindestaldestrom") * 230;
} else {
$power = $this->GetValue("Mindestaldestrom") * 400 * 1.71;
}
$this->SetValue("Power", $power);
}
return true;
}
private function GetGoEMaxCurrent(array $data): float
{
$maxCurrent = (float)$this->ReadPropertyInteger("Max_Current_abs");
foreach (["ama", "cbl"] as $key) {
if (isset($data[$key]) && is_numeric($data[$key])) {
$candidate = (float)$data[$key];
if ($candidate >= 6) {
$maxCurrent = min($maxCurrent, $candidate);
}
}
}
if (!empty($data["adi"])) {
$maxCurrent = min($maxCurrent, 16.0);
}
if (isset($data["var"]) && is_numeric($data["var"])) {
$variant = (int)$data["var"];
if ($variant === 11) {
$maxCurrent = min($maxCurrent, 16);
} elseif ($variant === 22) {
$maxCurrent = min($maxCurrent, 32);
}
}
return $maxCurrent;
}
private function IsGoEChargingEnabled(array $data, int $stationType): bool
{
if ($stationType === 1 && array_key_exists("alw", $data)) {
return (int)$data["alw"] === 1;
}
if (array_key_exists("frc", $data)) {
$forceState = (int)$data["frc"];
if ($forceState === 1) {
return false;
}
if ($forceState === 2) {
return true;
}
}
if (array_key_exists("alw", $data)) {
return (int)$data["alw"] === 1;
}
return $this->GetBuffer("GoEChargingEnabled") === "1";
}
private function DetectGoECar(int $stationType): bool
{
$path = $stationType === 1 ? "/mqtt?payload=" : "/api/status";
$data = $this->ReadJsonEndpoint(
"http://" . $this->ReadPropertyString("IP_Adresse") . $path
);
if (!is_array($data) || !isset($data["car"]) || !is_numeric($data["car"])) {
return $this->GetValue("Car_detected");
}
$carState = (int)$data["car"];
if (!in_array($carState, [1, 2, 3, 4, 5], true)) {
return $this->GetValue("Car_detected");
}
$this->SetValue("Fahrzeugstatus", $carState);
$this->SetBuffer(
"GoEChargingEnabledFromStatus",
$this->IsGoEChargingEnabled($data, $stationType) ? "1" : "0"
);
$isOnePhase = null;
$chargingPowerWatts = null;
if (isset($data["nrg"]) && is_array($data["nrg"])) {
$currentFactor = $stationType === 1 ? 0.1 : 1.0;
$phaseCurrents = [];
foreach ([4, 5, 6] as $index) {
$phaseCurrents[] = isset($data["nrg"][$index]) &&
is_numeric($data["nrg"][$index])
? (float)$data["nrg"][$index] * $currentFactor
: null;
}
$isOnePhase = $this->DetectOnePhaseFromCurrents($phaseCurrents);
if (isset($data["nrg"][11]) && is_numeric($data["nrg"][11])) {
$powerFactor = $stationType === 1 ? 10 : 1;
$chargingPowerWatts = (float)$data["nrg"][11] * $powerFactor;
$this->SetValue(
"Ladeleistung_Effektiv",
round($chargingPowerWatts)
);
$this->StoreAdaptiveMeasurement();
}
}
$carDetected = in_array($carState, [2, 3, 4, 5], true);
$stationMaxCurrent = $this->GetGoEMaxCurrent($data);
return $this->ApplyDirectStationDetection(
$carDetected,
false,
$isOnePhase,
$stationMaxCurrent
);
}
private function DetectSmartMeCar(): bool
{
// Bei einem fehlgeschlagenen Abruf darf eine alte Freigabe keinesfalls
// zur Ladeende-Erkennung weiterverwendet werden.
$this->SetBuffer("SmartMeChargingEnabled", "0");
$deviceID = trim($this->ReadPropertyString("ID"));
if ($deviceID === "") {
return $this->GetValue("Car_detected");
}
$chargingData = $this->ReadJsonEndpoint(
"https://api.smart-me.com/pico/charging/" . $deviceID,
true
);
if (!is_array($chargingData)) {
return $this->GetValue("Car_detected");
}
$stateValue = $chargingData["State"] ?? $chargingData["state"] ?? null;
if (!is_numeric($stateValue)) {
return $this->GetValue("Car_detected");
}
$stationState = (int)$stateValue;
if (!in_array($stationState, [1, 2, 3, 4, 6], true)) {
return $this->GetValue("Car_detected");
}
$this->SetValue("Fahrzeugstatus", $stationState);
$chargingPower = $chargingData["ActiveChargingPower"] ??
$chargingData["activeChargingPower"] ?? null;
$chargingPowerWatts = null;
if (is_numeric($chargingPower)) {
$chargingPowerWatts = (float)$chargingPower * 1000;
$this->SetValue(
"Ladeleistung_Effektiv",
round($chargingPowerWatts)
);
$this->StoreAdaptiveMeasurement();
}
// Die Pico-API unterscheidet zwischen der extern vorgegebenen
// Stromgrenze und der effektiv verfügbaren Stromgrenze. Nur wenn beide
// vorhandenen Grenzen mindestens dem Stationsminimum entsprechen, ist
// die Ladung wirklich freigegeben. Eine Regelungsunterbrechung mit 0 A
// darf nicht als abgeschlossenes Laden ausgewertet werden.
$minStationCurrent = $chargingData["MinStationCurrent"] ??
$chargingData["minStationCurrent"] ?? 6;
$minStationCurrent = is_numeric($minStationCurrent)
? max(1.0, (float)$minStationCurrent)
: 6.0;
$this->SetBuffer(
"SmartMeMinStationCurrent",
(string)$minStationCurrent
);
$maxDynamicCurrent = $chargingData["MaxDynamicCurrent"] ??
$chargingData["maxDynamicCurrent"] ?? null;
$maxAllowedCurrent = $chargingData["MaxAllowedChargingCurrent"] ??
$chargingData["maxAllowedChargingCurrent"] ?? null;
$hasCurrentLimit = is_numeric($maxDynamicCurrent) ||
is_numeric($maxAllowedCurrent);
$dynamicCurrentAllowsCharging = !is_numeric($maxDynamicCurrent) ||
(float)$maxDynamicCurrent >= $minStationCurrent;
$allowedCurrentAllowsCharging = !is_numeric($maxAllowedCurrent) ||
(float)$maxAllowedCurrent >= $minStationCurrent;
$chargingEnabled = $hasCurrentLimit
? $dynamicCurrentAllowsCharging && $allowedCurrentAllowsCharging
: $this->GetValue("Aktuelle_Leistung") > 0;
$this->SetBuffer(
"SmartMeChargingEnabled",
$chargingEnabled ? "1" : "0"
);
$isOnePhase = null;
$deviceData = $this->ReadJsonEndpoint(
"https://api.smart-me.com/Devices/" . $deviceID,
true
);
if (is_array($deviceData)) {
$phaseCurrents = [
$deviceData["CurrentL1"] ?? $deviceData["currentL1"] ?? null,
$deviceData["CurrentL2"] ?? $deviceData["currentL2"] ?? null,
$deviceData["CurrentL3"] ?? $deviceData["currentL3"] ?? null,
];
$isOnePhase = $this->DetectOnePhaseFromCurrents($phaseCurrents);
}
$maxCurrent = (float)$this->ReadPropertyInteger("Max_Current_abs");
foreach ([
"MaxStationCurrent",
"maxStationCurrent",
] as $key) {
if (isset($chargingData[$key]) && is_numeric($chargingData[$key])) {
$candidate = (float)$chargingData[$key];
if ($candidate >= 6) {
$maxCurrent = min($maxCurrent, $candidate);
}
}
}
$carDetected = in_array($stationState, [2, 3, 4, 6], true);
return $this->ApplyDirectStationDetection(
$carDetected,
false,
$isOnePhase,
$maxCurrent
);
}
private function SendEaseeCurrentToGateway(float $value)
{
$response = $this->SendEaseeGatewayRequest([
"action" => "SetDynamicChargerCurrent",
"serialNumber" => strtoupper(trim($this->ReadPropertyString("Seriennummer"))),
"amps" => $value,
]);
if (!is_array($response) || !($response["success"] ?? false)) {
$error = is_array($response)
? (string)($response["error"] ?? "Unbekannter Gateway-Fehler")
: "Easee Gateway nicht erreichbar";
return $error;
}
return $response["body"] ?? null;
}
public function Detect_Car(int $carType)
{
if ($carType === 1 || $carType === 2) {
return $this->DetectGoECar($carType);
}
if ($carType === 3) {
return $this->DetectSmartMeCar();
}
if ($this->UsesEaseeGateway($carType)) {
return $this->DetectEaseeCar($carType);
}
if($this->GetValue("Car_detected")==true){
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{
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->SetBuffer("AdaptivePhaseKnown", "1");
$this->Calc_Max_Current(false);
}
else{
$this->SetValue("Is_1_ph", true);
$this->SetBuffer("AdaptivePhaseKnown", "1");
$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");
}
// Methode zum Setzen der PowerSteps und Timer starten
public function SetTimerOn()
{
// Timer setzen, der nach "Zeit_Zwischen_Zustandswechseln" abläuft
$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 der PowerSteps und Timer starten
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 von PowerSteps 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 von PowerSteps nach Ablauf des Timers
public function ResetNullTimer()
{
// Timer stoppen
$this->SetTimerInterval("Null_Timer", 0);
// Timer-Status auf false setzen
$this->SetValue("IsTimerActive_Null_Timer", false);
}
public function Refresh_Token()
{
// Kompatibilitätsfunktion für bestehende Instanzen. Das Gateway
// verwaltet die Easee-Anmeldung und benötigt diesen Timer nicht mehr.
$this->SetTimerInterval("Timer_Refresh_Token", 0);
}
public function Get_Car_Status(int $carType)
{
$car_on_station = $this->GetValue("Car_detected");
switch ($carType) {
case 1:
$ch = curl_init();
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) {
$this->SetValue("Car_detected", true);
}
else{
$this->SetValue("Car_detected", false);
}*/
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:
$ch = curl_init();
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) {
$this->SetValue("Car_detected", true);
}
else{
$this->SetValue("Car_detected", false);
}*/
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:
$ch = curl_init();
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["car"] != 1) {
$this->SetValue("Car_detected", true);
}
else{
$this->SetValue("Car_detected", false);
}*/
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:
$car_on_station = true;
break;
case 5:
// 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);
}
}
$car_on_station = $this->GetEaseeCarStatusFromGateway($car_on_station);
break;
case 6:
$car_on_station = $this->GetEaseeCarStatusFromGateway($car_on_station);
break;
default:
$this->SetValue("Car_detected", false);
$this->SetValue("Fahrzeugstatus", -1);
break;
}
return $car_on_station;
}
public function Calc_Max_Current(bool $is_1_ph)
{
$phaseDivisor = $is_1_ph ? 230.0 : 1.71 * 400.0;
$actualCurrent = abs(
(float)$this->GetValue("Ladeleistung_Effektiv")
) / $phaseDivisor;
$maxCurrent = min(
$this->GetAdaptiveReferenceMaxCurrent(),
self::ADAPTIVE_MISMATCH_FACTOR * $actualCurrent
);
$this->SetBuffer("AdaptiveLearnedMaxCurrent", (string)$maxCurrent);
$this->SetValue("Max_Current", $maxCurrent);
if (
$maxCurrent < 6.0 &&
!$this->HasReliableFullStatus(
$this->ReadPropertyInteger("Ladestation")
)
) {
$this->SetValue("Car_is_full", true);
}
}
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;
}
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{
// 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;
}
}
}
// power > 0: keine 0 am Anfang, Schleife normal durchlaufen
} else {
// Timer aus: wie bisher, 0 am Anfang
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();
}
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);
}
$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));
}
}
private function BuildPowerSteps(
bool $peak,
bool $ladebereit,
bool $solarladen
): array {
if (!$ladebereit || $this->GetValue("Car_is_full")) {
return [0];
}
if ($this->GetBuffer("AdaptivePhaseKnown") !== "1") {
$referenceMaxCurrent = $this->GetAdaptiveReferenceMaxCurrent();
if ($referenceMaxCurrent < 6.0) {
return [0];
}
// Bis zur sicheren Phasenerkennung wird nur ein bilanzierter
// 6-A-Prüfschritt angeboten. Is_1_ph bleibt dabei absichtlich false.
return [(int)round(6.0 * 1.71 * 400.0)];
}
$availableSteps = $this->Get_Array_From_Current(
$this->GetValue("Is_1_ph"),
(float)$this->GetValue("Max_Current"),
$this->GetValue("Aktuelle_Leistung"),
$this->GetValue("IsTimerActive_Null_Timer")
);
if (count($availableSteps) === 0) {
$availableSteps = [0];
}
if (!$peak && !$solarladen) {
return [max($availableSteps)];
}
if ($solarladen && $peak) {
$minimumPower = $this->GetValue("Mindestaldestrom") *
($this->GetValue("Is_1_ph") ? 230 : 400 * 1.71);
return [$minimumPower];
}
return $availableSteps;
}
// Methode zum Abrufen der aktuellen Daten
public function GetCurrentData(bool $Peak)
{
if ($this->GetValue("IsTimerActive")) {
$this->SetValue("Pending_Counter", 0);
if (
$this->GetValue("Car_is_full") ||
!$this->GetValue("Ladebereit")
) {
$this->ResetTimer();
$this->SetValue("PowerSteps", json_encode([0]));
return [0];
}
$this->SetValue(
"PowerSteps",
json_encode([$this->GetValue("Aktuelle_Leistung")])
);
$this->SetValue(
"Leistung_Delta",
$this->GetValue("Aktuelle_Leistung") -
$this->GetValue("Ladeleistung_Effektiv")
);
return [$this->GetValue("Aktuelle_Leistung")];
}
$this->SetValue("Leistung_Delta", 0);
$ladebereit = (bool)$this->GetValue("Ladebereit");
$solarladen = (bool)$this->GetValue("Solarladen");
$this->SetValue("Peak", $Peak);
$stationType = $this->ReadPropertyInteger("Ladestation");
$phaseWasDetected = $this->UpdateFallbackPhaseDetection(
$stationType,
$ladebereit
);
// Erst die gelernte Grenze aktualisieren, damit der Manager bereits in
// diesem Zyklus nur noch tatsächlich erreichbare Schritte erhält.
if (!$phaseWasDetected) {
$this->UpdateAdaptiveCurrentLimit(
$stationType,
$ladebereit
);
}
$powerSteps = $this->BuildPowerSteps(
$Peak,
$ladebereit,
$solarladen
);
$this->SetValue("PowerSteps", json_encode($powerSteps));
return $powerSteps;
}
public function sendPowerToStation(float $value)
{
$baseUrl = "";
$stationType = $this->ReadPropertyInteger("Ladestation");
if ($stationType === 5 || $stationType === 6) {
if (
$stationType === 5 &&
$this->ReadPropertyString("Username") != $this->GetValue("Letzer_User")
) {
return;
}
return $this->SendEaseeCurrentToGateway($value);
}
switch ($stationType) {
case 1:
$baseUrl = "http://" . $this->ReadPropertyString("IP_Adresse") . "/mqtt?payload=";
break;
case 2:
$baseUrl = "http://" . $this->ReadPropertyString("IP_Adresse") . "/api/set?";
break;
case 3:
$baseUrl = "https://api.smart-me.com/pico/loadmanagementgroup/current/" . $this->ReadPropertyString("Seriennummer") . "?current=";
break;
case 4:
// Nichts zu tun für Dummy station
return;
}
$ch = curl_init();
if ($value == 0) {
switch ($stationType) {
case 1:
$url = $baseUrl . "alw=0";
break;
case 2:
$url = $baseUrl . "frc=1&sua=false";
break;
case 3:
$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:
// Nichts zu tun für Dummy station
return;
default:
return "Invalid station type.";
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (($stationType === 1 || $stationType === 2) && $response !== false) {
$this->SetBuffer("GoEChargingEnabled", "0");
}
curl_close($ch);
return $response;
} elseif ($value >= 1 && $value <= 32) {
switch ($stationType) {
case 1:
$url1 = $baseUrl . "alw=1";
$url2 = $baseUrl . "amp=$value";
break;
case 2:
$url1 = $baseUrl . "frc=2";
$url2 = $baseUrl . "amp=$value";
break;
case 3:
$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:
// Nichts zu tun für Dummy station
return;
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);
}
if ($stationType === 1 || $stationType === 2) {
$this->SetBuffer("GoEChargingEnabled", "1");
}
curl_close($ch);
return;
} else {
return "Invalid value. Must be between 0 and 32.";
}
}
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);
}
}
}
?>