/*
 * @Author: mbw
 * @Date: 2024-12-06 14:49:21
 * @LastEditors: mbw && 1600520629@qq.com
 * @LastEditTime: 2024-12-10 15:28:37
 * @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"


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

int Flash_Write_ConfigInfo(uint8_t *page_buf)
{
    EEPROM_WRITE(FLASH_INFO_ADDR, page_buf, DATA_FLASH_PAGE_SIZE);

    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_1_ADDR + number * 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 + 2]; // 读写buf需要4字节对齐
    // char mac[16] = {0};
    EEPROM_READ((FLASH_MAC_INFO_START_ADDR + number * FLASH_MAC_INFO_LEN), data, FLASH_MAC_INFO_LEN);
    if (data == NULL)
    {
        // PRINTF("Flash_Get_Mac_Addr failed");
        return -1;
    }
    // sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x",
    //      data[5], data[4], data[3], data[2], data[1], data[0]);
    // PRINTF("mac_addr:%s", mac);
    tmos_memcpy(mac_addr, data, FLASH_MAC_INFO_LEN);

    return 0;
}

/*设置无线调压器数量*/
int Flash_Set_Valve_Num(uint8_t valve_num)
{
    uint8_t page_buf[DATA_FLASH_PAGE_SIZE] = {0};
    uint8_t in_page_offset                 = (FLASH_INFO_ADDR - FLASH_MAC_INFO_START_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)
{
    uint8_t num;
    EEPROM_READ(FLASH_MAC_NUM_ADDR, &num, FLASH_MAC_NUM_LEN);
    return num;
}

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);
    if (flash_write_flag != FLASH_INFO_WRITE_FLAG_VAL) // 用以防止刷掉写入的数据
    {
        flash_write_flag = FLASH_INFO_WRITE_FLAG_VAL;
        // 擦除数据
        EEPROM_ERASE(FLASH_INFO_ADDR, DATA_FLASH_PAGE_SIZE); // 擦除待写区
        EEPROM_WRITE(FLASH_INFO_WRITE_FLAG_ADDR, &flash_write_flag, FLASH_INFO_WRITE_FLAG_LEN);
    }
}
