#include "QSerialPortUtil.h"

#include <iostream>
#include <QTimer>
#include <QDateTime>
#include "SettingConfig.h"

QSerialPortUtil::QSerialPortUtil(QObject *parent) : QObject(parent)
{
    // 其他默认配置
    serial.setDataBits(QSerialPort::Data8);
    serial.setParity(QSerialPort::NoParity);
    serial.setStopBits(QSerialPort::OneStop);
    serial.setFlowControl(QSerialPort::NoFlowControl);
}

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

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

    if (SettingConfig::getInstance().WORK_TYPE == "mock")
    {
        // mock data received per second
        QTimer * timer = new QTimer(this);
        connect(timer, &QTimer::timeout,
                this, &QSerialPortUtil::mockReceivData);
        timer->start(1000);
    } else
    {
        std::cout << portName.toStdString() << QString(" - %1").arg(baudRate).toStdString();
        if (open == true)
        {
            // 绑定信号与槽
            connect(&serial, &QSerialPort::readyRead,
                    this, &QSerialPortUtil::readData);
        }

        std::cout << " - " << open << std::endl;
    }
}

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

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

    emit dataRecieved(buffer);
}

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

void QSerialPortUtil::mockReceivData()
{
    QDateTime now = QDateTime::currentDateTime();

    QByteArray buffer;

    buffer.append("$XHTSXHPT0001220101031329276|1000000001111111101|+0.000000000000|-0.331044361095|+0.313295936193|+0.435712449844|+0.497012420153|+0.465550566276|+0.499386223873|-0.331044316306|+0.000000000000|+0.000000000000|+0.000000000000|+0.000000000000|+0.000000000000|+0.000000000000|+0.000000000000|+0.000000000000Z").append("\r\n");

    emit dataRecieved(buffer);
}
