32768) { $result -= 65536; } return $result; } // Unsigned 16-bit integer conversion function buf2int16US($byteArray, $pos) { return $byteArray[$pos] * 256 + $byteArray[$pos + 1]; } // Read data from BYD device function read($byd_ip, $byd_port) { try { // Connect to BYD $client = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($client, "192.168.178.34", 8080); // Message 2 (Sending command to read data) socket_write($client, hex2bin(MESSAGE_2)); // Read data $data = socket_read($client, BUFFER_SIZE); // Parse data $data = unpack("C*", $data); // Unpack binary data to array $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_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(); } } ?>