<?php
// listen_3011_cli.php — solo escucha frames "NNNNN|2|<bin>" por N segundos
$host='192.168.0.77'; $port=3011; $seconds=30;  // súbelo a 60 si quieres
$saveDir=__DIR__.DIRECTORY_SEPARATOR.'responses_listen';
if(!is_dir($saveDir)) mkdir($saveDir,0777,true);

function hexdump($d){ if($d==='')return''; $h=strtoupper(bin2hex($d)); return implode(' ',str_split($h,2)); }
function parseFrames(&$buf){
  $out=[]; $off=0;
  while(preg_match('/(\d{5}\|2\|)/',$buf,$m,PREG_OFFSET_CAPTURE,$off)){
    $pos=$m[0][1]; $hdr=$m[0][0]; $len=intval(substr($hdr,0,5));
    $start=$pos+strlen($hdr);
    if(($start+$len)<=strlen($buf)){
      $pay=substr($buf,$start,$len);
      $out[]=['hdr'=>$hdr,'pay'=>$pay];
      $off=$start+$len;
    } else break;
  }
  if(!empty($out)){
    $last=end($out);
    $cut=strpos($buf,$last['hdr'])+strlen($last['hdr'])+strlen($last['pay']);
    $buf=substr($buf,$cut);
  }
  return $out;
}

echo "[*] Conectando a $host:$port y escuchando $seconds s...\n";
$fp=@stream_socket_client("tcp://$host:$port",$errno,$errstr,5);
if(!$fp){ die("No conecta: $errstr ($errno)\n"); }
stream_set_blocking($fp,false);
$start=microtime(true); $buf=''; $count=0;
while((microtime(true)-$start)<$seconds){
  $chunk=@fread($fp,8192);
  if($chunk!==false && $chunk!==''){
    $buf.=$chunk;
    $frames=parseFrames($buf);
    foreach($frames as $i=>$f){
      $count++;
      $fname=$saveDir.DIRECTORY_SEPARATOR.date('Ymd_His')."_f".str_pad($count,3,'0',STR_PAD_LEFT).".bin";
      file_put_contents($fname,$f['pay']);
      echo "[<] Frame $count {$f['hdr']} len=".strlen($f['pay'])." HEX: ".substr(hexdump($f['pay']),0,120)."\n";
      echo "     Guardado: $fname\n";
    }
  } else { usleep(100000); }
}
fclose($fp);
echo "[*] Fin.\n";
