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

PhaseProtocolBM::PhaseProtocolBM(QObject *parent) : QObject(parent)
{

}

PhaseProtocolBM::~PhaseProtocolBM()
{

}

bool PhaseProtocolBM::parseMessureData(QByteArray rawData, PhaseDataDto * dataObj)
{
    // 获取帧头——帧计数
    QByteArray head = rawData.left(PHASE_FRAME_ID_LENGTH);
    dataObj->frameId = QByteUtil::binToHexString(head);

    int j = 0; // 用于转换通道顺序

    // 获取每个通道的测量数据
    for (int i = 1; i <= PHASE_MESSURE_CHANNEL; i++)
    {
        if (i <= 8)
        {
            j = 2 * i - 1;

        } else
        {
            j = 2 * (i - 8);
        }

        QByteArray channelRaw = rawData.left(PHASE_MESSURE_SIZE * j + PHASE_FRAME_ID_LENGTH).right(PHASE_MESSURE_SIZE);
        qulonglong channelRawData = QByteUtil::binToULong(channelRaw, 8);

        if (channelRawData == CALCULATE_OFFSET)
        {
            dataObj->channelActive.append("0");
            dataObj->channelData.append(0.00);
            dataObj->channelDataStr.append("0.00");
            dataObj->channelRawDataStr.append(QString::number(CALCULATE_OFFSET));
        } else if (channelRawData > CALCULATE_OFFSET)
        {
            double phase = (channelRawData - CALCULATE_OFFSET) * CALCULATE_FACTOR;
            dataObj->channelActive.append("1");
            dataObj->channelData.append(phase);
            dataObj->channelDataStr.append(QString::number(phase, 'f', 15));
            dataObj->channelRawDataStr.append(QString::number((channelRawData - CALCULATE_OFFSET)));
        } else
        {
            double phase = -(CALCULATE_OFFSET - channelRawData) * CALCULATE_FACTOR; // rawData是无符号long 相位有正有负 小于CALCULATE_OFFSET时是负值
            dataObj->channelActive.append("1");
            dataObj->channelData.append(phase);
            dataObj->channelDataStr.append(QString::number(phase, 'f', 15));
            dataObj->channelRawDataStr.append(QString::number((channelRawData - CALCULATE_OFFSET)));
        }
    }

    return true;
}

QString PhaseProtocolBM::startMessure()
{
    return "$START*";
}
QString PhaseProtocolBM::stopMessure()
{
    return "$$STOP*";
}

bool PhaseProtocolBM::checkFrame(QByteArray rawData)
{
    // 帧长度小于最小的长度
    if (rawData.length() != PHASE_FRAM_LENGTH)
    {
        return false;
    }

    // 帧尾不是0xEEEEEEEE
    if (rawData.mid(rawData.length() - PHASE_FRAME_TAIL.size()) != PHASE_FRAME_TAIL)
    {
        return false;
    }

    return true;
}
