#include "ES8P5066.h"
#include "stdio.h"
#include "es8p5066_iap_table.h"
#include "es_flash_common_api.h"

#define ES_EEPROM_FLASH_IN_CODE_AREA   (0)

void R_RFD_WriteDataNFlashReq(uint32_t addr,uint8_t * data,uint32_t data_len)
{
    uint32_t i,write_data_addr,data32;
    uint8_t offset,*data32_8bit_p;
    ErrorStatus ret;
    
    data32_8bit_p = (uint8_t*)(&data32);
    
    data32 = 0xFFFFFFFF;
    
    for(i = 0;i < data_len;i++)
    {
        offset = (addr + i) & 0x3;
        
        data32_8bit_p[offset] = data[i];
        
        if((i == (data_len - 1))||(offset == 0x3))
        {
            write_data_addr = (addr + i) & 0xFFFFFFFC;
            data32 = (*((uint32_t *)write_data_addr)) & data32;
            
            IAP_FLASH_Unlock();
#if ES_EEPROM_FLASH_IN_CODE_AREA
            ret = IAP_Code_WordProgram(write_data_addr, ~write_data_addr, data32);
#else
            ret = IAP_Data_WordProgram(write_data_addr, ~write_data_addr, data32);
#endif
            IAP_FLASH_Lock();
            
            if(ret == ERROR)
                printf("[flash]write err\r\n");
            
            data32 = 0xFFFFFFFF;
        }
    }
}

void R_RFD_EraseDataFlashReq(uint32_t page)
{
    uint32_t addr; 
    ErrorStatus ret;
    
    addr = EEPROM_START_ADDRESS + (page * MCU_PAGE_SIZE);
    
    IAP_FLASH_Unlock();
#if ES_EEPROM_FLASH_IN_CODE_AREA
    ret = IAP_Code_PageErase(addr,~addr);
#else
    ret = IAP_Data_PageErase(addr,~addr);
#endif
    IAP_FLASH_Lock();
    
    if(ret == ERROR)
        printf("[flash]erease err\r\n");
}

