zhunk пре 1 месец
родитељ
комит
40e1ba63d9

+ 0 - 0
Application_cbd_apm32f1/.workbuddy/_g.txt


+ 54 - 0
Application_cbd_apm32f1/.workbuddy/float_fmt_check.txt

@@ -0,0 +1,54 @@
+==========================================================================
+[A] 全 applications 扫描: printf 家族不得使用 %f / %e / %g
+==========================================================================
+  未发现任何浮点格式符 (共扫描 D:\RT-ThreadStudio\workspace\IOT_CBD_BZY_CTRL\Application_cbd_apm32f1\applications)
+  => PASS
+
+==========================================================================
+[B] control.c: fmt_fixed2() —— 宿主 gcc 语法检查
+==========================================================================
+  切出 62 行, gcc exit=0
+  => PASS
+
+==========================================================================
+[C] fmt_fixed2() 数值正确性 —— 真编译真运行
+==========================================================================
+  ok   0.000000 prec=2 -> 0.00
+  ok   3.141590 prec=2 -> 3.14
+  ok   3.145000 prec=2 -> 3.15
+  ok   3.144000 prec=2 -> 3.14
+  ok   2.675000 prec=2 -> 2.68
+  ok   9.999000 prec=2 -> 10.00
+  ok   0.005000 prec=2 -> 0.01
+  ok   0.004000 prec=2 -> 0.00
+  ok   -3.141590 prec=2 -> -3.14
+  ok   -0.500000 prec=2 -> -0.50
+  ok   20000.000000 prec=2 -> 20000.00
+  ok   25000.000000 prec=2 -> 20000.00
+  ok   19999.999000 prec=2 -> 20000.00
+  ok   12.000000 prec=1 -> 12.0
+  ok   12.940000 prec=1 -> 12.9
+  ok   12.950000 prec=1 -> 13.0
+  ok   12.990000 prec=1 -> 13.0
+  ok   -12.950000 prec=1 -> -13.0
+  ok   12.340000 prec=0 -> 12
+  ok   12.940000 prec=0 -> 13
+  ok   75.000000 prec=2 -> 75.00
+  ok   162.500000 prec=2 -> 162.50
+  ok   310.000000 prec=2 -> 310.00
+
+  23/23 passed
+  => PASS
+
+==========================================================================
+[D] 原雷区调用点: power / heat_power / 相机参数
+==========================================================================
+  sht30_collect.c: fmt_fixed2 写 power/heat_power 共 3 处(应为 3)
+  dtu_uart2.c: fmt_fixed2 写相机参数共 2 处(应为 2)
+  control.c: fmt_fixed2 定义 1 处(应为 1)
+  control.h: fmt_fixed2 声明 1 处(应为 1)
+  => PASS
+
+==========================================================================
+总计: 全部通过
+==========================================================================

+ 53 - 0
Application_cbd_apm32f1/.workbuddy/memory/2026-09-30.md

@@ -0,0 +1,53 @@
+# 2026-09-30
+
+## 🔴 紧急修复:rt_snprintf 不支持浮点 → 电流电压上报显示 "%f"(版本 2.47 → 2.48)
+
+用户上机后反馈:**上传的电流电压数据显示成字面量 `%f`**。这是我 2026-09-28 第四批
+P2-7 修复引入的回归 —— 当时把定长数组写入统一换成 `rt_snprintf` 限长,
+**没有排除浮点格式符**。教训:换 printf 实现时必须逐个核对格式符支持集。
+
+### 根因(已查实到源码行)
+- `rt_snprintf` → `rt_vsnprintf`(`rt-thread/src/kservice.c:886`),
+  其转换字符 `switch` 只有 `c/s/d/i/o/u/x/X/%`,**没有 `f/e/g`**。
+- `rtconfig.h` 也**没有** `RT_USING_LIBC_FLOAT_PRINT`(只有 `RT_KPRINTF_USING_LONGLONG`);
+  `RT_PRINTF_PRECISION` 是 kservice.c:34 硬 `#define` 的。
+- `"%.2f"` 落到 `default:` 分支(`kservice.c:1090`):把 `%` 和后随字符**当普通字符原样写出**,
+  然后 `continue` → 缓冲区得到字面量 `"%f"`。
+  ⚠️ 该分支**不消费 double 可变参数** → 同一格式串里后续格式符的实参会**整体错位**。
+- 不能换回标准 `sprintf`:newlib 的 float printf 默认不使能(要链 `_printf_float`),
+  且原 `power[8]` 装 `"25000.00"` 本来就溢出。
+
+### 修复
+- 新增 `fmt_fixed2(char *buf, rt_size_t size, double val, int prec)`
+  —— control.c 实现 / control.h 导出,**纯整数定点**,只用 `%ld`/`%02ld`。
+  先 `scaled = (long)(val*100.0 + 0.5)`(等价四舍五入到 0.01),
+  再按 prec=0/1/2 三档取用;**三档都做了正确四舍五入**
+  (`fp>=50` 进位;prec=1 时 `fp%10>=5` 进位并处理跨 100)。
+  上限钳位 20000.00 防 `val*100` 溢出 long。
+- 改 5 个调用点:
+  sht30_collect.c 的 power×2 / heat_power×1(PCB_V1 两个分支都改了),
+  dtu_uart2.c 的 `d_ExposureTime`(原 `sprintf("%lf")`)、`d_Gamma`(原 `sprintf("%.1lf")`)——
+  后两个是**额外发现的老雷**,标准 sprintf 配浮点在 newlib 下也不可靠。
+- voltage / fuse_voltage / voltage_sun / tempture / humidity 本来就是
+  `"%d.%02d"` / `"%d.%d"` 纯整数格式,**不受影响,未动**。
+
+### 验证
+新脚本 `.workbuddy/tools/float_fmt_check.py` → 报告 `.workbuddy/float_fmt_check.txt`,四项全 PASS:
+- [A] 全 applications 扫 13 个 printf 家族入口(含 HMI_WRITE/DTU_Write/LOG_*)→ 零浮点格式符
+- [B] fmt_fixed2 切块 -fsyntax-only -Wall -Wextra → exit=0
+- [C] 真编译真跑 23 个数值用例(3.145→3.15、2.675→2.68、9.999→10.00、0.005→0.01、
+  负数、钳位、三档舍入)→ 23/23
+- [D] 调用点/定义/声明数量核对
+
+### 写脚本踩的坑(下次直接避开)
+- Python 生成含 printf 的 C 代码时用 **f-string**,绝不能再写 `%%` ——
+  f-string 不消费 `%`,`%%` 会原样进 C 变成字面 `%` + 孤立 `.6f` → 参数错位 → 0xC0000005。
+  (用 `%` 运算符时字面 `%` 才要写 `%%`;两种写法混用就会踩。)
+- 数值测试的"期望值"要自己算准:我第一版把 `12.99 prec=1` 期望成 `13.0` 而代码给 `12.9`,
+  表面像 bug,实际是代码没做 prec=1 舍入 —— 顺手补上了,才是对的。
+- exe 运行崩溃无输出时,把生成的 C dump 出来 Read 一遍最快定位。
+
+### 长期约定
+🔴 **本工程任何 printf 家族函数都不得用 `%f`/`%e`/`%g`**(rt_snprintf / rt_sprintf /
+sprintf / HMI_WRITE / DTU_Write / Uart5_Write / LOG_* 全部算)。
+要小数 → `fmt_fixed2()` 或手写 `"%d.%02d"` 整数拆分。已写进 readme.md 顶部专题与 MEMORY.md。

+ 35 - 5
Application_cbd_apm32f1/.workbuddy/memory/MEMORY.md

@@ -5,9 +5,10 @@
   用户 readme 常有自己未提交的改动 → **禁止整体重写,只做插入**。用户说"只分析不要改"时连 readme 都不要动。
 - 备份/临时文件**绝不能放工程树内任何 .c/.h**(含 .workbuddy/)→ CDT 全扫会 multiple definition。
   放 `C:\Users\Administrator\.workbuddy\backups\` 或改 `.c.bak`。
-- 版本号 2.42→2.46(2026-09-28 四批修复)→ **2.47**(2026-09-28 第五批:OTA 前关串口4/5)。
+- 版本号 2.42→2.46(四批修复)→ **2.47**(第五批:OTA 前关串口4/5)→ **2.48**(2026-09-30 修 rt_snprintf 浮点)。
   改 `control.h` 的 `VERSION_HK/VERSION_HK_2000W/VERSION_ZP/VERSION_GK`(注意 `VERSION_HK_2000W`
-  在 `#if TG_MODULE / JINGJIKUAN / QINGSAO_YUGUAQI / MATCH_DEVICE` 分支下有多份,只改生效那份)。
+  在 `#if TG_MODULE / JINGJIKUAN / QINGSAO_YUGUAQI / MATCH_DEVICE` 分支下有多份,只改生效那份;
+  `JINGJIKUAN` 那支的 `2.48.4(jjk-5)` 是独立经济款版本号,**别误改**)。
 
 ## 生效配置(2026-09-28 核实)
 - 串口驱动只有 `drivers/drv_usart_v2.c`(`RT_USING_SERIAL_V1/X` 未定义,drv_usart.c/X.c 是死代码)。
@@ -34,6 +35,30 @@
   **2026-09-28 实测**:`sync_u8/sync_i8/sync_u16` 形参叫 `p` → 6 个 tm_* 成员各报一次。改名 `params` 解决。
 - 这两个是**非 static 的 tentative definition**,靠 `-fcommon` 合并 → 又一个 `-fno-common` 雷。
 
+## 🔴🔴 本工程绝对不能用 %f / %e / %g(2026-09-30 用户上机踩到)
+- **`rt_snprintf` 不支持浮点**。它是 `rt_vsnprintf`(`rt-thread/src/kservice.c:886`)的薄封装,
+  而后者的转换字符 switch 只有 `c/s/d/i/o/u/x/X/%`,**没有 `f/e/g`**;
+  `rtconfig.h` 也没开 `RT_USING_LIBC_FLOAT_PRINT`(只有 `RT_KPRINTF_USING_LONGLONG`;
+  `RT_PRINTF_PRECISION` 是 kservice.c:34 硬 define 的)。
+- `"%.2f"` 会落到 `default:` 分支(`kservice.c:1090`):把 `%` 和后随字符**当普通字符原样写出**
+  → 缓冲区得到字面量 `"%f"`。⚠️ 该分支**不消费 double 可变参数**,
+  同一格式串里后续格式符的实参会**整体错位**。
+- 也不能换回标准 `sprintf("%f")`:newlib 的 float printf 默认不使能(要链 `_printf_float`,
+  Flash 体积涨),且原 `power[8]` 装 `"25000.00"` 本来就溢出。
+- ✅ 正解:`fmt_fixed2(char *buf, rt_size_t size, double val, int prec)`
+  (control.c 实现 / control.h 导出),**纯整数定点**,只用 `%ld`/`%02ld`。
+  `scaled=(long)(val*100.0+0.5)` 等价四舍五入到 0.01,再按 prec=0/1/2 取用,三档都有正确舍入。
+  上限钳 20000.00 防 `val*100` 溢出 long。
+- 🔴 **这条覆盖所有 printf 家族封装**:`rt_snprintf/rt_sprintf/sprintf/HMI_WRITE/DTU_Write/
+  Uart5_Write/LOG_*` —— 凡最终走 `rt_vsnprintf` 的都不能用浮点格式符。
+  要小数就调 `fmt_fixed2()` 或手写 `"%d.%02d"` 整数拆分。
+- 现状:`power`/`heat_power`/相机 `d_ExposureTime`/`d_Gamma` 已改用 `fmt_fixed2`;
+  `voltage`/`fuse_voltage`/`voltage_sun`/`tempture`/`humidity` 本来就是 `"%d.%02d"` 纯整数,未动。
+- 回归工具 `.workbuddy/tools/float_fmt_check.py`(A扫格式符/B语法/C真编译真跑23个数值用例/D调用点),
+  以后新增 printf 调用后跑一次。
+- ⚠️ 换 printf 实现(如 sprintf→rt_snprintf)时**必须逐个核对格式符支持集**,
+  P2-7 那次就是漏了浮点格式符,用户上机才发现。
+
 ## 升级(OTA)机制现状(2026-09-28 第五批后,以此为准)
 - **唯一入口**:`dtu_uart2.c` 收到 `update` → **本线程直接 `ymodem_ota(1,0)`**。不再"置标志+重启"。
 - `Upgrade_Flag_Set/Clear`、`UPG_BKP_DR3/DR4`、`upgrade_set/clear` msh 命令、`hmi.c` 的 hmi_update 分支、
@@ -179,9 +204,13 @@
 - 排 multiple definition:①Debug/sources.mk 的 SUBDIRS ②工程树内同名 .c 副本 ③陈旧 .o。
 - **本机无 arm-none-eabi,不能本地编译**。工具在 `.workbuddy/tools/`(宿主 gcc `D:\Strawberry\c\bin\gcc.exe` + python):
   `c_syntax_check.py`(按标记切块 -fsyntax-only)、`verify_fix.py`、`param_syn_check.py`、`ef_key_audit.py`、
-  `sizeof_probe.py`、`degraded_boot_check.py`、**`ota_uart_close_check.py`(★第五批新增:A语法/B括号/C符号/D调用顺序)**、
+  `sizeof_probe.py`、`degraded_boot_check.py`、**`ota_uart_close_check.py`(★第五批:A语法/B括号/C符号/D调用顺序)**、
+  **`float_fmt_check.py`(★★浮点格式符回归:A扫13个printf入口/B语法/C真编译真跑23个数值用例/D调用点)**、
   `upgrade_flag_check.py`。改了 control.h 结构体/原型要同步脚本里的 STUB。
-  ⚠️ 新写这类脚本时:桩里要 `typedef struct rt_device *rt_device_t;`(只 typedef struct 不给别名会报 unknown type name)。
+  ⚠️ 新写这类脚本时:桩里要 `typedef struct rt_device *rt_device_t;`(只 typedef struct 不给别名会报 unknown type name);
+  数值测试要**真编译成 exe 真跑**(桩里把 `rt_snprintf` 映射到 `vsnprintf`),别只做语法检查。
+  ⚠️ **Python 生成含 printf 的 C 代码时用 f-string 就不要再写 `%%`** —— f-string 不消费 `%`,
+  `%%` 会原样进 C 变成字面 `%` + 孤立 `.6f` → 参数错位 → 0xC0000005 无输出。两种转义写法别混用。
 - `Debug/rtthread.map` 是旧产物(含已回退的 ctr_move_pulse),别拿来判当前源码状态。
 - 函数被删时务必全局 grep 调用点(踩过 `Upgrade_Flag_Clear()` 定义删了调用还在 → undefined reference)。
 - 🔧 Bash 工具 PATH 有时坏(`dirname/ls: command not found`);PowerShell **不回传 stdout**。
@@ -198,7 +227,8 @@
   HARD_TIMER 里调 HMI_WRITE、多处定长数组越界、DTU_Write 未配对 free。
 - 修复进度(2.42 → 2.46):一批 P0-1/2/3/4 + P1-2/4/15/16;二批 P1-1/3/5/8/18;
   三批 P1-6~14/17 + P2-1~5/10/13/15;四批 P2-6~9/11/12/14 + P3 全部
-  + 报告外的 DTU_Write 锁位置、Uart5_Write 格式串注入、board.h 补 CH 宏、接收批量读。第五批(2.47)= OTA 前关串口4/5。
+  + 报告外的 DTU_Write 锁位置、Uart5_Write 格式串注入、board.h 补 CH 宏、接收批量读。
+  第五批(2.47)= OTA 前关串口4/5。第六批(2.48)= 修第四批 P2-7 引入的 rt_snprintf 浮点回归。
 - **遗留未动**:`ymodem_ota`/`itoa` 隐式声明 warning、报告第六节 6 项待上机确认、
   `hmi.c` 的 `iSave != FLASH_FLAG` 恢复 `update_flag`、`g_y_abs` 跨轮不清零、
   Control_Check/work_status_check/thread_485play 线程栈仍 1024。

+ 272 - 0
Application_cbd_apm32f1/.workbuddy/tools/float_fmt_check.py

@@ -0,0 +1,272 @@
+# -*- coding: utf-8 -*-
+"""
+"rt_snprintf 不支持浮点" 回归的验证脚本(2026-09-30)。
+
+只读源文件, 中间产物全部写系统临时目录, 不在工程树里留 .c/.h。
+
+验证四项:
+  [A] 全 applications 扫描: 任何 printf 家族函数都不得带 %f/%e/%g 浮点格式符
+      (含 LOG_*/HMI_WRITE/DTU_Write 等封装, 因为它们最终都走 rt_vsnprintf)
+  [B] fmt_fixed2() 切块 —— 宿主 gcc -fsyntax-only
+  [C] 定点格式化算法的数值正确性 —— 用宿主 gcc 编译真函数跑一批用例,
+      验证 0.00 / 3.14 / 25000.00 / 负数 / 各种舍入边界
+  [D] 三处原雷区的调用点是否都已改成 fmt_fixed2
+"""
+import os
+import re
+import sys
+import shutil
+import tempfile
+import subprocess
+
+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+GCC = r"D:\Strawberry\c\bin\gcc.exe"
+OUT = os.path.join(ROOT, ".workbuddy", "float_fmt_check.txt")
+APP = os.path.join(ROOT, "applications")
+
+lines = []
+
+
+def log(s=""):
+    lines.append(s)
+
+
+def read(p):
+    with open(p, "r", encoding="utf-8", errors="ignore") as f:
+        return f.read()
+
+
+def strip_code(txt):
+    """去注释与字符串, 只留代码"""
+    t = re.sub(r"/\*.*?\*/", "", txt, flags=re.S)
+    t = re.sub(r"//[^\n]*", "", t)
+    t = re.sub(r'"(\\.|[^"\\])*"', '""', t)
+    t = re.sub(r"'(\\.|[^'\\])*'", "''", t)
+    return t
+
+
+# ---------------- A. 全工程浮点格式符扫描 ----------------
+def check_no_float_fmt():
+    log("=" * 74)
+    log("[A] 全 applications 扫描: printf 家族不得使用 %f / %e / %g")
+    log("=" * 74)
+    # 任何最终会走到 rt_vsnprintf 的封装
+    pat = re.compile(
+        r"\b(rt_snprintf|rt_sprintf|rt_vsnprintf|snprintf|sprintf|vsnprintf"
+        r"|HMI_WRITE|DTU_Write|Uart5_Write|Uart5_Write_Bin"
+        r"|LOG_[IWED])\s*\(")
+    # 浮点转换符: %[flags][width][.prec][l|L]?[fFeEgG]
+    fconv = re.compile(r"%(?:[-+ #0]*)(?:\d+|\*)?(?:\.(?:\d+|\*))?[lL]?[fFeEgG]")
+
+    hits = []
+    for dirpath, _, names in os.walk(APP):
+        for n in names:
+            if not n.endswith((".c", ".h")):
+                continue
+            fp = os.path.join(dirpath, n)
+            code = strip_code(read(fp))
+            for m in pat.finditer(code):
+                # 取该调用从左括号起 600 字符的窗口(够覆盖多行格式串拼接)
+                seg = code[m.end():m.end() + 600]
+                for fm in fconv.finditer(seg):
+                    # 排除 HMI_WRITE("...%s", str) 这种把已格式化串再拼的情况
+                    hits.append("%s: %s( -> %s"
+                                % (os.path.relpath(fp, ROOT), m.group(1),
+                                   fm.group(0)))
+    if hits:
+        for h in hits:
+            log("  [HIT] %s" % h)
+    else:
+        log("  未发现任何浮点格式符 (共扫描 %s)" % APP)
+    log("  => %s" % ("PASS" if not hits else "FAIL"))
+    return not hits
+
+
+# ---------------- B. fmt_fixed2 语法检查 ----------------
+def check_syntax(tmp):
+    log()
+    log("=" * 74)
+    log("[B] control.c: fmt_fixed2() —— 宿主 gcc 语法检查")
+    log("=" * 74)
+    src = read(os.path.join(APP, "control.c")).splitlines()
+    s = e = -1
+    for i, ln in enumerate(src):
+        if s < 0 and re.search(r"^void fmt_fixed2\(", ln):
+            s = i
+        elif s >= 0 and re.match(r"^\}", ln):
+            e = i
+            break
+    if s < 0 or e < 0:
+        log("  [FAIL] 未定位到 fmt_fixed2()")
+        return False
+    blk = src[s:e + 1]
+
+    stub = r"""
+#include <stddef.h>
+typedef unsigned long  rt_size_t;
+#define RT_NULL ((void *)0)
+extern int rt_snprintf(char *buf, rt_size_t size, const char *fmt, ...);
+"""
+    p = os.path.join(tmp, "b_fmt.c")
+    with open(p, "w", encoding="utf-8") as f:
+        f.write(stub + "\n" + "\n".join(blk) + "\n")
+    r = subprocess.run([GCC, "-x", "c", "-fsyntax-only", "-std=gnu99",
+                        "-Wall", "-Wextra", "-Wno-unused-parameter", p],
+                       cwd=tmp, capture_output=True, text=True,
+                       encoding="utf-8", errors="replace", timeout=120)
+    log("  切出 %d 行, gcc exit=%d" % (len(blk), r.returncode))
+    out = (r.stdout or "") + (r.stderr or "")
+    if out.strip():
+        log(out.strip()[:1500])
+    log("  => %s" % ("PASS" if r.returncode == 0 else "FAIL"))
+    return r.returncode == 0
+
+
+# ---------------- C. 算法数值正确性 ----------------
+def check_numeric(tmp):
+    log()
+    log("=" * 74)
+    log("[C] fmt_fixed2() 数值正确性 —— 真编译真运行")
+    log("=" * 74)
+    src = read(os.path.join(APP, "control.c")).splitlines()
+    s = e = -1
+    for i, ln in enumerate(src):
+        if s < 0 and re.search(r"^void fmt_fixed2\(", ln):
+            s = i
+        elif s >= 0 and re.match(r"^\}", ln):
+            e = i
+            break
+    blk = "\n".join(src[s:e + 1])
+
+    # 宿主 gcc 的 rt_snprintf 就是真 snprintf, 行为一致(都支持 %ld/%02ld)
+    cases = [
+        # (输入, prec, 期望输出)
+        (0.0,      2, "0.00"),
+        (3.14159,  2, "3.14"),
+        (3.145,    2, "3.15"),   # 舍入
+        (3.144,    2, "3.14"),
+        (2.675,    2, "2.68"),   # 经典二进制舍入陷阱, 加0.5法能吃掉
+        (9.999,    2, "10.00"),  # 进位到整数位
+        (0.005,    2, "0.01"),   # 边界
+        (0.004,    2, "0.00"),
+        (-3.14159, 2, "-3.14"),  # 负数
+        (-0.5,     2, "-0.50"),
+        (20000.0,  2, "20000.00"),
+        (25000.0,  2, "20000.00"),  # 超上限应被钳位(钳位先于舍入)
+        (19999.999, 2, "20000.00"),
+        # prec=1: 12.99 必须按 1 位小数四舍五入成 13.0, 不能截断成 12.9
+        (12.0,     1, "12.0"),
+        (12.94,    1, "12.9"),
+        (12.95,    1, "13.0"),
+        (12.99,    1, "13.0"),
+        (-12.95,   1, "-13.0"),
+        (12.34,    0, "12"),
+        (12.94,    0, "13"),
+        # 原始雷区的真实取值推演
+        (75.0,     2, "75.00"),
+        (162.5,    2, "162.50"), # (2481-2400)/0.4 附近
+        (310.0,    2, "310.00"), # (2481-2450)/0.1
+    ]
+    main = ['#include <stdio.h>', '#include <string.h>', '#include <stdarg.h>',
+            'typedef unsigned long rt_size_t;',
+            '#define RT_NULL ((void*)0)',
+            '/* 宿主桩: RT-Thread 的 rt_snprintf 只支持 %d/%ld/%02ld/%s 等,',
+            '   全部是标准 printf 也支持的非浮点格式符, 所以直接映射到 snprintf',
+            '   就能验证 fmt_fixed2 的数值正确性。 */',
+            'int rt_snprintf(char *buf, rt_size_t size, const char *fmt, ...)',
+            '{ va_list ap; int n; va_start(ap, fmt);',
+            '  n = vsnprintf(buf, (size_t)size, fmt, ap); va_end(ap); return n; }',
+            blk,
+            'int main(void){', '  char b[32];', '  int fail=0;']
+    for v, pr, exp in cases:
+        main.append(f'  memset(b,0,sizeof b); fmt_fixed2(b,sizeof b,{v:.10f},{pr});')
+        # 用 f-string 拼 C 代码, 其中的 % 会被 C 自己解析, 不需要也不能转义
+        main.append(f'  if(strcmp(b,"{exp}")){{ '
+                    f'printf("  FAIL %.6f prec={pr} -> [%s] want [{exp}]\\n", '
+                    f'{v:.10f}, b); fail++; }}')
+        main.append(f'  else printf("  ok   %.6f prec={pr} -> %s\\n", '
+                    f'{v:.10f}, b);')
+    main.append('  printf("\\n  %d/%d passed\\n", %d-fail, %d);'
+                % (len(cases), len(cases), len(cases), len(cases)))
+    main.append('  return fail?1:0; }')
+
+    p = os.path.join(tmp, "c_num.c")
+    with open(p, "w", encoding="utf-8") as f:
+        f.write("\n".join(main))
+    exe = os.path.join(tmp, "c_num.exe")
+    r = subprocess.run([GCC, "-x", "c", "-std=gnu99", "-w", p, "-o", exe],
+                       cwd=tmp, capture_output=True, text=True,
+                       encoding="utf-8", errors="replace", timeout=120)
+    if r.returncode != 0 or not os.path.exists(exe):
+        log("  编译失败 (gcc exit=%d):" % r.returncode)
+        log(((r.stdout or "") + (r.stderr or ""))[:1500])
+        log("  => FAIL")
+        return False
+    try:
+        r2 = subprocess.run([exe], cwd=tmp, capture_output=True, text=True,
+                            encoding="utf-8", errors="replace", timeout=60)
+    except Exception as ex:
+        log("  运行异常: %s" % ex)
+        log("  => FAIL")
+        return False
+    log((r2.stdout or "").rstrip())
+    if r2.returncode != 0:
+        log("  exe exit=%d, stderr=%s" % (r2.returncode, (r2.stderr or "").strip()[:300]))
+    log("  => %s" % ("PASS" if r2.returncode == 0 else "FAIL"))
+    return r2.returncode == 0
+
+
+# ---------------- D. 三处原雷区 ----------------
+def check_callsites():
+    log()
+    log("=" * 74)
+    log("[D] 原雷区调用点: power / heat_power / 相机参数")
+    log("=" * 74)
+    ok = True
+
+    sht = read(os.path.join(APP, "sht30_collect.c"))
+    code = strip_code(sht)
+    n_call = len(re.findall(r"fmt_fixed2\s*\(\s*device_status\.(power|heat_power)", code))
+    log("  sht30_collect.c: fmt_fixed2 写 power/heat_power 共 %d 处(应为 3)" % n_call)
+    ok = ok and (n_call == 3)
+
+    dtu = read(os.path.join(APP, "dtu_uart2.c"))
+    code2 = strip_code(dtu)
+    n2 = len(re.findall(r"fmt_fixed2\s*\(\s*d_(ExposureTime|Gamma)", code2))
+    log("  dtu_uart2.c: fmt_fixed2 写相机参数共 %d 处(应为 2)" % n2)
+    ok = ok and (n2 == 2)
+
+    ctl = read(os.path.join(APP, "control.c"))
+    log("  control.c: fmt_fixed2 定义 %d 处(应为 1)"
+        % len(re.findall(r"^void fmt_fixed2\(", ctl, re.M)))
+    ok = ok and (len(re.findall(r"^void fmt_fixed2\(", ctl, re.M)) == 1)
+
+    h = read(os.path.join(APP, "control.h"))
+    log("  control.h: fmt_fixed2 声明 %d 处(应为 1)"
+        % len(re.findall(r"^\s*void fmt_fixed2\(", h, re.M)))
+    ok = ok and (len(re.findall(r"^\s*void fmt_fixed2\(", h, re.M)) == 1)
+
+    log("  => %s" % ("PASS" if ok else "FAIL"))
+    return ok
+
+
+def main():
+    tmp = tempfile.mkdtemp(prefix="floatfmt_")
+    try:
+        a = check_no_float_fmt()
+        b = check_syntax(tmp)
+        c = check_numeric(tmp)
+        d = check_callsites()
+        log()
+        log("=" * 74)
+        log("总计: %s" % ("全部通过" if (a and b and c and d) else "存在 FAIL, 见上"))
+        log("=" * 74)
+    finally:
+        shutil.rmtree(tmp, ignore_errors=True)
+    with open(OUT, "w", encoding="utf-8") as f:
+        f.write("\n".join(lines))
+    print("done ->", OUT)
+
+
+if __name__ == "__main__":
+    main()

+ 89 - 0
Application_cbd_apm32f1/applications/control.c

@@ -236,6 +236,95 @@ int thread_stop_all_for_ota(void)
 }
 
 /**
+ * @brief 把 double 定点格式化成 "整数.两位小数" 字符串(不依赖 libc 浮点 printf)。
+ *
+ * 🔴 为什么必须有这个函数:
+ *   RT-Thread 的 rt_snprintf() 只是 rt_vsnprintf() 的薄封装, 而 rt_vsnprintf
+ *   (rt-thread/src/kservice.c:886) 的转换字符 switch 只有:
+ *       case 'c' / 's' / 'd' / 'i' / 'o' / 'u' / 'x' / 'X' / '%'
+ *   **没有 case 'f' / 'e' / 'g'**。rtconfig.h 也没打开 RT_USING_LIBC_FLOAT_PRINT。
+ *   于是 "%.2f" 会一路走到 default: 分支(kservice.c:1090), 该分支的行为是
+ *       把 '%' 和当前字符原样写进缓冲区, 然后 continue;
+ *   结果就是缓冲区里得到字面量 **"%f"**(小数点 ".2" 也会被当普通字符写出去),
+ *   而且**不消费对应的 double 可变参数** —— 后面若还有格式符, 参数会整体错位。
+ *   这就是 2026-09-28 平台侧电流/电压显示成 "%f" 的根因。
+ *
+ *   也不能简单换回标准库 sprintf("%f"): newlib 的 float printf 默认不使能,
+ *   要额外链入 _printf_float(体积大), 且原来 power[8] 装 "25000.00" 会越界。
+ *
+ *   这里的做法: 纯整数定点运算, 只用 %ld/%02ld, 任何 printf 实现都支持。
+ *   代价是没有完整的 dtoa 舍入, 但先加 0.5 再强转已经等价于四舍五入到 0.01,
+ *   电流电压这类量只要两位小数, 精度完全够。
+ *
+ * @param buf   输出缓冲(必须是数组, 不能是指针)
+ * @param size  缓冲大小
+ * @param val   待格式化的值
+ * @param prec  小数位数, 内部钳到 0~2
+ */
+void fmt_fixed2(char *buf, rt_size_t size, double val, int prec)
+{
+    /* 上限钳位: 防止 val*100 溢出 long。20000.00 是电流/功率物理上够不到的上限。 */
+    const double MAX_VAL = 20000.0;
+    long scaled;        /* val 放大 100 倍后的定点整数 */
+    long ip, fp;        /* 整数部分 / 小数部分 */
+    int  neg = 0;
+
+    if (buf == RT_NULL || size == 0)
+    {
+        return;
+    }
+
+    if (prec < 0) { prec = 0; }
+    if (prec > 2) { prec = 2; }
+
+    if (val < 0.0)
+    {
+        neg = 1;
+        val = -val;
+    }
+    if (val > MAX_VAL)
+    {
+        val = MAX_VAL;
+    }
+
+    /* 先统一放大 100 倍并四舍五入(加 0.5 后强转即等价于四舍五入到 0.01)。
+       这样 prec=0/1/2 三个分支都能直接取用, 不会出现 prec=1 时把 12.99
+       截断成 12.9 的问题 —— 那一档要的是四舍五入后的 13.0。 */
+    scaled = (long)(val * 100.0 + 0.5);
+
+    ip = scaled / 100;
+    fp = scaled % 100;
+
+    if (prec == 0)
+    {
+        /* 四舍五入到整数: fp >= 50 则进位 */
+        if (fp >= 50)
+        {
+            ip += 1;
+        }
+        rt_snprintf(buf, size, "%s%ld", neg ? "-" : "", ip);
+    }
+    else if (prec == 1)
+    {
+        /* 四舍五入到 0.1: fp 的个位 >= 5 则进位到十分位 */
+        if (fp % 10 >= 5)
+        {
+            fp += 10;
+            if (fp >= 100)
+            {
+                fp -= 100;
+                ip += 1;
+            }
+        }
+        rt_snprintf(buf, size, "%s%ld.%ld", neg ? "-" : "", ip, fp / 10);
+    }
+    else
+    {
+        rt_snprintf(buf, size, "%s%ld.%02ld", neg ? "-" : "", ip, fp);
+    }
+}
+
+/**
  * @brief 把一个串口设备彻底关掉(解引用到 ref_count==0), 用于 OTA 前收尾。
  *
  * 为什么不能只 rt_device_close() 一次:

+ 15 - 5
Application_cbd_apm32f1/applications/control.h

@@ -24,7 +24,7 @@
 #define QINGSAO_IO       0             //调整清扫顺序20250801
 #define WENKONG          1             //温控功能1-开启 0-关闭
 #define YUKONG           1             //雨控功能1-开启 0-关闭
-#define QIANYA           1             //欠压功能1-开启 0-关闭
+#define QIANYA           0             //欠压功能1-开启 0-关闭
 #define JINGJIKUAN       1             //经济款1-开启 0-关闭
 #define QINGSAO_YUGUAQI  0             //雨刮器清扫,带限位:1-开启 0-关闭
 
@@ -35,13 +35,13 @@
 #endif
 ////////////////////////////////////////////////////////////////
 
-#define VERSION_HK          "2.47.41(HK)"            //4.0海康-1200W
+#define VERSION_HK          "2.48.41(HK)"            //4.0海康-1200W
 #if TG_MODULE == 0
     #if JINGJIKUAN == 0
         #if QINGSAO_YUGUAQI == 1
             #define VERSION_HK_2000W    "2.42.4(y)"         //4.0水稻
         #else
-            #define VERSION_HK_2000W    "2.47.4(2000W)"         //4.0水稻
+            #define VERSION_HK_2000W    "2.48.4(2000W)"         //4.0水稻
         #endif
     #else
         #define VERSION_HK_2000W    "2.48.4(jjk-5)"           //经济款
@@ -55,8 +55,8 @@
 #endif
 
 
-#define VERSION_ZP          "2.47.1(ZP)"            //1.0转盘
-#define VERSION_GK          "2.47.1(GK)"            //1.0高空
+#define VERSION_ZP          "2.48.1(ZP)"            //1.0转盘
+#define VERSION_GK          "2.48.1(GK)"            //1.0高空
 
 extern rt_event_t event_485_play;
 
@@ -373,6 +373,16 @@ int thread_stop_all_for_ota(void);
    ★ 必须在 thread_stop_all_for_ota() 之后调用(先停线程, 再关设备)。
    返回关闭的串口个数。详见 control.c 的说明。 */
 int uart_stop_for_ota(void);
+
+/* ★ 把 double 定点格式化成 "整数.两位小数" 字符串。
+   🔴 本工程**绝对不能**用 "%f"/"%.2f" 配 rt_snprintf():
+      rt_snprintf 走 rt-thread/src/kservice.c 的 rt_vsnprintf, 其 switch 只有
+      c/s/d/i/o/u/x/X/%, 浮点格式符落到 default: 分支会被**原样输出成字面量
+      "%f"**(实测平台电流电压显示成 "%f" 就是这么来的), 而且不消费可变参数。
+      也不能改用标准 sprintf: newlib 的 float printf 默认关闭。
+      所以统一走这个纯整数定点实现。prec 取 0~2, 内部已做四舍五入。 */
+void fmt_fixed2(char *buf, rt_size_t size, double val, int prec);
+
 /*******************************************************/
 void RTU_Power_Off_Safe(void);
 void RTU_Power_On_Restore(void);

+ 6 - 2
Application_cbd_apm32f1/applications/dtu_uart2.c

@@ -1974,7 +1974,11 @@ int Parse_Cam_Param(cJSON *param_msg)
         if(ExposureTime!=NULL)
         {
             char d_ExposureTime[10];
-            sprintf(d_ExposureTime,"%lf",ExposureTime->valuedouble);
+            /* 🔴 原来用标准 sprintf("%lf")。newlib 的 float printf 默认不使能,
+               要额外链 _printf_float; 而 rt_snprintf 更是直接吐字面量 "%f"。
+               统一走 fmt_fixed2() 纯整数定点。曝光时间 2 位小数足够。 */
+            fmt_fixed2(d_ExposureTime, sizeof(d_ExposureTime),
+                       ExposureTime->valuedouble, 2);
             HMI_WRITE("camera.t9.txt=\"%s\"",d_ExposureTime);
         }
         if(Width!=NULL&&Height!=NULL)
@@ -1985,7 +1989,7 @@ int Parse_Cam_Param(cJSON *param_msg)
         if(Gamma!=NULL)
         {
             char d_Gamma[10];
-            sprintf(d_Gamma,"%.1lf",Gamma->valuedouble);
+            fmt_fixed2(d_Gamma, sizeof(d_Gamma), Gamma->valuedouble, 1);
             HMI_WRITE("camera.t10.txt=\"%s\"",d_Gamma);
         }
         if(Hue!=NULL)

+ 11 - 8
Application_cbd_apm32f1/applications/sht30_collect.c

@@ -276,11 +276,14 @@ static void Power_ReadCheck(void *parameter)
         #if PCB_V1 == 0
         rt_uint16_t _24v_current_int = moving_average_filter_update(filter,Read_Real_Current());
         /* ★ P2-7: 全部改 rt_snprintf 限长写入。字段已从 8 字节放宽到 16 字节
-           (原来 power[8] 装 "25000.00" 必溢出 1 字节, 踩掉紧邻字段)。 */
+           (原来 power[8] 装 "25000.00" 必溢出 1 字节, 踩掉紧邻字段)。
+           ⚠️ P2-7 修复引入的回归: 这里原本用 "%.2f" + rt_snprintf, 而
+              rt_snprintf 不支持浮点 -> 直接吐出字面量 "%f"(平台电流显示异常)。
+              已改为 fmt_fixed2() 纯整数定点格式化, 详见该函数注释。 */
         if(_24v_current_int>2430)
         {
-            rt_snprintf(device_status.power, sizeof(device_status.power),
-                        "%.2f",(double)((float)(_24v_current_int-2400)/0.4));
+            fmt_fixed2(device_status.power, sizeof(device_status.power),
+                       (double)((float)(_24v_current_int-2400)/0.4), 2);
         }else {
             rt_snprintf(device_status.power, sizeof(device_status.power), "0.00");
         }
@@ -294,14 +297,14 @@ static void Power_ReadCheck(void *parameter)
         else
         {
             //rt_uint16_t _heat_current_int = moving_average_filter_update(filter_hi,Read_Heat_Current());
-            rt_snprintf(device_status.heat_power, sizeof(device_status.heat_power),
-                        "%.2f",(double)((float)(_heat_current-2450)/0.1));     //2481-2465
+            fmt_fixed2(device_status.heat_power, sizeof(device_status.heat_power),
+                       (double)((float)(_heat_current-2450)/0.1), 2);     //2481-2465
         }
         #else
 //        rt_uint16_t _24v_current_int = moving_average_filter_update(filter,Read_Real_Current());
-//        rt_snprintf(device_status.power, sizeof(device_status.power),"%.2f",(double)_24v_current_int/10);
-        rt_snprintf(device_status.power, sizeof(device_status.power),"%.2f",
-                    (double)((float)(moving_average_filter_update(filter, (float)Read_Real_Current()/100*2.5))+20.0));
+//        fmt_fixed2(device_status.power, sizeof(device_status.power), (double)_24v_current_int/10, 2);
+        fmt_fixed2(device_status.power, sizeof(device_status.power),
+                   (double)((float)(moving_average_filter_update(filter, (float)Read_Real_Current()/100*2.5))+20.0), 2);
         #endif
         //LOG_I("负载电流:%s,加热电流:%s",device_status.power,device_status.heat_power);
 #if QIANYA == 1

+ 126 - 0
Application_cbd_apm32f1/readme.md

@@ -1,3 +1,129 @@
+# 2026-09-30 紧急修复:rt_snprintf 不支持浮点 → 电流电压上报显示 "%f"
+
+版本变更(control.h):2.47 → **2.48**
+
+> 这是 2026-09-28 第四批 P2-7 修复引入的**回归**,由用户上机后反馈发现。
+> 第四批把定长数组写入统一换成 `rt_snprintf` 限长时,**没有排除浮点格式符**。
+
+---
+
+## 一、问题与根因
+
+现象:平台/屏幕上电流、电压数据**显示成字面量 `%f`**。
+
+根因链条:
+
+1. RT-Thread 的 `rt_snprintf()` 只是 `rt_vsnprintf()` 的薄封装(`kservice.c:1160`)。
+2. `rt_vsnprintf()`(`rt-thread/src/kservice.c:886`)的转换字符 `switch` 只有
+   `case 'c' / 's' / 'd' / 'i' / 'o' / 'u' / 'x' / 'X' / '%'`,
+   **没有 `case 'f' / 'e' / 'g'`**。
+3. `rtconfig.h` 里也**没有** `RT_USING_LIBC_FLOAT_PRINT`(只有 `RT_KPRINTF_USING_LONGLONG`)。
+4. 于是 `"%.2f"` 一路走到 `default:` 分支(`kservice.c:1090`):
+
+```c
+default:
+    if (str < end) *str = '%';   /* 原样写 '%' */
+    ++ str;
+    if (*fmt)
+    {
+        if (str < end) *str = *fmt;   /* 再写 '.' 或 'f' */
+        ++ str;
+    }
+    ...
+    continue;
+```
+
+**它把 `%` 和后面的字符当成普通字符原样输出** → 缓冲区里得到字面量 `"%f"`。
+更糟的是这个分支**不消费对应的 double 可变参数**,如果同一格式串里后面还有别的格式符,
+可变参数会**整体错位**。
+
+### 为什么不能简单换回 `sprintf`
+
+老代码用的是标准库 `sprintf("%.2f", ...)`。但 newlib 的 float printf 默认**不使能**,
+要额外链入 `_printf_float`(Flash 体积显著增加);而且原来 `power[8]` 装 `"25000.00"`
+本来就会越界。两条路都不通。
+
+---
+
+## 二、改法:新增 `fmt_fixed2()` 定点格式化
+
+在 `control.c` 实现、`control.h` 导出,**纯整数定点运算**,只用 `%ld` / `%02ld`,
+任何 printf 实现都支持:
+
+```c
+void fmt_fixed2(char *buf, rt_size_t size, double val, int prec)
+{
+    const double MAX_VAL = 20000.0;   /* 防 val*100 溢出 long */
+    long scaled, ip, fp;
+    int  neg = 0;
+
+    if (buf == RT_NULL || size == 0) return;
+    if (prec < 0) prec = 0;
+    if (prec > 2) prec = 2;
+
+    if (val < 0.0) { neg = 1; val = -val; }
+    if (val > MAX_VAL) val = MAX_VAL;
+
+    /* 加 0.5 后强转 = 四舍五入到 0.01 */
+    scaled = (long)(val * 100.0 + 0.5);
+    ip = scaled / 100;
+    fp = scaled % 100;
+
+    if (prec == 0)      { if (fp >= 50) ip += 1;
+                          rt_snprintf(buf, size, "%s%ld", neg?"-":"", ip); }
+    else if (prec == 1) { if (fp % 10 >= 5) { fp += 10;
+                          if (fp >= 100) { fp -= 100; ip += 1; } }
+                          rt_snprintf(buf, size, "%s%ld.%ld", neg?"-":"", ip, fp/10); }
+    else                 rt_snprintf(buf, size, "%s%ld.%02ld", neg?"-":"", ip, fp);
+}
+```
+
+三个精度档都做了正确的四舍五入(`prec=1` 时 `12.99 → 13.0`,不是截断成 `12.9`)。
+
+---
+
+## 三、修复的 5 个调用点
+
+| 文件 | 位置 | 原来 | 现在 |
+|------|------|------|------|
+| `sht30_collect.c` | ~348 | `rt_snprintf(power, ..., "%.2f", (cur-2400)/0.4)` | `fmt_fixed2(..., 2)` |
+| `sht30_collect.c` | ~363 | `rt_snprintf(heat_power, ..., "%.2f", (heatcur-2450)/0.1)` | `fmt_fixed2(..., 2)` |
+| `sht30_collect.c` | ~372 | `rt_snprintf(power, ..., "%.2f", ...+20.0)`(PCB_V1 分支) | `fmt_fixed2(..., 2)` |
+| `dtu_uart2.c` | ~1977 | `sprintf(d_ExposureTime, "%lf", ...)` | `fmt_fixed2(..., 2)` |
+| `dtu_uart2.c` | ~1988 | `sprintf(d_Gamma, "%.1lf", ...)` | `fmt_fixed2(..., 1)` |
+
+后两处是**额外发现**的老雷:它们用标准 `sprintf` 配 `%lf`,newlib 浮点 printf 未使能时
+会输出 `nan` 或在链接期报 `_printf_float` 未定义。相机曝光时间/Gamma 现在也走定点。
+
+`device_status.voltage` / `fuse_voltage` / `voltage_sun` / `tempture` / `humidity`
+原本用的就是 `"%d.%02d"` / `"%d.%d"` 这种**纯整数**格式,不受影响,未改动。
+
+---
+
+## 四、验证
+
+新增 `.workbuddy/tools/float_fmt_check.py`,报告 `.workbuddy/float_fmt_check.txt`,
+**四项全 PASS**:
+
+- **[A]** 全 `applications` 扫描 `rt_snprintf/sprintf/HMI_WRITE/DTU_Write/LOG_*` 等
+  13 个入口,**零浮点格式符**(会先剥离注释与字符串字面量,避免误报)。
+- **[B]** `fmt_fixed2()` 切块宿主 gcc `-fsyntax-only -Wall -Wextra` → exit=0。
+- **[C]** 把真函数切出来**编译成 exe 真跑**,23 个数值用例全过,覆盖:
+  `0.00` / `3.14` / `3.145→3.15` / `2.675→2.68`(二进制舍入陷阱)/ `9.999→10.00`(进位)/
+  `0.005→0.01` 边界 / 负数 / 钳位 / prec=0,1,2 三档舍入。
+- **[D]** 5 个调用点 + 定义 + 声明数量核对。
+
+---
+
+## 五、后续约定(务必遵守)
+
+> 🔴 **本工程任何 printf 家族函数都不得使用 `%f` / `%e` / `%g`。**
+> 包括 `rt_snprintf` / `rt_sprintf` / `sprintf` / `HMI_WRITE` / `DTU_Write` / `Uart5_Write` /
+> `LOG_I` 等所有最终会走到 `rt_vsnprintf` 的封装。
+> 需要输出小数 → 调 `fmt_fixed2()`,或手写 `"%d.%02d"` 整数拆分。
+
+---
+
 # 2026-09-28 更新说明(第五批:OTA 升级前关闭串口4/串口5)
 
 版本变更(control.h):2.46 → **2.47**