#include "gd32f10x.h"
#include "main.h"
#include "delay.h"
#include "fmc.h"
#include "ota_message.h"
#include "usart.h"
#include "ec800m.h"
#include "boot.h"
#include "w25q32.h"
void task_fwdgt_reload(void);
OTA_STRUCT UpDataA;           //A区更新用到的结构体

#if 0
 void my_test(void)	//往UFS写好文件
 {
 	static OTA_MESSAGE ota_message = {0};
 	char str[100];
 	char string[] = "{\"otaflag\":1,\"XmodemByte\":102400}"; 
 	uint32_t i = 0;
 	ota_message.otaflag = 1;
 	ota_message.XmodemByte = 17152;
 	memcpy(str,string,strlen(string)+1);
 	char OPEN_FILE[] = "AT+QFOPEN=\"otaMSG.txt\",0\r\n";
 	char OPEN_NEW_FILE[] = "AT+QFOPEN=\"otaMSG.txt\",1\r\n";
 	char WRITEFILE[] = "AT+QFWRITE=1,8\r\n";
 	char CLOSEFILE[] = "AT+QFCLOSE=1\r\n";
 	char LOADFILE[] = "AT+QFDWL=otaMSG.txt\r\n";
 	// GD32_EraseFlash(420,1);
 	// GD32_WriteFlash(0x08069000,(uint32_t *)&ota_message,sizeof(OTA_MESSAGE)); 
 	// i = *(uint32_t*)(0x08069000);
 	// i = *(uint32_t*)(0x08069004);
 	EC800MSendCmd(OPEN_NEW_FILE,strlen(OPEN_NEW_FILE));
 	memset(str,0,sizeof(str));
 	strcpy(str,(char *)&UART0_RX_BUF);
 	i = WaitResponse("QFOPEN:", 2000);

 	EC800MSendCmd(WRITEFILE,strlen(WRITEFILE));
 	memset(str,0,sizeof(str));
 	strcpy(str,(char *)&UART0_RX_BUF);
 	i = WaitResponse("CONNECT", 2000);

 	EC800MSendCmd((uint8_t *)&ota_message,8);
 	memset(str,0,sizeof(str));
 	strcpy(str,(char *)&UART0_RX_BUF);
 	i = WaitResponse("QFWRITE", 2000);

 	EC800MSendCmd(CLOSEFILE,strlen(CLOSEFILE));
 	memset(str,0,sizeof(str));
 	strcpy(str,(char *)&UART0_RX_BUF);
 	i = WaitResponse("OK", 2000);

 	free(str);
 	Delay_Ms(10);
 }
#endif

int main(void)
{
	Delay_Init();
	/* 弃用w25q32改用EC800存储ota文件 */
	// W25Q32_Init();
	nvic_config();
	gd_com_init(COM_EC800);
	dma_config();
	gd_EC800M_pin_init();
	EC800MPwoerOn();
	EC800MWaitReady();
	// my_test();
	OTA_MESSAGE *ota_data;
	task_fwdgt_reload();
	if(load_ota_message_config_params()==0)
	{
		//ota事件产生了，进入Bootloader分支
		ota_data=get_config_params();
		BootLoader_Brance(ota_data->XmodemByte);
	}
	//没有OTA事件产生跳转A区
	else
	{
		LOAD_A(GD32_A_SADDR);
	}
  
	while(1)
	{
		
		
	}
	
}

void task_fwdgt_reload(void)
{
	/* uncock fwdgt write protect*/
	fwdgt_write_enable();
	/* feed fwdgt */
	fwdgt_counter_reload();	
}