#include "CounterProtocolBM.h"
#include <iostream>

CounterProtocolBM::CounterProtocolBM(QObject *parent) : QObject(parent)
{

}

CounterProtocolBM::~CounterProtocolBM()
{

}

bool CounterProtocolBM::parseMessureData(QByteArray rawData, CounterDataDto * counterData)
{
    int start = rawData.indexOf(COUNTER_FRAME_CONTENT_SEP);
    int end = rawData.indexOf(COUNTER_FRAME_SUM_SEP);

    QByteArray content = rawData.mid(start + 1, end - start - 1);
    QString contentStr = QString(content);
    QStringList subList = contentStr.split(",");

    counterData->type = subList.at(0).toUInt();
    counterData->channelId = subList.at(1).toUInt();
    counterData->channelActive = subList.at(2).toUInt();
    counterData->channelRefId = subList.at(3).toUInt();
    counterData->channelData = subList.at(4).toLongLong();
    counterData->load = subList.at(5);
    counterData->level = subList.at(6).toDouble();
    counterData->frameId = subList.at(7);

    return true;
}

bool CounterProtocolBM::checkFrame(QByteArray rawData)
{
    // 帧长度小于最小的长度
    if (rawData.size() < COUNTER_FRAME_MIN_LENGTH)
    {
        return false;
    }

    // 帧头不是$GL
    if (COUNTER_FRAME_HEAD.toLocal8Bit() != rawData.mid(0, COUNTER_FRAME_HEAD.size()))
    {
        return false;
    }

    // 帧尾不是\r\n
    if (COUNTER_FRAME_TAIL.toLocal8Bit() != rawData.mid(rawData.size() - COUNTER_FRAME_TAIL.size()))
    {
        return false;
    }

    // 校验和的分隔符不是*
    if (COUNTER_FRAME_SUM_SEP.toLocal8Bit() != rawData.mid(rawData.size() - COUNTER_FRAME_TAIL.size() - 2 - 1, 1))
    {
        return false;
    }

    return true;
}
