#pragma once
#include <QSerialPort>
#include <QObject>
class QThread;
class LkSerialPort : public QObject
{
Q_OBJECT
public:
LkSerialPort(QObject *parent = 0);
~LkSerialPort();
virtual void init(QString portName, int baudRate);
virtual void parse(QByteArray data) = 0;
void writeData(QByteArray data);
void setRecLength(int len);
public slots:
virtual void onReceive() = 0;
signals:
void serialChanged(QByteArray);
protected:
QSerialPort *mPort;
QByteArray mRecBytes;
int mRecLen;
private:
QThread *mThread;
};
#include "LkSerialPort.h"
#include <QThread>
#include <QMessageBox>
LkSerialPort::LkSerialPort(QObject *parent)
: QObject(parent)
{
}
LkSerialPort::~LkSerialPort()
{
mPort->close();
mPort->deleteLater();
mThread->quit();
mThread->wait();
mThread->deleteLater();
}
void LkSerialPort::init(QString portName, int baudRate)
{
mThread = new QThread();
mPort = new QSerialPort();
mPort->setPortName(portName);
mPort->setBaudRate(baudRate);
mPort->setParity(QSerialPort::NoParity);
if (!mPort->open(QIODevice::ReadWrite))
{
QMessageBox msg;
msg.setText(QString::fromLocal8Bit("串口打开失败!"));
msg.exec();
}
this->moveToThread(mThread);
mPort->moveToThread(mThread);
mThread->start();
mRecLen = 0;
}
void LkSerialPort::writeData(QByteArray data)
{
mPort->write(data.data());
}
void LkSerialPort::setRecLength(int len)
{
mRecLen = len;
}
void LkSerialPort::onReceive()
{
}