#include "fan_pwm.h"

void fan_pwm_init(void){
	tmr_output_config_type tmr_oc_init_structure;

	/* compute the div value */
	u16 div_value = (uint16_t)(system_core_clock / 1000000) - 1;
	
	/* tmr3 time base configuration */
	tmr_base_init(FAN_PWM_TIMER, FAN_MAX_DUTY_COUNT, div_value);
	tmr_cnt_dir_set(FAN_PWM_TIMER, TMR_COUNT_UP);
	tmr_clock_source_div_set(FAN_PWM_TIMER, TMR_CLOCK_DIV1);

	tmr_output_default_para_init(&tmr_oc_init_structure);
	tmr_oc_init_structure.oc_mode = TMR_OUTPUT_CONTROL_PWM_MODE_A;
	tmr_oc_init_structure.oc_idle_state = FALSE;
	tmr_oc_init_structure.oc_polarity = TMR_OUTPUT_ACTIVE_HIGH;
	tmr_oc_init_structure.oc_output_state = TRUE;
	tmr_output_channel_config(FAN_PWM_TIMER, FAN_PWM_CHAN, &tmr_oc_init_structure);
	tmr_channel_value_set(FAN_PWM_TIMER, FAN_PWM_CHAN, FAN_MAX_DUTY_COUNT-1);
	tmr_output_channel_buffer_enable(FAN_PWM_TIMER, FAN_PWM_CHAN, TRUE);

	tmr_period_buffer_enable(FAN_PWM_TIMER, TRUE);

	tmr_output_enable(FAN_PWM_TIMER, FALSE);
	
	/* tmr enable counter */
	tmr_counter_enable(FAN_PWM_TIMER, TRUE);
}


void fan_stop(void) {
	tmr_counter_enable(FAN_PWM_TIMER, FALSE);
}

void fan_set_duty(u8 duty) {
	if (duty > 100) {
		duty = 100;
	}else if (duty > 0 && duty < 30) {
		duty = 30;
	}
	u32 count = (float)duty * (float)FAN_MAX_DUTY_COUNT / 100.0f;
	tmr_channel_value_set(FAN_PWM_TIMER,FAN_PWM_CHAN, count);
	if (count == 0) {
		tmr_output_enable(FAN_PWM_TIMER,FALSE);
	}else {
		tmr_output_enable(FAN_PWM_TIMER,TRUE);
	}
}


bool fan_pwm_is_running(void) {
	if (FAN_PWM_TIMER->ctrl1_bit.tmren == TRUE) {
		return true;
	}
	return false;
}

