#include "fan_pwm.h"

void fan_pwm_init(void){
	uint16_t chno = FAN_PWM_CHAN;
	TIM_TimeBaseInitType TIM_TimeBaseStructure;
	OCInitType TIM_OCInitStructure;

	TIM_InitTimBaseStruct(&TIM_TimeBaseStructure);
    /* Time base configuration */
    TIM_TimeBaseStructure.Period    = FAN_MAX_DUTY_COUNT;
    TIM_TimeBaseStructure.Prescaler = TIM_CLOCK_MHz - 1;
    TIM_TimeBaseStructure.ClkDiv    = 0;
    TIM_TimeBaseStructure.CntMode   = TIM_CNT_MODE_UP;

    TIM_InitTimeBase(FAN_PWM_TIMER, &TIM_TimeBaseStructure);

    /* PWM1 Mode configuration: Channel1 */
    TIM_OCInitStructure.OcMode      = TIM_OCMODE_PWM1;
    TIM_OCInitStructure.OutputState = TIM_OUTPUT_STATE_ENABLE;
    TIM_OCInitStructure.Pulse       = FAN_MAX_DUTY_COUNT-1;
    TIM_OCInitStructure.OcPolarity  = TIM_OC_POLARITY_HIGH;
	if (chno == TIM_CH_1) {
		TIM_InitOc1(FAN_PWM_TIMER, &TIM_OCInitStructure);
	}else if (chno == TIM_CH_2) {
		TIM_InitOc2(FAN_PWM_TIMER, &TIM_OCInitStructure);
	}else if (chno == TIM_CH_3) {
		TIM_InitOc3(FAN_PWM_TIMER, &TIM_OCInitStructure);
	}else if (chno == TIM_CH_4) {
		TIM_InitOc4(FAN_PWM_TIMER, &TIM_OCInitStructure);
	}

    TIM_ConfigOc1Preload(FAN_PWM_TIMER, TIM_OC_PRE_LOAD_ENABLE);

    TIM_ConfigArPreload(FAN_PWM_TIMER, ENABLE);

    /* TIM3 enable counter */
    TIM_Enable(FAN_PWM_TIMER, ENABLE);

}


void fan_stop(void) {
	TIM_Enable(FAN_PWM_TIMER, DISABLE);
}

void fan_set_duty(u8 duty) {
	uint16_t chno = FAN_PWM_CHAN;
	if (duty > 100) {
		duty = 100;
	}else if (duty > 0 && duty < 30) {
		duty = 30;
	}
	u32 count = (float)duty * (float)FAN_MAX_DUTY_COUNT / 100.0f;
	if (chno == TIM_CH_1) {
		TIM_SetCmp1(FAN_PWM_TIMER, count);
	}else if (chno == TIM_CH_2) {
		TIM_SetCmp2(FAN_PWM_TIMER, count);
	}else if (chno == TIM_CH_3) {
		TIM_SetCmp3(FAN_PWM_TIMER, count);
	}else if (chno == TIM_CH_4) {
		TIM_SetCmp4(FAN_PWM_TIMER, count);
	}
	if (FAN_PWM_TIMER == TIM8) {
		if (count == 0) {
			TIM_EnableCtrlPwmOutputs(FAN_PWM_TIMER, DISABLE);
		}else {
			TIM_EnableCtrlPwmOutputs(FAN_PWM_TIMER, ENABLE);
		}
	}
}


bool fan_pwm_is_running(void) {
	uint16_t chno = FAN_PWM_CHAN;
	u32 count = 0;
	if (chno == TIM_CH_1) {
		count = TIM_GetCap1(FAN_PWM_TIMER);
	}else if (chno == TIM_CH_2) {
		count = TIM_GetCap2(FAN_PWM_TIMER);
	}else if (chno == TIM_CH_3) {
		count = TIM_GetCap3(FAN_PWM_TIMER);
	}else if (chno == TIM_CH_4) {
		count = TIM_GetCap4(FAN_PWM_TIMER);
	}
	return (count != 0);
}

