#include "BCodeTerminalProtocolBM.h"

BCodeTerminalProtocolBM::BCodeTerminalProtocolBM(QObject* parent) : DeviceStatusProtocolBase(parent)
{

}

BCodeTerminalProtocolBM::~BCodeTerminalProtocolBM()
{

}

// 解析数据
bool BCodeTerminalProtocolBM::parseDeviceFrameData(QByteArray rawData, DeviceFrameBaseDto * frameData, int frameType)
{
    if (frameType != 1)
        return false;

    qint8 length = rawData.mid(1, 2).toInt(0, 16);
    QByteArray content = rawData.mid(19, length - 24);
    int outBdcByte = 0;
    int outBacByte = 0;
    QString outStr = "";

    ((BCodeTerminalStatusDto *) frameData)->devStatus = content.at(0);
    ((BCodeTerminalStatusDto *) frameData)->bdcInStatus = content.at(2);
    ((BCodeTerminalStatusDto *) frameData)->bacInStatus = content.at(3);
    ((BCodeTerminalStatusDto *) frameData)->fiveInStatus = content.at(4);

    outBdcByte = content.mid(6, 1).toInt(0, 16);
    outBacByte = content.mid(5, 1).toInt(0, 16);
    for (int i = 0; i < 4; i++)
    {
        ((BCodeTerminalStatusDto *) frameData)->bdcOutStatusList.append(QString("%1").arg(outBdcByte % 2));
        ((BCodeTerminalStatusDto *) frameData)->bacOutStatusList.append(QString("%1").arg(outBacByte % 2));

        outBdcByte = outBdcByte / 2;
        outBacByte = outBacByte / 2;
    }

    ((BCodeTerminalStatusDto *) frameData)->ref = content.at(7);
    ((BCodeTerminalStatusDto *) frameData)->track = content.at(8);
    ((BCodeTerminalStatusDto *) frameData)->bacRange = content.mid(9, 4).toFloat();
    ((BCodeTerminalStatusDto *) frameData)->bacRatio = content.mid(13, 1).toInt();

    ((BCodeTerminalStatusDto *)frameData)->frameType = B_CODE_TERMINAL_STATUS_FRAME_TYPE;

    return true;
}
DeviceFrameBaseDto * BCodeTerminalProtocolBM::frameFactory(int frameType)
{
    DeviceFrameBaseDto * frameData = new BCodeTerminalStatusDto();

    return frameData;
}

//
QList<QByteArray> BCodeTerminalProtocolBM::extractFrameList(QByteArray rawData)
{
    QList<QByteArray> resultList;
    while (rawData.endsWith(QByteArray("*")) == true && rawData.startsWith("$") == true)
    {
        QByteArray ba;
        qint8 length = rawData.mid(1, 2).toInt(0, 16);
        if (rawData.at(0) == '$' && rawData.at(length - 1) == '*')
        {
            ba.append(rawData.mid(0, length));
            resultList.append(ba);
            ba.clear();
            rawData = rawData.mid(length, rawData.size() - length);
        } else
        {
            break;
        }
    }

    return resultList;
}

// 检测帧格式，帧头帧尾
int BCodeTerminalProtocolBM::checkFrame(QByteArray rawData)
{
    if (rawData.at(0) == '$' && rawData.at(rawData.size() - 1) == '*' &&
            rawData.at(3) == '2' && rawData.at(20) == '2' && //
            rawData.size() == rawData.mid(1, 2).toInt(0, 16))
        return 1;
    return 0;
}
