#include "data_save.h"
#include "stdlib.h"

DataFlash_Save_T dataFlash_save_t={
	.flash_save_flg = 0,        //需要保存标志
	.flash_save_head = 0,       //保存的头
	.bleName_len = 15,          //蓝牙名长度
	.scanRspData = {
		// complete name
		0x10,   // length of this data
		GAP_ADTYPE_LOCAL_NAME_COMPLETE,
		'B',   
		'L',   
		'V',   
		'-',   
		'C',   
		'1',   
		' ',
		'R',   
		'C',   
		'U',
		':',
		'8',
		'8',
		'8',
		'8',
		// connection interval range
		0x05,   // length of this data
		GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE,
		LO_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ),   // 100ms
		HI_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ),
		LO_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ),   // 1s
		HI_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ),
	},
	
};

void DataFlash_Save_Init()
{
	//DataFlash_Save_T save_t = {0};
	PRINT("flash head:%X, %X\n", (*(uint8*)DATAFLASH_SAVE_START_ADDR & 3), *(uint8*)DATAFLASH_SAVE_START_ADDR);
	if( (*(uint8*)DATAFLASH_SAVE_START_ADDR & 3) == FALSH_SAVE_HEAD)    //有头标记，从flash读参数
	{
		PRINT("Read flash\n");
		memset(&dataFlash_save_t, 0, sizeof(DataFlash_Save_T));
		memcpy((uint8*)&dataFlash_save_t, (uint8*)DATAFLASH_SAVE_START_ADDR, sizeof(DataFlash_Save_T));
		
		PRINT("bleName_len:%d\n", dataFlash_save_t.bleName_len);
		for(int i = 0; i< dataFlash_save_t.bleName_len ; i++)
		{
			PRINT("%c", (char)dataFlash_save_t.scanRspData[i+2]);
		}
		PRINT("\n");
		
	}
	else    //往flash写默认参数
	{
		dataFlash_save_t.flash_save_flg = 1; 
	}
}

/*参数保存任务*/
void DataFlash_Save_Task()
{
	if(dataFlash_save_t.flash_save_flg)
	{
		PRINT("Write flash\n");
		dataFlash_save_t.flash_save_flg = 0; 
		dataFlash_save_t.flash_save_head = FALSH_SAVE_HEAD;      //写头标记
		
		uint8 err = FlashBlockErase(DATAFLASH_SAVE_START_ADDR);    //512对齐,擦除
		if(err) PRINT("Erase flash err:%d\n", err);
		
		int len = 0;
		
		if( sizeof(DataFlash_Save_T) %4 != 0)    //参数非4字节对齐
		{
			len = sizeof(DataFlash_Save_T) / 4 + 1;
		}
		else len = sizeof(DataFlash_Save_T) / 4;
		
//		PRINT("buff size:%d\n", len);
		
		uint32* buff = malloc(len);
		if(buff == NULL)   return;
		
		for(int i = 0; i< len; i++)
		{
			buff[i] = 0x00000000;
		}
		
		memcpy((uint8*)buff, (uint8*)&dataFlash_save_t, sizeof(DataFlash_Save_T));
	
		err = FlashWriteBuf(DATAFLASH_SAVE_START_ADDR, buff, len*4);
		
		if(err) PRINT("Write flash err:%d\n", err);
		
		free(buff);
	}
}







