int OpenPort(AnsiString NumPort, int Baud) {
DCB ComDcb;
COMMTIMEOUTS TimeOuts;
int ok;
hCOM = INVALID_HANDLE_VALUE;
memset( &ComDcb, '\0', sizeof(DCB) );
NumPort = "\\\\.\\COM" + NumPort;
hCOM = CreateFile(NumPort.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
ok = hCOM != INVALID_HANDLE_VALUE;
// "baud=115200 parity=N data=8 stop=1"
AnsiString Param = "baud=" + IntToStr(Baud) + " parity=N data=8 stop=1";
ok = ok && BuildCommDCB(Param.c_str(), &ComDcb );
ComDcb.fDtrControl = DTR_CONTROL_ENABLE;
ComDcb.fBinary = true;
ok = ok && SetCommState( hCOM, &ComDcb );
ok = ok && GetCommTimeouts( hCOM, &TimeOuts );
TimeOuts.ReadTotalTimeoutMultiplier = 10;
ok = ok && SetCommTimeouts( hCOM, &TimeOuts );
if ( (!ok) && (hCOM != INVALID_HANDLE_VALUE) )
return 0;
if (hCOM == INVALID_HANDLE_VALUE)
return 0;
return 1;
}
//---------------------------------------------------------------------------
// закрытие СОМ- порта
void ClosePort() {
if (hCOM != INVALID_HANDLE_VALUE) {
CloseHandle( hCOM );
}
}
//---------------------------------------------------------------------------
// поиск свободных портов
void FindComPort(TStrings *ComList) {
AnsiString S;
char name[15];
int ok;
DCB ComDcb;
for (int i = 1; i <= 10; i++) {
hCOM = INVALID_HANDLE_VALUE;
memset( &ComDcb, '\0', sizeof(DCB) );
ComDcb.fRtsControl = RTS_CONTROL_ENABLE;
S = (AnsiString)i;
strcpy(name, "\\\\.\\COM");
strcat(name, S.c_str());
hCOM = CreateFile( name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
ok = hCOM != INVALID_HANDLE_VALUE;
if (ok) {
ComList->Add("COM" + S);
CloseHandle( hCOM );
}
}
}
//---------------------------------------------------------------------------
int GetFromPort(unsigned char *buf, int len) {
DWORD rTmp;
if (ReadFile(hCOM, buf, len, &rTmp, NULL ))
return rTmp;
return 0;
}
//---------------------------------------------------------------------------
int Send2Port(unsigned char *SBuf, int sP, bool F) {
DWORD sTmp;
int WFRet;
unsigned char Ch;
if(F) {
while(GetFromPort(&Ch, 1) > 0)
Application->ProcessMessages();
}
WFRet = WriteFile(hCOM, SBuf, sP, &sTmp, NULL );
return WFRet ? sTmp: 0;
}