72353f3773
背景:现场读代码的人只读中文。此前代码里的 docstring 是英文、行内注释是中文,
一半英文一半中文反而更难看懂 —— 新手打开一个 .py 不知道这个模块为什么存在。
范围(本仓库自己的代码,厂商上游不动)
src/arm_application/** 37 个文件:servo_node / perception_node / handeye_* / dh_pgea /
yolo_detector / kalman_filter / goto_ee_plane / dual_gripper …
src/arm_interfaces/** 11 个文件:paths / manifest / loader / config_guard / errors …
src/arm_control/** 5 个文件
src/arm_bringup/** 3 个 launch
scripts/** 6 个 .py + 29 个 .sh(scripts/ 是"唯一操作入口",用户屏幕上
看到的就是这些提示,所以提示信息也一并中文化)
config/ handeye/ devices/ src/arm_*/config/ 17 个 .yaml/.xml/.xacro/.cfg
口径(写进 docs/FRAMEWORK_RULES.md 新增的 R6.5,作为长期约束)
注释、docstring、print/日志/异常里给人看的句子 = 中文;
标识符、API 名、话题名、参数名、字段名、命令名 = 保留英文原文(用 `` `` 包起来);
单位、十六进制、协议报文、CRC 值、命令示例 = 原样保留;
src/flexiv_*/ = 厂商上游代码,不许改也不许翻译(R4.4)。
翻译保原意与原有详细程度:那些"为什么不能用另一种做法""踩过什么坑"的说明
全部完整保留 —— 它们才是这份代码里最贵的部分。
新增 scripts/check_text_only.py:只改文字时的自证工具
人工 review 靠不住(115 个文件、3000 多行 diff)。这个脚本把改动前后的源码解析成
语法树,删掉 docstring、抹平字符串常量、把 f-string 只留"插值了几次 + 插值是什么",
再比对:完全相同 = 改动范围内没有逻辑变化。
留了一个口子:f-string 的插值按内容排序后再比 —— 因为中文语序常常要和英文反着来
(f"on {port} read {idx} failed" → f"在 {port} 上读 {idx} 失败"),只换显示顺序不该判失败;
但多插一个、少插一个、换掉被插入的表达式,立刻会报出来。
本次 66 个 .py 全部通过该闸门。
验收
改动的 66 个 .py:scripts/check_text_only.py 全部通过(零逻辑变化)
45 个非 .py 文件:去注释后与 HEAD 逐字节相同(零配置变化)
docstring 总数:没有一个文件减少(不存在"翻译时顺手删了说明")
单测:arm_application 233 / arm_driver_flexiv 69 / arm_interfaces 46 /
arm_kinematics 24 / arm_sim_gazebo 236 = 608 passed,与改动前一致
全部 .sh:bash -n 通过;并额外实际执行了 --help 验证(见下一个提交:
bash -n 对 CRLF 脚本会漏报,只有真跑才暴露)
Co-authored-by: Cursor <cursoragent@cursor.com>
118 lines
4.3 KiB
Python
Executable File
118 lines
4.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""把 Flexiv Elements 的 .traj(文本)转换成 arm_application 的 YAML 路点。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import math
|
||
import re
|
||
import sys
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
|
||
def parse_flexiv_traj(text: str) -> list[dict[str, Any]]:
|
||
"""解析 Elements Studio 导出的散点 .traj 文件。"""
|
||
blocks = re.split(r'pattern_params\s*\{', text)[1:]
|
||
waypoints: list[dict[str, Any]] = []
|
||
for block in blocks:
|
||
name_m = re.search(r'pattern_name:\s*"([^"]+)"', block)
|
||
vel_m = re.search(r'velocity:\s*"([^"]+)"', block)
|
||
joints: dict[str, float] = {}
|
||
for j in range(1, 8):
|
||
m = re.search(rf'joint{j}:\s*"([^"]+)"', block)
|
||
if m:
|
||
joints[f'joint{j}'] = math.radians(float(m.group(1)))
|
||
if len(joints) != 7:
|
||
continue
|
||
positions = [joints[f'joint{i}'] for i in range(1, 8)]
|
||
waypoints.append({
|
||
'name': name_m.group(1) if name_m else f'WPT{len(waypoints)}',
|
||
'positions': positions,
|
||
'velocity': float(vel_m.group(1)) if vel_m else 0.2,
|
||
})
|
||
return waypoints
|
||
|
||
|
||
def assign_times(waypoints: list[dict[str, Any]], min_seg: float = 3.0) -> None:
|
||
"""按关节空间的段长累加出 time_from_start。"""
|
||
t = 0.0
|
||
prev = None
|
||
for wp in waypoints:
|
||
pos = wp['positions']
|
||
if prev is None:
|
||
t += min_seg
|
||
else:
|
||
delta = max(abs(a - b) for a, b in zip(pos, prev))
|
||
# 关节最大运动量每弧度约 4 秒,且不低于 min_seg
|
||
t += max(min_seg, delta * 4.0)
|
||
wp['time'] = round(t, 2)
|
||
prev = pos
|
||
|
||
|
||
def to_yaml(
|
||
waypoints: list[dict[str, Any]],
|
||
*,
|
||
joint_prefix: str = 'Rizon4-063989_',
|
||
velocity_scale: float | None = None,
|
||
) -> str:
|
||
if velocity_scale is None:
|
||
velocity_scale = waypoints[0].get('velocity', 0.2) if waypoints else 0.2
|
||
times = [wp['time'] for wp in waypoints]
|
||
flat: list[float] = []
|
||
for wp in waypoints:
|
||
flat.extend(wp['positions'])
|
||
pos_line = ', '.join(f'{v:.6f}' for v in flat)
|
||
time_line = ', '.join(str(t) for t in times)
|
||
names = ', '.join(f' # {wp.get("name", "")}' if i == 0 else '' for i, wp in enumerate(waypoints))
|
||
_ = names # 名称保留在下面的注释里
|
||
lines = [
|
||
'# 由 Flexiv Elements .traj 自动转换而来(关节角:度 -> 弧度)',
|
||
'# ROS 参数:扁平的 waypoint_positions + waypoint_times(不使用嵌套字典)',
|
||
'# 按需修改 velocity_scale / loop_count(无需重新编译)。',
|
||
'run_joint_trajectory:',
|
||
' ros__parameters:',
|
||
f' joint_prefix: "{joint_prefix}"',
|
||
' joint_names: [joint1, joint2, joint3, joint4, joint5, joint6, joint7]',
|
||
f' velocity_scale: {velocity_scale}',
|
||
' loop_count: 1 # 1=执行一次,0=无限循环,N=重复 N 次',
|
||
' pause_between_loops: 0.5',
|
||
f' waypoint_times: [{time_line}]',
|
||
' waypoint_positions: [',
|
||
]
|
||
for i, wp in enumerate(waypoints):
|
||
pos = ', '.join(f'{v:.6f}' for v in wp['positions'])
|
||
lines.append(f' {pos}, # {wp.get("name", f"WPT{i}")}')
|
||
lines.append(' ]')
|
||
return '\n'.join(lines) + '\n'
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser(description=__doc__)
|
||
ap.add_argument('input', type=Path, help='Flexiv Elements 的 .traj 文件')
|
||
ap.add_argument('-o', '--output', type=Path, help='输出的 YAML 路径')
|
||
ap.add_argument('--prefix', default='Rizon4-063989_', help='关节名前缀(现场 SN + _)')
|
||
ap.add_argument('--min-seg', type=float, default=3.0, help='每段的最小秒数')
|
||
args = ap.parse_args()
|
||
|
||
text = args.input.read_text(encoding='utf-8')
|
||
wps = parse_flexiv_traj(text)
|
||
if not wps:
|
||
print('错误:没有解析到任何路点', file=sys.stderr)
|
||
return 1
|
||
assign_times(wps, min_seg=args.min_seg)
|
||
yaml_text = to_yaml(wps, joint_prefix=args.prefix)
|
||
|
||
out = args.output
|
||
if out:
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
out.write_text(yaml_text, encoding='utf-8')
|
||
print(f'已写入 {len(wps)} 个路点 -> {out}')
|
||
else:
|
||
print(yaml_text)
|
||
return 0
|
||
|
||
|
||
if __name__ == '__main__':
|
||
raise SystemExit(main())
|