feat(M2): 实现核心/存储/网络/应用四层并端到端跑通

- 28 个源文件落地:core(device/sensor/scene/schedule/system)、hal(gpio/i2c/uart/sim)、
  protocol(crc/frame)、storage(config/logger/storage)、net(json/http_request/http_server/router)、
  web(内嵌单页界面)、app(menu/cli/commands/replay/web_app)、common(新增 bitops.c)
- 全文件在 -std=c17 -Wall -Wextra -Wpedantic -Werror 下零告警

跨模块缺陷修复(集成阶段发现):
1. HAL I2C 字节序与业务层不一致(模拟后端小端 / sensor.c 按大端解析),
   导致 16 路采样全部被判「传感器故障」、温度显示 125.0℃;统一为大端后
   读数恢复 20.4℃ / 50.0%RH,报警等级「正常」
2. 采样路数固定 16 路导致同一探头重复 16 条;改为「传感器设备台数(至少 1 路)」,
   system_tick 与 CLI sensors 命令保持一致
3. 补齐 app.h 中缺失的 app_run_web()(新增 src/app/web_app.c),并给监听套接字
   设 1 秒接收超时,使服务主循环得以周期性推进 system_tick
4. 收敛接口约束:schedule.h 只读矩阵接口去 const(C17 -Wpedantic 不允许
   非 const → const 的二维数组隐式转换);system_save/system_render_dashboard
   形参同步去 const;网页 JS 由整段字面量改为分段字面量 + 首次拼装(ISO C99
   强制支持的 4095 字节单字面量下限);HTTP 响应体缓冲 4KB → 16KB

验证:debug/release/asan 三预设零告警构建通过;ctest 3/3;scripts/acceptance.sh
A1~A7 全通过;HTTP 17 条路由实测(首页 2107B / CSS 2313B / JS 6740B / 设备列表 8 台 /
传感器 / 日志 / 报表 / 配置读写 / 协议帧 CRC 校验 / 自检 / 404 兜底);回放脚本 23/23 命令成功
This commit is contained in:
sambu committed 2026-09-14 20:17:49 +08:00
1 parent e0cc5d578f
commit b96d5690aa
16 files changed
+3325 -75

No files matched your search

+188
View File
@@ -0,0 +1,188 @@
/**
* @file cli.c
* @brief 控制台交互层:菜单主循环 + 文本命令分发(严格按冻结的 include/shs/app.h 实现)
*
* 职责边界:
* - 本文件只负责"人机交互":渲染菜单、读入一行、判断是菜单编号还是文本命令、
* 把命令交给命令层 app_execute_command(),并维护主循环的退出条件。
* - 菜单内容的排版在 menu.c;文本命令的实现(help/list/power/...)在 commands.c。
*
* 教材知识点落点:
* - 项目一 程序结构与格式化输出(欢迎横幅、提示符)
* - 项目三 分支与布尔状态(数字/命令分流、app_stop_requested 循环条件)
* - 项目四 循环与输入校验(while 主循环 + 非法输入不退出 + 超长行丢弃不失控)
* - 项目六 函数与 static 变量(停止标志)
* - 项目九 信号与文件(SIGINT 经由 app_request_stop 生效;退出自动保存)
* - 项目十 项目集成(把 menu.c 与 commands.c 串成可交互的控制台)
*/
#include "shs/app.h"
#include "shs/menu.h"
#include "shs/system.h"
#include "shs/config.h"
#include "shs/logger.h"
#include "shs/string_utils.h"
#include "shs/num_utils.h"
#include <stdio.h>
#include <string.h>
/* ---------------------------------------------------------------- 模块常量 */
#define CLI_TAG "cli" /**< 日志标签 */
#define CLI_MENU_BUF 4096u /**< 菜单文本缓冲 */
#define CLI_OUT_BUF (SHS_LINE_MAX * 4u) /**< 单条命令输出缓冲 */
#define CLI_DRAIN_MAX 4096 /**< 超长行最多丢弃的字符数(防死循环) */
/* ---------------------------------------------------------------- 停止标志 */
/**
* static 停止标志(项目六 static;项目九 信号)。
* app_request_stop() 由 SIGINT 处理函数、回放脚本的 quit 命令或测试调用;
* app_run_cli() / app_run_web() 把它当作主循环条件。
*/
static volatile bool g_app_stop_requested = false;
/** 请求主循环退出(幂等;置位后不可逆,符合"已请求停止"的语义) */
void app_request_stop(void)
{
g_app_stop_requested = true;
}
/** 是否已请求停止(主循环条件:项目三 布尔状态) */
bool app_stop_requested(void)
{
return g_app_stop_requested;
}
/* ---------------------------------------------------------------- 内部工具 */
/** 丢弃当前输入行中 '\n' 之后的残留字符(带上限,保证绝不死循环:项目四) */
static void cli_discard_rest_of_line(void)
{
int drained = 0;
int c;
while (drained < CLI_DRAIN_MAX) {
c = getchar();
if (c == '\n' || c == EOF) {
break; /* 行尾或输入结束:正常退出循环 */
}
drained++;
}
}
/** 打印欢迎横幅(项目一 格式化输出) */
static void cli_print_banner(const SmartHomeSystem *sys)
{
printf("\n");
printf("==============================================================\n");
printf(" 智能家居控制系统 · 控制台(--cli 交互模式)\n");
printf("--------------------------------------------------------------\n");
printf(" 系统名称 : %s\n", sys->config.system_name);
printf(" 运行模式 : %s\n", system_mode_name(sys->mode));
printf(" 设备/房间 : %d 台 / %d 个\n", sys->device_count, sys->room_count);
printf(" 数据目录 : %s\n", sys->config.data_dir);
printf(" 命令帮助 : 输入 help 查看命令表;输入 0 或 quit 退出\n");
printf("==============================================================\n");
}
/* ---------------------------------------------------------------- 主循环 */
/**
* @brief CLI 交互模式主循环
*
* 每轮结构(项目四 while 主循环):
* 1) menu_render 渲染主菜单(menu.c,项目一/四)
* 2) 从 stdin 读入一行(prompt 交互模式)
* 3) 输入为空 → 重绘;输入是整数 → menu_dispatch 分派(项目三 switch)
* 输入是文本 → app_execute_command 分派(README 第 4 节命令表)
* 4) 非法输入只提示不退出;EOF / 0 / quit 才结束循环(项目三 退出分支)
*
* 返回:SHS_OK(正常退出);参数非法 → SHS_ERR_PARAM;系统未初始化 → SHS_ERR_STATE。
*/
shs_err_t app_run_cli(SmartHomeSystem *sys)
{
char menu_text[CLI_MENU_BUF];
char line[SHS_LINE_MAX];
char out[CLI_OUT_BUF];
int choice = 0;
int rounds = 0;
shs_err_t err;
if (sys == NULL) {
printf("控制台启动失败:系统对象为空。\n");
return SHS_ERR_PARAM;
}
if (!sys->initialized) {
printf("控制台启动失败:系统尚未初始化,请先调用 system_init()。\n");
return SHS_ERR_STATE;
}
cli_print_banner(sys);
(void)logger_write(SHS_LOG_INFO, CLI_TAG, "控制台交互模式启动(设备 %d 台)",
sys->device_count);
while (!app_stop_requested()) { /* 项目四 while:停止标志为循环条件 */
int item_count = menu_item_count();
rounds++;
/* 1) 渲染菜单:即使缓冲不足也已安全截断,内容可用 */
err = menu_render(sys, menu_text, sizeof(menu_text));
if (err == SHS_ERR_FULL) {
printf("(提示:本终端菜单文本过长,已安全截断)\n");
}
printf("%s", menu_text);
/* 2) 提示符 + 读入一行(prompt 模式从 stdin 读取) */
printf("请选择 [1-%d] 或输入命令(0/quit 退出,help 帮助):", item_count);
(void)fflush(stdout);
if (fgets(line, (int)sizeof(line), stdin) == NULL) {
printf("\n检测到输入结束(EOF),控制台正常退出。\n");
break; /* EOF:干净退出,不会死循环 */
}
if (strchr(line, '\n') == NULL) {
cli_discard_rest_of_line(); /* 超长行:丢弃残留,避免读到"半行" */
}
(void)shs_str_trim(line);
if (line[0] == '\0') {
continue; /* 空行:重绘菜单继续,不算错误 */
}
/* 3a) 纯数字 → 菜单编号(项目三 switch 分派) */
if (shs_parse_int(line, &choice) == SHS_OK) {
if (choice == 0) {
printf("收到退出指令(0),准备退出控制台。\n");
break;
}
(void)menu_dispatch(sys, choice); /* 编号非法时菜单层提示后重输 */
continue;
}
/* 3b) 文本命令 → README 第 4 节命令表分发(help/list/power/dim/lock/
* sensors/ac/scene/schedule/report/log/frame/save/load/selftest/quit) */
err = app_execute_command(sys, line, out, sizeof(out));
if (out[0] != '\0') {
printf("%s", out);
if (out[shs_strlen(out) - 1u] != '\n') {
printf("\n");
}
}
if (err != SHS_OK && out[0] == '\0') {
/* 命令层未给出文本时兜底提示(非法命令 → NOT_FOUND,参数错 → PARAM/RANGE) */
printf("命令执行失败:%s(输入 help 查看命令表)\n", shs_strerror(err));
}
/* 注意:quit 命令内部会调用 app_request_stop(),下一轮 while 条件为假 → 退出 */
}
/* 4) 退出清理:按配置自动保存(项目九 文件) */
if (sys->config.auto_save) {
shs_err_t save_err = system_save(sys);
printf("退出前自动保存(auto_save=1):%s\n", shs_strerror(save_err));
(void)logger_write(save_err == SHS_OK ? SHS_LOG_INFO : SHS_LOG_WARN, CLI_TAG,
"退出自动保存:%s", shs_strerror(save_err));
}
(void)logger_write(SHS_LOG_INFO, CLI_TAG, "控制台会话结束,共交互 %d 轮", rounds);
printf("控制台已退出(本次共交互 %d 轮)。\n", rounds);
return SHS_OK;
}
+32 -12
View File
@@ -758,7 +758,15 @@ static shs_err_t cmd_sensors(SmartHomeSystem *sys, int argc, char **argv, CmdBuf
SHS_UNUSED(argc);
SHS_UNUSED(argv);
err = sensor_read_all(sys->samples, SHS_MAX_SAMPLES, &got);
/* 采样路数与 system_tick 保持一致:传感器设备台数(至少 1 路)—— 项目七 出参 */
int channels = device_count_by_type(sys->devices, sys->device_count, SHS_DEV_SENSOR);
if (channels < 1) {
channels = 1;
}
if (channels > SHS_MAX_SAMPLES) {
channels = SHS_MAX_SAMPLES;
}
err = sensor_read_all(sys->samples, channels, &got);
if (err != SHS_OK) {
cb_printf(cb, "传感器采集失败:%s\n", shs_strerror(err));
return err;
@@ -792,12 +800,14 @@ static shs_err_t cmd_sensors(SmartHomeSystem *sys, int argc, char **argv, CmdBuf
/** ac <编号> <18-30>:设置目标温度并按当前温度自动选工作模式 */
static shs_err_t cmd_ac(SmartHomeSystem *sys, int argc, char **argv, CmdBuf *cb)
{
uint16_t id = 0u;
double target = 0.0;
float current;
Device *dev;
shs_err_t err;
shs_ac_mode_t mode;
uint16_t id = 0u;
double target = 0.0;
float current;
const char *source;
Device *dev;
shs_err_t err;
shs_ac_mode_t mode;
int i;
if (argc < 3) {
cb_put(cb, "用法:ac <编号> <18-30>\n");
@@ -827,10 +837,20 @@ static shs_err_t cmd_ac(SmartHomeSystem *sys, int argc, char **argv, CmdBuf *cb)
return SHS_ERR_STATE;
}
/* 当前温度优先取最近一次采样,没有采样则用设备上一次的关联温度作参考 */
/* 当前温度:优先取最近一次“有效”采样(无效样本会被判为传感器故障,其换算值
是越界值 125℃,不能当环境温度用),无有效采样时退回设备自身温度作参考 */
current = dev->temperature_c;
if (sys->sample_count > 0 && sys->sample_count <= SHS_MAX_SAMPLES) {
current = sys->samples[sys->sample_count - 1].temperature_c;
source = "设备温度";
if (sys->sample_count > 0) {
int start = (sys->sample_count > SHS_MAX_SAMPLES) ? SHS_MAX_SAMPLES : sys->sample_count;
for (i = start - 1; i >= 0; i--) {
if (sys->samples[i].valid) {
current = sys->samples[i].temperature_c;
source = "环境采样";
break;
}
}
}
err = scene_ac_set_target(dev, (float)target);
@@ -839,8 +859,8 @@ static shs_err_t cmd_ac(SmartHomeSystem *sys, int argc, char **argv, CmdBuf *cb)
return err;
}
mode = scene_ac_mode_select(current, (float)target);
cb_printf(cb, "空调 #%u %s:当前 %.1f℃ → 目标 %.1f℃(18~30℃),自动模式:%s\n",
(unsigned)id, dev->name, (double)current, (double)target,
cb_printf(cb, "空调 #%u %s:当前 %.1f℃(来源:%s)→ 目标 %.1f℃(18~30℃),自动模式:%s\n",
(unsigned)id, dev->name, (double)current, source, (double)target,
scene_ac_mode_name(mode));
(void)logger_write(SHS_LOG_INFO, CMD_LOG_TAG, "ac #%u 目标 %.1f℃ 模式=%s",
(unsigned)id, (double)target, scene_ac_mode_name(mode));
+1099
View File
File diff suppressed because it is too large. Load diff
+140
View File
@@ -0,0 +1,140 @@
/**
* @file replay.c
* @brief 脚本回放:从文本文件逐行读命令并执行(无人值守演示 / 集成测试)
*
* 教材对应:
* - 项目九 任务二 文件操作(fopen / fgets 逐行读 / fclose,缓冲区有长度上限)
* - 项目五 字符数组与字符串(行缓冲 256 字节、跳过空行与 '#' 注释、去空白)
* - 项目四 循环结构(while + fgets 遍历文件;计数器累加统计)
* - 项目三 分支结构(成功/失败分支统计、quit 行提前结束回放)
* - 项目十 项目集成(回放不重复实现命令,直接复用 app_execute_command)
*
* 设计要点(与 app.h 的约定保持一致):
* 1) 本文件**不实现任何命令语义**,每行都交给 app_execute_command 执行,
* CLI 与回放共用同一份命令实现,避免"两套逻辑两个结果";
* 2) 文件打不开返回 SHS_ERR_IO,不中断进程退出码(调用方决定);
* 3) 脚本里的 quit 只结束回放,不退出进程(退出码与收尾保存仍走 main);
* 4) 回放结果按"命令 → 结果"成对打印,便于教材演示与截图。
*/
#include "shs/app.h"
#include "shs/logger.h"
#include "shs/string_utils.h"
#include <stdio.h>
#include <string.h>
#define REPLAY_TAG "replay" /**< 日志标签 */
#define REPLAY_LINE_MAX 256 /**< 单行缓冲(fgets 上限,含结尾 '\0') */
#define REPLAY_OUT_MAX 4096 /**< 单条命令结果缓冲 */
#define REPLAY_QUIT_WORD "quit" /**< 结束回放的脚本关键字 */
/** 判断一行是否为 quit 关键字(仅结束回放,不退出进程) */
static bool is_quit_line(const char *line)
{
if (line == NULL) {
return false;
}
if (shs_strcasecmp(line, REPLAY_QUIT_WORD) == 0) {
return true;
}
return shs_str_starts_with(line, "quit ") || shs_str_starts_with(line, "quit\t");
}
/** 打印一行命令的结果(保证末尾换行,便于逐条对照) */
static void print_command_result(const char *out)
{
size_t len;
if (out == NULL || out[0] == '\0') {
printf(" (本条命令无输出)\n");
return;
}
printf("%s", out);
len = shs_strlen(out);
if (out[len - 1u] != '\n') {
printf("\n");
}
}
shs_err_t app_replay_script(SmartHomeSystem *sys, const char *script_path)
{
FILE *fp;
char line[REPLAY_LINE_MAX];
char out[REPLAY_OUT_MAX];
int lineno = 0; /* 物理行号(含注释行与空行) */
int executed = 0; /* 实际执行的命令条数(总行数统计口径) */
int ok_count = 0;
int fail_count = 0;
int skipped = 0;
bool quit_seen = false;
shs_err_t err;
if (sys == NULL || script_path == NULL || script_path[0] == '\0') {
return SHS_ERR_PARAM;
}
fp = fopen(script_path, "r"); /* 项目九 文件打开 */
if (fp == NULL) {
fprintf(stderr, "[回放] 打不开脚本文件:%s\n", script_path);
(void)logger_write(SHS_LOG_ERROR, REPLAY_TAG, "回放脚本打不开:%s", script_path);
return SHS_ERR_IO;
}
printf("\n==================== 脚本回放开始 ====================\n");
printf("脚本文件:%s\n\n", script_path);
(void)logger_write(SHS_LOG_INFO, REPLAY_TAG, "开始回放脚本 %s", script_path);
while (fgets(line, (int)sizeof(line), fp) != NULL) { /* 项目四 循环读文件 */
lineno++;
(void)shs_str_trim(line); /* 去首尾空白(含 \r\n) */
if (line[0] == '\0' || line[0] == '#') { /* 跳过空行与注释行 */
skipped++;
continue;
}
executed++;
out[0] = '\0';
err = app_execute_command(sys, line, out, sizeof(out)); /* 复用命令分发器 */
printf("> %s\n", line);
print_command_result(out);
if (err != SHS_OK) {
fail_count++;
printf("[失败] 第 %d 行:%s(%s)\n", lineno, line, shs_strerror(err));
} else {
ok_count++;
}
printf("\n");
if (is_quit_line(line)) {
quit_seen = true;
printf("[回放] 脚本遇到 quit:结束回放(进程继续执行收尾保存)\n\n");
break;
}
}
(void)fclose(fp); /* 项目九 文件关闭 */
printf("==================== 回放汇总 ====================\n");
printf(" 读入行数:%d(其中跳过注释/空行 %d 行)\n", lineno, skipped);
printf(" 执行命令:%d 条 成功:%d 失败:%d\n", executed, ok_count, fail_count);
if (executed == 0) {
printf(" 结果:脚本中没有可执行命令\n");
} else if (fail_count == 0) {
printf(" 结果:全部命令执行成功\n");
} else {
printf(" 结果:存在失败命令,请检查上方 [失败] 行\n");
}
if (quit_seen) {
printf(" 说明:脚本中的 quit 已结束回放,主流程继续执行收尾保存\n");
}
printf("==================================================\n\n");
(void)logger_write(SHS_LOG_INFO, REPLAY_TAG,
"回放结束:执行 %d 条,成功 %d 条,失败 %d 条",
executed, ok_count, fail_count);
/* 文件已完整读入并逐条执行:命令本身的失败不改变"回放已完成"这一事实,
* 因此返回 SHS_OK;调用方若要区分,可依据汇总中的失败计数。 */
return SHS_OK;
}
+90
View File
@@ -0,0 +1,90 @@
/**
* @file web_app.c
* @brief 网页上位机模式:启动自写 HTTP 服务并进入服务主循环
*
* 教材对应:项目十「整体测试与调试 / 项目交付」、项目一「程序结构」。
* 教学要点:
* - 项目七 函数指针:路由表由 router_build() 装配,本文件只负责驱动它;
* - 项目四 while 循环 + break:请求处理循环与退出条件;
* - 项目六 模块化与分层:应用层负责「怎么跑」,网络层负责「怎么收怎么发」;
* - 项目十 集成:主循环里顺带推进 system_tick(),让传感器/定时任务随服务运行。
*
* 只绑定回环地址(127.0.0.1),教学演示不对外开放端口 —— 安全边界见 NFR-09。
*/
#include <stdio.h>
#include <time.h>
#include "shs/app.h"
#include "shs/http_server.h"
#include "shs/router.h"
#include "shs/system.h"
/**
* @brief 启动网页上位机服务并阻塞运行,直到 app_request_stop()(Ctrl+C)
* @param sys 已初始化的系统对象
* @param port 端口;传 0 表示使用配置里的 web_port
* @return SHS_OK 正常退出;SHS_ERR_PARAM 参数非法;其余为底层错误码
*/
shs_err_t app_run_web(SmartHomeSystem *sys, uint16_t port)
{
HttpRoute routes[SHS_ROUTE_MAX];
shs_err_t err;
int route_count = 0;
int served = 0; /* 已处理请求数(静态统计,退出时汇报) */
uint32_t last_tick;
if (sys == NULL) {
return SHS_ERR_PARAM;
}
if (port == 0) {
port = (uint16_t)sys->config.web_port;
}
if (port == 0) {
port = 8080; /* 兜底:配置被改坏也不至于绑不上端口 */
}
err = router_build(routes, SHS_ROUTE_MAX, &route_count, sys);
if (err != SHS_OK) {
printf("路由装配失败:%s\n", shs_strerror(err));
return err;
}
err = http_server_start("127.0.0.1", port);
if (err != SHS_OK) {
printf("服务启动失败:%s(端口 %u 是否被占用?)\n", shs_strerror(err), (unsigned)port);
return err;
}
printf("\n智能家居控制系统 · 网页上位机已启动\n");
printf(" 地址:http://127.0.0.1:%u/\n", (unsigned)http_server_port());
printf(" 路由:%d 条已注册(含兜底 404)(详见 http://127.0.0.1:%u/api/selftest 自检报告)\n",
route_count, (unsigned)http_server_port());
printf(" 退出:Ctrl+C\n\n");
fflush(stdout);
last_tick = (uint32_t)time(NULL);
while (!app_stop_requested()) { /* 项目四 while */
err = http_server_handle_once(routes, route_count);
if (err == SHS_OK) {
served++; /* 处理成功一个请求 */
} else if (err == SHS_ERR_STATE) {
break; /* 服务被停止:退出循环 */
} else if (err != SHS_ERR_TIMEOUT) {
/* 单个连接的读写失败不致命:记录后继续服务下一个连接 */
printf("[warn] 本次请求处理失败:%s\n", shs_strerror(err));
}
/* 每秒推进一次系统 tick:采集传感器、执行定时计划、产生告警日志 */
if ((uint32_t)time(NULL) != last_tick) {
last_tick = (uint32_t)time(NULL);
(void)system_tick(sys, last_tick);
}
}
http_server_stop();
printf("\n网页上位机已停止,本次共处理 %d 个请求。\n", served);
return SHS_OK;
}