/* Includes ----------------------------------------------------------------- */
#include "bsp\pwm.h"

#include <main.h>
#include <tim.h>

/* Private define ----------------------------------------------------------- */
/* Private macro ------------------------------------------------------------ */
/* Private typedef ---------------------------------------------------------- */
/* Private variables -------------------------------------------------------- */
/* Private function  -------------------------------------------------------- */
/* Exported functions ------------------------------------------------------- */
int8_t BSP_PWM_Start(BSP_PWM_Channel_t ch) {
  switch (ch) {
    case BSP_PWM_IMU_HEAT:
      HAL_TIM_PWM_Start(&htim10, TIM_CHANNEL_1);
      break;
		
		case BSP_PWM_BUZZER:
      HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_3);
      break;
  }
  return BSP_OK;
}

/*PWM 占空比设置函数  duty_cycle(0-1)*/   
int8_t BSP_PWM_Set(BSP_PWM_Channel_t ch, float duty_cycle) {
  if (duty_cycle < 0.0f) duty_cycle = 0.f;

      uint16_t pulse;
  /* 通过PWM通道对应定时器重载值和给定占空比，计算PWM周期值 */
  switch (ch) {
    case BSP_PWM_IMU_HEAT:
      pulse = (uint16_t)(duty_cycle * (float)__HAL_TIM_GET_AUTORELOAD(&htim10));
      break;
		
    case BSP_PWM_BUZZER:
      pulse = (uint16_t)(duty_cycle * (float)__HAL_TIM_GET_AUTORELOAD(&htim4));
      break;		
  }

  if (pulse > 0) {
    switch (ch) {
      case BSP_PWM_IMU_HEAT:
        __HAL_TIM_SET_COMPARE(&htim10, TIM_CHANNEL_1, pulse);
        break;
			
      case BSP_PWM_BUZZER:
        __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_3, pulse);
        break;			
    }
  } 
	else {
//    BSP_PWM_Stop(ch);
  }
  return BSP_OK;
}

int8_t BSP_PWM_Stop(BSP_PWM_Channel_t ch) {
  switch (ch) {
    case BSP_PWM_IMU_HEAT:
      HAL_TIM_PWM_Stop(&htim10, TIM_CHANNEL_1);
      break;
		
    case BSP_PWM_BUZZER:
      HAL_TIM_PWM_Stop(&htim4, TIM_CHANNEL_3);
      break;		
  }
  //关闭加热器，防止淫威定时器残留而误触发，防止加热器异常工作
  HAL_GPIO_WritePin(IMU_HEAT_PWM_GPIO_Port, IMU_HEAT_PWM_Pin, GPIO_PIN_RESET);
  return BSP_OK;
}

//蜂鸣器初始化
void Buzzer_Init(Buzzer_t* ctrl,uint16_t beep_duration,uint16_t silent_duration,float duty_cycle){
	ctrl->timer = 0;
	ctrl->state = false;
	ctrl->beep_duration = beep_duration;
	ctrl->silent_duration = silent_duration;
	ctrl->duty_cycle = duty_cycle;
}

//蜂鸣器控制函数,间断鸣叫
void Buzzer_Control(Buzzer_t* ctrl, bool condition) {
  if (condition) {
    // 鸣叫模式
    if (HAL_GetTick() - ctrl->timer >= (ctrl->state ? ctrl->beep_duration : ctrl->silent_duration)) {
       ctrl->state = !ctrl->state;
       ctrl->timer = HAL_GetTick();
            
       if (ctrl->state) {
          BSP_PWM_Start(BSP_PWM_BUZZER);
          BSP_PWM_Set(BSP_PWM_BUZZER, ctrl->duty_cycle);
       } 
			 else {
         BSP_PWM_Stop(BSP_PWM_BUZZER);
       }
    }
  } 
  else {
    // 停止鸣叫
    ctrl->state = false;
    BSP_PWM_Stop(BSP_PWM_BUZZER);
  }
}
