handler.py 拆分笔记

背景

src/planarmwebsocketservice/scripts/handler.py 原为 5366 行的单文件, 含 ~52 个 *_handler 接口 + 47 个 helper 函数 + 22+ 全局变量. 维护成本高, 按功能领域拆分模块.

最终结果: handler.py 5366 → 2229 行 (-3137, -58%), 52/52 dispatch-able handler 全部迁出.

拆分机制 (保守式, dispatcher 不动)

plan_arm_action_websocket_server.py
   └─ from handler import (...)
              │
              ▼
   handler.py                                   (主入口)
   ├─ Payload / Response dataclass
   ├─ 全局变量 (response_queue, active_threads, MUSIC_FILE_FOLDER,
   │           robot_status, robot_instance, control_head_pub, ...)
   ├─ helper 函数 (upload_music_file, get_music_list, execute_command_progress,
   │              robot_status_timer_callback, map_callback, odometry_callback, ...)
   ├─ KuavoRobotReal / KuavoRobotSim class (start/stop/stand/switch_pose 实现)
   ├─ async def websocket_message_handler(...)  ← dispatcher, 用 globals()[cmd_handler]
   ├─ async def broadacast_handler(...)         ← 唯一不可拆的内部 handler
   │
   └─ (文件末尾) 8 个子模块注入
      from handlers_music import *
      from handlers_calibration import *
      from handlers_vr_realtime import *
      from handlers_voice_api import *
      from handlers_navigation import *
      from handlers_mapping import *
      from handlers_robot_control import *
      from handlers_action_run import *

关键点:

  • 子模块 scripts/handlers_*.py 顶部 import handler, 函数体内通过 handler.<attr> 访问主模块的全局变量. 不用 from handler import * (避免名字快照与混淆).
  • 子模块仅搬 *_handler 函数, helper / class / ROS callback / timer / publisher 全部留主文件.
  • handler.py 末尾 from handlers_xxx import * 把子模块定义的 _handler 名字回注入主模块 globals(), dispatcher 通过 globals()[cmd_handler] 找到. dispatcher 0 修改.
  • 全局变量赋值 (rebinding) 必须 handler.X = ..., 仅 read 可直接 handler.X.

已拆模块 (全部)

文件 handler 数 handler 列表 备注
handlers_music.py 2 check_music_path, get_music_list 第 1 轮
handlers_calibration.py 4 adjust/set/get_zero_point, zero_point_debug 第 1 轮
handlers_vr_realtime.py 7 get_vr_status, start/stop/get_real_time_chat, start/stop/cancel_vr_record 第 1 轮
handlers_voice_api.py 5 get/update_voice_keywords, set/get/get_api_key_status 第 1 轮
handlers_navigation.py 5 task_point, get_task_points, navigate_to_task_point, get_robot_position, calibration_by_task_point 第 2 轮
handlers_mapping.py 11 load_map, init_localization_by_pose, check_lidar, create_map, save_map, stop_mapping, rename_map, delete_map, assist_scan, edit_map, get_all_maps 第 2 轮
handlers_robot_control.py 9 get_robot_info, get_robot_status, get_robot_launch_status, start_robot, stop_robot, stand_robot, robot_switch_pose, set_align_stair_param, check_robot_standing 第 3 轮
handlers_action_run.py 9 preview_action, stop_preview_action, execute_python_script, run_node, stop_run_node, update_h12_config, update_data_pilot, execute_demo, stop_execute_demo 第 3 轮
合计 52 / 52 handler.py 5366 → 2229 行 (-3137, -58%)

主文件 handler.py 剩下:

  • websocket_message_handler (dispatcher) + broadacast_handler (内部 broadcast, 不走 dispatch)
  • ~30 个 helper 函数 + ~20 个全局变量
  • KuavoRobot / KuavoRobotReal / KuavoRobotSim 3 个 class
  • ROS Subscriber/Publisher/Timer init 逻辑 + 业务 callback

第 2 轮 (navigation + mapping) 关键决策

  • 17 个 handler 一起拆 (不是分两轮), 因为同属 SLAM/地图子系统, 共享 helper (png_to_map, map_to_png, get_robot_position_for_task_point).
  • 实际是 16 个 (5 + 11), 不是文档原说的 17 (5 + 12) — 之前数错.
  • mapping helper 全留主文件: download_map_file, map_callback, init_map_publisher, check_and_publish_map, get_latest_map_data, odometry_callback, get_robot_position_for_task_point, convert_map_to_base64, check_map_exists, get_map_image_for_editing.
  • kuavo_msgs.srv vs kuavo_mapping.srv 混用是原 handler 风格, 1:1 保留.

第 3 轮 (robot_control + action_run) 关键决策

robot_control 顺便完成 P4 deep 6 个 handler 走 bridge

  • bridge controller_rpc_bridge.py 暴露的 ROS srv 名跟 KuavoRobotReal 已经在调的 srv 名对齐 (stand/launch_status/switch_robot_pose 这 3 个 method 不动).
  • 真正改动只在 KuavoRobotReal.start_robot() 和 stop_robot() 两个 method (主文件 L587-616):
    • 原来 start_robot(): tmux roslaunch humanoid_controllers load_kuavo_real.launch (NX 上没装该包, 必坏)
    • 改为: rospy.ServiceProxy('/hardware/switch_robot_state', robotSwitchPose) 调 bridge composite, status="ready"
    • 原来 stop_robot(): publish Bool 到 /stop_robot topic (NX-lejulab 架构无监听者)
    • 改为: 同上 bridge composite "ready" 分支当近似 (lejulab 没"真停止", ready = SwitchController dummy = 最接近)
  • KuavoRobotSim 保持 tmux roslaunch (仿真模式还要用), 没动.

action_run 实际拆 9 个 (含 update_h12_config)

  • update_h12_config_handler 函数名含数字, 上一轮 grep regex ^async def [a-z_]+_handler 漏匹配, 这轮补上.
  • preview_action_handler 1:1 搬过去, 其 broken 链路 (依赖未提供的 /plan_arm_trajectory_bezier_curve service) 不在拆分范围, 留给独立决策 — 见 docs/preview_action_decision.md (方案 A 是本机 bezier player, 工作量 ~1.5d, 推荐下轮独立 plan 启动).
  • execute_command_progress / monitor_and_stop / is_player_in_body / upload_music_file / download_data_pilot_to_head / get_music_list 这 6 个 helper 留主文件.

已知风险与陷阱

  1. rebinding 必须 prefix: 子模块 handler.X = new_value 才能修改主模块全局. 直接 X = ... 只建本地名, bug 隐蔽.
  2. 循环 import 时机: handler.py 末尾才 from handlers_xxx import *, 此时主模块所有 top-level state 都已建立. 子模块顶部 import handler 拿到的 handler 模块已具备所需 attr.
  3. PYTHONUNBUFFERED=1 在 systemd unit 必加, 否则 print 被 buffered 看不到, 排错困难.
  4. 业务遗留 bug 不属于拆分范围: 比如 get_zero_point_handler 依赖 rospkg.RosPack().get_path('kuavo_assets'), NX 上没装该包. 拆前拆后行为一致, 修复属业务清理.
  5. 正则陷阱: ^async def [a-z_]+_handler 不匹配数字, 漏 update_h12_config_handler. 用 ^async def [a-z_0-9]+_handler 或 ^async def (含所有) 才稳.

验证清单

第 1 轮 (NX systemd 实跑)

sudo systemctl restart planarm-websocket
sudo systemctl is-active planarm-websocket   # active
# get_music_list / check_music_path / get_zero_point / get_vr_status / get_api_key_status → 通

第 2/3 轮 (本机静态 + import 验证)

# 1. 语法
python3 -m py_compile handler.py handlers_*.py   # SYNTAX_OK

# 2. import (需 source ROS workspace 拿 kuavo_msgs / kuavo_ros_interfaces 等)
source /opt/ros/noetic/setup.bash
source ~/work/kuavo-ros-control/devel/setup.bash   # 或 NX 上 ~/lejulab_ws/devel/setup.bash
python3 -c "
import sys; sys.path.insert(0, '<scripts dir>')
import handler
ALL = [...52 个 handler 名...]
g = vars(handler)
print('found:', sum(1 for h in ALL if h in g), '/', len(ALL))
"
# → 52/52 found, 模块归属正确 (action_run:9, calibration:4, mapping:11, music:2, navigation:5, robot_control:9, voice_api:5, vr_realtime:7)

第 3 轮 (NX systemd + 真机)

还没真机验证 (RK3588 + lejulab 当前未跑), 验证清单:

sudo systemctl restart planarm-websocket
# WebSocket 发命令测:
# - get_robot_info / get_robot_status / check_robot_standing (本机 read, 不依赖 bridge)
# - start_robot / stop_robot / robot_switch_pose / stand_robot (走 bridge → lejulab)
# - preview_action → 预期 code=4 (bezier service 不存在, 见 preview_action_decision.md)

拆分完结. 后续工作

handler 拆分已完结 (52/52). 后续不属拆分范围, 但相关:

  1. preview_action 改造: 见 docs/preview_action_decision.md — 启动新轮 plan 实现本机 bezier player (工作量 ~1.5d)
  2. 死代码清理 ✅ 2026-05-19 done: KuavoRobotReal.__init__ 的 self.stop_pub / self.cmd_vel_pub Publisher 已删 (P4 deep 后没人 read). KuavoRobot.zero_point_robot method 保留 (被 handlers_calibration.py:zero_point_debug_handler 调用; lejulab 架构下功能不可用属业务问题, 不归拆分管). KuavoRobotSim 还在用 stop_pub/cmd_vel_pub, 保留.
  3. MIGRATION_NOTES ✅ 2026-05-19 精简: 行号过期 + 内容散到本笔记 + preview_action_decision.md. 已重写为索引页 (src/planarmwebsocketservice/MIGRATION_NOTES.md).