#include "VoltageDevice.h"

VoltageDevice::VoltageDevice(/* args */)
{
}

VoltageDevice::~VoltageDevice()
{
}

bool VoltageDevice::ReadData()
{
    for (size_t i = 0; i < sizeof(data); i++)
        data[i] = 0;
    Delay myDelay; //定时器
    bool IsRun = true;
    int count = 0;
    byte read[8] = {0x01, 0x03, 0x00, 0x48, 0x00, 0x0A, 0x45, 0xDB};
    Serial2.write(read, sizeof(read));
    // Serial.println("写入数据：0x01, 0x03, 0x00, 0x48, 0x00, 0x0A, 0x45, 0xDB");
    while (IsRun)
    {
        if (Serial2.available() > 0 && count < sizeof(data))
        {
            data[count] = Serial2.read();
            count++;
        }
        if (count >= sizeof(data))
            return true;
        if (myDelay.Start(IsRun, 2))
            return false;
    }
}

float VoltageDevice::DataConvert(int len, int Index, int bl)
{
    byte dt[len];
    int tempIndex;
    for (size_t i = 0; i < len; i++)
    {
        tempIndex = len + Index - 1 - i;
        if (tempIndex >= 0 && tempIndex < sizeof(data))
        {
            dt[i] = data[len + Index - 1 - i];
        }
    }

    int Temp = 0;
    for (size_t i = 0; i < sizeof(dt); i++)
    {
        Temp += (int)(dt[i] << (i * 8));
    }
    return (float)(Temp / bl);
}

VoltageDevice MyVd;
