#include <common.h>
#include "drv_io.h"
#include "drv_can.h"
#include "drv_watch_dog.h"
#include "app.h"
#include "app_rs485_1.h"
#include "app_rs485_2.h"
#include "app_can.h"
#include "measure_temprature.h"
#include "measure_vol.h"
#include "app_bms_1.h"
#include "app_bms_2.h"
#include "app_end_ctr.h"
#include "app_adas.h"
#include "hardware_test.h"
#include "low_power.h"
#include "sw_build_info.h"


#ifdef CONFIG_CAN_IAP
extern void qws_iap_write_magic(uint32_t magic);
const uint8_t iap_board_name[] __attribute__((at(0x8002800))) = "PS100";
const uint8_t soft_version[] __attribute__((at(0x8002A00))) = CONFIG_VERSION;
const uint8_t iap_volume[] __attribute__((at(0x8002C00))) = "App";
#else
const uint8_t soft_version[] = CONFIG_VERSION;
#endif



uint8_t sn[PS100_SERIAL_NUM_SIZE];


uint32_t g_event = NO_EVENT;



void Flash_flag_clear(void)
{
	fmc_flag_clear(FMC_FLAG_BANK0_PGERR | FMC_FLAG_BANK0_WPERR | FMC_FLAG_BANK0_END);
}
void Check_SN(void)
{
	uint32_t capacity = (REG32(0x1FFFF7E0) & 0xFFFF) << 10;
	uint32_t address = 0x08000000 + (capacity - SN_FLASH_ADDRESS);
	uint8_t i = 0;
	uint16_t df_value = 0x3030;

	if (REG32(address) < 0xFFFFFFFF) 
	{
		memcpy(sn,(uint8_t*)address,sizeof(sn));
		return;
	}
	

	fmc_unlock();

	Flash_flag_clear();
	fmc_page_erase(address);

	i = 0;
	while(i<PS100_SERIAL_NUM_SIZE)
	{
		Flash_flag_clear();
		fmc_halfword_program(address + i, df_value);
		i+= 2;
	}
	fmc_lock();

	address = 0x08000000 + (capacity - SN_FLASH_ADDRESS);
	memcpy(sn,(uint8_t*)address,sizeof(sn));
	
}

void Writer_SN(uint8_t *data)
{
	uint32_t capacity = (REG32(0x1FFFF7E0) & 0xFFFF) << 10;
	uint32_t address = 0x08000000 + (capacity - SN_FLASH_ADDRESS);
	uint8_t i = 0;
	uint16_t df_value = 0xFFFF;
	
	fmc_unlock();

	Flash_flag_clear();
	fmc_page_erase(address);

	i = 0;
	while(i<PS100_SERIAL_NUM_SIZE)
	{
		Flash_flag_clear();
		df_value = data[i+1];
		df_value <<= 8;
		df_value |= data[i];
		fmc_halfword_program(address + i,df_value);
		i+= 2;
	}
	fmc_lock();

	address = 0x08000000 + (capacity - SN_FLASH_ADDRESS);
	memcpy(sn,(uint8_t*)address,sizeof(sn));
	
}

void init_NVIC(uint32_t NVoffset)
{
	//ÉèÖÃÖÐ¶Ï

	nvic_vector_table_set(NVIC_VECTTAB_FLASH,NVoffset);
	
	//nvic_priority_group_set(NVIC_PRIGROUP_PRE2_SUB2);
	nvic_priority_group_set(NVIC_PRIGROUP_PRE4_SUB0);
	
}

void test_Initial(void)
{

	rcu_periph_clock_enable(RCU_GPIOB);
	rcu_periph_clock_enable(RCU_GPIOD);
	gpio_init(GPIOB,GPIO_MODE_IPU,GPIO_OSPEED_50MHZ,GPIO_PIN_14);
	gpio_init(GPIOD,GPIO_MODE_IPU,GPIO_OSPEED_50MHZ,GPIO_PIN_14);


	rcu_periph_clock_enable(RCU_AF);
	
	nvic_irq_enable(EXTI10_15_IRQn,1,0);
	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOB, GPIO_PIN_SOURCE_14);
	exti_init(EXTI_14, EXTI_INTERRUPT, EXTI_TRIG_FALLING);
    exti_interrupt_flag_clear(EXTI_14);


#if 1
	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOD, GPIO_PIN_SOURCE_14);
	exti_init(EXTI_14, EXTI_INTERRUPT, EXTI_TRIG_FALLING);
    exti_interrupt_flag_clear(EXTI_14);
#endif


}

int main(void)
{	

#ifdef CONFIG_CAN_IAP
#else
	init_NVIC(NVIC_OFFSET);
#endif

	systick_config();

	Misc_Initial();

	Sub_BMS_1_Initial();

	Sub_BMS_2_Initial();
	
	Can_Com_Initial();

	Measure_Temprature_Initial();
	
	Measure_Vol_Initial();

	CB_Operate_Initial();

	End_Ctr_Initial();

	ADAS_Initial();

	HT_Main();
	
	App_Initial();
	
	//printf("PS100 Initial!\r\n");
	Check_SN();

	Low_Power_Initial();
	
#if DEBUG_MODE == 0
	Watch_Dog_Initial();
#endif
#ifdef CONFIG_CAN_IAP
		qws_iap_write_magic(0x11223344);
#endif
	/*extern void test_io(void);
	for(;;)
	{

		test_io();
	}*/
	for(;;)
	{
#if DEBUG_MODE == 0
		Feed_Watch_Dog();
#endif

		Check_Can_Poll();

		Check_CB_Operate_State();

		Intelligent_Management_Battery();

		//Check_Battery_Small_Current();
		
		Check_Charge_In();
			
		Sub_BMS_1_lt_State();
		
		Sub_BMS_2_lt_State();
	
		Check_Sub_BMS_1();

		Check_Sub_BMS_2();

		Check_End_Ctr_Status();
		
		Check_Can_Self_Send_Status();

		Cal_Sheng_Yu_Li_Cheng();

		Check_S11_May_Operate();
		
		if(g_event & SUB_BMS_1_SEND_CMD_EVENT)
		{
			if(update_bat.ub_bat != UPDATE_BAT_1)
				Send_Sub_BMS_1_CMD();
			
			g_event &= ~SUB_BMS_1_SEND_CMD_EVENT;
		}

		if(g_event & SUB_BMS_2_SEND_CMD_EVENT)
		{
			if(update_bat.ub_bat != UPDATE_BAT_2)
				Send_Sub_BMS_2_CMD();
			
			g_event &= ~SUB_BMS_2_SEND_CMD_EVENT;
		}

		
		if(g_event & BMS_1_RESEND_CMD_EVENT)
		{
			if(Resend_can_bms_1_frame())
			{
				g_event &= ~BMS_1_RESEND_CMD_EVENT;
			}
		}

		if(g_event & BMS_2_RESEND_CMD_EVENT)
		{
			if(Resend_can_bms_2_frame())
			{
				g_event &= ~BMS_2_RESEND_CMD_EVENT;
			}
		}

		if(g_event & END_CTR_RESEND_CMD_EVENT)
		{
			if(Resend_can_ctr_frame())
			{
				g_event &= ~END_CTR_RESEND_CMD_EVENT;
			}
		}

		if(g_event & ADAS_RESEND_CMD_EVENT)
		{
			if(Resend_can_adas_frame())
			{
				g_event &= ~ADAS_RESEND_CMD_EVENT;
			}
		}
		
		//if(g_event & EVENT_CAN_RECEIVE_FINISH)
		{
			if(Handle_Can_Data() == 1)
			{
				// output fail
				
				;
			}
			
			//g_event &= ~EVENT_CAN_RECEIVE_FINISH;
		}

		if(g_event & MEASURE_TEMPERATURE_EVENT)
		{
			
			getTemperature();
			
			g_event &= ~MEASURE_TEMPERATURE_EVENT;
		}

		if(g_event & SUB_BMS_1_RS485_DISC_EVENT)
		{
			
			RS485_Communication_Time_Out_1();
			
			g_event &= ~SUB_BMS_1_RS485_DISC_EVENT;
		}
		
		if(g_event & SUB_BMS_2_RS485_DISC_EVENT)
		{
			
			RS485_Communication_Time_Out_2();
			
			g_event &= ~SUB_BMS_2_RS485_DISC_EVENT;
		}
		
		
		if(g_event & RS485_RECEIVE_END_EVENT)
		{
			
			if(Handle_RS485_1_Data() == 1)
			{
				// output fail
				
				;
			}
			g_event &= ~RS485_RECEIVE_END_EVENT;
		}
	
		if(g_event & RS485_2_RECEIVE_END_EVENT)
		{
			
			if(Handle_RS485_2_Data() == 1)
			{
				// output fail
				
				;
			}
			g_event &= ~RS485_2_RECEIVE_END_EVENT;
		}

		
		if(g_event & BMS_1_SELF_TIMEOUT_EVENT)
		{
			Timeout_Resend_can_bms_1_frame();
			
			g_event &= ~BMS_1_SELF_TIMEOUT_EVENT;
			
		}

		if(g_event & BMS_2_SELF_TIMEOUT_EVENT)
		{
			Timeout_Resend_can_bms_2_frame();
		
			g_event &= ~BMS_2_SELF_TIMEOUT_EVENT;
			
		}

		if(g_event & END_CTR_SELF_TIMEOUT_EVENT)
		{
			Timeout_Resend_can_ctr_frame();
			
			g_event &= ~END_CTR_SELF_TIMEOUT_EVENT;
			
		}

		if(g_event & ADAS_SELF_TIMEOUT_EVENT)
		{
			Timeout_Resend_can_adas_frame();
			
			g_event &= ~ADAS_SELF_TIMEOUT_EVENT;
			
		}

		if(g_event & ADAS_PWM_1_TIMEOUT_EVENT)
		{
			ADAS_PWM_1_Enable();
			
			g_event &= ~ADAS_PWM_1_TIMEOUT_EVENT;
			
		}

		if(g_event & ADAS_PWM_2_TIMEOUT_EVENT)
		{
			ADAS_PWM_2_Enable();
			
			g_event &= ~ADAS_PWM_2_TIMEOUT_EVENT;
			
		}

		if(g_event & ADAS_MEAS_1_FINISH_EVENT)
		{
			ADAS_Measure_Finish_Ju_Li_1();

			ADAS_Self_Send_Up();
			
			g_event &= ~ADAS_MEAS_1_FINISH_EVENT;
			
		}

		if(g_event & ADAS_MEAS_2_FINISH_EVENT)
		{
			ADAS_Measure_Finish_Ju_Li_2();
			
			g_event &= ~ADAS_MEAS_2_FINISH_EVENT;
			
		}

		if(g_event & ENTER_SLEEP_EVENT)
		{
			
		    Enter_Sleep();
			
			g_event &= ~ENTER_SLEEP_EVENT;
			
		}
		
		if(g_event & RE_INITIAL_CAN_EVENT)
		{
			
		  //Can_Com_Initial();
			
			g_event &= ~RE_INITIAL_CAN_EVENT;
			
		}
		
		if(g_event & DEVICE_REBOOT_EVENT)
		{	
			g_event &= ~DEVICE_REBOOT_EVENT;
		  	__set_FAULTMASK(1);
			NVIC_SystemReset();
		}

		if(g_event & SAVE_PARAM_EVENT)
		{	
			g_event &= ~SAVE_PARAM_EVENT;
		  	Save_Param();
		}
		
	}
	
	//return (1);

}




	
#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(u8_t* file, uint32_t line)
{ 
  /* 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) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/*********************************************************************************************************
      END FILE
*********************************************************************************************************/


