232 lines
12 KiB
Python
232 lines
12 KiB
Python
"""In-process, USB-only shadow policy slot for the original XGO Duck controller.
|
|
No Bridge imports, actuator writes, mode changes, calibration or firmware updates.
|
|
"""
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import os
|
|
import re
|
|
import socketserver
|
|
import threading
|
|
import tempfile
|
|
import time
|
|
import zipfile
|
|
from http.server import BaseHTTPRequestHandler
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import onnxruntime as ort
|
|
from rl_core import POLICY_INDEX
|
|
from shadow_core.config import validate_robot_manifest
|
|
from shadow_core.observations import build_observation
|
|
from shadow_core.state_machine import MicroduckStateMachine
|
|
|
|
DATA = Path(__file__).resolve().parents[1] / 'data' / 'usb-shadow'
|
|
SOCKET = DATA / 'api.sock'
|
|
ORIGINS = {'http://127.0.0.1:5173', 'http://localhost:5173'}
|
|
CONTROL_ORIGINS = {'http://127.0.0.1:19527', 'http://localhost:19527'}
|
|
ACTIONS = {'walk': None, 'stand': None, 'sitstand': 'sitToggle', 'kickL': 'kickL', 'kickR': 'kickR', 'roll': 'roll', 'groundpick': 'groundPick'}
|
|
LIMIT = 32 << 20
|
|
JOINTS = 'left_hip_yaw left_hip_roll left_hip_pitch left_knee left_ankle neck_pitch head_pitch head_yaw head_roll right_hip_yaw right_hip_roll right_hip_pitch right_knee right_ankle'.split()
|
|
|
|
|
|
class Preview:
|
|
def __init__(self, raw):
|
|
self.version = hashlib.sha256(raw).hexdigest()
|
|
self.sessions = {}
|
|
prefix = 'microduck_unoq/'
|
|
with zipfile.ZipFile(io.BytesIO(raw)) as z:
|
|
names = z.namelist()
|
|
if len(names) > 32 or len(names) != len(set(names)) or sum(i.file_size for i in z.infolist()) > LIMIT:
|
|
raise ValueError('部署包超出限制或有重名文件')
|
|
manifest = validate_robot_manifest(json.loads(z.read(prefix+'config/robot_manifest.json')))
|
|
if manifest['joint_names'] != JOINTS or manifest['command_size'] != 13:
|
|
raise ValueError('关节或指令布局不兼容')
|
|
self.pose = np.array(manifest['default_pose'], dtype=np.float32)
|
|
if not np.isfinite(self.pose).all():
|
|
raise ValueError('非有限默认关节角')
|
|
script_path = prefix+'config/custom_move_script.json'
|
|
script = json.loads(z.read(script_path)) if script_path in names else None
|
|
self.sm = MicroduckStateMachine(manifest, script)
|
|
allowed = {prefix+'config/robot_manifest.json', script_path}
|
|
for key, spec in manifest['skills'].items():
|
|
path = spec['path']
|
|
if not re.fullmatch(r'policies/[\w-]+\.onnx', path):
|
|
raise ValueError('策略文件路径不兼容')
|
|
allowed.add(prefix+path)
|
|
opts = ort.SessionOptions()
|
|
opts.intra_op_num_threads = opts.inter_op_num_threads = 1
|
|
session = ort.InferenceSession(z.read(prefix+path), sess_options=opts, providers=['CPUExecutionProvider'])
|
|
ins, outs = session.get_inputs(), session.get_outputs()
|
|
if len(ins)!=1 or len(outs)!=1 or ins[0].shape != [1,61] or outs[0].shape != [1,14] or ins[0].type != 'tensor(float)' or outs[0].type != 'tensor(float)':
|
|
raise ValueError(f'{key}: 需要 float32 [1,61] → [1,14]')
|
|
if not np.isfinite(session.run(None, {ins[0].name: np.zeros((1,61), np.float32)})[0]).all():
|
|
raise ValueError(f'{key}: 试推理失败')
|
|
self.sessions[key] = (session, ins[0].name)
|
|
if set(names) - allowed:
|
|
raise ValueError('仅支持策略热更新包,不接受固件或标定文件')
|
|
self.sm.request_stand(self.pose, soft_start_s=0.02) # virtual lifecycle only
|
|
self.last = np.zeros(14, np.float32)
|
|
self.steps, self.skill, self.error = 0, None, None
|
|
self.guard = threading.Lock()
|
|
self.stand_frames = 0
|
|
|
|
def select(self, key): # caller holds guard; this state is never used for motion
|
|
if key == 'walk':
|
|
self.stand_frames = 0
|
|
self.sm.request_stand(self.pose, soft_start_s=0.02)
|
|
return True
|
|
if key == 'stand':
|
|
if self.sm.skill_mode != 'walk' or self.sm.recovery_state: return False
|
|
self.last.fill(0)
|
|
self.stand_frames = 50 # preview the recovery model without forging an IMU fall
|
|
return True
|
|
if self.stand_frames or (key == 'sitstand' and self.sm.custom_slot in ('trick', 'script')): return False
|
|
return self.sm.trigger_action(ACTIONS[key])
|
|
|
|
def step(self, filt):
|
|
with self.guard:
|
|
d = self.sm.step(0.02, float(filt['grav'][2]))
|
|
key = d.policy_key
|
|
if self.stand_frames:
|
|
key = 'stand'
|
|
self.stand_frames -= 1
|
|
if d.zero_last_action or self.skill != key:
|
|
self.last.fill(0)
|
|
self.skill = key
|
|
if not key:
|
|
return
|
|
q, dq = [np.deg2rad(np.asarray(filt[k])[POLICY_INDEX]) for k in ('angles_deg','vels_deg')]
|
|
obs = build_observation(filt['gyro_rad'], filt['grav'], q, dq, self.last, d.command_13, self.pose)
|
|
sess, name = self.sessions[key]
|
|
out = sess.run(None, {name: obs.reshape(1,61)})[0][0]
|
|
if not np.isfinite(out).all():
|
|
raise ValueError('非有限策略输出')
|
|
self.last[:] = out # history only; deliberately never returned to the native target path
|
|
self.steps += 1
|
|
|
|
|
|
class Slot:
|
|
def __init__(self, controller):
|
|
self.c, self.current = controller, None
|
|
self.live = self.load_error = None
|
|
if getattr(controller,'has_live_hook',False):
|
|
from live_skills import LiveSkills
|
|
self.live = LiveSkills(self)
|
|
|
|
def idle(self): # caller holds native controller lock
|
|
c = self.c
|
|
return bool(c.mode in ('off','shadow') and c.feedback and not c.arm_pending and not c.feedback.enabled and time.monotonic()-c.rx_time < .15)
|
|
|
|
def replace(self, raw):
|
|
with self.c.lock:
|
|
if not self.idle(): raise ValueError('仅允许在反馈新鲜、扭矩关闭时更新')
|
|
generation = self.c.generation
|
|
candidate = Preview(raw) # never load while holding native control locks
|
|
with self.c.lock:
|
|
if not self.idle() or generation != self.c.generation: raise ValueError('更新期间设备状态已改变')
|
|
sample = self.c.filtered
|
|
if not sample: raise ValueError('缺少传感器反馈')
|
|
candidate.step(sample) # real observation before commit
|
|
with tempfile.NamedTemporaryFile(dir=DATA,delete=False) as f:
|
|
pending=Path(f.name)
|
|
try:
|
|
with pending.open('wb') as f:
|
|
f.write(raw); f.flush(); os.fsync(f.fileno())
|
|
with self.c.lock:
|
|
if not self.idle() or generation != self.c.generation: raise ValueError('更新期间设备状态已改变')
|
|
os.replace(pending,DATA/'active.zip'); self.current=candidate; self.load_error=None
|
|
finally: pending.unlink(missing_ok=True)
|
|
|
|
def select_shadow(self,key):
|
|
p=self.current
|
|
if not p or key not in ACTIONS: raise ValueError('尚未加载或未知技能')
|
|
with p.guard, self.c.lock:
|
|
if not (self.current is p and self.idle() and self.c.mode=='shadow' and self.c.feedback.imu_ok and not p.error and key in p.sessions):
|
|
raise ValueError('需要有效反馈和无扭矩预览模式')
|
|
if not p.select(key): raise ValueError('当前预览状态不能切换技能')
|
|
|
|
def status(self):
|
|
with self.c.lock:
|
|
p = self.current
|
|
return dict(hal='xgoduck-shadow', lifecycle='IDLE' if self.idle() else 'BUSY', native_mode=self.c.mode,
|
|
imu_ok=bool(self.c.feedback and self.c.feedback.imu_ok), torque_enabled=bool(not self.c.feedback or self.c.feedback.enabled),
|
|
live_supported=bool(self.live), generation=self.c.generation, live_skill=self.live.skill if self.live and self.c.mode=='imported_live' else None,
|
|
loaded_skills=sorted(p.sessions) if p else [], version=p.version if p else None,
|
|
shadow_skill=p.skill if p else None, shadow_steps=p.steps if p else 0, shadow_error=p.error if p else self.load_error)
|
|
|
|
def tick(self, filt):
|
|
p = self.current
|
|
if p and not p.error:
|
|
try: p.step(filt)
|
|
except Exception as exc: p.error = str(exc)
|
|
return p is not None
|
|
|
|
|
|
def attach(controller,ui=None):
|
|
slot = Slot(controller)
|
|
DATA.mkdir(mode=0o700,exist_ok=True)
|
|
saved=DATA/'active.zip'
|
|
if saved.exists():
|
|
try:
|
|
if not 0<saved.stat().st_size<=LIMIT: raise ValueError('本地策略包大小异常')
|
|
slot.current=Preview(saved.read_bytes()) # never restores motor enable/session
|
|
except Exception as exc: slot.load_error=str(exc)
|
|
if ui is not None:
|
|
from hotspot_skills import register
|
|
register(ui,slot)
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def answer(self, code, obj):
|
|
body=json.dumps(obj).encode()
|
|
self.send_response(code)
|
|
if self.headers.get('Origin') in ORIGINS | CONTROL_ORIGINS:
|
|
self.send_header('Access-Control-Allow-Origin', self.headers['Origin'])
|
|
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
|
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
|
|
self.send_header('Cache-Control','no-store')
|
|
self.send_header('Content-Type','application/json'); self.send_header('Content-Length',str(len(body)))
|
|
self.end_headers(); self.wfile.write(body)
|
|
def do_OPTIONS(self): self.answer(200,{})
|
|
def do_GET(self):
|
|
if self.path != '/api/status': return self.answer(404,{})
|
|
self.answer(200,slot.status())
|
|
def do_POST(self):
|
|
is_skill = self.path.startswith('/api/shadow/')
|
|
is_live = self.path == '/api/live'
|
|
permitted = CONTROL_ORIGINS if is_live else ORIGINS | CONTROL_ORIGINS if is_skill else ORIGINS
|
|
if self.headers.get('Origin') not in permitted or self.headers.get('Host') not in ('127.0.0.1:18000','localhost:18000'):
|
|
return self.answer(403,{'error':'来源不受信任'})
|
|
if is_live:
|
|
try:
|
|
if not slot.live or self.headers.get('Content-Type') != 'application/json': raise ValueError('不支持真机联调请求')
|
|
n=int(self.headers.get('Content-Length',0))
|
|
if not 0<n<=1024: raise ValueError('无效请求')
|
|
self.connection.settimeout(1)
|
|
data=slot.live.request(json.loads(self.rfile.read(n)))
|
|
except (KeyError,TypeError,ValueError,OSError) as exc: return self.answer(409,{'error':str(exc)})
|
|
return self.answer(200,{'ok':True,**data,'status':slot.status()})
|
|
if is_skill:
|
|
key = self.path.removeprefix('/api/shadow/')
|
|
if key not in ACTIONS: return self.answer(404,{'error':'未知技能'})
|
|
try: slot.select_shadow(key)
|
|
except ValueError as exc: return self.answer(409,{'error':str(exc)})
|
|
return self.answer(200,{'ok':True,'status':slot.status()})
|
|
if self.path != '/api/deploy?overwrite_profile=0' or self.headers.get('Content-Type') != 'application/zip':
|
|
return self.answer(400,{'error':'只接受策略部署包,不支持覆盖原机标定'})
|
|
try:
|
|
n=int(self.headers.get('Content-Length',0))
|
|
if not 0<n<=LIMIT: raise ValueError('部署包大小无效')
|
|
self.connection.settimeout(30)
|
|
raw=self.rfile.read(n)
|
|
if len(raw)!=n: raise ValueError('部署包不完整')
|
|
slot.replace(raw)
|
|
except Exception as exc: return self.answer(400,{'ok':False,'error':str(exc)})
|
|
self.answer(200,{'ok':True,'status':slot.status()})
|
|
def log_message(self,*args): pass
|
|
DATA.mkdir(mode=0o700,exist_ok=True)
|
|
SOCKET.unlink(missing_ok=True)
|
|
server=socketserver.UnixStreamServer(str(SOCKET),Handler)
|
|
os.chmod(SOCKET,0o600)
|
|
threading.Thread(target=server.serve_forever,name='usb-shadow-api',daemon=True).start()
|
|
return slot
|