我正在尝试使用QSerialPort类通过串行端口发送一些数据。每次从同一父类发送数据效果很好。但是,当我尝试使用另一个线程QSerialPort发送数据时,它没有。我使用串口监视器来观察数据,但它没有显示任何内容。 代码如下所示:
#include <QSerialPort>
#include <QObject>
#include <QDebug>
#include <QCoreApplication>
#include <thread>
#include <mutex>
#include <list>
#include <memory>
class Message {
public:
bool isSent;
bool isProcessed;
int data;
Message(int d) :
data(d),
isSent(false),
isProcessed(false) {
}
};
class SerialClass : public QObject {
Q_OBJECT
public:
SerialClass(unsigned short portNumber, unsigned int baudrate, QObject *parent = 0) :
_portNumber(portNumber),
_baudrate(baudrate),
_serialPort(new QSerialPort(this)),
_messages(),
_writeThread(nullptr),
QObject(parent) {
_serialPort->setPortName(QString("COM%1").arg(_portNumber));
_serialPort->setBaudRate(baudrate);
_serialPort->setDataBits(QSerialPort::DataBits::Data8);
_serialPort->setParity(QSerialPort::Parity::NoParity);
_serialPort->setStopBits(QSerialPort::StopBits::OneStop);
}
void start() {
if (!_serialPort->open(QIODevice::ReadWrite)) {
qDebug() << "Couldn't open serial port";
return;
}
auto *m = &_messages;
auto *p = &_enableProcessing;
auto *port = _serialPort.get();
auto *mutex = &_mutex;
_serialPort->write(QString("Hello\r\n").toLocal8Bit());
_writeThread = std::make_unique<std::thread>([m, p, port, mutex]() {
qDebug() << "Work thread started";
while (*p) {
std::this_thread::sleep_for(std::chrono::milliseconds(15));
auto inactiveMessage = std::find_if(m->begin(), m->end(), [](Message &item) {
return !item.isSent;
});
if (inactiveMessage != m->end()) {
mutex->lock();
qDebug() << "Written" << port->write(QString("data %1\r\n").arg(inactiveMessage->data).toLocal8Bit());
inactiveMessage->isSent = true;
mutex->unlock();
}
}
qDebug() << "Work thread stopped";
});
}
void wait() {
if (!_writeThread) {
return;
}
_writeThread->join();
}
void addMessage(Message& msg) {
_mutex.lock();
_messages.push_back(msg);
_mutex.unlock();
}
private:
unsigned short _portNumber;
unsigned int _baudrate;
std::unique_ptr<QSerialPort> _serialPort;
std::unique_ptr<std::thread> _writeThread;
std::list<Message> _messages;
bool _enableProcessing;
std::mutex _mutex;
};
int main(int argc, char ** argv) {
QCoreApplication application(argc, argv);
SerialClass serialProcessor(2, 9600, &application);
serialProcessor.addMessage(Message(228));
serialProcessor.addMessage(Message(929));
serialProcessor.addMessage(Message(221424));
serialProcessor.start();
return application.exec();
}
#include "main.moc"
这是否意味着QSerialPort类无法从另一个线程传输数据? (不是QSerialPort线程)
答案 0 :(得分:0)
QSerialPort
可以在任何线程中使用QThread
的示例:https://stackoverflow.com/a/35673612/4149835