#include "gd_ota_flash.h"
#include "gd32f10x_fmc.h"
#include "systick.h"
#include "string.h"

void GD32_WriteFlash(uint32_t saddr, uint32_t *wdata, uint32_t wnum);
void GD32_EraseFlash(uint16_t start, uint16_t num);

//读取soft版本信息
int read_soft_version()
{
	
}




void write_soft_version(BOOT_MESSAGE *save_message)
{
	GD32_EraseFlash(FMC_Page,1);
	GD32_WriteFlash(FMC_WRITE_START_ADDR,(uint32_t *)save_message,sizeof(BOOT_MESSAGE));
}

/*-------------------------------------------------*/
/*函数名：擦除FLASH                                */
/*参  数：start：擦除起始扇区   num：擦几个扇区    */
/*返回值：无                                       */
/*-------------------------------------------------*/
void GD32_EraseFlash(uint16_t start, uint16_t num)
{
	uint16_t i;

	fmc_unlock();
	for (i = 0; i < num; i++)
	{
		fmc_page_erase((0x08000000 + start * 1024) + (1024 * i));
	}
	fmc_lock();
}
/*---------------------------------------------------------------------*/
/*函数名：写入FLASH                                                    */ 
/*参  数：saddr：写入地址 wdata：写入数据指针  wnum：写入多少个字节    */
/*返回值：无                                                           */
/*---------------------------------------------------------------------*/
void GD32_WriteFlash(uint32_t saddr, uint32_t *wdata, uint32_t wnum)
{
	fmc_unlock();
	while (wnum > 0)
	{
		fmc_word_program(saddr, *wdata);
		wnum -= 4;
		saddr += 4;
		wdata++;
	}
	fmc_lock();
}
//读取GD32flash
void GD32_READ_OTA(BOOT_MESSAGE *READ)
{
	uint32_t data=FMC_READ(FMC_WRITE_START_ADDR);
	delay_1ms(10);
	memcpy(READ,&data,4);
}

//对系统存储版本信息进行初始化
void soft_init()
{
	BOOT_MESSAGE *currentBoot=malloc(sizeof(BOOT_MESSAGE));
	GD32_READ_OTA(currentBoot);
	if(currentBoot->VERSION_H ==0 && currentBoot->VERSION_L==0 && currentBoot->VERSION_M==0 )
	{
		currentBoot->VERSION_H=1;currentBoot->VERSION_L=0;currentBoot->VERSION_M=0;currentBoot->UP_FLAG=0;
	}
	write_soft_version(currentBoot);
	free(currentBoot);
	
}


