#include "ota_message.h"
#include "gd32f10x.h"
#include "w25q32.h"
#include <stdio.h>
static OTA_MESSAGE ota_message = {0};
void clear_ota_message_config_block(void);
void write_ota_message_to_flash(uint32_t *data, int size){
	uint8_t *pdata = (uint8_t *)data;
	W25Q32_PageWrite(pdata,256*OTA_EVENT_BLOCK);//写在第二扇区的第一页中
}

/*
 *  函数名：save_ota_message_config_params(OTA_MESSAGE *params)
 *  输入参数：无
 *  输出参数：无
 *  返回值：无
 *  函数作用：保存ota事件的信息
 */
int save_ota_message_config_params(OTA_MESSAGE *params)
{
		if(params == NULL)
				return -1;
		memset(&ota_message, 0, sizeof(OTA_MESSAGE));	
		memcpy(&ota_message, params, sizeof(OTA_MESSAGE)); 
	  clear_ota_message_config_block();
		write_ota_message_to_flash((uint32_t *)&ota_message,sizeof(OTA_MESSAGE));
		return 0;
}



/*
 *  函数名：load_config_params(CONFIG_PARAMS *params)
 *  输入参数：无
 *  输出参数：无
 *  返回值：ota升级标志是否有效 0有效 -1无效
 *  函数作用：从w25q32中加载ota信息
 */
int load_ota_message_config_params()
{
		memset(&ota_message, 0, sizeof(OTA_MESSAGE));//清空原先数据
		W25Q32_Read((uint8_t *)&ota_message, OTA_EVENT_BLOCK*64*1024, sizeof(OTA_MESSAGE)); //从W25Q32中读取结构体数据
		uint32_t *ptr=(uint32_t *)&ota_message;           
		if(*ptr == 1U)
		{
			return 0;
		}
		else return -1;
}
OTA_MESSAGE *get_config_params()
{
		return &ota_message;
}
/*
 *  函数名：void clear_ota_message_config_block(void)
 *  输入参数：无
 *  输出参数：无
 *  返回值：无
 *  函数作用：清除block内包含的ota事件信息
 */
void clear_ota_message_config_block(void)
{
	W25Q32_Erase64K(OTA_EVENT_BLOCK);//擦除一块区域的大小
}
