/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    stm32f1xx_it.c
  * @brief   Interrupt Service Routines.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f1xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <string.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */

/* USER CODE END TD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
volatile uint16_t blue_led_blink	= 0;
volatile uint16_t red_led_blink 	= 0;
volatile uint16_t green_led_blink = 0;
volatile uint16_t Emergency_stop_count = 0, GFD_stop_count = 0;
volatile uint16_t buzzer_enable_time = 0;
volatile char buzzer_enable;

extern volatile char alarm;

extern char chargingStart, chargingStop;

uint8_t id[15];


// Added by Nihar
extern uint8_t rxchar;
extern uint8_t rxbuff[100];
extern uint8_t startFrame;
extern int cmdrxd;
extern uint8_t configmode;

extern struct rfid_data rfid;		// Added by Nihar

/*
char rfid1[13]={'4','2','0','0','1','5','8','9','6','A','B','4'};
char rfid2[13]={'4','2','0','0','1','5','8','B','6','C','B','0'};
char rfid3[13]={'4','2','0','0','1','5','E','3','0','0','B','4'};
*/


uint8_t Authentication_done = 0;
uint8_t Type2_OCPP_Authorization_Flag = 0;

char uart_rxFlag	= 0;
char lclflagLED		= 0;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* External variables --------------------------------------------------------*/
extern DMA_HandleTypeDef hdma_adc1;
extern TIM_HandleTypeDef htim1;
extern DMA_HandleTypeDef hdma_usart1_rx;
extern DMA_HandleTypeDef hdma_usart3_rx;
extern DMA_HandleTypeDef hdma_usart3_tx;
extern UART_HandleTypeDef huart1;
/* USER CODE BEGIN EV */
extern UART_HandleTypeDef huart1;

extern UART_HandleTypeDef huart3;
//extern uint8_t PWM_DutyCycle;
extern char pwm_start_stop;
extern uint8_t CURRENT_STATE;
extern volatile int16_t timer123;
extern volatile uint8_t Emergency_stop, GFD_stop;

void adc_check(void);

/* USER CODE END EV */

/******************************************************************************/
/*           Cortex-M3 Processor Interruption and Exception Handlers          */
/******************************************************************************/
/**
  * @brief This function handles Non maskable interrupt.
  */
void NMI_Handler(void)
{
  /* USER CODE BEGIN NonMaskableInt_IRQn 0 */

  /* USER CODE END NonMaskableInt_IRQn 0 */
  /* USER CODE BEGIN NonMaskableInt_IRQn 1 */

  /* USER CODE END NonMaskableInt_IRQn 1 */
}

/**
  * @brief This function handles Hard fault interrupt.
  */
void HardFault_Handler(void)
{
  /* USER CODE BEGIN HardFault_IRQn 0 */

  /* USER CODE END HardFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_HardFault_IRQn 0 */
  //   HAL_
    /* USER CODE END W1_HardFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Memory management fault.
  */
void MemManage_Handler(void)
{
  /* USER CODE BEGIN MemoryManagement_IRQn 0 */

  /* USER CODE END MemoryManagement_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
    /* USER CODE END W1_MemoryManagement_IRQn 0 */
  }
}

/**
  * @brief This function handles Prefetch fault, memory access fault.
  */
void BusFault_Handler(void)
{
  /* USER CODE BEGIN BusFault_IRQn 0 */

  /* USER CODE END BusFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_BusFault_IRQn 0 */
    /* USER CODE END W1_BusFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Undefined instruction or illegal state.
  */
void UsageFault_Handler(void)
{
  /* USER CODE BEGIN UsageFault_IRQn 0 */

  /* USER CODE END UsageFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_UsageFault_IRQn 0 */
    /* USER CODE END W1_UsageFault_IRQn 0 */
  }
}

/**
  * @brief This function handles System service call via SWI instruction.
  */
void SVC_Handler(void)
{
  /* USER CODE BEGIN SVCall_IRQn 0 */

  /* USER CODE END SVCall_IRQn 0 */
  /* USER CODE BEGIN SVCall_IRQn 1 */

  /* USER CODE END SVCall_IRQn 1 */
}

/**
  * @brief This function handles Debug monitor.
  */
void DebugMon_Handler(void)
{
  /* USER CODE BEGIN DebugMonitor_IRQn 0 */

  /* USER CODE END DebugMonitor_IRQn 0 */
  /* USER CODE BEGIN DebugMonitor_IRQn 1 */

  /* USER CODE END DebugMonitor_IRQn 1 */
}

/**
  * @brief This function handles Pendable request for system service.
  */
void PendSV_Handler(void)
{
  /* USER CODE BEGIN PendSV_IRQn 0 */

  /* USER CODE END PendSV_IRQn 0 */
  /* USER CODE BEGIN PendSV_IRQn 1 */

  /* USER CODE END PendSV_IRQn 1 */
}

/**
  * @brief This function handles System tick timer.
  */
void SysTick_Handler(void)
{
  /* USER CODE BEGIN SysTick_IRQn 0 */

	if(timer123)timer123--;
	if(blue_led_blink)blue_led_blink--;
	if(red_led_blink)red_led_blink--;
	if(green_led_blink)green_led_blink--;
	if(buzzer_enable_time)buzzer_enable_time--;

	if(!EMG_SW_READ)
	{
		Emergency_stop_count++;
		if(Emergency_stop_count >= 100)
		{
      Emergency_stop = 1;
		}
	}
	else
	{
		Emergency_stop_count = 0;
		Emergency_stop = 0;
	}

	if (rfid.GFDBypassEn == 1)		// IF GFD ENABLE
	{
		if(GFD_READ)
		{
			GFD_stop_count++;
			if(GFD_stop_count >= 100)
			{
				GFD_stop_count = 0;
				GFD_stop = 1;
			}
		}
		else
		{
			GFD_stop_count = 0;
			GFD_stop = 0;
		}
	}

	if(Emergency_stop || GFD_stop)
	{
		if(!red_led_blink)
		{
			red_led_blink = 500;
			TOGGLE_LED2;		//D13 LED (heartbeat) blinks RED
			TOGGLE_LED4;		//LED strip blinks RED
		}
		LED1_OFF;
		LED3_OFF;
		LED5_OFF;
		LED6_OFF;
		alarm = 1;
	}
	else
	{
		if(CURRENT_STATE == STATE_A)
		{

			if(!blue_led_blink)
			{
				blue_led_blink = 500;
				TOGGLE_LED1;			//D13 LED (heartbeat) blinks BLUE
			}
			LED3_OFF;

			if(Emergency_stop == 0 && GFD_stop == 0)
			 {
				 LED4_OFF;
				 LED2_OFF;
			 }
			LED5_OFF;
			LED6_ON;					//LED strip ON BLUE
			alarm = 0;
		}
		else if(CURRENT_STATE == STATE_B)
		{
			LED1_ON;				//D13 LED (heartbeat) ON BLUE
			LED2_OFF;
			LED3_OFF;
			LED4_OFF;

			if(Authentication_done)
			{
				if(!blue_led_blink)
				{
					lclflagLED = 1- lclflagLED;			//for STATE_B LED5 and LED6 should be turned ON in alternate cycles

					blue_led_blink = 500;
					if(lclflagLED)
					{
						LED5_ON;			//LED strip ON GREEN
						LED6_ON;			//LED strip ON BLUE
					}
					else
					{
						LED5_OFF;
						LED6_OFF;
					}
				}
			}
			else
			{
				if(!blue_led_blink)
				{
					blue_led_blink = 500;
					TOGGLE_LED6;		//LED strip blinks BLUE
				}
				LED5_OFF;
			}
			alarm = 0;
		}
		else if(CURRENT_STATE == STATE_C && !chargingStop)		//charging
		{
			 LED1_OFF;
			 LED3_ON;				//D13 LED (heartbeat) ON GREEN
			 LED5_ON;				//LED strip ON GREEN
			 LED4_OFF;
			 LED6_OFF;
			 alarm = 0;
		}
		else if(CURRENT_STATE == STATE_C && chargingStop)			//not charging
		{
			if(!blue_led_blink)
			{
				blue_led_blink = 500;
				TOGGLE_LED1;				//D13 LED (heartbeat) blinks BLUE
			}

			LED3_OFF;
			LED5_OFF;
			LED6_ON;					//LED strip ON BLUE
			LED4_ON;					//LED strip ON RED
			alarm = 0;
		}
		/*
		else if(CURRENT_STATE == STATE_D)					//NEVER EXECUTED as STATE_D is never assigned to CURRENT_STATE
		{
			 LED1_OFF;
			 LED3_OFF;
			 if(!Emergency_stop && !GFD_stop)
			 {
				 LED2_ON;
				 LED4_ON;
			 }
			 LED5_OFF;
			 LED6_OFF;

			 alarm = 1;
		}
		*/
 }


	/******buzzer**********/
	if(alarm)
  {
		if(!buzzer_enable_time)
		{
			if(Emergency_stop || GFD_stop)
				buzzer_enable_time = 100;
			else
				buzzer_enable_time = 500;

			buzzer_enable = !buzzer_enable;
		}

		if(buzzer_enable)
		{
			TOGGLE_BUZZER;
		}
		else
		{
		 BUZZER_OFF;
		}
  }
	else
		BUZZER_OFF;

	/******buzzer**********/


	if(!pwm_start_stop)
		adc_check();

  /* USER CODE END SysTick_IRQn 0 */
  HAL_IncTick();
  /* USER CODE BEGIN SysTick_IRQn 1 */

  /* USER CODE END SysTick_IRQn 1 */
}

/******************************************************************************/
/* STM32F1xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32f1xx.s).                    */
/******************************************************************************/

/**
  * @brief This function handles DMA1 channel1 global interrupt.
  */
void DMA1_Channel1_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel1_IRQn 0 */

  /* USER CODE END DMA1_Channel1_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_adc1);
  /* USER CODE BEGIN DMA1_Channel1_IRQn 1 */

  /* USER CODE END DMA1_Channel1_IRQn 1 */
}

/**
  * @brief This function handles DMA1 channel2 global interrupt.
  */
void DMA1_Channel2_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel2_IRQn 0 */

  /* USER CODE END DMA1_Channel2_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart3_tx);
  /* USER CODE BEGIN DMA1_Channel2_IRQn 1 */

  /* USER CODE END DMA1_Channel2_IRQn 1 */
}

/**
  * @brief This function handles DMA1 channel3 global interrupt.
  */
void DMA1_Channel3_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel3_IRQn 0 */

  /* USER CODE END DMA1_Channel3_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart3_rx);
  /* USER CODE BEGIN DMA1_Channel3_IRQn 1 */

  /* USER CODE END DMA1_Channel3_IRQn 1 */
}

/**
  * @brief This function handles DMA1 channel5 global interrupt.
  */
void DMA1_Channel5_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel5_IRQn 0 */

  /* USER CODE END DMA1_Channel5_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart1_rx);
  /* USER CODE BEGIN DMA1_Channel5_IRQn 1 */

  /* USER CODE END DMA1_Channel5_IRQn 1 */
}

/**
  * @brief This function handles TIM1 update interrupt.
  */
void TIM1_UP_IRQHandler(void)
{
  /* USER CODE BEGIN TIM1_UP_IRQn 0 */

  /* USER CODE END TIM1_UP_IRQn 0 */
  HAL_TIM_IRQHandler(&htim1);
  /* USER CODE BEGIN TIM1_UP_IRQn 1 */
	if(uart_rxFlag == 0)					//uart_rxFlag value is never changed
	{
		for(int i=0; i<300; i++);		//creating a delay

		adc_check();								//called here to check ADC read value whenever Timer1 interrupt is triggered
	}
  /* USER CODE END TIM1_UP_IRQn 1 */
}

/**
  * @brief This function handles USART1 global interrupt.
  */
void USART1_IRQHandler(void)
{
  /* USER CODE BEGIN USART1_IRQn 0 */
	__HAL_UART_FLUSH_DRREGISTER(&huart1);
	HAL_UART_Receive_DMA(&huart1,id,14);
  /* USER CODE END USART1_IRQn 0 */
  HAL_UART_IRQHandler(&huart1);
  /* USER CODE BEGIN USART1_IRQn 1 */

  /* USER CODE END USART1_IRQn 1 */
}

/**
  * @brief This function handles USART3 global interrupt.
  */
void USART3_IRQHandler (void)
{
  /* USER CODE BEGIN USART3_IRQn 0 */
	__HAL_UART_FLUSH_DRREGISTER(&huart3);
	HAL_UART_Receive_DMA(&huart3,&rxchar,1);
  /* USER CODE END USART3_IRQn 0 */
  HAL_UART_IRQHandler(&huart3);
  /* USER CODE BEGIN USART3_IRQn 1 */

  /* USER CODE END USART3_IRQn 1 */
}


/* USER CODE BEGIN 1 */
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
	if(huart->Instance == USART1)
	{
		HAL_UART_Receive_DMA(&huart1, id, 14);
	}
	if(huart->Instance == USART3)		// Added by Nihar
	{
		HAL_UART_Receive_DMA(&huart3, &rxchar, 1);
	}
}

//automatically called by the HAL library when a UART receive operation is complete
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{

	if(huart->Instance == USART1)
	{
		char tagid[13];
		memset(tagid,0,sizeof(tagid));
		int i;
		if((id[0] == 2) && (id[13] == 3))
		{
				for(i = 1; i < 13; i++)
				{
					tagid[i-1] = id[i];
				}
				tagid[i-1] = '\0';

				if(strncmp(tagid,(char *)rfid.rfid1,12) == 0)
				{
					Type2_OCPP_Authorization_Flag = 1;
				}
				else if(strncmp(tagid,(char *)rfid.rfid2,12) == 0)
				{
					Type2_OCPP_Authorization_Flag = 1;
				}
				else if(strncmp(tagid,(char *)rfid.rfid3,12) == 0)
				{
					Type2_OCPP_Authorization_Flag = 1;
				}
				else
				{
					Authentication_done = 0;
					Type2_OCPP_Authorization_Flag = 0;
				}
				//if authorized user
				if(Type2_OCPP_Authorization_Flag)
				{
					//to start charging with the first swipe of RFID tag
					if(CURRENT_STATE == STATE_B && !chargingStart  && timer123 == 0)
					{
							Authentication_done = 1;
						timer123 = 2500;
					}
				//to stop charging when RFID tag is swiped again
					else if(CURRENT_STATE == STATE_C && chargingStart && !chargingStop && timer123 == 0)
					{
						Authentication_done = 1;
						chargingStop = 1;
						timer123 = 2500;
					}
					Type2_OCPP_Authorization_Flag = 0;
				}
			}
			uart_rxFlag = 0;
		}//if(huart->Instance == USART6) ENDS HERE

		if (huart->Instance == USART3)		// Added by Nihar
		{
			__HAL_UART_FLUSH_DRREGISTER(&huart3);   // check for 2 line
			HAL_UART_Receive_DMA(&huart3,&rxchar,1);
			static uint8_t lclcounter=0;

			if(rxchar == '*' && startFrame == 0)
			{
				startFrame=1;
				lclcounter=0;
				rxbuff[lclcounter++]=rxchar;
			}
			else if(startFrame == 1 && rxchar != '#' && (lclcounter < 50))
			{
				rxbuff[lclcounter++]=rxchar;
			}
			else if(startFrame == 1 && rxchar == '#')
			{
				rxbuff[lclcounter++]=rxchar;
				cmdrxd=1;
				startFrame=0;
				configmode=1;
				lclcounter=0;
			}
			else
			{
				startFrame=0;
			}
			rxchar=0;
		}

}//void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) ENDS HERE

/* USER CODE END 1 */
