#include "charge.h"

void Charge_init(void)
{
    charge_init_typedef charge_init_struct;
    sadc_init_typedef sadc_init_struct;

    pmu_init(1);        // pmu buck mode.

    charge_init_struct.const_curr = CHARGE_CONS_CUR_200mA;
    charge_init_struct.cutoff_curr = CHARGE_CUTOFF_CUR_30mA;
    charge_init_struct.cutoff_volt = CHARGE_CUTOFF_VOL_4V2;
    charge_init_struct.dcin_reset = CHARGE_DCIN_RESET_DIS;
    charge_init_struct.trick_curr = CHARGE_TRI_CUR_10mA;
    charge_init_struct.trick_curr_en = ENABLE;
    charge_init_struct.trick_cutoff_volt = CHARGE_TRI_OFF_VOL_3V;
    charge_init_struct.mode = CHARGE_MODE_FULL_DISCONNECT;
    charge_init(&charge_init_struct);

    sadc_init_struct.clk = SADC_CLK_6M;
    sadc_init_struct.baud = SADC_ST_8_CLK;
    sadc_init(&sadc_init_struct);

    sadc_channel_config(ADCCH_VBAT, SADC_ST_8_CLK);
    sadc_channel_config(ADCCH_BGOP, SADC_ST_8_CLK);
}


//Test function
void Charge_example(void)
{
    static u32 delay_cnt1;
    static u32 delay_cnt2;

    if (tick_check_expire(delay_cnt1, 500)) {
        delay_cnt1 = tick_get();
        printf("\n---> DC online: %X\n", charge_detect_dc());   // Check if usb 5V input is online
        printf("power: %d\n", charge_get_level(0));     //get current percentage battery level
        printf("vbat: %d\n", charge_get_level(1));      //get voltage value
        printf("charge_cfg.sta(0:un-init  1:off  2:off-but-connect  3:trickle  4:const curr  5:const vol):\n");
        printf("--->>> sta: %X\n", charge_get_status());    //the status of charge stage
        printf("charge enable bit: %X\n", RTCCON8 & (1 << 6));
        printf("cutoff current condition: %X\n", charge_cutoff_cur_condition());
        printf("cutoff voltage condition: %X\n", charge_cutoff_vol_condition());
        printf("trickle voltage condition: %X\n", charge_trickle_vol_condition());
    }

    if (tick_check_expire(delay_cnt2, 10)) {
        delay_cnt2 = tick_get();
        charge_process();
    }
}
