#include "QSerialPortUtil.h"

#include <iostream>
#include <QTimer>
#include <QDateTime>
#include "common/utils/QByteUtil.h"
#include "common/utils/SettingConfig.h"

QSerialPortUtil::QSerialPortUtil(QObject *parent) : QObject(parent)
{
    // 其他默认配置
    serial.setDataBits(QSerialPort::Data8);
    serial.setStopBits(QSerialPort::OneStop);
    serial.setFlowControl(QSerialPort::NoFlowControl);
    switch (SettingConfig::getInstance().PARITY)
    {
    case 2:
        serial.setParity(QSerialPort::EvenParity);
        break;

    case 3:
        serial.setParity(QSerialPort::OddParity);
        break;

    default:
        serial.setParity(QSerialPort::NoParity);
        break;
    }

    // 绑定信号与槽
    connect(&serial, &QSerialPort::readyRead,
            this, &QSerialPortUtil::readData);
}

void QSerialPortUtil::openSerialPort(QString portName, int baudRate)
{
    serial.setPortName(portName); // 串口名
    serial.setBaudRate(baudRate); // 波特率

    open = serial.open(QIODevice::ReadWrite);

    std::cout << portName.toStdString() << " " << QString::number(baudRate).toStdString() << " " << open << std::endl;

//    if (open == true)
//    {

//    }

}

void QSerialPortUtil::sendData(QByteArray data)
{
    std::cout << "[send]" << data.toStdString() << std::endl;
    if (this->open == true)
    {
        serial.write(data);
    }
}

void QSerialPortUtil::readData()
{
    QByteArray buffer = serial.readAll();
    emit dataRecieved(buffer);
}

bool QSerialPortUtil::isOpen()
{
    return this->open;
}
