#include "logserialport.h"
#include <QCoreApplication>
#include <QByteArray>
#include <pqQtlib/utils/pqutilsfunc.h>
#include <pqQtlib/utils/pqendian.h>
#include "cstring"

LogSerialPort::LogSerialPort()
{
    buchang  = 0;
    min = 0;
    max = 999;
    ret = QByteArray::fromHex("010300000006C5C8");
}

LogSerialPort::~LogSerialPort()
{
}

float LogSerialPort::toFloat(const QByteArray & ray){
    char ch[4] = {0};
    ch[0] = ray.at(2);
    ch[1] = ray.at(3);
    ch[2] = ray.at(0);
    ch[3] = ray.at(1);
    float value = qFromBigEndian<float>(reinterpret_cast<EndianPointType *>(&ch[0]));
//   memcpy(&value,&ch[0],4);
    return value;
}

bool LogSerialPort::needSend()
{
    return true;
}

QByteArray LogSerialPort::sendData()
{
    return ret;
}

void LogSerialPort::handle(QByteArray & data)
{
    doHandle(data);
}

void LogSerialPort::doHandle(const QByteArray & data)
{
    if(data.at(1) != 0x03) return;
    int l = data.length() - 2;
    QByteArray td = data.right(2);
    int crcc = static_cast<uchar>(td.at(1));
    crcc = crcc << 8;
    crcc = crcc | static_cast<uchar>(td.at(0));
    int scrc = PQ::CRC(data, l);
    if(scrc != crcc) {
        qDebug()<< " RTC CRC erro : should be : " << scrc << "  rev is : " << crcc << "\n"
                                    << "data is :  " << data.toHex();
       return;
    }

    QByteArray dt;
    dt = data.mid(5,4);
    if(dt.isEmpty()) return;
    needReply = true;
    float v = toFloat(dt);
    double rv = v + buchang;
    if(rv > max){
        rv = max;
    }
    if(rv < min){
        rv = min;
    }
    GlobalInfo::this_()->currentWidght = rv;
}
