cosmo/terminal/tools/terminal_sim.py

234 lines
9.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""
终端配对流程模拟器:用 ESP32-S3 完全相同的 HTTP 调用序列跑通全流程。
python3 terminal_sim.py pair # 申请配对码 -> 轮询 -> 拿长期 token -> 拉取关注天体
python3 terminal_sim.py follows # 模拟重启:只用本地保存的 token(等价于 NVS)
--api 默认 http://127.0.0.1:8000/api,--device 默认模拟一个 MAC 地址。
token 保存在 terminal/tools/.terminal_nvs.json,模拟设备的 NVS 分区。
"""
import argparse
import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime
from pathlib import Path
# 设备侧不走任何系统代理,模拟器保持一致,避免 HTTP_PROXY 把 127.0.0.1 请求转发掉
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
NVS_FILE = Path(__file__).with_name(".terminal_nvs.json")
DEFAULT_DEVICE = "ESP32S3-AABBCCDDEEFF"
POLL_SECONDS = 2
def call(api: str, method: str, path: str, *, json_body=None, params=None, token=None, timeout=20):
url = api.rstrip("/") + path
if params:
url += "?" + urllib.parse.urlencode(params)
data = json.dumps(json_body).encode() if json_body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Content-Type", "application/json")
if token:
req.add_header("Authorization", f"Bearer {token}")
try:
with OPENER.open(req, timeout=timeout) as resp:
body = resp.read().decode()
return resp.status, json.loads(body) if body else None
except urllib.error.HTTPError as exc:
raw = exc.read().decode()
try:
return exc.code, json.loads(raw)
except json.JSONDecodeError:
return exc.code, {"detail": raw}
except urllib.error.URLError as exc:
sys.exit(f"无法访问 {url}: {exc.reason}(请确认后端已启动,或用 --api 指定地址)")
def read_nvs() -> dict:
if NVS_FILE.exists():
return json.loads(NVS_FILE.read_text())
return {}
def write_nvs(data: dict) -> None:
NVS_FILE.write_text(json.dumps(data, indent=2))
# ---------------------------------------------------------------- render
def render_pair_screen(code: str, expires_in: int, device_id: str) -> str:
"""What the 2.4寸 TFT shows while waiting for the user to bind."""
minutes, seconds = divmod(max(0, expires_in), 60)
return "\n".join(
[
"+------------------------------+",
"| NET: ONLINE PWR: 89% |",
"| |",
"| DEVICE BINDING |",
"| |",
f"|{(code[:3] + chr(32) + code[3:]):^30}|",
"| |",
f"| 等待网页端输入配对码 |",
f"| 剩余 {minutes:02d}:{seconds:02d} DEV {device_id[-4:]} |",
"| |",
"| [ORBIT] [COMM] [SYS]|",
"+------------------------------+",
]
)
def render_follows(payload: dict) -> str:
"""Text preview of the follow list page + the detail page of the first body."""
bodies = payload["bodies"]
lines = [
"",
"=== 关注天体列表页 (SUBSCRIBED) ===",
f"NET: ONLINE USER: {payload['username']} 服务器时间: {payload['server_time'][:19]}",
f"共 {payload['follow_count']} 个关注天体",
"",
]
for body in bodies:
pos = body.get("position")
dist = f"DIST: {pos['distance_au']:.2f} AU" if pos else "DIST: -- AU"
zh = f" / {body['name_zh']}" if body.get("name_zh") else ""
events = body.get("events") or []
lines.append(f" [ON ] {body['name']}{zh} ({body['type']})")
lines.append(f" {dist}")
for event in events[:2]:
flag = "将要发生" if event["is_upcoming"] else "已发生"
lines.append(f" · {event['title']} {event['event_time'][:10]} [{flag}]")
if not events:
lines.append(" · 暂无事件记录")
lines.append("")
if bodies:
body = bodies[0]
pos = body.get("position")
lines.append(f"=== 天体详情页 (DETAIL): TARGET: {body['name']} ({body['type'].upper()}) ===")
if pos:
speed = f"{pos['speed_km_s']:.1f}" if pos.get("speed_km_s") is not None else "--"
lines += [
f"POS (AU) X: {pos['x']:.2f} Y: {pos['y']:.2f} Z: {pos['z']:.2f}",
f"VEL (KM/S) VX: {pos['vx'] if pos['vx'] is not None else '--'}"
f" VY: {pos['vy'] if pos['vy'] is not None else '--'}"
f" VZ: {pos['vz'] if pos['vz'] is not None else '--'}",
f"DIST: {pos['distance_au']:.3f} AU SPEED: {speed} km/s",
f"数据时间(UTC): {pos['time'][:19]} 来源: {pos['source']}",
]
else:
lines.append("POS/VEL: 暂无位置数据")
if body.get("description"):
lines.append(f"INFO: {body['description']}")
lines.append("EVENTS:")
for event in body.get("events") or []:
lines.append(f" {event['event_time'][:10]} {event['title']} ({event['event_type']})")
if not body.get("events"):
lines.append(" --")
lines.append("")
lines.append("[ORBIT] [COMM] [SYS]")
return "\n".join(lines)
# ---------------------------------------------------------------- commands
def cmd_pair(args) -> None:
nvs = read_nvs()
device_id = args.device or nvs.get("device_id") or DEFAULT_DEVICE
status_code, data = call(
args.api, "POST", "/terminal/pair/code", json_body={"device_id": device_id, "name": "Cosmo Terminal"}
)
if status_code != 200:
sys.exit(f"申请配对码失败 {status_code}: {data}")
if data["status"] == "bound":
print(f"设备已绑定到 {data['username']},无需重新配对(如需换人绑定,请先在网页端解绑)。")
cmd_follows(args)
return
code = data["code"]
if not code:
sys.exit(f"服务端没有返回配对码: {data}")
deadline = time.time() + args.wait
print(f"设备 ID: {device_id}\n请在网页端『绑定设备』输入下面的 6 位码({args.wait}s 内有效于轮询):\n")
print(render_pair_screen(code, data["expires_in"], device_id))
while time.time() < deadline:
time.sleep(POLL_SECONDS)
status_code, data = call(
args.api, "GET", "/terminal/pair/status", params={"device_id": device_id, "code": code}
)
if status_code != 200:
sys.exit(f"轮询失败 {status_code}: {data}")
state = data["status"]
if state == "pending":
print(f" ... 等待绑定中(剩余 {data['expires_in']}s)", flush=True)
continue
if state == "expired":
print("配对码已过期,重新运行本命令获取新码。")
return
if state in ("unknown", "invalid_code", "unbound"):
sys.exit(f"配对状态异常: {data}")
if state == "bound":
print(f"\nLINK ESTABLISHED — 已绑定用户: {data['username']}")
token = data.get("access_token")
if token:
write_nvs(
{
"device_id": device_id,
"access_token": token,
"username": data["username"],
"token_expires_at": data.get("expires_at"),
"saved_at": datetime.utcnow().isoformat() + "Z",
}
)
print(f"长期 token 已写入 NVS({NVS_FILE.name}),有效期见 token_expires_at。")
else:
print("该设备此前已领取过 token,继续使用本地 NVS 中的 token。")
cmd_follows(args)
return
print(f"\n超时 {args.wait}s 未检测到绑定,退出。")
def cmd_follows(args) -> None:
nvs = read_nvs()
token = nvs.get("access_token")
if not token:
sys.exit("NVS 中没有 token,请先运行: python3 terminal_sim.py pair")
status_code, data = call(args.api, "GET", "/terminal/follows", token=token)
if status_code == 401:
sys.exit(f"token 已失效(很可能被解绑):{data['detail']}\n请重新运行 pair。")
if status_code != 200:
sys.exit(f"拉取失败 {status_code}: {data}")
print(render_follows(data))
raw = Path(__file__).with_name("last_follows.json")
raw.write_text(json.dumps(data, ensure_ascii=False, indent=2))
print(f"\n原始响应已保存: {raw}")
def main() -> None:
parser = argparse.ArgumentParser(description="Cosmo ESP32-S3 终端配对/数据流模拟器")
parser.add_argument("--api", default="http://127.0.0.1:8000/api")
parser.add_argument("--device", default=None, help="设备 ID,默认使用 NVS 中的值")
parser.add_argument("--wait", type=int, default=180, help="等待绑定的最长秒数")
parser.add_argument("command", choices=["pair", "follows"], nargs="?", default="pair")
args = parser.parse_args()
if args.command == "pair":
cmd_pair(args)
else:
cmd_follows(args)
if __name__ == "__main__":
main()