|
| 1 | +"""Open a live camera window in the browser once the station's media service is up. |
| 2 | +
|
| 3 | +`rua serve` starts this in the background so whoever is watching the robot can see |
| 4 | +what its cameras see. Run it yourself with `python -m hebbian_rua.live_view |
| 5 | +[media-url]`. The browser fetches each camera's newest JPEG from the media service |
| 6 | +directly, so nothing here keeps running once the page is open. |
| 7 | +""" |
| 8 | + |
| 9 | +import json |
| 10 | +import sys |
| 11 | +import tempfile |
| 12 | +import time |
| 13 | +import urllib.request |
| 14 | +import webbrowser |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +DEFAULT_MEDIA_URL = "http://127.0.0.1:8781" |
| 18 | +# A simulator may connect its cameras well after the station starts. |
| 19 | +CAMERA_WAIT_SECONDS = 120.0 |
| 20 | + |
| 21 | +PAGE = """<!doctype html> |
| 22 | +<meta charset="utf-8"> |
| 23 | +<title>RUA live view</title> |
| 24 | +<style> |
| 25 | + body { margin: 0; background: #111; color: #ddd; font: 14px system-ui, sans-serif; } |
| 26 | + main { display: flex; flex-wrap: wrap; gap: 8px; padding: 8px; } |
| 27 | + figure { margin: 0; flex: 1 1 480px; } |
| 28 | + img { width: 100%; background: #000; display: block; } |
| 29 | + figcaption { padding: 4px 0; } |
| 30 | +</style> |
| 31 | +<main></main> |
| 32 | +<script> |
| 33 | +const MEDIA = __MEDIA__; |
| 34 | +const CAMERAS = __CAMERAS__; |
| 35 | +const FRAME_INTERVAL_MS = 33; // ~30 fps; the media service always serves its newest frame |
| 36 | +for (const name of CAMERAS) { |
| 37 | + const figure = document.createElement("figure"); |
| 38 | + const image = document.createElement("img"); |
| 39 | + const caption = document.createElement("figcaption"); |
| 40 | + figure.append(image, caption); |
| 41 | + document.querySelector("main").append(figure); |
| 42 | + let frames = 0; |
| 43 | + const next = () => { |
| 44 | + image.src = `${MEDIA}/cameras/${encodeURIComponent(name)}?t=${Date.now()}`; |
| 45 | + }; |
| 46 | + image.onload = () => { frames += 1; setTimeout(next, FRAME_INTERVAL_MS); }; |
| 47 | + // The station may be restarting; keep the window and retry. |
| 48 | + image.onerror = () => { caption.textContent = `${name}: waiting for the station`; setTimeout(next, 500); }; |
| 49 | + setInterval(() => { |
| 50 | + if (frames > 0) caption.textContent = `${name}: ${frames} fps`; |
| 51 | + frames = 0; |
| 52 | + }, 1000); |
| 53 | + next(); |
| 54 | +} |
| 55 | +</script> |
| 56 | +""" |
| 57 | + |
| 58 | + |
| 59 | +def available_cameras(media_url: str) -> list[str]: |
| 60 | + """The cameras the media service can serve now; empty while it is starting.""" |
| 61 | + try: |
| 62 | + with urllib.request.urlopen(f"{media_url}/cameras", timeout=2) as response: |
| 63 | + listing = json.load(response) |
| 64 | + except (OSError, ValueError): |
| 65 | + return [] |
| 66 | + return [camera["name"] for camera in listing if camera.get("available")] |
| 67 | + |
| 68 | + |
| 69 | +def open_live_view( |
| 70 | + media_url: str = DEFAULT_MEDIA_URL, wait_seconds: float = CAMERA_WAIT_SECONDS |
| 71 | +) -> bool: |
| 72 | + """Wait for at least one camera, then open the live page; False if none appeared.""" |
| 73 | + deadline = time.monotonic() + wait_seconds |
| 74 | + while not (cameras := available_cameras(media_url)): |
| 75 | + if time.monotonic() > deadline: |
| 76 | + return False |
| 77 | + time.sleep(0.5) |
| 78 | + page = Path(tempfile.gettempdir()) / "rua-live-view.html" |
| 79 | + # Values go into the page itself: macOS drops query strings from file URLs. |
| 80 | + page.write_text( |
| 81 | + PAGE.replace("__MEDIA__", json.dumps(media_url)).replace( |
| 82 | + "__CAMERAS__", json.dumps(cameras) |
| 83 | + ) |
| 84 | + ) |
| 85 | + return webbrowser.open(page.as_uri()) |
| 86 | + |
| 87 | + |
| 88 | +def media_url_from_serve_arguments(arguments: list[str]) -> str: |
| 89 | + """The media URL for `rua serve`'s `--media-address`, reachable from this machine.""" |
| 90 | + address = "127.0.0.1:8781" |
| 91 | + for index, argument in enumerate(arguments): |
| 92 | + if argument == "--media-address" and index + 1 < len(arguments): |
| 93 | + address = arguments[index + 1] |
| 94 | + elif argument.startswith("--media-address="): |
| 95 | + address = argument.split("=", 1)[1] |
| 96 | + host, _, port = address.rpartition(":") |
| 97 | + if host in ("0.0.0.0", "[::]", ""): # bound to every interface |
| 98 | + host = "127.0.0.1" |
| 99 | + return f"http://{host}:{port}" |
| 100 | + |
| 101 | + |
| 102 | +def main() -> None: |
| 103 | + media_url = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_MEDIA_URL |
| 104 | + page = Path(tempfile.gettempdir()) / "rua-live-view.html" |
| 105 | + if open_live_view(media_url): |
| 106 | + print(f"rua live view: opened {page.as_uri()}", file=sys.stderr) |
| 107 | + else: |
| 108 | + print( |
| 109 | + f"rua live view: no camera at {media_url} or no browser; open {page.as_uri()}", |
| 110 | + file=sys.stderr, |
| 111 | + ) |
| 112 | + |
| 113 | + |
| 114 | +if __name__ == "__main__": |
| 115 | + main() |
0 commit comments