From 737c0f0c0c95d86b01572f3c1a33dbd28ce2e647 Mon Sep 17 00:00:00 2001 From: Josh Date: Fri, 13 Nov 2026 12:40:36 -0500 Subject: [PATCH] Add live Dunnellon weather and clean up Roku guide titles --- .env.example | 4 + HANDOFF.md | 2 +- README.md | 10 ++- bridge/app.py | 40 ++++++++-- bridge/requirements.txt | 1 + bridge/weather.py | 129 +++++++++++++++++++++++++++++++++ compose.yaml | 2 + roku/components/BridgeTask.brs | 6 +- roku/components/RetroScene.brs | 8 +- roku/components/RetroScene.xml | 15 +++- roku/components/Weather.brs | 111 ++++++++++++++++++++++++++++ tests/test_bridge.py | 10 ++- 12 files changed, 322 insertions(+), 16 deletions(-) create mode 100644 bridge/weather.py create mode 100644 roku/components/Weather.brs diff --git a/.env.example b/.env.example index 8efae32..224c41e 100644 --- a/.env.example +++ b/.env.example @@ -5,3 +5,7 @@ RETROTV_NAME=retroLabs RETROTV_MEDIA_DIR=./data/media TUNARR_LOOPBACK_PORT=14242 TUNARR_CPUS=2 + +# NWS point coordinates, latitude and longitude. Leave blank to disable. +RETROTV_WEATHER_POINT= +RETROTV_WEATHER_LOCATION="Local Weather" diff --git a/HANDOFF.md b/HANDOFF.md index aab2398..a970091 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -4,7 +4,7 @@ Updated: 2026-11-13 ## Status -The initial bridge, Compose stack, and Roku client are implemented. The backend runs on the current machine at `192.168.0.203:4242`. See [README.md](README.md) to set up programming and build the Roku package. Tunarr programming and physical Roku acceptance remain open. The `visionLabs` reference checkout was unavailable on this machine. +The initial bridge, Compose stack, and Roku client are implemented. The backend runs on the current machine at `192.168.0.203:4242`. See [README.md](README.md) to set up programming and build the Roku package. Tunarr has a programmed lineup, and the native weather channel uses live NWS data for Dunnellon, FL. Physical Roku acceptance remains open. The `visionLabs` reference checkout was unavailable on this machine. ## Product goal diff --git a/README.md b/README.md index a04a1ef..f5026d4 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ The stack on this machine uses [Tunarr at 192.168.0.203:4242](http://192.168.0.2 1. Put a few compatible test videos in `data/media/`, or set `RETROTV_MEDIA_DIR` in `.env` to an existing library and run `docker compose up -d`. The directory is mounted read-only at `/media` inside Tunarr. 2. In Tunarr's media sources, add a Local source and a library under `/media`. Start a scan. You can also connect an existing Plex, Jellyfin, or Emby source. 3. Create two channels with different numbers. Use HLS as the channel's stream mode for the initial Roku test. Add programming to each channel, save, and use Tunarr's Guide and Watch actions to verify the schedule and playback. -4. Open the [Roku channel lineup](http://192.168.0.203:4242/api/v1/channels) to check that both channels and the native weather placeholder are present. +4. Open the [Roku channel lineup](http://192.168.0.203:4242/api/v1/channels) to check that both channels and the native weather channel are present. See the [Tunarr setup walkthrough](https://tunarr.com/getting-started/setup/) and [scheduling documentation](https://tunarr.com/configure/scheduling/) for time slots, sequential programming, and filler. @@ -32,6 +32,12 @@ Use `http://:4242/web/` for the programming UI and `/api/v1/health` for The current host uses the NVIDIA Compose override for Tunarr's CUDA transcode profile. The local `.env` selects it with `COMPOSE_FILE=compose.yaml:deploy/compose.nvidia.yaml`. The override maps NVIDIA device nodes and the host's x86-64 driver libraries into Tunarr. If the host driver version changes, set `TUNARR_NVIDIA_DRIVER_VERSION` in `.env` to the version shown by `nvidia-smi` and recreate Tunarr with `docker compose up -d --no-deps tunarr`. +## Weather channel + +Tune to channel 99 in the retroLabs Roku app. This host is configured for Dunnellon, FL (34431). The screen rotates through current conditions, six hourly periods, six extended forecast periods, and sunrise/sunset. Active NWS alerts appear across the rotation. The bridge caches data and marks delayed responses. + +To set a location on another host, set `RETROTV_WEATHER_POINT` (latitude,longitude) and `RETROTV_WEATHER_LOCATION` in `.env`, then run `docker compose up -d --no-deps bridge`. The bridge serves the feed at `/api/v1/weather`. Weather is rendered by the Roku app. + ## Roku Run `./roku/build.sh` to produce `roku/dist/retroLabs.zip`. See [Roku setup and controls](roku/README.md) for sideloading and manual server entry. @@ -44,4 +50,4 @@ python3 -m venv .venv .venv/bin/python -m unittest discover -s tests -v ``` -The tests exercise lineup and guide normalization, server ID persistence, Tunarr admin writes, and HLS manifest/segment forwarding. Physical Roku discovery, playback, live tuning, and reboot recovery are the remaining device acceptance checks. Pairing and live weather are deferred. +The tests exercise lineup and guide normalization, server ID persistence, Tunarr admin writes, and HLS manifest/segment forwarding. Physical Roku discovery, playback, live tuning, and reboot recovery are the remaining device acceptance checks. Pairing is deferred. diff --git a/bridge/app.py b/bridge/app.py index 58ac8e0..f5ecb28 100644 --- a/bridge/app.py +++ b/bridge/app.py @@ -14,6 +14,7 @@ from fastapi.responses import RedirectResponse, Response, StreamingResponse from starlette.background import BackgroundTask from .discovery import SERVICE, start_discovery +from .weather import NWSWeather WEATHER_ID = "weather" HOP_HEADERS = { @@ -49,12 +50,35 @@ def lineup(data): return sorted(channels, key=lambda channel: channel["number"]) -def programs(channel_guide): +EPISODE_CODE = re.compile(r"\bS(\d{1,2})E(\d{1,3})\b", re.IGNORECASE) +RELEASE_SUFFIX = re.compile( + r"\b(?:\d{3,4}p|WEB(?:[ ._-]?(?:DL|Rip))?|BluRay|BRRip|HDTV|[xh][ .]?26[45]|HEVC)\b", + re.IGNORECASE, +) + + +def program_title(item, channel_name): + program = item.get("program") or {} + title = item.get("title") or program.get("title") + if not title: + return "Off air" if item["type"] == "flex" else "Programming" + if program.get("type") != "episode": + return title + words = re.sub(r"(?<=\w)\.(?=\w)", " ", title) + match = EPISODE_CODE.search(words) + if not match: + return words + season, episode = map(int, match.groups()) + label = f"{channel_name} S{season:02d}E{episode:02d}" + detail = RELEASE_SUFFIX.split(words[match.end():], maxsplit=1)[0].strip(" ._-") + return f"{label} · {detail}" if detail else label + + +def programs(channel_guide, channel_name): result = [] for item in sorted(channel_guide.get("programs", []), key=lambda p: p["start"]): - title = item.get("title") or (item.get("program") or {}).get("title") result.append({ - "title": title or ("Off air" if item["type"] == "flex" else "Programming"), + "title": program_title(item, channel_name), "start": utc_string(datetime.fromtimestamp(item["start"] / 1000, UTC)), "stop": utc_string(datetime.fromtimestamp(item["stop"] / 1000, UTC)), }) @@ -90,6 +114,7 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None): port = int(os.getenv("RETROTV_PORT", "4242")) base_url = f"http://{ip}:{port}" name = os.getenv("RETROTV_NAME", "retroLabs") + weather_provider = NWSWeather() upstream = tunarr_url or os.getenv("RETROTV_TUNARR_URL", "http://127.0.0.1:14242") identity = Path(id_file or os.getenv("RETROTV_ID_FILE", "data/server-id")) @@ -171,7 +196,7 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None): return { "serverTime": utc_string(now), "channels": [ - {**channel, "programs": programs(schedules.get(channel["id"], {}))} + {**channel, "programs": programs(schedules.get(channel["id"], {}), channel["name"])} for channel in lineup(channel_data) ], } @@ -185,9 +210,10 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None): channel_data, schedules = await asyncio.gather( upstream_json("/api/channels"), guide_data(now, 24) ) - if not any(channel["id"] == channel_id for channel in lineup(channel_data)): + channel = next((entry for entry in lineup(channel_data) if entry["id"] == channel_id), None) + if channel is None: raise HTTPException(404, "Channel not found") - entries = programs(schedules.get(channel_id, {})) + entries = programs(schedules.get(channel_id, {}), channel["name"]) return { "now": next((p for p in entries if p["start"] <= stamp < p["stop"]), None), "next": next((p for p in entries if p["start"] > stamp), None), @@ -196,7 +222,7 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None): @app.get("/api/v1/weather") async def weather(): - return {"status": "placeholder"} + return await weather_provider.read() async def proxy(request, path, *, playlist=False, params=None): client = app.state.tunarr diff --git a/bridge/requirements.txt b/bridge/requirements.txt index ab15ad1..8585cdc 100644 --- a/bridge/requirements.txt +++ b/bridge/requirements.txt @@ -1,3 +1,4 @@ fastapi==0.115.14 httpx==0.28.1 uvicorn==0.34.3 +astral==3.2 diff --git a/bridge/weather.py b/bridge/weather.py new file mode 100644 index 0000000..9ac5767 --- /dev/null +++ b/bridge/weather.py @@ -0,0 +1,129 @@ +import asyncio +import logging +import os +from datetime import UTC, datetime +from time import monotonic +from zoneinfo import ZoneInfo + +from astral import Observer +from astral.sun import sun + +import httpx + +LOG = logging.getLogger(__name__) + + +class NWSWeather: + def __init__(self): + self.point = os.getenv("RETROTV_WEATHER_POINT", "").strip() + self.location = os.getenv("RETROTV_WEATHER_LOCATION", "Local Weather") + self.cache = {} + self.retry_at = {} + self.lock = asyncio.Lock() + + async def _cached(self, client, key, url, ttl, transform): + now = monotonic() + if now >= self.retry_at.get(key, 0): + try: + response = await client.get(url) + response.raise_for_status() + self.cache[key] = (transform(response.json()), now + ttl) + self.retry_at[key] = now + ttl + except (httpx.HTTPError, ValueError, KeyError, IndexError, TypeError) as exc: + LOG.warning("NWS %s unavailable: %s", key, exc) + self.retry_at[key] = now + 60 + return self.cache.get(key, (None, 0)) + + async def read(self): + if not self.point: + return {"status": "unconfigured", "location": self.location} + async with self.lock, httpx.AsyncClient( + base_url="https://api.weather.gov", timeout=3, + headers={"User-Agent": "retroLabs/0.1", "Accept": "application/geo+json"}, + ) as client: + grid, _ = await self._cached( + client, "grid", f"/points/{self.point}", 86400, + lambda body: body["properties"], + ) + if not grid: + return {"status": "unavailable", "location": self.location} + + async def current(): + stations, _ = await self._cached( + client, "stations", grid["observationStations"], 86400, + lambda body: [station["properties"]["stationIdentifier"] + for station in body["features"][:5]], + ) + candidates = await asyncio.gather(*( + self._cached(client, f"observation:{station}", + f"/stations/{station}/observations/latest", 300, observation) + for station in stations or [] + )) + recent = [(value, deadline) for value, deadline in candidates if value] + return next(((value, deadline) for value, deadline in recent + if deadline > monotonic()), recent[0] if recent else (None, 0)) + + parts = await asyncio.gather( + current(), + self._cached(client, "hourly", grid["forecastHourly"], 600, + lambda body: periods(body, 18)), + self._cached(client, "forecast", grid["forecast"], 600, + lambda body: periods(body, 14)), + self._cached(client, "alerts", f"/alerts/active?point={self.point}", 120, + lambda body: [alert["properties"] for alert in body["features"]]), + ) + clock = datetime.now(UTC) + now = clock.isoformat() + local_zone = ZoneInfo(grid["timeZone"]) + latitude, longitude = map(float, self.point.split(",")) + daylight = sun(Observer(latitude, longitude), + date=clock.astimezone(local_zone).date(), tzinfo=local_zone) + observation_data, hourly, forecast, alerts = (value for value, _ in parts) + return { + "status": "ok", "location": self.location, "source": "National Weather Service", + "current": observation_data, + "almanac": {key: local_time(daylight[key]) for key in ("sunrise", "sunset")}, + "hourly": future_periods(hourly, now)[:6], + "forecast": future_periods(forecast, now)[:6], + "alerts": [ + {"event": alert["event"], "headline": alert.get("headline")} + for alert in alerts or [] if after(alert.get("ends") or alert.get("expires"), now) + ], + "alertsAvailable": parts[3][1] > monotonic(), + "stale": any(deadline <= monotonic() for _, deadline in parts[:3]), + } + + +def local_time(value): + return value.strftime("%I:%M %p").lstrip("0") + + +def observation(body): + data = body["properties"] + celsius = data["temperature"]["value"] + if celsius is None: + raise ValueError("Observation has no temperature") + humidity = data.get("relativeHumidity", {}).get("value") + wind = data.get("windSpeed", {}).get("value") + return { + "temperature": round(celsius * 9 / 5 + 32), "conditions": data["textDescription"], + "humidity": None if humidity is None else round(humidity), + "windMph": None if wind is None else round(wind * 0.621371), + "observedAt": data["timestamp"], + } + + +def periods(body, limit): + return [ + {"name": item["name"] or local_time(datetime.fromisoformat(item["startTime"])), "start": item["startTime"], "end": item["endTime"], + "temperature": item["temperature"], "conditions": item["shortForecast"]} + for item in body["properties"]["periods"][:limit] + ] + + +def after(value, now): + return value is not None and datetime.fromisoformat(value) > datetime.fromisoformat(now) + + +def future_periods(items, now): + return [item for item in items or [] if after(item["end"], now)] diff --git a/compose.yaml b/compose.yaml index bcfdb2f..8592c58 100644 --- a/compose.yaml +++ b/compose.yaml @@ -30,6 +30,8 @@ services: RETROTV_NAME: ${RETROTV_NAME:-retroLabs} RETROTV_TUNARR_URL: http://127.0.0.1:${TUNARR_LOOPBACK_PORT:-14242} RETROTV_ID_FILE: /state/server-id + RETROTV_WEATHER_POINT: ${RETROTV_WEATHER_POINT:-} + RETROTV_WEATHER_LOCATION: ${RETROTV_WEATHER_LOCATION:-Local Weather} volumes: - bridge-data:/state diff --git a/roku/components/BridgeTask.brs b/roku/components/BridgeTask.brs index 5e97935..ec5f9f3 100644 --- a/roku/components/BridgeTask.brs +++ b/roku/components/BridgeTask.brs @@ -43,6 +43,8 @@ sub runRequest() registry.Write("id", request.server.id) registry.Flush() m.top.result = {data: readJson(request.server.baseUrl + "/api/v1/channels")} + else if request.kind = "weather" + m.top.result = {data: readJson(request.url, 12000)} else m.top.result = {data: readJson(request.url)} end if @@ -55,14 +57,14 @@ function readServer(baseUrl as string) as dynamic return {id: data.id, name: data.name, baseUrl: baseUrl} end function -function readJson(url as string) as dynamic +function readJson(url as string, timeoutMs = 3500 as integer) as dynamic port = CreateObject("roMessagePort") transfer = CreateObject("roUrlTransfer") transfer.SetMessagePort(port) transfer.SetUrl(url) transfer.AddHeader("Accept", "application/json") if not transfer.AsyncGetToString() then return invalid - event = Wait(3500, port) + event = Wait(timeoutMs, port) if Type(event) = "roUrlEvent" and event.GetResponseCode() = 200 data = ParseJson(event.GetString()) if GetInterface(data, "ifAssociativeArray") <> invalid then return data diff --git a/roku/components/RetroScene.brs b/roku/components/RetroScene.brs index cdfff4e..d68bf60 100644 --- a/roku/components/RetroScene.brs +++ b/roku/components/RetroScene.brs @@ -12,6 +12,7 @@ sub init() m.menu.ObserveField("itemSelected", "onMenuSelect") m.video.ObserveField("state", "onVideoState") + initWeather() m.bannerTimer.ObserveField("fire", "hideBanner") m.clockTimer.ObserveField("fire", "refreshClock") m.retryTimer.ObserveField("fire", "retryPlayback") @@ -23,6 +24,7 @@ sub findServer(baseUrl as string, useSaved as boolean) if m.serverRequest <> invalid then return m.banner.visible = false m.weather.visible = false + stopWeather() m.video.control = "stop" m.video.visible = false m.playbackStatus.visible = false @@ -156,7 +158,11 @@ sub startPlayback() m.weather.visible = channel.type = "weather" m.video.visible = not m.weather.visible m.playbackStatus.visible = false - if m.weather.visible then return + if m.weather.visible + startWeather() + return + end if + stopWeather() streamUrl = channel.streamUrl if GetInterface(streamUrl, "ifString") = invalid or streamUrl = "" diff --git a/roku/components/RetroScene.xml b/roku/components/RetroScene.xml index ce160fc..d799a8a 100644 --- a/roku/components/RetroScene.xml +++ b/roku/components/RetroScene.xml @@ -2,6 +2,7 @@