//---------------------------------------------------------------------------
#include <vcl\vcl.h>
#include <stdio.h>
#pragma hdrstop

#include "Configb.h"
#include "..\..\..\..\PcScale.h"

PcScaleVars Vars; //PcScaleVars is define in PcScale.h and has a variables used
                 //for functions
//---------------------------------------------------------------------------
#pragma resource "*.dfm"
TFormConfBal *FormConfBal;

//---------------------------------------------------------------------------
__fastcall TFormConfBal::TFormConfBal(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
bool __fastcall TFormConfBal::GeraArquivo(void)
{

    HANDLE	hPar;
    DWORD	BytesRead;
    char    msg[100];
    bool	ret;

    hPar = CreateFile("lebal.txt", GENERIC_READ | GENERIC_WRITE,
                      FILE_SHARE_READ | FILE_SHARE_WRITE,
                      NULL, OPEN_ALWAYS, 0, NULL);

    ret = false;
    if (hPar != INVALID_HANDLE_VALUE)
      {
         sprintf(msg,"%d;%s;%s;%s;%s\r\n",status,Vars.bruto,Vars.tara,Vars.liquido,Vars.unidade);
         SetFilePointer(hPar,0,NULL,FILE_END);
         if (WriteFile(hPar, msg, strlen(msg), &BytesRead, NULL))
            ret = true;
         CloseHandle(hPar);
      }
    return ret;
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::TimerConfBalTimer(TObject *Sender)
{
    int	Indicador;

    // apaga as luzes
    ShapeStable->Brush->Color  = clInactiveBorder;
    ShapeMotion->Brush->Color  = clInactiveBorder;
    ShapeOvercap->Brush->Color = clInactiveBorder;
    ShapeError->Brush->Color   = clInactiveBorder;

    // faz a leitura de acordo com o tipo de indicador
    switch( (Indicador=CBIndicador->ItemIndex) )
    {
        // A CS tem outro programa de exemplo
        case BCS:
        status=ScaleError;
        break;

        case BCI:
        status = ReadCI(&hScale,
                        Vars.bruto,
                        Vars.tara,
                        Vars.liquido,
                        Vars.quantidade,
                        Vars.codigo,
                        Vars.pmedio,
                        Vars.datafab,
                        Vars.dataval
                        );
        break;

        case BIDU:
        case BIDM:
        status = ReadIDM(&hScale,
                         Vars.bruto,
                         Vars.tara,
                         Vars.liquido,
                         Vars.quantidade,
                         Vars.codigo
                         );
        break;

        default:
        status = ReadScale(&hScale,
                            Indicador,
                            Vars.bruto,
                            Vars.tara,
                            Vars.liquido,
                            Vars.unidade
                            );
        break;
    }

    // processa o status recebido
    switch (status)
    {
        case ScaleError:
        if ( Indicador == BCS )
        {
            TimerConfBal->Enabled = false;  // desabilita nova leitura
            ShowMessage("Use o aplicativo LeCS.exe para fazer teste com esta balança.");
        }

        ShapeError->Brush->Color = clRed;
        break;

        case ScaleStable:
        ShapeStable->Brush->Color = clGreen;
        if ((Indicador == BIDC))
        {
            // desabilita timer por 5 segundos antes de permitir uma nova
            // leitura
            TimerConfBal->Enabled = false;
            TimerReabilita->Enabled = true;
        }
        break;

        case ScaleInMotion:
        ShapeMotion->Brush->Color = clYellow;
        break;

        case ScaleOutOfRange:
        ShapeOvercap->Brush->Color = clPurple;
        break;

        case ProteqNotFound:
        TimerConfBal->Enabled = false;
        Application->MessageBox("Erro lendo chave de licença do software","Erro",MB_OK | MB_ICONERROR);
        break;
    }

    // se foi bem sucedido, atualiza os campos
    if (status)
    {
        PanelNet->Caption   = Vars.liquido;
        PanelGross->Caption = Vars.bruto;
        PanelTare->Caption  = Vars.tara;
        PanelCont->Caption  = Vars.quantidade;
        PanelCod->Caption   = Vars.codigo;
        if  ((Indicador == BIDM) || (Indicador == BIDU))
        {
            LabelUnidade->Caption = "kg";
            try
            {
                PanelNet->Caption = FormatFloat("#0.000",StrToFloat(Vars.bruto)-StrToFloat(Vars.tara));
            }
            catch(...)
            {
                PanelNet->Caption = FormatFloat("#0.000",0);
            }
        }
    }

    // verifica a gravação do arquivo
    if (CheckBoxArquivo->Checked && !GeraArquivo())
    {
        TimerConfBal->Enabled = false;
        Application->MessageBox("Erro gerando arquivo LEBAL.TXT","Erro",MB_ICONERROR);
    }
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::CheckParametersComm(void)
{
	if (CBIndicador->ItemIndex != -1 &&
        CBConexao->ItemIndex != -1 &&
        RGBaudRate->ItemIndex != -1 &&
        RGParity->ItemIndex != -1 &&
        RGDataBits->ItemIndex != -1 &&
        RGStopBit->ItemIndex != -1)
    {
        ButtonTeste->Enabled = true;
        BitBtnSalvar->Enabled = true;
    }
    else
    {
        ButtonTeste->Enabled = false;
        BitBtnSalvar->Enabled = false;
    }
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::DisableAllFields(void)
{
     CBIndicador->Enabled = false;
     CBConexao->Enabled = false;
     RGBaudRate->Enabled = false;
     RGDataBits->Enabled = false;
     RGStopBit->Enabled = false;
     RGParity->Enabled = false;
     ClearPanel();
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::EnableAllFields(void)
{
     ClearPanel();
     CBIndicador->Enabled = true;
     CBConexao->Enabled = true;
     RGBaudRate->Enabled = true;
     RGDataBits->Enabled = true;
     RGStopBit->Enabled = true;
     RGParity->Enabled = true;
}
//---------------------------------------------------------------------------
bool __fastcall TFormConfBal::InicializaBalanca(void)
{
    int         StopBits,Parity;
    char        msg[50];

    if( RGStopBit->ItemIndex == 0 )
       StopBits = ONESTOPBIT;
    else
       StopBits = TWOSTOPBITS;

    switch(RGParity->ItemIndex)
       {
          case 0:
             Parity = NOPARITY;
             break;

          case 1:
             Parity = ODDPARITY;
             break;

          case 2:
             Parity = EVENPARITY;
       }

    status = AttachScale(
                &hScale,
                CBConexao->ItemIndex+1,
                StrToInt(RGBaudRate->Items->Strings[RGBaudRate->ItemIndex]),
                (BYTE)StrToInt(RGDataBits->Items->Strings[RGDataBits->ItemIndex]),
                StopBits,
                Parity
                );

    if( status < 0 )
       {
           switch(status)
              {
                  case -2:
                     sprintf(msg,"Erro abrindo com");
                     break;

                  case -3:
                     sprintf(msg,"Com inválida");
                     break;

                  case -4:
                     sprintf(msg,"Muitos arquivos abertos");
                     break;

                  case -5:
                     sprintf(msg,"Acesso a Com não permitido");
                     break;

                  case -6:
                     sprintf(msg,"Erro setando parâmetros de comunicação");
                     break;

                  case -7:
                     sprintf(msg,"Erro setando timeout de comunicação");
                     break;

                  case -100:
                     sprintf(msg,"Arquivo vazio");
                     break;

                  case -101:
                     sprintf(msg,"Disco cheio");
                     break;

                  case -106:
                     sprintf(msg,"Input inválido");
                     break;

                  default:
                     sprintf(msg,"Erro Genérico");
              }
           Application->MessageBox(msg,"Erro",MB_OK | MB_ICONERROR );
           return false;
       }
    return true;
}

//---------------------------------------------------------------------------
void __fastcall TFormConfBal::ButtonTesteClick(TObject *Sender)
{
     if( ButtonTeste->Caption == "Parar" )
       {
           ButtonTeste->Caption = "Teste";
           TimerConfBal->Enabled = false;
           EnableAllFields();
       }
     else
       {
          if( InicializaBalanca() )
           {
              ButtonTeste->Caption = "Parar";
              DisableAllFields();
              TimerConfBal->Enabled = true;
           }
       }
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::CBIndicadorChange(TObject *Sender)
{
	CheckParametersComm();
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::RGBaudRateClick(TObject *Sender)
{
	CheckParametersComm();
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::RGParityClick(TObject *Sender)
{
	CheckParametersComm();
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::RGStopBitClick(TObject *Sender)
{
	CheckParametersComm();
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::RGDataBitsClick(TObject *Sender)
{
	CheckParametersComm();
}
//---------------------------------------------------------------------------
int __fastcall TFormConfBal::GetScaleParameters(int balno,ScalePars *pPars)
{
   	char    	file[13];
	int		ret;
        HANDLE          hPar;
 	DWORD   	BytesRead;

    sprintf(file,"Sclpars%1.1d.sys",balno);

    hPar = CreateFile(file, GENERIC_READ | GENERIC_WRITE,
                      0, NULL, OPEN_EXISTING, 0, NULL);

    ret=0;
    if( hPar != INVALID_HANDLE_VALUE )
       {
          if (ReadFile( hPar, pPars, sizeof(ScalePars), &BytesRead, NULL ))
             {
                if (BytesRead == sizeof(ScalePars))
                   ret = 1;
             }
          CloseHandle(hPar);
       }
    return ret;
}
//---------------------------------------------------------------------------
int __fastcall TFormConfBal::WriteScaleParameters(int balno,ScalePars *pPars)
{
    char       file[13];
    int        ret;
    HANDLE     hPar;
    DWORD      BytesRead;

    sprintf(file,"Sclpars%1.1d.sys",balno);

    hPar = CreateFile(file, GENERIC_READ | GENERIC_WRITE,
                      0, NULL, OPEN_ALWAYS, 0, NULL);

    ret = 0;
    if (hPar != INVALID_HANDLE_VALUE)
       {
          if (WriteFile(hPar, pPars, sizeof(ScalePars), &BytesRead, NULL))
             ret =1;
          CloseHandle(hPar);
       }
    return ret;
}
//---------------------------------------------------------------------------

void __fastcall TFormConfBal::ClearPanel(void)
{
     ShapeStable->Brush->Color  = clInactiveBorder;
     ShapeMotion->Brush->Color  = clInactiveBorder;
     ShapeOvercap->Brush->Color = clInactiveBorder;
     ShapeError->Brush->Color   = clInactiveBorder;

     PanelGross->Caption = "";
     PanelNet->Caption = "";
     PanelTare->Caption = "";
     PanelCod->Caption = "";
     PanelCont->Caption = "";
     LabelUnidade->Caption = "";

}

//---------------------------------------------------------------------------
void __fastcall TFormConfBal::FormClose(TObject *Sender, TCloseAction &Action)
{
     TimerConfBal->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::BitBtnSalvarClick(TObject *Sender)
{
    ParametrosBal.Com = CBConexao->ItemIndex+1;
    ParametrosBal.Indicator =CBIndicador->ItemIndex;

	if (RGStopBit->ItemIndex == 0)
        ParametrosBal.StopBits = ONESTOPBIT;
	else
        ParametrosBal.StopBits = TWOSTOPBITS;
    switch(RGParity->ItemIndex)
    {
        case 0:
        ParametrosBal.Parity = NOPARITY;
    	break;

        case 1:
	    ParametrosBal.Parity = ODDPARITY;
        break;

        case 2:
        ParametrosBal.Parity = EVENPARITY;
    }

    ParametrosBal.ByteSize = (BYTE)StrToInt(RGDataBits->Items->Strings[RGDataBits->ItemIndex]);
    ParametrosBal.BaudRate = StrToInt(RGBaudRate->Items->Strings[RGBaudRate->ItemIndex]);
    ParametrosBal.Arquivo = CheckBoxArquivo->Checked;
    ParametrosBal.Leitura = CheckBoxLeitura->Checked;

    if (!WriteScaleParameters(1,&ParametrosBal))
       Application->MessageBox("Erro grando parâmetros da balança", "Erro",MB_OK | MB_ICONERROR);
    else
       BitBtnSalvar->Enabled = false;

    TimerConfBal->Enabled = CheckBoxLeitura->Checked;
    ButtonTeste->Enabled = !CheckBoxLeitura->Checked;
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::ClearAllFields(void)
{
    CBIndicador->ItemIndex = -1;
    CBConexao->ItemIndex = -1;
    RGBaudRate->ItemIndex = -1;
    RGDataBits->ItemIndex = -1;
    RGStopBit->ItemIndex = -1;
    RGParity->ItemIndex = -1;
}

//---------------------------------------------------------------------------
void __fastcall TFormConfBal::GetInformation(void)
{
     int        aux;

     EnableAllFields();

    if (!GetScaleParameters(1,&ParametrosBal))
        ClearAllFields();
    else
    {
        CBIndicador->ItemIndex=ParametrosBal.Indicator;
        CBConexao->ItemIndex=ParametrosBal.Com-1;
        for (aux=0; aux < RGDataBits->Items->Count; aux++)
        {
            if (StrToInt(RGDataBits->Items->Strings[aux]) == ParametrosBal.ByteSize )
            {
                RGDataBits->ItemIndex = aux;
                break;
            }
        }

        for (aux= 0; aux < RGBaudRate->Items->Count; aux++)
        {
            if (StrToInt(RGBaudRate->Items->Strings[aux]) == (int)ParametrosBal.BaudRate)
            {
                RGBaudRate->ItemIndex = aux;
                break;
            }
        }

        if (ParametrosBal.StopBits == ONESTOPBIT)
            RGStopBit->ItemIndex = 0;
        else
            RGStopBit->ItemIndex = 1;

        switch(ParametrosBal.Parity)
        {
            case NOPARITY:
            RGParity->ItemIndex=0;
            break;

            case ODDPARITY:
            RGParity->ItemIndex=1;
            break;

            case EVENPARITY:
            RGParity->ItemIndex=2;
        }

        CheckBoxArquivo->Checked = ParametrosBal.Arquivo;
        CheckBoxLeitura->Checked = ParametrosBal.Leitura;
    }
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::FormShow(TObject *Sender)
{
    int aux;
    char  name[50];
    CBIndicador->Clear();
    for( aux=0; aux < GetScaleRecordCount(); aux++ )
    {
        ObtemNomeBalanca(aux,name);
        CBIndicador->Items->Add(name);
    }
    CBIndicador->ItemIndex=-1;
    GetInformation();
    if (CheckBoxLeitura->Checked)
    {
        if (InicializaBalanca())
        {
            TimerConfBal->Enabled = true;
            ButtonTeste->Enabled = false;
        }
    }
    BitBtnSalvar->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::CheckBoxLeituraClick(TObject *Sender)
{
     BitBtnSalvar->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::CheckBoxArquivoClick(TObject *Sender)
{
     BitBtnSalvar->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::TimerReabilitaTimer(TObject *Sender)
{
     TimerReabilita->Enabled = false;
     TimerConfBal->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::CBConexaoChange(TObject *Sender)
{
	CheckParametersComm();
}
//---------------------------------------------------------------------------

