#include "serialthreadhandle.h"
#include "globalinfo.h"

SerialThreadHandle::SerialThreadHandle(QObject *parent) : QObject(parent),th(nullptr)/*,port(nullptr)*/
{

}


void SerialThreadHandle::start()
{
    if(th == nullptr){
        th = new QThread(this);
        connect(th,&QThread::started,this,&SerialThreadHandle::updateConfig);
        port = new RtuPort(this);
        auto config = GlobalInfo::this_()->config();
        connect(config,&ConfigInfo::configUpdate,this,&SerialThreadHandle::updateConfig,Qt::QueuedConnection);
        this->moveToThread(th);
        th->start();
    }
}

void SerialThreadHandle::updateConfig()
{
    if(port == nullptr) return;
    auto config = GlobalInfo::this_()->config();
    auto old = port->handle();
    auto handle = SerialBaseHandle::getHandler(config->portType);// todo:
    port->start(config->portName,config->portBaudRate.toInt(),handle);
    if(old) delete old;
}
