Add live Dunnellon weather and clean up Roku guide titles

This commit is contained in:
Josh
2026-11-13 12:40:36 -05:00
parent 364d911fe4
commit 737c0f0c0c
12 changed files with 322 additions and 16 deletions

View File

@@ -5,3 +5,7 @@ RETROTV_NAME=retroLabs
RETROTV_MEDIA_DIR=./data/media RETROTV_MEDIA_DIR=./data/media
TUNARR_LOOPBACK_PORT=14242 TUNARR_LOOPBACK_PORT=14242
TUNARR_CPUS=2 TUNARR_CPUS=2
# NWS point coordinates, latitude and longitude. Leave blank to disable.
RETROTV_WEATHER_POINT=
RETROTV_WEATHER_LOCATION="Local Weather"

View File

@@ -4,7 +4,7 @@ Updated: 2026-11-13
## Status ## 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 ## Product goal

View File

@@ -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. 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. 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. 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. 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://<LAN-IP>: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`. 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 ## 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. 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 .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.

View File

@@ -14,6 +14,7 @@ from fastapi.responses import RedirectResponse, Response, StreamingResponse
from starlette.background import BackgroundTask from starlette.background import BackgroundTask
from .discovery import SERVICE, start_discovery from .discovery import SERVICE, start_discovery
from .weather import NWSWeather
WEATHER_ID = "weather" WEATHER_ID = "weather"
HOP_HEADERS = { HOP_HEADERS = {
@@ -49,12 +50,35 @@ def lineup(data):
return sorted(channels, key=lambda channel: channel["number"]) 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 = [] result = []
for item in sorted(channel_guide.get("programs", []), key=lambda p: p["start"]): 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({ 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)), "start": utc_string(datetime.fromtimestamp(item["start"] / 1000, UTC)),
"stop": utc_string(datetime.fromtimestamp(item["stop"] / 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")) port = int(os.getenv("RETROTV_PORT", "4242"))
base_url = f"http://{ip}:{port}" base_url = f"http://{ip}:{port}"
name = os.getenv("RETROTV_NAME", "retroLabs") name = os.getenv("RETROTV_NAME", "retroLabs")
weather_provider = NWSWeather()
upstream = tunarr_url or os.getenv("RETROTV_TUNARR_URL", "http://127.0.0.1:14242") 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")) 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 { return {
"serverTime": utc_string(now), "serverTime": utc_string(now),
"channels": [ "channels": [
{**channel, "programs": programs(schedules.get(channel["id"], {}))} {**channel, "programs": programs(schedules.get(channel["id"], {}), channel["name"])}
for channel in lineup(channel_data) 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( channel_data, schedules = await asyncio.gather(
upstream_json("/api/channels"), guide_data(now, 24) 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") raise HTTPException(404, "Channel not found")
entries = programs(schedules.get(channel_id, {})) entries = programs(schedules.get(channel_id, {}), channel["name"])
return { return {
"now": next((p for p in entries if p["start"] <= stamp < p["stop"]), None), "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), "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") @app.get("/api/v1/weather")
async def weather(): async def weather():
return {"status": "placeholder"} return await weather_provider.read()
async def proxy(request, path, *, playlist=False, params=None): async def proxy(request, path, *, playlist=False, params=None):
client = app.state.tunarr client = app.state.tunarr

View File

@@ -1,3 +1,4 @@
fastapi==0.115.14 fastapi==0.115.14
httpx==0.28.1 httpx==0.28.1
uvicorn==0.34.3 uvicorn==0.34.3
astral==3.2

129
bridge/weather.py Normal file
View File

@@ -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)]

View File

@@ -30,6 +30,8 @@ services:
RETROTV_NAME: ${RETROTV_NAME:-retroLabs} RETROTV_NAME: ${RETROTV_NAME:-retroLabs}
RETROTV_TUNARR_URL: http://127.0.0.1:${TUNARR_LOOPBACK_PORT:-14242} RETROTV_TUNARR_URL: http://127.0.0.1:${TUNARR_LOOPBACK_PORT:-14242}
RETROTV_ID_FILE: /state/server-id RETROTV_ID_FILE: /state/server-id
RETROTV_WEATHER_POINT: ${RETROTV_WEATHER_POINT:-}
RETROTV_WEATHER_LOCATION: ${RETROTV_WEATHER_LOCATION:-Local Weather}
volumes: volumes:
- bridge-data:/state - bridge-data:/state

View File

@@ -43,6 +43,8 @@ sub runRequest()
registry.Write("id", request.server.id) registry.Write("id", request.server.id)
registry.Flush() registry.Flush()
m.top.result = {data: readJson(request.server.baseUrl + "/api/v1/channels")} 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 else
m.top.result = {data: readJson(request.url)} m.top.result = {data: readJson(request.url)}
end if end if
@@ -55,14 +57,14 @@ function readServer(baseUrl as string) as dynamic
return {id: data.id, name: data.name, baseUrl: baseUrl} return {id: data.id, name: data.name, baseUrl: baseUrl}
end function end function
function readJson(url as string) as dynamic function readJson(url as string, timeoutMs = 3500 as integer) as dynamic
port = CreateObject("roMessagePort") port = CreateObject("roMessagePort")
transfer = CreateObject("roUrlTransfer") transfer = CreateObject("roUrlTransfer")
transfer.SetMessagePort(port) transfer.SetMessagePort(port)
transfer.SetUrl(url) transfer.SetUrl(url)
transfer.AddHeader("Accept", "application/json") transfer.AddHeader("Accept", "application/json")
if not transfer.AsyncGetToString() then return invalid if not transfer.AsyncGetToString() then return invalid
event = Wait(3500, port) event = Wait(timeoutMs, port)
if Type(event) = "roUrlEvent" and event.GetResponseCode() = 200 if Type(event) = "roUrlEvent" and event.GetResponseCode() = 200
data = ParseJson(event.GetString()) data = ParseJson(event.GetString())
if GetInterface(data, "ifAssociativeArray") <> invalid then return data if GetInterface(data, "ifAssociativeArray") <> invalid then return data

View File

@@ -12,6 +12,7 @@ sub init()
m.menu.ObserveField("itemSelected", "onMenuSelect") m.menu.ObserveField("itemSelected", "onMenuSelect")
m.video.ObserveField("state", "onVideoState") m.video.ObserveField("state", "onVideoState")
initWeather()
m.bannerTimer.ObserveField("fire", "hideBanner") m.bannerTimer.ObserveField("fire", "hideBanner")
m.clockTimer.ObserveField("fire", "refreshClock") m.clockTimer.ObserveField("fire", "refreshClock")
m.retryTimer.ObserveField("fire", "retryPlayback") m.retryTimer.ObserveField("fire", "retryPlayback")
@@ -23,6 +24,7 @@ sub findServer(baseUrl as string, useSaved as boolean)
if m.serverRequest <> invalid then return if m.serverRequest <> invalid then return
m.banner.visible = false m.banner.visible = false
m.weather.visible = false m.weather.visible = false
stopWeather()
m.video.control = "stop" m.video.control = "stop"
m.video.visible = false m.video.visible = false
m.playbackStatus.visible = false m.playbackStatus.visible = false
@@ -156,7 +158,11 @@ sub startPlayback()
m.weather.visible = channel.type = "weather" m.weather.visible = channel.type = "weather"
m.video.visible = not m.weather.visible m.video.visible = not m.weather.visible
m.playbackStatus.visible = false m.playbackStatus.visible = false
if m.weather.visible then return if m.weather.visible
startWeather()
return
end if
stopWeather()
streamUrl = channel.streamUrl streamUrl = channel.streamUrl
if GetInterface(streamUrl, "ifString") = invalid or streamUrl = "" if GetInterface(streamUrl, "ifString") = invalid or streamUrl = ""

View File

@@ -2,6 +2,7 @@
<component name="RetroScene" extends="Scene"> <component name="RetroScene" extends="Scene">
<script type="text/brightscript" uri="pkg:/components/RetroScene.brs" /> <script type="text/brightscript" uri="pkg:/components/RetroScene.brs" />
<script type="text/brightscript" uri="pkg:/components/Guide.brs" /> <script type="text/brightscript" uri="pkg:/components/Guide.brs" />
<script type="text/brightscript" uri="pkg:/components/Weather.brs" />
<children> <children>
<Video id="video" width="1280" height="720" enableUI="false" /> <Video id="video" width="1280" height="720" enableUI="false" />
<Group id="weather" visible="false"> <Group id="weather" visible="false">
@@ -9,8 +10,16 @@
<Rectangle translation="[70,120]" width="1140" height="5" color="0x78E5EBFF" /> <Rectangle translation="[70,120]" width="1140" height="5" color="0x78E5EBFF" />
<Label translation="[70,55]" width="900" height="55" text="retroLabs Weather" <Label translation="[70,55]" width="900" height="55" text="retroLabs Weather"
font="font:LargeBoldSystemFont" color="0xF8F7EFFF" /> font="font:LargeBoldSystemFont" color="0xF8F7EFFF" />
<Label translation="[70,195]" width="1100" height="50" text="Live local weather is coming soon." <Label id="weatherLocation" translation="[70,135]" width="1140" height="50"
font="font:MediumSystemFont" color="0xF8F7EFFF" /> font="font:MediumBoldSystemFont" color="0x78E5EBFF" />
<Label id="weatherHeading" translation="[70,198]" width="1140" height="42"
font="font:MediumBoldSystemFont" />
<Label id="weatherBody" translation="[70,252]" width="1140" height="285"
font="font:MediumSystemFont" wrap="true" numLines="7" />
<Label id="weatherAlerts" translation="[70,553]" width="1140" height="74"
font="font:SmallBoldSystemFont" color="0xFFD57AFF" wrap="true" numLines="2" />
<Label id="weatherSource" translation="[70,646]" width="1140" height="32"
font="font:SmallSystemFont" color="0xB7D4E9FF" />
</Group> </Group>
<Group id="banner" translation="[50,525]" visible="false"> <Group id="banner" translation="[50,525]" visible="false">
<Rectangle width="1180" height="145" color="0x101A32EF" /> <Rectangle width="1180" height="145" color="0x101A32EF" />
@@ -41,6 +50,8 @@
</Group> </Group>
<Timer id="bannerTimer" duration="5" /> <Timer id="bannerTimer" duration="5" />
<Timer id="clockTimer" duration="1" repeat="true" /> <Timer id="clockTimer" duration="1" repeat="true" />
<Timer id="weatherRotation" duration="9" repeat="true" />
<Timer id="weatherRefresh" duration="60" repeat="true" />
<Timer id="retryTimer" duration="3" /> <Timer id="retryTimer" duration="3" />
</children> </children>
</component> </component>

111
roku/components/Weather.brs Normal file
View File

@@ -0,0 +1,111 @@
sub initWeather()
for each id in ["weatherLocation", "weatherHeading", "weatherBody", "weatherAlerts", "weatherSource", "weatherRotation", "weatherRefresh"]
m[id] = m.top.FindNode(id)
end for
m.weatherRotation.ObserveField("fire", "rotateWeather")
m.weatherRefresh.ObserveField("fire", "refreshWeather")
end sub
sub startWeather()
m.weatherPage = 0
m.weatherData = invalid
m.weatherLocation.text = ""
m.weatherHeading.text = "Loading local weather"
m.weatherBody.text = ""
m.weatherAlerts.text = ""
m.weatherSource.text = ""
refreshWeather()
m.weatherRefresh.control = "start"
end sub
sub stopWeather()
m.weatherRotation.control = "stop"
m.weatherRefresh.control = "stop"
if m.weatherWorker <> invalid
m.weatherWorker.UnobserveFieldScoped("result")
m.weatherWorker = invalid
end if
end sub
sub refreshWeather()
if not m.weather.visible or m.weatherWorker <> invalid then return
m.weatherWorker = startRequest({kind: "weather", url: m.server.baseUrl + "/api/v1/weather"}, "onWeather")
end sub
sub onWeather(event as object)
if m.weatherWorker = invalid or not event.GetRoSGNode().IsSameNode(m.weatherWorker) then return
m.weatherWorker = invalid
if not m.weather.visible then return
firstResult = m.weatherData = invalid
m.weatherData = event.GetData().data
renderWeather()
if firstResult then m.weatherRotation.control = "start"
end sub
sub rotateWeather()
if not m.weather.visible then return
m.weatherPage = (m.weatherPage + 1) mod 4
renderWeather()
end sub
sub renderWeather()
data = m.weatherData
m.weatherAlerts.text = ""
m.weatherSource.text = ""
if data = invalid
m.weatherHeading.text = "Local weather unavailable"
m.weatherBody.text = ""
return
end if
m.weatherLocation.text = data.location
if data.status <> "ok"
m.weatherHeading.text = "Local weather unavailable"
if data.status = "unconfigured" then m.weatherHeading.text = "Set a weather location on the server"
m.weatherBody.text = ""
return
end if
newline = Chr(10)
m.weatherSource.text = data.source
if data.stale then m.weatherSource.text += " | Some data may be delayed"
if data.alerts.Count() > 0
alert = data.alerts[0]
m.weatherAlerts.text = "ACTIVE ALERT | " + alert.event
if data.alerts.Count() > 1 then m.weatherAlerts.text += " (+" + StrI(data.alerts.Count() - 1).Trim() + " more)"
else if not data.alertsAvailable
m.weatherAlerts.text = "Alert feed temporarily unavailable"
end if
if m.weatherPage = 0
m.weatherHeading.text = "CURRENT CONDITIONS"
current = data.current
if current = invalid
m.weatherBody.text = "Station observation unavailable"
return
end if
m.weatherBody.text = tempLabel(current.temperature) + " | " + current.conditions
if current.humidity <> invalid then m.weatherBody.text += newline + "Humidity " + StrI(current.humidity).Trim() + "%"
if current.windMph <> invalid then m.weatherBody.text += newline + "Wind " + StrI(current.windMph).Trim() + " mph"
else if m.weatherPage = 3
m.weatherHeading.text = "TODAY'S ALMANAC"
m.weatherBody.text = "Sunrise " + data.almanac.sunrise + newline + "Sunset " + data.almanac.sunset
else
periods = data.hourly
m.weatherHeading.text = "NEXT SIX HOURS"
if m.weatherPage = 2
periods = data.forecast
m.weatherHeading.text = "EXTENDED FORECAST"
end if
lines = []
for each period in periods
lines.Push(period.name + " | " + tempLabel(period.temperature) + " | " + period.conditions)
end for
m.weatherBody.text = lines.Join(newline)
if lines.Count() = 0 then m.weatherBody.text = "Forecast temporarily unavailable"
end if
end sub
function tempLabel(value as dynamic) as string
if value = invalid then return "—"
return StrI(value).Trim() + "°F"
end function

View File

@@ -6,7 +6,7 @@ from pathlib import Path
import httpx import httpx
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from bridge.app import create_app from bridge.app import create_app, program_title
CHANNEL = "4592af97-494e-42d4-9758-10bb26b05343" CHANNEL = "4592af97-494e-42d4-9758-10bb26b05343"
@@ -97,3 +97,11 @@ class BridgeTest(unittest.TestCase):
self.assertIn(server_id, self.client.get("/api/v1/device.xml").text) self.assertIn(server_id, self.client.get("/api/v1/device.xml").text)
with TestClient(self.app) as restarted: with TestClient(self.app) as restarted:
self.assertEqual(restarted.get("/api/v1/server").json()["id"], server_id) self.assertEqual(restarted.get("/api/v1/server").json()["id"], server_id)
def test_episode_labels_remove_release_metadata(self):
episode = {"type": "content", "program": {
"type": "episode", "title": "The.Rookie.S01E01.720p.AMZN.WEBRip.x264",
}}
self.assertEqual(program_title(episode, "The Rookie"), "The Rookie S01E01")
episode["program"]["title"] = "The Rookie S01E01 Pilot"
self.assertEqual(program_title(episode, "The Rookie"), "The Rookie S01E01 · Pilot")