增加调试功能,以及yaw补偿

This commit is contained in:
lyf committed 2026-11-18 16:05:46 +08:00
1 parent 267a659242
commit 957c535bda
257 files changed
+239436 -692

No files matched your search

+61
View File
@@ -0,0 +1,61 @@
# -*- coding: utf-8 -*-
"""检查 底盘/云台 两份 robot_param.h 中"公共参数段"是否一致。
背景:为避免 Simba-OmniInfantry 根目录出现 common 目录,两份板级
robot_param.h 各自内联了一段"公共参数"(CToC ID/掉线时间/IMU 温控/蜂鸣器等),
用标记包裹:
/* ===== 公共参数段(...由 ...check_param_common.py 校验) ===== */
...
/* ===== 公共参数段结束 ===== */
本脚本比较两段文本(忽略行尾空白),不一致时返回非 0,可用于 CI/预构建检查。
用法:
python tools\\check_param_common.py
"""
import os
import re
import sys
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # .../module_test
SIMBA = os.path.dirname(BASE) # .../Simba-OmniInfantry
FILES = [
os.path.join(SIMBA, '底盘', 'Application', 'robot_param.h'),
os.path.join(SIMBA, '云台', 'Application', 'robot_param.h'),
]
START = '公共参数段'
END = '公共参数段结束'
def extract(path):
# 文件是 GBK(µVision 习惯),按 gbk 读;失败时退回 gb18030
for enc in ('gbk', 'gb18030'):
try:
text = open(path, encoding=enc).read()
break
except UnicodeDecodeError:
continue
else:
raise SystemExit('无法读取: %s' % path)
m = re.search(re.escape(START) + r'.*?\*/(.*?)/\* ===== ' + re.escape(END), text, re.S)
if not m:
raise SystemExit('找不到公共参数段标记: %s' % path)
lines = [ln.rstrip() for ln in m.group(1).splitlines() if ln.strip()]
return lines
def main():
a = extract(FILES[0])
b = extract(FILES[1])
if a == b:
print('公共参数段一致: %d 行' % len(a))
return 0
print('公共参数段不一致!')
import difflib
for ln in difflib.unified_diff(a, b, fromfile='底盘', tofile='云台', lineterm=''):
print(ln)
return 1
if __name__ == '__main__':
sys.exit(main())
+242
View File
@@ -0,0 +1,242 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
fit_power_model.py - 从参考数据集复核/重拟合 DJI M3508 + C620 输入功率模型
用途:
验证 Motor-modeling-and-power-control-master 中 chassis_power_control.c 的
k_torque / k_a / k_speed_sq / k_constant 是否与 model_fit/datasets/*.csv 自洽,
并给出 module_test 单电机台架可用的推荐常数。
模型形式(cmd/转速同号=电动,反号=回馈):
P_in = k_torque * speed_rpm * cmd + k_a * cmd^2 + k_speed_sq * speed_rpm^2 + k_constant
运行(Windows,仓库自带 Python):
C:\\Users\\16936\\.dsh\\dsh-runtimes\\dsh-primary-runtime\\dependencies\\python\\python.exe tools\\fit_power_model.py
数据集路径默认为 E:\\ELCT\\Motor-modeling-and-power-control-master\\model_fit\\datasets,
可用环境变量 POWER_MODEL_DATASETS 覆盖。
"""
import os
import sys
import numpy as np
import pandas as pd
try: # Windows 控制台默认 GBK,改成 UTF-8 输出避免中文乱码
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
# ---------------------------------------------------------------- 配置
DATASET_DIR = os.environ.get(
"POWER_MODEL_DATASETS",
r"E:\ELCT\Motor-modeling-and-power-control-master\model_fit\datasets",
)
BUS_V = 24.56 # 参考工程假设的母线电压 (V)
GEAR = 3591.0 / 187.0 # M3508 P19 减速比 = 19.2032
KT_ROTOR_NM_PER_A = 0.3 # DJI 标称力矩常数,注意这是减速箱输出轴口径
CMD_FULL_SCALE = 16384.0 # C620 电流指令满量程 counts
CUR_FULL_SCALE_A = 20.0 # 对应电流 (A)
# 参考工程 chassis_power_control.c 现有常数
KT_REF = 1.99688994e-6 # (20/16384)*0.3*(187/3591)/9.55
KA_REF = 1.23e-7
K2_REF = 1.453e-7
C_REF = 4.081
# 若把 0.3 N·m/A 当成“转子侧”力矩常数,转速用转子 RPM 时的系数
KT_ROTOR_SIDE = (CUR_FULL_SCALE_A / CMD_FULL_SCALE) * KT_ROTOR_NM_PER_A / 9.5493
# 电流通道测量饱和(数据里 |I|>0.80 A 的全部是 ±0.8188 A 硬削顶)
I_SAT_A = 0.8008
P_SAT_W = BUS_V * I_SAT_A # ≈19.67 W
COLS = {
"Ib": "current", # 电池电流 (A)
"cmd": "give_current", # 下发力矩电流指令 (counts)
"giv": "motor_chassis[0].given_current", # C620 回报实际力矩电流 (counts)
"spd": "motor_chassis[0].speed_rpm", # C620 回报转子转速 (RPM)
}
def load(path):
df = pd.read_csv(path, sep=";", low_memory=False)
out = pd.DataFrame({k: pd.to_numeric(df[v], errors="coerce").values for k, v in COLS.items()})
out = out.dropna().reset_index(drop=True)
out["Pin"] = BUS_V * out["Ib"]
out["sat"] = out["Ib"].abs() > I_SAT_A # 电流通道削顶
return out
def lstsq(X, y):
b = np.linalg.lstsq(X, y, rcond=None)[0]
e = X @ b - y
rms = float(np.sqrt(np.mean(e * e)))
r2 = float(1.0 - np.sum(e * e) / np.sum((y - y.mean()) ** 2))
return b, rms, r2
def design(spd, cur):
return np.column_stack([spd * cur, cur * cur, spd * spd, np.ones_like(spd)])
def eval_model(data, kt, ka, k2, c, cur="cmd", sat_clip=True):
"""逐数据集评估;预测按电流通道饱和上限钳位后再比较(否则削顶样本会把 RMS 拉爆)"""
rows = {}
for f, d in data.items():
spd, cmd, giv, y = d["spd"], d["cmd"], d["giv"], d["Pin"]
u = cmd if cur == "cmd" else giv
pred = kt * spd * u + ka * u * u + k2 * spd * spd + c
if sat_clip:
pred = np.clip(pred, -P_SAT_W, P_SAT_W)
e = pred - y
rms = float(np.sqrt(np.mean(e * e)))
r2 = float(1.0 - np.sum(e * e) / np.sum((y - y.mean()) ** 2))
rows[f] = (rms, r2, float(e.mean()))
return rows
def fmt_row(name, vals):
return "%-18s" % name + "".join("%9.2f" % v for v in vals)
def main():
files = sorted(f for f in os.listdir(DATASET_DIR) if f.endswith(".csv"))
if not files:
print("no csv under", DATASET_DIR)
return 1
F = {f: load(os.path.join(DATASET_DIR, f)) for f in files}
data = {f: {"spd": d.spd.values, "cmd": d.cmd.values, "giv": d.giv.values, "Pin": d.Pin.values}
for f, d in F.items()}
print("=" * 96)
print("0) 数据集概况 (bus=%.2f V)" % BUS_V)
print("%-16s %8s %7s %8s %8s %8s %8s %7s" %
("file", "n", "dur_s", "spd_min", "spd_max", "cmd_min", "cmd_max", "sat%"))
for f, d in F.items():
print("%-16s %8d %7.1f %8.0f %8.0f %8d %8d %6.1f%%" % (
f, len(d), (d.index[-1]) * 0.002, d.spd.min(), d.spd.max(),
d.cmd.min(), d.cmd.max(), 100.0 * d.sat.mean()))
print("\n" + "=" * 96)
print("1) 数据是不是 M3508?")
spd_abs = np.concatenate([np.abs(d["spd"]) for d in data.values()])
print(" 全数据集 |转子转速| 最大 = %.0f RPM, 99%%分位 = %.0f RPM" % (spd_abs.max(), np.percentile(spd_abs, 99)))
print(" M3508 P19 空载输出 ≈482 RPM × %.2f = %.0f RPM(转子) -> 转速口径与 M3508 一致"
% (GEAR, 482 * GEAR))
print(" 指令范围 counts ±%d, C620 反馈 giv 与 cmd 相关, 母线 24 V -> 与 M3508+C620 一致" % int(
max(np.abs(d['cmd']).max() for d in data.values())))
print("\n" + "=" * 96)
print("2) k_torque 量纲核对")
print(" KT_REF = %.8e (输出轴 0.3 N·m/A 口径, 转速=转子RPM, /9.55)" % KT_REF)
print(" KT_ROTOR_SIDE = %.8e (若 0.3 是转子侧常数则该用它)" % KT_ROTOR_SIDE)
print(" 两者之比 = %.2f (= 减速比 %0.3f)" % (KT_ROTOR_SIDE / KT_REF, GEAR))
print(" M3508 力矩常数 0.3 N·m/A 是减速箱输出轴口径: 20 A -> 输出 6 N·m,")
print(" 对应转子力矩仅 0.31 N·m -> 转子侧常数 0.0156 N·m/A. 反之(转子 0.3 N·m/A)会得到")
print(" 20 A -> 输出 115 N·m, 对 0.5 kg 级电机不可能。故对转子 RPM, KT_REF 量纲正确.")
print("\n" + "=" * 96)
print("3) 逐数据集自由四参数拟合 (仅未削顶样本) P_in ~ kT*spd*cmd + a*cmd^2 + k2*spd^2 + c")
print("%-16s %12s %10s %10s %7s %8s %8s" % ("file", "kT", "a", "k2", "c", "RMS/W", "R2"))
per_kt = {}
for f, d in data.items():
m = ~F[f].sat.values
spd, cmd, y = d["spd"][m], d["cmd"][m], d["Pin"][m]
b, rms, r2 = lstsq(design(spd, cmd), y)
per_kt[f] = b[0]
print("%-16s %12.3e %10.2e %10.2e %7.2f %8.2f %8.3f" % (f, b[0], b[1], b[2], b[3], rms, r2))
print(" -> 常数转速/斜坡 (cmd 近似恒定或单调) 与恒功率类数据集上 kT 不可辨识(与 a/k2 共线),")
print(" sin/sin3/test3 这类双向激励才给出可信 kT ≈ 2.2~2.4e-6; 负值只说明该测试无法定 kT.")
print("\n" + "=" * 96)
print("4) 汇总拟合 (未削顶样本, 353647 行)")
U = pd.concat([F[f][~F[f].sat] for f in files], ignore_index=True)
for cur, col in (("cmd", "give_current"), ("giv", "given_current")):
X = design(U.spd.values, U[cur].values)
b, rms, r2 = lstsq(X, U.Pin.values)
print(" 自由拟合 %s(%s): kT=%.6e a=%.4e k2=%.4e c=%.3f RMS=%.2f W R2=%.3f"
% (cur, col, b[0], b[1], b[2], b[3], rms, r2))
print(" kT/1.99688994e-6 = %.3f kT/KT_ROTOR_SIDE = %.4f"
% (b[0] / KT_REF, b[0] / KT_ROTOR_SIDE))
# 固定物理 k_torque 再拟合损耗项
mech = KT_REF * U.spd.values * U[cur].values
Xr = np.column_stack([U[cur].values ** 2, U.spd.values ** 2, np.ones(len(U))])
br, rmsr, _ = lstsq(Xr, U.Pin.values - mech)
print(" kT 固定 1.99688994e-6: a=%.4e k2=%.4e c=%.3f RMS=%.2f W"
% (br[0], br[1], br[2], rmsr))
print("\n" + "=" * 96)
print("5) 候选常数逐数据集 RMS/W (预测按 ±%.2f W 饱和钳位, 全样本)" % P_SAT_W)
hdr = "%-22s" % "model"
print(hdr + "".join(f.replace(".csv", "")[:8].rjust(9) for f in files) + " avgRMS")
cands = [
("A_ref(cmd)", KT_REF, KA_REF, K2_REF, C_REF, "cmd"),
("A_ref(giv)", KT_REF, KA_REF, K2_REF, C_REF, "giv"),
("B_c=2.2(cmd)", KT_REF, KA_REF, K2_REF, 2.2, "cmd"),
("C_refit(cmd)", KT_REF, 1.629e-7, 1.064e-7, 2.0, "cmd"),
("D_refit(giv)", 2.0381e-6, 1.629e-7, 1.064e-7, 1.99, "giv"),
("E_matlab(giv)", KT_REF, 9.805e-8, 2.11e-7, 2.138, "giv"),
]
results = {}
for name, kt, ka, k2, c, cur in cands:
r = eval_model(data, kt, ka, k2, c, cur)
results[name] = r
avg = np.sqrt(np.mean([v[0] ** 2 for v in r.values()]))
print(fmt_row(name, [r[f][0] for f in files]) + " %6.2f" % avg)
print("\n R2 (C_refit, cmd):")
r = results["C_refit(cmd)"]
print(" " + " ".join("%s=%.2f" % (f.replace(".csv", "")[:8], v[1]) for f, v in r.items()))
print(" (ramp/test4 等“恒功率”测试里 P_in 方差极小, R2 会被放大成负值, 看 RMS 更实在)")
print("\n" + "=" * 96)
print("6) 回馈/符号处理 (C_refit + cmd)")
tot_neg = 0
tot = 0
for f, d in data.items():
pred = KT_REF * d["spd"] * d["cmd"] + 1.629e-7 * d["cmd"] ** 2 + 1.064e-7 * d["spd"] ** 2 + 2.0
neg = pred < 0
yneg = d["Pin"][neg]
tot_neg += int(neg.sum())
tot += len(pred)
if neg.sum() > 50:
print(" %-16s 负功率段 %5.1f%% 采样, 实测均值 %6.2f W, 预测均值 %6.2f W"
% (f, 100.0 * neg.mean(), yneg.mean(), pred[neg].mean()))
print(" 负功率样本占比 %.1f%%, 说明数据里回馈真实存在; 前向“估计”不应钳零," % (100.0 * tot_neg / tot))
print(" 只有“功率限幅”求和时才把负功率排除(参考 C 代码里 `if (initial_give_power < 0)`")
print(" 比较的是数组地址, 恒为假 -> 该判断实际失效, 移植时应写成 initial_give_power[i] < 0)。")
print("\n" + "=" * 96)
print("7) give_current vs given_current")
for f, d in data.items():
diff = d["cmd"] - d["giv"]
corr = np.corrcoef(d["cmd"], d["giv"])[0, 1] if d["cmd"].std() > 0 else float("nan")
print(" %-16s corr=%s RMS(cmd-giv)=%6.1f counts = %5.2f A mean=%7.1f"
% (f, "n/a " if np.isnan(corr) else "%.4f" % corr,
np.sqrt(np.mean(diff ** 2)),
np.sqrt(np.mean(diff ** 2)) * CUR_FULL_SCALE_A / CMD_FULL_SCALE,
np.mean(diff)))
print(" 结论: 固件能同时拿到两者(下发指令 + 0x201 反馈里的 given_current)。")
print(" 前向估计优先用 given_current(物理上产生力矩的就是它); 逆解(功率->电流)只能用 cmd。")
print("\n" + "=" * 96)
print("8) 推荐常数 (module_test, 24 V M3508 单车台架)")
rec = (KT_REF, 1.63e-7, 1.06e-7, 2.0)
print(" k_torque = %.8e" % rec[0])
print(" k_a = %.2e" % rec[1])
print(" k_speed_sq = %.2e" % rec[2])
print(" k_constant = %.1f W" % rec[3])
r = eval_model(data, *rec, cur="cmd")
print(" (用 cmd 前向: 逐数据集 RMS 见下, avgRMS=%.2f W)" % np.sqrt(np.mean([v[0] ** 2 for v in r.values()])))
print("%-16s %9s %9s %9s" % ("file", "RMS/W", "R2", "bias/W"))
for f, d in data.items():
rms, r2, bias = r[f]
print("%-16s %9.2f %9.3f %+9.2f" % (f, rms, r2, bias))
print("\n 与参考工程常数对比: 维持 A_ref(cmd) 时 avgRMS=%.2f W 且系统性偏高约 +1.7~+2.6 W"
% np.sqrt(np.mean([v[0] ** 2 for v in results["A_ref(cmd)"].values()])))
print(" (k_constant 4.081 -> 最优约 1.7~2.0 W);kT 本身与数据差 2%(取 giv 时 2.04e-6)。")
return 0
if __name__ == "__main__":
sys.exit(main())
+73
View File
@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*-
"""修复 module_test 的 uvprojx:通过 ASCII junction(chassis_algo)引用 Simba 底盘
下的同一份 pid.c / dji_motor.c / robot_param.h。
说明:µVision 对含中文的 include 路径支持不稳定,因此在 Simba 根目录建立
junction: Simba-OmniInfantry/chassis_algo -> Simba-OmniInfantry/底盘
本脚本只写 ASCII 路径。运行前需先创建 junction(见 tools/link_chassis_algo.ps1)。
"""
import re
P = r'E:\ELCT\Simba-OmniInfinity\module_test\MDK-ARM\Simba-ELCT-FrameWork.uvprojx'
P = r'E:\ELCT\Simba-OmniInfantry\module_test\MDK-ARM\Simba-ELCT-FrameWork.uvprojx'
LINK = r'..\..\chassis_algo'
CH = '\u5e95\u76d8' # 底盘
s = open(P, encoding='utf-8', errors='replace').read()
# 1) 源文件路径
def fix_file(m):
body = m.group(0)
fp = re.search(r'<FilePath>(.*?)</FilePath>', body, re.S)
if not fp:
return body
path = fp.group(1)
low = path.lower()
if low.endswith(r'\pid.c') and 'algorithm' in low:
path = LINK + r'\modules\algorithm\pid.c'
elif low.endswith(r'\dji_motor.c'):
path = LINK + r'\modules\motor\dji_motor.c'
else:
return body
return body[:fp.start(1)] + path + body[fp.end(1):]
s = re.sub(r'<File>.*?</File>', fix_file, s, flags=re.S)
# 2) IncludePath:清洗 + 去重 + 追加 ASCII junction 路径
def fix_inc(m):
toks = [t for t in m.group(1).split(';') if t]
clean = []
for t in toks:
if '\ufffd' in t or CH in t:
continue
n = t.replace('/', '\\').lower()
if n in (r'..\modules\algorithm', r'..\modules\motor'):
continue
if t not in clean:
clean.append(t)
out = []
added = False
for t in clean:
out.append(t)
if t.replace('/', '\\').lower() == r'..\application\task\inc' and not added:
out.append(LINK + r'\Application')
out.append(LINK + r'\modules\algorithm')
out.append(LINK + r'\modules\motor')
added = True
return '<IncludePath>' + ';'.join(out) + '</IncludePath>'
s = re.sub(r'<IncludePath>(.*?)</IncludePath>', fix_inc, s, flags=re.S)
open(P, 'w', encoding='utf-8', newline='').write(s)
# 验证
s2 = open(P, encoding='utf-8').read()
print('replacement chars:', s2.count('\ufffd'))
print('chassis_algo count:', s2.count('chassis_algo'))
for i, m in enumerate(re.finditer(r'<IncludePath>(.*?)</IncludePath>', s2, re.S)):
toks = [t for t in m.group(1).split(';') if 'chassis_algo' in t]
if toks:
print('INC', i, ':', toks)
for m in re.findall(r'<FilePath>(.*?)</FilePath>', s2):
if 'chassis_algo' in m:
print('FILE:', m)
+40
View File
@@ -0,0 +1,40 @@
# 在 module_test 内部创建两个 ASCII junction,供 Keil 工程引用 底盘/云台 的
# 同一份源码与参数:
# module_test/refs/chassis -> ../../底盘
# module_test/refs/gimbal -> ../../云台
#
# 背景:µVision 对含中文的 include/源文件路径支持不稳定(本机实测报 file not found),
# 因此工程里统一使用 ASCII 路径 ..\refs\chassis\... / ..\refs\gimbal\...。
# junction 指向真实目录,保证"同一个文件",不会出现副本漂移;
# 同时 Simba-OmniInfantry 根目录只保留 底盘/云台/module_test 三个源码目录。
#
# 使用:在 PowerShell 中执行(无需管理员权限,同卷 junction 可创建)
# powershell -ExecutionPolicy Bypass -File tools\link_algo.ps1
$ErrorActionPreference = 'Stop'
$moduleTest = Split-Path -Parent $PSScriptRoot # ...\module_test
$simba = Split-Path -Parent $moduleTest # ...\Simba-OmniInfantry
$refs = Join-Path $moduleTest 'refs'
if (-not (Test-Path $refs)) { New-Item -ItemType Directory -Path $refs | Out-Null }
$pairs = @(
@{ Link = 'chassis'; Target = '底盘' },
@{ Link = 'gimbal'; Target = '云台' }
)
foreach ($p in $pairs) {
$link = Join-Path $refs $p.Link
$target = Join-Path $simba $p.Target
if (-not (Test-Path $target)) { throw "找不到目录: $target" }
if (Test-Path $link) {
$item = Get-Item $link -Force
if ($item.LinkType -eq 'Junction') {
Write-Host "junction 已存在: $link -> $($item.Target)"
continue
}
throw "$link 已存在且不是 junction,请先手动处理"
}
New-Item -ItemType Junction -Path $link -Target $target | Out-Null
Write-Host "已创建 junction: $link -> $target"
}
+133
View File
@@ -0,0 +1,133 @@
# -*- coding: utf-8 -*-
"""拆分 底盘/云台 的 robot_param.h:
- 公共参数 -> Simba-OmniInfantry/common/robot_param_common.h
- 底盘专属 -> 底盘/Application/robot_param.h (include common)
- 云台专属 -> 云台/Application/robot_param.h (include common)
按"参数归属"分类(不是按文件里是否出现):
COMMON : 两块板都会编译/使用的公共项(CToC ID、掉线时间、IMU 温控、蜂鸣器调试)
CHASSIS: MECANUM_* / CHASSIS_* / POWER_LIMIT_* (底盘专属;CHASSIS_SPIN_FEEDFORWARD_K 实际用于云台,归 GIMBAL)
GIMBAL : 其余(GIMBAL_* / PITCH_* / YAW_* / PC_MOUSE_* / DEBUG_SHOOT_* / 台架拨弹等)
原文件是 GBK 编码,输出保持 GBK,避免 µVision 显示/编译问题。
"""
import os
import re
import shutil
import tempfile
BASE = r'E:\ELCT\Simba-OmniInfantry'
CHASSIS = os.path.join(BASE, '底盘', 'Application', 'robot_param.h')
GIMBAL = os.path.join(BASE, '云台', 'Application', 'robot_param.h')
COMMON = os.path.join(BASE, 'common', 'robot_param_common.h')
os.makedirs(os.path.dirname(COMMON), exist_ok=True)
COMMON_NAMES = {
'CTOC_MASTER_ID1', 'CTOC_SLAVE_ID1', 'CTOC_SLAVE_ID2', 'CTOC_SLAVE_ID3', 'CTOC_SLAVE_ID4',
'CTOC_OFFLINE_TIME_MS', 'DEVICE_OFFLINE_TIME_MS',
'IMU_TEMPERATURE_TARGET', 'IMU_TEMPERATURE_LIMIT',
'IMU_TEMP_KP', 'IMU_TEMP_KI', 'IMU_TEMP_KD',
'DEBUG_BUZZER_MELODY', 'BUZZER_MELODY_SPEED_DIV',
}
def is_chassis_name(n):
if n == 'CHASSIS_SPIN_FEEDFORWARD_K':
return False # 名字带 CHASSIS,实际用于云台自旋前馈
return n.startswith(('MECANUM_', 'CHASSIS_', 'POWER_LIMIT_'))
def split_lines(path):
"""返回行列表,以及每个 #define 行对应的宏名(按行号索引)。"""
lines = open(path, encoding='gbk', errors='replace').read().splitlines(keepends=True)
names = {}
for i, ln in enumerate(lines):
m = re.match(r'\s*#\s*define\s+(\w+)\b', ln)
if m:
names[i] = m.group(1)
return lines, names
def filter_file(path, keep):
lines, names = split_lines(path)
out = []
removed = []
in_guard = True
for i, ln in enumerate(lines):
n = names.get(i)
if n is None:
out.append(ln)
continue
if n in keep:
out.append(ln)
else:
removed.append(n)
return out, removed
ch_lines, ch_names = split_lines(CHASSIS)
gy_lines, gy_names = split_lines(GIMBAL)
all_names = set(ch_names.values()) | set(gy_names.values())
ch_keep = {n for n in all_names if (n in COMMON_NAMES) or (n in ch_names.values() and not is_chassis_name(n) is False)}
# 底盘保留:公共 + 底盘专属
ch_keep = {n for n in ch_names.values() if n in COMMON_NAMES or is_chassis_name(n)}
gy_keep = {n for n in gy_names.values() if n in COMMON_NAMES or not is_chassis_name(n)}
# 1) 公共头:从云台文件里按原顺序抽取公共 define 行
common_lines = []
for ln, n in zip(gy_lines, [gy_names.get(i) for i in range(len(gy_lines))]):
if n in COMMON_NAMES:
common_lines.append(' ' + ln.replace('\n', '') + '\n')
common_text = '''/* =============================================================================
* robot_param_common.h - 底盘/云台/module_test 共用参数(单一来源)
*
* 本文件由 common 统一维护,底盘和云台各自的 robot_param.h 通过
* #include "../../common/robot_param_common.h"
* 引用,不再各存一份。
*
* 内容:板间通讯 CToC 帧 ID、掉线判定时间、IMU 温控、蜂鸣器/调试开关。
* 底盘专属参数见 底盘/Application/robot_param.h;
* 云台专属参数见 云台/Application/robot_param.h。
* ========================================================================== */
#ifndef ROBOT_PARAM_COMMON_H
#define ROBOT_PARAM_COMMON_H
''' + ''.join(common_lines) + '''
#endif /* ROBOT_PARAM_COMMON_H */
'''
open(COMMON, 'w', encoding='gbk', errors='replace').write(common_text)
print('common written:', COMMON, 'macros:', len(common_lines))
def rewrite(path, keep, guard, label):
lines, names = split_lines(path)
out = []
for i, ln in enumerate(lines):
n = names.get(i)
if n is None:
out.append(ln)
elif n in keep:
out.append(ln)
text = ''.join(out)
# 替换 include guard 并插入 common include
text = text.replace('#ifndef ROBOT_PARAM_H', '#ifndef %s' % guard, 1)
text = text.replace('#define ROBOT_PARAM_H', '#define %s' % guard, 1)
text = text.replace('#define %s\n' % guard,
'#define %s\n\n#include "../../common/robot_param_common.h"\n' % guard, 1)
open(path, 'w', encoding='gbk', errors='replace').write(text)
print(label, 'kept macros:', len([n for n in names.values() if n in keep]))
rewrite(CHASSIS, ch_keep, 'ROBOT_PARAM_CHASSIS_H', 'chassis:')
rewrite(GIMBAL, gy_keep, 'ROBOT_PARAM_GIMBAL_H', 'gimbal:')
# 简单验证:交集不应包含跨板参数
for p, keep, label in [(CHASSIS, ch_keep, 'chassis'), (GIMBAL, gy_keep, 'gimbal')]:
lines, names = split_lines(p)
got = set(names.values())
print(label, 'macros now:', len(got))
extra_c = sorted(n for n in got if is_chassis_name(n) and label == 'gimbal')
extra_g = sorted(n for n in got if (not is_chassis_name(n)) and n not in COMMON_NAMES and label == 'chassis')
print(' cross-board leftovers:', extra_c + extra_g)