#include "serialgps.h"

#include "../global.h"

SerialGPS::SerialGPS(QObject *parent) : QObject(parent) { setupSerialPort(); }

// 打开串口的函数
void SerialGPS::openSerialPort() {
    const QString portName = gpsPort;
    const qint32 baudRate = 9600;

    if (!serialPort.isOpen()) {
        serialPort.setPortName(portName);
        serialPort.setBaudRate(baudRate);
        if (serialPort.open(QIODevice::ReadWrite)) {
        } else {
            emit openError();
        }
    }
}

// 关闭串口的函数
void SerialGPS::closeSerialPort() {
    if (serialPort.isOpen()) {
        serialPort.close();
    }
}

void SerialGPS::sendData() {
    if (serialPort.isOpen()) {
        // serialPort.write(data.toUtf8());
    }
}

void SerialGPS::readData() {
    QByteArray data = serialPort.readAll();
    emit dataReceived(data);
    PareGNRMC parser;
    RMCData m_data = parser.parseRMC(data);
    storedGNRMCData = m_data;
    emit gnrmcDataReceived(storedGNRMCData);
    emit storedGNRMCDataUpdated(storedGNRMCData);  // 发出信号
}

RMCData SerialGPS::getStoredGNRMCData() const { return storedGNRMCData; }

void SerialGPS::setupSerialPort() {
    openSerialPort();
    connect(&serialPort, &QSerialPort::readyRead, this, &SerialGPS::readData);
}
