#include "gw3323_charge.h"

// charging process parameter struct
static struct charge_status_def{
    u8 sta;
    u8 mode;
    u8 power_level;
    u8 cutoff_vol;
    u8 cutoff_cur;
    u8 const_cur;
    u8 trickle_en;
    u8 trickle_cur;
    u8 trickle_vol;
} charge_status;

// charging process control struct
static struct charge_ctrl_def{
    u8 dc_in_cnt;
    u8 trick_curr_cnt;
    u8 dc_insert;
    u32 vddio_tmp;
} charge_ctrl;

// charge cutoff status struct.
static struct charge_cutoff_ctrl_def{
    u8 curr_cnt;                // reache current condition count.
    u8 volt_cnt;                // reache voltage condition count.
} charge_cutoff_ctrl;

// sys trim struct
typedef struct {
    u16 vbg;            //VBG Voltage,  standard 600*2 mV
    u8  vbat;           //trim to 4.2V register configure       CHAGCON[4:0]
    u8  vddcore;        //trim to 1.06V register configure      PWRCON0[3:0]
    u8  vddio;          //trim to 3.3V register configure       PWRCON0[6:4]
    u8  vbko;           //trim to 1.6V register configure       RTCCONT[4:0]
    u8  vddaud;         //trim to 2.9V register configure       AUANGCON0[6:4]
    u8  bt_dgain;
    s16  dac_val;
    u8  flag;
} sys_trim_t;

extern sys_trim_t sys_trim;

u32 getcfg_buck_mode_en(void);

/**
  * @brief  Initializes the charge according to the specified
  *         parameters in the charge_init_struct.
  * @param  charge_init_struct: pointer to a charge_init_typedef structure that
  *         contains the configuration information for the charge register.
  * @retval None
  */
void charge_init(charge_init_typedef *charge_init_struct)
{
    RTCCON8 &= ~((uint32_t)(0x03 << 8));
    RTCCON8 |= (uint32_t)(charge_init_struct->cutoff_volt);

    RTCCON8 &= ~((uint32_t)(0x01 << 7));
    RTCCON8 |= (uint32_t)(charge_init_struct->trick_cutoff_volt);

    RTCCON7 &= ~((uint32_t)(0x07 << 11));
    RTCCON7 |= (uint32_t)(charge_init_struct->cutoff_curr);

    RTCCON &= ~((uint32_t)(0x01 << 6));
    RTCCON |= (uint32_t)charge_init_struct->dcin_reset;

    RTCCON8 &= ~((uint32_t)(0x1f << 10));
    RTCCON8 |= (uint32_t)(0x08 << 10);

    // set charge current when power up.
    RTCCON7 &= ~(0x0f << 4);
    RTCCON7 |= (0x02 << 4);

    // set VUSB leakage current.
    RTCCON8 &= ~(0x07 << 16);
    RTCCON8 |= (0x02 << 16);

    memset(&charge_ctrl, 0, sizeof(struct charge_ctrl_def));
    memset(&charge_status, 0, sizeof(struct charge_status_def));
    memset(&charge_cutoff_ctrl, 0, sizeof(struct charge_cutoff_ctrl_def));

    // storage the configure value of charge.
    charge_status.trickle_en = charge_init_struct->trick_curr_en;
    charge_status.const_cur = charge_init_struct->const_curr;
    charge_status.trickle_cur = charge_init_struct->trick_curr;
    charge_status.mode = charge_init_struct->mode;
    charge_status.power_level = 100;

    // set the charge initial status to CHARGE_STA_OFF.
    charge_status.sta = CHARGE_STA_OFF;
}

/**
  * @brief  process state switch during charging, this func should be called continuously
  *         during charging.
  * @param  None.
  * @retval None
  */
AT(.com_text.charge)
void charge_process(void)
{
    // exit if charge uninitial.
    if (charge_status.sta == CHARGE_STA_UNINIT) {
        return;
    }

    // detect whether DC insert and run levevant code.
    if (charge_detect_dc() != charge_ctrl.dc_insert) {
        charge_ctrl.dc_in_cnt++;
        if (charge_ctrl.dc_in_cnt > 5) {
            charge_ctrl.dc_insert = charge_detect_dc();
            charge_ctrl.dc_in_cnt = 0;
            if (charge_ctrl.dc_insert == ENABLE) {
                RTCCON8 |= BIT(6);
                RTCCON8 &= ~BIT(1);
            }
        }
    } else {
        charge_ctrl.dc_in_cnt = 0;
    }

    if (charge_ctrl.dc_insert) {
        charge_insert_dc();
    } else {
        if (charge_status.sta != CHARGE_STA_OFF) {
            charge_status_update(CHARGE_STA_OFF);
        }
    }
}

/**
  * @brief  Process event when VUSB insert.
  * @param  None.
  * @retval None
  */
AT(.com_text.charge)
void charge_insert_dc(void)
{
    // if the charging is not begin.
    if (charge_status.sta == CHARGE_STA_OFF) {
        if (charge_status.trickle_en == DISABLE || (PWRCON1 & (1 << 29)) != RESET) {    // trickle disable or battery lower then 2.9V
            charge_status_update(CHARGE_STA_ON_CON_CURR);        // constant current charging.
        } else {
            charge_status_update(CHARGE_STA_ON_TRICKLE);        // trickle current charging.
        }
    // if the charging is begin.
    } else if (charge_status.sta == CHARGE_STA_ON_TRICKLE) {
        if ((PWRCON1 & (1 << 29)) != RESET) {
            charge_ctrl.trick_curr_cnt++;
        } else {
            charge_ctrl.trick_curr_cnt = 0;
        }

        if (charge_ctrl.trick_curr_cnt > 10) {
            charge_status_update(CHARGE_STA_ON_CON_CURR);
        }
    } else if (charge_status.sta > CHARGE_STA_ON_TRICKLE && charge_detect_off_condition()) {
        charge_status_update(CHARGE_STA_OFF_VBUS_PATH);
        if (charge_status.mode == CHARGE_MODE_FULL_DISCONNECT) {
            RTCCON8 &= ~BIT(6);
            RTCCON8 |= BIT(1);
        }
    }
}

/**
  * @brief  Update the charging status if needed, and perform relevant configuration.
  * @param  status: the charging status that need to update.
  *         this parameter can be one of the following values:
  *             @arg CHARGE_STA_UNINIT: charge parameter uninitialized flag.
  *             @arg CHARGE_STA_OFF: charge off flag.
  *             @arg CHARGE_STA_OFF_VBUS_PATH: charge off but VUSB still insert flag.
  *             @arg CHARGE_STA_ON_TRICKLE: charge on trickle stage flag.
  *             @arg CHARGE_STA_ON_CON_CURR: charge on const current stage flag.
  *             @arg CHARGE_STA_ON_CON_VOL: charge on const voltage stage flag.
  * @retval None
  */
AT(.com_text.charge)
void charge_status_update(u8 status)
{
    u32 reg_tmp;

    if (status == CHARGE_STA_OFF) {
        charge_status.sta = CHARGE_STA_OFF;
        PWRCON0 &= ~(0x0f << 4);
        PWRCON0 |= (charge_ctrl.vddio_tmp << 4);
        RTCCON8 &= ~(1 << 0);
        set_buck_mode(getcfg_buck_mode_en());
    } else if (status == CHARGE_STA_OFF_VBUS_PATH) {
        charge_status.sta = CHARGE_STA_OFF_VBUS_PATH;
    } else if (status == CHARGE_STA_ON_TRICKLE || status == CHARGE_STA_ON_CON_CURR) {
        set_buck_mode(0);
        RTCCON8 |= (1 << 0);

        RTCCON8 &= ~(0x03 << 2);
        RTCCON8 |= (0x03 << 2);

        reg_tmp = RTCCON7;

        charge_ctrl.vddio_tmp = (PWRCON0 >> 4) & 0x0f;

        reg_tmp &= ~(uint32_t)0x0f;

        if (status == CHARGE_STA_ON_TRICKLE) {
            charge_status.sta = CHARGE_STA_ON_TRICKLE;

            RTCCON8 &= ~(0x03 << 2);
            RTCCON8 |= (0x01 << 2);

            if (sys_trim.vddio < 8) {
                PWRCON0 &= ~(0x0f << 4);
                PWRCON0 |= (0 << 4);
            } else {
                PWRCON0 &= ~(0x0f << 4);
                PWRCON0 |= ((sys_trim.vddio - 8) << 4);
            }
        } else {
            charge_status.sta = CHARGE_STA_ON_CON_CURR;

            RTCCON8 &= ~(0x03 << 2);
            RTCCON8 |= (0x03 << 2);

            PWRCON0 &= ~(0x0f << 4);
            PWRCON0 |= ((sys_trim.vddio - 3) << 4);
            reg_tmp |= charge_status.const_cur;
        }

        RTCCON7 = reg_tmp;
        memset(&charge_cutoff_ctrl, 0, sizeof(struct charge_cutoff_ctrl_def));
        RTCCON8 &= ~(1 << 1);
    } else if (status == CHARGE_STA_ON_CON_VOL) {
        charge_status.sta = CHARGE_STA_ON_CON_VOL;
    }
}

/**
  * @brief  detect charge off condition and enter const voltage stage condition.
  * @param  None.
  * @retval true or false that can stop charge.
  */
AT(.com_text.charge)
bool charge_detect_off_condition(void)
{
    // judge if the charging current lower then setting val.
    if ((PWRCON1 & (1 << 30)) != RESET) {
        if (charge_cutoff_ctrl.curr_cnt >= 100) {
            return true;
        }   else {
            charge_cutoff_ctrl.curr_cnt++;
        }
    } else {
        charge_cutoff_ctrl.curr_cnt = 0;
    }

    // judge if the charging voltage higher then setting val.
    if ((PWRCON1 & (1 << 28)) != RESET) {
        if (charge_cutoff_ctrl.volt_cnt >= 100) {
            if (charge_status.sta != CHARGE_STA_ON_CON_VOL) {
                charge_status_update(CHARGE_STA_ON_CON_VOL);
                charge_cutoff_ctrl.curr_cnt = 0;                // Re count current.
            }
        } else {
            charge_cutoff_ctrl.volt_cnt++;
        }
    } else {
        charge_cutoff_ctrl.volt_cnt = 0;
    }

    return false;
}

/**
  * @brief  Update the charging status if needed, and perform relevant configuration.
  * @param  None.
  * @retval the status of charge stage. the value will be one in the CHARGE_STATUS_TYPEDEF.
  */
AT(.com_text.charge)
u8 charge_get_status(void) {
    return charge_status.sta;
}

/**
  * @brief  select the event to do when charge is finish.
  * @param  mode: charge mode.
  *         this parameter can be one of the following values:
  *             @arg CHARGE_MODE_FULL_KEEP: keep VUSB connect when charge finish.
  *             @arg CHARGE_MODE_FULL_DISCONNECT: disconnect VUSB when charge finish.
  * @retval None
  */
AT(.com_text.charge)
void charge_change_mode(u8 mode)
{
    if (mode == CHARGE_MODE_FULL_DISCONNECT) {
        charge_status.mode = CHARGE_MODE_FULL_DISCONNECT;
    } else if (mode == CHARGE_MODE_FULL_KEEP) {
        charge_status.mode = CHARGE_MODE_FULL_KEEP;
    }
}

/**
  * @brief  get current percentage battery level.
  * @param  mode: type of returned value selected. when it's 0,
  *         that will return battery level, else return voltage value.
  * @retval percentage of battery level or voltage value.
  */
uint16_t charge_get_level(u8 mode)
{
    u8 i = 0, loop = 5;
    u32 adc_val, adc_val_total = 0;
    u32 adc_vbg, adc_vbg_total = 0;
    u32 voltage;
    u16 bat_off;
    u8 current_power;

    while (i < loop) {
        sadc_kick_start(BIT(ADCCH_VBAT) | BIT(ADCCH_BGOP), 0);
        while (!sadc_get_flag(SADC_FLAG_PENDING));
        adc_val_total += sadc_get_data(ADCCH_VBAT) >> 2;
        adc_vbg_total += sadc_get_data(ADCCH_BGOP) >> 2;

        i++;
    }
    adc_val = adc_val_total / loop;
    adc_vbg = adc_vbg_total / loop;
    voltage = adc_val * 1500 / adc_vbg;

    if (mode == 0) {
        bat_off = LPWR_OFF_VBAT * 100 + 2700;
        if (bat_off > voltage) {
            return 0;
        }
        current_power = charge_status.power_level * (voltage - bat_off) / (4200 - bat_off);
        return (current_power > 100? 100: current_power);
    } else {
        return voltage;
    }
}

/**
  * @brief  Config the number of battery level.
  * @param  level: the number of battery level.
  * @retval None
  */
void charge_power_level_config(u8 level)
{
    if (level > 0) {
        charge_status.power_level = level;
    }
}

/**
  * @brief  get state VUSB insert.
  * @param  None.
  * @retval VUSB insertion statue.
  */
AT(.com_text.charge)
FUNCTIONAL_STATE charge_detect_dc(void)
{
    if ((RTCCON >> 20) & 0x01) {
        return ENABLE;
    } else {
        return DISABLE;
    }
}

/**
  * @brief  Judge if the charging current reach the cutoff current.
  * @param  None.
  * @retval the condition SET of RESET.
  */
AT(.com_text.charge)
FLAG_STATE charge_cutoff_cur_condition(void)
{
    if ((PWRCON1 & (1 << 30)) != RESET) {
        return SET;
    } else {
        return RESET;
    }
}

/**
  * @brief  Judge if the charging voltage reach the cutoff voltage.
  * @param  None.
  * @retval the condition SET of RESET.
  */
AT(.com_text.charge)
FLAG_STATE charge_cutoff_vol_condition(void)
{
    if ((PWRCON1 & (1 << 28)) != RESET) {
        return SET;
    } else {
        return RESET;
    }
}

/**
  * @brief  Judge if the charging voltage reach the trickle voltage.
  * @param  None.
  * @retval the condition SET of RESET.
  */
AT(.com_text.charge)
FLAG_STATE charge_trickle_vol_condition(void)
{
    if ((PWRCON1 & (1 << 29)) != RESET) {
        return SET;
    } else {
        return RESET;
    }
}

