/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @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 "adc.h"
#include "dma.h"
#include "iwdg.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include <string.h>
#include "stm32f1xx_hal_flash.h"
#include "stm32f1xx_hal_flash_ex.h"
/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* 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 */

uint32_t adc1_dat[3];
uint16_t cp_val = 0;
uint8_t CURRENT_STATE = 10, powerONflag = 0;
volatile uint16_t timer123 = 0;
volatile int adc_init = 0;
volatile uint8_t Emergency_stop = 0, GFD_stop = 0;
volatile char alarm = 0;
extern uint8_t Authentication_done;
extern uint8_t id[15];
uint8_t count_A = 0, count_B = 0, count_C = 0;
char chargingStart = 0, chargingStop = 0;
char adc_error;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void start_pwm(void);
void stop_pwm(void);
void adc_check(void);
extern char pwm_start_stop;

// Added by Nihar
#define bypassRFID '3'
void Config_Mode(void);
int TxbuffIndex = 0;
int cmdrxd = 0;
char Txbuff[1000];
uint8_t rxchar = 0;
uint8_t rxbuff[1000];
uint8_t configmode = 0;
uint8_t startFrame = 0;
struct rfid_data rfid;
#define FLASH_USER_START_ADDR		0x0801F800
#define FLASH_USER_END_ADDR			0X0801FFFF
#define DATA_64		((uint64_t)0x1234567812345678)
#define data_32		((uint32_t)0x12345678)
void Internal_Flash_Read(unsigned long int * addr_toread, unsigned int size);
void Internal_Flash_Program(unsigned char* FirmwareBytePAcket,unsigned short PacketSize);
void Write_Params(void);
void Read_Params(void);
__IO uint32_t data32 = 0 , MemoryProgramStatus = 0;
uint32_t Address = 0, PageError = 0;

/* USER CODE END PFP */

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

const struct rfid_data default_params = {

    "420016434B5C",		//RFID_1
	"3800379D63F1",		//RFID_1
	"0000000000000",	//RFID_1
	1,					//GFDBypassEn
	1,					//RFIDBypassEn
    100,				//dummy
    3500,		//3276,	//STATE_A
    3049,		//2942, //STATE_B
    2598,		//2608, //STATE_C
    2100,				//STATE_D
    0xAA66				//magic_value
};

void adc_check()
{
	  if(adc_init == 0)return;		//return if ADC initialization not done

		HAL_ADC_Start_DMA(&hadc1, adc1_dat, 1);

		cp_val = adc1_dat[0];

		if(cp_val < 1100)
		{
			adc_error++;
			if(adc_error > 20)
			{
				NVIC_SystemReset();
			}
		}
		else
		{
			adc_error = 0;
		}

		if((cp_val <= rfid.STATE_A_LEVEL + 100) && (cp_val >= rfid.STATE_A_LEVEL - 100))
		{
		  count_B = 0;
		  count_C = 0;
		  if(++count_A > 10)
		  {
				CURRENT_STATE = STATE_A;
				count_A = 0;
		  }
		}
		else if((cp_val <= rfid.STATE_B_LEVEL + 100) && (cp_val >= rfid.STATE_B_LEVEL - 100))
		{
			count_C = 0;
			count_A = 0;
			if(++count_B > 10)
			{
				CURRENT_STATE = STATE_B;
				count_B = 0;
			}
		}
		else if((cp_val <= rfid.STATE_C_LEVEL + 100) && (cp_val >= rfid.STATE_C_LEVEL - 100))
		{
			count_B = 0;
			count_A = 0;
			if(++count_C > 10)
			{
				CURRENT_STATE = STATE_C;
				count_C = 0;
			}
		}
}

// Added by Nihar
void Internal_Flash_Read(unsigned long int * addr_toread, unsigned int size)
{
	unsigned int addr=0,bal_size;

	bal_size=size%4;
	if(bal_size)
	size=size+bal_size;

	Address = FLASH_USER_START_ADDR;
	MemoryProgramStatus = 0x0;

	while (Address < FLASH_USER_END_ADDR)
	{
		if(addr>=(size/4))break;
		*addr_toread = *(__IO uint32_t *)Address;
		addr_toread++;addr++;
	    Address = Address + 4;
	}
}

void Internal_Flash_Program(unsigned char* FirmwareBytePAcket,unsigned short PacketSize)
{

	unsigned short  PacketLength=0;
	uint32_t   ProgramWord=0;
//	unsigned int   ProgramWord=0;
//	unsigned int    Address=0;
//  unsigned char   ProgramByte=0;
    Address = FLASH_USER_START_ADDR;
    HAL_FLASH_Unlock();

	FLASH_PageErase(FLASH_USER_START_ADDR);				//(0, 63);
	CLEAR_BIT(FLASH->CR, FLASH_CR_PER);

	for(PacketLength=0;PacketLength<PacketSize;PacketLength+=4)
	{
    	ProgramWord=0;
		ProgramWord|=(FirmwareBytePAcket[PacketLength+3] & 0xFF);
		ProgramWord<<=8;
		ProgramWord|=(FirmwareBytePAcket[PacketLength+2] & 0xFF);
		ProgramWord<<=8;
		ProgramWord|=(FirmwareBytePAcket[PacketLength+1] & 0xFF);
		ProgramWord<<=8;
		ProgramWord|=(FirmwareBytePAcket[PacketLength] & 0xFF);

		if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address, ProgramWord) == HAL_OK)
		{
			Address = Address + 4;
    }
		else
		{
			/* Error occurred while writing data in Flash memory.
			 User can add here some code to deal with this error */
			/*
			FLASH_ErrorTypeDef errorcode = HAL_FLASH_GetError();
			*/
			Error_Handler();
    	}

     }
     HAL_FLASH_Lock();
}

void Write_Params(void)
{
	Internal_Flash_Program((unsigned char*)&rfid, sizeof(struct rfid_data));
}

void Read_Params(void)
{
	Internal_Flash_Read((unsigned long int*)&rfid, sizeof(struct rfid_data));
}


/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_IWDG_Init();
  MX_USART1_UART_Init();
  MX_TIM1_Init();
  MX_ADC1_Init();
  MX_USART3_UART_Init();
  /* USER CODE BEGIN 2 */
	HAL_UART_Receive_DMA(&huart1, id, 14);		//ID is retrieved over UART1
	HAL_UART_Receive_DMA(&huart3,&rxchar,1);
	HAL_Delay(100);
	HAL_TIM_Base_MspInit(&htim1);				//Timer1 is intialized and Timer1 interrupt set to highest priority
	HAL_Delay(100);

  powerONflag = 1;								//indicates Supply to
 	adc_init = 1;								//indicates ADC initialization is done
	HAL_Delay(100);
	Read_Params();

	if(rfid.magic_value != 0xAA66)
	{
		Read_Params();
	}
	HAL_Delay(10);

	if(rfid.magic_value != 0xAA66)
	{
		Read_Params();
	}
	HAL_Delay(10);

	if(rfid.magic_value != 0xAA66)
	{
		rfid = default_params;
		Write_Params();
		HAL_Delay(10);
		Read_Params();
	}

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
	HAL_UART_Receive_IT(&huart3, &rxchar, 1);

  while (1)
  {
		HAL_IWDG_Refresh(&hiwdg);				//Refresh the IWDG for maintaining system stability and reliability
																	//refreshing IWDG counter at regular intervals during normal operation prevents an MCU reset
		if(CURRENT_STATE == STATE_A)
		{
			relayOff;

			if ( rfid.RFIDBypassEn == 0 )		// RFID DISABLE
			{
				if(pwm_start_stop)
				stop_pwm();
			}
			powerONflag = 1;
			chargingStop = 0;
			chargingStart = 0;
			Authentication_done = 0;
		}
		else if(CURRENT_STATE == STATE_B)
		{

			if ( rfid.RFIDBypassEn == 0 )		// RFID DISABLE
			{
				if(chargingStop)
				{
					chargingStart = 0;
					stop_pwm();
					relayOff;
				}
			}
			//if(!Emergency_stop && !GFD_stop && powerONflag && Authentication_done && !chargingStop)
			if(!Emergency_stop && !GFD_stop && powerONflag && !chargingStop)
			{
				if ( rfid.RFIDBypassEn == 1 && Authentication_done == 1)		// RFID ENABLE
				{
					//Authentication_done = 0;
					start_pwm();
					chargingStart = 1;
				}
				else if(rfid.RFIDBypassEn == 0)		//  RFID DISABLE
				{
					start_pwm();
					chargingStart = 1;
				}
			}
			else
			{
				stop_pwm();
			}

			relayOff;
		}
		else if(CURRENT_STATE == STATE_C)
		{
			if ( rfid.RFIDBypassEn == 1 )		// RFID ENABLE
			{
				Authentication_done = 0;
			}
			if(!Emergency_stop && !GFD_stop && !chargingStop && chargingStart)
			{
				powerONflag = 0;
				relayOn;
			}
		}
		if(Emergency_stop || chargingStop || GFD_stop)
		{
			relayOff;
			if ( rfid.RFIDBypassEn == 0 )		// Added by nihar
			{
				chargingStop = 1;
			}
			stop_pwm();
			powerONflag = 0;
			chargingStart = 0;
		}

    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		if	(configmode == 1)
		{
			Config_Mode();
		}

	}
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI|RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL5;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /*
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  */

  /** Initializes the CPU, AHB and APB buses clocks
  */

  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
  PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
  /*
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
  PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV2;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }*/
}

/* USER CODE BEGIN 4 */

// Function to handle RFID & CP Count configuration mode		// Added by Nihar
void Config_Mode(void)
{
    memset((unsigned char*)Txbuff, '\0', sizeof(Txbuff));  // Clear the transmit buffer

    if (cmdrxd == 1)  // If a command is received
    {
        TxbuffIndex = 0;

        if (rxbuff[1] == '1')  // Enter config mode
        {
            TxbuffIndex = sprintf(Txbuff, "******************** RFID Config Mode Enabled ********************\r\n");
        }
        // Show RFID Data
        else if (rxbuff[1] == '2')
        {
			// Read the stored RFID data from Flash
            Read_Params();  // Read data from flash into 'rfid'
			TxbuffIndex=snprintf(Txbuff,sizeof(Txbuff),"Stored Data : \t\n rfid1 : %s \t\n rfid2 : %s \t\n rfid3 : %s \t\n ",rfid.rfid1, rfid.rfid2, rfid.rfid3 );
			HAL_UART_Transmit(&huart1, (uint8_t*)Txbuff,TxbuffIndex,0Xffff);
        }
        // Add RFID Data
        else if (rxbuff[1] == 'A')
		{
        	if (rxbuff[2] == '1')  // Add to rfid1
        	{
        		int i = 0;
        		// Start at rxbuff[3] which should be the start of the RFID number
        		while (rxbuff[3 + i] != '#' && rxbuff[3 + i] != '\0')  // Make sure we stop at the end or '#'
        		{
        			if (i < 13)  // Ensure we don't exceed the rfid1 array length
        			{
        				rfid.rfid1[i] = rxbuff[3 + i];  // Add the character to rfid1
        				i++;
        			}
        			else
        			{
        				rfid.rfid1[i] = '\0';
        				break;  // Exit if the array is full
        			}
        		}
        		TxbuffIndex = snprintf(Txbuff, sizeof(Txbuff), "Added RFID to rfid1: %s\n", rfid.rfid1);
			}
			else if (rxbuff[2] == '2')  // Add to rfid2
			{
				int i = 0;
				while (rxbuff[3 + i] != '#' && rxbuff[3 + i] != '\0')
				{
					if (i < 13)
					{
						rfid.rfid2[i] = rxbuff[3 + i];
						i++;
					}
					else
					{
						rfid.rfid2[i] = '\0';
						break;
					}
				}
				TxbuffIndex = snprintf(Txbuff, sizeof(Txbuff), "Added RFID to rfid2: %s\n", rfid.rfid2);
			}
			else if (rxbuff[2] == '3')  // Add to rfid3
			{
				int i = 0;
				// Start at rxbuff[3]
				while (rxbuff[3 + i] != '#' && rxbuff[3 + i] != '\0')
				{
					if (i < 13)
					{
						rfid.rfid3[i] = rxbuff[3 + i];
						i++;
					}
					else
					{
						rfid.rfid3[i] = '\0';
						break;
					}
				}
				TxbuffIndex = snprintf(Txbuff, sizeof(Txbuff), "Added RFID to rfid3: %s\n", rfid.rfid3);
			}
		}
        // Remove RFID Data
        else if (rxbuff[1] == 'R')  // Remove data
        {
            if (rxbuff[2] == '1')  // Remove from rfid1
            {
                for (int i = 12; i >= 0; i--)
								{
                    if (rfid.rfid1[i] != 0)
					{  // Find last filled slot
                        rfid.rfid1[i] = 0;  // Clear the data
                        TxbuffIndex = sprintf(Txbuff, "Removed data from rfid1\n");
                    }
                }
            }
            else if (rxbuff[2] == '2')  // Remove from rfid2
            {
                for (int i = 12; i >= 0; i--)
								{
                    if (rfid.rfid2[i] != 0)
					{
                        rfid.rfid2[i] = 0;
                        TxbuffIndex = sprintf(Txbuff, "Removed data from rfid2\n");
                    }
                }

            }
            else if (rxbuff[2] == '3')  // Remove from rfid3
            {
                for (int i = 12; i >= 0; i--)
								{
                    if (rfid.rfid3[i] != 0)
					{
                        rfid.rfid3[i] = 0;
                        TxbuffIndex = sprintf(Txbuff, "Removed data from rfid3\n");
                    }
                }
            }
        }
		else if (rxbuff[1] == '4')
		{
			Write_Params();
			TxbuffIndex = sprintf(Txbuff, "******************** RFID Data Saved & RFID Calibration Done ********************\r\n");
			configmode = 0;  // Disable config mode
		}
		else if (rxbuff[1] == '5')
		{
			TxbuffIndex = sprintf(Txbuff, "******************** CP Config Mode Enable ********************\r\n");
		}
		else if (rxbuff[1] == '6')
		{
			TxbuffIndex=snprintf(Txbuff,sizeof(Txbuff),"CP_COUNT : %d \t\n", cp_val);
			HAL_UART_Transmit(&huart1, (uint8_t*)Txbuff,TxbuffIndex,0Xffff);
		}
		else if (rxbuff[1] == '7')  // Set STATE Level
		{
		    uint16_t value = 0;
		    int i = 0;

		    if (rxbuff[2] == 'A')
		    {
		        i = 0;
		        value = 0;
		        while (rxbuff[3 + i] != '#' && rxbuff[3 + i] != '\0' && i < 5)
		        {
		            value = value * 10 + (rxbuff[3 + i] - '0');
		            i++;
		        }
		        rfid.STATE_A_LEVEL = value;
		        TxbuffIndex = sprintf(Txbuff, "STATE_A_LEVEL set to: %d\n", rfid.STATE_A_LEVEL);
		    	}
		    	else if (rxbuff[2] == 'B')
		    	{
		    		i = 0;
		    		value = 0;
		    		while (rxbuff[3 + i] != '#' && rxbuff[3 + i] != '\0' && i < 5)
		    		{
		    			value = value * 10 + (rxbuff[3 + i] - '0');
		            	i++;
		    		}
		    		rfid.STATE_B_LEVEL = value;
		    		TxbuffIndex = sprintf(Txbuff, "STATE_B_LEVEL set to: %d\n", rfid.STATE_B_LEVEL);
		    	}
		    	else if (rxbuff[2] == 'C')
		    	{
		    		i = 0;
		    		value = 0;
		    		while (rxbuff[3 + i] != '#' && rxbuff[3 + i] != '\0' && i < 5)
		    		{
		    			value = value * 10 + (rxbuff[3 + i] - '0');
		    			i++;
		    		}
		    		rfid.STATE_C_LEVEL = value;
		    		TxbuffIndex = sprintf(Txbuff, "STATE_C_LEVEL set to: %d\n", rfid.STATE_C_LEVEL);
		    	}
		    	else if (rxbuff[2] == 'D')
		    	{
		    		i = 0;
		    		value = 0;
		    		while (rxbuff[3 + i] != '#' && rxbuff[3 + i] != '\0' && i < 5)
		    		{
		    			value = value * 10 + (rxbuff[3 + i] - '0');
		    			i++;
		    		}
		    		rfid.STATE_D_LEVEL = value;
		    		TxbuffIndex = sprintf(Txbuff, "STATE_D_LEVEL set to: %d\n", rfid.STATE_D_LEVEL);
		    	}

		}
		else if (rxbuff[1] == '8')  // Show stored STATE levels
		{
			Write_Params();
			TxbuffIndex = sprintf(Txbuff, "******************** CP Count Data Saved & CP Count Calibration Done ********************\r\n");
		}
		else if (rxbuff[1] == '9')
		{
		    Read_Params();  // Load values from flash into your variables
		    TxbuffIndex = snprintf(Txbuff, sizeof(Txbuff),
		                           "Stored STATE_A_LEVEL: %d\r\n"
		                           "Stored STATE_B_LEVEL: %d\r\n"
		                           "Stored STATE_C_LEVEL: %d\r\n"
		                           "Stored STATE_D_LEVEL: %d\r\n",
		                           rfid.STATE_A_LEVEL, rfid.STATE_B_LEVEL, rfid.STATE_C_LEVEL, rfid.STATE_D_LEVEL);
			configmode = 0;  // Disable config mode
		}

        /*
         * GFDBypassEn = 1	---->	GFD ENABLE
         * GFDBypassEn = 0	---->	GFD DISABLE
         * RFIDBypassEn = 1	---->	RFID ENABLE
         * RFIDBypassEn = 0	---->	RFID DISABLE
         * */
		else if (rxbuff[1] == 'G')
		{
			// Add Function to Enable / Disable GFD
			if(rxbuff[2]== '1')	//enable GFD
			{
				rfid.GFDBypassEn = 1;
				TxbuffIndex=sprintf(Txbuff,"GFD detection Enabled\r\n");
				Write_Params();
			}
			else if(rxbuff[2]== '2')	//disable GFD
			{
				rfid.GFDBypassEn = 0;
				TxbuffIndex=sprintf(Txbuff,"GFD detection Disabled\r\n");
				Write_Params();
			}
			else if (rxbuff[2] == '3')
			{
				TxbuffIndex=sprintf(Txbuff,"GFD Status : %d \r\n",rfid.GFDBypassEn);
				Read_Params();
				configmode = 0;  // Disable config mode
			}
		}
		else if (rxbuff[1] == bypassRFID)
		{
			if (rxbuff[2] == '1')	//Enable RFID
			{
				rfid.RFIDBypassEn = 1;
				TxbuffIndex=sprintf(Txbuff,"RFID detection Enabled\r\n");
				Write_Params();
			}
			else if (rxbuff[2] == '2')	//Disable RFID
			{
				rfid.RFIDBypassEn = 0;
				TxbuffIndex=sprintf(Txbuff,"RFID detection Disabled\r\n");
				Write_Params();
			}
			else if (rxbuff[2] == '3')
			{
				TxbuffIndex=sprintf(Txbuff,"RFID Status : %d \r\n",rfid.RFIDBypassEn);
				Read_Params();
				configmode = 0;  // Disable config mode
			}
		}
    	else
    	{
    		TxbuffIndex = sprintf(Txbuff, "Invalid command. Please enter a valid command.\r\n");
    	}
        HAL_UART_Transmit(&huart3, (uint8_t*)Txbuff, TxbuffIndex,0Xffff); //1000);
        cmdrxd = 0;			// Clear the command received flag
    }
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
	/* USER CODE BEGIN Error_Handler_Debug */
	/* User can add his own implementation to report the HAL error return state */
	 while (1)
	 {

	 }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
