#include "ModbusRtu.h"

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

ModbusRtu::~ModbusRtu()
{
}

void preTransmission()
{
    digitalWrite(RE, 1);
    digitalWrite(DE, 1);
}

void posTransmission()
{
    digitalWrite(RE, 0);
    digitalWrite(DE, 0);
}

float UshorsToFloat(uint16_t Word1, uint16_t word2)
{
    byte Udata[4];
    Udata[3] = (byte)(Word1 >> 8);
    Udata[2] = (byte)(Word1);
    Udata[1] = (byte)(word2 >> 8);
    Udata[0] = (byte)(word2);
    float f;
    union change
    {
        float d;
        unsigned char dat[4];
    } r1;

    r1.dat[0] = Udata[0];
    r1.dat[1] = Udata[1];
    r1.dat[2] = Udata[2];
    r1.dat[3] = Udata[3];
    f = r1.d;
    return f;
}

void ModbusRtu::Init()
{
    pinMode(RE, OUTPUT);
    pinMode(DE, OUTPUT);
    pinMode(Status, OUTPUT);
    posTransmission();
    Serial2.begin(9600); //电压采集模块串口  和 电流采集模块的串口
    myMaster.begin(1, Serial2);
    myMaster.preTransmission(preTransmission);
    myMaster.postTransmission(posTransmission);
}

void ModbusRtu::Start()
{
    digitalWrite(Status, 0);
    preTransmission();
    bool result = MyVd.ReadData();
    if (result)
        // Serial.println("电压获取成功");
        digitalWrite(Status, 1);
    // else
    //     Serial.println("电压获取失败");
    // float Voltage = MyVd.DataConvert(2, 3, 100); //电压
    Voltage = MyVd.DataConvert(2, 3, 100);
    uint8_t res = myMaster.readHoldingRegisters(32, 16);
    if (res == myMaster.ku8MBSuccess)
    {
        // Serial.print("读取寄存器：");
        for (size_t i = 0; i < 8; i++)
        {
            deviceModel[i].Current = UshorsToFloat(myMaster.getResponseBuffer(i * 2), myMaster.getResponseBuffer(i * 2 + 1));
            deviceModel[i].Voltage = Voltage;
            deviceModel[i].Power = deviceModel[i].Current * Voltage;
            deviceModel[i].Energy = deviceModel[i].Power * 0; //电能公式 W = UIT  电压 * 电流 * 时间

            Current[i] = deviceModel[i].Current;

            // Serial.print("电流：");
            // Serial.println(deviceModel[i].Current);

            // Serial.print("电压：");
            // Serial.println(deviceModel[i].Voltage);

            // Serial.print("功率：");
            // Serial.println(deviceModel[i].Power);

            // Serial.print("电能：");
            // Serial.println(deviceModel[i].Energy);
        }
    }
    else
    {
        // Serial.println("Modbus rtu 读取失败");
    }
}

ModbusRtu myRtu;
