diff --git a/CHANGELOG b/CHANGELOG
index dde62acb..d5136a38 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -3,6 +3,7 @@
## 0.8.3 - Future
* Add a client for T3 Code
+* Weather app shows an icon for current conditions, and can add the weather to the status bar and the Glanceboard system card (Weather menu > Settings)
## 0.8.2 - 2026-10-03
diff --git a/app/apps/glanceboard/widgets/system-card.ts b/app/apps/glanceboard/widgets/system-card.ts
index c952b67d..b497a434 100644
--- a/app/apps/glanceboard/widgets/system-card.ts
+++ b/app/apps/glanceboard/widgets/system-card.ts
@@ -1,7 +1,14 @@
-import { BATTERY_ICON_WIDTH, drawBattery, drawDenseBatteries, type BatteryDevice } from "../../../graphics/battery";
+import {
+ BATTERY_ICON_WIDTH,
+ DENSE_BATTERY_BLOCK_HEIGHT,
+ drawBattery,
+ drawDenseBatteries,
+ type BatteryDevice,
+} from "../../../graphics/battery";
import { type GrayImage, type UiFont } from "../../../graphics/image";
import { onAndroidNotificationPosted, readActiveNotificationIcons } from "../../../native/notification-icons";
import { readPhoneBatteryState } from "../../../native/phone-battery";
+import { weatherBridge } from "../../../native/weather";
import { formatClockDate, formatClockTime } from "../../../ui/clock-format";
import {
batteryDisplayModeSetting,
@@ -19,6 +26,8 @@ import { truncateText } from "../../../graphics/textwrap";
import { timerEngine } from "../../timer/timer-engine";
import { formatCountdown, sortTimers, timerDisplayName, timerPhase, timerRemainingMs } from "../../timer/timer-model";
import { lineStep } from "../../../ui/metrics";
+import { drawWeatherReading, measureWeatherReading, weatherReading } from "../../weather/weather-icons";
+import { weatherShowOnSystemCardSetting } from "../../weather/weather-settings";
import { glanceFont } from "../glance-font";
import { type GlanceWidget } from "../widget";
@@ -27,12 +36,17 @@ const NOTIFICATION_ICON_SIZE = 24;
const NOTIFICATION_ICON_GAP = 4;
const BATTERY_ITEM_GAP = 12;
const BATTERY_LABEL_VALUE = 150;
+/** Gap between the battery block and the weather reading below it. */
+const WEATHER_GAP = 6;
type BatteryItem = { label: string; device: BatteryDevice; percent: number; charging: boolean };
+/** A block drawn against the card's right edge: its left edge and its rows. */
+type RightBlock = { left: number; top: number; bottom: number };
/**
* Date and time, the phone's notification icons, the phone/watch/G2/R1
- * battery indicators (the Wear OS watch's only while one is reachable), and
+ * battery indicators (the Wear OS watch's only while one is reachable), the
+ * current weather (when the Weather app's "Show on system card" is on), and
* the Timers app's countdowns: the top bar's contents plus timers, laid out
* for a card. Battery style and per-device visibility
* follow Settings > Customization > Battery indicators, so the card agrees with
@@ -45,6 +59,7 @@ export class SystemCardWidget implements GlanceWidget {
private unsubscribeNotifications: (() => void) | null = null;
private unsubscribeSettings: (() => void) | null = null;
private unsubscribeTimers: (() => void) | null = null;
+ private unsubscribeWeather: (() => void) | null = null;
start(requestRender: () => void): void {
this.requestRender = requestRender;
@@ -55,6 +70,8 @@ export class SystemCardWidget implements GlanceWidget {
this.syncSecondTick();
this.requestRender?.();
});
+ // The Weather app's indicator keeps the bridge refreshing; this only listens.
+ this.unsubscribeWeather = weatherBridge.onStateChange(() => this.requestRender?.());
this.syncSecondTick();
}
@@ -70,6 +87,8 @@ export class SystemCardWidget implements GlanceWidget {
this.unsubscribeSettings = null;
this.unsubscribeTimers?.();
this.unsubscribeTimers = null;
+ this.unsubscribeWeather?.();
+ this.unsubscribeWeather = null;
}
/** Countdowns change every second; run that clock only while one is running. */
@@ -102,9 +121,15 @@ export class SystemCardWidget implements GlanceWidget {
const small = glanceFont.small();
const now = new Date();
- // Clock and date down the left; batteries take the right edge.
- const batteryLeft = drawBatteryBlock(image, small, image.width - PAD, PAD);
- const textWidth = Math.max(0, batteryLeft - BATTERY_ITEM_GAP - PAD);
+ // Clock and date down the left; batteries take the right edge, with the
+ // weather right-aligned beneath them. Text on the left stops short of
+ // whichever of those shares its rows.
+ const battery = drawBatteryBlock(image, small, image.width - PAD, PAD);
+ const weatherTop = battery.bottom > battery.top ? battery.bottom + WEATHER_GAP : PAD;
+ const weather = drawWeatherBlock(image, medium, image.width - PAD, weatherTop, now.getTime());
+ const textRight = (top: number, bottom: number): number =>
+ weather && weather.top < bottom && weather.bottom > top ? Math.min(battery.left, weather.left) : battery.left;
+ const textWidth = Math.max(0, textRight(PAD, PAD + large.lineHeight) - BATTERY_ITEM_GAP - PAD);
const timeText = formatClockTime(now);
const timeFont = large.measureText(timeText) <= textWidth ? large : medium;
let y = PAD;
@@ -116,7 +141,8 @@ export class SystemCardWidget implements GlanceWidget {
// Notification icons along the bottom, as many as fit; the Timers app's
// countdowns take the band between the date and the icons.
const iconY = image.height - PAD - NOTIFICATION_ICON_SIZE;
- drawTimers(image, small, PAD, y, textWidth, iconY - 4, now.getTime());
+ const timersWidth = Math.max(0, textRight(y, iconY - 4) - BATTERY_ITEM_GAP - PAD);
+ drawTimers(image, small, PAD, y, timersWidth, iconY - 4, now.getTime());
const maxIcons = Math.max(0, ((image.width - 2 * PAD + NOTIFICATION_ICON_GAP) / (NOTIFICATION_ICON_SIZE + NOTIFICATION_ICON_GAP)) | 0);
if (maxIcons > 0) {
const { icons, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData());
@@ -158,16 +184,20 @@ function collectBatteryItems(): BatteryItem[] {
* Side-by-side styles put the label beside the gauge (or percentage) on one
* line; stacked styles centre the label above it; the dense style swaps
* labels for device icons and stacks two indicators per column, as in the
- * top bar. Returns the block's left edge (or `right` when nothing is shown).
+ * top bar. Returns the block's extent (zero-height at `right` when nothing
+ * is shown).
*/
-function drawBatteryBlock(image: GrayImage, font: UiFont, right: number, top: number): number {
+function drawBatteryBlock(image: GrayImage, font: UiFont, right: number, top: number): RightBlock {
const items = collectBatteryItems();
- if (!items.length) return right;
+ if (!items.length) return { left: right, top, bottom: top };
const mode = batteryDisplayModeSetting.get();
- if (mode === "dense") return drawDenseBatteries(image, items, right, top);
+ if (mode === "dense") {
+ return { left: drawDenseBatteries(image, items, right, top), top, bottom: top + DENSE_BATTERY_BLOCK_HEIGHT };
+ }
const percentage = mode === "percentage" || mode === "stacked-percentage";
const stacked = mode === "stacked" || mode === "stacked-percentage";
const gaugeHeight = drawBattery(0, false).height;
+ const valueHeight = percentage ? font.lineHeight : Math.max(font.lineHeight, gaugeHeight);
let x = right;
for (let index = items.length - 1; index >= 0; index--) {
const item = items[index]!;
@@ -186,7 +216,23 @@ function drawBatteryBlock(image: GrayImage, font: UiFont, right: number, top: nu
}
x -= BATTERY_ITEM_GAP;
}
- return x + BATTERY_ITEM_GAP;
+ return { left: x + BATTERY_ITEM_GAP, top, bottom: top + (stacked ? font.lineHeight + 2 : 0) + valueHeight };
+}
+
+/**
+ * The current weather's condition icon and temperature, right-aligned at
+ * `right` from `top`, while the system-card weather setting is on and a
+ * fresh reading exists. Returns the block's extent, or null when not drawn.
+ */
+function drawWeatherBlock(image: GrayImage, font: UiFont, right: number, top: number, nowMs: number): RightBlock | null {
+ if (!weatherShowOnSystemCardSetting.get()) return null;
+ const reading = weatherReading(weatherBridge.snapshot(), nowMs);
+ if (!reading) return null;
+ const iconSize = font.lineHeight + 4;
+ const height = Math.max(iconSize, font.lineHeight);
+ const left = right - Math.ceil(measureWeatherReading(reading, font, iconSize));
+ drawWeatherReading(image, reading, font, iconSize, left, top, height, 200);
+ return { left, top, bottom: top + height };
}
function drawBatteryValue(
diff --git a/app/apps/weather/index.ts b/app/apps/weather/index.ts
index 8245202d..73f12e7d 100644
--- a/app/apps/weather/index.ts
+++ b/app/apps/weather/index.ts
@@ -1,10 +1,12 @@
import { type AppDefinition } from "../app-definition";
import { createWeatherAppWindow, WEATHER_SURFACE_ID, WEATHER_WINDOW_ID } from "./weather-app";
+import { startWeatherIndicators } from "./weather-indicators";
const weatherApp: AppDefinition = {
appId: "weather",
title: "Weather",
icon: "cloud-sun",
+ boot: () => startWeatherIndicators(),
launch: (ctx) => ctx.launchInProcessApp(WEATHER_WINDOW_ID, WEATHER_SURFACE_ID, createWeatherAppWindow),
};
diff --git a/app/apps/weather/weather-app.ts b/app/apps/weather/weather-app.ts
index ffe0fba5..2e4bd3e5 100644
--- a/app/apps/weather/weather-app.ts
+++ b/app/apps/weather/weather-app.ts
@@ -1,6 +1,9 @@
import { ensureLocationPermission, hasLocationPermission } from "../../native/location-permissions";
import { weatherBridge } from "../../native/weather";
+import { toggleSettingMenuItem } from "../../ui/dashboard-settings";
+import { openSettingsSubMenu } from "../../ui/dashboard/settings-panel";
import { WeatherLayer } from "./weather";
+import { weatherShowInStatusBarSetting, weatherShowOnSystemCardSetting } from "./weather-settings";
import {
createInProcessWindow,
YieldAtRootLayer,
@@ -32,6 +35,14 @@ export function createWeatherAppWindow(options: InProcessAppOptions): InProcessW
}).catch((error) => { requestingPermission = false; console.warn(`Weather permission: ${error}`); });
};
+ // An indicator switched on without location access asks for it here, since
+ // its background refreshes have no screen of their own to prompt from.
+ const indicatorSettingOptions = {
+ onChange: (_ctx: unknown, enabled: boolean) => {
+ if (enabled && !hasLocationPermission()) requestUpdate();
+ },
+ };
+
const app = createInProcessWindow({
appId: "weather",
windowId: WEATHER_WINDOW_ID,
@@ -47,6 +58,18 @@ export function createWeatherAppWindow(options: InProcessAppOptions): InProcessW
requestUpdate();
},
},
+ {
+ label: "Settings",
+ onSelect: (ctx) => {
+ // Pop the menu first so closing the settings modal lands back on
+ // the forecast, not this menu.
+ ctx.stack.pop();
+ openSettingsSubMenu(ctx, "Weather settings", [
+ toggleSettingMenuItem(weatherShowInStatusBarSetting, indicatorSettingOptions),
+ toggleSettingMenuItem(weatherShowOnSystemCardSetting, indicatorSettingOptions),
+ ]);
+ },
+ },
],
actions: options.actions,
baseLayer: new YieldAtRootLayer(new WeatherLayer(() => weatherBridge.snapshot(), requestUpdate)),
diff --git a/app/apps/weather/weather-icons.ts b/app/apps/weather/weather-icons.ts
new file mode 100644
index 00000000..0c2a3008
--- /dev/null
+++ b/app/apps/weather/weather-icons.ts
@@ -0,0 +1,119 @@
+import { renderSvgIcon } from "../../graphics/icons";
+import { type GrayImage, type UiFont } from "../../graphics/image";
+import { type WeatherCondition, type WeatherState } from "../../native/weather";
+
+// Lucide weather icons (ISC licensed), kept verbatim so they can be diffed
+// against upstream.
+const WEATHER_SVGS = {
+ sun:
+ '',
+ moon:
+ '',
+ cloud:
+ '',
+ "cloud-sun":
+ '',
+ "cloud-moon":
+ '',
+ "cloud-fog":
+ '',
+ wind:
+ '',
+ "cloud-drizzle":
+ '',
+ "cloud-sun-rain":
+ '',
+ "cloud-moon-rain":
+ '',
+ "cloud-rain":
+ '',
+ "cloud-lightning":
+ '',
+ "cloud-snow":
+ '',
+ "cloud-hail":
+ '',
+} as const;
+
+type WeatherIconName = keyof typeof WEATHER_SVGS;
+
+/** Status bar and system card hide weather whose last refresh is older than this. */
+const INDICATOR_STALE_MS = 3 * 60 * 60 * 1000;
+/** Gap between a reading's icon and its temperature. */
+const READING_ICON_GAP = 3;
+
+function weatherIconName(condition: WeatherCondition, isDaytime: boolean): WeatherIconName {
+ switch (condition) {
+ case "clear":
+ return isDaytime ? "sun" : "moon";
+ case "partly-cloudy":
+ return isDaytime ? "cloud-sun" : "cloud-moon";
+ case "cloudy":
+ return "cloud";
+ case "fog":
+ return "cloud-fog";
+ case "wind":
+ return "wind";
+ case "drizzle":
+ return "cloud-drizzle";
+ case "showers":
+ return isDaytime ? "cloud-sun-rain" : "cloud-moon-rain";
+ case "rain":
+ return "cloud-rain";
+ case "thunderstorm":
+ return "cloud-lightning";
+ case "snow":
+ return "cloud-snow";
+ case "sleet":
+ return "cloud-hail";
+ }
+}
+
+/** A size×size icon for the condition (sun or moon variants by time of day), rendered once and cached. */
+export function renderWeatherIcon(condition: WeatherCondition, isDaytime: boolean, size: number): GrayImage | null {
+ const name = weatherIconName(condition, isDaytime);
+ return renderSvgIcon(`weather:${name}`, WEATHER_SVGS[name], size);
+}
+
+/** Current conditions as the status bar and system card show them. */
+export type WeatherReading = {
+ condition: WeatherCondition | null;
+ isDaytime: boolean;
+ /** Rounded, unit-less ("72°"), to stay compact. */
+ temperature: string;
+};
+
+/** The current reading, or null when there is none or it has gone stale. */
+export function weatherReading(state: WeatherState, nowMs: number): WeatherReading | null {
+ const current = state.current;
+ if (!current || state.lastUpdatedMs === null || nowMs - state.lastUpdatedMs > INDICATOR_STALE_MS) return null;
+ return {
+ condition: current.condition,
+ isDaytime: current.isDaytime,
+ temperature: current.temperatureF === null ? "--°" : `${Math.round(current.temperatureF)}°`,
+ };
+}
+
+/** Width drawWeatherReading takes for this reading. */
+export function measureWeatherReading(reading: WeatherReading, font: UiFont, iconSize: number): number {
+ return (reading.condition ? iconSize + READING_ICON_GAP : 0) + font.measureText(reading.temperature);
+}
+
+/** The condition icon then the temperature, each centred vertically in the `height` rows from `top`. */
+export function drawWeatherReading(
+ image: GrayImage,
+ reading: WeatherReading,
+ font: UiFont,
+ iconSize: number,
+ x: number,
+ top: number,
+ height: number,
+ shade: number,
+): void {
+ if (reading.condition) {
+ const icon = renderWeatherIcon(reading.condition, reading.isDaytime, iconSize);
+ if (icon) image.drawImage(icon, x, top + (((height - icon.height) / 2) | 0));
+ x += iconSize + READING_ICON_GAP;
+ }
+ image.drawText(font, x, top + Math.max(0, ((height - font.lineHeight) / 2) | 0), reading.temperature, shade);
+}
diff --git a/app/apps/weather/weather-indicators.ts b/app/apps/weather/weather-indicators.ts
new file mode 100644
index 00000000..4ff28fef
--- /dev/null
+++ b/app/apps/weather/weather-indicators.ts
@@ -0,0 +1,46 @@
+import { GrayImage, type UiFont } from "../../graphics/image";
+import { getDefaultSmallFont } from "../../graphics/ui-fonts";
+import { weatherBridge } from "../../native/weather";
+import { onAnySettingChanged } from "../../ui/dashboard-settings";
+import { shell } from "../../ui/shell/shell";
+import { drawWeatherReading, measureWeatherReading, weatherReading, type WeatherReading } from "./weather-icons";
+import { weatherShowInStatusBarSetting, weatherShowOnSystemCardSetting } from "./weather-settings";
+
+const TRAY_ICON_ID = "weather";
+const TRAY_HEIGHT = 24;
+const TRAY_ICON_SIZE = 20;
+
+let started = false;
+/** What the tray currently shows, to skip rebuilding an unchanged icon. */
+let trayShown: { key: string; font: UiFont } | null = null;
+
+/**
+ * Shell-lifetime subscription: keeps the hourly background refresh running
+ * while the status-bar or system-card indicator is enabled, and the tray
+ * icon in sync. The system card reads the bridge itself while it shows.
+ */
+export function startWeatherIndicators(): void {
+ if (started) return;
+ started = true;
+ weatherBridge.onStateChange(syncWeatherIndicators);
+ onAnySettingChanged(syncWeatherIndicators);
+}
+
+function syncWeatherIndicators(): void {
+ const inStatusBar = weatherShowInStatusBarSetting.get();
+ weatherBridge.setBackgroundRefresh(inStatusBar || weatherShowOnSystemCardSetting.get());
+
+ const reading = inStatusBar ? weatherReading(weatherBridge.snapshot(), Date.now()) : null;
+ const font = getDefaultSmallFont();
+ const key = reading ? `${reading.condition}|${reading.isDaytime}|${reading.temperature}` : null;
+ if (key === (trayShown?.key ?? null) && (!trayShown || trayShown.font === font)) return;
+ trayShown = key === null ? null : { key, font };
+ shell.setTrayIcon(TRAY_ICON_ID, reading ? buildWeatherTrayIcon(reading, font) : null);
+}
+
+/** Condition icon and temperature, baked to a raster so the tray keeps one stable image. */
+function buildWeatherTrayIcon(reading: WeatherReading, font: UiFont): GrayImage {
+ const image = new GrayImage(Math.ceil(measureWeatherReading(reading, font, TRAY_ICON_SIZE)), TRAY_HEIGHT, 0);
+ drawWeatherReading(image, reading, font, TRAY_ICON_SIZE, 0, 0, TRAY_HEIGHT, 220);
+ return image.withDrawsBaked();
+}
diff --git a/app/apps/weather/weather-settings.ts b/app/apps/weather/weather-settings.ts
new file mode 100644
index 00000000..df86efa4
--- /dev/null
+++ b/app/apps/weather/weather-settings.ts
@@ -0,0 +1,24 @@
+import { ConfigSettingBoolean } from "../../ui/dashboard-settings";
+
+/**
+ * Where current conditions show outside the Weather app. While either is on
+ * and the glasses are connected, the weather bridge refreshes hourly (see
+ * weather-indicators.ts).
+ */
+export const weatherShowInStatusBarSetting = new ConfigSettingBoolean({
+ id: "weather-show-in-status-bar",
+ label: "Show in status bar",
+ storageKey: "weather.showInStatusBar",
+ defaultValue: false,
+ description:
+ "Show the current conditions and temperature in the top bar. Weather for your current location is fetched once an hour while the glasses are connected.",
+});
+
+export const weatherShowOnSystemCardSetting = new ConfigSettingBoolean({
+ id: "weather-show-on-system-card",
+ label: "Show on system card",
+ storageKey: "weather.showOnSystemCard",
+ defaultValue: false,
+ description:
+ "Show the current conditions and temperature on the Glanceboard's system card. Weather for your current location is fetched once an hour while the glasses are connected.",
+});
diff --git a/app/apps/weather/weather.ts b/app/apps/weather/weather.ts
index d32d2e3f..db97c810 100644
--- a/app/apps/weather/weather.ts
+++ b/app/apps/weather/weather.ts
@@ -6,11 +6,18 @@ import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext } from "../../ui/layers";
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
import { centeredTextY, lineStep, tightRowHeight } from "../../ui/metrics";
+import { renderWeatherIcon } from "./weather-icons";
const PAGE_X = 18;
const HEADER_Y = 8;
const CURRENT_TOP = 34;
+/** Minimum x of the description column right of the temperature. */
const CURRENT_TEXT_X = 112;
+/** The current-conditions icon, left of the temperature. */
+const CURRENT_ICON_SIZE = 40;
+const CURRENT_ICON_GAP = 10;
+/** Gap between the temperature and the description column. */
+const CURRENT_TEXT_GAP = 16;
const FORECAST_HEADER_Y = 105;
const FORECAST_TOP = 124;
/** Forecast rows hold a 20px icon; grow with the font past that. */
@@ -70,7 +77,8 @@ export class WeatherLayer implements Layer {
);
return image;
}
- if (weather.phase === "locating" || weather.phase === "loading") {
+ // A refresh with earlier data in hand keeps showing that data.
+ if ((weather.phase === "locating" || weather.phase === "loading") && !weather.current) {
this.drawMessage(image, font, width, height, weather.status);
return image;
}
@@ -94,7 +102,7 @@ export class WeatherLayer implements Layer {
}
return;
}
- if (!weather.forecast.length || weather.phase !== "ready") return;
+ if (!weather.forecast.length || !showsForecast(weather)) return;
if (event.type === "scroll-up" || event.type === "scroll-down") {
this.forecastMenu.setItems(weather.forecast);
void this.forecastMenu.handleInput(event);
@@ -108,16 +116,24 @@ export class WeatherLayer implements Layer {
const medium = getDefaultMediumFont();
const small = getDefaultSmallFont();
const temperature = current.temperatureF === null ? "--°" : `${Math.round(current.temperatureF)}°F`;
- image.drawText(large, PAGE_X, CURRENT_TOP + 8, temperature, 245);
+ const temperatureY = CURRENT_TOP + 8;
+ let temperatureX = PAGE_X;
+ if (current.condition) {
+ const icon = renderWeatherIcon(current.condition, current.isDaytime, CURRENT_ICON_SIZE);
+ if (icon) image.drawImage(icon, PAGE_X, temperatureY + (((large.lineHeight - icon.height) / 2) | 0));
+ temperatureX += CURRENT_ICON_SIZE + CURRENT_ICON_GAP;
+ }
+ image.drawText(large, temperatureX, temperatureY, temperature, 245);
+ const textX = Math.max(CURRENT_TEXT_X, temperatureX + Math.ceil(large.measureText(temperature)) + CURRENT_TEXT_GAP);
// Description / details / source stack compactly from just below the
// header line, so at large font sizes they stay clear of the forecast
// table instead of running into it.
let cy = 30;
image.drawText(
medium,
- CURRENT_TEXT_X,
+ textX,
cy,
- truncateText(medium, current.description || "Current conditions", width - CURRENT_TEXT_X - PAGE_X),
+ truncateText(medium, current.description || "Current conditions", width - textX - PAGE_X),
220,
);
cy += medium.lineHeight + 2;
@@ -127,11 +143,12 @@ export class WeatherLayer implements Layer {
if (current.windSpeedMph !== null) {
details.push(`Wind ${current.windDirection ? `${current.windDirection} ` : ""}${Math.round(current.windSpeedMph)} mph`);
}
- image.drawText(small, CURRENT_TEXT_X, cy, details.join(" ") || "Current forecast", 170);
+ image.drawText(small, textX, cy, details.join(" ") || "Current forecast", 170);
cy += lineStep(small);
const source = current.observed ? "Observed" : "Forecast";
const age = current.timestampMs ? formatAge(Date.now() - current.timestampMs) : "";
- image.drawText(small, CURRENT_TEXT_X, cy, `${source}${age ? ` ${age}` : ""}`, 105);
+ const updating = weather.phase === "locating" || weather.phase === "loading" ? " · updating" : "";
+ image.drawText(small, textX, cy, `${source}${age ? ` ${age}` : ""}${updating}`, 105);
image.drawLine(PAGE_X, FORECAST_HEADER_Y - 7, width - PAGE_X, FORECAST_HEADER_Y - 7, 40);
}
@@ -216,6 +233,12 @@ export class WeatherLayer implements Layer {
}
}
+/** Whether paint shows the forecast table (ready, or refreshing over earlier data). */
+function showsForecast(weather: WeatherState): boolean {
+ if (weather.phase === "ready") return true;
+ return (weather.phase === "locating" || weather.phase === "loading") && weather.current !== null;
+}
+
/** Forecast row pitch, including the gap between selection boxes. */
function forecastRowHeight(font: UiFont): number {
return Math.max(FORECAST_MIN_ROW_HEIGHT, tightRowHeight(font) + 3);
diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts
index 7f6ab9e6..c5cbfb5c 100644
--- a/app/g2/dashboard-controller.ts
+++ b/app/g2/dashboard-controller.ts
@@ -14,6 +14,7 @@ import * as frameTimings from "../native/frame-timings";
import { startForegroundNotification, stopForegroundNotification, updateForegroundNotification } from "../native/foreground-service";
import { mediaControllerBridge } from "../native/media-controller";
import { nightscoutBridge } from "../native/nightscout-bridge";
+import { weatherBridge } from "../native/weather";
import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, readActiveNotifications } from "../native/notification-icons";
import { shouldShowNotificationOnGlasses } from "../native/notification-sources";
import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict";
@@ -1626,6 +1627,7 @@ class DashboardController {
await mediaControllerBridge.start();
await nightscoutBridge.start();
+ weatherBridge.setSessionActive(true);
// Register the compositor surfaces: the shell chrome above all windows,
// and a surface per live window (only the foreground one is composited).
await communicator.configureSurface(SHELL_SURFACE_ID, {
@@ -1693,6 +1695,7 @@ class DashboardController {
this.offVoiceStatus = null;
await mediaControllerBridge.stop().catch(() => {});
await nightscoutBridge.stop().catch(() => {});
+ weatherBridge.setSessionActive(false);
voiceControlBridge.stop();
if (communicator) {
await communicator.setFaceclawWakeLeaseEnabled(false).catch(() => false);
@@ -1835,6 +1838,7 @@ class DashboardController {
// Faceclaw's final BLE message before the transport closes.
await mediaControllerBridge.stop().catch(() => {});
await nightscoutBridge.stop().catch(() => {});
+ weatherBridge.setSessionActive(false);
voiceControlBridge.handleSessionEnded();
const cleanupAcked = skipFirmwareCleanup
diff --git a/app/g2/ios-preview-controller.ts b/app/g2/ios-preview-controller.ts
index 1c09eda8..12c1574e 100644
--- a/app/g2/ios-preview-controller.ts
+++ b/app/g2/ios-preview-controller.ts
@@ -17,6 +17,7 @@ import { bindCompassSession, receiveCompassEvent } from '../native/compass.ios'
import { Dialogs, File, knownFolders, path, Utils, type ImageSource } from '@nativescript/core'
import { iosVoiceInput } from '../native/ios-voice-input'
import { nightscoutBridge } from '../native/nightscout-bridge'
+import { weatherBridge } from '../native/weather'
import { FaceclawCommunicatorBridge, resolveIosPeripherals, type CommunicatorState, type RawInputEvent } from '../native/faceclaw-communicator.ios'
import { PreviewDisplayTarget, type DisplayTarget } from '../native/preview-display.ios'
import { AncsClient, ANCS_FIRMWARE_VERSION } from './ancs-client'
@@ -296,6 +297,7 @@ export class IosPreviewController {
for (const window of shell.getWindows()) window.setScreenOn?.(running && shell.isScreenOn())
if (!running) {
void nightscoutBridge.stop().catch(error => this.fail(error))
+ weatherBridge.setSessionActive(false)
this.glance.dismiss()
void this.display?.setScreenBlanked(!shell.isScreenOn()).catch(error => this.fail(error))
this.offSettings?.(); this.offSettings = null
@@ -319,6 +321,7 @@ export class IosPreviewController {
this.handlePhoneLockState(!UIApplication.sharedApplication.protectedDataAvailable)
this.syncLockSetting()
void nightscoutBridge.start().catch(error => this.fail(error))
+ weatherBridge.setSessionActive(true)
for (const name of [UIDeviceBatteryLevelDidChangeNotification, UIDeviceBatteryStateDidChangeNotification]) {
this.batteryObservers.push(NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(name, null, NSOperationQueue.mainQueue, () => this.requestShellRender()))
}
diff --git a/app/native/weather.ts b/app/native/weather.ts
index f1e98a5f..e8e55dcb 100644
--- a/app/native/weather.ts
+++ b/app/native/weather.ts
@@ -1,10 +1,25 @@
import { hasLocationPermission } from "./location-permissions";
import { getCurrentLocation, type CurrentLocation } from "./location";
+import { getStringSetting, setStringSetting } from "./settings-store";
import { fetchWithUserAgent } from "../util/http";
import { USER_AGENT } from "../version";
export type WeatherPhase = "permission-required" | "locating" | "loading" | "ready" | "error";
+/** Sky and precipitation state, as coarse as the icons that show it. */
+export type WeatherCondition =
+ | "clear"
+ | "partly-cloudy"
+ | "cloudy"
+ | "fog"
+ | "wind"
+ | "drizzle"
+ | "showers"
+ | "rain"
+ | "thunderstorm"
+ | "snow"
+ | "sleet";
+
export type CurrentWeather = {
temperatureF: number | null;
description: string;
@@ -13,6 +28,8 @@ export type CurrentWeather = {
windDirection: string;
timestampMs: number | null;
observed: boolean;
+ condition: WeatherCondition | null;
+ isDaytime: boolean;
};
export type ForecastPeriod = {
@@ -25,6 +42,7 @@ export type ForecastPeriod = {
windSpeed: string;
windDirection: string;
isDaytime: boolean;
+ condition: WeatherCondition | null;
};
export type WeatherState = {
@@ -64,6 +82,7 @@ type NwsForecastPeriodResponse = {
windSpeed?: unknown;
windDirection?: unknown;
isDaytime?: unknown;
+ icon?: unknown;
};
type NwsStationsResponse = {
@@ -74,6 +93,7 @@ type NwsObservationResponse = {
properties?: {
timestamp?: unknown;
textDescription?: unknown;
+ icon?: unknown;
temperature?: NwsMeasure;
relativeHumidity?: NwsMeasure;
windSpeed?: NwsMeasure;
@@ -92,9 +112,17 @@ const NWS_HEADERS = {
// NWS asks callers to identify themselves with a contact address.
"User-Agent": `${USER_AGENT} (https://github.com/jimrandomh/faceclaw)`,
};
-const WEATHER_REFRESH_MS = 30 * 60 * 1000;
+/** Refresh period while the Weather app is open. */
+const APP_REFRESH_MS = 30 * 60 * 1000;
+/** Refresh period for the status-bar and system-card indicators. */
+const BACKGROUND_REFRESH_MS = 60 * 60 * 1000;
+/** Delay before retrying after a failed refresh (capped at the period). */
+const RETRY_AFTER_FAILURE_MS = 10 * 60 * 1000;
const FETCH_TIMEOUT_MS = 20_000;
const MAX_FORECAST_PERIODS = 14;
+/** Settings-store key holding the last successful refresh. */
+const CACHE_KEY = "weather.cache";
+const CACHE_VERSION = 1;
const DEFAULT_STATE: WeatherState = {
phase: "permission-required",
@@ -105,12 +133,31 @@ const DEFAULT_STATE: WeatherState = {
lastUpdatedMs: null,
};
-/** Shared weather state and periodic refresh, active only while its app is open. */
+type WeatherCache = {
+ version: number;
+ locationName: string;
+ current: CurrentWeather | null;
+ forecast: ForecastPeriod[];
+ lastUpdatedMs: number;
+};
+
+/**
+ * Shared weather state, refreshed on a schedule while anything shows it:
+ * every 30 minutes while the Weather app is open, and hourly while a weather
+ * indicator (status bar or Glanceboard system card) is enabled and the
+ * glasses session is up. The last successful refresh is persisted, so a
+ * restart shows it at once and the schedule counts from its age.
+ */
export class WeatherBridge {
private readonly listeners = new Set<(state: WeatherState) => void>();
- private state: WeatherState = cloneState(DEFAULT_STATE);
- private refreshHandle: ReturnType | null = null;
+ private loadedState: WeatherState | null = null;
+ private refreshTimer: ReturnType | null = null;
private refreshInFlight: Promise | null = null;
+ /** Start of the latest refresh attempt, successful or not. */
+ private lastAttemptMs: number | null = null;
+ private appOpen = false;
+ private sessionActive = false;
+ private backgroundWanted = false;
onStateChange(listener: (state: WeatherState) => void): () => void {
this.listeners.add(listener);
@@ -122,25 +169,40 @@ export class WeatherBridge {
return cloneState(this.state);
}
+ /** The Weather app opened (or asked to retry): refresh now, then every 30 minutes. */
start(): void {
- if (!this.refreshHandle) {
- this.refreshHandle = setInterval(() => void this.refreshNow(), WEATHER_REFRESH_MS);
- }
+ this.appOpen = true;
void this.refreshNow();
}
+ /** The Weather app closed; any indicator schedule continues. */
stop(): void {
- if (this.refreshHandle) {
- clearInterval(this.refreshHandle);
- this.refreshHandle = null;
- }
+ this.appOpen = false;
+ this.schedule();
+ }
+
+ /** Whether a glasses session is up; indicator refreshes only run during one. */
+ setSessionActive(active: boolean): void {
+ if (active === this.sessionActive) return;
+ this.sessionActive = active;
+ this.schedule();
+ }
+
+ /** Whether an indicator wants hourly refreshes (see app/apps/weather/weather-indicators.ts). */
+ setBackgroundRefresh(enabled: boolean): void {
+ if (enabled === this.backgroundWanted) return;
+ this.backgroundWanted = enabled;
+ this.schedule();
}
async refreshNow(): Promise {
if (this.refreshInFlight) return this.refreshInFlight;
+ this.clearRefreshTimer();
+ this.lastAttemptMs = Date.now();
if (!hasLocationPermission()) {
this.state = cloneState(DEFAULT_STATE);
this.emit();
+ this.schedule();
return;
}
@@ -149,6 +211,48 @@ export class WeatherBridge {
await this.refreshInFlight;
} finally {
this.refreshInFlight = null;
+ this.schedule();
+ }
+ }
+
+ private get state(): WeatherState {
+ if (!this.loadedState) this.loadedState = loadCachedState();
+ return this.loadedState;
+ }
+
+ private set state(state: WeatherState) {
+ this.loadedState = state;
+ }
+
+ private refreshIntervalMs(): number | null {
+ if (this.appOpen) return APP_REFRESH_MS;
+ if (this.sessionActive && this.backgroundWanted) return BACKGROUND_REFRESH_MS;
+ return null;
+ }
+
+ /**
+ * Arm the timer for the next refresh: one period after the last success,
+ * but no sooner than the retry delay after a failed attempt.
+ */
+ private schedule(): void {
+ this.clearRefreshTimer();
+ // A running refresh reschedules when it settles.
+ if (this.refreshInFlight) return;
+ const intervalMs = this.refreshIntervalMs();
+ if (intervalMs === null) return;
+ const lastSuccessMs = this.state.lastUpdatedMs ?? -Infinity;
+ const lastAttemptMs = this.lastAttemptMs ?? -Infinity;
+ const dueMs = Math.max(lastSuccessMs + intervalMs, lastAttemptMs + Math.min(intervalMs, RETRY_AFTER_FAILURE_MS));
+ this.refreshTimer = setTimeout(() => {
+ this.refreshTimer = null;
+ void this.refreshNow();
+ }, Math.max(0, dueMs - Date.now()));
+ }
+
+ private clearRefreshTimer(): void {
+ if (this.refreshTimer) {
+ clearTimeout(this.refreshTimer);
+ this.refreshTimer = null;
}
}
@@ -169,6 +273,7 @@ export class WeatherBridge {
forecast: weather.forecast,
lastUpdatedMs: Date.now(),
};
+ saveCachedState(this.state);
this.emit();
} catch (error) {
const message = friendlyWeatherError(error);
@@ -188,6 +293,51 @@ export class WeatherBridge {
}
}
+/** The persisted last refresh, or the default state when there is none (or no permission to refresh it). */
+function loadCachedState(): WeatherState {
+ try {
+ if (!hasLocationPermission()) return cloneState(DEFAULT_STATE);
+ const raw = getStringSetting(CACHE_KEY, "");
+ if (!raw) return cloneState(DEFAULT_STATE);
+ const cache = JSON.parse(raw) as Partial | null;
+ if (
+ !cache ||
+ cache.version !== CACHE_VERSION ||
+ typeof cache.lastUpdatedMs !== "number" ||
+ !Array.isArray(cache.forecast)
+ ) {
+ return cloneState(DEFAULT_STATE);
+ }
+ return cloneState({
+ phase: "ready",
+ status: "Weather updated.",
+ locationName: typeof cache.locationName === "string" ? cache.locationName : "",
+ current: cache.current && typeof cache.current === "object" ? cache.current : null,
+ forecast: cache.forecast,
+ lastUpdatedMs: cache.lastUpdatedMs,
+ });
+ } catch (error) {
+ console.warn(`weather cache unreadable: ${error}`);
+ return cloneState(DEFAULT_STATE);
+ }
+}
+
+function saveCachedState(state: WeatherState): void {
+ if (state.lastUpdatedMs === null) return;
+ const cache: WeatherCache = {
+ version: CACHE_VERSION,
+ locationName: state.locationName,
+ current: state.current,
+ forecast: state.forecast,
+ lastUpdatedMs: state.lastUpdatedMs,
+ };
+ try {
+ setStringSetting(CACHE_KEY, JSON.stringify(cache));
+ } catch (error) {
+ console.warn(`weather cache write failed: ${error}`);
+ }
+}
+
async function loadNwsWeather(location: CurrentLocation): Promise<{
locationName: string;
current: CurrentWeather;
@@ -260,14 +410,18 @@ function normalizeObservation(
const temperatureF = convertTemperatureToF(properties?.temperature);
const windSpeedMph = convertSpeedToMph(properties?.windSpeed);
const windDegrees = finiteNumber(properties?.windDirection?.value);
+ const textDescription = stringValue(properties?.textDescription);
+ const icon = parseNwsIcon(properties?.icon);
return {
temperatureF: temperatureF ?? hourly?.temperatureF ?? null,
- description: stringValue(properties?.textDescription) || hourly?.shortForecast || "Current conditions",
+ description: textDescription || hourly?.shortForecast || "Current conditions",
humidityPercent: finiteNumber(properties?.relativeHumidity?.value),
windSpeedMph,
windDirection: windDegrees === null ? hourly?.windDirection ?? "" : degreesToCompass(windDegrees),
timestampMs: timestampValue(properties?.timestamp),
observed: true,
+ condition: icon.condition ?? conditionFromText(textDescription) ?? hourly?.condition ?? null,
+ isDaytime: icon.isDaytime ?? hourly?.isDaytime ?? isLocalDaytime(),
};
}
@@ -281,6 +435,8 @@ function currentFromHourly(hourly: ForecastPeriod | undefined, fallback: Forecas
windDirection: source.windDirection,
timestampMs: source.startTimeMs || null,
observed: false,
+ condition: source.condition,
+ isDaytime: source.isDaytime,
};
}
@@ -289,19 +445,93 @@ function normalizeForecastPeriod(value: NwsForecastPeriodResponse): ForecastPeri
const name = stringValue(value.name);
const temperature = finiteNumber(value.temperature);
const unit = stringValue(value.temperatureUnit).toUpperCase();
+ const shortForecast = stringValue(value.shortForecast);
+ const icon = parseNwsIcon(value.icon);
return {
name: name || "Forecast",
startTimeMs: timestampValue(value.startTime) ?? 0,
temperatureF: temperature === null ? null : unit === "C" ? temperature * 9 / 5 + 32 : temperature,
- shortForecast: stringValue(value.shortForecast),
+ shortForecast,
detailedForecast: stringValue(value.detailedForecast),
precipitationPercent: finiteNumber(value.probabilityOfPrecipitation?.value),
windSpeed: stringValue(value.windSpeed),
windDirection: stringValue(value.windDirection),
- isDaytime: Boolean(value.isDaytime),
+ isDaytime: icon.isDaytime ?? Boolean(value.isDaytime),
+ condition: icon.condition ?? conditionFromText(shortForecast),
};
}
+// NWS icon codes (https://api.weather.gov/icons) by the condition they show.
+const NWS_ICON_CONDITIONS: Record = {
+ skc: "clear",
+ hot: "clear",
+ cold: "clear",
+ few: "partly-cloudy",
+ sct: "partly-cloudy",
+ bkn: "cloudy",
+ ovc: "cloudy",
+ wind_skc: "wind",
+ wind_few: "wind",
+ wind_sct: "wind",
+ wind_bkn: "wind",
+ wind_ovc: "wind",
+ fog: "fog",
+ haze: "fog",
+ smoke: "fog",
+ dust: "fog",
+ rain: "rain",
+ rain_showers: "rain",
+ rain_showers_hi: "showers",
+ tsra: "thunderstorm",
+ tsra_sct: "thunderstorm",
+ tsra_hi: "thunderstorm",
+ tornado: "thunderstorm",
+ hurricane: "thunderstorm",
+ tropical_storm: "thunderstorm",
+ snow: "snow",
+ blizzard: "snow",
+ sleet: "sleet",
+ fzra: "sleet",
+ rain_fzra: "sleet",
+ snow_fzra: "sleet",
+ rain_sleet: "sleet",
+ snow_sleet: "sleet",
+ rain_snow: "sleet",
+};
+
+/**
+ * Condition and day/night from an NWS icon URL such as
+ * ".../icons/land/day/tsra_sct,40/rain,20?size=medium". A period that
+ * changes partway lists two codes; the first is the one in effect now.
+ */
+function parseNwsIcon(value: unknown): { condition: WeatherCondition | null; isDaytime: boolean | null } {
+ const match = stringValue(value).match(/\/icons\/[^/]+\/(day|night)\/([a-z_]+)/);
+ if (!match) return { condition: null, isDaytime: null };
+ return { condition: NWS_ICON_CONDITIONS[match[2]!] ?? null, isDaytime: match[1] === "day" };
+}
+
+/** Condition from an NWS text description ("Chance Rain Showers"), for when there is no icon. */
+function conditionFromText(text: string): WeatherCondition | null {
+ const lower = text.toLowerCase();
+ if (/thunder|t-storm|tstorm/.test(lower)) return "thunderstorm";
+ if (/freezing|sleet|ice pellets|wintry|hail|rain and snow|snow and rain/.test(lower)) return "sleet";
+ if (/snow|flurr|blizzard/.test(lower)) return "snow";
+ if (/drizzle/.test(lower)) return "drizzle";
+ if (/rain|showers/.test(lower)) return /chance|slight|scattered|isolated|patchy/.test(lower) ? "showers" : "rain";
+ if (/fog|haze|smoke|dust|mist/.test(lower)) return "fog";
+ if (/windy|breezy|blustery/.test(lower)) return "wind";
+ if (/partly|few clouds|mostly sunny|mostly clear/.test(lower)) return "partly-cloudy";
+ if (/cloud|overcast/.test(lower)) return "cloudy";
+ if (/sunny|clear|fair/.test(lower)) return "clear";
+ return null;
+}
+
+/** Rough day/night by the phone's clock, for when NWS gives no hint. */
+function isLocalDaytime(): boolean {
+ const hour = new Date().getHours();
+ return hour >= 6 && hour < 18;
+}
+
function convertTemperatureToF(measure: NwsMeasure | undefined): number | null {
const value = finiteNumber(measure?.value);
if (value === null) return null;
diff --git a/tests/ios-glanceboard.test.cjs b/tests/ios-glanceboard.test.cjs
index 63bd2f94..30c1155a 100644
--- a/tests/ios-glanceboard.test.cjs
+++ b/tests/ios-glanceboard.test.cjs
@@ -143,6 +143,7 @@ function fixture() {
'../native/preview-display.ios': { PreviewDisplayTarget },
'./ancs-client': { ANCS_FIRMWARE_VERSION: 16, AncsClient: class { state = 'disconnected'; start() {} stop() {} stopCommand() { return new Uint8Array(); } receive() { return false; } } },
'../native/nightscout-bridge': { nightscoutBridge: { async start() {}, async stop() {} } },
+ '../native/weather': { weatherBridge: { setSessionActive() {} } },
'./glance-host': { GlanceHost }, './events': events,
'./lock-screen': { LOCK_SCREEN_SURFACE_ID: 'lock-screen', createLockScreenImage: () => new images.GrayImage(640, 480, 123) },
'./device-addresses': { loadDeviceAddresses: () => ({ right: 'AA', left: 'BB', ring: '' }) }, './ios-peripheral-identity': { deviceAddressError: () => null },
diff --git a/tests/ios-location.test.cjs b/tests/ios-location.test.cjs
index 01f384e7..cdc5d5df 100644
--- a/tests/ios-location.test.cjs
+++ b/tests/ios-location.test.cjs
@@ -93,8 +93,9 @@ test('Navigate host releases GPS and compass together and ignores an old stream
test('Weather uses the portable location provider and preserves NWS parsing', async () => {
const requests = [], timers = new Set(); let permission = true;
const period = { name: 'Today', temperature: 70, temperatureUnit: 'F', shortForecast: 'Sunny', windSpeed: '5 mph', windDirection: 'W' };
- const api = loader({ setTimeout, clearTimeout, setInterval: fn => { timers.add(fn); return fn; }, clearInterval: fn => timers.delete(fn) }, {
+ const api = loader({ setTimeout: fn => { timers.add(fn); return fn; }, clearTimeout: fn => timers.delete(fn) }, {
'./location-permissions': { hasLocationPermission: () => permission },
+ './settings-store': { getStringSetting: (_key, fallback) => fallback, setStringSetting() {} },
'./location': { getCurrentLocation: async () => fix },
'../version': { USER_AGENT: 'test' },
'../util/http': { fetchWithUserAgent: async url => { requests.push(url); return { ok: true, json: async () =>
@@ -115,6 +116,9 @@ test('closing Weather during permission prompt cannot restart polling', async ()
'../../native/location-permissions': { hasLocationPermission: () => false, ensureLocationPermission: () => new Promise(resolve => { granted = resolve; }) },
'../../native/weather': { weatherBridge: { start() { starts++; }, stop() { stops++; }, onStateChange: () => () => {}, snapshot() {} } },
'./weather': { WeatherLayer: class {} },
+ './weather-settings': {},
+ '../../ui/dashboard-settings': { toggleSettingMenuItem: () => ({}) },
+ '../../ui/dashboard/settings-panel': { openSettingsSubMenu() {} },
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: opts => { options = opts; return { requestRender() {} }; } },
})('app/apps/weather/weather-app.ts');
api.createWeatherAppWindow({ onClosed() {} }); options.onClosed(); granted(true); await flush();
diff --git a/tests/weather.test.cjs b/tests/weather.test.cjs
new file mode 100644
index 00000000..a423b985
--- /dev/null
+++ b/tests/weather.test.cjs
@@ -0,0 +1,199 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { loader } = require('./helpers/load-typescript.cjs');
+
+const HOUR_MS = 60 * 60 * 1000;
+const fix = { latitude: 37.7, longitude: -122.4, accuracyMeters: 8, timestampMs: 1234 };
+
+/** weather.ts with fake timers, settings store and NWS responses. */
+function weatherHarness({ periods, observation = null, store = new Map(), permission = () => true }) {
+ const timers = new Map(), requests = [];
+ let nextTimer = 1;
+ const api = loader({
+ setTimeout: (fn, ms) => { const id = nextTimer++; timers.set(id, { fn: () => { timers.delete(id); fn(); }, ms }); return id; },
+ clearTimeout: id => timers.delete(id),
+ }, {
+ './location-permissions': { hasLocationPermission: permission },
+ './location': { getCurrentLocation: async () => fix },
+ './settings-store': { getStringSetting: (key, fallback) => store.get(key) ?? fallback, setStringSetting: (key, value) => store.set(key, value) },
+ '../version': { USER_AGENT: 'test' },
+ '../util/http': { fetchWithUserAgent: async url => {
+ requests.push(url);
+ let body;
+ if (url.includes('/points/')) {
+ body = { properties: {
+ forecast: 'https://fixture/forecast',
+ observationStations: observation ? 'https://fixture/stations' : undefined,
+ relativeLocation: { properties: { city: 'San Francisco', state: 'CA' } },
+ } };
+ } else if (url === 'https://fixture/stations') {
+ body = { features: [{ id: 'https://fixture/station' }] };
+ } else if (url.endsWith('/observations/latest')) {
+ body = { properties: observation };
+ } else {
+ body = { properties: { periods } };
+ }
+ return { ok: true, json: async () => body };
+ } },
+ })('app/native/weather.ts');
+ // Only the bridge's refresh timer outlives a refresh (fetch timeouts are cleared).
+ const refreshTimer = () => {
+ assert.ok(timers.size <= 1, `expected at most one timer, got ${timers.size}`);
+ return [...timers.values()][0] ?? null;
+ };
+ return { api, store, requests, refreshTimer };
+}
+
+const sunny = { name: 'Today', temperature: 70, temperatureUnit: 'F', shortForecast: 'Sunny', isDaytime: true };
+
+test('Weather takes the condition from the NWS icon, falling back to the text', async () => {
+ const h = weatherHarness({
+ periods: [
+ { ...sunny, icon: 'https://api.weather.gov/icons/land/night/snow,60/rain,20?size=medium' },
+ { ...sunny, name: 'Tonight', shortForecast: 'Chance Rain Showers', isDaytime: false },
+ { ...sunny, name: 'Monday', shortForecast: 'Mostly Cloudy' },
+ ],
+ observation: {
+ textDescription: 'Thunderstorms', icon: 'https://api.weather.gov/icons/land/day/tsra?size=medium',
+ temperature: { value: 20, unitCode: 'wmoUnit:degC' },
+ },
+ });
+ const bridge = new h.api.WeatherBridge();
+ await bridge.refreshNow();
+ const { current, forecast } = bridge.snapshot();
+ assert.equal(current.condition, 'thunderstorm');
+ assert.equal(current.isDaytime, true);
+ assert.equal(current.temperatureF, 68);
+ // The first code of a two-part icon, and its day/night segment.
+ assert.equal(forecast[0].condition, 'snow');
+ assert.equal(forecast[0].isDaytime, false);
+ assert.equal(forecast[1].condition, 'showers');
+ assert.equal(forecast[2].condition, 'cloudy');
+});
+
+test('Weather without an observation takes the condition from the first forecast period', async () => {
+ const h = weatherHarness({ periods: [{ ...sunny, icon: 'https://api.weather.gov/icons/land/day/few?size=medium' }] });
+ const bridge = new h.api.WeatherBridge();
+ await bridge.refreshNow();
+ assert.equal(bridge.snapshot().current.condition, 'partly-cloudy');
+ assert.equal(bridge.snapshot().current.observed, false);
+});
+
+test('Weather restores its cache on restart and refreshes hourly only during a session with an indicator on', async () => {
+ const first = weatherHarness({ periods: [sunny] });
+ const bridge = new first.api.WeatherBridge();
+ await bridge.refreshNow();
+ assert.ok(first.store.get('weather.cache'));
+
+ // A restart shows the cached reading without fetching.
+ const h = weatherHarness({ periods: [sunny], store: first.store });
+ const restarted = new h.api.WeatherBridge();
+ assert.equal(restarted.snapshot().phase, 'ready');
+ assert.equal(restarted.snapshot().current.temperatureF, 70);
+ assert.equal(h.requests.length, 0);
+
+ restarted.setBackgroundRefresh(true);
+ assert.equal(h.refreshTimer(), null, 'no refreshes outside a glasses session');
+ restarted.setSessionActive(true);
+ const timer = h.refreshTimer();
+ assert.ok(timer.ms > HOUR_MS - 60_000 && timer.ms <= HOUR_MS, `fresh cache waits out the hour (${timer.ms})`);
+ restarted.setBackgroundRefresh(false);
+ assert.equal(h.refreshTimer(), null);
+ restarted.setBackgroundRefresh(true);
+ restarted.setSessionActive(false);
+ assert.equal(h.refreshTimer(), null);
+});
+
+test('Weather refreshes a stale cache at once and backs off after a failure', async () => {
+ const store = new Map([['weather.cache', JSON.stringify({
+ version: 1, locationName: 'Old', current: null, forecast: [], lastUpdatedMs: Date.now() - 2 * HOUR_MS,
+ })]]);
+ let permission = true;
+ const h = weatherHarness({ periods: [sunny], store, permission: () => permission });
+ const bridge = new h.api.WeatherBridge();
+ bridge.setBackgroundRefresh(true);
+ bridge.setSessionActive(true);
+ assert.equal(h.refreshTimer().ms, 0);
+
+ h.refreshTimer().fn();
+ await bridge.refreshNow();
+ assert.equal(bridge.snapshot().locationName, 'San Francisco, CA');
+ assert.ok(h.refreshTimer().ms > HOUR_MS - 60_000);
+
+ // Without permission the attempt fails; the next one waits the retry delay, not zero.
+ permission = false;
+ await bridge.refreshNow();
+ assert.equal(bridge.snapshot().phase, 'permission-required');
+ const retry = h.refreshTimer().ms;
+ assert.ok(retry > 9 * 60_000 && retry <= 10 * 60_000, `retry delay ${retry}`);
+});
+
+/** weather-indicators.ts with a fake shell, settings and bridge. */
+function indicatorHarness() {
+ const settings = new Map(), settingListeners = new Set(), stateListeners = new Set(), trays = [];
+ const background = [];
+ let state = { phase: 'ready', current: null, forecast: [], lastUpdatedMs: null };
+ class GrayImage {
+ constructor(width, height) { this.width = width; this.height = height; this.draws = []; }
+ drawImage(_source, x, y) { this.draws.push(['image', x, y]); }
+ drawText(_font, x, y, text) { this.draws.push(['text', x, y, text]); }
+ withDrawsBaked() { return this; }
+ }
+ const font = { lineHeight: 12, measureText: text => text.length * 6 };
+ class Setting {
+ constructor(options) { Object.assign(this, options); }
+ get() { return settings.get(this.storageKey) ?? this.defaultValue; }
+ }
+ const api = loader({}, {
+ '../../graphics/image': { GrayImage },
+ '../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
+ '../../graphics/icons': { renderSvgIcon: (_name, _svg, size) => new GrayImage(size, size) },
+ '../../native/weather': { weatherBridge: {
+ onStateChange: listener => { stateListeners.add(listener); listener(state); return () => stateListeners.delete(listener); },
+ snapshot: () => state,
+ setBackgroundRefresh: enabled => background.push(enabled),
+ } },
+ '../../ui/dashboard-settings': {
+ ConfigSettingBoolean: Setting,
+ onAnySettingChanged: listener => { settingListeners.add(listener); return () => settingListeners.delete(listener); },
+ },
+ '../../ui/shell/shell': { shell: { setTrayIcon: (id, icon) => trays.push([id, icon]) } },
+ })('app/apps/weather/weather-indicators.ts');
+ return {
+ api, trays, background,
+ setSetting(key, value) { settings.set(key, value); for (const listener of settingListeners) listener(); },
+ setState(next) { state = next; for (const listener of stateListeners) listener(state); },
+ };
+}
+
+test('Weather tray icon follows the status-bar setting and hides a stale reading', () => {
+ const h = indicatorHarness();
+ h.api.startWeatherIndicators();
+ assert.deepEqual(h.background, [false]);
+ assert.equal(h.trays.length, 0, 'nothing shown, nothing to clear');
+
+ h.setSetting('weather.showOnSystemCard', true);
+ assert.equal(h.background.at(-1), true, 'the system card alone keeps refreshes running');
+ assert.equal(h.trays.length, 0);
+
+ h.setSetting('weather.showInStatusBar', true);
+ const current = { temperatureF: 71.6, condition: 'rain', isDaytime: true };
+ h.setState({ phase: 'ready', current, forecast: [], lastUpdatedMs: Date.now() });
+ const [id, icon] = h.trays.at(-1);
+ assert.equal(id, 'weather');
+ assert.equal(icon.height, 24);
+ assert.deepEqual(icon.draws.map(draw => draw[0]), ['image', 'text']);
+ assert.equal(icon.draws[1][3], '72°');
+
+ // An unchanged reading does not rebuild the icon.
+ const count = h.trays.length;
+ h.setState({ phase: 'loading', current, forecast: [], lastUpdatedMs: Date.now() });
+ assert.equal(h.trays.length, count);
+
+ h.setState({ phase: 'error', current, forecast: [], lastUpdatedMs: Date.now() - 4 * HOUR_MS });
+ assert.deepEqual(h.trays.at(-1), ['weather', null]);
+
+ h.setSetting('weather.showOnSystemCard', false);
+ h.setSetting('weather.showInStatusBar', false);
+ assert.equal(h.background.at(-1), false);
+});