/* * Copyright (c) 2026, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2026-03-06 user first version * 2026-04-16 user add power-loss protection, fix index wrap, reduce RAM */ #define DBG_TAG "ecode" #define DBG_LVL DBG_INFO #include #include #include #include #include #include #include "ecode.h" /* 分区名称 */ #define ECODE_PART_NAME "ecode" /* NOR Flash 扇区大小 */ #define SECTOR_SIZE 4096 /* 每条记录固定为64字节 */ #define RECORD_SIZE sizeof(ecode_record_t) /* 每扇区记录数 */ #define RECORDS_PER_SECTOR (SECTOR_SIZE / RECORD_SIZE) _Static_assert(sizeof(ecode_record_t) == 64, "ecode_record_t size must be 64 bytes"); /* 头部结构 */ typedef struct { uint32_t magic; uint32_t version; uint32_t write_seq; } ecode_header_t; /* 缓存扇区尾部信息(位于扇区末尾16字节) */ #define CACHE_MAGIC_VALID 0xA5A5A5A5 #define CACHE_TAIL_OFFSET (SECTOR_SIZE - 16) typedef struct __attribute__((packed)) { uint32_t magic; uint32_t target_sector; uint32_t new_write_seq; uint32_t crc32; } cache_tail_t; static const struct fal_partition *ecode_part = RT_NULL; static uint32_t max_sectors = 0; // 数据扇区总数(不含头部和缓存扇区) static rt_mutex_t ecode_lock = RT_NULL; static rt_bool_t initialized = RT_FALSE; static rt_mutex_t init_mutex = RT_NULL; /* 全局唯一缓冲区(受 ecode_lock 保护),用于所有 Flash 扇区操作 */ static uint8_t g_buf[SECTOR_SIZE]; extern struct rtc_time time_now; /* 清理detail字符串,确保只包含可打印字符(保留中文UTF-8),遇垃圾数据或无效UTF-8序列截断 */ static void sanitize_detail(char *detail, size_t size) { if (size == 0) return; detail[size - 1] = '\0'; /* 确保结尾有终止符 */ for (size_t i = 0; i < size - 1; i++) { unsigned char c = detail[i]; if (c == 0x00) break; /* 正常结束 */ if (c == 0xFF) /* Flash擦除状态,视为未写入数据 */ { detail[i] = '\0'; break; } /* 控制字符(除\t \n \r外)也截断 */ if (c < 0x20 && c != '\t' && c != '\n' && c != '\r') { detail[i] = '\0'; break; } /* UTF-8多字节序列验证 - 防止截断的UTF-8字符导致乱码 */ if (c >= 0x80) { int bytes_needed = 0; /* 确定需要的字节数 */ if ((c & 0xE0) == 0xC0) bytes_needed = 2; /* 2字节序列: 110xxxxx */ else if ((c & 0xF0) == 0xE0) bytes_needed = 3; /* 3字节序列: 1110xxxx */ else if ((c & 0xF8) == 0xF0) bytes_needed = 4; /* 4字节序列: 11110xxx */ else /* 无效的UTF-8首字节 */ { detail[i] = '\0'; break; } /* 检查后续字节是否足够 */ if (i + bytes_needed >= size) { detail[i] = '\0'; break; } /* 验证后续字节是否符合UTF-8格式(必须是10xxxxxx) */ int valid = 1; for (int j = 1; j < bytes_needed; j++) { if ((detail[i + j] & 0xC0) != 0x80) /* 必须以10开头 */ { valid = 0; break; } } if (!valid) { detail[i] = '\0'; break; } /* 跳过已验证的多字节字符 */ i += bytes_needed - 1; } } } /* CRC32 计算 */ static uint32_t crc32_calc(const uint8_t *data, size_t len) { uint32_t crc = 0xFFFFFFFF; for (size_t i = 0; i < len; i++) { crc ^= data[i]; for (int j = 0; j < 8; j++) { if (crc & 1) crc = (crc >> 1) ^ 0xEDB88320; else crc >>= 1; } } return ~crc; } /* 获取有效记录数 */ static uint32_t get_valid_count(uint32_t write_seq) { uint32_t max_records = max_sectors * RECORDS_PER_SECTOR; return (write_seq < max_records) ? write_seq : max_records; } /* 读取头部 */ static int read_header(ecode_header_t *hdr) { if (fal_partition_read(ecode_part, 0, (uint8_t *)hdr, sizeof(ecode_header_t)) < 0) { LOG_E("read header failed"); return -RT_ERROR; } return RT_EOK; } /* 写入头部 */ static int write_header(const ecode_header_t *hdr) { int ret = RT_EOK; if (fal_partition_read(ecode_part, 0, g_buf, SECTOR_SIZE) < 0) { LOG_E("read header sector failed"); return -RT_ERROR; } memcpy(g_buf, hdr, sizeof(ecode_header_t)); if (fal_partition_erase(ecode_part, 0, SECTOR_SIZE) < 0) { LOG_E("erase header sector failed"); return -RT_ERROR; } if (fal_partition_write(ecode_part, 0, g_buf, SECTOR_SIZE) != SECTOR_SIZE) { LOG_E("write header sector failed"); ret = -RT_ERROR; } return ret; } /* 擦除整个分区 */ static int erase_whole_partition(void) { if (fal_partition_erase(ecode_part, 0, ecode_part->len) < 0) { LOG_E("erase whole partition failed"); return -RT_ERROR; } return RT_EOK; } /* 获取缓存扇区地址 */ static uint32_t get_cache_sector_addr(void) { return ecode_part->len - SECTOR_SIZE; } /* 从缓存扇区恢复未完成写入 */ static void recover_from_cache(void) { uint32_t cache_addr = get_cache_sector_addr(); cache_tail_t tail; uint32_t calc_crc; if (fal_partition_read(ecode_part, cache_addr, g_buf, SECTOR_SIZE) < 0) { LOG_E("read cache sector failed"); return; } /* 读取尾部信息 */ memcpy(&tail, g_buf + CACHE_TAIL_OFFSET, sizeof(cache_tail_t)); if (tail.magic != CACHE_MAGIC_VALID) { LOG_D("no valid cache found"); return; } /* 计算数据部分 CRC */ calc_crc = crc32_calc(g_buf, CACHE_TAIL_OFFSET); if (calc_crc != tail.crc32) { LOG_W("cache sector CRC mismatch, discard"); fal_partition_erase(ecode_part, cache_addr, SECTOR_SIZE); return; } /* 校验目标扇区地址 */ if (tail.target_sector < SECTOR_SIZE || tail.target_sector >= cache_addr || (tail.target_sector - SECTOR_SIZE) % SECTOR_SIZE != 0) { LOG_E("invalid target sector 0x%x in cache", tail.target_sector); fal_partition_erase(ecode_part, cache_addr, SECTOR_SIZE); return; } LOG_I("found incomplete write, recovering target sector 0x%x", tail.target_sector); /* 恢复目标扇区 */ if (fal_partition_erase(ecode_part, tail.target_sector, SECTOR_SIZE) < 0) { LOG_E("erase target sector failed during recovery"); return; } if (fal_partition_write(ecode_part, tail.target_sector, g_buf, SECTOR_SIZE) != SECTOR_SIZE) { LOG_E("write target sector failed during recovery"); return; } /* 更新头部 */ ecode_header_t hdr; if (read_header(&hdr) == RT_EOK) { if (tail.new_write_seq > hdr.write_seq) { hdr.write_seq = tail.new_write_seq; if (write_header(&hdr) != RT_EOK) { LOG_E("update header after recovery failed"); } } } /* 清除缓存扇区 */ fal_partition_erase(ecode_part, cache_addr, SECTOR_SIZE); LOG_I("recovery completed"); } /* 核心初始化 */ static int ecode_init_core(void) { ecode_header_t hdr; uint32_t part_size; ecode_part = fal_partition_find(ECODE_PART_NAME); if (ecode_part == RT_NULL) { LOG_E("partition '%s' not found", ECODE_PART_NAME); return -RT_ERROR; } part_size = ecode_part->len; LOG_D("partition size: %u bytes", part_size); if (part_size < SECTOR_SIZE * 3) { LOG_E("partition too small (need at least %d bytes)", SECTOR_SIZE * 3); return -RT_ERROR; } max_sectors = (part_size / SECTOR_SIZE) - 2; // 头部扇区 + 缓存扇区 LOG_D("max_sectors=%u, records per sector=%u", max_sectors, RECORDS_PER_SECTOR); ecode_lock = rt_mutex_create("ecode", RT_IPC_FLAG_FIFO); if (ecode_lock == RT_NULL) { LOG_E("create mutex failed"); return -RT_ERROR; } /* 尝试恢复未完成写入 */ recover_from_cache(); if (read_header(&hdr) == RT_EOK && hdr.magic == ECODE_MAGIC && hdr.version == ECODE_VERSION) { LOG_D("ecode already initialized, write_seq=%u", hdr.write_seq); return RT_EOK; } LOG_W("partition not initialized or invalid, erasing..."); if (erase_whole_partition() != RT_EOK) { LOG_E("erase failed"); return -RT_ERROR; } hdr.magic = ECODE_MAGIC; hdr.version = ECODE_VERSION; hdr.write_seq = 0; if (write_header(&hdr) != RT_EOK) { LOG_E("write header failed"); return -RT_ERROR; } LOG_I("ecode initialized, max_sectors=%d", max_sectors); return RT_EOK; } static int ensure_initialized(void) { if (initialized) return RT_EOK; if (init_mutex == RT_NULL) { init_mutex = rt_mutex_create("ecode_init", RT_IPC_FLAG_FIFO); if (init_mutex == RT_NULL) { LOG_E("create init mutex failed"); return -RT_ERROR; } } rt_mutex_take(init_mutex, RT_WAITING_FOREVER); if (!initialized) { if (ecode_init_core() == RT_EOK) initialized = RT_TRUE; else LOG_E("ecode_init_core failed"); } rt_mutex_release(init_mutex); return initialized ? RT_EOK : -RT_ERROR; } int ecode_init(void) { return ensure_initialized(); } /** * @brief 记录异常事件 * * @param code 事件码 * @param para 参数码 * @param detail 描述 */ void Recode_e_code(ecode_list code, uint16_t para, char *detail) { ecode_header_t hdr; ecode_record_t rec; uint32_t seq, sector_index, record_offset_in_sector; uint32_t sector_start; uint32_t cache_addr; cache_tail_t tail; if (ensure_initialized() != RT_EOK) { LOG_E("ecode not initialized, abort write"); return; } rt_mutex_take(ecode_lock, RT_WAITING_FOREVER); if (read_header(&hdr) != RT_EOK) { LOG_E("read header failed"); rt_mutex_release(ecode_lock); return; } if (hdr.magic != ECODE_MAGIC || hdr.version != ECODE_VERSION) { LOG_E("header corrupted"); rt_mutex_release(ecode_lock); return; } seq = hdr.write_seq; /* 构建记录 */ rec.time_stamp.tm_year = time_now.year - 2000; rec.time_stamp.tm_mon = time_now.month; rec.time_stamp.tm_mday = time_now.date; rec.time_stamp.tm_hour = time_now.hour; rec.time_stamp.tm_min = time_now.minute; rec.time_stamp.tm_sec = time_now.second; rec.code = (uint16_t)code; rec.para = para; rec.num = seq; rt_strncpy(rec.detail, detail, sizeof(rec.detail) - 1); rec.detail[sizeof(rec.detail) - 1] = '\0'; /* 计算物理位置(修正循环逻辑) */ sector_index = (seq / RECORDS_PER_SECTOR) % max_sectors; sector_start = SECTOR_SIZE + sector_index * SECTOR_SIZE; record_offset_in_sector = (seq % RECORDS_PER_SECTOR) * RECORD_SIZE; LOG_D("write: seq=%u sector_index=%u sector_start=0x%x offset=%u", seq, sector_index, sector_start, record_offset_in_sector); /* 读取目标扇区到 g_buf */ if (fal_partition_read(ecode_part, sector_start, g_buf, SECTOR_SIZE) < 0) { LOG_E("read target sector failed"); rt_mutex_release(ecode_lock); return; } /* 修改对应记录 */ memcpy(g_buf + record_offset_in_sector, &rec, RECORD_SIZE); /* 准备缓存扇区尾部信息 */ cache_addr = get_cache_sector_addr(); tail.magic = CACHE_MAGIC_VALID; tail.target_sector = sector_start; tail.new_write_seq = seq + 1; tail.crc32 = crc32_calc(g_buf, CACHE_TAIL_OFFSET); /* 将尾部信息填入 g_buf 末尾 */ memcpy(g_buf + CACHE_TAIL_OFFSET, &tail, sizeof(cache_tail_t)); /* 步骤1:写入缓存扇区 */ if (fal_partition_erase(ecode_part, cache_addr, SECTOR_SIZE) < 0) { LOG_E("erase cache sector failed"); rt_mutex_release(ecode_lock); return; } if (fal_partition_write(ecode_part, cache_addr, g_buf, SECTOR_SIZE) != SECTOR_SIZE) { LOG_E("write cache sector failed"); rt_mutex_release(ecode_lock); return; } /* 步骤2:擦除目标扇区 */ if (fal_partition_erase(ecode_part, sector_start, SECTOR_SIZE) < 0) { LOG_E("erase target sector failed"); /* 尝试清除缓存扇区 */ fal_partition_erase(ecode_part, cache_addr, SECTOR_SIZE); rt_mutex_release(ecode_lock); return; } /* 步骤3:写回目标扇区(注意此时 g_buf 末尾仍带有缓存信息,但不影响数据部分) */ if (fal_partition_write(ecode_part, sector_start, g_buf, SECTOR_SIZE) != SECTOR_SIZE) { LOG_E("write target sector failed, data may be lost!"); /* 缓存扇区仍有效,下次上电可恢复 */ rt_mutex_release(ecode_lock); return; } /* 步骤4:更新头部 */ hdr.write_seq = seq + 1; if (write_header(&hdr) != RT_EOK) { LOG_E("write header failed, but data written"); } /* 步骤5:清除缓存扇区 */ if (fal_partition_erase(ecode_part, cache_addr, SECTOR_SIZE) < 0) { LOG_W("clear cache sector failed"); } LOG_W("e_code SET 0 c %d p %d d %s", code, para, detail); uint32_t total_records = max_sectors * RECORDS_PER_SECTOR; uint32_t used_records = hdr.write_seq; if (used_records > total_records) used_records = total_records; uint32_t used_bytes = used_records * RECORD_SIZE; LOG_I("e_code used %d cnt %d/%d", used_bytes, used_records, total_records); rt_mutex_release(ecode_lock); } /* 读取记录 */ int ecode_read(uint32_t index, ecode_record_t *rec) { ecode_header_t hdr; uint32_t valid_count; uint32_t logical_seq, sector_index, record_offset_in_sector; uint32_t sector_start; if (ensure_initialized() != RT_EOK) return -RT_ERROR; rt_mutex_take(ecode_lock, RT_WAITING_FOREVER); if (read_header(&hdr) != RT_EOK) { rt_mutex_release(ecode_lock); return -RT_ERROR; } if (hdr.magic != ECODE_MAGIC || hdr.version != ECODE_VERSION) { LOG_E("header corrupted"); rt_mutex_release(ecode_lock); return -RT_ERROR; } valid_count = get_valid_count(hdr.write_seq); if (index >= valid_count) { rt_mutex_release(ecode_lock); return -RT_ERROR; } logical_seq = hdr.write_seq - 1 - index; sector_index = (logical_seq / RECORDS_PER_SECTOR) % max_sectors; sector_start = SECTOR_SIZE + sector_index * SECTOR_SIZE; record_offset_in_sector = (logical_seq % RECORDS_PER_SECTOR) * RECORD_SIZE; LOG_D("read: index=%u logical_seq=%u sector_start=0x%x offset=%u", index, logical_seq, sector_start, record_offset_in_sector); if (fal_partition_read(ecode_part, sector_start, g_buf, SECTOR_SIZE) < 0) { LOG_E("read sector failed"); rt_mutex_release(ecode_lock); return -RT_ERROR; } memcpy(rec, g_buf + record_offset_in_sector, RECORD_SIZE); sanitize_detail(rec->detail, sizeof(rec->detail)); // 新增这一行 /* 检查是否为全0xFF */ uint8_t *p = (uint8_t *)rec; int all_ff = 1; for (uint32_t i = 0; i < RECORD_SIZE; i++) { if (p[i] != 0xFF) { all_ff = 0; break; } } if (all_ff) { LOG_W("record at index %d is all 0xFF (empty)", index); rt_mutex_release(ecode_lock); return -RT_ERROR; } if (rec->num > hdr.write_seq) { LOG_W("record at index %d has invalid num %u", index, rec->num); rt_mutex_release(ecode_lock); return -RT_ERROR; } rt_mutex_release(ecode_lock); return RT_EOK; } uint32_t ecode_get_count(void) { ecode_header_t hdr; uint32_t count; if (ensure_initialized() != RT_EOK) return 0; rt_mutex_take(ecode_lock, RT_WAITING_FOREVER); if (read_header(&hdr) != RT_EOK) { rt_mutex_release(ecode_lock); return 0; } if (hdr.magic != ECODE_MAGIC || hdr.version != ECODE_VERSION) { rt_mutex_release(ecode_lock); return 0; } count = get_valid_count(hdr.write_seq); rt_mutex_release(ecode_lock); return count; } void ecode_clear(void) { ecode_header_t hdr; if (ensure_initialized() != RT_EOK) { LOG_E("ecode not initialized"); return; } rt_mutex_take(ecode_lock, RT_WAITING_FOREVER); if (erase_whole_partition() != RT_EOK) { LOG_E("erase whole partition failed"); rt_mutex_release(ecode_lock); return; } hdr.magic = ECODE_MAGIC; hdr.version = ECODE_VERSION; hdr.write_seq = 0; if (write_header(&hdr) != RT_EOK) { LOG_E("write header failed after clear"); } else { LOG_I("ecode cleared"); } rt_mutex_release(ecode_lock); } /*====================== MSH 命令(保持不变)======================*/ #include static void recode_test(void) { Recode_e_code(e_test_fun, 6, "3-6 is a test record 123456789"); } MSH_CMD_EXPORT(recode_test, write a test ecode); static void pre(void) { ecode_record_t rec; uint32_t cnt = ecode_get_count(); LOG_I("ecode count: %u", cnt); for (uint32_t i = 0; i < cnt; i++) { if (ecode_read(i, &rec) == 0) { LOG_I("%u - %02u/%02u/%02u %02u:%02u:%02u: (%5u-%-5u) %s", rec.num, rec.time_stamp.tm_year, rec.time_stamp.tm_mon, rec.time_stamp.tm_mday, rec.time_stamp.tm_hour, rec.time_stamp.tm_min, rec.time_stamp.tm_sec, rec.code, rec.para, rec.detail); } else { LOG_I("read error at index %u", i); } } } MSH_CMD_EXPORT(pre, print all ecode records from newest to oldest); static void delecode(void) { ecode_clear(); } MSH_CMD_EXPORT(delecode, clear all ecode records); static void ecode_test(int argc, char **argv) { ecode_record_t rec; uint32_t cnt_before, cnt_after; int i, ret; LOG_I("===== ecode module test start ====="); ecode_clear(); cnt_before = ecode_get_count(); LOG_I("after clear, count=%u", cnt_before); if (cnt_before != 0) { LOG_E("clear failed"); return; } for (i = 0; i < 10; i++) { char detail[64]; rt_snprintf(detail, sizeof(detail), "test data %d", i); Recode_e_code(e_test_fun, i, detail); } cnt_after = ecode_get_count(); LOG_I("after write 10, count=%u", cnt_after); if (cnt_after != 10) { LOG_E("write count mismatch"); return; } for (i = 0; i < 10; i++) { ret = ecode_read(i, &rec); if (ret != 0) { LOG_E("read index %d failed", i); return; } LOG_I("read[%d]: num=%u time=%02u/%02u/%02u %02u:%02u:%02u code=%u para=%u detail=%s", i, rec.num, rec.time_stamp.tm_year, rec.time_stamp.tm_mon, rec.time_stamp.tm_mday, rec.time_stamp.tm_hour, rec.time_stamp.tm_min, rec.time_stamp.tm_sec, rec.code, rec.para, rec.detail); if (rec.num != (uint32_t)(9 - i)) { LOG_E("num mismatch: expected %d, got %u", 9 - i, rec.num); } if (rec.code != e_test_fun || rec.para != (uint16_t)(9 - i)) { LOG_E("code/para mismatch"); } } ret = ecode_read(10, &rec); if (ret == 0) { LOG_E("read beyond count should fail"); } else { LOG_I("read beyond count failed as expected"); } ecode_clear(); cnt_after = ecode_get_count(); if (cnt_after != 0) { LOG_E("clear after test failed"); } else { LOG_I("clear ok"); } LOG_I("===== ecode module test passed ====="); } MSH_CMD_EXPORT(ecode_test, run ecode module self - test);