
#include "FM_TIM.h"
#include "timeSliceOffset.h"
#include "capture.h"


static int PWM_RESOLUTION; 

/**
  * @brief  定时器初始化
  * @param  None
  * @retval None
  */
void tim_Init(void)
{
    HD_PWM_Init();
    /* 得到pwm的分辨率 */
    PWM_RESOLUTION = HAL_RCC_GetHCLKFreq() / 100000;
    // HAL_TIM_Base_Start(&htim3);
    HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_4);
    
    // HD_controlTim_Init();
    HAL_TIM_Base_Start_IT(&htim7);

    HD_taskBaseTim_Init();
    HAL_TIM_Base_Start_IT(&htim16);

    // HD_time_Init();
    // HAL_TIM_Base_Start_IT(&htim15);
}

/**
  * @brief  设置占空比的大小
  * @param  Pulse   高电平所占的数
  * @retval None
  */
void set_pwmPulse(uint32_t Pulse)
{
    if (Pulse > PWM_RESOLUTION) {
        return;
    }
    __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_4, Pulse); 
}

/**
 * @brief 停止PWM信号输出
 */
void pwm_Stop(void)
{
    // 设置PWM脉冲宽度为0， effectively停止PWM信号输出
    set_pwmPulse(0);
    // HAL_TIM_Base_Stop(&htim3);
}


/**
  * @brief  设置占空比的大小
  * @param  DutyRatio   占空比
  * @retval None
  */
void set_pwmDutyRatio(float DutyRatio)
{
    uint32_t Pulse = (int)(DutyRatio * PWM_RESOLUTION);

    set_pwmPulse(Pulse);
}

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM1 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
 /**
  * @brief  回调函数
  * @param  htim   产生中断定时器
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    /* USER CODE BEGIN Callback 0 */

    /* USER CODE END Callback 0 */
    // if (htim->Instance == TIM1) {
    //     HAL_IncTick();
    // }
    /* USER CODE BEGIN Callback 1 */

    // else if (htim->Instance == TIM7) {
    //     chargControl();
    // }
    if (htim->Instance == TIM7) {
        chargControl();
    }

    else if (htim->Instance == TIM16) {
        TimeSliceOffset_Produce();
        setTotalElectricityConsumption();
        setTotalChargCapacity();
    }

    // else if (htim->Instance == TIM15) {
    //     hw_inc_tick();
    // }

    /* USER CODE END Callback 1 */
}