unit uCapturaBascula;

interface

uses
  System.SysUtils, System.Classes, System.Math;

type
  TCapturaBascula = class
  private
    FBuffer: string;
    FUltimoPeso: Double;
    FUltimaTrama: string;
    FEstable: Boolean;

    // Historial para calculo de estabilidad heuristica
    FHistorialPesos: array[0..4] of Double;
    FHistorialCount: Integer;

    function ExtraerNumeroDeTrama(const ATrama: string; out APeso: Double; out AEstableFlag: Boolean): Boolean;
    function ComprobarEstabilidad(APeso: Double): Boolean;
  public
    constructor Create;
    procedure Reset;
    procedure LimpiarBuffer;

    { Procesa los datos entrantes del puerto COM.
      Devuelve True si se ha decodificado una trama valida con peso numerico. }
    function ProcesarDatos(const AData: string; out APeso: Double; out AEstable: Boolean; out APesoTexto: string): Boolean;

    property Buffer: string read FBuffer;
    property UltimoPeso: Double read FUltimoPeso;
    property UltimaTrama: string read FUltimaTrama;
    property Estable: Boolean read FEstable;
  end;

implementation

constructor TCapturaBascula.Create;
begin
  inherited Create;
  Reset;
end;

procedure TCapturaBascula.Reset;
var
  I: Integer;
begin
  FBuffer := '';
  FUltimoPeso := 0.0;
  FUltimaTrama := '';
  FEstable := False;
  FHistorialCount := 0;
  for I := Low(FHistorialPesos) to High(FHistorialPesos) do
    FHistorialPesos[I] := 0.0;
end;

procedure TCapturaBascula.LimpiarBuffer;
begin
  FBuffer := '';
end;

function TCapturaBascula.ComprobarEstabilidad(APeso: Double): Boolean;
var
  I: Integer;
  MaxP, MinP: Double;
begin
  // Desplazar historial
  for I := High(FHistorialPesos) downto 1 do
    FHistorialPesos[I] := FHistorialPesos[I - 1];
  FHistorialPesos[0] := APeso;

  if FHistorialCount < Length(FHistorialPesos) then
    Inc(FHistorialCount);

  if FHistorialCount < 3 then
  begin
    Result := False;
    Exit;
  end;

  MaxP := FHistorialPesos[0];
  MinP := FHistorialPesos[0];
  for I := 1 to FHistorialCount - 1 do
  begin
    if FHistorialPesos[I] > MaxP then MaxP := FHistorialPesos[I];
    if FHistorialPesos[I] < MinP then MinP := FHistorialPesos[I];
  end;

  // Si la variacion entre las ultimas muestras es <= 0.05 kg, consideramos estable
  Result := (MaxP - MinP) <= 0.05;
end;

function TCapturaBascula.ExtraerNumeroDeTrama(const ATrama: string; out APeso: Double; out AEstableFlag: Boolean): Boolean;
var
  I: Integer;
  S, StrNum, UpperT: string;
  Signo: Double;
  ValParsed: Double;
  FS: TFormatSettings;
  TieneFlagExplicito: Boolean;
  FlagEstable: Boolean;
  EnNumero: Boolean;
begin
  Result := False;
  APeso := 0.0;
  AEstableFlag := False;

  S := Trim(ATrama);
  if S = '' then
    Exit;

  UpperT := UpperCase(S);
  TieneFlagExplicito := False;
  FlagEstable := False;

  // Deteccion de banderas de estabilidad en la trama
  if (Pos('ST', UpperT) > 0) or (Pos('S,', UpperT) > 0) or (Pos('OK', UpperT) > 0) or (Pos('ESTABLE', UpperT) > 0) then
  begin
    TieneFlagExplicito := True;
    FlagEstable := True;
  end
  else if (Pos('US', UpperT) > 0) or (Pos('U,', UpperT) > 0) or (Pos('MOV', UpperT) > 0) or (Pos('DYN', UpperT) > 0) then
  begin
    TieneFlagExplicito := True;
    FlagEstable := False;
  end;

  // Limpiar caracteres de control o prefijos tipicos
  Signo := 1.0;
  StrNum := '';
  EnNumero := False;

  for I := 1 to Length(S) do
  begin
    if (S[I] = '-') and (not EnNumero) then
    begin
      Signo := -1.0;
    end
    else if (S[I] = '+') and (not EnNumero) then
    begin
      Signo := 1.0;
    end
    else if CharInSet(S[I], ['0'..'9', '.', ',']) then
    begin
      EnNumero := True;
      if S[I] = ',' then
        StrNum := StrNum + '.'
      else
        StrNum := StrNum + S[I];
    end
    else if EnNumero then
    begin
      // Terminar lectura del bloque numerico al encontrar espacio o letra
      Break;
    end;
  end;

  if StrNum <> '' then
  begin
    FS := TFormatSettings.Create;
    FS.DecimalSeparator := '.';
    if TryStrToFloat(StrNum, ValParsed, FS) then
    begin
      APeso := ValParsed * Signo;
      if TieneFlagExplicito then
        AEstableFlag := FlagEstable
      else
        AEstableFlag := ComprobarEstabilidad(APeso);

      Result := True;
    end;
  end;
end;

function TCapturaBascula.ProcesarDatos(const AData: string; out APeso: Double; out AEstable: Boolean; out APesoTexto: string): Boolean;
var
  DelimPos: Integer;
  Trama: string;
  PosCR, PosLF, PosETX: Integer;
  PesoTemp: Double;
  EstableTemp: Boolean;
  Decodificado: Boolean;
begin
  Result := False;
  APeso := FUltimoPeso;
  AEstable := FEstable;
  APesoTexto := '';

  if AData = '' then
    Exit;

  FBuffer := FBuffer + AData;

  // Evitar desbordamiento de buffer por ruido en la linea serie
  if Length(FBuffer) > 2048 then
    Delete(FBuffer, 1, Length(FBuffer) - 512);

  Decodificado := False;

  // Buscar delimitadores de fin de trama (#13, #10 o #3 ETX)
  while True do
  begin
    PosCR := Pos(#13, FBuffer);
    PosLF := Pos(#10, FBuffer);
    PosETX := Pos(#3, FBuffer);

    DelimPos := 0;
    if (PosCR > 0) and ((PosLF = 0) or (PosCR < PosLF)) and ((PosETX = 0) or (PosCR < PosETX)) then
      DelimPos := PosCR
    else if (PosLF > 0) and ((PosETX = 0) or (PosLF < PosETX)) then
      DelimPos := PosLF
    else if PosETX > 0 then
      DelimPos := PosETX;

    if DelimPos <= 0 then
      Break;

    Trama := Copy(FBuffer, 1, DelimPos - 1);
    Delete(FBuffer, 1, DelimPos);

    // Limpiar salto de linea continuo (ej: si era CRLF y consumimos CR, consumir el LF siguiente)
    while (Length(FBuffer) > 0) and CharInSet(FBuffer[1], [#10, #13, #0]) do
      Delete(FBuffer, 1, 1);

    Trama := Trim(Trama);
    if Trama <> '' then
    begin
      FUltimaTrama := Trama;
      if ExtraerNumeroDeTrama(Trama, PesoTemp, EstableTemp) then
      begin
        FUltimoPeso := PesoTemp;
        FEstable := EstableTemp;
        Decodificado := True;
      end;
    end;
  end;

  if Decodificado then
  begin
    APeso := FUltimoPeso;
    AEstable := FEstable;
    APesoTexto := FormatFloat('0.00', FUltimoPeso);
    Result := True;
  end;
end;

end.
