使用Linux伪终端测试QSerialPort

时间:2018-03-28 21:16:27

标签: c++ linux qt serial-port virtual-serial-port

我想使用带有伪终结的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?

1 个答案:

答案 0 :(得分:1)

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,因为它是阻止事件循环执行的阻塞任务。