<?php
// Información inicial del script
echo "Running script version: 2025-03-10-hex-fixed-v11\n";
echo "Script file: " . __FILE__ . "\n";
echo "PHP version: " . PHP_VERSION . "\n";
echo "Current working directory: " . getcwd() . "\n";

// Ruta del archivo
$dataFile = '/home/lamp/test/1_fresh.DAT';
echo "Reading file: $dataFile\n";
clearstatcache();
echo "File size: " . filesize($dataFile) . " bytes\n";

// Leer el archivo completo
$rawData = file_get_contents($dataFile);
if ($rawData === false) {
    die("Error: Could not read file '$dataFile'.\n");
}
echo "Raw data length: " . strlen($rawData) . " bytes\n";
$hexData = bin2hex($rawData);

// Procesar el encabezado
$headerLength = 288;
$headerHex = substr($hexData, 0, $headerLength * 2);
echo "Header hex: $headerHex\n";
echo "Header length: $headerLength\n";

// Definir el mapeo de TagIndex a Tagname
$tags = [
    48 => '[PTA]G_PT101_OUTPUT',
    49 => '[PTA]G_ORPAT101_OUTPUT',
    50 => '[PTA]G_LC201_OUTPUT',
    51 => '[PTA]G_FIT301_OUTPUT',
    52 => '[PTA]G_AT301B_OUTPUT'
];

// Configurar iteración de registros
$offset = $headerLength * 2;
$recordLength = 39;
$recordNum = 1;

// Encabezado de la salida CSV
echo "Timestamp,Tagname,Value,Status,Marker,Internal\n";

// Iterar sobre los registros
while ($offset + ($recordLength * 2) <= strlen($hexData)) {
    $recordHex = substr($hexData, $offset, $recordLength * 2);
    echo "Registro Nro: $recordNum\n";
    echo "Record hex (raw): $recordHex\n";

    // Extraer Timestamp completo (Bytes 1–20)
    $timestampHex = substr($recordHex, 2, 40);
    $timestamp = rtrim(hex2bin($timestampHex)); // Cadena completa sin espacios finales

    // Extraer TagIndex y mapear a Tagname (Byte 24)
    $tagIndexHex = substr($recordHex, 48, 2);
    $tagIndex = hexdec($tagIndexHex);
    $tagName = $tags[$tagIndex] ?? "Unknown ($tagIndex)";

    // Extraer Value (Bytes 25–32)
    $valueHex = substr($recordHex, 50, 16);
    $valueBin = hex2bin($valueHex);
    $value = unpack('d', $valueBin)[1]; // Double en little-endian
    $formattedValue = number_format($value, 8); // Formatear a 8 decimales

    // Extraer Status (Byte 33)
    $statusHex = substr($recordHex, 66, 2);
    $status = hexdec($statusHex) === 32 ? ' ' : hexdec($statusHex); // Espacio si es 32

    // Extraer Marker (Byte 34)
    $markerHex = substr($recordHex, 68, 2);
    $marker = hex2bin($markerHex);

    // Extraer Internal (Bytes 35–38)
    $internalHex = substr($recordHex, 70, 8);
    $internal = unpack('l', hex2bin($internalHex))[1]; // Entero con signo

    // Generar línea CSV con Timestamp completo y campos requeridos
    echo "\"$timestamp\",$tagName,$formattedValue,$status,$marker,$internal\n\n";

    // Avanzar al siguiente registro
    $offset += $recordLength * 2;
    $recordNum++;
}
?>
