Preview open-mic colour on the rig and save it back to the pad.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
c9df537567
commit
10c39015b7
8 files changed
+805
No files matched your search
@@ -0,0 +1,125 @@
|
||||
"""HTTP server for the pad colour page. Run via `python -m pad_color`."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from pad_color.engine import open_studio
|
||||
|
||||
STATIC = Path(__file__).resolve().parent / "static"
|
||||
BOOT = str(time.time_ns())
|
||||
HOST = "127.0.0.1"
|
||||
PORT = 8767
|
||||
|
||||
MIME = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
}
|
||||
|
||||
|
||||
def static_stamp(directory: Path) -> str:
|
||||
latest = 0
|
||||
if directory.is_dir():
|
||||
for path in directory.rglob("*"):
|
||||
if path.is_file():
|
||||
latest = max(latest, path.stat().st_mtime_ns)
|
||||
return str(latest)
|
||||
|
||||
|
||||
def make_handler(studio):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt: str, *args) -> None:
|
||||
return
|
||||
|
||||
def _send(self, code: int, body: bytes, content_type: str) -> None:
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _json(self, code: int, payload: dict) -> None:
|
||||
self._send(code, json.dumps(payload).encode(), "application/json")
|
||||
|
||||
def _read_json(self) -> dict:
|
||||
length = int(self.headers.get("Content-Length", "0") or 0)
|
||||
if length <= 0:
|
||||
return {}
|
||||
data = json.loads(self.rfile.read(length).decode() or "{}")
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Expected a JSON object")
|
||||
return data
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
path = self.path.split("?", 1)[0]
|
||||
if path == "/api/state":
|
||||
self._json(200, studio.state())
|
||||
return
|
||||
if path == "/api/dev":
|
||||
self._json(200, {"boot": BOOT, "static": static_stamp(STATIC)})
|
||||
return
|
||||
if path == "/":
|
||||
path = "/index.html"
|
||||
file_path = (STATIC / path.lstrip("/")).resolve()
|
||||
if not str(file_path).startswith(str(STATIC)) or not file_path.is_file():
|
||||
self._send(404, b"not found", "text/plain; charset=utf-8")
|
||||
return
|
||||
self._send(200, file_path.read_bytes(), MIME.get(file_path.suffix, "application/octet-stream"))
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
path = self.path.split("?", 1)[0]
|
||||
try:
|
||||
body = self._read_json()
|
||||
if path == "/api/pad":
|
||||
studio.press(int(body["pad"]))
|
||||
elif path == "/api/part":
|
||||
studio.set_part(int(body["part"]), int(body["level"]))
|
||||
else:
|
||||
self._json(404, {"error": "Unknown request"})
|
||||
return
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
self._json(400, {"error": str(exc) or "Bad request"})
|
||||
return
|
||||
self._json(200, studio.state())
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Pad colour page")
|
||||
parser.add_argument("--host", default=HOST)
|
||||
parser.add_argument("--port", type=int, default=PORT)
|
||||
parser.add_argument("--ip", default=None, help="Art-Net destination")
|
||||
parser.add_argument("--midi", default=None, help="ALSA port, for example 128:0")
|
||||
args = parser.parse_args()
|
||||
|
||||
studio = open_studio(args.ip, args.midi)
|
||||
studio.start()
|
||||
ThreadingHTTPServer.allow_reuse_address = True
|
||||
httpd = ThreadingHTTPServer((args.host, args.port), make_handler(studio))
|
||||
|
||||
def stop(_signum, _frame) -> None:
|
||||
threading.Thread(target=httpd.shutdown, daemon=True).start()
|
||||
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
print(f"http://{args.host}:{args.port}", flush=True)
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
finally:
|
||||
httpd.server_close()
|
||||
studio.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user