72 lines
2.0 KiB
C
72 lines
2.0 KiB
C
/*
|
||
* 模块名称:Network Configuration Store (MCU 后端)
|
||
* 模块功能:net_cfg 存储后端——NAND 上 FatFS 文件 /cfg/netcfg.bin
|
||
* (目录 /cfg 首次写入时自动创建;卷由 defaultTask 挂载并广播
|
||
* SYS_EVT_STORAGE_READY 后方可读写)
|
||
* 适用平台:STM32F407ZGTx
|
||
* 作者:王建锋
|
||
* 创建日期:2026-09-10
|
||
* 修改记录:
|
||
* v1.0 2026-09-10 王建锋 创建初始版本
|
||
*/
|
||
|
||
/* 头文件包含区 */
|
||
#include "net_cfg_store.h"
|
||
|
||
#include "ff.h"
|
||
|
||
/* 静态变量定义区 */
|
||
|
||
static const char s_path[] = "/cfg/netcfg.bin";
|
||
|
||
/* 函数定义区 */
|
||
|
||
/*
|
||
* 函数功能:读取配置文件
|
||
* 入口参数:p_buf - 接收缓冲(不可为 NULL) uint8_t *
|
||
* len - 文件长度 size_t
|
||
* 返回值:0 - 成功;-1 - 文件缺失/读失败 int
|
||
* 限定条件:FatFS 已挂载(未挂载时 f_open 返回 FR_NO_SYSTEM,转 -1)
|
||
*/
|
||
int net_cfg_store_read(uint8_t *p_buf, size_t len) {
|
||
FIL f;
|
||
FRESULT fr;
|
||
UINT br = 0u;
|
||
|
||
if (p_buf == NULL) {
|
||
return -1;
|
||
}
|
||
fr = f_open(&f, s_path, FA_READ);
|
||
if (fr != FR_OK) {
|
||
return -1;
|
||
}
|
||
fr = f_read(&f, p_buf, (UINT)len, &br);
|
||
(void)f_close(&f);
|
||
return (fr == FR_OK && br == (UINT)len) ? 0 : -1;
|
||
}
|
||
|
||
/*
|
||
* 函数功能:写配置文件(目录不存在则创建;文件覆盖写)
|
||
* 入口参数:p_buf - 待写数据(不可为 NULL) const uint8_t *
|
||
* len - 数据长度 size_t
|
||
* 返回值:0 - 成功;-1 - 写失败 int
|
||
* 限定条件:FatFS 已挂载
|
||
*/
|
||
int net_cfg_store_write(const uint8_t *p_buf, size_t len) {
|
||
FIL f;
|
||
FRESULT fr;
|
||
UINT bw = 0u;
|
||
|
||
if (p_buf == NULL) {
|
||
return -1;
|
||
}
|
||
(void)f_mkdir("/cfg"); /* 目录已存在(FR_EXIST)不影响后续建文件 */
|
||
fr = f_open(&f, s_path, FA_WRITE | FA_CREATE_ALWAYS);
|
||
if (fr != FR_OK) {
|
||
return -1;
|
||
}
|
||
fr = f_write(&f, (const void *)p_buf, (UINT)len, &bw);
|
||
(void)f_close(&f);
|
||
return (fr == FR_OK && bw == (UINT)len) ? 0 : -1;
|
||
}
|