#include <QDebug>
#include <QDataStream>

#include "dataparser.h"

DataParser::DataParser()
{

}

QByteArray DataParser::connectToDevice(const QVector<Phase> &vtr)
{
    const int phaseLength = sizeof(Phase);
    const int phaseArrayLength = vtr.size() * phaseLength;
    char phaseArray[300] = {};
    int offset = 0;

    for(const Phase& phase:vtr){
        memcpy(phaseArray + offset,&phase, sizeof(Phase));
        offset += phaseLength;
    }

    //
    //    int totalDataLength = 0;
    char totalData[300] = {};

    u16 header = 0x5aa5;
    memcpy(totalData,(char*)&header,sizeof(u16));
    //    totalDataLength +=2;

    totalData[2] = 1 + 2 + phaseArrayLength + 2;
    //    totalDataLength++;

    totalData[3] = 0x82;
    //    totalDataLength++;

    u16 address = 0x0050;
    memcpy(totalData + 4,(char*)&address,sizeof(u16));

    memcpy(totalData + 6,phaseArray,phaseArrayLength);

    //crc
    char data[300] = {};

    data[0] = 0x82;

    //    u16 address = 0x0050;
    memcpy(data + 1,(char*)&address,sizeof(u16));

    memcpy(data + 3,phaseArray,phaseArrayLength);

    u16 crc = modbusCRC16((u8*)data, 3 + phaseArrayLength);
    //
    memcpy(totalData + 6 + phaseArrayLength,(char*)&crc,sizeof(u16));

    //

    return QByteArray(totalData,6 + phaseArrayLength + 2);
}

unsigned short DataParser::modbusCRC16(unsigned char *data, unsigned short length) {
    unsigned short crc = 0xFFFF;
    unsigned char i;
    for (unsigned short j = 0; j < length; j++) {
        crc ^= (unsigned short)data[j];
        for (i = 0; i < 8; i++) {
            if (crc & 0x0001) {
                crc = (crc >> 1) ^ 0xA001;
            } else {
                crc = crc >> 1;
            }
        }
    }
    // CRC结果低字节在前，高字节在后
    return crc;
}
