#include "bsp_Flash.h"
#include "string.h"
#include "bsp_Wdg.h"
#include "gas_data.h"
/* FLASH Memory Definitions */ 
//#define BSP_FLASH_SIZE          (0x100000UL)    
//#define BSP_FLASH_PAGE_SIZE     (PAGESIZE)
//#define BSP_FLASH_PAGE_NUM      (BSP_FLASH_SIZE/BSP_FLASH_PAGE_SIZE) 

//#define BSP_FLASH_ADDR_RW(n)    ((uint32_t)(FLASH_BASE + (BSP_FLASH_PAGE_NUM - (n)) * BSP_FLASH_PAGE_SIZE))
//#define BSP_FLASH_DATASAVE_ADDR BSP_FLASH_ADDR_RW(1)

//FLASH地址
#define BSP_FLASH_SECTION_0_ADDR    ((u32)0x08000000)  //16k
#define BSP_FLASH_SECTION_1_ADDR    ((u32)0x08004000)  //16k
#define BSP_FLASH_SECTION_2_ADDR    ((u32)0x08008000)  //16k
#define BSP_FLASH_SECTION_3_ADDR    ((u32)0x0800C000)  //16k
#define BSP_FLASH_SECTION_4_ADDR    ((u32)0x08010000)  //64k
#define BSP_FLASH_SECTION_5_ADDR    ((u32)0x08020000)  //128k
#define BSP_FLASH_SECTION_6_ADDR    ((u32)0x08040000)  //128k
#define BSP_FLASH_SECTION_7_ADDR    ((u32)0x08060000)  //128k 
#define BSP_FLASH_SECTION_8_ADDR    ((u32)0x08080000)  //128k
#define BSP_FLASH_SECTION_9_ADDR    ((u32)0x080A0000)  //128k
#define BSP_FLASH_SECTION_10_ADDR   ((u32)0x080C0000)  //128k
#define BSP_FLASH_SECTION_11_ADDR   ((u32)0x080E0000)  //128k

#define BSP_FLASH_DATASAVE_ADDR BSP_FLASH_SECTION_11_ADDR//最后一片扇区 128k

static void bsp_Flash_Init(void);
static void bsp_FlashDataWrite(void);
static void bsp_FlashDataRead(void);
static void bsp_FlashReset(void);

bsp_Flash_t Usr_Flash = 
{
    .Init = bsp_Flash_Init,
    .Write = bsp_FlashDataWrite,
    .Read = bsp_FlashDataRead,
    .Reset = bsp_FlashReset, 
};

bsp_Flash_t *p_Usr_Flash = &Usr_Flash;

// 擦除指定页
static HAL_StatusTypeDef bsp_FLASH_ErasePage(uint32_t PageAddress)
{
    //初始化FLASH_EraseInitTypeDef
    FLASH_EraseInitTypeDef f;
    
    f.TypeErase = FLASH_TYPEERASE_SECTORS;
    f.Sector = FLASH_SECTOR_11;
    f.NbSectors = 1;
    f.VoltageRange = VOLTAGE_RANGE_3;
    //设置PageError
    uint32_t PageError = 0;
    //调用擦除函数
    return HAL_FLASHEx_Erase(&f, &PageError);
}

// 读取数据 - 按32位读取
static void bsp_Flash_STMFLASH_Read(uint32_t ReadAddr, void *pBuffer, uint32_t size)
{
    uint8_t *pBuf = (uint8_t*)pBuffer;
    uint32_t *addr = (uint32_t*)ReadAddr;
    uint32_t words = size / 4;
    uint32_t bytes_remaining = size % 4;
    
    // 读取完整的32位字
    for(uint32_t i = 0; i < words; i++)
    {
        *((uint32_t*)pBuf) = addr[i];
        pBuf += 4;
    }
    
    // 读取剩余的字节
    if(bytes_remaining > 0)
    {
        uint32_t last_word = addr[words];
        uint8_t *last_bytes = (uint8_t*)&last_word;
        
        for(uint32_t i = 0; i < bytes_remaining; i++)
        {
            pBuf[i] = last_bytes[i];
        }
    }
}

// 写入数据 - 按32位写入
static HAL_StatusTypeDef bsp_Flash_STMFLASH_Write(uint32_t WriteAddr, void *pBuffer, uint32_t size)
{
    HAL_StatusTypeDef status = HAL_OK;
    uint8_t *pBuf = (uint8_t*)pBuffer;
    uint32_t words = size / 4;
    uint32_t bytes_remaining = size % 4;
    uint32_t current_addr = WriteAddr;
    
    HAL_FLASH_Unlock();
    
    // 擦除目标页
    status = bsp_FLASH_ErasePage(WriteAddr);
    if(status != HAL_OK)
    {
        HAL_FLASH_Lock();
        return status;
    }
    
    // 写入完整的32位字
    for(uint32_t i = 0; i < words; i++)
    {
        status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, 
                                  current_addr, 
                                  *((uint32_t*)pBuf));
        if(status != HAL_OK) break;
        
        current_addr += 4;
        pBuf += 4;
    }
    
    // 写入剩余的字节
    if(status == HAL_OK && bytes_remaining > 0)
    {
        uint32_t last_word = 0xFFFFFFFF; // 默认填充0xFF
        uint8_t *last_bytes = (uint8_t*)&last_word;
        
        // 复制剩余数据
        for(uint32_t i = 0; i < bytes_remaining; i++)
        {
            last_bytes[i] = pBuf[i];
        }
        
        status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, current_addr, last_word);
    }
    
    HAL_FLASH_Lock();
    return status;
}

static void bsp_FlashReset(void)
{
    
    bsp_FlashDataWrite();
}

static void bsp_Flash_Init(void)
{
    
    bsp_FlashDataRead();
    if(p_Usr_Flash->FlashData.modbus_read_reg_num > 1000)
        p_Usr_Flash->FlashData.modbus_read_reg_num = sizeof(gas_data_t)/2;
    if(p_Usr_Flash->FlashData.modbus_read_sensor_num > SENSOR_NUM)
        p_Usr_Flash->FlashData.modbus_read_sensor_num = SENSOR_NUM;
    memcpy(&Usr_Flash.TempFlashData, &Usr_Flash.FlashData, sizeof(bsp_FlashData_t));
}

static void bsp_FlashDataWrite(void)
{ 
    /*防止重复擦写相同数据*/
    if(memcmp(&Usr_Flash.TempFlashData, &Usr_Flash.FlashData, sizeof(bsp_FlashData_t)) != 0)
    {
        Wdg.Feed();
        
        __disable_irq(); // 禁用全局中断
        
        HAL_StatusTypeDef status = bsp_Flash_STMFLASH_Write(BSP_FLASH_DATASAVE_ADDR,&Usr_Flash.FlashData,sizeof(bsp_FlashData_t));
        if(status == HAL_OK)
        {
            // 写入成功，更新临时数据
            memcpy(&Usr_Flash.TempFlashData, &Usr_Flash.FlashData, sizeof(bsp_FlashData_t));
        }
        else
        {
               
        }
        __enable_irq(); // 恢复中断
        Wdg.Feed();
    }
}

static void bsp_FlashDataRead(void)
{ 
    Wdg.Feed();
    bsp_Flash_STMFLASH_Read(BSP_FLASH_DATASAVE_ADDR, 
                           &Usr_Flash.FlashData, 
                           sizeof(bsp_FlashData_t));
    Wdg.Feed();
}
