#include "http_upgrade.h"
#include "uip_drv.h"
#include <common.h>

DECLARE_GLOBAL_DATA_PTR;

#define CFG_FLASH_SECTOR_SIZE (4*1024)

/*
 * Function Name: writeFlash
 * Author: CaiBin
 * Date: 2014-11-07
 * Description: Write data to given flash address.
 * Parameter:
 *       addrOffset: Flash address to be written to.
 *       buf: Points to the data buf to write.
 *       buflen: Length of the data buf in bytes.
 * return:
 *       0: Succeeded;
 *       ERR_WRITE_FLASH: Write command execution error.
 *       ERR_BAD_ADDRESS: Invalid address values passed. 
 */
int writeFlash(uint32_t addrOffset, uint8_t* buf, uint32_t buflen)
{
	if(raspi_write(buf, addrOffset, buflen) != buflen)
	{
		printf("flash write error! addrOffset = 0x%x\n", addrOffset);
		return ERR_WRITE_FLASH;
	}	

	return 0;
}

/*
 * Function Name: readFlash
 * Author: CaiBin
 * Date: 2014-11-07
 * Description: Read data from a given flash address.
 * Parameter:
 *       addrOffset: Flash address to be read from.
 *       buf: Points to the data buf to receive the read data.
 *       buflen: Length of the data buf in bytes.
 * return:
 *       0: Succeeded;
 *       ERR_READ_FLASH: Read command execution error.
 *       ERR_BAD_ADDRESS: Invalid address values passed. 
 */
int readFlash(uint32_t addrOffset, uint8_t* buf, uint32_t buflen)
{
	if(raspi_read(buf, addrOffset, buflen) != buflen)
	{
		printf("read flash error! addrOffset = 0x%x\n", addrOffset);
		return ERR_READ_FLASH;
	}

	return 0;
}

/*
 * Function Name: eraseFlash
 * Author: CaiBin
 * Date: 2014-11-07
 * Description: Erase flash content of a given flash address.
 * Parameter:
 *       addrOffset: Flash address to erase.
 *       eraselen:   Erase length in bytes.
 *       buflen: Length of the data buf in bytes.
 * return:
 *       0: Succeeded;
 *       ERR_ERASE_FLASH: Erase command execution error.
 *       ERR_BAD_ADDRESS: Invalid address values passed. 
 */
int eraseFlash(uint32_t addrOffset, uint32_t eraselen)
{
	if(raspi_erase(addrOffset, eraselen) != 0)
	{
		printf("erase flash error! addroffset = 0x%x\n", addrOffset);
		return ERR_ERASE_FLASH;
	}

	return 0;
}
