/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * Last modifications done on 25-08-2022
 * Added WIFI disconnect symbol update
 * In case of energy meter failure - charging stopped
 * In charging start event in gun 1 & gun 2 , automatic go to main page issue resolved
 * OCPP testing pending
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "cmsis_os.h"
#include "adc.h"
#include "dma.h"
#include "rng.h"
#include "rtc.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
#include "iwdg.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include<string.h>
#include <stdarg.h>
#include"OCPP.h"
#include"modbus.h"
#include "w25qxx.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 */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void MX_FREERTOS_Init(void);
/* USER CODE BEGIN PFP */
extern char ether_connection_varify(void);
extern char wifi_connection_varify(void);
extern int validate_ip(unsigned char *ip);
extern void Write_Params(void);
extern char OCPP_setting, WIFI_Setting;

void StartTask1(void const *argument);
extern void Read_Params(void);
void Billing(char i);
void AC001(void);
void adc_check(void);
void adc_check_2(void);
void AC_TYPE2(void);
void AC_TYPE2_1(void);
char Gun1_ocpp(void);
char Gun2_ocpp(void);
char Gun3_ocpp(void);
void Adding_Rfid(void);
extern char websocket_success, boot_success;
extern char server_packet[1024];
extern volatile char DC001_OCPP_timestamp1[30];
extern uint8_t rxmsg[100], hmi_buffer[50];
extern uint8_t id[15];
extern uint8_t incorrect_rfid, correct_rfid;
extern char tagid[15];
//extern char charger_status[20];
//extern uint8_t AC001_OCPP_Charger_Status;
uint32_t adc1_dat[3], adc1_dat_2[6];
uint8_t count_D = 0, count_C = 0, count_A = 0, count_B = 0, count_D_2 = 0,
		count_C_2 = 0, count_A_2 = 0, count_B_2 = 0;

extern uint8_t internet_connection;
uint16_t pp_val = 0, cp_val = 0, cp_val_2 = 0;
volatile int adc_init = 0, adc_init_2 = 0;
//volatile uint8_t Emergency_stop=0;
volatile char alarm;
uint8_t CURRENT_STATE = 0;
extern uint8_t start_timer;
extern const struct Config_Parameter default_params;
extern const struct Config_Parameter_OCPP default_params_ocpp;

extern uint8_t rxBuffer, hmi_buff;
extern char write_para, chip_erase, Send_meter;
extern volatile uint32_t energy, energy2, energy3;
volatile char read_flash = 0;
//static uint8_t wifi_connected;
uint8_t relay_on = 0, Charging_time, ocpp_boot_status, billing_gun,
		CURRENT_STATE_1;
char req_network_select, res_downlink, res_notfound, req_ocpp_status,
		GSMreq_network_select;
extern unsigned char etherip[10], ethersm[10], ethergw[10], ssid[20],
		wifi_pass[20], ocpp_uri[100], ocpp_status;
extern uint16_t charge_by_time, automatic_charging, Total_time, Total_unit,
		Total_cost, charging_unit;
extern char pwm_start_stop, OCPP_setting, pwm_start_stop_1;
extern volatile uint8_t HMI_wifi_disconnect, HMI_websocket_connect,
		HMI_websocket_disconnect, HMI_wifi_connect;
extern uint32_t byte_in;
extern uint32_t byte_out;
extern uint8_t gun_3, gun_2, gun_1, M_buff;
volatile extern uint8_t LocalListAdding, Local_List_Update;
extern uint8_t Type2_OCPP_Authorization_Flag;
osThreadId Task1Handle;
char ocpp_timer, seq, internal_rtc_read;
uint8_t update_variable, erage_chip;
extern uint8_t Store_Key_Parameter;
uint16_t s6_counter1, s6_counter2, s6_counter3;
volatile extern char Clear_Register;
extern volatile char flash_writing;
uint8_t status_hal;
extern uint8_t RCD1_stop, RCD2_stop, RCD3_stop;
uint8_t ALARM_FLAG = 0, change = 0; //ALARM_FLAG
extern char pwm_start_stop;
uint8_t adcFailed = 0, meter_failed = 0;

extern volatile uint8_t recieve_complete_2;

//---------fota update varibles-------//
extern volatile uint8_t RemoteStarttx_res;
extern char Array1[5][50];
volatile extern uint8_t inprocess;
extern volatile uint8_t BootNotification_res;

char fw_update;

extern uint8_t hard_reset;
extern struct stFirmwareUpgrade FirmwareupdateTime;

FlashInfo_t FlashInfo;
uint8_t PWM_stop_flag;
////////////////////////////////////////

//////////////////4G_parameter///////////////
unsigned char fourGtxBuffer[1000]; //__attribute__ ((section(".ccm")));
//static uint8_t buffex[50] __attribute__ ((section(".ccm")));
unsigned short fourgtxBufferIndex = 0;
char seperator = 0x07;
extern char network_switch_flag;
/////////////////////////////////////////////
//////V4.1.4 changes //////////////////////////////
char expiry_calculation(String rtc_time, String expiery_time);

extern struct Config_Parameter_Cach_Memory Cash_Memory;
////////////////////////////////////////
////////////////V4.1.5 CHANGES////////////////////////
char pwronFlag = 0;
//////////////////////////////////////////////////////
#if defined(NAYARA)
unsigned char ALARM_CHARGING_STATUS;
int PowerFailureOnStartTxInvl = 1000; // ioncharge
#endif
//////////////////V4.x.7 changes//////////////////////
extern unsigned char WaitForResponse;
extern int strcmp_1(unsigned char *b, unsigned char *a);
extern int strlen_1(unsigned char *data);

//////////////////V4.x.8/////////////////////
unsigned char hmi_resetCause = 0;
reset_cause_t reset_cause;	//v4.x.8
//////////////////////////////////////////////////////
//V501change
uint16_t hmicp_val = 0, hmicp_val_1 = 0;

extern char update_CP_Count, update_CP_1_Count;
//V501change

//V6 change for firmware status notification
extern char gafw_status[30];

extern char fwUPdateTimer;
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void UART_Printf(const char *fmt, ...) {
	char buff[256];
	va_list args;
	va_start(args, fmt);
	vsnprintf(buff, sizeof(buff), fmt, args);
	//HAL_UART_Transmit(&huart6, (uint8_t*)buff, strlen(buff),500);
	va_end(args);
}

void Remap_Table(void) {
// Copy interrupt vector table to the RAM.
//    volatile uint32_t *VectorTable = (volatile uint32_t *)0x20000000;
//    uint32_t ui32_VectorIndex = 0;
//
//    for(ui32_VectorIndex = 0; ui32_VectorIndex < 48; ui32_VectorIndex++)
//    {
//        VectorTable[ui32_VectorIndex] = *(__IO uint32_t*)((uint32_t)0x08008000 + (ui32_VectorIndex << 2));
//    }
	__HAL_RCC_AHB1_FORCE_RESET();
	__HAL_RCC_AHB2_FORCE_RESET();
	//  Enable SYSCFG peripheral clock
	__HAL_RCC_SYSCFG_CLK_ENABLE();
	//   __HAL_RCC_AHB_RELEASE_RESET();
	__HAL_RCC_AHB1_RELEASE_RESET();
	__HAL_RCC_AHB2_RELEASE_RESET();
	// Remap RAM into 0x0000 0000
	__HAL_SYSCFG_REMAPMEMORY_SRAM();
}
/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void) {
	/* USER CODE BEGIN 1 */
	Remap_Table();
	__enable_irq();
	/* USER CODE END 1 */

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

	/* USER CODE BEGIN Init */
	/* Reset of all peripherals, Initializes the Flash interface and the Systick. */

	HAL_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_USART2_UART_Init();
	MX_TIM1_Init();
	MX_USART1_UART_Init();
	MX_RTC_Init();
	MX_USART3_UART_Init();
	MX_USART6_UART_Init();
	MX_RNG_Init();
	MX_TIM2_Init();
	MX_TIM5_Init();
	MX_SPI1_Init();
	MX_IWDG_Init();
	MX_ADC1_Init();
#if defined(dualgun)
	MX_ADC2_Init();
#endif
	/* USER CODE BEGIN 2 */
	///////////4G/////////////
#if defined(newhw)
	//////////4G/////////////
	//RFIDON;
	GSMON
	;
	ESPOFF
	;
//	RELAY_SW_ESPOFF;			//INTIALLY CONNECT OCPP ON GSM
//	GSM.wifi_enable_sts =1;
//	GSM.ethernet_enable_sts=0;
//	GSM.gsm_enable_sts =0;
	////////////////////////////////
#else

	GSM.wifi_enable_sts = 1;
	GSM.ethernet_enable_sts = 0;
	GSM.gsm_enable_sts = 0;
	////////////////////////////////
#endif
	HAL_TIM_Base_Start_IT(&htim2);
	HAL_TIM_Base_MspInit(&htim1);
	HAL_TIM_Base_Start_IT(&htim1);
	//status_hal = HAL_TIM_Base_Start_IT(&htim5);

	HAL_Delay(1000);
	HAL_UART_Receive_DMA(&huart6, (uint8_t*) id, 13);
	HAL_Delay(10);
	HAL_UART_Receive_DMA(&huart1, (uint8_t*) &M_buff, 1);
	HAL_Delay(10);
	HAL_UART_Receive_DMA(&huart3, &hmi_buff, 1);
	HAL_Delay(10);
	HAL_UART_Receive_DMA(&huart2, &rxBuffer, 1);
	HAL_Delay(10);

	//HAL_ADC_Start_DMA(&hadc2,adc2_dat,500);
	W25qxx_Init();
	internal_rtc_read = 1;
	Read_Params();

	HAL_Delay(10);
	if (OCPP.magic_value != CRC_value_OCPP) {
		Read_Params();
	}
	HAL_Delay(10);
	if (OCPP.magic_value != CRC_value_OCPP) {
		Read_Params();
	}
	HAL_Delay(10);
	if (OCPP.magic_value != CRC_value_OCPP) {
		OCPP = default_params;
		OCPP.Communication_Mode = 3;
		OCPP.ether_ip[0] = 172;
		OCPP.ether_ip[1] = 16;
		OCPP.ether_ip[2] = 100;
		OCPP.ether_ip[3] = 1;
		OCPP.magic_value = CRC_value_OCPP;
		W25qxx_EraseSector(3840);
		HAL_Delay(10);
		Write_Params();
	}
	HAL_Delay(10);
	HAL_Delay(10);
#if defined(newhw)
	HAL_Delay(10);
	if (OCPP.Communication_Mode == 1) {
		RELAY_SW_ESPOFF
		;
		ESPOFF
		;
		GSM.gsm_enable_sts = 1;
		GSM.wifi_enable_sts = 0;
		GSM.ethernet_enable_sts = 0;
	} else if (OCPP.Communication_Mode == 2) {
		RELAY_SW_ESPON
		;
		ESPON
		;
		GSMOFF
		;
		GSM.gsm_enable_sts = 0;
		GSM.wifi_enable_sts = 1;
		GSM.ethernet_enable_sts = 0;
	}
	else if (OCPP.Communication_Mode == 3)
	{
		RELAY_SW_ESPON
		;
		ESPON
		;
		GSMOFF
		;
		GSM.gsm_enable_sts = 0;
		GSM.wifi_enable_sts = 0;
		GSM.ethernet_enable_sts = 1;
	}
#endif

	if (OCPP.fw_status == 8) {
		strcpy(gafw_status, "DownloadFailed");
	}

	if (OCPP.fw_status == 128) {
		strcpy(gafw_status, "Installed");
	}

	if (OCPP.fw_status == 0) {
		strcpy(gafw_status, "Idle");
	}

	OCPP.fw_status = 0;
	Write_Params();

	HAL_Delay(10);
	HAL_Delay(1000);
	SFlash_pointer_read();
	HAL_Delay(10);

	if (FlashInfo.StructGuard1 != '$') {
		SFlash_pointer_read();
	}
	HAL_Delay(10);
	if (FlashInfo.StructGuard2 != '#') {
		SFlash_pointer_read();
	}
	byte_in = FlashInfo.lastPointer;
	HAL_Delay(10);
	SRfid_pointer_read();

	if (rfid_pointer.StructGuard1 != '$') {
		SRfid_pointer_read();
	}
	HAL_Delay(10);
	HAL_Delay(10);
	Read_Key_Params();

	if (Ocpp_Setting.magic_value != CRC_value_OCPP_setting) {
		Read_Key_Params();
	}

	if (Ocpp_Setting.magic_value != CRC_value_OCPP_setting) {
		Ocpp_Setting = default_params_ocpp;
		W25qxx_EraseSector(3809);
		HAL_Delay(10);
		Ocpp_Setting.magic_value = CRC_value_OCPP_setting;
		Write_Key_Params();
	}

	if (Ocpp_Setting.Operative[1] == Unavailable_ChargerPoint) {
		charger_status_G1.charging_status = Unavailable_ChargerPoint;
	} else {
		charger_status_G1.charging_status = Available_ChargerPoint;
	}
#if defined(dualgun)
	if(Ocpp_Setting.Operative[2] == Unavailable_ChargerPoint)
	{
		charger_status_G2.charging_status = Unavailable_ChargerPoint;
	}
	else
	{
		charger_status_G2.charging_status = Available_ChargerPoint;
	}
#endif
#if defined(threegun)
	if(Ocpp_Setting.Operative[3] == Unavailable_ChargerPoint)
	{
		 charger_status_G3.charging_status = Unavailable_ChargerPoint;
	}
	else
	{
		charger_status_G3.charging_status = Available_ChargerPoint;
	}
#endif

	//3.3.1 changes///////////
	charger_status_G3.ocpp_status = Not_Connect;
	charger_status_G2.ocpp_status = Not_Connect;
	charger_status_G1.ocpp_status = Not_Connect;

	charger_status_G2.error = NoError_ChargerPoint;
	charger_status_G1.error = NoError_ChargerPoint;
	charger_status_G3.error = NoError_ChargerPoint;

	charger_status_G1.start = Stoped;
	charger_status_G2.start = Stoped;
	charger_status_G3.start = Stoped;

	charger_status_G1.stop = Stoped;
	charger_status_G2.stop = Stoped;
	charger_status_G3.stop = Stoped;

	charger_status_G1.timer = 5;
	charger_status_G2.timer = 5;

	gun_1 = G_NoError;
	gun_2 = G_NoError;
	gun_3 = G_NoError;

	//////////////////////////////////////////////////
	/////////////////v4.1.4/////////////////////

	HAL_Delay(10);
	HAL_Delay(10);
	Read_CACH_Params();
	HAL_Delay(10);
	HAL_Delay(10);
	if (Cash_Memory.magic_value != 0xAA55) {
		memset((unsigned char*) &Cash_Memory.transaction_id[0], 0x00,
				sizeof(Cash_Memory));
		Cash_Memory.magic_value = 0xAA55;
		Write_CACH_Params();
	}
	/////////////////////////////////////////////
	UART_Printf("START_uart\r\n");
	adc_init = 1;
#if defined(dualgun)
	adc_init_2 = 1;
#endif
	change = 1; //ESP restart when STM starts or Restart
	pwronFlag = 1;
#if defined(selecdual)
	meterquerycntr=0;
#endif

	if (__HAL_RCC_GET_FLAG(RCC_FLAG_LPWRRST))	//v4.x.8
			{
		reset_cause = RESET_CAUSE_LOW_POWER_RESET;
	} else if (__HAL_RCC_GET_FLAG(RCC_FLAG_WWDGRST)) {
		reset_cause = RESET_CAUSE_WINDOW_WATCHDOG_RESET;
	} else if (__HAL_RCC_GET_FLAG(RCC_FLAG_IWDGRST)) {
		reset_cause = RESET_CAUSE_INDEPENDENT_WATCHDOG_RESET;
	} else if (__HAL_RCC_GET_FLAG(RCC_FLAG_SFTRST)) {
		// This reset is induced by calling the ARM CMSIS
		// `NVIC_SystemReset()` function!
		reset_cause = RESET_CAUSE_SOFTWARE_RESET;
	} else if (__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST)) {
		reset_cause = RESET_CAUSE_POWER_ON_POWER_DOWN_RESET;
	} else if (__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST)) {
		reset_cause = RESET_CAUSE_EXTERNAL_RESET_PIN_RESET;
	}
	// Needs to come *after* checking the `RCC_FLAG_PORRST` flag in order to
	// ensure first that the reset cause is NOT a POR/PDR reset. See note
	// below.
	else if (__HAL_RCC_GET_FLAG(RCC_FLAG_BORRST)) {
		reset_cause = RESET_CAUSE_BROWNOUT_RESET;
	} else {
		reset_cause = RESET_CAUSE_UNKNOWN;
	}

	__HAL_RCC_CLEAR_RESET_FLAGS();
	hmi_resetCause = reset_cause;

#if defined(NAYARA)
	PowerFailureOnStartTxInvl = Ocpp_Setting.FailedTx_Intvl;  // ioncharger
#endif

	/* USER CODE END 2 */

	/* Call init function for freertos objects (in freertos.c) */
	MX_FREERTOS_Init();
	osThreadDef(Task1, StartTask1, osPriorityAboveNormal, 0, 256);
	Task1Handle = osThreadCreate(osThread(Task1), NULL);
	/* Start scheduler */
	osKernelStart();

	/* We should never get here as control is--- now taken by the scheduler */
	/* Infinite loop */
	/* USER CODE BEGIN WHILE */
	while (1) {
		/* USER CODE END WHILE */

		/* USER CODE BEGIN 3 */
	}
	/* USER CODE END 3 */
}
/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void)	//v4.x.8
{
	RCC_OscInitTypeDef RCC_OscInitStruct = { 0 };
	RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 };
	RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = { 0 };
	/** Configure the main internal regulator output voltage
	 */
	__HAL_RCC_PWR_CLK_ENABLE();
	__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

	/** Initializes the RCC Oscillators according to the specified parameters
	 * in the RCC_OscInitTypeDef structure.
	 */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI
			| RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_LSE;
	RCC_OscInitStruct.HSEState = RCC_HSE_ON;
	RCC_OscInitStruct.LSEState = RCC_LSE_ON;
	RCC_OscInitStruct.LSIState = RCC_LSI_ON;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
	RCC_OscInitStruct.PLL.PLLM = 6;
	RCC_OscInitStruct.PLL.PLLN = 96;
	RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
	RCC_OscInitStruct.PLL.PLLQ = 4;
	RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
	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_DIV4;
	RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV4;

	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK) {
		Error_Handler();
	}
	PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
	PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
	if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) {
		Error_Handler();
	}
}
/*void SystemClock_Config(void)
 {
 RCC_OscInitTypeDef RCC_OscInitStruct = {0};
 RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
 RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
 * Configure the main internal regulator output voltage

 __HAL_RCC_PWR_CLK_ENABLE();
 __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

 * 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.LSIState = RCC_LSI_ON;
 RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
 RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
 RCC_OscInitStruct.PLL.PLLM = 6;
 RCC_OscInitStruct.PLL.PLLN = 96;
 RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
 RCC_OscInitStruct.PLL.PLLQ = 4;
 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_DIV4;
 RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV4;

 if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK)
 {
 Error_Handler();
 }
 PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
 PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
 if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
 {
 Error_Handler();
 }
 }*/
/* USER CODE BEGIN 4 */
void StartTask1(void const *argument) {
	uint8_t buff[200];
	uint8_t trigger;
	///////V4.x.7 changes///////
	char Heartbeat_Interval = 0;		//V4.x.7
	int OCPP_Error_Interval = 0;
	///////////////////////////
	for (;;) {
//	  char *buff;
//	  buff = malloc(200 * sizeof(char));

		HAL_IWDG_Refresh(&hiwdg);
		////////////////////////V3.3.1///////////////////
		if (hard_reset == 1) {
#if defined(dualgun)
		  if(charger_status_G1.ocpp_status == Not_Connect && charger_status_G2.ocpp_status == Not_Connect)
		  {
			  HMI_Send(0);
			  HAL_Delay(5000);
			  NVIC_SystemReset(); 	//hard reset the system
		  }
#else
			if (charger_status_G1.ocpp_status == Not_Connect) {
				HMI_Send(0);
				HAL_Delay(5000);
				NVIC_SystemReset(); 	//hard reset the system
			}
#endif

		}
		//////////////////////////////////////////////////

//	 	if(Ocpp_Setting.Operative[0] != Unavailable_ChargerPoint)
//		{
		AC_TYPE2();
#if defined(dualgun)
	 		 AC_TYPE2_1();
#endif

//		}
		//V6 change
		if (fwUPdateTimer == 1) {
			if (FirmwareupdateTime.status == 1) {
				if (--FirmwareupdateTime.counter == 0) {
					OCPP.fw_status = 64;
					write_para = 1;
					fw_update = 1;
					FirmwareupdateTime.status = 0;
				} else if (FirmwareupdateTime.counter == 5) {
					strcpy(gafw_status, "Downloading");
					enQueue(FirmwareStatusNotification);
				}
			}
			fwUPdateTimer = 0;
		}
		//V6 change

		if (start_timer == 1) {
#if defined(selecdual)
		  if(++trigger > 30)
		  {
			trigger = 0;
			Send_Meterquery(meterquerycntr);
			Send_meter = 1;
		  }

#else
			if (Send_meter)   // disable
			{
				if (++trigger > 60) {
					Send_meter = 0;
					// meter_failed++;
					trigger = 0;
				}
			} else {
				trigger = 0;
				//meter_failed = 0;
			}
#endif
			HMI_data();
			start_timer = 0;
		} else if ((ocpp_timer == 1) && (seq == 0)) {
			if ((!ocpp_boot_status) && (OCPP.ocpp_status[0] == 1)) //v4.x.7 change
					{
				if (++OCPP_Error_Interval > 300) {
					OCPP_Error_Interval = 0;
					change = 1;
				}
			} else {
				OCPP_Error_Interval = 0;
			}

			if (WaitForResponse == true)					//v4.x.7 change
			{
				if (++Heartbeat_Interval > (Ocpp_Setting.HeartbeatIntvl * 3)) {
					Heartbeat_Interval = 0;
					WaitForResponse = false;
					change = 1;
				}
			} else {
				Heartbeat_Interval = 0;
			}
			if (Ocpp_Setting.AllowOfflineTXUnknownId == true) // gf SELECTED
			{
				if (GFD_READ == 0) // 1 - GF DETECT
						{
					if (ALARM_FLAG == ALARM_GROUNDFAULT
							|| ALARM_FLAG == ALARM_POWERFAIL) {
						charger_status_G1.error = NoError; // fault
						charger_status_G2.error = NoError;
						charger_status_G3.error = NoError;
						ALARM_FLAG = ALARM_NO;
#if defined(NAYARA)
						if (CURRENT_STATE == STATE_B)  //NAYARA
						{
							if (ALARM_CHARGING_STATUS == true) {
								charger_status_G1.start = PowerFail_To_Start;
								charger_status_G1.Authentication_done = PowerFailAuthorisation;
								charger_status_G1.reson == Remote;
							}
						} else {
							enQueue(powerON_available);	//v4.x.8
						}
						ALARM_CHARGING_STATUS = false;
						PowerFailureOnStartTxInvl = Ocpp_Setting.FailedTx_Intvl;
#else
					   enQueue(powerON_available);	//v4.x.8
#endif
					}
				} else {
#if defined(dualgun)
					 if ((charger_status_G2.voltage == 0 && charger_status_G1.voltage == 0))
					 {
										 //power failure
						 charger_status_G1.error = PowerSwitchFailure; //fault
						 charger_status_G2.error = PowerSwitchFailure;
//						 charger_status_G3.error = PowerSwitchFailure;
//
//						 charger_status_G3.reson = PowerLoss;
						 charger_status_G2.reson = PowerLoss;
						 charger_status_G1.reson = PowerLoss;
						 ALARM_FLAG =5;
					 }
					 else
					 {
						 charger_status_G1.error = GroundFailure; //fault
						 charger_status_G2.error = GroundFailure;
//						 charger_status_G3.error = GroundFailure;
						// Protection_flag =2; // fault
					 }
#else
					if (charger_status_G1.voltage == 0 || meter_failed > 5) {
#if meter == selec
						 charger_status_G1.stop = Error;
						 charger_status_G1.charging_status = Faulted_ChargerPoint;
						 gun_1 = G_Error;
						 meter_failed = 5;
#endif
						charger_status_G1.error = PowerSwitchFailure; //fault
						charger_status_G1.reson = PowerLoss;
						ALARM_FLAG = ALARM_POWERFAIL;
#if defined(NAYARA)
						if (PowerFailureOnStartTxInvl > 0) {
							PowerFailureOnStartTxInvl--;
						}
						if (ALARM_CHARGING_STATUS == true) {
							ALARM_CHARGING_STATUS = false;
							charger_status_G1.start = Started;
							charger_status_G1.stop = Try_To_Stop;
							charger_status_G1.timer = 0;
							charger_status_G1.charging_status =
									Finishing_ChargerPoint;
						}
#endif
					} else {
						ALARM_FLAG = ALARM_GROUNDFAULT;
						charger_status_G1.error = GroundFailure; //fault
					}

#endif
				}
			} else {
#if defined(dualgun)
				if((charger_status_G2.voltage == 0 && charger_status_G1.voltage == 0 ))
				{
					// power failure
					charger_status_G1.error = PowerSwitchFailure; //fault
					charger_status_G2.error = PowerSwitchFailure;
					// charger_status_G3.error = PowerSwitchFailure;
					//
					// charger_status_G3.reson = PowerLoss;
					charger_status_G2.reson = PowerLoss;
					charger_status_G1.reson = PowerLoss;
					ALARM_FLAG = 5;
				}
				else
				{
					if(ALARM_FLAG == 5)
					{
						// NVIC_SystemReset();
						charger_status_G1.error = NoError; //fault
						charger_status_G2.error = NoError;
						//charger_status_G3.error = NoError;
						ALARM_FLAG = 0;
						//restartrt
					}
				}
#else
				if (charger_status_G1.voltage == 0 || meter_failed > 5) {
					charger_status_G1.error = PowerSwitchFailure; // fault
#if meter == selec
						 charger_status_G1.stop = Error;
						 charger_status_G1.charging_status = Faulted_ChargerPoint;
						 gun_1 = G_Error;
						 meter_failed = 5;
#endif
					charger_status_G1.reson = PowerLoss;
					ALARM_FLAG = ALARM_POWERFAIL;
				} else {
					if (ALARM_FLAG == ALARM_POWERFAIL) {
						charger_status_G1.error = NoError; // fault
						ALARM_FLAG = ALARM_NO;
					}
				}
#endif
			}

			if (websocket_success == 1) {
				if (ocpp_boot_status != Boot_Success) {
					ocpp_timer = 0;
					seq = 0;
					// goto ocpp;
				} else {
					Gun1_ocpp();
#if defined(dualgun)
					Gun2_ocpp();
#endif
//					Gun3_ocpp();
					ocpp_timer = 0;
					seq = 0;
				}
			} else {
				seq = 0;
				ocpp_timer = 0;
				if (Ocpp_Setting.Operative[1] == Available_ChargerPoint) {
					if (charger_status_G1.charging_status
							== Finishing_ChargerPoint)//SuspendedEVSE_ChargerPoint)
							{
						charger_status_G1.charging_status =
								Available_ChargerPoint;
					}
				}
#if defined(dualgun)
		  if(Ocpp_Setting.Operative[2] == Available_ChargerPoint)
		  {
			  if(charger_status_G2.charging_status == Finishing_ChargerPoint)	//SuspendedEVSE_ChargerPoint)
			  {
				  charger_status_G2.charging_status =  Available_ChargerPoint;
			  }
		  }
#endif

			}
		}
		if ((Local_List_Update == 1) && (flash_writing == 0)) {
			Local_List_Update = 0;
			while (LocalListAdding) // == rfid_pointer.Added_rfid)
			{
				strcpy(rfid_data_to_flash.TagId,
						rfid_data.TagId[LocalListAdding]);
				strcpy(rfid_data_to_flash.expiery_time,
						rfid_data.expiery_time[LocalListAdding]);
				rfid_data_to_flash.status = rfid_data.status[LocalListAdding];
				Adding_Rfid();
				LocalListAdding--;
			}
			SRfid_pointer_write();
		}

		if (Ocpp_Setting.Operative[1] == Unavailable_ChargerPoint) {
			if (charger_status_G1.charging_status == Charging_ChargerPoint) {
				if (charger_status_G1.start == Started) {
					charger_status_G1.stop = Try_To_Stop;
					charger_status_G1.reson = Other;
					 charger_status_G1.charging_status = SuspendedEVSE_ChargerPoint;
				}
			}
		}
#if defined(dualgun)
	 if(Ocpp_Setting.Operative[2] == Unavailable_ChargerPoint)
	 {
		  if(charger_status_G2.charging_status == Charging_ChargerPoint)
			{
				 if(charger_status_G2.start == Started)
				 {
					 charger_status_G2.stop = Try_To_Stop;
					 charger_status_G2.reson = Other;
					  charger_status_G2.charging_status = SuspendedEVSE_ChargerPoint;
				 }
			}
	 }
#endif

		if (recieve_complete_2 == 1) {
			if (inprocess == 0) {
				process_ReceiveArray();
			}
			recieve_complete_2 = 0;
		}

		if (OCPP_setting || WIFI_Setting) {
			if (WIFI_Setting == 1) {
				change = 1;
			} else if (OCPP_setting == 1) {
				change = 1;
			}

			OCPP_setting = WIFI_Setting = 0;
		} else if (req_network_select == 1 || GSMreq_network_select == 1) {
			if (Ocpp_Setting.stoptransinternetLoss == 0) {
				if (charger_status_G1.On_Going_Tx == Tx_Fail) {

					charger_status_G1.ocpp_status = StopTransaction_Req;
				}

				if (charger_status_G2.On_Going_Tx == Tx_Fail) {
					charger_status_G2.ocpp_status = StopTransaction_Req;
				}
			} else {

				if (charger_status_G1.charging_status
						== Charging_ChargerPoint) {
					if (charger_status_G1.start == Started) {
						charger_status_G1.charging_status =
								Finishing_ChargerPoint;	//SuspendedEVSE_ChargerPoint;
						charger_status_G1.stop = Try_To_Stop;
					}
				}
				if (charger_status_G2.charging_status
						== Charging_ChargerPoint) {
					if (charger_status_G2.start == Started) {
						charger_status_G2.charging_status =
								Finishing_ChargerPoint;	//SuspendedEVSE_ChargerPoint;
						charger_status_G2.stop = Try_To_Stop;
					}
				}

				charger_status_G1.ocpp_status = Not_Connect;
				charger_status_G2.ocpp_status = Not_Connect;
				charger_status_G3.ocpp_status = Not_Connect;
			}
			if (OCPP.Communication_Mode == 2) //wifi)
					{
				if (wifi_connection_varify()) {
					memset((unsigned char*) fourGtxBuffer, 0x00,
							sizeof(fourGtxBuffer));
					memset((unsigned char*) buff, 0x00, sizeof(buff));

					//		       	sprintf(&buff,"%u",content_length);
					fourgtxBufferIndex = 0;
					fourGtxBuffer[fourgtxBufferIndex++] = 0x02; //start byte //0
					fourGtxBuffer[fourgtxBufferIndex++] = 0x96; //frame info firmware info //1
					fourGtxBuffer[fourgtxBufferIndex++] = 0x01; //sub frame  //2
					fourGtxBuffer[fourgtxBufferIndex++] = 0x01; //length high //3
					fourGtxBuffer[fourgtxBufferIndex++] = 0x01; //length Low  //4

					sprintf(buff, "%s%c%s%c", OCPP.wifi_ssid, 0x07,
							OCPP.wifi_password, 0x07);

					memcpy(&fourGtxBuffer[fourgtxBufferIndex], buff,
							strlen(buff)); //6 &7

					fourgtxBufferIndex += strlen(buff);

					fourGtxBuffer[fourgtxBufferIndex++] = 0x03; //end byte //8

					fourGtxBuffer[3] = ((fourgtxBufferIndex - 6) / 256);  //3
					fourGtxBuffer[4] = (fourgtxBufferIndex - 6) % 256;   //4

					HAL_UART_Transmit(&huart2, (uint8_t*) fourGtxBuffer,
							fourgtxBufferIndex, 0Xffff);

				}
			} else if (OCPP.Communication_Mode == 1) {
				if (GSMreq_network_select == 1)   //V4.X.6
						{
					char lclarray[7];
					if (OCPP.ipselection == 0) //V4=1
							{
						lclarray[0] = 'I';
						lclarray[1] = 'P'; //v4
						lclarray[2] = '\0';

					} else if (OCPP.ipselection == 1) //V6=1
							{
						lclarray[0] = 'I';
						lclarray[1] = 'P';
						lclarray[2] = 'V';
						lclarray[3] = '6';
						lclarray[4] = '\0';
					} else if (OCPP.ipselection == 2) //V4V6=1
							{
						lclarray[0] = 'I';
						lclarray[1] = 'P';
						lclarray[2] = 'V';
						lclarray[3] = '4';
						lclarray[4] = 'V';
						lclarray[5] = '6';
						lclarray[6] = '\0';
					}

					memset((unsigned char*) fourGtxBuffer, 0x00,
							sizeof(fourGtxBuffer));
					memset((unsigned char*) buff, 0x00, sizeof(buff));

					fourgtxBufferIndex = 0;
					fourGtxBuffer[fourgtxBufferIndex++] = 0x02; //start byte //0
					fourGtxBuffer[fourgtxBufferIndex++] = 0x96; //frame info firmware info //1
					fourGtxBuffer[fourgtxBufferIndex++] = 0x01; //sub frame  //2
					fourGtxBuffer[fourgtxBufferIndex++] = 0x01; //length high //3
					fourGtxBuffer[fourgtxBufferIndex++] = 0x01; //length Low  //4

					sprintf(buff, "%s%c%s%c", OCPP.networkoperator, 0x07,
							lclarray, 0x07);

					memcpy(&fourGtxBuffer[fourgtxBufferIndex], buff,
							strlen(buff)); //6 &7

					fourgtxBufferIndex += strlen(buff);

					fourGtxBuffer[fourgtxBufferIndex++] = 0x03; //end byte //8

					fourGtxBuffer[3] = ((fourgtxBufferIndex - 6) / 256);  //3
					fourGtxBuffer[4] = (fourgtxBufferIndex - 6) % 256;   //4

					HAL_UART_Transmit(&huart2, (uint8_t*) fourGtxBuffer,
							fourgtxBufferIndex, 0Xffff);

					GSMreq_network_select = 0;
				}
			} else if (OCPP.Communication_Mode == 3) //ethernet
					{
				if (ether_connection_varify()) {
					////////////////////////4G_PARAMETER//////////////////////////////////

					memset((unsigned char*) fourGtxBuffer, 0x00,
							sizeof(fourGtxBuffer));
					memset((unsigned char*) buff, 0x00, sizeof(buff));

					//		       	sprintf(&buff,"%u",content_length);
					fourgtxBufferIndex = 0;
					fourGtxBuffer[fourgtxBufferIndex++] = 0x02; //start byte //0
					fourGtxBuffer[fourgtxBufferIndex++] = 0x9A; //frame info firmware info //1
					fourGtxBuffer[fourgtxBufferIndex++] = 0x01; //sub frame  //2
					fourGtxBuffer[fourgtxBufferIndex++] = 0x01; //length high //3
					fourGtxBuffer[fourgtxBufferIndex++] = 0x01; //length Low  //4

					sprintf(buff, "%d.%d.%d.%d%c%d.%d.%d.%d%c%d.%d.%d.%d%c",
							OCPP.ether_ip[0], OCPP.ether_ip[1],
							OCPP.ether_ip[2], OCPP.ether_ip[3], 0x07,
							OCPP.ether_getway[0], OCPP.ether_getway[1],
							OCPP.ether_getway[2], OCPP.ether_getway[3], 0x07,
							OCPP.ether_subnetmask[0], OCPP.ether_subnetmask[1],
							OCPP.ether_subnetmask[2], OCPP.ether_subnetmask[3],
							0x07);
					memcpy(&fourGtxBuffer[fourgtxBufferIndex], buff,
							strlen(buff)); //6 &7

					fourgtxBufferIndex += strlen(buff);

					fourGtxBuffer[fourgtxBufferIndex++] = 0x03; //end byte //8

					fourGtxBuffer[3] = ((fourgtxBufferIndex - 6) / 256);  //3
					fourGtxBuffer[4] = (fourgtxBufferIndex - 6) % 256;   //4

					HAL_UART_Transmit(&huart2, (uint8_t*) fourGtxBuffer,
							fourgtxBufferIndex, 0Xffff);

				}
			} else {
				//return 1;
			}
			req_network_select = 0;
		} else if (res_notfound == 1) {
			res_notfound = 0;
		} else if (wifi_connected == 1) {
			////////////////////////4G_PARAMETER//////////////////////////////////

			memset((unsigned char*) fourGtxBuffer, 0x00, sizeof(fourGtxBuffer));
			memset((unsigned char*) buff, 0x00, sizeof(buff));

			fourgtxBufferIndex = 0;
			fourGtxBuffer[fourgtxBufferIndex++] = 0x02;   //start byte //0
			fourGtxBuffer[fourgtxBufferIndex++] = 0x91; //frame info firmware info //1
			fourGtxBuffer[fourgtxBufferIndex++] = 0x01;   //sub frame  //2
			fourGtxBuffer[fourgtxBufferIndex++] = 0x01;   //length high //3
			fourGtxBuffer[fourgtxBufferIndex++] = 0x01;   //length Low  //4

			sprintf(buff, "%s%c%s%c%s%c%s%c%s", OCPP.OCPP_servername, seperator,
					OCPP.OCPP_Port, seperator, OCPP.ocpp_uri, seperator,
					OCPP.OCPP_username, seperator, OCPP.OCPP_Password);
			memcpy(&fourGtxBuffer[fourgtxBufferIndex], buff, strlen_1(buff)); //6 &7

			fourgtxBufferIndex += strlen_1(buff);

			fourGtxBuffer[fourgtxBufferIndex++] = 0x03; //end byte //8

			fourGtxBuffer[3] = ((fourgtxBufferIndex - 6) / 256);  //3
			fourGtxBuffer[4] = (fourgtxBufferIndex - 6) % 256;   //4

			HAL_UART_Transmit(&huart2, (uint8_t*) fourGtxBuffer,
					fourgtxBufferIndex, 0Xffff);
			wifi_connected = 0;

			/////////////////////////////////////////////////////////////
		} else if (req_ocpp_status == 1) {
			////////////////////////4G_PARAMETER//////////////////////////////////
			int BuffIndex = 0;
			buff[BuffIndex++] = 0x02; //START BYTE
			buff[BuffIndex++] = 0x92; //FRAME BYTE
			buff[BuffIndex++] = 0x00; //SUB FRAEME BYTE
			buff[BuffIndex++] = 0x00; //LENGH HIGH
			buff[BuffIndex++] = 0x01; //LENGTH LOW

			if (OCPP.ocpp_status[0] == 1) {
				buff[BuffIndex++] = 0x01; //OCPP ENABLE
			} else {
				buff[BuffIndex++] = 0x02; //OCPP DISABLE
			}
			buff[BuffIndex++] = 0x03; //END BYTE
			HAL_UART_Transmit(&huart2, (uint8_t*) buff, BuffIndex, 0xffff);
			req_ocpp_status = 0;
			//////////////////////////////////////////////////////////////////////
		}

		if (BootNotification_res == 1) {
			parse_BootNotification(Array1);
			BootNotification_res = 0;
		}
		if (RemoteStarttx_res == 1) {
			parse_remote_start_tx(Array1);
			RemoteStarttx_res = 0;
		}
		if (network_switch_flag) {

			if (GSM.wifi_enable_sts == 1) {
				////////////////////////4G_PARAMETER//////////////////////////////////
				int BuffIndex = 0;
				buff[BuffIndex++] = 0x02; //START BYTE
				buff[BuffIndex++] = 0x92; //FRAME BYTE
				buff[BuffIndex++] = 0x00; //SUB FRAEME BYTE
				buff[BuffIndex++] = 0x00; //LENGH HIGH
				buff[BuffIndex++] = 0x01; //LENGTH LOW

				buff[BuffIndex++] = 0x02; //OCPP DISABLE
				buff[BuffIndex++] = 0x03; //END BYTE
				HAL_UART_Transmit(&huart2, (uint8_t*) buff, BuffIndex, 0xffff);
				//////////////////////////////////////////////////////////////////////
				websocket_success = 0;
				HMI_websocket_disconnect = 1;
				HMI_wifi_disconnect = 1;
				ocpp_boot_status = 0;
				RELAY_SW_ESPON
				; //ESP ON;
			}
			if (GSM.gsm_enable_sts == 1) {

				////////////////////////4G_PARAMETER//////////////////////////////////
				int BuffIndex = 0;
				buff[BuffIndex++] = 0x02; //START BYTE
				buff[BuffIndex++] = 0x92; //FRAME BYTE
				buff[BuffIndex++] = 0x00; //SUB FRAEME BYTE
				buff[BuffIndex++] = 0x00; //LENGH HIGH
				buff[BuffIndex++] = 0x01; //LENGTH LOW

				buff[BuffIndex++] = 0x02; //OCPP DISABLE
				buff[BuffIndex++] = 0x03; //END BYTE
				HAL_UART_Transmit(&huart2, (uint8_t*) buff, BuffIndex, 0xffff);
				//////////////////////////////////////////////////////////////////////
				websocket_success = 0;
				HMI_websocket_disconnect = 1;
				HMI_wifi_disconnect = 1;
				ocpp_boot_status = 0;
				RELAY_SW_ESPOFF
				;

			}
			network_switch_flag = 0;
		}
		if (change == 1) {
			websocket_success = 0;
			HMI_websocket_disconnect = 1;
			HMI_wifi_disconnect = 1;
			ocpp_boot_status = 0;

			////////////////////////4G_PARAMETER//////////////////////////////////
			int BuffIndex = 0;
			buff[BuffIndex++] = 0x02;
			buff[BuffIndex++] = 0x90;
			buff[BuffIndex++] = 0x00;
			buff[BuffIndex++] = 0x00;
			buff[BuffIndex++] = 0x01;
			buff[BuffIndex++] = 0x01;
			buff[BuffIndex++] = 0x03;
			// sprintf(buff,"esp32_restart*");
			HAL_UART_Transmit_DMA(&huart2, (uint8_t*) buff, BuffIndex);
			change = 0;
			//////////////////////////////////////////////
		}
		if (write_para == 1) {
			write_para = 0;
			Write_Params();
			HAL_Delay(100);
			if ((fw_update == 1) && (OCPP.fw_status == 64)) {
				hard_reset = 1;
				fw_update = 0;
			}
		}
		if ((erage_chip == 1) && (flash_writing == 0) && (byte_in != 0)) {
			erage_chip = 0;
			if (chip_erase == 0) {
				//			 W25qxx_EraseChip();
				for (int i = 0; i < 3800; i++) {
					W25qxx_EraseSector(i);
					HAL_Delay(1);
					HAL_IWDG_Refresh(&hiwdg);
				}
			}
			byte_in = 0;
			byte_out = 0;
			SFlash_pointer_write();
			if (flash_writing == 0) {
				Clear_Register = 71;
			}
		}
///////////////////////////////////////////////////////////////////////
		if ((Store_Key_Parameter == 1) && (flash_writing == 0)) {
			Store_Key_Parameter = 0;

			Write_Key_Params();
		}
		if ((Clear_Register == 24 /* rfid_screen*/) && (flash_writing == 0)) {
			Clear_Register = 0;
			uint8_t k;
			(rfid_pointer.Added_rfid >= 5) ?
					(k = 5) : (k = rfid_pointer.Added_rfid);

			for (uint8_t j = 1; j <= k; j++) {
				if (read_rfid_last_data(j) == 1) {
					strcpy(rfid_data.TagId[j], rfid_data_to_flash.TagId);
					rfid_data.status[j] = rfid_data_to_flash.status;
					// strcpy(rfid_data_to_flash.expiery_time,rfid_data.expiery_time[LocalListAdding]);
					//	rfid_data_to_flash.status = rfid_data.status[LocalListAdding];
				}
			}
			enQueue_hmi(2402); //RFid
		}

		if (Type2_OCPP_Authorization_Flag) // && Ocpp_Setting.LocalAuthOffln == 1)
		{
			Type2_OCPP_Authorization_Flag = 0;
			uint8_t status = 0;

			if ((ocpp_boot_status) && (OCPP.ocpp_status[0] == 1)) {
				status = 3;
			} else if (Ocpp_Setting.LocalAuthOffln == 1) {
				if (rfid_pointer.Added_rfid <= 100) {
					for (int j = 1; j <= ((rfid_pointer.Added_rfid) + 1); j++) {
						if (read_rfid_last_data(j) == 1) {
							for (int i = 0; i < 10; i++) {
								if ((strcmp(tagid, rfid_data_to_flash.TagId))
										== 0) {
									if (rfid_data_to_flash.status == 1) {
										Get_Time();
										status = expiry_calculation( DC001_OCPP_timestamp1, rfid_data_to_flash.expiery_time[i]);
										//status = 1;
									}
									break;
								}
							}
						}
						if (status == 1)
							break;
					}
				}
			}

			if (status == 1) {
				if (charger_status_G1.start == Authenticate) {
					strcpy(charger_status_G1.start_tagid, tagid);
					//charger_status_G1.start = Try_To_Start;
					charger_status_G1.reson = Local;
					charger_status_G1.Authentication_done = 1;
					correct_rfid = 1;
				} else if (charger_status_G2.start == Authenticate) {
					strcpy(charger_status_G2.start_tagid, tagid);
					// charger_status_G2.start = Try_To_Start;
					charger_status_G2.reson = Local;
					charger_status_G2.Authentication_done = 1;
					correct_rfid = 1;
				} else if (charger_status_G2.stop == Authenticate) {
					strcpy(charger_status_G2.start_tagid, tagid);
					charger_status_G2.stop = Try_To_Stop;
					charger_status_G2.reson = Local;
					correct_rfid = 1;
					charger_status_G2.charging_status = Finishing_ChargerPoint;
				} else if (charger_status_G1.stop == Authenticate) {
					strcpy(charger_status_G1.start_tagid, tagid);
					charger_status_G1.stop = Try_To_Stop;
					charger_status_G1.reson = Local;
					correct_rfid = 1;
					charger_status_G1.charging_status = Finishing_ChargerPoint;
				}
			} else if (status == 3) {
				if (charger_status_G1.start == Authenticate) {
					strcpy(charger_status_G1.start_tagid, tagid);
					//charger_status_G1.start = Try_To_Start;
					charger_status_G1.reson = Local;
					if (Ocpp_Setting.LocalPreAuth == false) {
						charger_status_G1.ocpp_status = Authorise_Req;
					}
//					charger_status_G1.Authentication_done = 1;
					correct_rfid = 1;
				} else if (charger_status_G2.start == Authenticate) {
					strcpy(charger_status_G2.start_tagid, tagid);
					// charger_status_G2.start = Try_To_Start;
					charger_status_G2.reson = Local;
					if (Ocpp_Setting.LocalPreAuth == false) {
						charger_status_G2.ocpp_status = Authorise_Req;
					}
					// charger_status_G2.Authentication_done = 1;
					correct_rfid = 1;
				} else if (charger_status_G1.stop == Authenticate) {
					if (strcmp_1(charger_status_G1.start_tagid, tagid) == 0) {
						// strcpy(charger_status_G1.start_tagid, tagid);
						charger_status_G1.stop = Try_To_Stop;
						charger_status_G1.reson = Local;
						correct_rfid = 1;
						charger_status_G1.charging_status =
								Finishing_ChargerPoint;
					}
				} else if (charger_status_G2.stop == Authenticate) {
					if (strcmp_1(charger_status_G1.start_tagid, tagid) == 0) {
						// strcpy(charger_status_G2.start_tagid, tagid);
						charger_status_G2.stop = Try_To_Stop;
						charger_status_G2.reson = Local;
						correct_rfid = 1;
						charger_status_G2.charging_status =
								Finishing_ChargerPoint;
					}
				}
			}

			else {
				incorrect_rfid = 1;
			}
		}
/////////////////////////////////////////////////////////////////////////

//	       	  free(buff);
//	       	  buff = NULL;
/////////////////////////////////////
	}

}

char Gun1_ocpp(void) {
	if (charger_status_G1.ocpp_status == Authorise_Req) {

		++charger_status_G1.timer;
		if (charger_status_G1.timer > 1) {
			enQueue(G1_Authorise_EVSE);
			charger_status_G1.timer = -15;
		}
	} else if (charger_status_G1.ocpp_status == StartTransaction_Req) {
		//G1 send start transaction
		++charger_status_G1.timer;
		if (charger_status_G1.timer > 0) {
			enQueue(G1_StartCharging_EVSE);
			charger_status_G1.timer = -15;
		}
	} else if (charger_status_G1.ocpp_status == Current_Demand) {
		if (++charger_status_G1.timer == 1) {
			enQueue(G1_StatusNotification);
			// enQueue(G1_StatusNotification);
		} else if (charger_status_G1.timer == 2) {
			enQueue(G1_MeterValue_Began);
		} else if (charger_status_G1.timer > (Ocpp_Setting.MeterIntvl + 5)) {
			enQueue(G1_MeterValue_Periodic);
			charger_status_G1.timer = 5;
		}
	} else if (charger_status_G1.ocpp_status == StopTransaction_Req) {
		//G1 send stop transaction
		++charger_status_G1.timer;
		if (charger_status_G1.timer >= 1) {
			enQueue(G1_StopCharging_EVSE);
			enQueue(G1_MeterValue_End);
			charger_status_G1.timer = -15;
		}
	} else if (charger_status_G1.ocpp_status == StopTransaction_Success) {
		//G1 finish send notification
		charger_status_G1.ocpp_status = Not_Connect;
		//charger_status_G1.charging_status = Finishing_ChargerPoint;
		charger_status_G1.On_Going_Tx = Tx_Success;
		enQueue(G1_StatusNotification);
		charger_status_G1.timer = Ocpp_Setting.StatusDuration;

	} else if (charger_status_G1.ocpp_status == Not_Connect
			|| charger_status_G1.ocpp_status == Boot_Success) {
		++charger_status_G1.timer;
		charger_status_G1.Clock_Align_Timer++;
		if (charger_status_G1.timer > Ocpp_Setting.StatusDuration) {
			if (charger_status_G1.charging_status == SuspendedEVSE_ChargerPoint
					|| charger_status_G1.charging_status == Finishing_ChargerPoint
					|| charger_status_G1.charging_status == SuspendedEV_ChargerPoint) {
				if (Ocpp_Setting.Operative[1] == Available_ChargerPoint) {
					charger_status_G1.charging_status = Available_ChargerPoint;
				} else if (Ocpp_Setting.Operative[1] == Unavailable_ChargerPoint) {
					charger_status_G1.charging_status = Unavailable_ChargerPoint;
				}
			}
			enQueue(G1_StatusNotification);
			charger_status_G1.timer = 0;
		} else if (charger_status_G1.Clock_Align_Timer >= Ocpp_Setting.ClkAlgnIntvl) {
			enQueue(G1_MeterValue_ClockAlign);
			charger_status_G1.Clock_Align_Timer = 0;
		}
	}

	if (charger_status_G1.ocpp_status == Authorise_Success) {
		//V6 change
//		gun_1 = G_charging;
//		charger_status_G1.charging_status = Charging_ChargerPoint;
//		HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_RESET); //ON
//		charger_status_G1.ocpp_status = StartTransaction_Req;
		charger_status_G1.Authentication_done = 1;
		charger_status_G1.Retries = 0;
	} else if (charger_status_G1.ocpp_status == StartTransaction_Success) {
		charger_status_G1.ocpp_status = Current_Demand;
		charger_status_G1.Retries = 0;
		charger_status_G1.timer = 0;
		charger_status_G1.On_Going_Tx = Tx_Pending;
	} else if ((charger_status_G1.ocpp_status == Authorise_Fail)
			|| (charger_status_G1.ocpp_status == StartTransaction_Fail)) {

		if (++charger_status_G1.Retries < Ocpp_Setting.FailedAttempt) //V4.
				{
			if (charger_status_G1.ocpp_status == StartTransaction_Fail) {
				charger_status_G1.ocpp_status = StartTransaction_Req;
			} else if (charger_status_G1.ocpp_status == Authorise_Fail) {
				charger_status_G1.ocpp_status = Authorise_Req;
			}
		} else {
			charger_status_G1.ocpp_status = Not_Connect;
			if (charger_status_G1.start == Started) {
				charger_status_G1.stop = Try_To_Stop;            //V4.x.6 change
				charger_status_G1.charging_status = Available_ChargerPoint; //V5.0.0 change

			}
			charger_status_G1.Retries = Ocpp_Setting.FailedAttempt;
		}
	}
}
char Gun2_ocpp(void) {
	if (charger_status_G2.ocpp_status == Authorise_Req) {
		//G1 send start transaction
		++charger_status_G2.timer;
		if (charger_status_G2.timer > 1) {
			enQueue(G2_Authorise_EVSE);
			charger_status_G2.timer = -15;
		}
	} else if (charger_status_G2.ocpp_status == StartTransaction_Req) {
		//G1 send start transaction
		++charger_status_G2.timer;
		if (charger_status_G2.timer > 0) {
			enQueue(G2_StartCharging_EVSE);
			charger_status_G2.timer = -15;
		}
	} else if (charger_status_G2.ocpp_status == Current_Demand) {

		if (++charger_status_G2.timer == 1) {
			enQueue(G2_StatusNotification);
			enQueue(G2_StatusNotification);
		} else if (charger_status_G2.timer == 2) {
			enQueue(G2_MeterValue_Began);
		} else if (charger_status_G2.timer > (Ocpp_Setting.MeterIntvl + 5)) {

			enQueue(G2_MeterValue_Periodic);
			charger_status_G2.timer = 5;
		}
	} else if (charger_status_G2.ocpp_status == StopTransaction_Req) {
		//G2 send stop transaction
		++charger_status_G2.timer;
		if (charger_status_G2.timer >= 1) {
			enQueue(G2_StopCharging_EVSE);
			enQueue(G2_MeterValue_End);
			charger_status_G2.timer = -15;
		}
	} else if (charger_status_G2.ocpp_status == StopTransaction_Success) {
		//G2 finish send notification
		charger_status_G2.ocpp_status = Not_Connect;
		//  charger_status_G2.charging_status = Finishing_ChargerPoint;
		enQueue(G2_StatusNotification);
		charger_status_G2.On_Going_Tx = Tx_Success;
		charger_status_G2.timer = Ocpp_Setting.StatusDuration;
	} else if (charger_status_G2.ocpp_status == Not_Connect
			|| charger_status_G2.ocpp_status == Boot_Success) {
		++charger_status_G2.timer;
		charger_status_G2.Clock_Align_Timer++;
		if (charger_status_G2.timer > Ocpp_Setting.StatusDuration) {
			if (charger_status_G2.charging_status == SuspendedEVSE_ChargerPoint
					|| charger_status_G2.charging_status
							== Finishing_ChargerPoint
					|| charger_status_G2.charging_status
							== SuspendedEV_ChargerPoint) {
				if (Ocpp_Setting.Operative[2] == Available_ChargerPoint) {
					charger_status_G2.charging_status = Available_ChargerPoint;
				} else if (Ocpp_Setting.Operative[2]
						== Unavailable_ChargerPoint) {
					charger_status_G2.charging_status =
							Unavailable_ChargerPoint;
				}
			}
			enQueue(G2_StatusNotification);
			charger_status_G2.timer = 0;
		} else if (charger_status_G2.Clock_Align_Timer
				>= Ocpp_Setting.ClkAlgnIntvl) {
			enQueue(G2_MeterValue_ClockAlign);
			charger_status_G2.Clock_Align_Timer = 0;
		}
	}

	if (charger_status_G2.ocpp_status == Authorise_Success) {
		gun_2 = G_charging;
		charger_status_G2.charging_status = Charging_ChargerPoint;
		HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_RESET); //ON
		charger_status_G2.ocpp_status = StartTransaction_Req;
		charger_status_G2.Retries = 0;
	} else if (charger_status_G2.ocpp_status == StartTransaction_Success) {
		charger_status_G2.ocpp_status = Current_Demand;
		charger_status_G2.Retries = 0;
		charger_status_G2.timer = 0;
		charger_status_G2.On_Going_Tx = Tx_Pending;
	} else if ((charger_status_G2.ocpp_status == Authorise_Fail)
			|| (charger_status_G2.ocpp_status == StartTransaction_Fail)) {
		if (++charger_status_G2.Retries <= Ocpp_Setting.FailedAttempt) {
			if (charger_status_G2.ocpp_status == StartTransaction_Fail) {
				charger_status_G2.ocpp_status = StartTransaction_Req; //4.1.5
			} else if (charger_status_G2.ocpp_status == Authorise_Fail) {
				charger_status_G2.ocpp_status = Authorise_Req;	//4.1.5
			}
		} else {
			charger_status_G2.ocpp_status = Not_Connect;
			if (charger_status_G2.start == Started) {
				charger_status_G2.stop = Try_To_Stop;            //V4.x.6 change
				charger_status_G2.charging_status = Available_ChargerPoint; //V5.0.0 change

			}
			charger_status_G2.Retries = Ocpp_Setting.FailedAttempt;
		}
	}
}
char Gun3_ocpp(void) {
	if (charger_status_G3.ocpp_status == Authorise_Req) {
		//G1 send start transaction
		++charger_status_G3.timer;
		if (charger_status_G3.timer > 1) {
			enQueue(G3_Authorise_EVSE);
			charger_status_G3.timer = -15;
		}
	} else if (charger_status_G3.ocpp_status == StartTransaction_Req) {
		//G1 send start transaction
		++charger_status_G3.timer;
		charger_status_G3.On_Going_Tx = Tx_Pending;
		if (charger_status_G3.timer > 0) {
			enQueue(G3_StartCharging_EVSE);
			charger_status_G3.timer = -15;
		}
	} else if (charger_status_G3.ocpp_status == Current_Demand) {

		if (++charger_status_G3.timer == 1) {
			enQueue(G3_StatusNotification);
		} else if (charger_status_G3.timer == 2) {
			enQueue(G3_MeterValue_Began);
		} else if (charger_status_G3.timer > (Ocpp_Setting.MeterIntvl + 5)) {
			enQueue(G3_MeterValue_Periodic);
			charger_status_G3.timer = 5;
		}
	} else if (charger_status_G3.ocpp_status == StopTransaction_Req) {
		//G3 send stop transaction
		++charger_status_G3.timer;
		if (charger_status_G3.timer >= 1) {
			enQueue(G3_StopCharging_EVSE);
			enQueue(G3_MeterValue_End);
			charger_status_G3.timer = -15;
		}
	} else if (charger_status_G3.ocpp_status == StopTransaction_Success) {
		//G3 finish send notification
		charger_status_G3.ocpp_status = Not_Connect;

		charger_status_G3.On_Going_Tx = Tx_Success;
		//  charger_status_G3.charging_status = Finishing_ChargerPoint;
		enQueue(G3_StatusNotification);
		charger_status_G3.timer = Ocpp_Setting.StatusDuration;
	} else if (charger_status_G3.ocpp_status == Not_Connect
			|| charger_status_G3.ocpp_status == Boot_Success) {
		++charger_status_G3.timer;
		charger_status_G3.Clock_Align_Timer++;
		if (charger_status_G3.timer > Ocpp_Setting.StatusDuration) {
			if (charger_status_G3.charging_status == SuspendedEVSE_ChargerPoint
					|| charger_status_G3.charging_status
							== Finishing_ChargerPoint
					|| charger_status_G3.charging_status
							== SuspendedEV_ChargerPoint) {
				if (Ocpp_Setting.Operative[3] == Available_ChargerPoint) {
					charger_status_G3.charging_status = Available_ChargerPoint;
				} else if (Ocpp_Setting.Operative[3]
						== Unavailable_ChargerPoint) {
					charger_status_G3.charging_status =
							Unavailable_ChargerPoint;
				}
			}
			enQueue(G3_StatusNotification);
			charger_status_G3.timer = 0;
		} else if (charger_status_G3.Clock_Align_Timer
				>= Ocpp_Setting.ClkAlgnIntvl) {
			enQueue(G3_MeterValue_ClockAlign);
			charger_status_G3.Clock_Align_Timer = 0;
		}
	}

	if (charger_status_G3.ocpp_status == Authorise_Success) {
		gun_3 = G_charging;
		charger_status_G3.charging_status = Charging_ChargerPoint;
		HAL_GPIO_WritePin(RELAY_G3_GPIO_Port, RELAY_G3_Pin, GPIO_PIN_RESET); //ON
		charger_status_G3.ocpp_status = StartTransaction_Req;
		charger_status_G3.Retries = 0;
	} else if (charger_status_G3.ocpp_status == StartTransaction_Success) {
		charger_status_G3.ocpp_status = Current_Demand;
		charger_status_G3.Retries = 0;
	} else if ((charger_status_G3.ocpp_status == Authorise_Fail)
			|| (charger_status_G3.ocpp_status == StartTransaction_Fail)) {
		if (++charger_status_G3.Retries <= Ocpp_Setting.FailedAttempt) {
			if (charger_status_G3.ocpp_status == StartTransaction_Fail) {
				charger_status_G3.ocpp_status = StartTransaction_Req;
			} else if (charger_status_G3.ocpp_status == Authorise_Fail) {
				charger_status_G3.ocpp_status = Authorise_Req;
			}
		} else {
			if (charger_status_G3.start == Started) {
				charger_status_G3.stop = Try_To_Stop;            //V4.x.6 change
				charger_status_G3.charging_status = Available_ChargerPoint; //V5.0.0 change
			}

			charger_status_G3.ocpp_status = Not_Connect;
			charger_status_G3.Retries = Ocpp_Setting.FailedAttempt;
		}
	}
}

void AC_TYPE2(void) {
	if (Ocpp_Setting.Operative[1] == Available_ChargerPoint)
	{
		if (CURRENT_STATE == STATE_A) {
			stop_pwm();
			// pwm_start_stop =1;
			if (charger_status_G1.charging_status == Charging_ChargerPoint|| ALARM_CHARGING_STATUS == true) {
				charger_status_G1.stop = Try_To_Stop;
				if (ALARM_CHARGING_STATUS == true) {
					ALARM_CHARGING_STATUS = 2;
					charger_status_G1.start = Started;
				}
				charger_status_G1.charging_status = SuspendedEV_ChargerPoint;
			} else if (charger_status_G1.charging_status != Faulted_ChargerPoint) {
				if (charger_status_G1.charging_status != Available_ChargerPoint) {
					gun_1 = G_NoError;
					// charger_status_G1.timer = Ocpp_Setting.StatusDuration;
					enQueue(G1_StatusNotification);
				}
				charger_status_G1.charging_status = Available_ChargerPoint;
				charger_status_G1.reson = Other;
				charger_status_G1.stop = Stoped;
				charger_status_G1.start = Stoped;
				charger_status_G1.Authentication_done = 0;
			}
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_SET); //ON
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_SET); //ON
		} else if (CURRENT_STATE == STATE_B) {
			if (charger_status_G1.Authentication_done && charger_status_G1.error == NoError_ChargerPoint) {
				start_pwm();
				if (charger_status_G1.Authentication_done == PowerFailAuthorisation) {
					charger_status_G1.Authentication_done = PowerFailAuthorisation_Success;
				}
				charger_status_G1.timer = 0;
			} else {
				stop_pwm();
				if (charger_status_G1.charging_status == Charging_ChargerPoint) {
					if (charger_status_G1.start == Started) {
						charger_status_G1.stop = Try_To_Stop;
						charger_status_G1.charging_status = SuspendedEV_ChargerPoint;
						charger_status_G1.timer = Ocpp_Setting.StatusDuration;
						enQueue(G1_StatusNotification);

						charger_status_G1.reson = EVDisconnected;
						gun_1 = G_Discharging;
					}
				} else if (charger_status_G1.charging_status == Available_ChargerPoint) {
					charger_status_G1.charging_status = Preparing_ChargerPoint;
					// charger_status_G1.reson = Other;
					charger_status_G1.timer = Ocpp_Setting.StatusDuration;
					gun_1 = G_connected;
					enQueue(G1_StatusNotification);
				}
			}
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_SET);
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_SET); //ON
		} else if ((CURRENT_STATE == STATE_C) || (CURRENT_STATE == STATE_D)) {
			if (charger_status_G1.Authentication_done) {
				if (charger_status_G1.Authentication_done == PowerFailAuthorisation) {
					return;
				} else if (charger_status_G1.Authentication_done == PowerFailAuthorisation_Success) {
					charger_status_G1.start = PowerFail_To_Start;
				} else if (charger_status_G1.Authentication_done == LocalAuthorisation
						|| charger_status_G1.Authentication_done == RemoteAuthorisation) {
					charger_status_G1.start = Try_To_Start;
				}

				charger_status_G1.Authentication_done = 0;
				start_pwm();
			}
		}
	}
	/***********************************************V3.3.1***************************************************/
	if ((charger_status_G1.start == Try_To_Start
			|| charger_status_G1.start == PowerFail_To_Start)
			&& (charger_status_G1.error == NoError_ChargerPoint)) {

		if (charger_status_G1.start == PowerFail_To_Start) {
			charger_status_G1.start = Started;
			charger_status_G1.ocpp_status = StartTransaction_Success;
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_RESET); //ON
			charger_status_G1.charging_status = Charging_ChargerPoint;
			gun_1 = G_charging;
			ALARM_CHARGING_STATUS = false;
			return;
		}
		ALARM_CHARGING_STATUS = false;
		charger_status_G1.charging_time = 0;
		charger_status_G1.Bill_Amount = 0;
		Get_Time();

		if ((websocket_success == 0) && (charger_status_G1.On_Going_Tx == Tx_Pending)) {
			charger_status_G1.On_Going_Tx = Tx_Fail;
		}

		strcpy(charger_status_G1.start_time, DC001_OCPP_timestamp1);
		if ((charger_status_G1.reson == Remote)
				|| (Ocpp_Setting.LocalPreAuth == true)
				|| charger_status_G1.ocpp_status == Authorise_Success) {
			gun_1 = G_charging;
			charger_status_G1.ocpp_status = StartTransaction_Req;

			charger_status_G1.charging_status = Charging_ChargerPoint;
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_RESET); //ON
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_RESET); //ON
		} else if (Ocpp_Setting.LocalPreAuth == false) {
			charger_status_G1.ocpp_status = Authorise_Req;
		}

		charger_status_G1.start_energy = energy;
		charger_status_G1.timer = Ocpp_Setting.StatusDuration;
		;
		charger_status_G1.start = Started;

		if (OCPP.ocpp_status[0] == ENABLE) {

		} else if (Ocpp_Setting.LocalAuthOffln == true) {
			gun_1 = G_charging;
			charger_status_G1.charging_status = Charging_ChargerPoint;
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_RESET); //ON
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_RESET); //ON

		}
	}
	if ((charger_status_G1.start == Started)
			&& ((charger_status_G1.stop == Error)
					|| (charger_status_G1.stop == Try_To_Stop))) {
		stop_pwm();
#if defined(NAYARA)
		if ((ALARM_FLAG == ALARM_OVERVOLTAGE || ALARM_FLAG == ALARM_UNDERVOLTAGE || ALARM_FLAG == ALARM_POWERFAIL)
				&& ALARM_CHARGING_STATUS == false) {
			ALARM_CHARGING_STATUS = true;
			charger_status_G1.start = Stoped;
			charger_status_G1.stop = Stoped;
			gun_1 = G_Discharging;
			s6_counter1 = 0;
			PWM_stop_flag = 1;
			update_variable = 1;
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_SET); //OFF
			HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_SET); //OFF
			return;
		}
		ALARM_CHARGING_STATUS = false;
#endif
		Get_Time();
		strcpy(charger_status_G1.stop_time, DC001_OCPP_timestamp1);
		charger_status_G1.timer = 0;
		if ((websocket_success == 0) && (charger_status_G1.On_Going_Tx == Tx_Pending)) {
			charger_status_G1.On_Going_Tx = Tx_Fail;
			charger_status_G1.charging_status = Available_ChargerPoint; //V4.1.3
		}
		charger_status_G1.ocpp_status = StopTransaction_Req;
		charger_status_G1.stop_energy = energy;
		if (OCPP.ocpp_status[0] == 0) {
			charger_status_G1.charging_status = Available_ChargerPoint; //V4.1.3
			Billing(1);
//			enQueue_hmi(1903); //Bill
//			enQueue_hmi(19);
			Clear_Register = 19;
		} else {
			Total_time = charger_status_G1.charging_time; // //V4.1.3
			Total_cost = charger_status_G1.Bill_Amount;
			Total_unit = charger_status_G1.stop_energy - charger_status_G1.start_energy;
//			enQueue_hmi(1903); //Bill
//			enQueue_hmi(19);
			Clear_Register = 19;
			/*	if(Cash_Memory.counter > 9)
			 {
			 Cash_Memory.counter = 0;
			 }

			 Cash_Memory.Metervalue[Cash_Memory.counter] = charger_status_G1.stop_energy;
			 Cash_Memory.transaction_id[Cash_Memory.counter] = charger_status_G1.transaction_id;
			 Cash_Memory.Reson[Cash_Memory.counter] = charger_status_G1.reson;
			 strcpy(Cash_Memory.StopTxTime[Cash_Memory.counter],charger_status_G1.stop_time);
			 strcpy(Cash_Memory.Tag_Id[Cash_Memory.counter],charger_status_G1.start_tagid);
			 Cash_Memory.counter++;
			 Write_CACH_Params();*/
//			 Billing(1);
		}

		charger_status_G1.stop = Stoped;
		charger_status_G1.start = Stoped;

		s6_counter1 = 0;
		update_variable = 1;

		HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_SET); //OFF
		HAL_GPIO_WritePin(RELAY_G1_GPIO_Port, RELAY_G1_Pin, GPIO_PIN_SET); //OFF
		gun_1 = G_Discharging;
	}
	////////////////////////////////////////////////////////
}
void AC_TYPE2_1(void) {
	// if (Ocpp_Setting.Operative[2] == Available_ChargerPoint) 
	{
		/////////////////////////////////////////////////////////////////////////////////
		if (CURRENT_STATE_1 == STATE_A) {
			stop_pwm_1();
			// pwm_start_stop_1 =1;
			if (charger_status_G2.charging_status == Charging_ChargerPoint) {
				charger_status_G2.stop = Try_To_Stop;
				charger_status_G2.charging_status = SuspendedEV_ChargerPoint;
			} else if (charger_status_G2.charging_status
					!= Faulted_ChargerPoint) {
				if (charger_status_G2.charging_status
						!= Available_ChargerPoint) {
					gun_2 = G_NoError;
					charger_status_G2.timer = Ocpp_Setting.StatusDuration;
					enQueue(G2_StatusNotification);
				}
				charger_status_G2.charging_status = Available_ChargerPoint;
				charger_status_G2.reson = Other;
				charger_status_G2.stop = Stoped;
				charger_status_G2.start = Stoped;
				charger_status_G2.Authentication_done = 0;
			}
			HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_SET); //ON
			HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_SET); //ON
		} else if (CURRENT_STATE_1 == STATE_B) {
			if (charger_status_G2.Authentication_done
					&& charger_status_G2.error == NoError_ChargerPoint) {
				start_pwm_1();
			} else {
				stop_pwm_1();
				//pwm_start_stop_1 =1;
				if (charger_status_G2.charging_status
						== Charging_ChargerPoint) {
					if (charger_status_G2.start == Started) {
						charger_status_G2.stop = Try_To_Stop;
						charger_status_G2.charging_status =
								SuspendedEV_ChargerPoint;
						charger_status_G2.timer = Ocpp_Setting.StatusDuration;
						enQueue(G2_StatusNotification);
						charger_status_G2.reson = EVDisconnected;
						gun_2 = G_Discharging;
					}
				} else if (charger_status_G2.charging_status
						== Available_ChargerPoint) {
					charger_status_G2.charging_status = Preparing_ChargerPoint;
					charger_status_G2.reson = Other;
					charger_status_G2.timer = Ocpp_Setting.StatusDuration;
					gun_2 = G_connected;
					enQueue(G2_StatusNotification);
				}
			}
			HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_SET);
			HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_SET); //ON
		} else if ((CURRENT_STATE_1 == STATE_C)
				|| (CURRENT_STATE_1 == STATE_D)) {
			if (charger_status_G2.Authentication_done) {
				charger_status_G2.Authentication_done = 0;
				start_pwm_1();
				charger_status_G2.start = Try_To_Start;
			}
		}
	}
	/***********************************************V3.3.1***************************************************/
	if ((charger_status_G2.start == Try_To_Start)
			&& (charger_status_G2.error == NoError_ChargerPoint)) {
		charger_status_G2.charging_time = 0;
		charger_status_G2.Bill_Amount = 0;
		charger_status_G2.start = Started;
		Get_Time();
		if ((websocket_success == 0)
				&& (charger_status_G2.On_Going_Tx == Tx_Pending)) {
			charger_status_G2.On_Going_Tx = Tx_Fail;
		}

		strcpy(charger_status_G2.start_time, DC001_OCPP_timestamp1);
		if ((charger_status_G2.reson == Remote)
				|| (Ocpp_Setting.LocalPreAuth == true)
				|| charger_status_G2.ocpp_status == Authorise_Success) {
			gun_2 = G_charging;
			charger_status_G2.ocpp_status = StartTransaction_Req;
			charger_status_G2.charging_status = Charging_ChargerPoint;
			HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_RESET); //ON
			HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_RESET); //ON
		} else if (Ocpp_Setting.LocalPreAuth == false) {
			charger_status_G2.ocpp_status = Authorise_Req;
		}

		charger_status_G2.start_energy = energy2;
		charger_status_G2.timer = Ocpp_Setting.StatusDuration;
		;
		charger_status_G2.start = Started;

		if (OCPP.ocpp_status[0] == ENABLE) {

		} else if (Ocpp_Setting.LocalAuthOffln == true) {
			gun_2 = G_charging;
			charger_status_G2.charging_status = Charging_ChargerPoint;
			HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_RESET); //ON
			HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_RESET); //ON

		}
	}

	//////////////////////////////////////////////////////////////////////////////
	if ((charger_status_G2.start == Started)
			&& ((charger_status_G2.stop == Error)
					|| (charger_status_G2.stop == Try_To_Stop))) {
		stop_pwm_1();
		Get_Time();
		strcpy(charger_status_G2.stop_time, DC001_OCPP_timestamp1);
		charger_status_G2.timer = 0;
		charger_status_G2.ocpp_status = StopTransaction_Req;

		if ((websocket_success == 0)
				&& (charger_status_G2.On_Going_Tx == Tx_Pending)) {
			charger_status_G2.On_Going_Tx = Tx_Fail;
			charger_status_G2.charging_status = Available_ChargerPoint; //V4.1.3
		}
		charger_status_G2.ocpp_status = StopTransaction_Req;
		charger_status_G2.stop_energy = energy2;
		if (OCPP.ocpp_status[0] == 0) {
			charger_status_G2.charging_status = Available_ChargerPoint; //V4.1.3
			Billing(2);
			Clear_Register = 19;
//			enQueue_hmi(1903); //Bill
//			enQueue_hmi(33);
		} else {
			Total_time = charger_status_G2.charging_time; // //V4.1.3
			Total_cost = charger_status_G2.Bill_Amount;
			Total_unit = charger_status_G2.stop_energy
					- charger_status_G2.start_energy;
			Clear_Register = 19;
//			enQueue_hmi(1903); //Bill
//			enQueue_hmi(33);
			if (Cash_Memory.counter > 9) {
				Cash_Memory.counter = 0;
			}

			Cash_Memory.Metervalue[Cash_Memory.counter] =
					charger_status_G2.stop_energy;
			Cash_Memory.transaction_id[Cash_Memory.counter] =
					charger_status_G2.transaction_id;
			Cash_Memory.Reson[Cash_Memory.counter] = charger_status_G2.reson;
			strcpy(Cash_Memory.StopTxTime[Cash_Memory.counter],
					charger_status_G2.stop_time);
			strcpy(Cash_Memory.Tag_Id[Cash_Memory.counter],
					charger_status_G2.start_tagid);
			Cash_Memory.counter++;
			Clear_Register = 19;
			Write_CACH_Params();
		}

		charger_status_G2.stop = Stoped;
		charger_status_G2.start = Stoped;

		s6_counter2 = 0;
		update_variable = 1;

		HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_SET); //OFF
		HAL_GPIO_WritePin(RELAY_G2_GPIO_Port, RELAY_G2_Pin, GPIO_PIN_SET); //OFF
		gun_2 = G_Discharging;
	}
	////////////////////////////////////////////////////////

}

unsigned char Is_EvStatus(void) {
	return CURRENT_STATE;
}
void adc_check() {
	static uint8_t lclcnt = 0;
	if (adc_init == 0)
		return;

	HAL_ADC_Start_DMA(&hadc1, adc1_dat, 1);
	cp_val = adc1_dat[0]; //3081
	hmicp_val = cp_val;

	if (update_CP_Count == 1) {
		if ((cp_val <= OCPP.STATE_A_LEVEL + Ocpp_Setting.offset)
				&& (cp_val >= OCPP.STATE_A_LEVEL - Ocpp_Setting.offset)) {
			count_D = 0;
			count_B = 0;
			count_C = 0;
			if (++count_A > Ocpp_Setting.count) {
				CURRENT_STATE = STATE_A;
				count_A = 0;
			}
		} else if ((cp_val <= OCPP.STATE_B_LEVEL + Ocpp_Setting.offset)
				&& (cp_val >= OCPP.STATE_B_LEVEL - Ocpp_Setting.offset)) {
			count_D = 0;
			count_C = 0;
			count_A = 0;
			if (++count_B > Ocpp_Setting.count) {
				CURRENT_STATE = STATE_B;
				count_B = 0;
			}
		} else if ((cp_val <= OCPP.STATE_C_LEVEL + Ocpp_Setting.offset)
				&& (cp_val >= OCPP.STATE_C_LEVEL - Ocpp_Setting.offset)) {
			count_D = 0;
			count_B = 0;
			count_A = 0;
			if (++count_C > Ocpp_Setting.count) {
				CURRENT_STATE = STATE_C;
				count_C = 0;
			}
		} else if ((cp_val <= OCPP.STATE_D_LEVEL + Ocpp_Setting.offset)
				&& (cp_val >= OCPP.STATE_D_LEVEL - Ocpp_Setting.offset)) {
			count_C = 0;
			count_B = 0;
			count_A = 0;
			if (++count_D > Ocpp_Setting.count) {
				CURRENT_STATE = STATE_D;
				count_D = 0;
			}
		} else {
			count_D = 0;
			count_C = 0;
			count_B = 0;
			count_A = 0;
		}
		update_CP_Count = 0;
	}
//V501change
#if cpchange == no
	  if((cp_val<=STATE_A_LEVEL+100)&&(cp_val>=STATE_A_LEVEL-100))
		{
		  count_D = 0;
		  count_B = 0;
		  count_C = 0;
		  if(++count_A > 25)
		  {
			CURRENT_STATE=STATE_A;
			count_A = 0;
		  }
		}
		else if((cp_val<=STATE_B_LEVEL+100)&&(cp_val>=STATE_B_LEVEL-100))
		{
			count_D = 0;
			count_C = 0;
			count_A = 0;
			if(++count_B > 25)
			{
				CURRENT_STATE=STATE_B;
				count_B = 0;
			}
		}
		else if((cp_val<=STATE_C_LEVEL+100)&&(cp_val>=STATE_C_LEVEL-100))
		{
			count_D = 0;
			count_B = 0;
			count_A = 0;
			if(++count_C > 25)
			  {
				CURRENT_STATE=STATE_C;
				count_C = 0;
			  }
		}
		else if((cp_val<=STATE_D_LEVEL+100)&&(cp_val>=STATE_D_LEVEL-100))
		{
			count_C = 0;
			count_B = 0;
			count_A = 0;
			if(++count_D > 25)
			  {
				CURRENT_STATE=STATE_D;
				count_D = 0;
			  }
		}
#endif
}

void adc_check_2() {
	if (adc_init_2 == 0)
		return;

	HAL_ADC_Start_DMA(&hadc2, adc1_dat_2, 1);
	cp_val_2 = adc1_dat_2[0]; //3081
	hmicp_val_1 = cp_val_2;
//V501change
	if (update_CP_1_Count == 1) {
		if ((cp_val_2 <= OCPP.STATE_A_LEVEL + Ocpp_Setting.offset)
				&& (cp_val_2 >= OCPP.STATE_A_LEVEL - 100)) {
			count_D_2 = 0;
			count_B_2 = 0;
			count_C_2 = 0;
			if (++count_A_2 > Ocpp_Setting.count) {
				CURRENT_STATE_1 = STATE_A_2;
				count_A_2 = 0;
			}
		} else if ((cp_val_2 <= OCPP.STATE_B_LEVEL + Ocpp_Setting.offset)
				&& (cp_val_2 >= OCPP.STATE_B_LEVEL - Ocpp_Setting.offset)) {
			count_D_2 = 0;
			count_C_2 = 0;
			count_A_2 = 0;
			if (++count_B_2 > Ocpp_Setting.count) {
				CURRENT_STATE_1 = STATE_B_2;
				count_B_2 = 0;
			}
		} else if ((cp_val_2 <= OCPP.STATE_C_LEVEL + Ocpp_Setting.offset)
				&& (cp_val_2 >= OCPP.STATE_C_LEVEL - Ocpp_Setting.offset)) {
			count_D_2 = 0;
			count_B_2 = 0;
			count_A_2 = 0;
			if (++count_C_2 > Ocpp_Setting.count) {
				CURRENT_STATE_1 = STATE_C_2;
				count_C_2 = 0;
			}
		} else if ((cp_val_2 <= OCPP.STATE_D_LEVEL + Ocpp_Setting.offset)
				&& (cp_val_2 >= OCPP.STATE_D_LEVEL - Ocpp_Setting.offset)) {
			count_C_2 = 0;
			count_B_2 = 0;
			count_A_2 = 0;
			if (++count_D_2 > Ocpp_Setting.count) {
				CURRENT_STATE_1 = STATE_D_2;
				count_D_2 = 0;
			}
			//CURRENT_STATE=STATE_D;
		} else {
			count_D_2 = 0;
			count_C_2 = 0;
			count_B_2 = 0;
			count_A_2 = 0;
		}
		update_CP_1_Count = 0;
	}
//V501change
#if cpchange == no
	  if((cp_val_2<=STATE_A_LEVEL+100)&&(cp_val_2>=STATE_A_LEVEL-100))
		{
		  count_D_2 = 0;
		  count_B_2 = 0;
		  count_C_2 = 0;
		  if(++count_A_2 > 25)
		  {
			  CURRENT_STATE_1=STATE_A_2;
			  count_A_2 = 0;
		  }
		}
		else if((cp_val_2<=STATE_B_LEVEL+80)&&(cp_val_2>=STATE_B_LEVEL-80))
		{
			count_D_2 = 0;
			count_C_2 = 0;
			count_A_2 = 0;
			if(++count_B_2 > 25)
			{
				CURRENT_STATE_1=STATE_B_2;
				count_B_2 = 0;
			}
		}
		else if((cp_val_2<=STATE_C_LEVEL+80)&&(cp_val_2>=STATE_C_LEVEL-80))
		{
			count_D_2 = 0;
			count_B_2 = 0;
			count_A_2 = 0;
			if(++count_C_2 > 25)
			  {
				CURRENT_STATE_1=STATE_C_2;
				count_C_2 = 0;
			  }
		}
		else if((cp_val_2<=STATE_D_LEVEL+80)&&(cp_val_2>=STATE_D_LEVEL-80))
		{
			count_C_2 = 0;
			count_B_2 = 0;
			count_A_2 = 0;
			if(++count_D_2 > 25)
			  {
				CURRENT_STATE_1=STATE_D_2;
				count_D_2 = 0;
			  }
			  //CURRENT_STATE=STATE_D;
		}
#endif
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {

//    if(GPIO_Pin == GPIO_PIN_5) // If The INT Source Is EXTI Line9 (A9 Pin)
//    {
//    	// HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_8); // Toggle The Output (LED) Pi
//    	//system_energy = 1;
//    }

}
void Billing(char gun) {
	char *ptr, *ptr2;
	char save_ok = 0;
	uint32_t last_data_in = 0;
	char failed_attempt = 0;

	ptr = &data_to_flash.start;
	memset(ptr, '\0', sizeof(data_to_flash));

	if (gun == 1) {
		if (charger_status_G1.stop == Error) {
			strcpy(data_to_flash.ocpp_status, "Fail");
		} else {
			strcpy(data_to_flash.ocpp_status, "Success");
		}
		charger_status_G1.stop = Stoped;

		//	charger_status_G1.charging_status = SuspendedEV_ChargerPoint;
		data_to_flash.gn_no[0] = '1';
		data_to_flash.gn_no[1] = ' ';
		//snprintf(data_to_flash.gn_no,2,"%u",1);

		if (charger_status_G1.Bill_Amount < 99) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Bill_Amount[0] = (uint8_t)(
					(charger_status_G1.Bill_Amount % 100 / 10) + '0');
			data_to_flash.Bill_Amount[1] = (uint8_t)(
					charger_status_G1.Bill_Amount % 10 + '0');
			data_to_flash.Bill_Amount[2] = ' ';
			data_to_flash.Bill_Amount[3] = ' ';
		} else if (charger_status_G1.Bill_Amount < 999) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Bill_Amount[0] = (uint8_t)(
					(charger_status_G1.Bill_Amount % 1000 / 100) + '0');
			data_to_flash.Bill_Amount[1] = (uint8_t)(
					(charger_status_G1.Bill_Amount % 100 / 10) + '0');
			data_to_flash.Bill_Amount[2] = (charger_status_G1.Bill_Amount % 10
					+ '0');
			data_to_flash.Bill_Amount[3] = ' ';
		} else {
			data_to_flash.Bill_Amount[0] = (uint8_t)(
					(charger_status_G1.Bill_Amount % 10000 / 1000) + '0');
			data_to_flash.Bill_Amount[1] = (uint8_t)(
					(charger_status_G1.Bill_Amount % 1000 / 100) + '0');
			data_to_flash.Bill_Amount[2] = (uint8_t)(
					(charger_status_G1.Bill_Amount % 100 / 10) + '0');
			data_to_flash.Bill_Amount[3] = (charger_status_G1.Bill_Amount % 10
					+ '0');
		}

		Total_unit = charger_status_G1.stop_energy
				- charger_status_G1.start_energy;
		//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
		strncpy(data_to_flash.start_time, charger_status_G1.start_time, 18);
		strncpy(data_to_flash.stop_time, charger_status_G1.stop_time, 18);
		strncpy(data_to_flash.tagid, charger_status_G1.start_tagid, 12);

		if (charger_status_G1.charging_time < 99) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Total_time[0] = (uint8_t)(
					(charger_status_G1.charging_time % 100 / 10) + '0');
			data_to_flash.Total_time[1] = (uint8_t)(
					charger_status_G1.charging_time % 10 + '0');
			data_to_flash.Total_time[2] = ' ';
			data_to_flash.Total_time[3] = ' ';
		} else if (charger_status_G1.charging_time < 999) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Total_time[0] = (uint8_t)(
					(charger_status_G1.charging_time % 1000 / 100) + '0');
			data_to_flash.Total_time[1] = (uint8_t)(
					(charger_status_G1.charging_time % 100 / 10) + '0');
			data_to_flash.Total_time[2] = (uint8_t)(
					charger_status_G1.charging_time % 10 + '0');
			data_to_flash.Total_time[3] = ' ';
		} else {
			data_to_flash.Total_time[0] = (uint8_t)(
					(charger_status_G1.charging_time % 10000 / 1000) + '0');
			data_to_flash.Total_time[1] = (uint8_t)(
					(charger_status_G1.charging_time % 1000 / 100) + '0');
			data_to_flash.Total_time[2] = (uint8_t)(
					(charger_status_G1.charging_time % 100 / 10) + '0');
			data_to_flash.Total_time[3] = (charger_status_G1.charging_time % 10
					+ '0');
		}

//		sprintf(data_to_flash.Total_time,"%u",charger_status_G1.charging_time);
		Total_time = charger_status_G1.charging_time;
		Total_cost = charger_status_G1.Bill_Amount;

	} else if (gun == 2) {
		if (charger_status_G2.stop == Error) {
			strcpy(data_to_flash.ocpp_status, "Fail");
		} else {
			strcpy(data_to_flash.ocpp_status, "Success");
		}

		charger_status_G2.stop = Stoped;
		data_to_flash.gn_no[0] = '2';
		data_to_flash.gn_no[1] = ' ';
		//snprintf(data_to_flash.gn_no,2,"%u",2);
		Total_unit = charger_status_G2.stop_energy
				- charger_status_G2.start_energy;

		if (charger_status_G2.Bill_Amount < 99) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Bill_Amount[0] = (uint8_t)(
					(charger_status_G2.Bill_Amount % 100 / 10) + '0');
			data_to_flash.Bill_Amount[1] = (charger_status_G2.Bill_Amount % 10
					+ '0');
			data_to_flash.Bill_Amount[2] = ' ';
			data_to_flash.Bill_Amount[3] = ' ';
		} else if (charger_status_G2.Bill_Amount < 999) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Bill_Amount[0] = (uint8_t)(
					(charger_status_G2.Bill_Amount % 1000 / 100) + '0');
			data_to_flash.Bill_Amount[1] = (uint8_t)(
					(charger_status_G2.Bill_Amount % 100 / 10) + '0');
			data_to_flash.Bill_Amount[2] = (charger_status_G2.Bill_Amount % 10
					+ '0');
			data_to_flash.Bill_Amount[3] = ' ';
		} else {
			data_to_flash.Bill_Amount[0] = (uint8_t)(
					(charger_status_G2.Bill_Amount % 10000 / 1000) + '0');
			data_to_flash.Bill_Amount[1] = (uint8_t)(
					(charger_status_G2.Bill_Amount % 1000 / 100) + '0');
			data_to_flash.Bill_Amount[2] = (uint8_t)(
					(charger_status_G2.Bill_Amount % 100 / 10) + '0');
			data_to_flash.Bill_Amount[3] = (charger_status_G2.Bill_Amount % 10
					+ '0');
		}

		//	snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G2.Bill_Amount);
		strncpy(data_to_flash.start_time, charger_status_G2.start_time, 18);
		strncpy(data_to_flash.stop_time, charger_status_G2.stop_time, 18);
		if (charger_status_G2.charging_time < 99) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);

			data_to_flash.Total_time[0] = (uint8_t)(
					(charger_status_G2.charging_time % 100 / 10) + '0');
			data_to_flash.Total_time[1] = (uint8_t)(
					charger_status_G2.charging_time % 10 + '0');
			data_to_flash.Total_time[2] = ' ';
			data_to_flash.Total_time[3] = ' ';
		} else if (charger_status_G2.charging_time < 999) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Total_time[0] = (uint8_t)(
					(charger_status_G2.charging_time % 1000 / 100) + '0');
			data_to_flash.Total_time[1] = (uint8_t)(
					(charger_status_G2.charging_time % 100 / 10) + '0');
			data_to_flash.Total_time[2] = (uint8_t)(
					charger_status_G2.charging_time % 10 + '0');
			data_to_flash.Total_time[3] = ' ';
		} else {
			data_to_flash.Total_time[0] = (uint8_t)(
					(charger_status_G2.charging_time % 10000 / 1000) + '0');
			data_to_flash.Total_time[1] = (uint8_t)(
					(charger_status_G2.charging_time % 1000 / 100) + '0');
			data_to_flash.Total_time[2] = (uint8_t)(
					(charger_status_G2.charging_time % 100 / 10) + '0');
			data_to_flash.Total_time[3] = (charger_status_G2.charging_time % 10
					+ '0');
		}

		//	sprintf(data_to_flash.Total_time,"%u",charger_status_G2.charging_time);
		strncpy(data_to_flash.tagid, charger_status_G2.start_tagid, 12);
		Total_time = charger_status_G2.charging_time;
		Total_cost = charger_status_G2.Bill_Amount;
	} else if (gun == 3) {
		if (charger_status_G3.stop == Error) {
			strcpy(data_to_flash.ocpp_status, "Fail");

		} else {
			strcpy(data_to_flash.ocpp_status, "Success");
		}
		charger_status_G3.stop = Stoped;

		data_to_flash.gn_no[0] = '3';
		data_to_flash.gn_no[1] = ' ';

		//snprintf(data_to_flash.gn_no,2,"%u",3);
		Total_unit = charger_status_G3.stop_energy
				- charger_status_G3.start_energy;
		if (charger_status_G3.Bill_Amount < 99) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Bill_Amount[0] = (uint8_t)(
					(charger_status_G3.Bill_Amount % 100 / 10) + '0');
			data_to_flash.Bill_Amount[1] = (charger_status_G3.Bill_Amount % 10
					+ '0');
			data_to_flash.Bill_Amount[2] = ' ';
			data_to_flash.Bill_Amount[3] = ' ';
		} else if (charger_status_G3.Bill_Amount < 999) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Bill_Amount[0] = (uint8_t)(
					(charger_status_G3.Bill_Amount % 1000 / 100) + '0');
			data_to_flash.Bill_Amount[1] = (uint8_t)(
					(charger_status_G3.Bill_Amount % 100 / 10) + '0');
			data_to_flash.Bill_Amount[2] = (charger_status_G3.Bill_Amount % 10
					+ '0');
			data_to_flash.Bill_Amount[3] = ' ';
		} else {
			data_to_flash.Bill_Amount[0] = (uint8_t)(
					(charger_status_G3.Bill_Amount % 10000 / 1000) + '0');
			data_to_flash.Bill_Amount[1] = (uint8_t)(
					(charger_status_G3.Bill_Amount % 1000 / 100) + '0');
			data_to_flash.Bill_Amount[2] = (uint8_t)(
					(charger_status_G3.Bill_Amount % 100 / 10) + '0');
			data_to_flash.Bill_Amount[3] = (charger_status_G3.Bill_Amount % 10
					+ '0');
		}

		strncpy(data_to_flash.start_time, charger_status_G3.start_time, 18);
		strncpy(data_to_flash.stop_time, charger_status_G3.stop_time, 18);

		if (charger_status_G3.charging_time < 99) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Total_time[0] = (uint8_t)(
					(charger_status_G3.charging_time % 100 / 10) + '0');
			data_to_flash.Total_time[1] = (charger_status_G3.charging_time % 10
					+ '0');
			data_to_flash.Total_time[2] = ' ';
			data_to_flash.Total_time[3] = ' ';
		} else if (charger_status_G3.charging_time < 999) {
			//snprintf(data_to_flash.Bill_Amount,4,"%u",charger_status_G1.Bill_Amount);
			data_to_flash.Total_time[0] = (uint8_t)(
					(charger_status_G3.charging_time % 1000 / 100) + '0');
			data_to_flash.Total_time[1] = (uint8_t)(
					(charger_status_G3.charging_time % 100 / 10) + '0');
			data_to_flash.Total_time[2] = (charger_status_G3.charging_time % 10
					+ '0');
			data_to_flash.Total_time[3] = ' ';
		} else {
			data_to_flash.Total_time[0] = (uint8_t)(
					(charger_status_G3.charging_time % 10000 / 1000) + '0');
			data_to_flash.Total_time[1] = (uint8_t)(
					(charger_status_G3.charging_time % 1000 / 100) + '0');
			data_to_flash.Total_time[2] = (uint8_t)(
					(charger_status_G3.charging_time % 100 / 10) + '0');
			data_to_flash.Total_time[3] = (charger_status_G3.charging_time % 10
					+ '0');
		}

		//sprintf(data_to_flash.Total_time,"%4u",charger_status_G3.charging_time);
		strncpy(data_to_flash.tagid, charger_status_G3.start_tagid, 12);   //TBD
		Total_time = charger_status_G3.charging_time;
		Total_cost = charger_status_G3.Bill_Amount;
	}
//	Clear_Register = 19;
	//charger_status.Bill_Amount = (Total_unit*OCPP.energy_charges)/1000;
	//Total_cost = charger_status.Bill_Amount;
	//charger_status.Bill_Amount = charger_status.Bill_Amount + (time_charges *Total_time);

	data_to_flash.start = '$';

	data_to_flash.crc = CRC16(&data_to_flash.start,
			(sizeof(data_to_flash) - 4));
	data_to_flash.end = '#';

	last_data_in = byte_in;
	ptr = &data_to_flash.start;
	if (sizeof(data_to_flash) % 2)
		SFlash_write(ptr, sizeof(data_to_flash) - 1);
	else
		SFlash_write(ptr, sizeof(data_to_flash));
	save_ok = 0;
	do {
		ptr2 = &data_to_check.start;

		SFlash_read_to_check(ptr2, last_data_in);

		if (data_to_check.crc
				!= CRC16(&data_to_check.start, (sizeof(data_to_check) - 4))) {
			last_data_in = byte_in;

			if (sizeof(data_to_flash) % 2)
				SFlash_write(ptr, sizeof(data_to_flash) - 1);
			else
				SFlash_write(ptr, sizeof(data_to_flash));

			if (++failed_attempt > 3) {
				last_data_in = byte_in;
				failed_attempt = 0;
				break;
			}

		} else
			save_ok = 1;

	} while (save_ok == 0);

	SFlash_pointer_write();
//    free(ptr);
//    ptr = NULL;
//    free(ptr2);
//    ptr2 = NULL;

}
void Adding_Rfid(void) {
	uint8_t failed_attempt, save_ok;
	char *ptr2, *ptr;
	uint32_t last_data_in = 0;
	ptr = &rfid_data_to_flash.start;
	//if(LocalListAdding == rfid_pointer.Added_rfid )
	{
		rfid_data_to_flash.start = '$';

		rfid_data_to_flash.crc = CRC16(&rfid_data_to_flash.start,
				(sizeof(rfid_data_to_flash) - 4));
		rfid_data_to_flash.end = '#';

		last_data_in = rfid_pointer.lastPointer;

		if (sizeof(rfid_data_to_flash) % 2)
			SFlash_rfid_write(ptr, sizeof(rfid_data_to_flash) - 1);
		else
			SFlash_rfid_write(ptr, sizeof(rfid_data_to_flash));

		save_ok = 0;
		do {
			ptr2 = &rfid_data_to_check.start;

			SFlash_read_to_check(ptr2, last_data_in);

			if (rfid_data_to_check.crc
					!= CRC16(&rfid_data_to_check.start,
							(sizeof(rfid_data_to_check) - 4))) {
				rfid_pointer.lastPointer = last_data_in;

				if (sizeof(rfid_data_to_flash) % 2)
					SFlash_rfid_write(ptr, sizeof(rfid_data_to_flash) - 1);
				else
					SFlash_rfid_write(ptr, sizeof(rfid_data_to_flash));

				if (++failed_attempt > 3) {
					last_data_in = rfid_pointer.lastPointer;
					failed_attempt = 0;
					break;
				}
			} else {
				save_ok = 1;
				rfid_pointer.Added_rfid++;
			}

		} while (save_ok == 0);

	}

}
char expiry_calculation(String rtc_time, String expiery_time) {

	char *found;
	int Min = 0, diff;	// = exp_Hour - rtc_Hour;
	uint8_t rtc_Day, rtc_Month, rtc_Year, rtc_Hour, rtc_Min, rtc_Sec;
	uint8_t exp_Day, exp_Month, exp_Year, exp_Hour, exp_Min, exp_Sec;
	int total_min_rtc = 0, total_min_exp = 0;
	//found = strtok(rtc,"T");

	{
		rtc_Day = (((rtc_time[8] - 48) * 10) + (rtc_time[9] - 48));

		rtc_Month = (((rtc_time[5] - 48) * 10) + (rtc_time[6] - 48));

		rtc_Year = (((rtc_time[2] - 48) * 10) + (rtc_time[3] - 48));

		//found = strtok(NULL,"*");
		//if(found != NULL)

		rtc_Hour = (((rtc_time[11] - 48) * 10) + (rtc_time[12] - 48));

		rtc_Min = (((rtc_time[14] - 48) * 10) + (rtc_time[15] - 48));

		rtc_Sec = (((rtc_time[17] - 48) * 10) + (rtc_time[18] - 48));

	}
	//	found = strtok(expiery,"T");
	//	if(found != NULL)
	{
		exp_Day = (((expiery_time[8] - 48) * 10) + (expiery_time[9] - 48));

		exp_Month = (((expiery_time[5] - 48) * 10) + (expiery_time[6] - 48));

		exp_Year = (((expiery_time[2] - 48) * 10) + (expiery_time[3] - 48));

		exp_Hour = (((expiery_time[11] - 48) * 10) + (expiery_time[12] - 48));

		exp_Min = (((expiery_time[14] - 48) * 10) + (expiery_time[15] - 48));

		exp_Sec = (((expiery_time[17] - 48) * 10) + (expiery_time[18] - 48));
	}

	if (exp_Year > rtc_Year) {
		return 1;

	} else if (exp_Year == rtc_Year) {
		if (exp_Month > rtc_Month) {
			return 1;
		} else if (exp_Month == rtc_Month) {
			if (exp_Day > rtc_Day) {
				return 1;
			} else if (exp_Day == rtc_Day) {
				total_min_exp = exp_Hour * 60;
				total_min_exp += exp_Min;

				total_min_rtc = rtc_Hour * 60;
				total_min_rtc += rtc_Min;

				if (total_min_exp > total_min_rtc) {
					return 1;
				}

				/*
				 if(exp_Hour > rtc_Hour )
				 {
				 return 1;
				 }
				 else if(exp_Hour == rtc_Hour)
				 {
				 return 1;
				 }*/

			}
		}
	}
	return 0;
}
void Billing_calculation(void) {
	uint32_t Total_cost1 = 0, Total_cost2 = 0, Total_cost3 = 0;
	if (++Charging_time > 6) {
		if ((charger_status_G1.charging_status == Charging_ChargerPoint)
				|| (charger_status_G2.charging_status == Charging_ChargerPoint)
				|| (charger_status_G3.charging_status == Charging_ChargerPoint)) {
			update_variable = 1;
		}
		Charging_time = 0;
	}

	if (charger_status_G1.charging_status == Charging_ChargerPoint) {
		if (++charger_status_G1.charging_counter >= 6) {
			if ((++s6_counter1 % 10) == 0) {
				charger_status_G1.charging_time++;

				if (charger_status_G1.charge_by_automatic == 1) {

				} else if (charger_status_G1.charge_by_time != 0) {
					if (charger_status_G1.charging_time >= (charger_status_G1.charge_by_time)) {
						update_variable = 1;
						charger_status_G1.stop = Try_To_Stop;
						charger_status_G1.charging_status = Finishing_ChargerPoint;
					}
				} else if (charger_status_G1.charge_by_energy != 0) {
					if ((charger_status_G1.energy) >= charger_status_G1.charge_by_energy * 1000) {
						update_variable = 1;
						charger_status_G1.stop = Try_To_Stop;
						charger_status_G1.charging_status = Finishing_ChargerPoint;
					}
				}
			}
			charger_status_G1.charging_counter = 0;

			Total_cost1 = charger_status_G1.energy * OCPP.energy_charges_AC02;
			if (Total_cost1 >= 1000) {
				Total_cost1 = Total_cost1 / 1000;
			} else {
				Total_cost1 = 0;	//1
			}

			Total_cost1 += (s6_counter1 * OCPP.time_charges_AC02) / 10;
			charger_status_G1.Bill_Amount = Total_cost1;
			if (charger_status_G1.Bill_Amount > 9999) {
				charger_status_G1.Bill_Amount = 9999;
				charger_status_G1.stop = Try_To_Stop;
				charger_status_G1.charging_status = Finishing_ChargerPoint;
			}
		}
	}
	if (charger_status_G2.charging_status == Charging_ChargerPoint) {
		if (++charger_status_G2.charging_counter >= 6) {
			if ((++s6_counter2 % 10) == 0) {
				charger_status_G2.charging_time++;
				if (charger_status_G2.charge_by_automatic == 1) {

				} else if (charger_status_G2.charge_by_time != 0) {
					if (charger_status_G2.charging_time
							>= charger_status_G2.charge_by_time) {
						charger_status_G2.stop = Try_To_Stop;
						charger_status_G2.charging_status =
								Finishing_ChargerPoint;
						update_variable = 1;
					}
				} else if (charger_status_G2.charge_by_energy != 0) {
					if ((charger_status_G2.energy)
							>= charger_status_G2.charge_by_energy * 1000) {
						charger_status_G2.stop = Try_To_Stop;
						charger_status_G2.reson = Other;
						charger_status_G2.charging_status =
								Finishing_ChargerPoint;
						update_variable = 1;
					}
				}
			}
			charger_status_G2.charging_counter = 0;

			Total_cost2 = charger_status_G2.energy * OCPP.energy_charges_AC02;
			if (Total_cost2 >= 1000) {
				Total_cost2 = Total_cost2 / 1000;
			} else {
				Total_cost2 = 1;
			}

			Total_cost2 += (s6_counter2 * OCPP.time_charges_AC02) / 10;
			charger_status_G2.Bill_Amount = Total_cost2;
			if (charger_status_G2.Bill_Amount > 9999) {
				charger_status_G2.Bill_Amount = 9999;
				charger_status_G2.stop = Try_To_Stop;
				charger_status_G2.charging_status = Finishing_ChargerPoint;
				update_variable = 1;
			}
		}
	}
	if (charger_status_G3.charging_status == Charging_ChargerPoint) {
		if (++charger_status_G3.charging_counter >= 6) {
			if ((++s6_counter3 % 10) == 0) {
				charger_status_G3.charging_time++;
				if (charger_status_G3.charge_by_automatic == 1) {

				} else if (charger_status_G3.charge_by_time != 0) {
					if (charger_status_G3.charging_time
							>= charger_status_G3.charge_by_time) {
						charger_status_G3.stop = Try_To_Stop;
						charger_status_G3.charging_status =
								Finishing_ChargerPoint;
						update_variable = 1;
					}
				} else if (charger_status_G3.charge_by_energy != 0) {
					if ((charger_status_G3.energy)
							>= charger_status_G3.charge_by_energy * 1000) {
						charger_status_G3.stop = Try_To_Stop;
						charger_status_G3.charging_status =
								Finishing_ChargerPoint;
						update_variable = 1;
					}
				}
			}

			charger_status_G3.charging_counter = 0;
			Total_cost3 = charger_status_G3.energy * OCPP.energy_charges_AC02;
			if (Total_cost3 >= 1000) {
				Total_cost3 = Total_cost2 / 1000;
			} else {
				Total_cost3 = 1;
			}
			Total_cost3 += (s6_counter3 * OCPP.time_charges_AC02) / 10;
			charger_status_G3.Bill_Amount = Total_cost3;
			if (charger_status_G3.Bill_Amount > 9999) {
				charger_status_G3.Bill_Amount = 9999;
				charger_status_G3.stop = Try_To_Stop;
				charger_status_G3.charging_status = Finishing_ChargerPoint;
				update_variable = 1;
			}
		}
	}

}
/* 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 */
	__disable_irq();
	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,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
