feat: add Microduck UNO Q deployment and hotspot skill control
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user