Hi,
unpack wandelt den String ja schon in ein Array um und dann greift man z.B. mit $dataArray[‚SOC‘] oder so auf das Array zu. Ich würde mal
<?php
define('BUFFER_SIZE', 1024);
define('MESSAGE_1', "010300000066c5e0"); // read serial
define('MESSAGE_2', "01030500001984cc"); // read data
function buf2int16SI($byteArray, $pos) { // signed
$result = $byteArray[$pos] * 256 + $byteArray[$pos + 1];
if ($result > 32768) {
$result -= 65536;
}
return $result;
}
function buf2int16US($byteArray, $pos) { // unsigned
$result = $byteArray[$pos] * 256 + $byteArray[$pos + 1];
return $result;
}
function read($byd_ip, $byd_port) {
try {
// Verbindung zum BYD
$client = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($client === false) {
throw new Exception('Fehler beim Erstellen des Sockets: ' . socket_strerror(socket_last_error()));
}
// Verbindung zum Zielport herstellen
$result = socket_connect($client, "192.168.178.34", 23
);
if ($result === false) {
throw new Exception('Fehler beim Verbinden: ' . socket_strerror(socket_last_error($client)));
}
// Nachricht 2 senden
socket_write($client, hex2bin(MESSAGE_2));
// Daten lesen
$data = socket_read($client, BUFFER_SIZE);
if ($data === false) {
throw new Exception('Fehler beim Empfangen von Daten: ' . socket_strerror(socket_last_error($client)));
}
// Umwandlung der empfangenen Daten
$dataArray = unpack("C*", $data); // Byte-Daten in ein Array umwandeln
// Die Werte aus den empfangenen Daten extrahieren
$soc = buf2int16SI($data, 3);
$maxvolt = buf2int16SI($data, 5) * 1.0 / 100.0;
$minvolt = buf2int16SI($data, 7) * 1.0 / 100.0;
$soh = buf2int16SI($data, 9);
$ampere = buf2int16SI($data, 11) * 1.0 / 10.0;
$battvolt = buf2int16US($data, 13) * 1.0 / 100.0;
$maxtemp = buf2int16SI($data, 15);
$mintemp = buf2int16SI($data, 17);
$battemp = buf2int16SI($data, 19);
$error = buf2int16SI($data, 29);
$paramt = chr($data[31]) . "." . chr($data[32]);
$outvolt = buf2int16US($data, 35) * 1.0 / 100.0;
$power = round(($ampere * $outvolt) * 100 / 100, 2);
$diffvolt = round(($maxvolt - $minvolt) * 100 / 100, 2);
// Socket schließen
socket_close($client);
return [
"soc" => $soc,
"maxvolt" => $maxvolt,
"minvolt" => $minvolt,
"soh" => $soh,
"ampere" => $ampere,
"battvolt" => $battvolt,
"maxtemp" => $maxtemp,
"mintemp" => $mintemp,
"battemp" => $battemp,
"error" => $error,
"paramt" => $paramt,
"outvolt" => $outvolt,
"power" => $power,
"diffvolt" => $diffvolt,
];
} catch (Exception $ex) {
echo "ERROR BYD: " . $ex->getMessage();
}
}
// Beispielaufruf der Funktion
$byd_ip = "192.168.178.34"; // IP-Adresse des BYD Geräts
$byd_port = 23; // Port des BYD Geräts
$result = read($byd_ip, $byd_port);
print_r($result);
?>
versuchen.
Ralf