/*
  剩余电量算法。
  通过电压值计算剩余电量。
*/

#include "capacity.h"

/* USER INCLUDE BEGIN */

/* USER INCLUDE END */

/* USER DEFINE BEGIN */

/* USER DEFINE END */

/**
 * @brief 通过电压计算电池剩余电量
 *
 * @param volt 电压值
 * @return float 剩余电量比例
 */
float Capacity_GetBatteryRemain(float volt) {
  float percentage;
  float volt_2 = volt * volt;
  float volt_3 = volt_2 * volt;

  if (volt < 19.5f)
    percentage = 0.0f;

  else if (volt < 21.9f)
    percentage = 0.005664f * volt_3 - 0.3386f * volt_2 + 6.765f * volt - 45.17f;

  else if (volt < 25.5f)
    percentage = 0.02269f * volt_3 - 1.654f * volt_2 + 40.34f * volt - 328.4f;

  else
    percentage = 1.0f;

  if (percentage < 0.0f)
    percentage = 0.0f;

  else if (percentage > 1.0f)
    percentage = 1.0f;

  return percentage;
}

/**
 * @brief
 *
 * @param vcap 电容电压
 * @param vbat 电池电压
 * @param v_cutoff 截止电压
 * @return float 电容剩余电量比例
 */
float Capacity_GetCapacitorRemain(float vcap, float vbat, float v_cutoff) {
  float percentage = (vcap - v_cutoff) / (vbat - v_cutoff);

  if (percentage < 0.0f)
    percentage = 0.0f;

  else if (percentage > 1.0f)
    percentage = 1.0f;

  return percentage;
}

/* USER FUNCTION BEGIN */

/* USER FUNCTION END */
