﻿unit uBasculaSerial;

{ Lectura de báscula por puerto serie (RS-232 / COM virtual USB) en hilo secundario.
  - Abre el puerto con la API Win32 (CreateFile/SetCommState/ReadFile).
  - Acepta tramas ASCII continuas o bajo petición (ComandoPeticionHex).
  - Detecta estabilidad por la propia trama (ST/US) o por muestras consecutivas.
  - Entrega las lecturas al hilo principal mediante TThread.Queue (nunca bloquea la UI).
  - Modo simulado para pruebas sin báscula. }

interface

uses
  Winapi.Windows, System.SysUtils, System.Classes, System.SyncObjs, uPesadoConfig;

type
  TBasculaPesoEvent = procedure(Sender: TObject; APesoKg: Double; AEstable: Boolean; const ATrama: string) of object;
  TBasculaEstadoEvent = procedure(Sender: TObject; AConectada: Boolean; const AMensaje: string) of object;

  TBasculaThread = class(TThread)
  private
    FConfig: TPesadoConfig;
    FHandle: THandle;
    FBuffer: AnsiString;
    FMuestras: array of Double;
    FIdxMuestra: Integer;
    FNumMuestras: Integer;
    FLock: TCriticalSection;
    FPesoSimuladoKg: Double;
    FPesoSimuladoActualKg: Double;
    FComando: TBytes;
    FOnPeso: TBasculaPesoEvent;
    FOnEstado: TBasculaEstadoEvent;
    FOwner: TObject;

    function AbrirPuerto(out AError: string): Boolean;
    procedure CerrarPuerto;
    procedure ProcesarBuffer;
    function EvaluarEstable(APesoKg: Double): Boolean;
    procedure NotificarPeso(APesoKg: Double; AEstable: Boolean; const ATrama: string);
    procedure NotificarEstado(AConectada: Boolean; const AMensaje: string);
    procedure EjecutarSimulado;
    procedure EjecutarReal;
  protected
    procedure Execute; override;
  public
    constructor Create(AOwner: TObject; const AConfig: TPesadoConfig;
      AOnPeso: TBasculaPesoEvent; AOnEstado: TBasculaEstadoEvent);
    destructor Destroy; override;
    procedure SetPesoSimulado(APesoKg: Double);
  end;

  TBasculaSerial = class
  private
    FConfig: TPesadoConfig;
    FThread: TBasculaThread;
    FOnPeso: TBasculaPesoEvent;
    FOnEstado: TBasculaEstadoEvent;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Iniciar(const AConfig: TPesadoConfig);
    procedure Detener;
    procedure SetPesoSimulado(APesoKg: Double);
    function Activa: Boolean;
    property OnPeso: TBasculaPesoEvent read FOnPeso write FOnPeso;
    property OnEstado: TBasculaEstadoEvent read FOnEstado write FOnEstado;
  end;

{ Utilidades públicas }
function ParsearTramaPeso(const ATrama: string; AUnidadDefecto: TUnidadPeso;
  out APesoKg: Double; out AEstabilidad: Integer): Boolean;  // AEstabilidad: -1 desconocida, 0 inestable, 1 estable
function HexToBytes(const AHex: string): TBytes;
function ProbarPuertoBascula(const AConfig: TPesadoConfig; ASegundos: Integer; out ATexto: string): Boolean;
procedure ListarPuertosCOM(AStrings: TStrings);

implementation

uses
  System.Math, System.Win.Registry;

const
  ParityValues: array[0..2] of Byte = (NOPARITY, ODDPARITY, EVENPARITY);
  StopBitValues: array[0..2] of Byte = (ONESTOPBIT, ONE5STOPBITS, TWOSTOPBITS);

function HexToBytes(const AHex: string): TBytes;
var
  LClean: string;
  I, LVal: Integer;
begin
  SetLength(Result, 0);
  LClean := StringReplace(UpperCase(Trim(AHex)), ' ', '', [rfReplaceAll]);
  LClean := StringReplace(LClean, '0X', '', [rfReplaceAll]);
  I := 1;
  while I < Length(LClean) do
  begin
    if TryStrToInt('$' + Copy(LClean, I, 2), LVal) then
    begin
      SetLength(Result, Length(Result) + 1);
      Result[High(Result)] := Byte(LVal);
    end;
    Inc(I, 2);
  end;
end;

function ParsearTramaPeso(const ATrama: string; AUnidadDefecto: TUnidadPeso;
  out APesoKg: Double; out AEstabilidad: Integer): Boolean;
var
  LUp, LNum, LResto: string;
  I, LIni: Integer;
  LValor: Double;
  LNegativo: Boolean;
  LFmt: TFormatSettings;
  LUnidad: TUnidadPeso;
begin
  Result := False;
  APesoKg := 0;
  AEstabilidad := -1;
  LUp := UpperCase(Trim(ATrama));
  if LUp = '' then
    Exit;

  // Indicadores de estabilidad habituales (ST/US, GS/NT, "?" = en movimiento)
  if (Pos('ST', LUp) = 1) or (Pos(',ST', LUp) > 0) then
    AEstabilidad := 1
  else if (Pos('US', LUp) = 1) or (Pos(',US', LUp) > 0) or (Pos('?', LUp) > 0) then
    AEstabilidad := 0;

  // Buscar el primer número (con signo y decimales con punto o coma)
  LIni := 0;
  for I := 1 to Length(LUp) do
    if CharInSet(LUp[I], ['0'..'9']) then
    begin
      LIni := I;
      Break;
    end;
  if LIni = 0 then
    Exit;

  LNegativo := False;
  I := LIni - 1;
  while (I >= 1) and (LUp[I] = ' ') do
    Dec(I);
  if (I >= 1) and (LUp[I] = '-') then
    LNegativo := True;

  LNum := '';
  I := LIni;
  while (I <= Length(LUp)) and CharInSet(LUp[I], ['0'..'9', '.', ',']) do
  begin
    if LUp[I] = ',' then
      LNum := LNum + '.'
    else
      LNum := LNum + LUp[I];
    Inc(I);
  end;
  LResto := Trim(Copy(LUp, I, MaxInt));

  LFmt := TFormatSettings.Invariant;
  if not TryStrToFloat(LNum, LValor, LFmt) then
    Exit;
  if LNegativo then
    LValor := -LValor;

  LUnidad := AUnidadDefecto;
  if Pos('KG', LResto) = 1 then
    LUnidad := upKg
  else if (Pos('G', LResto) = 1) then
    LUnidad := upGramos;

  if LUnidad = upGramos then
    APesoKg := LValor / 1000
  else
    APesoKg := LValor;
  Result := True;
end;

procedure ListarPuertosCOM(AStrings: TStrings);
var
  LReg: TRegistry;
  LNombres: TStringList;
  I: Integer;
  LPuerto: string;
begin
  AStrings.Clear;
  LReg := TRegistry.Create(KEY_READ);
  LNombres := TStringList.Create;
  try
    LReg.RootKey := HKEY_LOCAL_MACHINE;
    if LReg.OpenKeyReadOnly('HARDWARE\DEVICEMAP\SERIALCOMM') then
    begin
      LReg.GetValueNames(LNombres);
      for I := 0 to LNombres.Count - 1 do
      begin
        LPuerto := LReg.ReadString(LNombres[I]);
        if (LPuerto <> '') and (AStrings.IndexOf(LPuerto) < 0) then
          AStrings.Add(LPuerto);
      end;
      LReg.CloseKey;
    end;
  finally
    LNombres.Free;
    LReg.Free;
  end;
  // Siempre ofrecer COM1..COM16 por si el driver aún no está enumerado
  for I := 1 to 16 do
    if AStrings.IndexOf('COM' + IntToStr(I)) < 0 then
      AStrings.Add('COM' + IntToStr(I));
end;

function AbrirHandleCOM(const AConfig: TPesadoConfig; out AHandle: THandle; out AError: string): Boolean;
var
  LDCB: TDCB;
  LTimeouts: TCommTimeouts;
begin
  Result := False;
  AError := '';
  AHandle := CreateFile(PChar('\\.\' + AConfig.Puerto), GENERIC_READ or GENERIC_WRITE, 0, nil,
    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  if AHandle = INVALID_HANDLE_VALUE then
  begin
    AError := Format('No se puede abrir %s: %s', [AConfig.Puerto, SysErrorMessage(GetLastError)]);
    Exit;
  end;

  SetupComm(AHandle, 4096, 4096);
  FillChar(LDCB, SizeOf(LDCB), 0);
  LDCB.DCBlength := SizeOf(LDCB);
  if not GetCommState(AHandle, LDCB) then
  begin
    AError := 'GetCommState: ' + SysErrorMessage(GetLastError);
    CloseHandle(AHandle);
    AHandle := INVALID_HANDLE_VALUE;
    Exit;
  end;
  LDCB.BaudRate := AConfig.BaudRate;
  LDCB.ByteSize := AConfig.DataBits;
  LDCB.Parity := ParityValues[EnsureRange(AConfig.Paridad, 0, 2)];
  LDCB.StopBits := StopBitValues[EnsureRange(AConfig.StopBits, 0, 2)];
  LDCB.Flags := 1; // fBinary
  if not SetCommState(AHandle, LDCB) then
  begin
    AError := 'SetCommState: ' + SysErrorMessage(GetLastError);
    CloseHandle(AHandle);
    AHandle := INVALID_HANDLE_VALUE;
    Exit;
  end;

  FillChar(LTimeouts, SizeOf(LTimeouts), 0);
  LTimeouts.ReadIntervalTimeout := 30;
  LTimeouts.ReadTotalTimeoutMultiplier := 0;
  LTimeouts.ReadTotalTimeoutConstant := 80;
  LTimeouts.WriteTotalTimeoutConstant := 200;
  SetCommTimeouts(AHandle, LTimeouts);
  PurgeComm(AHandle, PURGE_RXCLEAR or PURGE_TXCLEAR);
  Result := True;
end;

function ProbarPuertoBascula(const AConfig: TPesadoConfig; ASegundos: Integer; out ATexto: string): Boolean;
var
  LHandle: THandle;
  LError: string;
  LBuf: array[0..255] of AnsiChar;
  LLeidos, LEscritos: DWORD;
  LFin: UInt64;
  LCmd: TBytes;
  LRaw: AnsiString;
  I: Integer;
begin
  Result := False;
  ATexto := '';
  if not AbrirHandleCOM(AConfig, LHandle, LError) then
  begin
    ATexto := LError;
    Exit;
  end;
  try
    LCmd := HexToBytes(AConfig.ComandoPeticionHex);
    LRaw := '';
    LFin := GetTickCount64 + UInt64(ASegundos) * 1000;
    while GetTickCount64 < LFin do
    begin
      if Length(LCmd) > 0 then
        WriteFile(LHandle, LCmd[0], Length(LCmd), LEscritos, nil);
      LLeidos := 0;
      if ReadFile(LHandle, LBuf, SizeOf(LBuf), LLeidos, nil) and (LLeidos > 0) then
      begin
        for I := 0 to Integer(LLeidos) - 1 do
          LRaw := LRaw + LBuf[I];
      end;
      Sleep(AConfig.IntervaloMs);
    end;
    // Hacer visibles los caracteres de control
    for I := 1 to Length(LRaw) do
      case Ord(LRaw[I]) of
        2: ATexto := ATexto + '<STX>';
        3: ATexto := ATexto + '<ETX>';
        10: ATexto := ATexto + '<LF>' + sLineBreak;
        13: ATexto := ATexto + '<CR>';
        0..1, 4..9, 11..12, 14..31: ATexto := ATexto + Format('<%.2x>', [Ord(LRaw[I])]);
      else
        ATexto := ATexto + Char(LRaw[I]);
      end;
    Result := LRaw <> '';
    if not Result then
      ATexto := 'Puerto abierto correctamente pero no se han recibido datos en ' + IntToStr(ASegundos) + ' s.';
  finally
    CloseHandle(LHandle);
  end;
end;

{ TBasculaThread }

constructor TBasculaThread.Create(AOwner: TObject; const AConfig: TPesadoConfig;
  AOnPeso: TBasculaPesoEvent; AOnEstado: TBasculaEstadoEvent);
begin
  inherited Create(True);
  FreeOnTerminate := False;
  FOwner := AOwner;
  FConfig := AConfig;
  FOnPeso := AOnPeso;
  FOnEstado := AOnEstado;
  FHandle := INVALID_HANDLE_VALUE;
  FLock := TCriticalSection.Create;
  FNumMuestras := Max(2, FConfig.MuestrasEstables);
  SetLength(FMuestras, FNumMuestras);
  FIdxMuestra := 0;
  FComando := HexToBytes(FConfig.ComandoPeticionHex);
end;

destructor TBasculaThread.Destroy;
begin
  CerrarPuerto;
  FLock.Free;
  inherited;
end;

procedure TBasculaThread.SetPesoSimulado(APesoKg: Double);
begin
  FLock.Enter;
  try
    FPesoSimuladoKg := APesoKg;
  finally
    FLock.Leave;
  end;
end;

function TBasculaThread.AbrirPuerto(out AError: string): Boolean;
begin
  Result := AbrirHandleCOM(FConfig, FHandle, AError);
end;

procedure TBasculaThread.CerrarPuerto;
begin
  if FHandle <> INVALID_HANDLE_VALUE then
  begin
    CloseHandle(FHandle);
    FHandle := INVALID_HANDLE_VALUE;
  end;
end;

function TBasculaThread.EvaluarEstable(APesoKg: Double): Boolean;
var
  I: Integer;
  LMin, LMax: Double;
begin
  FMuestras[FIdxMuestra mod FNumMuestras] := APesoKg;
  Inc(FIdxMuestra);
  if FIdxMuestra < FNumMuestras then
    Exit(False);
  if FIdxMuestra > 1000000 then
    FIdxMuestra := FNumMuestras; // evitar desbordamiento
  LMin := FMuestras[0];
  LMax := FMuestras[0];
  for I := 1 to FNumMuestras - 1 do
  begin
    LMin := Min(LMin, FMuestras[I]);
    LMax := Max(LMax, FMuestras[I]);
  end;
  Result := (LMax - LMin) * 1000 <= FConfig.ToleranciaEstableGr;
end;

procedure TBasculaThread.NotificarPeso(APesoKg: Double; AEstable: Boolean; const ATrama: string);
var
  LEvento: TBasculaPesoEvent;
  LOwner: TObject;
begin
  LEvento := FOnPeso;
  LOwner := FOwner;
  if not Assigned(LEvento) then
    Exit;
  TThread.Queue(Self,
    procedure
    begin
      LEvento(LOwner, APesoKg, AEstable, ATrama);
    end);
end;

procedure TBasculaThread.NotificarEstado(AConectada: Boolean; const AMensaje: string);
var
  LEvento: TBasculaEstadoEvent;
  LOwner: TObject;
begin
  LEvento := FOnEstado;
  LOwner := FOwner;
  if not Assigned(LEvento) then
    Exit;
  TThread.Queue(Self,
    procedure
    begin
      LEvento(LOwner, AConectada, AMensaje);
    end);
end;

procedure TBasculaThread.ProcesarBuffer;
var
  LPos, I: Integer;
  LLinea: string;
  LPeso: Double;
  LEstabTrama: Integer;
  LEstable: Boolean;
begin
  // Separar líneas por CR, LF o ETX; eliminar STX
  repeat
    LPos := 0;
    for I := 1 to Length(FBuffer) do
      if CharInSet(FBuffer[I], [#13, #10, #3]) then
      begin
        LPos := I;
        Break;
      end;
    if LPos = 0 then
      Break;
    LLinea := string(Copy(FBuffer, 1, LPos - 1));
    Delete(FBuffer, 1, LPos);
    LLinea := StringReplace(LLinea, #2, '', [rfReplaceAll]);
    if Trim(LLinea) = '' then
      Continue;
    if ParsearTramaPeso(LLinea, FConfig.UnidadTrama, LPeso, LEstabTrama) then
    begin
      LEstable := EvaluarEstable(LPeso);
      if LEstabTrama = 0 then
        LEstable := False
      else if (LEstabTrama = 1) and (FIdxMuestra >= 2) then
        LEstable := LEstable or (Abs(FMuestras[(FIdxMuestra - 1) mod FNumMuestras] -
          FMuestras[(FIdxMuestra - 2) mod FNumMuestras]) * 1000 <= FConfig.ToleranciaEstableGr);
      NotificarPeso(LPeso, LEstable, LLinea);
    end;
  until False;
  // Protección ante basura sin terminadores
  if Length(FBuffer) > 1024 then
    FBuffer := '';
end;

procedure TBasculaThread.EjecutarReal;
var
  LError: string;
  LBuf: array[0..255] of AnsiChar;
  LLeidos, LEscritos: DWORD;
  I: Integer;
  LUltimoDato: UInt64;
  LAvisadoSinDatos: Boolean;
begin
  while not Terminated do
  begin
    if not AbrirPuerto(LError) then
    begin
      NotificarEstado(False, LError + ' (reintentando...)');
      for I := 1 to 20 do
      begin
        if Terminated then
          Exit;
        Sleep(100);
      end;
      Continue;
    end;

    NotificarEstado(True, Format('Báscula conectada en %s (%d baudios)', [FConfig.Puerto, FConfig.BaudRate]));
    FBuffer := '';
    LUltimoDato := GetTickCount64;
    LAvisadoSinDatos := False;

    while not Terminated do
    begin
      if Length(FComando) > 0 then
        if not WriteFile(FHandle, FComando[0], Length(FComando), LEscritos, nil) then
          Break;

      LLeidos := 0;
      if not ReadFile(FHandle, LBuf, SizeOf(LBuf), LLeidos, nil) then
        Break; // Puerto perdido (USB desconectado): reabrir

      if LLeidos > 0 then
      begin
        for I := 0 to Integer(LLeidos) - 1 do
          FBuffer := FBuffer + LBuf[I];
        ProcesarBuffer;
        LUltimoDato := GetTickCount64;
        if LAvisadoSinDatos then
        begin
          NotificarEstado(True, Format('Báscula conectada en %s (%d baudios)', [FConfig.Puerto, FConfig.BaudRate]));
          LAvisadoSinDatos := False;
        end;
      end
      else if (not LAvisadoSinDatos) and (GetTickCount64 - LUltimoDato > 3000) then
      begin
        NotificarEstado(False, Format('%s abierto pero sin datos de la báscula. Revise cable/configuración.', [FConfig.Puerto]));
        LAvisadoSinDatos := True;
      end;

      if Length(FComando) > 0 then
        Sleep(FConfig.IntervaloMs);
    end;

    CerrarPuerto;
    if not Terminated then
      NotificarEstado(False, 'Comunicación perdida con ' + FConfig.Puerto + '. Reconectando...');
  end;
end;

procedure TBasculaThread.EjecutarSimulado;
var
  LObjetivo: Double;
  LEstable: Boolean;
  LRuido: Double;
begin
  NotificarEstado(True, 'MODO SIMULACIÓN (sin báscula física)');
  Randomize;
  FPesoSimuladoActualKg := 0;
  while not Terminated do
  begin
    FLock.Enter;
    try
      LObjetivo := FPesoSimuladoKg;
    finally
      FLock.Leave;
    end;
    // Aproximación progresiva al objetivo para simular la oscilación del plato
    FPesoSimuladoActualKg := FPesoSimuladoActualKg + (LObjetivo - FPesoSimuladoActualKg) * 0.5;
    if Abs(LObjetivo - FPesoSimuladoActualKg) < 0.0005 then
      FPesoSimuladoActualKg := LObjetivo;
    LRuido := 0;
    if Abs(LObjetivo - FPesoSimuladoActualKg) > 0.0005 then
      LRuido := (Random - 0.5) * 0.002;
    LEstable := EvaluarEstable(RoundTo(FPesoSimuladoActualKg + LRuido, -3));
    NotificarPeso(RoundTo(FPesoSimuladoActualKg + LRuido, -3), LEstable,
      Format('SIM %.3f kg', [FPesoSimuladoActualKg + LRuido], TFormatSettings.Invariant));
    Sleep(FConfig.IntervaloMs);
  end;
end;

procedure TBasculaThread.Execute;
begin
  NameThreadForDebugging('BasculaCOM');
  try
    if FConfig.Simulado then
      EjecutarSimulado
    else
      EjecutarReal;
  except
    on E: Exception do
      NotificarEstado(False, 'Error en hilo de báscula: ' + E.Message);
  end;
end;

{ TBasculaSerial }

constructor TBasculaSerial.Create;
begin
  inherited Create;
  FThread := nil;
end;

destructor TBasculaSerial.Destroy;
begin
  Detener;
  inherited;
end;

function TBasculaSerial.Activa: Boolean;
begin
  Result := Assigned(FThread);
end;

procedure TBasculaSerial.Iniciar(const AConfig: TPesadoConfig);
begin
  Detener;
  FConfig := AConfig;
  FThread := TBasculaThread.Create(Self, FConfig, FOnPeso, FOnEstado);
  FThread.Start;
end;

procedure TBasculaSerial.Detener;
begin
  if Assigned(FThread) then
  begin
    FThread.Terminate;
    FThread.WaitFor;
    TThread.RemoveQueuedEvents(FThread);
    FreeAndNil(FThread);
  end;
end;

procedure TBasculaSerial.SetPesoSimulado(APesoKg: Double);
begin
  if Assigned(FThread) then
    FThread.SetPesoSimulado(APesoKg);
end;

end.

