"""
leju_head_lab WebSocket 命令行调试器 (绕开浏览器/代理).
用法:
python3 tools/cli_debugger.py [host] [port]
python3 tools/cli_debugger.py 192.168.50.187 8888
交互命令:
数字 (1-N) 按预设命令清单选 — 默认有 ~30 个常用命令
list / l 重新看命令清单
raw <json> 直接发自定义 JSON, 例: raw {"cmd":"start_robot"}
logger 切换连 logger (8889) 收推送日志
quit / q 退出
"""
import asyncio, json, sys, signal
try:
import websockets
except ImportError:
print("装一下 websockets: pip3 install --user websockets")
sys.exit(1)
class C:
RESET='\033[0m'; CYAN='\033[36m'; GREEN='\033[32m'; YELLOW='\033[33m'
RED='\033[31m'; BLUE='\033[34m'; MAGENTA='\033[35m'; DIM='\033[2m'; BOLD='\033[1m'
COMMANDS = [
("状态查询",
("get_robot_info", {"cmd": "get_robot_info"}),
("get_robot_status", {"cmd": "get_robot_status"}),
("get_robot_launch_status", {"cmd": "get_robot_launch_status"}),
("get_robot_position", {"cmd": "get_robot_position"}),
),
("机器人控制",
("start_robot", {"cmd": "start_robot"}),
("stand_robot", {"cmd": "stand_robot"}),
("stop_robot", {"cmd": "stop_robot"}),
("switch→stand", {"cmd": "robot_switch_pose", "data": {"robot_pose": "stand"}}),
("switch→ready", {"cmd": "robot_switch_pose", "data": {"robot_pose": "ready"}}),
("switch→cali_zero", {"cmd": "robot_switch_pose", "data": {"robot_pose": "cali_zero"}}),
),
("动作 / Demo",
("preview_action 抱拳", {"cmd": "preview_action", "data": {"action_filename": "抱拳.tact", "action_file_MD5": ""}}),
("stop_preview_action", {"cmd": "stop_preview_action"}),
("execute_demo trace_path", {"cmd": "execute_demo", "data": {"demo_name": "trace_path", "parameters": {}}}),
("stop_execute_demo", {"cmd": "stop_execute_demo"}),
),
("导航 / 地图",
("get_all_maps", {"cmd": "get_all_maps"}),
("get_task_points", {"cmd": "get_task_points"}),
("check_lidar", {"cmd": "check_lidar"}),
),
("语音 / LLM",
("get_voice_keywords", {"cmd": "get_voice_keywords"}),
("get_api_key", {"cmd": "get_api_key"}),
("api_key_status realtime", {"cmd": "get_api_key_status", "data": {"type": "realtime"}}),
("start_real_time_chat",{"cmd": "start_real_time_chat"}),
("stop_real_time_chat", {"cmd": "stop_real_time_chat"}),
("get_real_time_chat_status", {"cmd": "get_real_time_chat_status"}),
),
("VR 录制",
("get_vr_status", {"cmd": "get_vr_status"}),
("start_vr_record", {"cmd": "start_vr_record"}),
("stop_vr_record", {"cmd": "stop_vr_record"}),
("cancel_vr_record", {"cmd": "cancel_vr_record"}),
),
("脚本 / 音乐",
("get_music_list", {"cmd": "get_music_list", "data": {}}),
("stop_run_node", {"cmd": "stop_run_node"}),
("update_data_pilot", {"cmd": "update_data_pilot"}),
),
]
def print_menu():
print()
n = 1
flat = []
for group, *items in COMMANDS:
print(f" {C.BOLD}{C.YELLOW}── {group} ──{C.RESET}")
for label, payload in items:
print(f" {C.CYAN}{n:2d}{C.RESET}. {label:32s} {C.DIM}{json.dumps(payload, ensure_ascii=False)[:80]}{C.RESET}")
flat.append((label, payload))
n += 1
print(f"\n {C.DIM}raw <json> 自定义 JSON 发送")
print(f" logger 连 Logger 推送 (8889)")
print(f" list/l 再显示菜单")
print(f" quit/q 退出{C.RESET}")
return flat
def fmt_json(obj):
return json.dumps(obj, ensure_ascii=False, indent=2)
async def recv_loop(ws, prefix=""):
try:
async for msg in ws:
try:
d = json.loads(msg)
print(f"\n{C.BLUE}← {prefix}{C.RESET} {fmt_json(d)}")
except json.JSONDecodeError:
print(f"\n{C.BLUE}← {prefix}{C.RESET} {msg}")
print(f"{C.GREEN}> {C.RESET}", end="", flush=True)
except websockets.exceptions.ConnectionClosed as e:
print(f"\n{C.RED}!! {prefix} 关闭 (code={e.code}){C.RESET}")
async def logger_loop(host):
url = f"ws://{host}:8889"
print(f"{C.MAGENTA}连 Logger {url}...{C.RESET}")
try:
async with websockets.connect(url) as ws:
print(f"{C.GREEN}✓ Logger 已连{C.RESET}")
async for msg in ws:
try:
d = json.loads(msg)
lvl = d.get('level', '?')
print(f"\n{C.MAGENTA}📝 [{lvl}] {d.get('module','')}.{d.get('function','')}: {d.get('message','')}{C.RESET}")
print(f"{C.GREEN}> {C.RESET}", end="", flush=True)
except Exception:
print(f"\n{C.MAGENTA}📝 {msg}{C.RESET}")
except Exception as e:
print(f"\n{C.RED}Logger 连失败: {e}{C.RESET}")
async def main():
host = sys.argv[1] if len(sys.argv) > 1 else "192.168.50.187"
port = int(sys.argv[2]) if len(sys.argv) > 2 else 8888
url = f"ws://{host}:{port}"
print(f"{C.BOLD}{C.CYAN}leju_head_lab CLI 调试器{C.RESET}")
print(f"连 {C.YELLOW}{url}{C.RESET} ...")
try:
ws = await websockets.connect(url, open_timeout=5)
except Exception as e:
print(f"{C.RED}连接失败: {e}{C.RESET}")
print(f"{C.DIM}排查: NX 上 server 起着吗? ss -tlnp | grep 8888{C.RESET}")
return
print(f"{C.GREEN}✓ 已连 {url}{C.RESET}")
flat = print_menu()
recv_task = asyncio.create_task(recv_loop(ws, "MAIN"))
logger_task = None
loop = asyncio.get_event_loop()
while True:
try:
cmd = await loop.run_in_executor(None, lambda: input(f"{C.GREEN}> {C.RESET}").strip())
except (EOFError, KeyboardInterrupt):
break
if not cmd:
continue
if cmd in ("q", "quit", "exit"):
break
if cmd in ("l", "list"):
flat = print_menu()
continue
if cmd == "logger":
if logger_task is None:
logger_task = asyncio.create_task(logger_loop(host))
else:
print(f"{C.DIM}Logger 已连{C.RESET}")
continue
if cmd.startswith("raw "):
try:
payload = json.loads(cmd[4:])
print(f"{C.YELLOW}→ {json.dumps(payload, ensure_ascii=False)}{C.RESET}")
await ws.send(json.dumps(payload))
except Exception as e:
print(f"{C.RED}JSON 错误: {e}{C.RESET}")
continue
try:
idx = int(cmd) - 1
if 0 <= idx < len(flat):
label, payload = flat[idx]
print(f"{C.YELLOW}→ [{label}] {json.dumps(payload, ensure_ascii=False)}{C.RESET}")
await ws.send(json.dumps(payload))
else:
print(f"{C.RED}超出范围 (1-{len(flat)}){C.RESET}")
except ValueError:
print(f"{C.RED}未识别 '{cmd}'. 输入数字, raw <json>, list, 或 quit{C.RESET}")
print(f"{C.DIM}断开...{C.RESET}")
recv_task.cancel()
if logger_task: logger_task.cancel()
try: await ws.close()
except: pass
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass