#include "FanControl.h"

#include "stm32f4xx_hal_def.h"
#include "stm32f4xx_hal_tim.h"

TIM_HandleTypeDef* timer;
uint32_t channel;

HAL_StatusTypeDef fan_ctrl_init(TIM_HandleTypeDef* handle, uint32_t channel_) {
  timer = handle;
  channel = channel_;

  return HAL_TIM_PWM_Start(timer, channel);
}

void fan_ctrl_set_power(uint32_t percent) {
  if (percent > 100) {
    percent = 100;
  }

  // The PWM signal switches a low side switch, so we need to invert the duty
  // cycle.
  percent = 100 - percent;

  uint32_t counter = timer->Init.Period * percent / 100;
  __HAL_TIM_SET_COMPARE(timer, channel, counter);
}