/*
 * Modbus_timer.c
 *
 *  Created on: 8. 3. 2020
 *      Author: Ondrej Vitoslavsky
 */


#include "Modbus.h"
#include "Modbus_RTU.h"
#include "Modbus_periph.h"

TIM_HandleTypeDef htim3;
TIM_HandleTypeDef htim4;


void Modbus_Timers_Init( uint16_t Timer_35_value, uint16_t Timer_15_value  ){

	uint16_t PrescalerValue = 0;

	__TIM3_CLK_ENABLE();


	SystemCoreClockUpdate();
	PrescalerValue = (uint16_t)((SystemCoreClock/2)/20000)-1;

	//timer 3.5
	htim3.Instance = MODBUS_TIMER_35;
	htim3.Init.Period = Timer_35_value-1;
	htim3.Init.Prescaler = PrescalerValue;
	htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
	htim3.Init.CounterMode = TIM_COUNTERMODE_UP;

	if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
	{
		Error_Handler();
	}

	HAL_NVIC_SetPriority(MODBUS_TIMER_35_IRQn, 0, 0);
	HAL_NVIC_EnableIRQ(MODBUS_TIMER_35_IRQn);


	__HAL_TIM_CLEAR_IT(&htim3, TIM_IT_UPDATE );
	HAL_TIM_Base_Stop_IT(&htim3);


	//timer 1.5
	__TIM4_CLK_ENABLE();

	htim4.Instance = MODBUS_TIMER_15;
	htim4.Init.Period = Timer_15_value-1;
	htim4.Init.Prescaler = PrescalerValue;
	htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
	htim4.Init.CounterMode = TIM_COUNTERMODE_UP;

	if (HAL_TIM_Base_Init(&htim4) != HAL_OK)
	{
		Error_Handler();
	}

	HAL_NVIC_SetPriority(MODBUS_TIMER_15_IRQn, 0, 0);
	HAL_NVIC_EnableIRQ(MODBUS_TIMER_15_IRQn);


	__HAL_TIM_CLEAR_IT(&htim4, TIM_IT_UPDATE );
	HAL_TIM_Base_Stop_IT(&htim4);

}


void Modbus_Timers_Enable(uint8_t Timer_35, uint8_t Timer_15)
{
		__disable_irq();

		//timer 3.5
		if(Timer_35){
			__HAL_TIM_SET_COUNTER(&htim3, 0);
			HAL_TIM_Base_Start_IT(&htim3);
		}


		//timer 1.5
		if(Timer_15){
			__HAL_TIM_SET_COUNTER(&htim4, 0);
			HAL_TIM_Base_Start_IT(&htim4);
		}

		__enable_irq();
}

void Modbus_Timers_Disable(uint8_t Timer_35, uint8_t Timer_15)
{
	//timer 3.5
	if(Timer_35) HAL_TIM_Base_Stop_IT(&htim3);
	//timer 1.5
	if(Timer_15) HAL_TIM_Base_Stop_IT(&htim4);
}




void TIM3_IRQHandler( void )
{
	if (__HAL_TIM_GET_IT_SOURCE(&htim3, TIM_IT_UPDATE) != RESET)
  {
		__HAL_TIM_CLEAR_FLAG(&htim3,  TIM_IT_UPDATE | TIM_IT_CC1 | TIM_IT_CC2 | TIM_IT_CC3 | TIM_IT_CC4 );

		Modbus_RTU_Timer35_Expired();
	}

}

void TIM4_IRQHandler( void )
{
	if (__HAL_TIM_GET_IT_SOURCE(&htim4, TIM_IT_UPDATE) != RESET)
  {
		__HAL_TIM_CLEAR_FLAG(&htim4,  TIM_IT_UPDATE | TIM_IT_CC1 | TIM_IT_CC2 | TIM_IT_CC3 | TIM_IT_CC4 );

		Modbus_RTU_Timer15_Expired();
	}

}
