170 lines
6.2 KiB
Python
170 lines
6.2 KiB
Python
"""模拟 Android 设备(Bridge):用于在没有真实手机时联调验证服务端。
|
||
|
||
行为:
|
||
1. 连接服务器 /ws/device,发送 register
|
||
2. 每 10 秒发送 event.heartbeat
|
||
3. 响应 shell.exec(本地执行)与 device.info
|
||
4. 断线指数退避重连(1s → 2s → ... → 30s)
|
||
|
||
用法:
|
||
python scripts/mock_device.py --server ws://127.0.0.1:8000/ws/device --device-id mock-001
|
||
DEVICE_TOKEN=xxx python scripts/mock_device.py # 需要认证时
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import asyncio
|
||
import json
|
||
import os
|
||
import platform
|
||
import random
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
import uuid
|
||
|
||
try:
|
||
import websockets
|
||
except ImportError:
|
||
print("缺少依赖: pip install websockets", file=sys.stderr)
|
||
sys.exit(1)
|
||
|
||
SHELL_TIMEOUT = 30
|
||
|
||
|
||
class MockDevice:
|
||
def __init__(self, server_url: str, device_id: str, device_name: str):
|
||
self.server_url = server_url
|
||
self.device_id = device_id
|
||
self.device_name = device_name
|
||
self.battery = random.randint(60, 95)
|
||
|
||
# ---------- 消息处理 ----------
|
||
|
||
async def handle_command(self, ws, msg: dict) -> None:
|
||
action = msg.get("action", "")
|
||
mid = msg.get("id", "")
|
||
payload = msg.get("payload") or {}
|
||
|
||
if action == "shell.exec":
|
||
cmd = payload.get("cmd", "")
|
||
print(f"[cmd] {cmd}")
|
||
try:
|
||
proc = await asyncio.create_subprocess_shell(
|
||
cmd,
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.STDOUT,
|
||
)
|
||
try:
|
||
out, _ = await asyncio.wait_for(proc.communicate(), timeout=SHELL_TIMEOUT)
|
||
await self.send_response(ws, mid, action, "success",
|
||
{"exitCode": proc.returncode, "output": out.decode(errors="replace")})
|
||
except asyncio.TimeoutError:
|
||
proc.kill()
|
||
await self.send_response(ws, mid, action, "error",
|
||
{"code": 1002, "message": "shell 执行超时"})
|
||
except Exception as e:
|
||
await self.send_response(ws, mid, action, "error", {"code": 1001, "message": str(e)})
|
||
|
||
elif action == "device.info":
|
||
info = {
|
||
"deviceId": self.device_id,
|
||
"deviceName": self.device_name,
|
||
"osVersion": f"Mock {platform.system()} {platform.release()}",
|
||
"sdkVersion": 34,
|
||
"arch": platform.machine(),
|
||
"python": platform.python_version(),
|
||
"battery": self.battery,
|
||
}
|
||
await self.send_response(ws, mid, action, "success", info)
|
||
|
||
elif action == "atx.version":
|
||
# 模拟 Bridge 对纯文本响应的包装(atx-agent /version 返回 "0.10.1")
|
||
await self.send_response(ws, mid, action, "success", {"raw": "0.10.1"})
|
||
|
||
else:
|
||
await self.send_response(ws, mid, action, "error",
|
||
{"code": 1001, "message": f"未知 action: {action}"})
|
||
|
||
async def send_response(self, ws, mid: str, action: str, status: str, payload: dict) -> None:
|
||
await ws.send(json.dumps({
|
||
"id": mid, "type": "response", "action": action,
|
||
"status": status, "payload": payload,
|
||
}, ensure_ascii=False))
|
||
|
||
async def send_heartbeat(self, ws) -> None:
|
||
self.battery = max(5, self.battery - random.choice([0, 0, 0, 1]))
|
||
await ws.send(json.dumps({
|
||
"id": uuid.uuid4().hex,
|
||
"type": "event",
|
||
"action": "event.heartbeat",
|
||
"deviceId": self.device_id,
|
||
"timestamp": int(time.time() * 1000),
|
||
"payload": {
|
||
"battery": self.battery,
|
||
"cpu": random.randint(5, 40),
|
||
"memory": random.randint(35, 70),
|
||
"storage": 55,
|
||
},
|
||
}))
|
||
|
||
# ---------- 主循环 ----------
|
||
|
||
async def run(self) -> None:
|
||
backoff = 1
|
||
while True:
|
||
try:
|
||
print(f"[conn] 连接 {self.server_url}")
|
||
async with websockets.connect(self.server_url) as ws:
|
||
await ws.send(json.dumps({
|
||
"type": "register",
|
||
"deviceId": self.device_id,
|
||
"deviceName": self.device_name,
|
||
"osVersion": f"Mock {platform.system()} {platform.release()}",
|
||
"sdkVersion": 34,
|
||
"token": os.environ.get("DEVICE_TOKEN", ""),
|
||
}, ensure_ascii=False))
|
||
print("[conn] 已注册,开始心跳")
|
||
backoff = 1
|
||
|
||
async def heartbeat():
|
||
while True:
|
||
await asyncio.sleep(10)
|
||
await self.send_heartbeat(ws)
|
||
|
||
hb_task = asyncio.create_task(heartbeat())
|
||
try:
|
||
async for raw in ws:
|
||
try:
|
||
msg = json.loads(raw)
|
||
except (json.JSONDecodeError, TypeError):
|
||
continue
|
||
if msg.get("type") == "command":
|
||
await self.handle_command(ws, msg)
|
||
finally:
|
||
hb_task.cancel()
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as e:
|
||
print(f"[conn] 断开: {e},{backoff}s 后重连")
|
||
await asyncio.sleep(backoff)
|
||
backoff = min(backoff * 2, 30)
|
||
|
||
|
||
def main() -> None:
|
||
parser = argparse.ArgumentParser(description="模拟 Android 设备 Bridge")
|
||
parser.add_argument("--server", default="ws://127.0.0.1:8000/ws/device")
|
||
parser.add_argument("--device-id", default=f"mock-{uuid.uuid4().hex[:6]}")
|
||
parser.add_argument("--device-name", default="Mock Phone")
|
||
args = parser.parse_args()
|
||
|
||
device = MockDevice(args.server, args.device_id, args.device_name)
|
||
try:
|
||
asyncio.run(device.run())
|
||
except KeyboardInterrupt:
|
||
print("\n[exit] 模拟设备退出")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|