#include "rtuport.h"

RtuPort::RtuPort(QObject *p) : QObject(p)
{
    m_serialPort = new QSerialPort(this);
    stard = false;
    _handle = nullptr;
    //设置参数

   connect(m_serialPort,SIGNAL(readyRead()),this,SLOT(receiveInfo()));

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&RtuPort::portWrite);
}

void RtuPort::start(QString & name, int band, SerialBaseHandle * handle)
{
    if(m_serialPort->isOpen()) m_serialPort->close();
     m_serialPort->setPortName(name);
     m_serialPort->setBaudRate(band);
    _handle = handle;
    m_serialPort->open(QIODevice::ReadWrite);
    if(!timer->isActive())
        timer->start(200);
    stard = true;
}

void RtuPort::portWrite()
{
    if(!m_serialPort->isOpen()){
        m_serialPort->open(QIODevice::ReadWrite);
        return;
    }
    if(_handle && _handle->needSend()){
    m_serialPort->write(_handle->sendData());
    }
}

void RtuPort::receiveInfo()
{
    QByteArray info = m_serialPort->readAll();
    if(_handle)
      _handle->handle(info);

}


