如果您不需要低能耗并且可以打扰您的用户使用 Windows 系统设置对话框配对设备,那么我建议为不使用 QtBluetooth 的 Windows 编写包装器代码。IE
#include <Windows.h>
class win_con {
....
HANDLE hcon;
COMMTIMEOUTS *timeouts;
// i.e. com_port = L"\\\\.\\COM1";
void open_com(std::wstring com_port, int read_timeout, int write_timeout)
{
hcom = CreateFile(com_port.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr,
OPEN_EXISTING, 0, nullptr);
if (hcom == INVALID_HANDLE_VALUE) ...
timeouts = new COMMTIMEOUTS();
memset(timeouts, 0, sizeof(COMMTIMEOUTS));
timeouts->ReadTotalTimeoutConstant = read_timeout;
timeouts->WriteTotalTimeoutConstant = write_timeout;
if (!SetCommTimeouts(hcom, timeouts)) ...
}
void write_data(QString data)
{
std::string stddata = data.toStdString();
DWORD numwritten = 0;
if (!WriteFile(hcom, stddata.c_str(),
static_cast<DWORD>(stddata.length()), &numwritten, nullptr)) {
...
}
}
QString read_data(int len)
{
#define BUFFER_SIZE 256
char buffer[BUFFER_SIZE];
DWORD data_read = 0;
if (BUFFER_SIZE < len) ....
for (int i = 0; i < BUFFER_SIZE; i++)
buffer[i] = 0;
ReadFile(hcom, &buffer, len, &data_read, nullptr);
if (read == 0) ...
if (read < len) ...
return QString(buffer);
}
}