#include "smartee.h"

uint8_t SmartEEflag = ENABLE;


int8_t SmartEE_CheckConfig(void)
{
	int8_t  ret = 0;
    
    uint32_t    NVMCTRL_SEESBLK = ((*(uint32_t *)(USER_PAGE_ADDR + 4)) >> 0) & NVMCTRL_SEESBLK_MASK_BITS;
    uint32_t    NVMCTRL_SEEPSZ = ((*(uint32_t *)(USER_PAGE_ADDR + 4)) >> 4) & NVMCTRL_SEEPSZ_MASK_BITS;

	if (NVMCTRL_SEESBLK != NVMCTRL_SEESBLK_CONFIG || (NVMCTRL_SEEPSZ != NVMCTRL_SEEPSZ_CONFIG))
    {
        ret = -1;
        SmartEEflag = DISABLE;
	}

	return ret;
}


int8_t SmartEE_Read(uint16_t address, uint8_t *data, uint8_t len)
{
    int8_t ret = 0;
    uint8_t i = 0;
    uint8_t len2read = 0;

    if(SmartEEflag == DISABLE)
    {
        ret = -1;
    }else
    {
        if(address + len > SMARTEEPROM_SIZE)
        {
            len2read = SMARTEEPROM_SIZE - address;
        }else{
            len2read = len;
        }

        for(i=0; i<len2read; i++)
        {
            data[i] = *((uint8_t *)(SmartEE_BaseAddr+address+i));
        }

        ret = len2read;
    }

    return ret;
}

int8_t SmartEE_Write(uint16_t address, uint8_t *data, uint8_t len)
{
    int8_t ret = 0;
    uint8_t i = 0;
    uint8_t len2write = 0;

    if(SmartEEflag == DISABLE)
    {
        ret = -1;
    }else
    {
        if(address + len > SMARTEEPROM_SIZE)
        {
            len2write = SMARTEEPROM_SIZE - address;
        }else{
            len2write = len;
        }

        while (NVMCTRL_SmartEEPROM_IsBusy());

        for(i=0; i<len2write; i++)
        {
            *((uint8_t *)(SmartEE_BaseAddr+address+i)) = data[i];
        }

        ret = len2write;
    }

    return ret;
}