/*
 * setting.c
 *
 *  Created on: Feb 16, 2012
 *      Author: RomanM
 */

#include <inttypes.h>
#include <string.h>
#include "setting.h"
#include "../drivers/drivers.h"
#include "uIP/uip.h"

setting_t setting;

void Setting_Load(void) {
	uint32_t address = 0;
	uip_ipaddr_t ipaddr;

	// IP address
	SPI_Flash_ReadData(address, (uint8_t*)&ipaddr, sizeof(ipaddr));
	uip_sethostaddr(ipaddr);
	address += sizeof(ipaddr);

	// Gateway address
	SPI_Flash_ReadData(address, (uint8_t*)&ipaddr, sizeof(ipaddr));
	uip_setdraddr(ipaddr);
	address += sizeof(ipaddr);

	// Network mask
	SPI_Flash_ReadData(address, (uint8_t*)&ipaddr, sizeof(ipaddr));
	uip_setnetmask(ipaddr);
	address += sizeof(ipaddr);

	// Other settings
	SPI_Flash_ReadData(address, (uint8_t*)&setting, sizeof(setting_t));
	address += sizeof(setting_t);

	if (setting.password[0] == 0xff) strcpy(setting.password, "default");
}

void Setting_Save(void) {
	uint32_t address = 0;
	uip_ipaddr_t ipaddr;

	SPI_Flash_UnprotectSector(0);
	SPI_Flash_BlockErase4kB(0);

	// IP address
	uip_gethostaddr(&ipaddr);
	SPI_Flash_WriteData(address, (uint8_t*)&ipaddr, sizeof(ipaddr));
	address += sizeof(ipaddr);

	// Gateway address
	uip_getdraddr(&ipaddr);
	SPI_Flash_WriteData(address, (uint8_t*)&ipaddr, sizeof(ipaddr));
	address += sizeof(ipaddr);

	// Gateway address
	uip_getnetmask(&ipaddr);
	SPI_Flash_WriteData(address, (uint8_t*)&ipaddr, sizeof(ipaddr));
	address += sizeof(ipaddr);

	// Setting
	SPI_Flash_WriteData(address, (uint8_t*)&setting, sizeof(setting_t));
	address += sizeof(setting_t);

	SPI_Flash_ProtectSector(0);
}
