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

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

//---------------------------------------------------------------------------
#pragma resource "*.dfm"
TFormConfBal *FormConfBal;

//---------------------------------------------------------------------------
__fastcall TFormConfBal::TFormConfBal(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::TimerConfBalTimer(TObject *Sender)
{
	ShapeStable->Brush->Color = clSilver;
	ShapeMotion->Brush->Color = clSilver;
	ShapeOvercap->Brush->Color = clSilver;
	ShapeError->Brush->Color = clSilver;

	status = ReadCS(&hScale,peso,vunit,vtotal,codigo);

    switch( status )
	{
		case ScaleError:
		ShapeError->Brush->Color = clRed;
		break;

		case ScaleStable:
		ShapeStable->Brush->Color = clRed;
/*
		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 = clRed;
        break;

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

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

	}

	if( status )
    {
		LPeso->Caption = peso;
	    LUnitario->Caption = vunit;
	    LTotal->Caption = vtotal;
		LCodigo->Caption = codigo;
	}
}
//---------------------------------------------------------------------------
bool __fastcall TFormConfBal::CheckParametersComm(void)
{
	if( CBConexao->ItemIndex == -1 ||
        RGBaudRate->ItemIndex == -1 ||
        RGParity->ItemIndex == -1 ||
        RGDataBits->ItemIndex == -1 ||
        RGStopBit->ItemIndex == -1
        )
    {
        Application->MessageBox(
        "Parâmetro incorreto na configuração da Porta Serial","Erro",MB_ICONERROR
        );
        return false;
    }
    else
        return 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::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();
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::ClearFields(void)
{
	ShapeStable->Brush->Color = clSilver;
	ShapeMotion->Brush->Color = clSilver;
    ShapeOvercap->Brush->Color = clSilver;
    ShapeError->Brush->Color = clSilver;

    LPeso->Caption = "";
    LUnitario->Caption = "";
    LTotal->Caption = "";
    LCodigo->Caption = "";
}

//---------------------------------------------------------------------------
void __fastcall TFormConfBal::FormClose(TObject *Sender, TCloseAction &Action)
{
	TimerConfBal->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::ClearAllFields(void)
{
	CBConexao->ItemIndex = -1;
	RGBaudRate->ItemIndex = -1;
    RGDataBits->ItemIndex = -1;
    RGStopBit->ItemIndex = -1;
    RGParity->ItemIndex = -1;
}

//---------------------------------------------------------------------------
void __fastcall TFormConfBal::TimerReabilitaTimer(TObject *Sender)
{
	TimerReabilita->Enabled = false;
    TimerConfBal->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TFormConfBal::btnEnviarClick(TObject *Sender)
{
    char aux,buf[7];

    if( hScale == NULL )
    {
            Application->MessageBox("Porta serial não inicializada","Erro",MB_ICONERROR);
            return;
    }
    sprintf(buf,"%6.6s",MEPreco->Text.c_str());

    for(aux=0; aux < 6; aux++ )
    {
        if( buf[aux] == ' ' ) buf[aux]='0';
    }

    if( WriteCS(&hScale,buf) == 0 )
        Application->MessageBox(
        "Erro de envio do preço/kg","Erro",MB_ICONERROR
        );
    else
        Application->MessageBox(
        "Preço/kg enviado com sucesso","Informação",MB_ICONEXCLAMATION
        );

}
//---------------------------------------------------------------------------

void __fastcall TFormConfBal::TabSheet2Exit(TObject *Sender)
{
    TimerConfBal->Enabled = false;
    ClearFields();
}
//---------------------------------------------------------------------------


void __fastcall TFormConfBal::btnPortaClick(TObject *Sender)
{
    if( btnPorta->Tag == 0 ) // inicializa
    {
        if( !CheckParametersComm() ) return;

        if( InicializaBalanca() )
        {
            GBConexao->Enabled=false;
            RGBaudRate->Enabled=false;
            btnPorta->Caption = "Encerra Porta Serial";
            btnPorta->Tag = 1;
        }
    }
    else
    {
        GBConexao->Enabled=true;
        RGBaudRate->Enabled=true;
        btnPorta->Tag = 0;
        btnPorta->Caption = "Inicializa Porta Serial";
        DettachScale(&hScale);
        hScale=NULL;
    }

}
//---------------------------------------------------------------------------


void __fastcall TFormConfBal::TabSheet2Show(TObject *Sender)
{

    if( hScale != NULL)
    {
        LStatus->Caption="";
        TimerConfBal->Enabled = true;
    }
    else
        LStatus->Caption="Inicialize a porta serial";
}
//---------------------------------------------------------------------------

