本文介绍了使用Linux伪终端测试QSerialPort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to test an application using Qt serial ports with a pseudoterminal. According to the man pages I implemented:

// 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()命令始终返回空字符串.

Creating the slave device seems to work (in my case it is created at /dev/pts/2). However, the slave.readAll() command always returns an empty string.

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

Is it possible to test the QSerialPort with a pseudoterminal?

推荐答案

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

Qt is executed inside an event loop so you need to wait for the communication to be processed, in Qt you should work asynchronously using the signals:

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

这篇关于使用Linux伪终端测试QSerialPort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:21