/* * 模块名称:net_cfg_legacy * 模块功能:旧版 NCFG 二进制配置一次性迁移——读遗留文件 → 校验 magic/ver/CRC → * 填网络配置 RAM 副本 → 经 cfg_file 引擎生成新文件(带旧值)→ 删旧文件 * 适用平台:STM32F407ZGTx / PC 模拟器(两端共用;平台路径经 cfg_file_store 后端) * 作者:王建锋 * 创建日期:2026-09-14 * 修改记录: * v1.0 2026-09-14 王建锋 创建初始版本(P3:net_cfg 引擎化,旧格式代码迁入) */ /* 头文件包含区 */ #include #include "net_cfg_legacy.h" #include "net_cfg.h" #include "cfg_file.h" #include "cfg_file_store.h" #define DBG_TAG "[NET_CFG]" #include "dbg_log.h" /* 常量定义区 */ #define NET_CFG_MAGIC 0x4647434Eu /* 'NCFG'(文件字节序 N,C,G,F;小端装载) */ #define NET_CFG_VER 1u /* 磁盘格式版本 */ /* 旧磁盘格式(两端布局一致:u32 4 对齐;字段区 18B 连续,CRC 覆盖之) */ typedef struct { uint32_t magic; /* NET_CFG_MAGIC */ uint16_t ver; /* 格式版本 */ uint16_t crc; /* CRC-16/MODBUS(覆盖 ip..mac 共 18B) */ uint8_t ip[4]; uint8_t mask[4]; uint8_t gw[4]; uint8_t mac[6]; } net_cfg_blob_t; /* 静态函数声明区 */ static uint16_t s_crc16_modbus(const uint8_t *p_data, size_t len); /* 函数定义区 */ /* * 函数功能:CRC-16/MODBUS(无查表逐位算法) * 入口参数:p_data - 数据指针 const uint8_t * * len - 数据长度 size_t * 返回值:CRC-16 值 uint16_t * 限定条件:p_data 非空(len 可为 0,返回初始值 0xFFFF) * 函数说明:文件私有(数据量 ≤32B,性能无关) */ static uint16_t s_crc16_modbus(const uint8_t *p_data, size_t len) { uint16_t crc = 0xFFFFu; for (size_t i = 0u; i < len; i++) { crc = (uint16_t)(crc ^ (uint16_t)p_data[i]); for (int b = 0; b < 8; b++) { if (crc & 0x0001u) { crc = (uint16_t)((crc >> 1) ^ 0xA001u); } else { crc = (uint16_t)(crc >> 1); } } } return crc; } /* * 函数功能:旧 NCFG 二进制配置一次性迁移到通用配置文件 * 入口参数:无 * 返回值:0 - 迁移成功,或无旧文件/新文件已存在(正常);-1 - 迁移失败 int * 限定条件:调用方须已注册 [network] 段(net_cfg_load 内部完成) * 函数说明:见 net_cfg_legacy.h 同名函数说明 */ int net_cfg_legacy_migrate(void) { net_cfg_blob_t blob; uint8_t buf[32]; size_t nread = 0u; cfg_file_stat_t st; net_cfg_t tmp; const char *p_legacy; /* 新文件已存在 = 已迁移过(或已有配置):跳过 */ if (cfg_store_stat(cfg_store_config_path(), &st) == 0) { return 0; } p_legacy = cfg_store_legacy_path(); if (cfg_store_read(p_legacy, buf, sizeof(buf), &nread) != 0 || nread != sizeof(net_cfg_blob_t)) { DBG_INFO("legacy: no legacy file, skip"); return 0; } (void)memcpy(&blob, buf, sizeof(blob)); if (blob.magic != NET_CFG_MAGIC || blob.ver != NET_CFG_VER || s_crc16_modbus(blob.ip, 18u) != blob.crc) { DBG_INFO("legacy: blob invalid (magic/ver/crc), file kept for inspection"); return 0; } /* 填 RAM 副本(net_cfg_get 只读,经 net_cfg_set 可写接口整体回灌) * → 经引擎物化旧值到新文件(此时新文件必缺失 → 生成模板带旧值) */ (void)memcpy(&tmp, net_cfg_get(), sizeof(tmp)); (void)memcpy(tmp.ip, blob.ip, 4u); (void)memcpy(tmp.mask, blob.mask, 4u); (void)memcpy(tmp.gw, blob.gw, 4u); (void)memcpy(tmp.mac, blob.mac, 6u); net_cfg_set(&tmp); if (net_cfg_save() != 0) { DBG_ERROR("legacy: migrate save FAIL"); return -1; } (void)cfg_store_remove(p_legacy); DBG_INFO("legacy: migrated to config file (ip=%u.%u.%u.%u)", (unsigned)blob.ip[0], (unsigned)blob.ip[1], (unsigned)blob.ip[2], (unsigned)blob.ip[3]); return 0; }