#include "btnserialthread.h"

BtnSerialThread::BtnSerialThread(QObject *parent) : QThread(parent)
{
    btnSerialTool = nullptr;
    connect(this, &BtnSerialThread::destroySerialTool, this, &BtnSerialThread::onDestroySerialTool, Qt::QueuedConnection);
}

BtnSerialThread::~BtnSerialThread()
{    qDebug() << "SerialToolThread:" ;
    // emit destroySerialTool();
    // // if (isRunning()) {
    // //     qDebug() << "SerialToolT:" ;
    // //     quit();
    // //     wait();
    // // }
    qDebug() << "Current thread in run():" << QThread::currentThread();
    qDebug() << "SerialToolThread object is in thread:" << this->thread();
    qDebug() << "SerialTool object is in thread:" << btnSerialTool->thread();
}

void BtnSerialThread::run()
{
    btnSerialTool = new BtnSerialTool();
    emit serialToolCreated();

    qDebug() << "SerialToolThread object is in thread:" << this->thread();
    qDebug() << "SerialTool object is in thread:" << btnSerialTool->thread();
    qDebug() << "Current thread in run():" << QThread::currentThread();
    // 连接信号

    connect(this, &BtnSerialThread::sendDataRequest, btnSerialTool, &BtnSerialTool::handleSendDataReques, Qt::QueuedConnection);
    connect(btnSerialTool, &BtnSerialTool::dataReceived, this, &BtnSerialThread::handleReceivedData, Qt::QueuedConnection);
    // 启动事件循环
    exec();
}

// 处理接收到的数据
void BtnSerialThread::handleReceivedData(const QByteArray &data)
{
    // 这里可以添加具体的处理逻辑，例如打印接收到的数据
    qDebug() << "Received data:" << data;

    // 可以将接收到的数据通过信号发送出去
    emit dataReceived(data);
}

void BtnSerialThread::onDestroySerialTool()
 {
    qDebug() << "触发信号" ;
     if (btnSerialTool) {
         qDebug() << "delete serialTool";
         delete btnSerialTool;
         btnSerialTool = nullptr;
     }
 }
