#include "fan.h"
#include "tim.h"

#define FANTOUT 0
#define FAN1	1
#define FAN2	2
#define FAN3	3

uint8_t Fan_Pow(uint8_t NFan, uint8_t Value) {
	TIM_OC_InitTypeDef sConfigOC;
	switch (Value) {
	//La valeur du PWM est inverse a la vitesse de rotation des ventilateurs (PWMMAX => ventilateur arreter)
	case (FANSTOP):
		sConfigOC.Pulse = PWM_MAX;
		break;
	case (FAN25):
		sConfigOC.Pulse = PWM75;
		break;
	case (FAN50):
		sConfigOC.Pulse = PWM50;
		break;
	case (FAN75):
		sConfigOC.Pulse = PWM25;
		break;
	case (FAN100):
		sConfigOC.Pulse = 0;
		break;
	default:
		return -1; //erreur
	}
	switch (NFan) {
	case (FANTOUT):
		HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);
		HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1);
		HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2);
		HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
		HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
		HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
		break;
	case (FAN1):
		HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);
		HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
		break;
	case (FAN2):
		HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1);
		HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
		break;
	case (FAN3):
		HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2);
		HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
		break;
	default:
		return -1; //erreur
	}
	return 0;
}

uint8_t FanSatus(uint8_t NFan) {
	uint32_t pulse;
	switch (NFan) {
	case (FAN1):
		pulse = htim2.Instance->CCR1;
		break;
	case (FAN2):
		pulse = htim3.Instance->CCR1;
		break;
	case (FAN3):
		pulse = htim3.Instance->CCR2;
		break;
	default:
		return -1; ////todo (ORDINATEUR AMELIORATION) error
	}
	if (pulse == PWM_MIN)
		return FANSTOP;
	else if (pulse == PWM75)
		return FAN75;
	else if (pulse == PWM50)
		return FAN50;
	else if (pulse == PWM25)
		return FAN25;
	else if (pulse == PWM_MAX)
		return FAN100;
	else
		return -1; ////todo (ORDINATEUR AMELIORATION) error
}
