Merge branch 'fancy-weather' of https://github.com/jimrandomh/faceclaw into merged-testing
This commit is contained in:
commit
9cf180e5a1
14 files changed
+758
-33
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -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:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg>',
|
||||
moon:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"/></svg>',
|
||||
cloud:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>',
|
||||
"cloud-sun":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M12 2v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="M20 12h2"/><path d="m19.07 4.93-1.41 1.41"/><path d="M15.947 12.65a4 4 0 0 0-5.925-4.128"/><path d="M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z"/></svg>',
|
||||
"cloud-moon":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M13 16a3 3 0 0 1 0 6H7a5 5 0 1 1 4.9-6z"/><path d="M18.376 14.512a6 6 0 0 0 3.461-4.127c.148-.625-.659-.97-1.248-.714a4 4 0 0 1-5.259-5.26c.255-.589-.09-1.395-.716-1.248a6 6 0 0 0-4.594 5.36"/></svg>',
|
||||
"cloud-fog":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/><path d="M16 17H7"/><path d="M17 21H9"/></svg>',
|
||||
wind:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M12.8 19.6A2 2 0 1 0 14 16H2"/><path d="M17.5 8a2.5 2.5 0 1 1 2 4H2"/><path d="M9.8 4.4A2 2 0 1 1 11 8H2"/></svg>',
|
||||
"cloud-drizzle":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/><path d="M8 19v1"/><path d="M8 14v1"/><path d="M16 19v1"/><path d="M16 14v1"/><path d="M12 21v1"/><path d="M12 16v1"/></svg>',
|
||||
"cloud-sun-rain":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M12 2v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="M20 12h2"/><path d="m19.07 4.93-1.41 1.41"/><path d="M15.947 12.65a4 4 0 0 0-5.925-4.128"/><path d="M3 20a5 5 0 1 1 8.9-4H13a3 3 0 0 1 2 5.24"/><path d="M11 20v2"/><path d="M7 19v2"/></svg>',
|
||||
"cloud-moon-rain":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M11 20v2"/><path d="M18.376 14.512a6 6 0 0 0 3.461-4.127c.148-.625-.659-.97-1.248-.714a4 4 0 0 1-5.259-5.26c.255-.589-.09-1.395-.716-1.248a6 6 0 0 0-4.594 5.36"/><path d="M3 20a5 5 0 1 1 8.9-4H13a3 3 0 0 1 2 5.24"/><path d="M7 19v2"/></svg>',
|
||||
"cloud-rain":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/><path d="M16 14v6"/><path d="M8 14v6"/><path d="M12 16v6"/></svg>',
|
||||
"cloud-lightning":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M6 16.326A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 .5 8.973"/><path d="m13 12-3 5h4l-3 5"/></svg>',
|
||||
"cloud-snow":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/><path d="M8 15h.01"/><path d="M8 19h.01"/><path d="M12 17h.01"/><path d="M12 21h.01"/><path d="M16 15h.01"/><path d="M16 19h.01"/></svg>',
|
||||
"cloud-hail":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/><path d="M16 14v2"/><path d="M8 14v2"/><path d="M16 20h.01"/><path d="M8 20h.01"/><path d="M12 16v2"/><path d="M12 22h.01"/></svg>',
|
||||
} 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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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.",
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()))
|
||||
}
|
||||
|
||||
+244
-14
@@ -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<typeof setInterval> | null = null;
|
||||
private loadedState: WeatherState | null = null;
|
||||
private refreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private refreshInFlight: Promise<void> | 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<void> {
|
||||
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<WeatherCache> | 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<string, WeatherCondition> = {
|
||||
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;
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
Reference in new issue
Block a user