315 lines
16 KiB
Python

"""Local calibration UI, with the existing simulation page preserved at /."""
import argparse
import base64
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import math
import mimetypes
from pathlib import Path
import secrets
import threading
import time
from urllib.parse import unquote, urlsplit
import uuid
ROOT = Path(__file__).resolve().parent.parent
VERIFY = ROOT / 'deployment/x5_mg90s_20261109_verify'
SIM = ROOT / 'hardware_design/x5_sg90_v1/simulation'
DATA = VERIFY / 'web-calibration'
EVIDENCE = {
'hardware-calibration.json', 'imu_sampling/mounting-estimate.json',
'imu_sampling/RESULT.md', 'camera-angle-1/RESULT.md',
'camera-angle-1/movement.mp4', 'camera-angle-1/angle-result.json',
'camera-angle-1/execution-result.json', 'camera-angle-1/manifest.json',
*('camera-angle-1/frame-' + t + 's.png' for t in ('2.5', '3.5', '4.0', '5.5', '7.5', '8.5')),
}
def read_json(path, default=None):
return json.loads(path.read_text()) if path.exists() else default
def atomic_json(path, value):
tmp = path.with_suffix('.tmp')
tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2))
tmp.replace(path)
def history():
sources = ['hardware-calibration.json', 'imu_sampling/mounting-estimate.json',
'camera-angle-1/angle-result.json', 'camera-angle-1/execution-result.json']
imu = {}
for pose in ('stationary', 'front-up', 'left-up'):
rel = 'imu_sampling/' + pose + '-1.json'
data = read_json(VERIFY / rel, {})
imu[pose] = {k: data.get(k) for k in ('status', 'summary', 'configuration_restored')}
imu[pose]['source'] = rel
sources.append(rel)
return {'calibration': read_json(VERIFY / sources[0], {}),
'mounting': read_json(VERIFY / sources[1], {}),
'camera': read_json(VERIFY / sources[2], {}), 'imu': imu,
'provenance': {p: hashlib.sha256((VERIFY / p).read_bytes()).hexdigest()
for p in sources if (VERIFY / p).exists()},
'kind': 'historical_evidence', 'applied_to_motor_control': False}
class App:
def __init__(self, bridge, data=DATA):
self.bridge, self.data = bridge, data
data.mkdir(parents=True, exist_ok=True)
self.lock = threading.RLock()
self.token = secrets.token_urlsafe(32)
self.historical = history()
self.artifacts = read_json(data / 'artifacts.json', {'frames': [], 'observations': []})
def save(self):
atomic_json(self.data / 'artifacts.json', self.artifacts)
def state(self):
with self.lock:
state = self.bridge.status()
return {**state, 'recovery_ready': state['device'].get('recovery_ready') is True,
'history': self.historical,
**self.artifacts, 'csrf_token': self.token, 'server_time': time.time()}
def frame(self, p):
if p.get('role') not in ('before', 'after', 'reference', 'phase'):
raise ValueError('Invalid frame role')
phase_event = None
if p['role'] == 'phase':
job = self.bridge.status().get('job')
if (not job or job['id'] != p.get('job_id') or job['type'] != 'servo'
or job['status'] != 'running' or job.get('phase') != p.get('phase')
or p.get('phase') not in ('initial_command', 'increment', 'return_command')):
raise ValueError('阶段已切换或任务已结束,不能把当前图绑定到旧阶段')
phase_event = next((e for e in reversed(job.get('events', []))
if e.get('event') == 'phase' and e.get('phase') == p['phase']), None)
if not phase_event or time.time() - phase_event['received_at'] < 0.75:
raise ValueError('阶段尚未保持足够时间')
if p['role'] in ('before', 'reference') and p.get('job_id'):
raise ValueError('Before/reference frames cannot be pre-bound to a job')
if p['role'] == 'after':
job = next((j for j in self.bridge.export().get('jobs', []) if j['id'] == p.get('job_id')), None)
if not job or job['type'] not in ('servo', 'recovery') or job['status'] not in ('completed', 'stopped', 'failed'):
raise ValueError('后图必须关联已结束的舵机任务')
encoded = p.get('image', '')
if not isinstance(encoded, str) or not encoded.startswith('data:image/jpeg;base64,'):
raise ValueError('Expected JPEG data URL')
raw = base64.b64decode(encoded.split(',', 1)[1], validate=True)
if len(raw) > 2_000_000 or not raw.startswith(b'\xff\xd8\xff') or not raw.endswith(b'\xff\xd9'):
raise ValueError('Invalid or oversized JPEG')
ident = str(uuid.uuid4())
frame = {'id': ident, 'role': p['role'], 'job_id': p.get('job_id'),
'captured_at': time.time(), 'timestamp_kind': 'server_receive_time',
'sha256': hashlib.sha256(raw).hexdigest(), 'url': '/calibration/frames/' + ident + '.jpg'}
if phase_event:
frame.update(phase=p['phase'], phase_event=phase_event, hardware_synchronized=False)
with self.lock:
(self.data / (ident + '.jpg')).write_bytes(raw)
self.artifacts['frames'].append(frame)
self.save()
return frame
def start(self, p):
with self.lock:
frame = None
if p.get('type') == 'recovery' and self.bridge.status()['device'].get('recovery_ready') is not True:
raise ValueError('两轴目标角和行程尚未完成标定,恢复试验未启用')
if p.get('type') in ('servo', 'recovery'):
frame = next((f for f in self.artifacts['frames']
if f['id'] == p.get('before_frame_id')), None)
if not frame or frame['role'] != 'before' or frame.get('job_id') or time.time() - frame['captured_at'] > 15:
raise ValueError('请重新拍摄当前完整取景;前图已过期或已用于另一动作。')
job = self.bridge.start(p)
if frame:
frame['job_id'] = job['id']
self.save()
return job
def observation(self, p):
if p.get('physical_result') not in ('moved', 'no_motion', 'uncertain'):
raise ValueError('Invalid physical observation')
jobs = self.bridge.export().get('jobs', [])
if not any(j.get('id') == p.get('job_id') for j in jobs):
raise ValueError('Unknown job')
angles = p.get('angles') or {}
if not isinstance(angles, dict) or angles.keys() - {'before', 'after'}:
raise ValueError('Invalid angle observations')
for role, a in angles.items():
if a is None:
continue
if not isinstance(a, dict):
raise ValueError('Invalid angle record')
angle = a.get('angle_deg')
if angle is not None and (type(angle) not in (int, float) or not math.isfinite(angle) or abs(angle) > 360):
raise ValueError('Invalid projected angle')
if not any(f['id'] == a.get('frame_id') and f.get('job_id') == p['job_id']
and f['role'] == role for f in self.artifacts['frames']):
raise ValueError('Angle must reference this job and frame role')
points = a.get('points', [])
if not isinstance(points, list) or len(points) not in (0, 2):
raise ValueError('Expected two image points')
for point in points:
if not isinstance(point, dict) or any(type(point.get(k)) not in (int, float)
or not math.isfinite(point[k]) or point[k] < 0 for k in ('x', 'y')):
raise ValueError('Image coordinates must be finite nonnegative numbers')
note = p.get('note', '')
if not isinstance(note, str) or len(note) > 2000:
raise ValueError('Note too long')
result = {'job_id': p['job_id'], 'physical_result': p['physical_result'],
'angles': angles, 'note': note, 'recorded_at': time.time(),
'source': 'user_observation', 'angle_kind': '2D_projection_not_joint_angle'}
with self.lock:
self.artifacts['observations'].append(result)
self.save()
return result
def export(self):
with self.lock:
return {'schema': 'x5_calibration_web_v1', 'exported_at': time.time(),
'history': self.historical, **self.bridge.export(), **self.artifacts,
'policy_ready': False, 'parameters_applied': False,
'limits': ['1500us is not a verified upright reference',
'Image angles are 2D projections; no calibrated joint gain',
'X5 servo supply margin and full travel remain unverified']}
def report(self):
data = self.export()
return '# X5 实机标定记录\n\n历史证据、板端指令结果及用户观察分别保存。参数均未应用到闭环控制。\n\n' + \
'1500 微秒不等于长杆竖直;画面角度不是关节角。当前不具备实机爬起条件。\n\n' + \
'```json\n' + json.dumps(data, ensure_ascii=False, indent=2) + '\n```\n'
def handler_for(app, port):
hosts = {f'127.0.0.1:{port}', f'localhost:{port}'}
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
print(self.command, urlsplit(self.path).path, fmt % args, flush=True)
def reply(self, code, body, kind='application/json; charset=utf-8'):
if not isinstance(body, bytes):
body = json.dumps(body, ensure_ascii=False, allow_nan=False).encode()
self.send_response(code)
self.send_header('Content-Type', kind)
self.send_header('Content-Length', str(len(body)))
self.send_header('Cache-Control', 'no-store')
self.send_header('X-Content-Type-Options', 'nosniff')
self.send_header('X-Frame-Options', 'DENY')
self.send_header('Permissions-Policy', 'camera=(self), microphone=()')
self.end_headers()
try:
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError):
pass
def trusted(self):
if self.headers.get('Host') not in hosts or self.headers.get('Origin') not in {None, *('http://' + h for h in hosts)}:
self.reply(403, {'error': '仅允许本机同源访问'})
return False
if self.command == 'POST' and (self.headers.get('Sec-Fetch-Site') == 'cross-site' or
not secrets.compare_digest(self.headers.get('X-Cal-Token', ''), app.token)):
self.reply(403, {'error': '请从当前标定页面操作;请求令牌无效'})
return False
return True
def file(self, file):
if not file.is_file():
return self.reply(404, {'error': '文件不存在'})
self.reply(200, file.read_bytes(), mimetypes.guess_type(file.name)[0] or 'application/octet-stream')
def do_GET(self):
if not self.trusted():
return
path = unquote(urlsplit(self.path).path)
if path in ('/calibration', '/calibration/'):
return self.file(ROOT / 'calibration/index.html')
if path == '/api/calibration/state':
return self.reply(200, app.state())
if path == '/api/calibration/export':
return self.reply(200, app.export())
if path == '/api/calibration/report':
return self.reply(200, app.report().encode(), 'text/markdown; charset=utf-8')
if path.startswith('/calibration/evidence/'):
name = path.removeprefix('/calibration/evidence/')
return self.file(VERIFY / name) if name in EVIDENCE else self.reply(404, {'error': '未列入证据白名单'})
if path.startswith('/calibration/frames/'):
name = path.removeprefix('/calibration/frames/')
with app.lock:
allowed = {f['id'] + '.jpg' for f in app.artifacts['frames']}
return self.file(app.data / name) if name in allowed else self.reply(404, {'error': '未知照片'})
target = (SIM / (path.lstrip('/') or 'index.html')).resolve()
if target.is_relative_to(SIM) and not any(p.startswith('.') for p in Path(path).parts):
return self.file(target)
self.reply(404, {'error': '未知路径'})
def do_POST(self):
if not self.trusted():
return
try:
size = int(self.headers.get('Content-Length', '0'))
if self.headers.get('Transfer-Encoding') or not 0 < size <= 3_000_000:
return self.reply(413, {'error': '请求体大小无效'})
if self.headers.get_content_type() != 'application/json':
raise ValueError('Expected application/json')
def invalid_constant(value):
raise ValueError('Non-finite JSON number: ' + value)
payload = json.loads(self.rfile.read(size), parse_constant=invalid_constant)
if not isinstance(payload, dict):
raise ValueError('Expected JSON object')
action = urlsplit(self.path).path
methods = {'/api/calibration/start': app.start, '/api/calibration/frame': app.frame,
'/api/calibration/observation': app.observation,
'/api/calibration/heartbeat': lambda p: app.bridge.heartbeat(p.get('id'))}
if action in methods:
return self.reply(200, methods[action](payload))
if action in ('/api/calibration/refresh', '/api/calibration/stop'):
if payload:
raise ValueError('No parameters allowed')
result = app.bridge.refresh() if action.endswith('refresh') else app.bridge.stop()
return self.reply(200, result)
self.reply(404, {'error': '未知接口'})
except (ValueError, TypeError, KeyError) as exc:
self.reply(400, {'error': str(exc)})
except RuntimeError as exc:
self.reply(409, {'error': str(exc)})
except Exception as exc:
self.reply(500, {'error': type(exc).__name__ + ': ' + str(exc)})
return Handler
def maintain_connection(bridge):
while True:
if not bridge.prepared:
try:
bridge.prepare()
except Exception as exc:
print('Runner preparation failed; will retry:', exc, flush=True)
bridge.refresh()
time.sleep(5)
def main():
from calibration.bridge import Bridge
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--port', type=int, default=8766)
parser.add_argument('--debug-only', action='store_true', help='Allow IMU and single-servo tasks only')
args = parser.parse_args()
bridge = Bridge(debug_only=args.debug_only)
app = App(bridge)
http = ThreadingHTTPServer(('127.0.0.1', args.port), handler_for(app, args.port))
http.daemon_threads = True
threading.Thread(target=maintain_connection, args=(bridge,), daemon=True).start()
print(f'Calibration: http://127.0.0.1:{args.port}/calibration (no automatic motion)', flush=True)
try:
http.serve_forever()
finally:
bridge.stop()
http.server_close()
if __name__ == '__main__':
main()