#include "QSerialPortUtil.h"

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

double base[9] = {-0.331044361095, +0.313295936193, +0.435712449844, +0.497012420153, +0.465550566276, +0.499386223873, -0.331044316306, +0.499386223873, +0.499386223873};

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); // 波特率

    if (SettingConfig::getInstance().WORK_TYPE == "mock")
    {
        qDebug() << portName << QString(" - %1 - mock").arg(baudRate);

        // mock data received per second
        QTimer * timer = new QTimer(this);
        connect(timer, &QTimer::timeout,
                this, &QSerialPortUtil::mockReceivData);
        timer->start(1000);
    } else
    {
        open = serial.open(QIODevice::ReadWrite);
        if (open == true)
        {
            // 绑定信号与槽
            connect(&serial, &QSerialPort::readyRead,
                    this, &QSerialPortUtil::readData);
        }
    }
}

void QSerialPortUtil::sendData(QByteArray data)
{
    if (this->open == true)
    {
        qDebug() << data;
        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("$XHTS");
    buffer.append("02021001");
    buffer.append("220710140032");
    buffer.append("276");
    buffer.append("|");
    buffer.append("1");
    buffer.append("000000111111111101");
    buffer.append("|+0.000000000000");
    for ( int i = 1; i < 10; i++ )
    {
        qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
        double rand = (qrand() % 100) * 1E-12;
        buffer.append(QString("|%1%2").arg(base[i-1] > 0 ? "+" : "").arg(QString::number(base[i-1] + rand, 'f', 12)));
        base[i-1] = base[i-1] + rand;
    }
    buffer.append("|+0.000000000000|+0.000000000000|+0.000000000000|+0.000000000000|+0.000000000000|+0.000000000000Z");
    buffer.append("\r\n");

    emit dataRecieved(buffer);
}
