//
// Created by Mr.V on 2024/2/19.
//

#include <iostream>
#include "ComDetect.h"
ComDetect::ComDetect()
{
    this->serial_ = new QSerialPort;
}

ComDetect::~ComDetect()
{
    this->serial_->deleteLater();
}


QSerialPort* ComDetect::openCom(const QString &com, int baud)
{
    try
    {
        this->serial_->setPortName(com);

        if (baud == 9600)
        {
            this->serial_->setBaudRate(QSerialPort::Baud9600);
        }
        else if (baud == 19200)
        {
            this->serial_->setBaudRate(QSerialPort::Baud19200);
        }
        else if (baud == 115200)
        {
            this->serial_->setBaudRate(QSerialPort::Baud115200);
        }
        else
        {
            this->serial_->setBaudRate(QSerialPort::Baud19200);
        }

        this->serial_->setParity(QSerialPort::NoParity);// 校验
        this->serial_->setDataBits(QSerialPort::Data8); //数据位
        this->serial_->setStopBits(QSerialPort::OneStop);//停止位，停止位默认选择1位
        this->serial_->setFlowControl(QSerialPort::NoFlowControl);// 控制流，默认选择无
        if (this->serial_->open(QSerialPort::ReadWrite))
        {
            this->serial_->clear(QSerialPort::AllDirections);
            this->serial_->setDataTerminalReady(true);
            return this->serial_;
        }
    }
    catch (const std::exception &e)
    {
        std::cout << e.what() << std::endl;
        return nullptr;
    }

    return nullptr;
}

bool ComDetect::closeCom()
{
    this->serial_->close();
    return true;
}

[[deprecated("建议自行定义读取函数")]] void ComDetect::readCom()
{
    try {
        QByteArray data = this->serial_->readAll(); // 读取数据
        if(!data.isEmpty())
        {
//            this->queue_->push(QString(data));
        }
        data.clear();
    } catch(...) {

    }
}

bool ComDetect::writeCom(const QString &str)
{
    try
    {
        this->serial_->write(str.toUtf8());
    }
    catch (...)
    {
        return false;
    }
    return true;
}
