/**
  ******************************************************************************
  * @file    Project/STM32F10x_StdPeriph_Template/stm32f10x_it.c 
  * @author  MCD Application Team
  * @version V3.2.0
  * @date    03/01/2010
  * @brief   Main Interrupt Service Routines.
  *          This file provides template for all exceptions handler and 
  *          peripherals interrupt service routine.
  ******************************************************************************
  * @copy
  *
  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
  *
  * <h2><center>&copy; COPYRIGHT 2010 STMicroelectronics</center></h2>
  */ 

/* Includes ------------------------------------------------------------------*/
#include "stm32f10x_it.h"
#include "stm32f10x.h"
#include "main.h"
#include "common.h"

extern int delay_time;
extern unsigned int tick1ms;
extern unsigned char ledstat;
extern uint8_t Host_Rx_Buffer[];
extern uint8_t RFID_Rx_Buffer[];
int i=0;
char Prescaler_tab[]={RCC_SYSCLK_Div1,RCC_SYSCLK_Div2,RCC_SYSCLK_Div4};

/** @addtogroup STM32F10x_StdPeriph_Template
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/******************************************************************************/
/*            Cortex-M3 Processor Exceptions Handlers                         */
/******************************************************************************/

/**
  * @brief   This function handles NMI exception.
  * @param  None
  * @retval None
  */
void NMI_Handler(void)
{
#ifdef _CSS
	  /* This interrupt is generated when HSE clock fails */

	  if (RCC_GetITStatus(RCC_IT_CSS) != RESET)
	  {/* At this stage: HSE, PLL are disabled (but no change on PLL config) and HSI
	       is selected as system clock source */

	    /* Enable HSE */
	    RCC_HSEConfig(RCC_HSE_ON);

	    /* Enable HSE Ready interrupt */
	    RCC_ITConfig(RCC_IT_HSERDY, ENABLE);

	    /* Clear Clock Security System interrupt pending bit */
	    RCC_ClearITPendingBit(RCC_IT_CSS);

	    /* Once HSE clock recover, the HSERDY interrupt is generated and in the RCC ISR
	       routine the system clock will be reconfigured to its previous state (before
	       HSE clock failure) */
	  }
#endif
}

/**
  * @brief  This function handles Hard Fault exception.
  * @param  None
  * @retval None
  */
void HardFault_Handler(void)
{
  /* Go to infinite loop when Hard Fault exception occurs */
  while (1)
  {
  }
}

/**
  * @brief  This function handles Memory Manage exception.
  * @param  None
  * @retval None
  */
void MemManage_Handler(void)
{
  /* Go to infinite loop when Memory Manage exception occurs */
  while (1)
  {
  }
}

/**
  * @brief  This function handles Bus Fault exception.
  * @param  None
  * @retval None
  */
void BusFault_Handler(void)
{
  /* Go to infinite loop when Bus Fault exception occurs */
  while (1)
  {
  }
}

/**
  * @brief  This function handles Usage Fault exception.
  * @param  None
  * @retval None
  */
void UsageFault_Handler(void)
{
  /* Go to infinite loop when Usage Fault exception occurs */
  while (1)
  {
  }
}

/**
  * @brief  This function handles SVCall exception.
  * @param  None
  * @retval None
  */
void SVC_Handler(void)
{
}

/**
  * @brief  This function handles Debug Monitor exception.
  * @param  None
  * @retval None
  */
void DebugMon_Handler(void)
{
}

/**
  * @brief  This function handles PendSVC exception.
  * @param  None
  * @retval None
  */
void PendSV_Handler(void)
{
}

/**
  * @brief  This function handles SysTick Handler.
  * @param  None
  * @retval None
  */
void SysTick_Handler(void)
{
	delay_time--;
	tick1ms++;
}

/******************************************************************************/
/*                 STM32F10x Peripherals Interrupt Handlers                   */
/*  Add here the Interrupt Handler for the used peripheral(s) (PPP), for the  */
/*  available peripheral interrupt handler's name please refer to the startup */
/*  file (startup_stm32f10x_xx.s).                                            */
/******************************************************************************/

/**
  * @brief  This function handles RCC interrupt request.
  * @param  None
  * @retval None
  */
void RCC_IRQHandler(void)
{
#ifdef _CSS

/* When we have HSE ready */
  if(RCC_GetITStatus(RCC_IT_HSERDY) != RESET)
  {
    /* Clear HSERDY interrupt pending bit */
    //RCC_ClearITPendingBit(?????);

    /* Check if the HSE clock is still available */
    if (RCC_GetFlagStatus(RCC_FLAG_HSERDY) != RESET)
    {
      /* Enable PLL */
      //?????

	  /* Enable PLL Ready interrupt */
	  //?????
    }
  }
/* When we have PLL ready */
  if(RCC_GetITStatus(RCC_IT_PLLRDY) != RESET)
  {
    /* Clear PLLRDY interrupt pending bit */
    RCC_ClearITPendingBit(RCC_IT_PLLRDY);

    /* Check if the PLL is still locked */
    if (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) != RESET)
    {
      /* Select PLL as system clock source */
      //RCC_SYSCLKConfig(?????);
    }
  }
#endif

}


void TIM2_IRQHandler(void)
{


if(ledstat & RED_LED_BLINK_STAT)
	RED_LED_TOGGLE();
if(ledstat & RED_LED_TOFF_STAT){
	LED_R_PORT->BSRR = LED_R_PIN;
	ledstat = ledstat & (~RED_LED_TOFF_STAT);
	TIM2->CNT = 57000;
	ledstat |= RED_LED_PULSED_STAT;
	if(ledstat & GREEN_LED_BLINK_STAT) LED_G_PORT->BRR = LED_G_PIN;

	}
else if(ledstat & RED_LED_PULSED_STAT  ){
	LED_R_PORT->BRR = LED_R_PIN;
	ledstat = ledstat & (~RED_LED_PULSED_STAT);
	}

if(ledstat & GREEN_LED_BLINK_STAT && (!(ledstat & RED_LED_PULSED_STAT)))
	GREEN_LED_TOGGLE();

if(ledstat & (GREEN_LED_TOFF_STAT)){

	LED_G_PORT->BSRR = LED_G_PIN;
	ledstat = ledstat & (~GREEN_LED_TOFF_STAT);
	TIM2->CNT = 57000;
	ledstat |= GREEN_LED_PULSED_STAT;
	if(ledstat & RED_LED_BLINK_STAT) LED_R_PORT->BRR = LED_R_PIN;
	}
else if((ledstat & GREEN_LED_PULSED_STAT)){
	LED_G_PORT->BRR = LED_G_PIN;
	ledstat = ledstat & (~GREEN_LED_PULSED_STAT);
}



TIM_ClearITPendingBit(TIM2,TIM_IT_Update);

}

void USART1_IRQHandler(void)
{
        uint8_t data = 0;
        static uint8_t state=0;
        static uint16_t checksum,lenghth,CmdPos=0;

RED_LED_TOGGLE();
        if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
        {

                data = USART_ReceiveData(HOST_UART);
                        	switch (state){

                        	case 0 : //Waiting the first packet byte
                        		if(Host_Com_Stat)
                        		HOST_COM_OVERFLOW();
                        		else if(data==BORDER_P) state=1;
                        		lenghth=0;
                        	break;
                        	case 1 : //Waiting checksum high byte
                        		lenghth =(uint16_t) (((data)<<8)&0xFF00);
                        		state = 2;
                        	break;
                        	case 2 :
                        		lenghth += data;
                        		if(lenghth>HOST_MAX_PACKET_SIZE){
                        			HOST_COM_PACKERR();
                        			state=0;
                        		}
                        		else{
                        			state = 3;
                        			CmdPos=0;
                        		}
                        	break;
                        	case 3 :

									Host_Rx_Buffer[CmdPos++]=data;
									if(CmdPos<=(lenghth-2))
									checksum += data;


									if((CmdPos) >= lenghth){
										if(checksum != ((uint16_t)(((Host_Rx_Buffer[CmdPos-2]<<8)&0xFF00)|(Host_Rx_Buffer[CmdPos-1])))){
														HOST_COM_CHECKSUMERR();
														state=0;
													}
													else {
														HOST_COM_RECEIVED();
														state=0;
													}
										checksum=0;
									}
                        	break;
                        	}


        }

        if(USART_GetITStatus(USART1, USART_IT_TXE) != RESET)
        {

        	    /* Write one byte to the transmit data register */
        	    USART_SendData(USART1, 'o');




        }

}

void UART5_IRQHandler(void)
{
		static uint8_t cnt=0;
		if(!(STATUS_GET(STAT_RFID_READ))){
			RFID_Rx_Buffer[cnt++] = USART_ReceiveData(RFID_UART);
			if(cnt == 12){ STATUS_SET(STAT_RFID_READ);
			cnt=0;
			}
		}
		USART_ClearITPendingBit(RFID_UART,USART_IT_RXNE);
}

void ADC1_IRQHandler(void){

	GPIO_SetBits(BATT_POWER_EN_PORT,BATT_POWER_EN_PIN);

	if((ADC1->JDR1)>BACKUP_OFF_THRESHOLD){
		GPIO_ResetBits(BATT_POWER_EN_PORT,BATT_POWER_EN_PIN);
		ADC_AnalogWatchdogThresholdsConfig(ADC1, 0x0FFF, BACKUP_ON_THRESHOLD);
		STATUS_RESET(STAT_BATTERY_POWERED);
	}
	else{
		ADC_AnalogWatchdogThresholdsConfig(ADC1, BACKUP_OFF_THRESHOLD, 0x0000);
		STATUS_SET(STAT_BATTERY_POWERED);
	}

	ADC_ClearITPendingBit(ADC1, ADC_IT_AWD);

}
/*
void USART2_IRQHandler(void)
{
        uint8_t data = 0;
        static uint8_t CmdPos=0;
        static uint8_t state=0;
        if(USART_GetITStatus(FPR_UART, USART_IT_RXNE) != RESET)
        {
        	data = USART_ReceiveData(FPR_UART);
        	switch (state){

        	case 0 :
        		if(data==BORDER_P) state=1;
        	break;
        	case 1 :
        		if(data==0x07) state=2;
        		else if(data == BORDER_P) state = 1;
        		else state = 0;
        	break;
        	case 2 :
        		if(data == BORDER_P){
        			CmdPos=0;
        			state=0;
        		}
        		else
        			FPR_Rx_Buffer[CmdPos++]=data;

        		break;
        	}

        }

        if(USART_GetITStatus(FPR_UART, USART_IT_TXE) != RESET)
        {



        }

}
*/
void EXTI9_5_IRQHandler(){


	Statusword|=STAT_PIR_SIG;
	EXTI_ClearITPendingBit(EXTI_Line6);

}
