gpt4 book ai didi

c++ - 使用 Linux 伪终端测试 QSerialPort

转载 作者:太空狗 更新时间:2023-10-29 12:23:42 24 4
gpt4 key购买 nike

我想使用带有伪终端的 Qt 串行端口测试应用程序。根据我实现的手册页:

// open master
QSerialPort master("/dev/ptmx");
master.open(QSerialPort::ReadWrite);
int master_fd = master.handle();

// get device name of slave pseudoterminal
constexpr size_t PTSNAME_BUFFER_LENGTH = 128;
char ptsname_buffer[PTSNAME_BUFFER_LENGTH];
if (ptsname_r(master_fd, ptsname_buffer, PTSNAME_BUFFER_LENGTH) != 0)
return 0;

// grant access to the slave
if (grantpt(master_fd) != 0)
return 0;

// unlock the slave
if (unlockpt(master_fd) != 0)
return 0;

// open slave
std::cout << "Slave pseudoterminal: " << ptsname_buffer << std::endl;
QSerialPort slave(ptsname_buffer);
slave.open(QSerialPort::ReadWrite);

// test communication
master.write("Hello World");
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "Received: " << slave.readAll().toStdString() << std::endl;

创建从属设备似乎可行(在我的例子中,它是在 /dev/pts/2 中创建的)。然而,slave.readAll() 命令总是返回一个空字符串。

是否可以使用伪终端测试 QSerialPort?

最佳答案

Qt 在事件循环中执行,因此您需要等待通信被处理,在 Qt 中您应该使用信号异步工作:

main.cpp

#include <QCoreApplication>
#include <QSerialPort>

#include <iostream>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QSerialPort master("/dev/ptmx");
if(!master.open(QSerialPort::ReadWrite))
std::cout<<"The master port was not opened";

int master_fd = master.handle();

// get device name of slave pseudoterminal
constexpr size_t PTSNAME_BUFFER_LENGTH = 128;
char ptsname_buffer[PTSNAME_BUFFER_LENGTH];
if (ptsname_r(master_fd, ptsname_buffer, PTSNAME_BUFFER_LENGTH) != 0)
return -1;

// grant access to the slave
if (grantpt(master_fd) != 0)
return -1;

// unlock the slave
if (unlockpt(master_fd) != 0)
return -1;

// open slave
std::cout << "Slave pseudoterminal: " << ptsname_buffer << std::endl;
QSerialPort slave(ptsname_buffer);
if(!slave.open(QSerialPort::ReadWrite))
std::cout<<"The slave port was not opened";

QObject::connect(&slave, &QSerialPort::readyRead, [&](){
std::cout << "Received: " << slave.readAll().toStdString() << std::endl;
a.quit();
});
// test communication
master.write("Hello World");
return a.exec();
}

输出:

Slave pseudoterminal: /dev/pts/3
Received: Hello World

注意:不要使用 std::this_thread::sleep_for因为它是阻止事件循环执行的阻塞任务。

关于c++ - 使用 Linux 伪终端测试 QSerialPort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49544318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com