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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
|
/*
* Author: Manash Kumar Mandal
* Modified Library introduced in Arduino Playground which does not work
* This works perfectly
* LICENSE: MIT
*/
#include "SerialPort.hpp"
SerialPort::SerialPort(const char *portName, int BAUD)
{
this->connected = false;
this->handler = CreateFileA(static_cast<LPCSTR>(portName),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (this->handler == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
std::cerr << "ERROR: Handle was not attached.Reason : " << portName << " not available\n";
}
else
{
std::cerr << "ERROR!!!\n";
}
}
else
{
DCB dcbSerialParameters = {0};
if (!GetCommState(this->handler, &dcbSerialParameters))
{
std::cerr << "Failed to get current serial parameters\n";
}
else
{
dcbSerialParameters.BaudRate = BAUD;
dcbSerialParameters.ByteSize = 8;
dcbSerialParameters.StopBits = ONESTOPBIT;
dcbSerialParameters.Parity = NOPARITY;
dcbSerialParameters.fDtrControl = DTR_CONTROL_ENABLE;
if (!SetCommState(handler, &dcbSerialParameters))
{
std::cout << "ALERT: could not set serial port parameters\n";
}
else
{
this->connected = true;
PurgeComm(this->handler, PURGE_RXCLEAR | PURGE_TXCLEAR);
Sleep(ARDUINO_WAIT_TIME);
}
}
}
}
SerialPort::~SerialPort()
{
if (this->connected)
{
this->connected = false;
CloseHandle(this->handler);
}
}
// Reading bytes from serial port to buffer;
// returns read bytes count, or if error occurs, returns 0
int SerialPort::readSerialPort(const char *buffer, unsigned int buf_size)
{
DWORD bytesRead{};
unsigned int toRead = 0;
ClearCommError(this->handler, &this->errors, &this->status);
if (this->status.cbInQue > 0)
{
if (this->status.cbInQue > buf_size)
{
toRead = buf_size;
}
else
{
toRead = this->status.cbInQue;
}
}
memset((void*) buffer, 0, buf_size);
if (ReadFile(this->handler, (void*) buffer, toRead, &bytesRead, NULL))
{
return bytesRead;
}
return 0;
}
// Sending provided buffer to serial port;
// returns true if succeed, false if not
bool SerialPort::writeSerialPort(const char *buffer, unsigned int buf_size)
{
DWORD bytesSend;
if (!WriteFile(this->handler, (void*) buffer, buf_size, &bytesSend, 0))
{
ClearCommError(this->handler, &this->errors, &this->status);
return false;
}
return true;
}
// Checking if serial port is connected
bool SerialPort::isConnected()
{
if (!ClearCommError(this->handler, &this->errors, &this->status))
{
this->connected = false;
}
return this->connected;
}
void SerialPort::closeSerial()
{
CloseHandle(this->handler);
}
|