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

#include <vcl.h>
#pragma hdrstop

#include "Komunikace.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
HANDLE hPort;
char InZnak;
char znak;
unsigned long zapsano;
char buffer[1];
	unsigned long precteno;

bool run=true;

static DWORD WINAPI cteni(LPVOID vlakno)
{
	do{
			buffer[0]=' ';

			ReadFile(hPort,&buffer,1,&precteno,NULL);

			if(precteno>0)
				InZnak= buffer[0];

			buffer[0]=' ';

		}while(run);
	return 0;
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)

{


	/*for(;;)
	{
	      	cin>>znak;
		if(znak==0x4)
		{
			run=false;
			break;
		}

		WriteFile(hPort,&znak,1,&zapsano,NULL);
		//cout<<"Zapsano "<<zapsano<<" znaku"<<endl;
	}
     */



       //	CloseHandle(hPort);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)
{
 hPort=CreateFile("COM1",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
	if(hPort==INVALID_HANDLE_VALUE) {}

        DCB parametry;

	GetCommState(hPort,&parametry);

	parametry.BaudRate=CBR_9600;
	parametry.fParity=EVENPARITY;
	parametry.StopBits=ONESTOPBIT;
	parametry.ByteSize=8;

	SetCommState(hPort,&parametry);

	COMMTIMEOUTS timeouty;

	GetCommTimeouts(hPort,&timeouty);

	timeouty.ReadTotalTimeoutMultiplier=10;
	timeouty.ReadTotalTimeoutConstant=10;

	SetCommTimeouts(hPort,&timeouty);
        HANDLE hVlakno;
	DWORD a;
	hVlakno=CreateThread(NULL,0,cteni,NULL,0,&a);
InText->Text=InText->Text+ InZnak;
tmrCas->Interval=1;
tmrCas->Enabled=true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::KONECClick(TObject *Sender)
{
Application->Terminate();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::InTextChange(TObject *Sender)
{
       // WriteFile(hPort,&znak,1,&zapsano,NULL);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::InTextKeyUp(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
              // WriteFile(hPort,&Key,1,&zapsano,NULL);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::OdesliClick(TObject *Sender)
{
         znak='A';
        WriteFile(hPort,&znak,1,&zapsano,NULL);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::OutTextKeyUp(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
WriteFile(hPort,&Key,1,&zapsano,NULL);        
}
//---------------------------------------------------------------------------
