-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserialport.cpp
More file actions
90 lines (71 loc) · 2.63 KB
/
serialport.cpp
File metadata and controls
90 lines (71 loc) · 2.63 KB
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
#include "serialport.h"
std::vector<QString> getComPorts(){
std::vector<QString> ports = {};
wchar_t lpTargetPath[5000]; // to store the path of the COM ports
for(int i = 0; i < 3; i++){
char com_c_str[32];
sprintf(com_c_str, "\\Device\\USBPDO-%d", i);
printf("%s\r\n", com_c_str);
DWORD test = QueryDosDevice((wchar_t*)com_c_str, lpTargetPath, 5000);
if(test != 0){
printf("%s\n", com_c_str);
printf("%s\n", "We got one!!");
ports.push_back(QString(com_c_str));
}
}
return ports;
}
/**
* @brief SerialPort::SerialPort will open and initialize the com port
* also see https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-opencommport
* @param parent
* @param port the string name of the COM port
*/
SerialPort::SerialPort(QObject *parent, QString port) : QObject(parent), comPort(port)
{
std::string comStr = comPort.toStdString();
const wchar_t* comWideStr = std::wstring(comStr.begin(), comStr.end()).c_str();
hSerial = CreateFile(comWideStr,
GENERIC_READ | GENERIC_WRITE,
0,
nullptr,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
nullptr);
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if(!GetCommState(hSerial, &dcbSerialParams)){
// uh oh
}
dcbSerialParams.BaudRate = CBR_115200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if(!SetCommState(hSerial, &dcbSerialParams)){
// error setting serial port state
}
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier= 10;
if(!SetCommTimeouts(hSerial, &timeouts)){
// error occurred, uh oh
}
}
bool SerialPort::writeData(uint8_t* data, int writeSize){
bool retval;
DWORD dwBytesWritten = 0;
retval = WriteFile(this->hSerial, data, (unsigned long)writeSize, &dwBytesWritten, nullptr);
return retval && dwBytesWritten == (unsigned long)writeSize;
}
bool SerialPort::readData(uint8_t* data, int readSize){
bool retval;
DWORD dwBytesRead = 0;
retval = ReadFile(this->hSerial, data, (unsigned long)readSize, &dwBytesRead, nullptr);
return retval && dwBytesRead == (unsigned long)readSize;
}
void SerialPort::close(){
CloseHandle(this->hSerial);
}