#include "config.h"
 
#define CONFIG_DEMO

#define DEVICE_ID 	1001
#define VERSION_MAX	1
#define VERSION_MIN	12

struct config config;
struct config_uart cfg_uart =
{
	.baudrate = 9600,
	.databits = 8,
	.parity	=0,
	.stopbits = 1
};


struct config_protocol cfg_protocol =
{
    .type = 0,         /*0  rtu , 1  hex, 2 ascii*/
    .pre_command = "0103000000044408",
    // .pre_command = "",
    .pre_timeout = 150,
    .command = "0103000000044409",
    // .command = "00030000000445D8",
    .timeout = 0,
    .parser = 0,  /* 0：float  1:int  2 :ascii */
	.endian = 0,  /* 0: little  1: big */
    .validation = 0,   /*校验方法  0 ：crc16, 1: sum  2:sign*/
    .sign = "0D0A"   /*尾部标记*/
};
struct config_output cfg_output =
{
    .begin_byte = 0,
    .length = 0,
    .end_byte = 0,
	.place = 0,
	.number = 0 ,
    .coeff = 1,     /* int 系数 */
    .retension = 3  /* 保留位数*/
};

struct config_uart cfg_menu =
{
	.baudrate = 9600,
	.databits = 8,
	.parity	=0,
	.stopbits = 1
};

struct config_uart cfg_modbus =
{
	.baudrate = 9600,
	.databits = 8,
	.parity	=0,
	.stopbits = 1
};

int Config_Init(void)
{

	config.device_id = DEVICE_ID;
	config.version_max = VERSION_MAX;
	config.version_min = VERSION_MIN;
	config.samp_interval_s = 1;
	config.uart = cfg_uart;
	config.protocol = cfg_protocol;
	config.output = cfg_output;

    config.menu= cfg_menu;
    config.modbus= cfg_modbus;
    return 0;
}

// int Config_Read(void)
// {
// }

// int Config_Write(void)
// {
// }


int config_reset(void)
{
// #ifdef CONFIG_DEMO
	config.device_id = DEVICE_ID;
	config.version_max = VERSION_MAX;
	config.version_min = VERSION_MIN;
	config.samp_interval_s = 1;
	config.uart = cfg_uart;
	config.protocol = cfg_protocol;
	config.output = cfg_output;

    config.menu= cfg_menu;
    config.modbus= cfg_modbus;

// #endif
    return 0;
}

int config_check(void)
{
    /* 对从 eeprom 读出的配置进行校验，判断是否需要resetconfig, 重写eeprom */

    // if(!IS_USART_PARITY(config.uart.parity)) return -8;
    // if(!IS_USART_STOPBITS(config.uart.stopbits))  return -8;
    // if(!IS_USART_PARITY(config.menu.parity)) return -8;
    // if(!IS_USART_STOPBITS(config.menu.stopbits)) return -8;
    // if(!IS_USART_PARITY(config.modbus.parity))   return -8;
    // if(!IS_USART_STOPBITS(config.modbus.stopbits))  return -8;

    if ( config.uart.baudrate%2400 != 0) return -6;
    if ( config.menu.baudrate%2400 != 0) return -6;
    if ( config.modbus.baudrate%2400 != 0) return -6;
	return 0;
	
}

int config_get_cfg(void)
{

    // struct time_clock_time time;
    // time_clock_get_time(&time);
    // i2c_read_memory(&i2c_buf,0xa0,0x00,1,(uint8_t*)&config,sizeof(config));
    // while(i2c_get_state(&i2c_buf)!=0){
    //     if(time_clock_get_time_offset_ms(&time)>1000){
    //         return -1;
    //     }
    // }
    // if(config_check()==0){
    //     return 0;
    // }
    // config_reset();
    return 0;

}