#include "acrel_DJSF1352RN.h"


int ccu_DCMeters_init(DCMeters_t* dev, const char* devname)
{
    if (dev)
    {
        com_ttySx_init(&dev->tty, devname, 9600, 8, 'N', 1);
        com_ttySx_rs485_enable(&dev->tty, 1);
        dev->salve = 0x1;
        return 0;
    }
    return -1;
}

void ccu_DCMeters_readV(DCMeters_t* dev)
{
    if (dev)
    {
        uint16_t value[4];
        if (modbus_RTU_read_holding_registers(&dev->tty, dev->salve+0, 0, 2, value) == 0)
        {
            float readV = (float)value[0];
            float power = (float)value[1] - 3;
            readV = readV * powf(10, power);
            dev->current_V[0] = readV;
        }
        if (modbus_RTU_read_holding_registers(&dev->tty, dev->salve+1, 0, 2, value) == 0)
        {
            float readV = (float)value[0];
            float power = (float)value[1] - 3;
            readV = readV * powf(10, power);
            dev->current_V[1] = readV;  
        }
    }
}

void ccu_DCMeters_readI(DCMeters_t* dev)
{
    if (dev)
    {
        uint16_t value[4];
        if (modbus_RTU_read_holding_registers(&dev->tty, dev->salve+0, 2, 2, value) == 0)
        {
            float readV = (float)value[0];
            float power = (float)value[1] - 3;
            readV = readV * powf(10, power);
            dev->current_I[0] = readV;
        }
        if (modbus_RTU_read_holding_registers(&dev->tty, dev->salve+1, 2, 2, value) == 0)
        {
            float readV = (float)value[0];
            float power = (float)value[1] - 3;
            readV = readV * powf(10, power);
            dev->current_I[1] = readV;  
        }
    }
}

void ccu_DCMeters_readP(DCMeters_t* dev)
{
    if (dev)
    {
        uint16_t value[4];
        if (modbus_RTU_read_holding_registers(&dev->tty, dev->salve+0, 8, 2, value) == 0)
        {
            float readV = (float)value[0];
            float power = (float)value[1] - 3;
            readV = readV * powf(10, power);
            dev->current_P[0] = readV;
        }
        if (modbus_RTU_read_holding_registers(&dev->tty, dev->salve+1, 8, 2, value) == 0)
        {
            float readV = (float)value[0];
            float power = (float)value[1] - 3;
            readV = readV * powf(10, power);
            dev->current_P[1] = readV;  
        }
    }
}

void ccu_DCMeters_readE(DCMeters_t* dev)
{
    if (dev)
    {
        uint16_t value[4];
        if (modbus_RTU_read_holding_registers(&dev->tty, dev->salve+0, 12, 2, value) == 0)
        {
            dev->current_E[0] = (float)((value[0]<<16)|value[1]);
        }
        if (modbus_RTU_read_holding_registers(&dev->tty, dev->salve+1, 12, 2, value) == 0)
        {
            dev->current_E[1] = (float)((value[0]<<16)|value[1]);
        }
    }
}


void ccu_DCMeters_exit(DCMeters_t* dev)
{
    if(dev)
    {
        com_ttySx_rs485_enable(&dev->tty, 0);
        com_ttySx_exit(&dev->tty);
    }
}