#include "bsp/i2c.h"
#include "eeprom.h"

#define I2C_ADDR 0XA4
#define PAGE_SIZE 16

static int eeprom_write_page(u16 addr,u8 *data,u8 len);

int eeprom_write_bytes(u16 addr, u8 *data, int len){
	U16 remain_len = len;
	while(remain_len > 0){
		U16 w_len = (remain_len > PAGE_SIZE)?PAGE_SIZE:remain_len;
		if (eeprom_write_page(addr, data, w_len) < 0){
			return -1;
		}
		addr+= w_len;
		data += w_len;
		remain_len -= w_len;
	}
	return 0;
}
int eeprom_read_bytes(u16 addr, u8 *data, int len){
	uint8_t device_addr = I2C_ADDR | ((addr >>8) << 1);
	int try_count = 100;
	while(0 >= shark_i2c_read_nbytes(0, device_addr, (uint8_t)(addr&0xFF), data, len)){
		if (try_count-- <= 0){
			return -1;
		}
	};
	return 0;
}

/* use page write to improve write time */
static int eeprom_write_page(u16 addr,u8 *data,u8 len){
	uint8_t device_addr = I2C_ADDR | ((addr >>8) << 1);
	int try_count = 100;
	while(0 >= shark_i2c_write_nbytes(0, device_addr, (uint8_t)(addr&0xFF), data, len)){
		if (try_count-- <= 0){
			return -1;
		}

	};
	return 0;
}

#if 0

#define ADDR_START 	(2<<7)

static U8 buffr[128];
static int index = 0;
static int _AT24CXX_test(void)
{
	int i=0;
	char wdata = 0x5A;
	if (index % 2 == 1){
		wdata = 0xA5;
	}
	for(i=0;i<128;i++)
	{
		buffr[i] = wdata;
	}
	
	eeprom_write_bytes(ADDR_START,buffr,128);
	
	memset(buffr,0,128);
	
	eeprom_read_bytes(ADDR_START,buffr,128);
	
	for(i=0;i<128;i++)
	{
		if (buffr[i] != wdata){
			return -1;
		}
	}
	return 0;
}


void AT24CXX_test(void){
	while(_AT24CXX_test() == 0){
		index++;
	};
}

#endif


