1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| #include "SerialPortManager.h"
#include <sstream>
SerialPortManager::~SerialPortManager()
{
ClosePort();
}
bool SerialPortManager::OpenPort( int port )
{
std::stringstream device;
device << "COM";
device << port;
m_hCom = CreateFile ( device.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, 0, NULL );
if ( m_hCom == INVALID_HANDLE_VALUE )
{
//TODO: gestion erreur
return false;
}
DCB dcb;
ZeroMemory(&dcb, sizeof(DCB));
COMMTIMEOUTS timeouts;
dcb.DCBlength = sizeof(DCB);
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.BaudRate = CBR_38400;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
if ( GetCommTimeouts( m_hCom, &timeouts ) == 0 )
{
//TODO: gestion erreur
return false;
}
timeouts.ReadIntervalTimeout = MAXDWORD;
if ( SetCommTimeouts( m_hCom, &timeouts) == 0 )
{
//TODO: gestion erreur
return false;
}
if ( SetCommState( m_hCom, &dcb) == 0 )
{
//TODO: gestion erreur
return false;
}
return true;
}
void SerialPortManager::FlushPort()
{
DWORD nChar = 1;
BYTE cInBuf [8];
while ( nChar >0 )
ReadFile( m_hCom, cInBuf, 1, &nChar, NULL);
}
int SerialPortManager::Read( unsigned char * buffer, int buffLen )
{
int nbRetry = 5;
int nbCharRead = 0;
int countFailed = 0;
DWORD nChar = 0;
while ( countFailed < reintentos )
{
ReadFile( m_hCom, &buffer[nbCharLeido], 1, &nChar, NULL );
if ( nChar > 0 )
{
nbCharRead +=nChar;
}
else
{
countFailed++;
Sleep( 100 );
}
}
return nbCharRead;
}
void SerialPortManager::Write( const unsigned char * buffer, const int buffLen )
{
DWORD nChar = 0;
if ( WriteFile( m_hCom, buffer, buffLen, &nChar, NULL) == 0 )
{
// TODO: gestion erreur
}
}
void SerialPortManager::ClosePort()
{
std::cout << "ClosePort" << std::endl;
CloseHandle( m_hCom );
} |
Partager