from __future__ import annotations import copy import json from email.parser import BytesParser from email.policy import default as email_default_policy from pathlib import Path from typing import Any from core.controller import MicroduckController from core.deploy_service import DeployService STATIC_DIR = Path(__file__).resolve().parent / "static" def load_index_html() -> bytes: path = STATIC_DIR / "index.html" if not path.is_file(): return b"

Microduck controller UI missing

" return path.read_bytes() def parse_bool_flag(raw: str | None) -> bool: if raw is None: return False return raw.strip().lower() in ("1", "true", "yes", "on") def extract_deploy_payload( content_type: str, body: bytes, query_overwrite: str | None = None, ) -> tuple[bytes, bool]: overwrite = parse_bool_flag(query_overwrite) ctype = (content_type or "").lower() if "multipart/form-data" in ctype: raw_msg = f"Content-Type: {content_type}\r\nMIME-Version: 1.0\r\n\r\n".encode("latin1") + body msg = BytesParser(policy=email_default_policy).parsebytes(raw_msg) if not msg.is_multipart(): raise ValueError("Malformed multipart/form-data upload") zip_bytes: bytes | None = None for part in msg.iter_parts(): field = part.get_param("name", header="content-disposition") payload = part.get_payload(decode=True) or b"" if field in ("bundle", "file", "zip") and payload: zip_bytes = payload elif field == "overwrite_profile": overwrite = parse_bool_flag(payload.decode("utf-8", errors="ignore")) if not zip_bytes: raise ValueError("Multipart upload missing 'bundle' zip field") return zip_bytes, overwrite return body, overwrite def build_status_payload(controller: MicroduckController, deploy_service: DeployService) -> dict[str, Any]: st = controller.get_status() st["last_deploy"] = copy.deepcopy(deploy_service.last_deploy) if deploy_service.last_deploy else None return st def handle_ws_message(controller: MicroduckController, msg: dict[str, Any]) -> dict[str, Any] | None: kind = msg.get("type") if kind == "input": controller.set_remote_input( norm_x=float(msg.get("vx", 0.0)), norm_wz=float(msg.get("wz", 0.0)), speed_scale=float(msg["speed_scale"]) if "speed_scale" in msg else None, ) return None if kind == "head": controller.set_head_target( float(msg.get("neck_pitch", 0.0)), float(msg.get("head_pitch", 0.0)), float(msg.get("head_yaw", 0.0)), float(msg.get("head_roll", 0.0)), ) return None if kind == "stand": try: controller.request_stand() return {"type": "ack", "event": "stand"} except RuntimeError as exc: return {"type": "error", "error": str(exc)} if kind == "estop": controller.emergency_stop() return {"type": "ack", "event": "estop"} if kind == "action": action = str(msg.get("action", "")) ok = controller.trigger_action(action) return {"type": "ack", "event": "action", "action": action, "ok": ok} if kind == "settings": if "auto_stand_on_fall" in msg: controller.set_auto_stand_on_fall(bool(msg["auto_stand_on_fall"])) if "speed_scale" in msg: controller.set_speed_scale(float(msg["speed_scale"])) return {"type": "ack", "event": "settings"} if kind == "ping": return {"type": "pong", "t": msg.get("t")} return None def dispatch_api_get( path: str, controller: MicroduckController, deploy_service: DeployService, ) -> tuple[int, dict[str, Any]]: if path == "/api/status": return 200, build_status_payload(controller, deploy_service) if path == "/api/profile": return 200, {"ok": True, "profile": copy.deepcopy(controller.profile)} return 404, {"ok": False, "error": f"Unknown GET endpoint: {path}"} def dispatch_api_post( path: str, body_bytes: bytes, content_type: str, query_params: dict[str, list[str]], controller: MicroduckController, deploy_service: DeployService, ) -> tuple[int, dict[str, Any]]: if path == "/api/deploy": try: q_ow = query_params.get("overwrite_profile", [None])[0] raw_zip, overwrite = extract_deploy_payload(content_type, body_bytes, q_ow) res = dict(deploy_service.apply_zip_bytes(raw_zip, overwrite_profile=overwrite)) res["status"] = build_status_payload(controller, deploy_service) return 200, res except ValueError as exc: return 400, {"ok": False, "error": str(exc)} except Exception as exc: return 500, {"ok": False, "error": str(exc)} try: payload = json.loads(body_bytes.decode("utf-8")) if body_bytes.strip() else {} except Exception: return 400, {"ok": False, "error": "Invalid JSON body"} try: if path == "/api/stand": controller.request_stand() return 200, build_status_payload(controller, deploy_service) if path == "/api/estop": controller.emergency_stop() return 200, build_status_payload(controller, deploy_service) if path == "/api/action": action = str(payload.get("action", "")) ok = controller.trigger_action(action) return 200, {"ok": ok, "status": build_status_payload(controller, deploy_service)} if path == "/api/settings": if "auto_stand_on_fall" in payload: controller.set_auto_stand_on_fall(bool(payload["auto_stand_on_fall"])) if "speed_scale" in payload: controller.set_speed_scale(float(payload["speed_scale"])) return 200, build_status_payload(controller, deploy_service) if path == "/api/profile": profile = controller.update_profile(payload) return 200, {"ok": True, "profile": profile} if path == "/api/calibrate/ping": max_id = int(payload.get("max_id", 20)) return 200, {"ok": True, "ids": controller.ping_servos(max_id=max_id)} if path == "/api/calibrate/joint_zero": joint = str(payload.get("joint", "")) profile = controller.capture_joint_zero(joint) return 200, {"ok": True, "profile": profile} if path == "/api/calibrate/test_joint": joint = str(payload.get("joint", "")) rad = float(payload.get("rad", 0.0)) ticks = controller.test_single_joint(joint, rad) return 200, {"ok": True, "ticks": ticks} if path == "/api/calibrate/exit": controller.exit_calibration() return 200, build_status_payload(controller, deploy_service) if path == "/api/calibrate/imu_zero": samples = int(payload.get("samples", 200)) imu = controller.calibrate_imu_zero(samples=samples) return 200, {"ok": True, "imu": imu} except (ValueError, RuntimeError) as exc: return 400, {"ok": False, "error": str(exc)} except Exception as exc: return 500, {"ok": False, "error": str(exc)} return 404, {"ok": False, "error": f"Unknown POST endpoint: {path}"}