//---------------------------------------------------------------------------
#include <vcl.h>
#include <windows.h>
#include <math.h>
#include <dir.h>
#pragma hdrstop
#include "serial.cpp"
#include "komunikace.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "PERFGRAP"
#pragma link "piereg"
#pragma resource "*.dfm"
TfrmHlavni *frmHlavni;

        HANDLE hPort;
        
        unsigned long precteno;
        unsigned long zapsano;
        int dataOut,dataOutOld,smer,Kroky1, Kroky2,stav,Uhel;

        long kanal0,kanal1,kanal2,PocitadloReset;
        int PocitadloZnaku,DrahaUjeta,JedeProgram,PocetRadku,AktRadek,Vyckej;
        char PrijateSlovo[31];
        float baterie;
        unsigned char BezpSouc;
        char rychlost,UjedKroku;

//---------------------------------------------------------------------------
__fastcall TfrmHlavni::TfrmHlavni(TComponent* Owner)
        : TForm(Owner)
{
        Serial=new TSerial(2);
        //nastav na 9600, bez parity, 8 bitu, 1 stop bit
        Serial->BaudRate=br9600;
        Serial->Parity=pNo;
        Serial->StopBits=sb10;
        Serial->ByteSize=bs8;

        Serial->SetupComm(16000,50);
        Serial->ReadIntervalTimeout=0;
        Serial->ReadTotalTimeoutMultiplier=0;
        Serial->ReadTotalTimeoutConstant=10;

        Serial->WriteTotalTimeoutMultiplier=200;
        Serial->WriteTotalTimeoutConstant=100;

        Serial->PurgeInput(); //Vyprazdneni vstupu
        Vyckej=0;
}
//------------------------------------------------------------

__fastcall TfrmHlavni::~TfrmHlavni() //destruktor
{
        //zruseni instance na konci programu
        delete(Serial);
}
//---------------------------------------------------------------------------
   char HexToChar(char Vstup);

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

void __fastcall TfrmHlavni::FormCreate(TObject *Sender)
{
        tmrCti->Interval=5;
        tmrCti->Enabled=true;
        tmrVyckej->Interval=2500;
        tmrVyckej->Enabled=false;
        tmrPockej->Enabled=false;
        tmrPockej->Interval=1500;
        
        PocitadloZnaku=0;
        memoTraj->Clear();
        rychlost = 130;
        DrahaUjeta=0;
        JedeProgram=0;
        AktRadek=0;
        rbgRychlost->ItemIndex=2;
        rgSmer->ItemIndex=0;
        Uhel=0;
        

        
}

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

void __fastcall TfrmHlavni::Memo1KeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
        Serial->WriteChar(Key);
}
//---------------------------------------------------------------------------

void __fastcall TfrmHlavni::NulujPocitadla(void)
{
   Serial->WriteChar('#');
   Serial->WriteChar('X');
   Serial->WriteChar('X');

   Serial->WriteChar('*');
}
//---------------------------------------------------------------------------

void __fastcall TfrmHlavni::OdesliData(void)
{
//rychlost=scrRychlost->Position;
  dataOut=smer+rychlost;
  if(dataOut!=dataOutOld)
  {
   Serial->WriteChar('#');
   Serial->WriteChar(smer);
   Serial->WriteChar(smer);

   //Serial->WriteChar(rychlost);

   Serial->WriteChar('*');
   dataOutOld=dataOut;

   if (smer !=0)
   {
     memoTraj->Lines->Add(smer);
   }
  }

}

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

 void __fastcall TfrmHlavni::OdesliData2(void)
{
//rychlost=scrRychlost->Position;
  dataOut=smer+UjedKroku;
  if(dataOut!=dataOutOld)
  {
   Serial->WriteChar('@');
   Serial->WriteChar(rychlost);
   Serial->WriteChar(rychlost);

   //Serial->WriteChar(UjedKroku);
   
   Serial->WriteChar('*');
   dataOutOld=dataOut;
  }

}
//---------------------------------------------------------------------------
 void __fastcall TfrmHlavni::OdesliData3(void)
 {
  if( scrDraha->Position <10000)
  {
  edtDraha->Text="0" + IntToStr(scrDraha->Position);
  }
  if( scrDraha->Position <1000)
  {
  edtDraha->Text="00" + IntToStr(scrDraha->Position);
  }
  if( scrDraha->Position <100)
  {
  edtDraha->Text="000" + IntToStr(scrDraha->Position);
  }
  if( scrDraha->Position <10)
  {
  edtDraha->Text="0000" + IntToStr(scrDraha->Position);
  }

  char Zabezpeceni;

  Zabezpeceni=smer+StrToInt(edtDraha->Text[1])+StrToInt(edtDraha->Text[2])+StrToInt(edtDraha->Text[3])+StrToInt(edtDraha->Text[4])+StrToInt(edtDraha->Text[5]);
  lblZabezpeceni->Caption=IntToStr(Zabezpeceni);
  if( Zabezpeceni <10)
  {
    lblZabezpeceni->Caption="0" + IntToStr(Zabezpeceni);
  }

  Serial->WriteChar('$');
  Serial->WriteChar(smer);
  Serial->WriteString(edtDraha->Text);
  Serial->WriteChar(lblZabezpeceni->Caption[2]);
  Serial->WriteChar('*');
  //aaa
 }

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

 void __fastcall TfrmHlavni::ZobrazStavCidel(void)
 {
   Pie->Angles->StartAngle=360-( (Uhel*1.411)+5-90);
   Pie->Angles->EndAngle =360-( (Uhel*1.411)-5-90);

   chbCidlo1->Checked=PrijateSlovo[19]-48;
   chbCidlo2->Checked=PrijateSlovo[20]-48;
   chbCidlo3->Checked=PrijateSlovo[21]-48;
   chbCidlo4->Checked=PrijateSlovo[22]-48;
   chbCidlo5->Checked=PrijateSlovo[23]-48;

   if ((chbCidlo1->Checked == 1) && (chbCidlo2->Checked == 1) && (chbCidlo3->Checked == 1) && (chbCidlo4->Checked == 1) && (chbCidlo5->Checked == 1) )
   {
     Cidla->Font->Color= clWindowText;
   }
   else
   {
     Cidla->Font->Color= clRed;
   }


 }

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

void __fastcall TfrmHlavni::tmrCtiTimer(TObject *Sender)
{
lblPocetRadku->Caption=memoTraj->Lines->Count;
lblAktRadek->Caption=AktRadek;

if(PocetRadku == AktRadek)
{
JedeProgram=0;
}

if((JedeProgram == 1)&&(stav==0) )
{
 tmrVyckej->Enabled=true;
        if(Vyckej==1)
        {
        smer=StrToInt(memoTraj->Lines->Strings[AktRadek]);
        scrDraha->Position=StrToInt(memoTraj->Lines->Strings[AktRadek+1]);
        AktRadek=AktRadek+2;
        OdesliData3();
        stav=1;
        Vyckej=0;
        //DrahaUjeta=0;
        }


}


if (stav==0)
{
  lblDrahaUjeta->Caption="Čeká na zadání";

}
else
{
  lblDrahaUjeta->Caption="Provádím";

}

unsigned char c,d;
char s[40];
char k1[6];
float OdberProudu;

        if (Serial->ReadChar(&c)) //je prijat znak?
        {d=c;

               if((c == 35) || (c == 42) || ((c >= 48) && (c <= 57)) || ((c >= 65) && (c <= 70)) || (c == 45) || (c=='O') || (c=='K')) //je prijat znak  # * nebo 0~9 nebo A az F nebo znak -? O K
                {
                 PocitadloReset++;
                }
                else
                {
                 Serial->PurgeInput();
                 PocitadloZnaku=0;
                }

                if(c == 35)
                {
                 PocitadloZnaku= 0;
                 PrijateSlovo[0]=c;
                }

                if ((c >= 48) && (c <= 57) || (c == 42) || ((c >= 65) && (c <= 70)) || (c == 45) || (c == 'O') || (c == 'K'))
                {
                 PocitadloZnaku++;
                 PrijateSlovo[PocitadloZnaku]=c;
                }
            /*
                lbl0->Caption=PrijateSlovo[0];
                lbl1->Caption=PrijateSlovo[1];
                lbl2->Caption=PrijateSlovo[2];

                if ((PocitadloZnaku ==2) && (PrijateSlovo[1]== 79) && (PrijateSlovo[2]==75))
                {  lblDrahaUjeta->Caption="OK...";
                Label10->Caption="AAA";
                }
        */

                if (PocitadloZnaku == 31) //Prislo cele slovo
                {

                 //lblStatus->Caption=IntToStr(status);

                 baterie= (PrijateSlovo[1]-48)*10+(PrijateSlovo[2]-48)+(PrijateSlovo[3]-48)*0.1;


                 Kroky1=StrToInt(PrijateSlovo[9])+StrToInt(PrijateSlovo[8])*10+StrToInt(PrijateSlovo[7])*100+StrToInt(PrijateSlovo[6])*1000+StrToInt(PrijateSlovo[5])*10000;
                 Kroky2=StrToInt(PrijateSlovo[15])+StrToInt(PrijateSlovo[14])*10+StrToInt(PrijateSlovo[13])*100+StrToInt(PrijateSlovo[12])*1000+StrToInt(PrijateSlovo[11])*10000;

                 if(PrijateSlovo[4]==45) //Kroky jsou v zapornych hodnotach
                 {
                   Kroky1= 0-Kroky1;
                 }


                 if(PrijateSlovo[10]==45) //Kroky jsou v zapornych hodnotach
                 {
                   Kroky2= 0-Kroky2;
                 }


                  OdberProudu=(PrijateSlovo[16]-48)*10+(PrijateSlovo[17]-48)+(PrijateSlovo[18]-48)*0.1;


                  ZobrazStavCidel();

                  stav=PrijateSlovo[24]-48;


                  Uhel=(PrijateSlovo[25]-48)*100+(PrijateSlovo[26]-48)*10+(PrijateSlovo[27]-48);



                  BezpSouc=baterie*10+OdberProudu+Kroky1+Kroky2+PrijateSlovo[19]-48+PrijateSlovo[20]-48+PrijateSlovo[21]-48+PrijateSlovo[22]-48+PrijateSlovo[23]-48+stav+Uhel+1;
                  lblSouc->Caption=IntToStr(BezpSouc);

                  unsigned char BS;
                  BS=(PrijateSlovo[28]-48)*100+(PrijateSlovo[29]-48)*10+PrijateSlovo[30]-48;
                  lblBS->Caption=IntToStr(BS);


                  if(BezpSouc==BS);
                  {
                    lblKroky1->Caption=IntToStr(Kroky1);
                    lblKroky2->Caption=IntToStr(Kroky2);
                    lblUhel->Caption=FloatToStrF(Uhel*1.411,2,5,1)+"°";
                    lblStav->Caption=IntToStr(stav);
                    lblBaterie->Caption=FloatToStrF(baterie,5,1,5);
                    lblI1->Caption=FloatToStrF(OdberProudu,6,1,5);
                  }

                 }
        }

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

void __fastcall TfrmHlavni::Edit1KeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{


 switch (Key)
  {
             case (38):
                lblSmer->Caption="VPRED";
                smer=1;
                break;
             case (40):
                lblSmer->Caption="VZAD";
                smer=2;
                break;
             case (37):
                lblSmer->Caption="VLEVO";
                smer=3;
                break;
             case (39):
                lblSmer->Caption="VPRAVO";
                smer=4;
                break;
             default :
                lblSmer->Caption="STOP";
                smer=0;
                break;


  }
 OdesliData();
}
//---------------------------------------------------------------------------

void __fastcall TfrmHlavni::tmrFocusTimer(TObject *Sender)
{
        edtRizeni->SetFocus();        
}
//---------------------------------------------------------------------------

void __fastcall TfrmHlavni::edtRizeniKeyUp(TObject *Sender, WORD &Key,
      TShiftState Shift)
{

        lblSmer->Caption="STOP";
        smer=0;

        OdesliData();
        tmrPockej->Enabled=true;

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

void __fastcall TfrmHlavni::KonecClick(TObject *Sender)
{
        Application->Terminate();        
}
//---------------------------------------------------------------------------

void __fastcall TfrmHlavni::OtevriClick(TObject *Sender)
{
  int FileHandle, FileLength;
  char *FileBuffer;
  if (dlgOpen->Execute());
  {
    try
    {
      FileHandle = FileOpen(dlgOpen->FileName, fmOpenRead);
      FileLength = FileSeek(FileHandle, 0, 2);
      FileSeek(FileHandle, 0, 0);
      FileBuffer = new char[FileLength + 1];
      FileRead(FileHandle, FileBuffer, FileLength);
      memoTraj->Clear();
      memoTraj->Text = memoTraj->Text + FileBuffer;

      FileClose(FileHandle);
      delete [] FileBuffer;

    }
    catch(...)
    {
    }

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

void __fastcall TfrmHlavni::UlozClick(TObject *Sender)
{
int FileHandle, FileLength;
  char *FileBuffer;

  if (dlgSave->Execute());
  {
    try
    {

      if( FileExists(dlgSave->FileName))
      {
        FileHandle = FileOpen(dlgSave->FileName, fmOpenWrite);
      }
      else
      {
        FileHandle = FileCreate(dlgSave->FileName);
        //FileHandle = FileOpen(dlgSave->FileName, fmOpenWrite);
      }
      FileLength = memoTraj->Text.Length();
      FileSeek(FileHandle, 0, 0);
      FileBuffer = memoTraj->Text.c_str();
      FileWrite(FileHandle, FileBuffer, FileLength);
      
      FileClose(FileHandle);
      delete [] FileBuffer;

    }
    catch(...)
    {
    }

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

void __fastcall TfrmHlavni::Nov1Click(TObject *Sender)
{
        memoTraj->Clear();
}
//---------------------------------------------------------------------------

void __fastcall TfrmHlavni::btnProgClick(TObject *Sender)
{
        UjedKroku=scrDraha->Position;
        smer=rgSmer->ItemIndex+1;
        OdesliData3();
        memoTraj->Lines->Add(smer);
        memoTraj->Lines->Add(scrDraha->Position);
        lblDrahaUjeta->Caption="Provadím...";


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

void __fastcall TfrmHlavni::btnJedProgramClick(TObject *Sender)
{
        PocetRadku=memoTraj->Lines->Count;
        JedeProgram=1;
        Vyckej =0;
        AktRadek=0;
        //DrahaUjeta=0;

        smer=StrToInt(memoTraj->Lines->Strings[0]);

        scrDraha->Position=StrToInt(memoTraj->Lines->Strings[1]);
        AktRadek=AktRadek+2;
        OdesliData3();


        //lblDrahaUjeta->Caption="Provadím...";
        
}
//---------------------------------------------------------------------------

void __fastcall TfrmHlavni::scrRychlostExit(TObject *Sender)
{
   // konec tahani scrollbaru
   OdesliData2();
}
//---------------------------------------------------------------------------

void __fastcall TfrmHlavni::tmrPockejTimer(TObject *Sender)
{
        tmrPockej->Enabled=false;
    memoTraj->Lines->Add((abs(Kroky1)+abs(Kroky2))/2);
    NulujPocitadla();

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

void __fastcall TfrmHlavni::scrDrahaChange(TObject *Sender)
{
edtDraha->Text=IntToStr(scrDraha->Position);        
}
//---------------------------------------------------------------------------

void __fastcall TfrmHlavni::tmrVyckejTimer(TObject *Sender)
{
        tmrVyckej->Enabled=false;
        Vyckej=1;
}
//---------------------------------------------------------------------------
 
void __fastcall TfrmHlavni::rbgRychlostClick(TObject *Sender)
{
        rychlost= rbgRychlost->ItemIndex+5;
        OdesliData2();
}
//---------------------------------------------------------------------------






