#include "common.h"
#include <stdint.h>
#include <stdlib.h>
#include "cpu.h"
#include "datatype.h"

#include "app.h"
#include "hw_adjust.h"
#include "app_config.h"


ws8100_config ws8100_cfg;
uint8_t is_log_enable(void)
{
	return ws8100_cfg.log_en;
}

const uint32_t boaudrate[8]={
	1200,
	2400,
	4800,
	9600,
	19200,
	38400,
	57600,
	115200,
};

uint32_t get_baudrate(void)
{
	char i;
	for(i=0;i<8;i++){
		if(ws8100_cfg.uart_rate == boaudrate[i]){
			return ws8100_cfg.uart_rate;
		}
	}
	ws8100_cfg.uart_rate = 115200;
	return ws8100_cfg.uart_rate;
}


uint8_t load_default_config(void)
{
	memset(&ws8100_cfg,0,sizeof(ws8100_cfg));

	ws8100_cfg.uart_rate 					= 115200;
	ws8100_cfg.starten					= 1;					// 1 开机运行 0 开机休眠
	ws8100_cfg.log_en						= LOG_DEFAULT_ON;		// 日志使能

	ws8100_cfg.bat_lever					= 100;					// 电量级别 0~100



	ws8100_cfg.up_rigister				= 3;					// 分压方式上电阻
	ws8100_cfg.down_rigister				= 1;					// 分压方式下电阻


	ws8100_cfg.bat_empty_vol 				= 3300;					// 默认3.3V空电平
	ws8100_cfg.bat_full_vol 				= 3800;					// 默认3.8V满电平
	ws8100_cfg.bat_power_off				= 3000;					// 默认3.0V关机电平


	ws8100_cfg.head[0] = 0x12;
	ws8100_cfg.head[1] = 0x34;
	ws8100_cfg.tail[0] = 0x56;
	ws8100_cfg.tail[1] = 0x78;
	
	return 0;
}

uint8_t check_config(void)
{
	uint8_t sz = 0;
	uint8_t baud_ok = 0;
	char i;

	baud_ok = 0;
	for(i=0;i<8;i++){
		if(ws8100_cfg.uart_rate == boaudrate[i]){
			baud_ok = 1;
			break;
		}
	}
	
	if(baud_ok == 0){
		sz = 1;
		ws8100_cfg.uart_rate = 115200;
	}
	

//	if(ws8100_cfg.peer_addr.atype != 0 && ws8100_cfg.peer_addr.atype != 1 ){
//		memset(&(ws8100_cfg.peer_addr),0xFF,sizeof(ws8100_cfg.peer_addr));
//		sz = 1;
//	}
	return sz;
}



void set_config_default(void)
{
	load_default_config();
	save_config();
}

void load_config(void)
{
	uint8_t need_recovery = 0xD4;
// 【1】 加载配置
#if SAVE_FLASH_SURPORT
	flash_read(INF_ADDR_FLASH, sizeof(ws8100_cfg), (uint8_t *)(&ws8100_cfg));
	if((ws8100_cfg.head[0] == 0x12) && (ws8100_cfg.head[1] == 0x34) && (ws8100_cfg.tail[0] == 0x56) && (ws8100_cfg.tail[1] == 0x78))
	{
		need_recovery = 0;
		if(check_config() == 1){
			save_config();
		}
	}
#endif
// 【2】 是否需要恢复默认配置
	if(need_recovery == 0xD4){
		load_default_config();
		save_config();
	}
	
	
}


void save_config(void)
{
#if SAVE_FLASH_SURPORT
	flash_erase(INF_ADDR_FLASH, 0x1000);
	flash_write(INF_ADDR_FLASH, sizeof(ws8100_cfg), (uint8_t *)(&ws8100_cfg));
#endif
}



