#include "power.h"

static const char *TAG = "POWER";

i2c_master_dev_handle_t bq25896_handle; // 设备句柄








// 读取单个寄存器
esp_err_t bq25896_read_reg(uint8_t reg_addr, uint8_t *value)
{
    if (bq25896_handle == NULL) {
        return ESP_ERR_INVALID_STATE;
    }
    
    return i2c_master_transmit_receive(
        bq25896_handle,
        &reg_addr, 1,      // 发送寄存器地址
        value, 1,          // 接收数据
        1000
    );
}

// 读取多个连续寄存器
esp_err_t bq25896_read_regs(uint8_t start_addr, uint8_t *buffer, size_t len)
{
    if (bq25896_handle == NULL) {
        return ESP_ERR_INVALID_STATE;
    }
    
    return i2c_master_transmit_receive(
        bq25896_handle,
        &start_addr, 1,    // 发送起始地址
        buffer, len,       // 接收数据
        1000
    );
}


void bq25896_read_system_status(void)
{
    uint8_t reg_value;
    esp_err_t ret = bq25896_read_reg(0x0B, &reg_value);
    
    if (ret == ESP_OK) {
        bq25896_reg0b_t status = *(bq25896_reg0b_t *)&reg_value;
        
        // VBUS 状态
        const char* vbus_status[] = {
            "No Input", "USB Host SDP", "USB CDP", "USB DCP", 
            "Adjustable High Voltage DCP", "Unknown", "Non-Standard Adapter", "OTG"
        };
        if (status.vbus_stat < 8) {
            ESP_LOGI(TAG, "VBUS Status: %s", vbus_status[status.vbus_stat]);
        }
        
        // 充电状态
        const char* chrg_status[] = {
            "Not Charging", "Trickle Charge", "Pre-Charge", "Fast Charging"
        };
        if (status.chrg_stat < 4) {
            ESP_LOGI(TAG, "Charging Status: %s", chrg_status[status.chrg_stat]);
        }
        
        // 其他状态
        ESP_LOGI(TAG, "Power Good: %s", status.pg_stat ? "YES" : "NO");
        ESP_LOGI(TAG, "VSYS Status: %s", status.vsys_stat ? "MIN System Voltage" : "Normal");
    }
}

// 读取电池电压
float bq25896_read_battery_voltage(void)
{
    uint8_t reg_value;
    if (bq25896_read_reg(0x0E, &reg_value) != ESP_OK) {
        return -1.0f;
    }
    
    // 计算电压: VBAT = (VBAT_REG[5:0] * 20mV) + 2.304V
    float voltage = ((reg_value & 0x3F) * 0.020f) + 2.304f;
    
    ESP_LOGI(TAG, "Battery Voltage: %.3fV (Raw: 0x%02X)", voltage, reg_value);
    return voltage;
}

// 读取系统电压
float bq25896_read_system_voltage(void)
{
    uint8_t reg_value;
    if (bq25896_read_reg(0x0F, &reg_value) != ESP_OK) {
        return -1.0f;
    }
    
    // 计算电压: VSYS = (VSYS_REG[5:0] * 20mV) + 2.304V
    float voltage = ((reg_value & 0x3F) * 0.020f) + 2.304f;
    
    ESP_LOGI(TAG, "System Voltage: %.3fV (Raw: 0x%02X)", voltage, reg_value);
    return voltage;
}

// 读取 VBUS 电压
float bq25896_read_vbus_voltage(void)
{
    uint8_t reg_value;
    if (bq25896_read_reg(0x11, &reg_value) != ESP_OK) {
        return -1.0f;
    }
    
    // 计算电压: VBUS = (VBUS_REG[5:0] * 100mV) + 2.6V
    float voltage = ((reg_value & 0x3F) * 0.100f) + 2.600f;
    
    ESP_LOGI(TAG, "VBUS Voltage: %.2fV (Raw: 0x%02X)", voltage, reg_value);
    return voltage;
}

// 读取充电电流
float bq25896_read_charge_current(void)
{
    uint8_t reg_value;
    if (bq25896_read_reg(0x12, &reg_value) != ESP_OK) {
        return -1.0f;
    }
    
    // 计算电流: ICHG = (ICHG_REG[6:0] * 50mA)
    float current = (reg_value & 0x7F) * 0.050f;
    
    ESP_LOGI(TAG, "Charge Current: %.2fA (Raw: 0x%02X)", current, reg_value);
    return current;
}

// 读取输入电流
float bq25896_read_input_current(void)
{
    uint8_t reg_value;
    if (bq25896_read_reg(0x13, &reg_value) != ESP_OK) {
        return -1.0f;
    }
    
    // 计算电流: IIN = (IIN_REG[5:0] * 50mA)
    float current = (reg_value & 0x3F) * 0.050f;
    
    ESP_LOGI(TAG, "Input Current: %.2fA (Raw: 0x%02X)", current, reg_value);
    return current;
}

// 读取芯片温度
float bq25896_read_junction_temp(void)
{
    uint8_t reg_value;
    if (bq25896_read_reg(0x14, &reg_value) != ESP_OK) {
        return -100.0f;
    }
    
    // 计算温度: TREG = (TREG_REG[6:0] * 0.5°C) - 40°C
    float temperature = ((reg_value & 0x7F) * 0.5f) - 40.0f;
    
    ESP_LOGI(TAG, "Junction Temperature: %.1f°C (Raw: 0x%02X)", temperature, reg_value);
    return temperature;
}

void bq25896_read_fault_status(void)
{
    uint8_t reg_value;
    if (bq25896_read_reg(0x0C, &reg_value) == ESP_OK) {
        bq25896_reg0c_t fault = *(bq25896_reg0c_t *)&reg_value;
        
        if (fault.watchdog_fault) ESP_LOGE(TAG, "Watchdog Timer Expired");
        if (fault.boost_fault)    ESP_LOGE(TAG, "Boost Over-current/Over-voltage");
        
        // 充电故障
        if (fault.chrg_fault == 0) ESP_LOGI(TAG, "Charging: Normal");
        if (fault.chrg_fault == 1) ESP_LOGE(TAG, "Charging: Input Fault");
        if (fault.chrg_fault == 2) ESP_LOGE(TAG, "Charging: Thermal Shutdown");
        if (fault.chrg_fault == 3) ESP_LOGE(TAG, "Charging: Charge Safety Timer Expiration");
        
        if (fault.bat_fault) ESP_LOGE(TAG, "Battery Over-voltage");
        
        // NTC 故障
        if (fault.ntc_fault == 0) ESP_LOGI(TAG, "NTC: Normal");
        if (fault.ntc_fault == 1) ESP_LOGW(TAG, "NTC: Warm");
        if (fault.ntc_fault == 2) ESP_LOGW(TAG, "NTC: Cool");
        if (fault.ntc_fault == 3) ESP_LOGW(TAG, "NTC: Cold");
        if (fault.ntc_fault == 4) ESP_LOGE(TAG, "NTC: Hot");
    }
}

// 关闭充电功能（系统仍由电池供电）
esp_err_t bq25896_disable_charging(void)
{
    // 读取寄存器 0x03
    uint8_t reg03_val;
    esp_err_t ret = bq25896_read_reg(0x03, &reg03_val);
    if (ret != ESP_OK) return ret;
    
    // 设置 CHG_CONFIG 位 (BIT7 = 0) 关闭充电
    reg03_val &= ~(1 << 7);  // 清除 BIT7
    
    uint8_t write_buf[] = {0x03, reg03_val};
    ret = i2c_master_transmit(bq25896_handle, write_buf, 2, 1000);
    
    if (ret == ESP_OK) {
        ESP_LOGI(TAG, "Charging disabled");
        
        // 同时将充电电流设为0
        uint8_t zero_current[] = {0x04, 0x00};  // 寄存器 0x04，充电电流=0
        i2c_master_transmit(bq25896_handle, zero_current, 2, 1000);
    }
    return ret;
}


// 启用充电功能
esp_err_t bq25896_enable_charging(void)
{
    uint8_t reg03_val;
    esp_err_t ret = bq25896_read_reg(0x03, &reg03_val);
    if (ret != ESP_OK) return ret;
    
    // 设置 CHG_CONFIG 位 (BIT7 = 1) 启用充电
    reg03_val |= (1 << 7);  // 设置 BIT7
    
    uint8_t write_buf[] = {0x03, reg03_val};
    ret = i2c_master_transmit(bq25896_handle, write_buf, 2, 1000);
    
    if (ret == ESP_OK) {
        ESP_LOGI(TAG, "Charging enabled");
    }
    return ret;
}

// 关闭 OTG 升压输出
esp_err_t bq25896_disable_otg(void)
{
    uint8_t reg03_val;
    esp_err_t ret = bq25896_read_reg(0x03, &reg03_val);
    if (ret != ESP_OK) return ret;
    
    // 清除 OTG_CONFIG 位 (BIT5 = 0)
    reg03_val &= ~(1 << 5);
    
    uint8_t write_buf[] = {0x03, reg03_val};
    ret = i2c_master_transmit(bq25896_handle, write_buf, 2, 1000);
    
    if (ret == ESP_OK) {
        ESP_LOGI(TAG, "OTG disabled");
        
        // 可选：将 OTG 电压设为最小值
        uint8_t min_voltage[] = {0x0A, 0x1E};  // 寄存器 0x0A，最小电压 ~4.8V
        i2c_master_transmit(bq25896_handle, min_voltage, 2, 1000);
    }
    return ret;
}

// 开启 OTG 升压输出
esp_err_t bq25896_enable_otg(void)
{
    uint8_t reg03_val;
    esp_err_t ret = bq25896_read_reg(0x03, &reg03_val);
    if (ret != ESP_OK) return ret;
    
    // 设置 OTG_CONFIG 位 (BIT5 = 1)
    reg03_val |= (1 << 5);
    
    uint8_t write_buf[] = {0x03, reg03_val};
    ret = i2c_master_transmit(bq25896_handle, write_buf, 2, 1000);
    
    if (ret == ESP_OK) {
        ESP_LOGI(TAG, "OTG enabled (5V output)");
        
        // 设置 OTG 电压为 5.0V
        // 公式: VOTG = (VOTG_REG[5:0] * 64mV) + 4.8V
        // 5.0V = 4.8V + 0.2V = 4.8V + (3 * 64mV)
        uint8_t otg_voltage[] = {0x0A, 0x23};  // 0x23 = 35 * 64mV ≈ 5.0V
        i2c_master_transmit(bq25896_handle, otg_voltage, 2, 1000);
    }
    return ret;
}

// 关闭输入电流（最小化 VBUS 消耗）
esp_err_t bq25896_disable_input(void)
{
    // 设置最小输入电流限制
    uint8_t min_input[] = {0x00, 0x00};  // 寄存器 0x00，输入电流=100mA
    esp_err_t ret = i2c_master_transmit(bq25896_handle, min_input, 2, 1000);
    
    if (ret == ESP_OK) {
        ESP_LOGI(TAG, "Input current limited to minimum");
    }
    return ret;
}

// 完全关闭电池供电（进入运输模式）
esp_err_t bq25896_enter_shipping_mode(void)
{
    // 1. 读取当前寄存器 0x03 的值
    uint8_t reg03_val;
    esp_err_t ret = bq25896_read_reg(0x03, &reg03_val);
    if (ret != ESP_OK) return ret;
    
    // 2. 设置 BATFET_DIS 位 (BIT4 = 1)
    reg03_val |= (1 << 4);  // 0x10
    
    // 3. 写入寄存器
    uint8_t write_buf[] = {0x03, reg03_val};
    ret = i2c_master_transmit(bq25896_handle, write_buf, 2, 1000);
    
    if (ret == ESP_OK) {
        ESP_LOGI(TAG, "Entered shipping mode (BATFET disabled)");
    }
    return ret;
}

void power_sys_off()
{

    ESP_LOGI(TAG, "Starting system shutdown...");
    
    uint8_t write_buf[] = {0x09, 5};
    esp_err_t ret = i2c_master_transmit(bq25896_handle, write_buf, 2, 1000);
    if (ret == ESP_OK) {
        ESP_LOGI(TAG, "shutdown");
    }
 
 
}

void bq25896_check_immediate(void)
{
    ESP_LOGI(TAG, "=== 立即检查 ===");
    
    // 1. 确认 I2C 通信正常
    uint8_t device_id;
    if (bq25896_read_reg(0x14, &device_id) != ESP_OK) {
        ESP_LOGE(TAG, "❌ I2C 通信失败！");
        return;
    }
    ESP_LOGI(TAG, "✓ I2C 通信正常，器件ID: 0x%02X", device_id);
    
    // 2. 读取寄存器 0x03
    uint8_t reg03;
    bq25896_read_reg(0x03, &reg03);
    ESP_LOGI(TAG, "寄存器 0x03 = 0x%02X", reg03);
    
    // 3. 检查关键位
    ESP_LOGI(TAG, "BIT7(CHG_CONFIG): %s", (reg03 & 0x80) ? "1(启用充电)" : "0(关闭充电)");
    ESP_LOGI(TAG, "BIT5(OTG_CONFIG): %s", (reg03 & 0x20) ? "1(启用OTG)" : "0(关闭OTG)");
    ESP_LOGI(TAG, "BIT4(BATFET_DIS): %s", (reg03 & 0x10) ? "1(断开电池)" : "0(连接电池)");
}

void power_init()
{
    ESP_LOGI(TAG, "init");

    i2c_device_config_t dev_config = {
    .dev_addr_length = I2C_ADDR_BIT_LEN_7, // 7位地址模式
    .device_address  = BQ25896_ADDR,
    .scl_speed_hz    = BQ25896_SPEED_HZ,
    // .scl_wait_us   = 0,  // 可选，SCL 等待时间
    };
    esp_err_t err=i2c_master_bus_add_device(bus_handle, &dev_config, &bq25896_handle);
    if(err!=ESP_OK)
    {
        ESP_LOGE(TAG, "bq25896 init err:%d",err);
    }

    bq25896_check_immediate();

}