#include "common.h"
#include "INA226.h"
#include "softiic.h"

float currentLSB;


// 配置 INA226
bool ina226_configure() {
    uint16_t config = 0x4127; // 默认配置：16次平均，1.1ms 转换时间，连续模式
    i2c_start();
    i2c_write_byte(INA226_ADDRESS << 1);
    i2c_write_byte(INA226_REG_CONFIG);
    i2c_write_byte(config >> 8);
    i2c_write_byte(config & 0xFF);
    i2c_stop();
    return true;
}

// 校准 INA226
bool ina226_calibrate(float rShuntValue, float iMaxExpected) {
    currentLSB = iMaxExpected / 32767.0; // 电流 LSB
    uint16_t calibrationValue = (uint16_t)(0.00512 / (currentLSB * rShuntValue));

    i2c_start();
    i2c_write_byte(INA226_ADDRESS << 1);
    i2c_write_byte(INA226_REG_CALIBRATION);
    i2c_write_byte(calibrationValue >> 8);
    i2c_write_byte(calibrationValue & 0xFF);
    i2c_stop();
    return true;
}

// 读取总线电压
float ina226_readbusvoltage(){
    i2c_start();
    i2c_write_byte(INA226_ADDRESS << 1);
    i2c_write_byte(INA226_REG_BUSVOLTAGE);
    i2c_start();
    i2c_write_byte((INA226_ADDRESS << 1) | 1);
    uint8_t high = i2c_read_byte(true);
    uint8_t low = i2c_read_byte(false);
    i2c_stop();
    int16_t value = (high << 8) | low;
    return value * 0.00125f; // 每 LSB = 1.25mV
}

// 读取电流
float ina226_readcurrent() {
    i2c_start();
    i2c_write_byte(INA226_ADDRESS << 1);
    i2c_write_byte(INA226_REG_CURRENT);
    i2c_start();
    i2c_write_byte((INA226_ADDRESS << 1) | 1);
    uint8_t high = i2c_read_byte(true);
    uint8_t low = i2c_read_byte(false);
    i2c_stop();
    int16_t value = (high << 8) | low;
    return -value * currentLSB;
}

int ina225_init(){
   // 配置 INA226
    if(!ina226_configure()) {
        my_zlog_warn("INA226初始化失败");
        return -1;
    }
    // 校准 INA226
    float rshuntvalue = 0.01; // 分流电阻值（单位：欧姆）
    float imaxexpected= 5; // 最大预期电流（单位：安培）
    if(!ina226_calibrate(rshuntvalue, imaxexpected)){
        my_zlog_warn("INA226校准失败");
        return -2;
    }
    return 0;

}
