#include "drv_bq27z561.h"




/**
 * @brief 初始化bq27z561驱动
 */
rt_err_t bq27z561_drv_init(bq27z561_drv_t *drv, bq27z561_read_cb_t read_cb, bq27z561_write_cb_t write_cb, void *user_data)
{
    if (drv == NULL || read_cb == NULL || write_cb == NULL) {
        return -RT_ERROR;
    }

    drv->read_cb = read_cb;
    drv->write_cb = write_cb;
    drv->user_data = user_data;
    drv->is_initlized = RT_TRUE;

    return RT_EOK;
}

/**
 * @brief 反初始化bq27z561驱动
 */
rt_err_t bq27z561_drv_deinit(bq27z561_drv_t *drv)
{
    if (drv == NULL) {
        return -RT_ERROR;
    }
    drv->is_initlized = RT_FALSE;
    drv->read_cb = NULL;
    drv->write_cb = NULL;
    drv->user_data = NULL;
    return RT_EOK;
}

/**
 * @brief 读取16位寄存器
 */
static rt_err_t bq27z561_read_u16(bq27z561_drv_t *drv, uint8_t reg, uint16_t *value)
{
    uint8_t buf[2] = {0};
    rt_err_t ret = drv->read_cb(BQ27Z561_DRIVER_ADDR, reg, 1, buf, 2, drv->user_data);
    if (ret != RT_EOK) {
        return ret;
    }
    *value = ((uint16_t)buf[1] << 8) | buf[0];
    return RT_EOK;
}


/**
 * @brief: 从bq27z561读取数据
 * @param: raw_data 读取到的数据存储地址
 * @return: rt_err_t 读取结果
*/  
rt_err_t bq27z561_drv_read(bq27z561_drv_t *drv, bq27z561_raw_data_t *raw_data)
{
    rt_err_t ret;
    uint16_t value = 0;

    if (drv == NULL || raw_data == NULL || drv->is_initlized == RT_FALSE || drv->read_cb == NULL) {
        return -RT_ERROR;
    }

    ret = bq27z561_read_u16(drv, BQ27Z561_VOLTAGE_REG, &value);
    if (ret != RT_EOK) {
        return ret;
    }
    raw_data->voltage = value;

    ret = bq27z561_read_u16(drv, BQ27Z561_CURRENT_REG, &value);
    if (ret != RT_EOK) {
        return ret;
    }
    raw_data->current = (int16_t)value;

    ret = bq27z561_read_u16(drv, BQ27Z561_TEMPERATURE_REG, &value);
    if (ret != RT_EOK) {
        return ret;
    }
    raw_data->temperature = value;

    ret = bq27z561_read_u16(drv, BQ27Z561_STATUS_REG, &value);
    if (ret != RT_EOK) {
        return ret;
    }
    raw_data->status = value;

    ret = bq27z561_read_u16(drv, BQ27Z561_SOC_REG, &value);
    if (ret != RT_EOK) {
        return ret;
    }
    raw_data->soc = value;

    ret = bq27z561_read_u16(drv, BQ27Z561_REMAINING_CAPACITY_REG, &value);
    if (ret != RT_EOK) {
        return ret;
    }
    raw_data->remaining_capacity = value;

    ret = bq27z561_read_u16(drv, BQ27Z561_FULL_CHARGE_CAPACITY_REG, &value);
    if (ret != RT_EOK) {
        return ret;
    }
    raw_data->full_charge_capacity = value;

    return RT_EOK;
}

