2 #include "SerialConnection.h"
10 hCom = CreateFile(_comstring.c_str(),
11 GENERIC_READ | GENERIC_WRITE,
18 if (
hCom == INVALID_HANDLE_VALUE)
19 throw std::exception(
"Initializing serial connection failed");
23 SecureZeroMemory(&dcb,
sizeof(DCB));
24 dcb.DCBlength =
sizeof(DCB);
28 if ( !GetCommState(
hCom, &dcb) )
29 throw std::exception(
"GetCommState of serial connection failed");
34 dcb.ByteSize = _bytesize;
36 dcb.StopBits = _stopbits;
38 if ( !SetCommState(
hCom, &dcb) )
39 throw std::exception(
"SetCommState of serial connection failed");
42 if ( !GetCommState(
hCom, &dcb) )
43 throw std::exception(
"GetCommState of serial connection failed");
45 DBOUT(L
"SerialConnection::Initialize configured: " << dcb.BaudRate << L
"baud " << dcb.ByteSize << L
"byte size" << dcb.Parity << L
"parity " << dcb.StopBits << L
"stop bits");
55 if ( !WriteFile(
hCom, _string.data(),
static_cast<DWORD
>(_string.length()), &written, NULL) )
56 throw std::exception(
"SerialConnection::Send failed");
62 if ( !ClearCommError(
hCom, &errors, &comstat) )
63 throw std::exception(
"SerialConnection::Receive getting buffer info failed");
65 if ( comstat.cbInQue < _toread ) {
66 std::this_thread::sleep_for(std::chrono::milliseconds(_waitfor));
67 if ( !ClearCommError(
hCom, &errors, &comstat) )
68 throw std::exception(
"SerialConnection::Receive getting buffer info failed");
71 if ( comstat.cbInQue < _toread )
72 throw std::exception(
"SerialConnection::Receive not all requested bytes in buffer");
75 std::vector<BYTE> read(_toread, 0);
77 if ( !ReadFile(
hCom, (
void*)read.data(), comstat.cbInQue, &readbytes, NULL) )
78 throw std::exception(
"SerialConnection::Receive read from buffer failed");
void Send(const std::string &_string)
send command string over connection
HANDLE hCom
the connection handle
std::vector< BYTE > Receive(const uint32_t &_toread, const uint32_t &_waitfor=100)
Receive bytes from connection, does only wait 100ms for the bytes to be ready, otherwise throws...
This is the include file for standard system include files, or project specific include files that ar...
SerialConnection(const std::wstring &_comstring, const DWORD &_baud=CBR_9600, const BYTE &_bytesize=8, const BYTE &_parity=NOPARITY, const BYTE &_stopbits=ONESTOPBIT)
Initializes connection.
#define DBOUT(s)
A debug output to the debug console.
~SerialConnection(void)
Closes connection.
Various helper functions and classes for Scope.