/*
 * drv_flash.c
 *
 *  Created on: 2025年4月8日
 *      Author: 22332
 */
#include "drv_flash.h"

#define FTFx_DPHRASE_SIZE  0x0010U

#define BUFFER_SIZE         24u          /* Size of data source */

#define EFM_SECTOR_VENDOR_DATA_NUM (31U)   // 诊断数据存储区

#define SECTOR_SIZE                     (0x400UL)

#define SECTOR_ADDR(x)          (uint32_t)(SECTOR_SIZE * (x))

flash_ssd_config_t flashSSDConfig;
status_t ret;        /* Store the driver APIs return code */
uint32_t failAddr;


/* Function declarations */

void bsp_drv_flash_init(void)
{
    ret = FLASH_DRV_Init(&Flash_InitConfig0, &flashSSDConfig);
    DEV_ASSERT(STATUS_SUCCESS == ret);
}

void bsp_drv_flash_write(uint8_t * write_buffer,uint32_t address)
{
		ret = FLASH_DRV_EraseSector(&flashSSDConfig, address, FEATURE_FLS_DF_BLOCK_SECTOR_SIZE);
	    DEV_ASSERT(STATUS_SUCCESS == ret);

	    /* Disable Callback */
	    flashSSDConfig.CallBack = NULL_CALLBACK;

	    /* Verify the erase operation at margin level value of 1, user read */
	    ret = FLASH_DRV_VerifySection(&flashSSDConfig, address, 256 / FTFx_DPHRASE_SIZE, 1u);
	    DEV_ASSERT(STATUS_SUCCESS == ret);

	    /* Write some data to the erased PFlash sector */
	    ret = FLASH_DRV_Program(&flashSSDConfig, address, BUFFER_SIZE, write_buffer);
	    DEV_ASSERT(STATUS_SUCCESS == ret);

	    /* Verify the program operation at margin level value of 1, user margin */
	    ret = FLASH_DRV_ProgramCheck(&flashSSDConfig, address, BUFFER_SIZE, write_buffer, &failAddr, 1u);
	    DEV_ASSERT(STATUS_SUCCESS == ret);
}
uint16_t bsp_drv_flash_read_byte(volatile uint8_t * flashPtr,uint8_t *buffer, uint32_t length)
{
	while (0UL != length) {
	   *(buffer++) = *(flashPtr++);
	   length--;
	           }
	return 0;

}
uint16_t bsp_drv_get_vendor_data(uint8_t *buffer, uint32_t length)
{
    uint32_t u32Addr = 0x10000000;
	u32Addr += SECTOR_ADDR(EFM_SECTOR_VENDOR_DATA_NUM);
    __IO uint8_t *pu8Buf = (uint8_t *)u32Addr;
    while (0UL != length) {
       *(buffer++) = *(pu8Buf++);
       length--;
               }
	return 0;
}
