feat: add Microduck UNO Q deployment and hotspot skill control
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Web HTTP/WebSocket control and deployment package for Microduck UNO Q."""
|
||||
@@ -0,0 +1,184 @@
|
||||
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"<html><body><h1>Microduck controller UI missing</h1></body></html>"
|
||||
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}"}
|
||||
@@ -0,0 +1,227 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import select
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from core.controller import MicroduckController
|
||||
from core.deploy_service import DeployService
|
||||
|
||||
from .api import (
|
||||
build_status_payload,
|
||||
dispatch_api_get,
|
||||
dispatch_api_post,
|
||||
handle_ws_message,
|
||||
load_index_html,
|
||||
)
|
||||
|
||||
|
||||
WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
|
||||
def _ws_encode_frame(opcode: int, payload: bytes) -> bytes:
|
||||
header = bytearray([0x80 | (opcode & 0x0F)])
|
||||
n = len(payload)
|
||||
if n < 126:
|
||||
header.append(n)
|
||||
elif n < 65536:
|
||||
header.append(126)
|
||||
header.extend(struct.pack("!H", n))
|
||||
else:
|
||||
header.append(127)
|
||||
header.extend(struct.pack("!Q", n))
|
||||
return bytes(header) + payload
|
||||
|
||||
|
||||
def _recv_exact(sock: socket.socket, n: int) -> bytes | None:
|
||||
chunks = bytearray()
|
||||
while len(chunks) < n:
|
||||
chunk = sock.recv(n - len(chunks))
|
||||
if not chunk:
|
||||
return None
|
||||
chunks.extend(chunk)
|
||||
return bytes(chunks)
|
||||
|
||||
|
||||
def _ws_read_frame(sock: socket.socket) -> tuple[int, bytes] | None:
|
||||
head = _recv_exact(sock, 2)
|
||||
if head is None:
|
||||
return None
|
||||
b1, b2 = head[0], head[1]
|
||||
opcode = b1 & 0x0F
|
||||
masked = bool(b2 & 0x80)
|
||||
length = b2 & 0x7F
|
||||
if length == 126:
|
||||
ext = _recv_exact(sock, 2)
|
||||
if ext is None:
|
||||
return None
|
||||
length = struct.unpack("!H", ext)[0]
|
||||
elif length == 127:
|
||||
ext = _recv_exact(sock, 8)
|
||||
if ext is None:
|
||||
return None
|
||||
length = struct.unpack("!Q", ext)[0]
|
||||
if length > 1024 * 1024:
|
||||
return None
|
||||
mask = _recv_exact(sock, 4) if masked else b""
|
||||
if masked and mask is None:
|
||||
return None
|
||||
payload = _recv_exact(sock, length) if length > 0 else b""
|
||||
if payload is None:
|
||||
return None
|
||||
if masked:
|
||||
payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
|
||||
return opcode, payload
|
||||
|
||||
|
||||
class FallbackWebServer(ThreadingHTTPServer):
|
||||
"""Zero-dependency HTTP + RFC6455 WebSocket server (runs on stock Python 3.12)."""
|
||||
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
host: str,
|
||||
port: int,
|
||||
controller: MicroduckController,
|
||||
deploy_service: DeployService,
|
||||
) -> None:
|
||||
self.controller = controller
|
||||
self.deploy_service = deploy_service
|
||||
super().__init__((host, port), _RequestHandler)
|
||||
self.port = int(self.server_address[1])
|
||||
|
||||
|
||||
class _RequestHandler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, format: str, *args: Any) -> None: # noqa: A002
|
||||
return
|
||||
|
||||
def _send_cors_headers(self) -> None:
|
||||
self.send_header("Access-Control-Allow-Origin", "*")
|
||||
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
||||
self.send_header("Access-Control-Allow-Private-Network", "true")
|
||||
|
||||
def _send_json(self, status_code: int, payload: dict[str, Any]) -> None:
|
||||
raw = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status_code)
|
||||
self._send_cors_headers()
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def _send_bytes(self, status_code: int, content_type: str, data: bytes) -> None:
|
||||
self.send_response(status_code)
|
||||
self._send_cors_headers()
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_OPTIONS(self) -> None: # noqa: N802
|
||||
self.send_response(204)
|
||||
self._send_cors_headers()
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
parsed = urlparse(self.path)
|
||||
if parsed.path == "/ws/control" and self.headers.get("Upgrade", "").lower() == "websocket":
|
||||
self._handle_websocket()
|
||||
return
|
||||
if parsed.path in ("/", "/index.html"):
|
||||
self._send_bytes(200, "text/html; charset=utf-8", load_index_html())
|
||||
return
|
||||
|
||||
srv: FallbackWebServer = self.server # type: ignore[assignment]
|
||||
code, payload = dispatch_api_get(parsed.path, srv.controller, srv.deploy_service)
|
||||
self._send_json(code, payload)
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
parsed = urlparse(self.path)
|
||||
length = int(self.headers.get("Content-Length", "0") or "0")
|
||||
if length < 0 or length > 160 * 1024 * 1024:
|
||||
self._send_json(413, {"ok": False, "error": "Payload too large"})
|
||||
return
|
||||
body = self.rfile.read(length) if length > 0 else b""
|
||||
content_type = self.headers.get("Content-Type", "")
|
||||
query = parse_qs(parsed.query)
|
||||
srv: FallbackWebServer = self.server # type: ignore[assignment]
|
||||
code, payload = dispatch_api_post(
|
||||
parsed.path,
|
||||
body,
|
||||
content_type,
|
||||
query,
|
||||
srv.controller,
|
||||
srv.deploy_service,
|
||||
)
|
||||
self._send_json(code, payload)
|
||||
|
||||
def _handle_websocket(self) -> None:
|
||||
key = self.headers.get("Sec-WebSocket-Key")
|
||||
if not key:
|
||||
self.send_error(400, "Missing Sec-WebSocket-Key")
|
||||
return
|
||||
accept = base64.b64encode(hashlib.sha1((key.strip() + WS_GUID).encode("ascii")).digest()).decode("ascii")
|
||||
self.send_response(101, "Switching Protocols")
|
||||
self.send_header("Upgrade", "websocket")
|
||||
self.send_header("Connection", "Upgrade")
|
||||
self.send_header("Sec-WebSocket-Accept", accept)
|
||||
self.end_headers()
|
||||
|
||||
srv: FallbackWebServer = self.server # type: ignore[assignment]
|
||||
sock: socket.socket = self.connection
|
||||
sock.settimeout(5.0)
|
||||
write_lock = threading.Lock()
|
||||
last_telemetry = 0.0
|
||||
|
||||
try:
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
if now - last_telemetry >= 0.1:
|
||||
last_telemetry = now
|
||||
msg = {"type": "telemetry", **build_status_payload(srv.controller, srv.deploy_service)}
|
||||
frame = _ws_encode_frame(0x1, json.dumps(msg).encode("utf-8"))
|
||||
with write_lock:
|
||||
sock.sendall(frame)
|
||||
|
||||
readable, _, _ = select.select([sock], [], [], 0.05)
|
||||
if not readable:
|
||||
continue
|
||||
parsed = _ws_read_frame(sock)
|
||||
if parsed is None:
|
||||
break
|
||||
opcode, payload = parsed
|
||||
if opcode == 0x8: # close
|
||||
with write_lock:
|
||||
sock.sendall(_ws_encode_frame(0x8, b""))
|
||||
break
|
||||
if opcode == 0x9: # ping -> pong
|
||||
with write_lock:
|
||||
sock.sendall(_ws_encode_frame(0xA, payload))
|
||||
continue
|
||||
if opcode == 0x1: # text
|
||||
try:
|
||||
data = json.loads(payload.decode("utf-8"))
|
||||
except Exception:
|
||||
continue
|
||||
ack = handle_ws_message(srv.controller, data)
|
||||
if ack is not None:
|
||||
with write_lock:
|
||||
sock.sendall(_ws_encode_frame(0x1, json.dumps(ack).encode("utf-8")))
|
||||
except (BrokenPipeError, ConnectionResetError, TimeoutError, OSError):
|
||||
pass
|
||||
finally:
|
||||
self.close_connection = True
|
||||
@@ -0,0 +1,92 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
from core.controller import MicroduckController
|
||||
from core.deploy_service import DeployService
|
||||
|
||||
from .api import (
|
||||
build_status_payload,
|
||||
dispatch_api_get,
|
||||
dispatch_api_post,
|
||||
handle_ws_message,
|
||||
load_index_html,
|
||||
)
|
||||
|
||||
|
||||
def create_fastapi_app(controller: MicroduckController, deploy_service: DeployService) -> Any:
|
||||
"""Create FastAPI app backed by the shared web.api dispatcher."""
|
||||
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
|
||||
app = FastAPI(title="Microduck UNO Q Controller", version="0.1.0")
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_pna_header(request: Request, call_next: Any) -> Any:
|
||||
resp = await call_next(request)
|
||||
resp.headers["Access-Control-Allow-Private-Network"] = "true"
|
||||
return resp
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def index() -> HTMLResponse:
|
||||
return HTMLResponse(content=load_index_html().decode("utf-8"))
|
||||
|
||||
@app.get("/api/{subpath:path}")
|
||||
async def api_get(subpath: str) -> JSONResponse:
|
||||
code, payload = dispatch_api_get(f"/api/{subpath}", controller, deploy_service)
|
||||
return JSONResponse(status_code=code, content=payload)
|
||||
|
||||
@app.post("/api/{subpath:path}")
|
||||
async def api_post(subpath: str, request: Request) -> JSONResponse:
|
||||
body = await request.body()
|
||||
content_type = request.headers.get("content-type", "")
|
||||
query = parse_qs(request.url.query)
|
||||
code, payload = dispatch_api_post(
|
||||
f"/api/{subpath}",
|
||||
body,
|
||||
content_type,
|
||||
query,
|
||||
controller,
|
||||
deploy_service,
|
||||
)
|
||||
return JSONResponse(status_code=code, content=payload)
|
||||
|
||||
@app.websocket("/ws/control")
|
||||
async def ws_control(websocket: WebSocket) -> None:
|
||||
await websocket.accept()
|
||||
stop_event = asyncio.Event()
|
||||
|
||||
async def telemetry_loop() -> None:
|
||||
while not stop_event.is_set():
|
||||
msg = {"type": "telemetry", **build_status_payload(controller, deploy_service)}
|
||||
await websocket.send_text(json.dumps(msg))
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
sender = asyncio.create_task(telemetry_loop())
|
||||
try:
|
||||
while True:
|
||||
raw = await websocket.receive_text()
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception:
|
||||
continue
|
||||
ack = handle_ws_message(controller, data)
|
||||
if ack is not None:
|
||||
await websocket.send_text(json.dumps(ack))
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
stop_event.set()
|
||||
sender.cancel()
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,619 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
|
||||
<title>Microduck UNO Q Controller</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f1117;
|
||||
--panel: #191d27;
|
||||
--ink: #f6f4ed;
|
||||
--muted: #98a2b3;
|
||||
--accent: #ff7a2f;
|
||||
--accent-dark: #c95212;
|
||||
--danger: #e53935;
|
||||
--ok: #2ecc71;
|
||||
--warn: #f39c12;
|
||||
--border: #2a3142;
|
||||
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
}
|
||||
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
font-family: var(--mono);
|
||||
overflow-x: hidden;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.topbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
background: var(--panel);
|
||||
border-bottom: 2px solid var(--border);
|
||||
}
|
||||
.brand { font-weight: 700; font-size: 15px; letter-spacing: 0.04em; color: var(--accent); }
|
||||
.badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; font-size: 12px; }
|
||||
.badge {
|
||||
padding: 3px 8px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--border);
|
||||
background: #12151d;
|
||||
}
|
||||
.badge.ok { border-color: var(--ok); color: var(--ok); }
|
||||
.badge.warn { border-color: var(--warn); color: var(--warn); }
|
||||
.badge.danger { border-color: var(--danger); color: var(--danger); }
|
||||
.tabs { display: flex; gap: 6px; }
|
||||
.tab-btn {
|
||||
padding: 6px 12px;
|
||||
background: #12151d;
|
||||
color: var(--muted);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
.tab-btn.active { background: var(--accent); color: #08080c; border-color: var(--accent); }
|
||||
.safety-bar {
|
||||
display: grid;
|
||||
grid-template-columns: 1.3fr 1.2fr 1fr 1fr;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
background: #141821;
|
||||
border-bottom: 1px solid var(--border);
|
||||
align-items: center;
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.safety-bar { grid-template-columns: 1fr 1fr; }
|
||||
}
|
||||
button.btn {
|
||||
font-family: inherit;
|
||||
font-weight: 700;
|
||||
font-size: 13px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
padding: 10px 12px;
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
}
|
||||
button.btn:active { transform: translateY(1px); }
|
||||
button.btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
button.btn-estop {
|
||||
background: var(--danger);
|
||||
border-color: #ff6b6b;
|
||||
color: #fff;
|
||||
font-size: 15px;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
button.btn-stand {
|
||||
background: var(--accent);
|
||||
border-color: #ffa573;
|
||||
color: #08080c;
|
||||
}
|
||||
.toggle-box, .slider-box {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 6px 10px;
|
||||
}
|
||||
.toggle-row { display: flex; justify-content: space-between; align-items: center; gap: 8px; color: var(--ink); font-size: 12px; }
|
||||
.main { padding: 12px 14px; }
|
||||
.hidden { display: none !important; }
|
||||
.control-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(240px, 1fr) minmax(240px, 1fr);
|
||||
gap: 14px;
|
||||
align-items: stretch;
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
.control-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
.card {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 12px;
|
||||
}
|
||||
.card-title { font-size: 12px; color: var(--muted); margin: 0 0 10px; text-transform: uppercase; letter-spacing: 0.06em; }
|
||||
.stick-zone {
|
||||
position: relative;
|
||||
height: 250px;
|
||||
border-radius: 10px;
|
||||
background: radial-gradient(circle at center, #202636 0%, #11151f 75%);
|
||||
border: 1px dashed #374151;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.stick-hint { color: var(--muted); font-size: 12px; pointer-events: none; text-align: center; padding: 12px; }
|
||||
.stick-base {
|
||||
position: absolute;
|
||||
width: 112px;
|
||||
height: 112px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid rgba(255, 122, 47, 0.75);
|
||||
background: rgba(255, 122, 47, 0.08);
|
||||
transform: translate(-50%, -50%);
|
||||
pointer-events: none;
|
||||
}
|
||||
.stick-knob {
|
||||
position: absolute;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent);
|
||||
box-shadow: 0 0 16px rgba(255, 122, 47, 0.5);
|
||||
transform: translate(-50%, -50%);
|
||||
pointer-events: none;
|
||||
}
|
||||
.vel-readout { margin-top: 8px; font-size: 12px; color: var(--muted); display: flex; justify-content: space-between; }
|
||||
.skills-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
.skill-btn.active { background: var(--accent); color: #08080c; border-color: #ffa573; }
|
||||
.head-panel { margin-top: 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
||||
.calib-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }
|
||||
.joint-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
||||
.joint-table th, .joint-table td { border-bottom: 1px solid var(--border); padding: 6px 4px; text-align: left; }
|
||||
.joint-table input[type="number"] {
|
||||
width: 64px;
|
||||
background: #0f1117;
|
||||
color: var(--ink);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
padding: 3px 5px;
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
.mini-btn {
|
||||
padding: 4px 7px;
|
||||
font-size: 11px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--border);
|
||||
background: #12151d;
|
||||
color: var(--ink);
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.mini-btn:hover { border-color: var(--accent); }
|
||||
.log-line { margin-top: 8px; font-size: 11px; color: var(--muted); word-break: break-word; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
<div class="brand">MICRODUCK // UNO Q</div>
|
||||
<div class="badges">
|
||||
<span id="badge-life" class="badge warn">IDLE</span>
|
||||
<span id="badge-mode" class="badge">Idle</span>
|
||||
<span id="badge-ws" class="badge">WS ...</span>
|
||||
<span id="badge-imu" class="badge">IMU --</span>
|
||||
<span id="badge-batt" class="badge">--.-V</span>
|
||||
<span id="badge-temp" class="badge">--C</span>
|
||||
<span id="badge-hz" class="badge">--Hz</span>
|
||||
</div>
|
||||
<div class="tabs">
|
||||
<button id="tab-ctrl" class="tab-btn active" type="button">Control</button>
|
||||
<button id="tab-cal" class="tab-btn" type="button">Calibration</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="safety-bar">
|
||||
<button id="btn-estop" class="btn btn-estop" type="button">E-STOP (TORQUE OFF)</button>
|
||||
<button id="btn-stand" class="btn btn-stand" type="button">Prepare Stand (1.5s)</button>
|
||||
<label class="toggle-box">
|
||||
<span>Recovery Policy</span>
|
||||
<span class="toggle-row">
|
||||
<span>Auto Stand on Fall</span>
|
||||
<input id="chk-auto-stand" type="checkbox" />
|
||||
</span>
|
||||
</label>
|
||||
<label class="slider-box">
|
||||
<span>Speed Scale: <strong id="lbl-speed">50%</strong></span>
|
||||
<input id="rng-speed" type="range" min="10" max="100" step="5" value="50" />
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<main class="main">
|
||||
<section id="view-control" class="control-grid">
|
||||
<div class="card">
|
||||
<h2 class="card-title">Virtual Joystick (Hold & Drag)</h2>
|
||||
<div id="stick-zone" class="stick-zone">
|
||||
<div id="stick-hint" class="stick-hint">Touch or drag anywhere here to walk / turn</div>
|
||||
<div id="stick-base" class="stick-base hidden"></div>
|
||||
<div id="stick-knob" class="stick-knob hidden"></div>
|
||||
</div>
|
||||
<div class="vel-readout">
|
||||
<span id="lbl-vx">vx norm: 0.00</span>
|
||||
<span id="lbl-wz">wz norm: 0.00</span>
|
||||
</div>
|
||||
|
||||
<div id="head-panel" class="head-panel hidden">
|
||||
<label class="slider-box">Neck Pitch <input id="hd-0" type="range" min="-1" max="1" step="0.05" value="0" /></label>
|
||||
<label class="slider-box">Head Pitch <input id="hd-1" type="range" min="-1" max="1" step="0.05" value="0" /></label>
|
||||
<label class="slider-box">Head Yaw <input id="hd-2" type="range" min="-1" max="1" step="0.05" value="0" /></label>
|
||||
<label class="slider-box">Head Roll <input id="hd-3" type="range" min="-1" max="1" step="0.05" value="0" /></label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2 class="card-title">Skills & Modes</h2>
|
||||
<div class="skills-grid">
|
||||
<button class="btn skill-btn" data-action="sitStand" type="button">Sit / Stand</button>
|
||||
<button class="btn skill-btn" data-action="head" id="btn-head" type="button">Head Mode</button>
|
||||
<button class="btn skill-btn" data-action="kickL" type="button">Kick Left</button>
|
||||
<button class="btn skill-btn" data-action="kickR" type="button">Kick Right</button>
|
||||
<button class="btn skill-btn" data-action="groundPick" type="button">Ground Pick</button>
|
||||
<button class="btn skill-btn" data-action="roll" id="btn-roll" type="button">Roll / Trick</button>
|
||||
<button class="btn skill-btn" data-action="rollers" id="btn-rollers" type="button">Feet / Rollers</button>
|
||||
<button class="btn skill-btn hidden" data-action="script" id="btn-script" type="button">Custom Script</button>
|
||||
</div>
|
||||
<div id="ctrl-log" class="log-line">Ready. Tap "Prepare Stand" when the robot is upright on the floor.</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="view-calib" class="card hidden">
|
||||
<h2 class="card-title">Hardware Profile & Servo Calibration (IDLE Required for Joint Test)</h2>
|
||||
<div class="calib-actions">
|
||||
<button id="btn-ping" class="btn" type="button">Ping Servos (1-20)</button>
|
||||
<button id="btn-imu-zero" class="btn" type="button">IMU Bias Zero (Keep Still)</button>
|
||||
<button id="btn-exit-cal" class="btn" type="button">Exit Calibration (Torque Off)</button>
|
||||
<button id="btn-save-prof" class="btn btn-stand" type="button">Save Profile to Robot</button>
|
||||
</div>
|
||||
<div id="calib-status" class="log-line">No ping scan yet.</div>
|
||||
<div style="overflow-x:auto; margin-top:10px;">
|
||||
<table class="joint-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Joint</th>
|
||||
<th>ID</th>
|
||||
<th>Sign</th>
|
||||
<th>Offset</th>
|
||||
<th>Live Tick</th>
|
||||
<th>Live Rad</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="joint-tbody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
(() => {
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let ws = null;
|
||||
let reconnectTimer = null;
|
||||
let profile = null;
|
||||
let latestStatus = null;
|
||||
const stickState = { active: false, pointerId: null, originX: 0, originY: 0, nx: 0, nwz: 0 };
|
||||
const MAX_RADIUS = 56;
|
||||
|
||||
function log(msg) {
|
||||
$("ctrl-log").textContent = msg;
|
||||
}
|
||||
|
||||
async function apiPost(path, body) {
|
||||
const res = await fetch(path, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body || {}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.ok === false) {
|
||||
throw new Error(data.error || `HTTP ${res.status}`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function setTab(tab) {
|
||||
const isCtrl = tab === "ctrl";
|
||||
$("view-control").classList.toggle("hidden", !isCtrl);
|
||||
$("view-calib").classList.toggle("hidden", isCtrl);
|
||||
$("tab-ctrl").classList.toggle("active", isCtrl);
|
||||
$("tab-cal").classList.toggle("active", !isCtrl);
|
||||
if (!isCtrl) loadProfile();
|
||||
}
|
||||
|
||||
$("tab-ctrl").onclick = () => setTab("ctrl");
|
||||
$("tab-cal").onclick = () => setTab("cal");
|
||||
|
||||
function sendWs(obj) {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify(obj));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function updateStatusUI(st) {
|
||||
latestStatus = st;
|
||||
const lifeEl = $("badge-life");
|
||||
lifeEl.textContent = st.lifecycle || "UNKNOWN";
|
||||
lifeEl.className = "badge " + (st.lifecycle === "ACTIVE" ? "ok" : st.lifecycle === "FALL_SAFE" ? "danger" : "warn");
|
||||
$("badge-mode").textContent = st.mode_label || st.skill_mode || "-";
|
||||
$("badge-imu").textContent = st.imu_ok ? "IMU OK" : "IMU ERR";
|
||||
$("badge-imu").className = "badge " + (st.imu_ok ? "ok" : "danger");
|
||||
$("badge-batt").textContent = `${Number(st.voltage_v || 0).toFixed(2)}V`;
|
||||
$("badge-temp").textContent = `${Number(st.max_temp_c || 0).toFixed(0)}C`;
|
||||
$("badge-hz").textContent = `${Number(st.ctrl_hz || 0).toFixed(0)}Hz`;
|
||||
|
||||
$("chk-auto-stand").checked = !!st.auto_stand_on_fall;
|
||||
const spdPct = Math.round((st.speed_scale || 0.5) * 100);
|
||||
if (document.activeElement !== $("rng-speed")) {
|
||||
$("rng-speed").value = String(spdPct);
|
||||
$("lbl-speed").textContent = `${spdPct}%`;
|
||||
}
|
||||
|
||||
$("btn-head").classList.toggle("active", !!st.head_mode);
|
||||
$("head-panel").classList.toggle("hidden", !st.head_mode);
|
||||
$("btn-rollers").disabled = !st.rollers_enabled;
|
||||
$("btn-rollers").classList.toggle("active", st.loco === "rollers");
|
||||
const hasScript = !!(st.custom_move && st.custom_move.slot === "script");
|
||||
$("btn-script").classList.toggle("hidden", !hasScript);
|
||||
if (st.error) log(`Error: ${st.error}`);
|
||||
|
||||
if (st.ticks && st.joint_pos_rad && profile) {
|
||||
Object.keys(profile.joints).forEach((name, idx) => {
|
||||
const tCell = document.getElementById(`live-tick-${name}`);
|
||||
const rCell = document.getElementById(`live-rad-${name}`);
|
||||
if (tCell) tCell.textContent = String(st.ticks[idx] ?? "-");
|
||||
if (rCell) rCell.textContent = Number(st.joint_pos_rad[idx] ?? 0).toFixed(3);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function connectWs() {
|
||||
if (reconnectTimer) clearTimeout(reconnectTimer);
|
||||
const proto = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
ws = new WebSocket(`${proto}//${location.host}/ws/control`);
|
||||
ws.onopen = () => {
|
||||
$("badge-ws").textContent = "WS LIVE";
|
||||
$("badge-ws").className = "badge ok";
|
||||
};
|
||||
ws.onclose = () => {
|
||||
$("badge-ws").textContent = "WS OFF";
|
||||
$("badge-ws").className = "badge danger";
|
||||
reconnectTimer = setTimeout(connectWs, 1000);
|
||||
};
|
||||
ws.onmessage = (evt) => {
|
||||
try {
|
||||
const msg = JSON.parse(evt.data);
|
||||
if (msg.type === "telemetry") updateStatusUI(msg);
|
||||
} catch (_) {}
|
||||
};
|
||||
}
|
||||
|
||||
// Safety & Skill controls
|
||||
$("btn-estop").onclick = async () => {
|
||||
sendWs({ type: "estop" });
|
||||
try { updateStatusUI(await apiPost("/api/estop")); log("E-STOP activated (torque off)"); } catch (e) { log(e.message); }
|
||||
};
|
||||
$("btn-stand").onclick = async () => {
|
||||
try { updateStatusUI(await apiPost("/api/stand")); log("Soft-start stand engaged..."); } catch (e) { log(e.message); }
|
||||
};
|
||||
$("chk-auto-stand").onchange = async (e) => {
|
||||
try { updateStatusUI(await apiPost("/api/settings", { auto_stand_on_fall: e.target.checked })); } catch (err) { log(err.message); }
|
||||
};
|
||||
$("rng-speed").oninput = (e) => {
|
||||
$("lbl-speed").textContent = `${e.target.value}%`;
|
||||
};
|
||||
$("rng-speed").onchange = async (e) => {
|
||||
try { updateStatusUI(await apiPost("/api/settings", { speed_scale: Number(e.target.value) / 100 })); } catch (err) { log(err.message); }
|
||||
};
|
||||
|
||||
document.querySelectorAll(".skill-btn").forEach((btn) => {
|
||||
btn.onclick = async () => {
|
||||
const action = btn.dataset.action;
|
||||
try {
|
||||
const res = await apiPost("/api/action", { action });
|
||||
if (res.status) updateStatusUI(res.status);
|
||||
log(res.ok ? `Triggered ${action}` : `Action '${action}' rejected in current state`);
|
||||
} catch (e) { log(e.message); }
|
||||
};
|
||||
});
|
||||
|
||||
const sendHead = () => {
|
||||
sendWs({
|
||||
type: "head",
|
||||
neck_pitch: Number($("hd-0").value),
|
||||
head_pitch: Number($("hd-1").value),
|
||||
head_yaw: Number($("hd-2").value),
|
||||
head_roll: Number($("hd-3").value),
|
||||
});
|
||||
};
|
||||
["hd-0", "hd-1", "hd-2", "hd-3"].forEach((id) => { $(id).oninput = sendHead; });
|
||||
|
||||
// Floating virtual joystick
|
||||
const zone = $("stick-zone");
|
||||
const base = $("stick-base");
|
||||
const knob = $("stick-knob");
|
||||
const hint = $("stick-hint");
|
||||
|
||||
function updateStickVisual(x, y) {
|
||||
if (!stickState.active) {
|
||||
base.classList.add("hidden");
|
||||
knob.classList.add("hidden");
|
||||
hint.classList.remove("hidden");
|
||||
return;
|
||||
}
|
||||
hint.classList.add("hidden");
|
||||
base.classList.remove("hidden");
|
||||
knob.classList.remove("hidden");
|
||||
base.style.left = `${stickState.originX}px`;
|
||||
base.style.top = `${stickState.originY}px`;
|
||||
knob.style.left = `${x}px`;
|
||||
knob.style.top = `${y}px`;
|
||||
}
|
||||
|
||||
function applyStickCoords(clientX, clientY) {
|
||||
const rect = zone.getBoundingClientRect();
|
||||
const px = clientX - rect.left;
|
||||
const py = clientY - rect.top;
|
||||
const dx = px - stickState.originX;
|
||||
const dy = py - stickState.originY;
|
||||
const dist = Math.hypot(dx, dy);
|
||||
const clamped = dist > MAX_RADIUS ? MAX_RADIUS / dist : 1.0;
|
||||
const cx = stickState.originX + dx * clamped;
|
||||
const cy = stickState.originY + dy * clamped;
|
||||
stickState.nx = -((cy - stickState.originY) / MAX_RADIUS);
|
||||
stickState.nwz = -((cx - stickState.originX) / MAX_RADIUS);
|
||||
$("lbl-vx").textContent = `vx norm: ${stickState.nx.toFixed(2)}`;
|
||||
$("lbl-wz").textContent = `wz norm: ${stickState.nwz.toFixed(2)}`;
|
||||
updateStickVisual(cx, cy);
|
||||
}
|
||||
|
||||
function releaseStick() {
|
||||
stickState.active = false;
|
||||
stickState.pointerId = null;
|
||||
stickState.nx = 0;
|
||||
stickState.nwz = 0;
|
||||
$("lbl-vx").textContent = "vx norm: 0.00";
|
||||
$("lbl-wz").textContent = "wz norm: 0.00";
|
||||
updateStickVisual(0, 0);
|
||||
sendWs({ type: "input", vx: 0, wz: 0, speed_scale: Number($("rng-speed").value) / 100 });
|
||||
}
|
||||
|
||||
zone.addEventListener("pointerdown", (e) => {
|
||||
const rect = zone.getBoundingClientRect();
|
||||
stickState.active = true;
|
||||
stickState.pointerId = e.pointerId;
|
||||
stickState.originX = e.clientX - rect.left;
|
||||
stickState.originY = e.clientY - rect.top;
|
||||
zone.setPointerCapture(e.pointerId);
|
||||
applyStickCoords(e.clientX, e.clientY);
|
||||
});
|
||||
zone.addEventListener("pointermove", (e) => {
|
||||
if (!stickState.active || e.pointerId !== stickState.pointerId) return;
|
||||
applyStickCoords(e.clientX, e.clientY);
|
||||
});
|
||||
zone.addEventListener("pointerup", (e) => {
|
||||
if (e.pointerId === stickState.pointerId) releaseStick();
|
||||
});
|
||||
zone.addEventListener("pointercancel", releaseStick);
|
||||
|
||||
setInterval(() => {
|
||||
if (stickState.active) {
|
||||
sendWs({
|
||||
type: "input",
|
||||
vx: stickState.nx,
|
||||
wz: stickState.nwz,
|
||||
speed_scale: Number($("rng-speed").value) / 100,
|
||||
});
|
||||
}
|
||||
}, 50);
|
||||
|
||||
// Calibration helpers
|
||||
function renderJointTable() {
|
||||
const tbody = $("joint-tbody");
|
||||
tbody.innerHTML = "";
|
||||
if (!profile || !profile.joints) return;
|
||||
Object.entries(profile.joints).forEach(([name, cfg]) => {
|
||||
const tr = document.createElement("tr");
|
||||
tr.innerHTML = `
|
||||
<td>${name}</td>
|
||||
<td><input type="number" min="0" max="253" value="${cfg.id}" data-j="${name}" data-f="id" /></td>
|
||||
<td><button class="mini-btn" type="button" data-flip="${name}">${cfg.sign > 0 ? "+1" : "-1"}</button></td>
|
||||
<td><input type="number" min="-4096" max="4096" value="${cfg.zero_offset_ticks}" data-j="${name}" data-f="zero_offset_ticks" /></td>
|
||||
<td id="live-tick-${name}">-</td>
|
||||
<td id="live-rad-${name}">0.000</td>
|
||||
<td>
|
||||
<button class="mini-btn" type="button" data-zero="${name}">Zero</button>
|
||||
<button class="mini-btn" type="button" data-test="${name}" data-rad="-0.2">-0.2</button>
|
||||
<button class="mini-btn" type="button" data-test="${name}" data-rad="0">0</button>
|
||||
<button class="mini-btn" type="button" data-test="${name}" data-rad="0.2">+0.2</button>
|
||||
</td>
|
||||
`;
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
|
||||
tbody.querySelectorAll("input[data-j]").forEach((inp) => {
|
||||
inp.onchange = () => {
|
||||
profile.joints[inp.dataset.j][inp.dataset.f] = Number(inp.value);
|
||||
};
|
||||
});
|
||||
tbody.querySelectorAll("button[data-flip]").forEach((btn) => {
|
||||
btn.onclick = () => {
|
||||
const j = profile.joints[btn.dataset.flip];
|
||||
j.sign = j.sign > 0 ? -1 : 1;
|
||||
btn.textContent = j.sign > 0 ? "+1" : "-1";
|
||||
};
|
||||
});
|
||||
tbody.querySelectorAll("button[data-zero]").forEach((btn) => {
|
||||
btn.onclick = async () => {
|
||||
try {
|
||||
const res = await apiPost("/api/calibrate/joint_zero", { joint: btn.dataset.zero });
|
||||
profile = res.profile;
|
||||
renderJointTable();
|
||||
$("calib-status").textContent = `Captured current tick as zero for ${btn.dataset.zero}`;
|
||||
} catch (e) { $("calib-status").textContent = `Error: ${e.message}`; }
|
||||
};
|
||||
});
|
||||
tbody.querySelectorAll("button[data-test]").forEach((btn) => {
|
||||
btn.onclick = async () => {
|
||||
try {
|
||||
await apiPost("/api/calibrate/test_joint", { joint: btn.dataset.test, rad: Number(btn.dataset.rad) });
|
||||
$("calib-status").textContent = `Commanded ${btn.dataset.test} -> ${btn.dataset.rad} rad`;
|
||||
} catch (e) { $("calib-status").textContent = `Error: ${e.message}`; }
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function loadProfile() {
|
||||
const res = await fetch("/api/profile");
|
||||
const data = await res.json();
|
||||
profile = data.profile;
|
||||
renderJointTable();
|
||||
}
|
||||
|
||||
$("btn-ping").onclick = async () => {
|
||||
try {
|
||||
const res = await apiPost("/api/calibrate/ping", { max_id: 20 });
|
||||
$("calib-status").textContent = `Responding IDs (${res.ids.length}): [${res.ids.join(", ")}]`;
|
||||
} catch (e) { $("calib-status").textContent = `Ping error: ${e.message}`; }
|
||||
};
|
||||
$("btn-imu-zero").onclick = async () => {
|
||||
try {
|
||||
$("calib-status").textContent = "Sampling IMU bias (keep robot stationary)...";
|
||||
const res = await apiPost("/api/calibrate/imu_zero", { samples: 200 });
|
||||
if (profile) profile.imu = res.imu;
|
||||
$("calib-status").textContent = `IMU gyro bias updated: [${res.imu.gyro_bias_rad_s.map((x) => x.toFixed(4)).join(", ")}]`;
|
||||
} catch (e) { $("calib-status").textContent = `IMU zero error: ${e.message}`; }
|
||||
};
|
||||
$("btn-exit-cal").onclick = async () => {
|
||||
try { updateStatusUI(await apiPost("/api/calibrate/exit")); $("calib-status").textContent = "Exited calibration (torque off)"; } catch (e) { $("calib-status").textContent = e.message; }
|
||||
};
|
||||
$("btn-save-prof").onclick = async () => {
|
||||
if (!profile) return;
|
||||
try {
|
||||
const res = await apiPost("/api/profile", profile);
|
||||
profile = res.profile;
|
||||
renderJointTable();
|
||||
$("calib-status").textContent = "Saved hardware_profile.json to UNO Q.";
|
||||
} catch (e) { $("calib-status").textContent = `Save error: ${e.message}`; }
|
||||
};
|
||||
|
||||
fetch("/api/status").then((r) => r.json()).then(updateStatusUI).catch(() => {});
|
||||
connectWs();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user