//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "main.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TFormMain *FormMain;
//---------------------------------------------------------------------------

DCB dcbCommPort;
BOOL bPort;
COMMTIMEOUTS CommTimeouts;
DWORD BytesRead;
HANDLE hComm = NULL;
bool CommFlag;
unsigned char InBuffer[101];


void TFormMain::Connect(){
CommFlag=false;
hComm = CreateFile(ComboBoxPort->Text.c_str(),
					GENERIC_READ | GENERIC_WRITE,
					0,
					0,
					OPEN_EXISTING,
					0,
					0);

	if (hComm == INVALID_HANDLE_VALUE) {
		Memo->Lines->Add("Nemohu otevrit comm port.");
		return;
	}

	dcbCommPort.DCBlength = sizeof(DCB);
	GetCommState(hComm, &dcbCommPort);

	if(!BuildCommDCB("baud=9600 parity=N data=8 stop=1", &dcbCommPort)) {
		hComm = NULL;
		Memo->Lines->Add("Nemohu vytvorit comm DCB.");
		return;
	}

	if(!SetCommState(hComm, &dcbCommPort)) {
		CloseHandle(hComm);
		hComm = NULL;
		Memo->Lines->Add("Nemohu nastavit comm state.");
		return;
	}

	CommTimeouts.ReadIntervalTimeout = MAXDWORD;
	CommTimeouts.ReadTotalTimeoutConstant = 0;
	CommTimeouts.ReadTotalTimeoutMultiplier = 0;
	CommTimeouts.WriteTotalTimeoutConstant = 250;
	CommTimeouts.WriteTotalTimeoutMultiplier = 1;

	if(!SetCommTimeouts(hComm, &CommTimeouts)) {
		CloseHandle(hComm);
		hComm = NULL;
		Memo->Lines->Add("Nemohu nastavit comm timeouty.");
		return;
	}
	CommFlag = true;
}

void TFormMain::Disconnect(){
    CommFlag=false;
    CloseHandle(hComm);
    hComm = NULL;
}

AnsiString BCDtoStr(unsigned char what){
unsigned char a;
a=((what>>4) & 0x0f)*10+(what&0x0f);
if (a<10) {return "0"+IntToStr(a); }
else {
return IntToStr(a); }

}

AnsiString DENtoStr(unsigned char what){
switch (what&0x07) {
case 0:return "Ne";
case 1:return "Po";
case 2:return "Ut";
case 3:return "St";
case 4:return "Ct";
case 5:return "Pa";
case 6:return "So";
}
return "Chyba";
}


unsigned char String_To_BCD(AnsiString co){
return (  ((co[1]-'0') << 4) | (co[2]-'0'));
}

__fastcall TFormMain::TFormMain(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------


AnsiString Buff2DateString(byte buff[8]){
        AnsiString TempString;

        TempString=DENtoStr(buff[4])+" "+
        BCDtoStr(buff[3] & 0x3f)+"/" +
        BCDtoStr(buff[5] & 0x1f)+"/" +
        BCDtoStr(buff[6])+" "        +
        BCDtoStr(buff[2] & 0x3f)+":" +
        BCDtoStr(buff[1] & 0x7f)+":" +
        BCDtoStr(buff[0] & 0x7f);
        return TempString;
}


void __fastcall TFormMain::ButtonGetTimeClick(TObject *Sender)
{
Connect();
TransmitCommChar(hComm, 't');
while(CommFlag)
        {Application->ProcessMessages();
                do {
                ReadFile(hComm, InBuffer, 100, &BytesRead, NULL);
                   } 
                while (BytesRead==0);
	     	 if(BytesRead==7)
                {
                Memo->Lines->Add(Buff2DateString(InBuffer));
                CommFlag=false;
               }
	      }
Disconnect();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ButtonSetTimeClick(TObject *Sender)
{
TDateTime ted;
Connect();
  if (CommFlag){
                ted=Now();
                InBuffer[0]='s';
                InBuffer[1]=String_To_BCD(FormatDateTime("ss",ted));
                InBuffer[2]=String_To_BCD(FormatDateTime("nn",ted));
                InBuffer[3]=String_To_BCD(FormatDateTime("hh",ted));
                InBuffer[4]=String_To_BCD(FormatDateTime("dd",ted));
                InBuffer[5]=DayOfWeek(ted)-1;
                InBuffer[6]=String_To_BCD(FormatDateTime("mm",ted));
                InBuffer[7]=String_To_BCD(FormatDateTime("yy",ted));
                WriteFile(hComm, InBuffer, 8, &BytesRead, NULL);
                Application->ProcessMessages();
                Memo->Lines->Add("Cas synchronizovan.");
                CommFlag=false;
  	}
Disconnect();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ButtonLoadClick(TObject *Sender)
{
unsigned int address=0x20;
AnsiString TempString;
unsigned int TempWord;
float TempFloat;
Connect();
if (CommFlag) ListBox->Items->Clear();
while (CommFlag){
        InBuffer[0]='o';
        InBuffer[1]=address >> 8;
        InBuffer[2]=address;
        InBuffer[3]='r';
        WriteFile(hComm, InBuffer, 4, &BytesRead, NULL);
        Application->ProcessMessages();
        do {
	    ReadFile(hComm, InBuffer, 100, &BytesRead, NULL);
        }
        while (BytesRead==0);
        if ( (InBuffer[0]==0xff) || (address>=0x8000)) {CommFlag=false;}
        else {TempString=Buff2DateString(InBuffer+1)+" - ";
              TempWord=(InBuffer[8]<<8) + InBuffer[9];
              TempFloat=0.5*9.81*((float)TempWord/1000)*((float)TempWord/1000)*100;
              TempString+=FloatToStrF((TempFloat), ffFixed, 8,0)+" cm; ";
              if (InBuffer[10]>=127) TempString+="> 8g"; else
              TempString+=FloatToStrF((float)InBuffer[10]/16, ffFixed, 8,2)+"g";
              ListBox->Items->Add(TempString);
              address+=0x10;
        }
        }

Disconnect();        
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ButtonDeleteClick(TObject *Sender)
{
Connect();
if (CommFlag){
    InBuffer[0]='w';
    InBuffer[1]=1;
    InBuffer[2]=0;
    InBuffer[3]=0x20;
    InBuffer[4]=0xff;
    WriteFile(hComm, InBuffer, 5, &BytesRead, NULL);
    ListBox->Items->Clear();
}
Disconnect();
}
//---------------------------------------------------------------------------
