3 实现
3.5 KermitFileRecver
该模块实现了Kermit异步接收文件功能。
3.5.1 KermitFileRecver定义
class QSerialPort;
class KermitFileRecver : public QObject
{Q_OBJECT
public:explicit KermitFileRecver(QSerialPort *serial, QObject *parent = nullptr);~KermitFileRecver();
signals:void start_recv(QString const& fileName);void cancel_recv();void gotFileSize(quint64 filesize);void progressInfo(quint32 blockNumber, quint64 bytesOfSend);void finished();void error(QString const& e);
public:void start(QString const& fileName);void stop();void cancel();
private:QThread workerThread;
};
公共接口:
- start 开始接收文件
- stop 停止传输文件
- cancel 中断传输文件
信号:
- gotFileSize 文件大小信号
- progressInfo 传输进度信号
- error 出错信号
- finished 传输结束信号
- start_recv 开始接收文件信号
- cancel_recv 中断传输文件信号
3.5.2 KermitFileRecver实现
3.5.2.1 构造函数/析构函数
KermitFileRecver::KermitFileRecver(QSerialPort *serial, QObject *parent): QObject(parent)
{KermitRecvFile* worker = new KermitRecvFile(serial);serial->moveToThread(&workerThread);worker->moveToThread(&workerThread);connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);connect(this, &KermitFileRecver::start_recv, worker, &KermitRecvFile::start);connect(this, &KermitFileRecver::cancel_recv, worker, &KermitRecvFile::cancel);connect(worker, &KermitRecvFile::gotFileSize, this, &KermitFileRecver::gotFileSize);connect(worker, &KermitRecvFile::progressInfo, this, &KermitFileRecver::progressInfo);connect(worker, &KermitRecvFile::finished, this, &KermitFileRecver::finished);connect(worker, &KermitRecvFile::error, this, &KermitFileRecver::error);workerThread.start();
}KermitFileRecver::~KermitFileRecver()
{workerThread.quit();workerThread.wait();
}
函数说明:
- 构造函数
- 将serial和worker移动到workerThread线程
- 连接信号和槽函数
- 启动线程
- 析构函数
- 退出线程
- 等待线程退出
3.5.2.2 start/stop/cancel
void KermitFileRecver::start(QString const& fileName)
{emit start_recv(fileName);
}void KermitFileRecver::stop()
{worker->stop();
}void KermitFileRecver::cancel()
{emit cancel_recv();
}
函数说明:
- start 发送信号start_send开始文件传输
- stop 调用work函数stop停止操作
- cancel 发送信号cancel_send取消文件传输操作
Qt实现Kermit协议(五)