<?php
// replay_and_listen_3011_web.php
// Uso via navegador: ?payload=A_19  o ?hex=239d...
$host = '192.168.0.77';
$port = 3011;
$connectTimeout = 5;
$readTimeoutSec = 6;
$saveDir = __DIR__ . DIRECTORY_SEPARATOR . 'responses_web';
if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);

$examples = [
    'A_19' => '239d329aa5c1b1797d54ba347959b23f48065e',
    'B_32' => 'b6111cc64b369db2bdd10b6b39f08522de8b2521ede82817badcaf0c45fba55e',
];

$payloadHex = '';
if (!empty($_GET['payload']) && isset($examples[$_GET['payload']])) $payloadHex = $examples[$_GET['payload']];
elseif (!empty($_GET['hex'])) $payloadHex = preg_replace('/[^0-9a-fA-F]/','', $_GET['hex']);
else {
    echo "Usar ?payload=A_19 o ?hex=239d...\n";
    exit;
}

function hexToBinStrict($hex){ $h=preg_replace('/[^0-9a-fA-F]/','',$hex); return $h===''? '': hex2bin($h); }
function buildFrame($payloadHex){ $bin=hexToBinStrict($payloadHex); $len=strlen($bin); $header=str_pad((string)$len,5,'0',STR_PAD_LEFT).'|2|'; return $header.$bin; }
function hexdump($data){ if($data==='') return ''; $hex=strtoupper(bin2hex($data)); return implode(' ', str_split($hex,2)); }
function parseResponses($buffer){ $results=[]; $offset=0; while (preg_match('/(\d{5}\|2\|)/', $buffer, $m, PREG_OFFSET_CAPTURE, $offset)) { $hdrPos=$m[0][1]; $hdr=$m[0][0]; $len=intval(substr($hdr,0,5)); $payloadStart=$hdrPos+strlen($hdr); if (($payloadStart+$len)<=strlen($buffer)) { $payload=substr($buffer,$payloadStart,$len); $results[]=['header'=>$hdr,'payload'=>$payload,'pos'=>$hdrPos]; $offset=$payloadStart+$len; } else break; } return $results; }

$frame = buildFrame($payloadHex);
$fp = @stream_socket_client("tcp://$host:$port", $errno, $errstr, $connectTimeout);
if (!$fp) { echo "ERROR: $errstr ($errno)"; exit; }
stream_set_blocking($fp, false);
fwrite($fp,$frame);
$start = microtime(true);
$buffer = ''; $any=false;
while ((microtime(true)-$start) < $readTimeoutSec) {
    $chunk = @fread($fp, 8192);
    if ($chunk !== false && $chunk !== '') {
        $buffer .= $chunk;
        $parsed = parseResponses($buffer);
        if (count($parsed)>0) {
            $any=true;
            $out='';
            foreach ($parsed as $idx=>$p) {
                $fname = $saveDir . DIRECTORY_SEPARATOR . date('Ymd_His') . "_resp_{$idx}.bin";
                file_put_contents($fname, $p['payload']);
                $out .= "Resp header={$p['header']} payload_len=" . strlen($p['payload']) . "<br>";
                $out .= "HEX: " . hexdump($p['payload']) . "<br>";
                $out .= "Guardada: $fname<br><hr>";
            }
            echo $out;
            $last = end($parsed);
            $posEnd = $last['pos'] + strlen($last['header']) + strlen($last['payload']);
            $buffer = substr($buffer, $posEnd);
            $start = microtime(true);
        } else { usleep(100000); }
    } else { usleep(100000); }
}
if (!$any) {
    if ($buffer !== '') {
        $fname = $saveDir . DIRECTORY_SEPARATOR . date('Ymd_His') . "_resp_raw.bin";
        file_put_contents($fname,$buffer);
        echo "No framing parseable. Guardado crudo: $fname<br>HEX preview: " . substr(hexdump($buffer),0,500);
    } else {
        echo "No se recibió respuesta durante {$readTimeoutSec}s.";
    }
}
fclose($fp);
