/*
 * PWM.c
 *
 *  Created on: 14 janv. 2019
 *      Author: e_rcluze
 */

#include "PWM.h"
#include "tim.h"
#include "gpio.h"

void PWMSetDutyCycle(uint8_t sortie, uint8_t pourcentage) {
	TIM_OC_InitTypeDef sConfigOC;

	sConfigOC.OCMode = TIM_OCMODE_PWM1;
	sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
	sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;

	sConfigOC.Pulse = PourcentageToValue(pourcentage);
	HAL_Delay(1);
	switch (sortie) {
	case S0:
		HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_3);
		break;
	case S1:
		HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_4);
		break;
	case S2:
		HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1);
		break;
	case S3:
		HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2);
		break;
	case S4:
		HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_3);
		break;
	case S5:
		HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_4);
		break;
	case S6:
		HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_1);
		break;
	case S7:
		HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_2);
		break;
	case S8:
		HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_3);
		break;
	case S9:
		HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_4);
		break;
	}
}

void PWMStart(uint8_t sortie) {
	switch (sortie) {
	case S0:
		HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_3);
		break;
	case S1:
		HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_4);
		break;
	case S2:
		HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
		break;
	case S3:
		HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
		break;
	case S4:
		HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_3);
		break;
	case S5:
		HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_4);
		break;
	case S6:
		HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1);
		break;
	case S7:
		HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_2);
		break;
	case S8:
		HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_3);
		break;
	case S9:
		HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_4);
		break;
	}
}

uint16_t PourcentageToValue(uint8_t val){
	HAL_Delay(1);
	return (uint16_t)val * PWM_MAX;
}

uint8_t PWMPourcentage(Heure *heure, Sortie *sortie){
	Heure hd,he;

	HeureAjout(hd,sortie->Demmarage,sortie->Pente);
	HeureSuppr(he,sortie->Extinxtion,sortie->Pente);

	if ((CompareHeure(*heure,sortie->Demmarage)>=0) & (CompareHeure(*heure,hd)<0)){
		return (DiffHeure(*heure,sortie->Demmarage)/sortie->Pente)*sortie->PuissanceMax;
	}
	else if ((CompareHeure(*heure,hd)>=0) &(CompareHeure(*heure,he)<=0)){
		return sortie->PuissanceMax;
	}
	else if ((CompareHeure(*heure,hd)>0) & (CompareHeure(*heure,sortie->Extinxtion)<=0)){
		return (DiffHeure(sortie->Extinxtion,*heure)/sortie->Pente)*sortie->PuissanceMax;
	}
	else{
		return 0;
	}
}
