/*
 * @Author: mbw
 * @Date: 2024-12-06 14:49:21
 * @LastEditors: mbw && 1600520629@qq.com
 * @LastEditTime: 2025-01-04 16:10:24
 * @FilePath: \ble_-tyq_-bjq_-ch584-m\bsp\src\bsp_flash.c
 * @Description: 主要用于对一些MAC地址等关键信息进行保存和读取操作
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
#include "bsp_flash.h"
#include "CONFIG.h"
#include "string.h"
#include "bsp_valve.h"

#undef LOG_ENABLE
#define LOG_ENABLE 1
# include "log.h"

void Flash_ErasePage_ReadConfigInfo(uint8_t *page_buf)
{
    EEPROM_READ(FLASH_INFO_ADDR, page_buf, DATA_FLASH_PAGE_SIZE);
    DelayMs(10);
    EEPROM_ERASE(FLASH_INFO_ADDR, DATA_FLASH_PAGE_SIZE);
    DelayMs(20);
}

int Flash_Write_ConfigInfo(uint8_t *page_buf)
{
    EEPROM_WRITE(FLASH_INFO_ADDR, page_buf, DATA_FLASH_PAGE_SIZE);
    DelayMs(10);
    return 0;
}

/*写入MAC地址*/
int Flash_Set_Mac_Addr(uint8_t *mac_addr, uint8_t number)
{
    uint8_t page_buf[DATA_FLASH_PAGE_SIZE] = {0};
    uint8_t in_page_offset                 = ((FLASH_MAC_INFO_START_ADDR + (number - 1) * FLASH_MAC_INFO_LEN) - FLASH_MAC_INFO_START_ADDR);
    if ((mac_addr == NULL)||( number > MAX_VALVE_NUM))
    {
        return -1;
    }
    Flash_ErasePage_ReadConfigInfo(page_buf);
    for (int i = 0; i < FLASH_MAC_INFO_LEN; i++)
    {
        page_buf[in_page_offset++] = mac_addr[i];
    }
    return Flash_Write_ConfigInfo(page_buf);
}

/*读取MAC地址*/
int Flash_Get_Mac_Addr(uint8_t *mac_addr, uint8_t number)
{
    __attribute__((aligned(4)))
    uint8_t data[FLASH_MAC_INFO_LEN]; // 读写buf需要4字节对齐
    EEPROM_READ((FLASH_MAC_INFO_START_ADDR + (number - 1) * FLASH_MAC_INFO_LEN), mac_addr, FLASH_MAC_INFO_LEN);
    DelayMs(10);
    return 0;
}

/*设置无线调压器数量*/
int Flash_Set_Valve_Num(uint8_t valve_num)
{
    __attribute__((aligned(4)))
    uint8_t page_buf[DATA_FLASH_PAGE_SIZE] = {0};
    uint8_t in_page_offset                 = (FLASH_MAC_NUM_ADDR - FLASH_INFO_ADDR);
    Flash_ErasePage_ReadConfigInfo(page_buf);
    page_buf[in_page_offset] = valve_num;

    return Flash_Write_ConfigInfo(page_buf);
}


/*获取无线调压器数量*/
uint8_t Flash_Get_Valve_Num(void)
{
    int num;
    EEPROM_READ(FLASH_MAC_NUM_ADDR, &num, FLASH_MAC_NUM_LEN);
    DelayMs(10);
    if ((uint8_t)num != 0xFF)
    {
        return (uint8_t)(num & 0xFF);
    }
    else
    {
        return 0;
    }
}

void BSP_FLASH_Init(void)
{
    uint32_t flash_write_flag = 0;
    EEPROM_READ(FLASH_INFO_WRITE_FLAG_ADDR, &flash_write_flag, FLASH_INFO_WRITE_FLAG_LEN);
    DelayMs(1000);
    logDebug("flash_write_flag = %X", flash_write_flag);
    
    if (flash_write_flag != FLASH_INFO_WRITE_FLAG_VAL) // 用以防止刷掉写入的数据
    {
        logDebug("flash_write_flag != FLASH_INFO_WRITE_FLAG_VAL");
        logDebug("BSP_FLASH_Init");
        flash_write_flag = FLASH_INFO_WRITE_FLAG_VAL;
        // 擦除数据
        EEPROM_ERASE(FLASH_INFO_ADDR, DATA_FLASH_PAGE_SIZE); // 擦除待写区
        DelayMs(10);
        EEPROM_WRITE(FLASH_INFO_WRITE_FLAG_ADDR, &flash_write_flag, FLASH_INFO_WRITE_FLAG_LEN);
        DelayMs(10);
    }
}
