mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
1 parent
cb165d90d2
commit
2c819c8d0e
13 files changed
+537
-25
No files matched your search
@@ -13,6 +13,9 @@ and others who contributed to documenting the G2's bluetooth protocol and firmwa
|
||||
|
||||
G2 microphone LC3 decoding uses Google's liblc3: https://github.com/google/liblc3
|
||||
|
||||
Weather data outside the US is by Open-Meteo.com: https://open-meteo.com/. It is
|
||||
licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/).
|
||||
|
||||
The Terminus font is by Dimitar Zhekov's Terminus: https://framagit.org/ohnonot/terv-terc
|
||||
and is distributed under the SIL Open Font License; see app/fonts/terminus/LICENSE.
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import android.content.Context
|
||||
import android.location.Address
|
||||
import android.location.Geocoder
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import java.util.Locale
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
/**
|
||||
* Place name for the Weather header where the weather source doesn't supply
|
||||
* one (outside National Weather Service coverage), from Android's own
|
||||
* Geocoder. Its lookup blocks on the network, so it runs on a thread of its
|
||||
* own; the listener hears back on the main thread, with nulls when the phone
|
||||
* has no geocoder or the lookup fails.
|
||||
*/
|
||||
class FaceclawReverseGeocoder(context: Context) {
|
||||
interface Listener {
|
||||
fun onResult(locality: String?, region: String?, country: String?)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "FaceclawGeocoder"
|
||||
}
|
||||
|
||||
private val context: Context = context.applicationContext
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
fun lookup(latitude: Double, longitude: Double, listener: Listener) {
|
||||
thread(name = "FaceclawReverseGeocoder", isDaemon = true) {
|
||||
val address = lookupBlocking(latitude, longitude)
|
||||
mainHandler.post { listener.onResult(address?.locality, address?.adminArea, address?.countryName) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun lookupBlocking(latitude: Double, longitude: Double): Address? {
|
||||
if (!Geocoder.isPresent()) {
|
||||
return null
|
||||
}
|
||||
return try {
|
||||
// The listener form needs API 33; this one is fine off the main thread.
|
||||
@Suppress("DEPRECATION")
|
||||
Geocoder(context, Locale.getDefault()).getFromLocation(latitude, longitude, 1)?.firstOrNull()
|
||||
} catch (error: Throwable) {
|
||||
Log.w(TAG, "reverse geocode failed: $error")
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
## 0.8.5 - Future
|
||||
|
||||
### Features
|
||||
|
||||
* Use Open-Meteo for weather in regions that the US National Weather Service doesn't cover
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* Inverting Android notification-icons to indicate selectionis now gamma-correct
|
||||
|
||||
@@ -145,7 +145,12 @@ transmitted to Mapbox, and are subject to Mapbox's privacy policy.
|
||||
Mapbox: https://www.mapbox.com/legal/privacy
|
||||
|
||||
The Weather app will retrieve the user's coarse location, and will use it to
|
||||
query a third-party weather information provider.
|
||||
query a third-party weather information provider: the US National Weather
|
||||
Service, then Open-Meteo if the location is outside the US. Outside the US, it
|
||||
also asks the phone's built-in geocoder (Google's on most Android phones,
|
||||
Apple's on iOS) for the name of the place.
|
||||
|
||||
Open-Meteo: https://open-meteo.com/en/terms
|
||||
|
||||
|
||||
## EvenHub
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
export const WEATHER_WINDOW_ID = "weather";
|
||||
export const WEATHER_SURFACE_ID = "window:weather";
|
||||
|
||||
/** Local current conditions and forecast from the National Weather Service. */
|
||||
/** Local current conditions and forecast from the National Weather Service, or Open-Meteo outside the US. */
|
||||
export function createWeatherAppWindow(options: InProcessAppOptions): InProcessWindow {
|
||||
let closed = false;
|
||||
let requestingPermission = false;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { getDefaultLargeFont, getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { wrapText, truncateText } from "../../graphics/textwrap";
|
||||
import { type ForecastPeriod, type WeatherState } from "../../native/weather";
|
||||
import { WEATHER_SOURCE_NAMES, type ForecastPeriod, type WeatherState } from "../../native/weather";
|
||||
import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures";
|
||||
import { type Layer, type LayerContext } from "../../ui/layers";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
@@ -145,7 +145,9 @@ export class WeatherLayer implements Layer {
|
||||
}
|
||||
image.drawText(small, textX, cy, details.join(" ") || "Current forecast", 170);
|
||||
cy += lineStep(small);
|
||||
const source = current.observed ? "Observed" : "Forecast";
|
||||
// Naming the source also credits Open-Meteo, as its CC BY licence asks.
|
||||
const sourceName = weather.source ? `${WEATHER_SOURCE_NAMES[weather.source]} ` : "";
|
||||
const source = `${sourceName}${current.observed ? "observed" : "forecast"}`;
|
||||
const age = current.timestampMs ? formatAge(Date.now() - current.timestampMs) : "";
|
||||
const updating = weather.phase === "locating" || weather.phase === "loading" ? " · updating" : "";
|
||||
image.drawText(small, textX, cy, `${source}${age ? ` ${age}` : ""}${updating}`, 105);
|
||||
|
||||
@@ -5,6 +5,15 @@ export type CurrentLocation = {
|
||||
timestampMs: number;
|
||||
};
|
||||
|
||||
/** A reverse-geocoded place; parts the geocoder doesn't know are empty. */
|
||||
export type Place = {
|
||||
/** City or town. */
|
||||
locality: string;
|
||||
/** State, province or similar. */
|
||||
region: string;
|
||||
country: string;
|
||||
};
|
||||
|
||||
export type TrackedLocation = {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { type Place } from './location-types'
|
||||
declare const CLGeocoder: any, CLLocation: any
|
||||
|
||||
/** Geocoders with a lookup in flight, held until their callback so collection can't drop it. */
|
||||
const pending = new Set<any>()
|
||||
|
||||
/** The place at a coordinate from Apple's geocoder, or null when it can't name it. */
|
||||
export function reverseGeocode(latitude: number, longitude: number): Promise<Place | null> {
|
||||
return new Promise(resolve => {
|
||||
const geocoder = CLGeocoder.new()
|
||||
pending.add(geocoder)
|
||||
const location = CLLocation.alloc().initWithLatitudeLongitude(latitude, longitude)
|
||||
geocoder.reverseGeocodeLocationCompletionHandler(location, (placemarks: any, error: any) => {
|
||||
pending.delete(geocoder)
|
||||
const placemark = !error && placemarks && placemarks.count ? placemarks.objectAtIndex(0) : null
|
||||
resolve(placemark
|
||||
? { locality: placemark.locality ?? '', region: placemark.administrativeArea ?? '', country: placemark.country ?? '' }
|
||||
: null)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
import { type Place } from "./location-types";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
/** The place at a coordinate from Android's Geocoder, or null when the phone can't name it. */
|
||||
export function reverseGeocode(latitude: number, longitude: number): Promise<Place | null> {
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) return Promise.resolve(null);
|
||||
return new Promise<Place | null>((resolve) => {
|
||||
const geocoder = new com.faceclaw.app.FaceclawReverseGeocoder(context);
|
||||
// The lookup thread holds the listener proxy until its one callback.
|
||||
geocoder.lookup(latitude, longitude, new com.faceclaw.app.FaceclawReverseGeocoder.Listener({
|
||||
onResult: (locality: string | null, region: string | null, country: string | null) => {
|
||||
resolve({ locality: locality ? String(locality) : "", region: region ? String(region) : "", country: country ? String(country) : "" });
|
||||
},
|
||||
}));
|
||||
});
|
||||
}
|
||||
+296
-17
@@ -1,11 +1,22 @@
|
||||
import { hasLocationPermission } from "./location-permissions";
|
||||
import { getCurrentLocation, type CurrentLocation } from "./location";
|
||||
import { type Place } from "./location-types";
|
||||
import { reverseGeocode } from "./reverse-geocode";
|
||||
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";
|
||||
|
||||
/** National Weather Service in the US, Open-Meteo everywhere else. */
|
||||
export type WeatherSource = "nws" | "open-meteo";
|
||||
|
||||
/** Short source names for the Weather app's credit line. */
|
||||
export const WEATHER_SOURCE_NAMES: Record<WeatherSource, string> = {
|
||||
nws: "NWS",
|
||||
"open-meteo": "Open-Meteo",
|
||||
};
|
||||
|
||||
/** Sky and precipitation state, as coarse as the icons that show it. */
|
||||
export type WeatherCondition =
|
||||
| "clear"
|
||||
@@ -48,6 +59,8 @@ export type ForecastPeriod = {
|
||||
export type WeatherState = {
|
||||
phase: WeatherPhase;
|
||||
status: string;
|
||||
/** Where current and forecast came from; null until the first refresh. */
|
||||
source: WeatherSource | null;
|
||||
locationName: string;
|
||||
current: CurrentWeather | null;
|
||||
forecast: ForecastPeriod[];
|
||||
@@ -106,12 +119,56 @@ type NwsMeasure = {
|
||||
unitCode?: unknown;
|
||||
};
|
||||
|
||||
type OpenMeteoResponse = {
|
||||
utc_offset_seconds?: unknown;
|
||||
current?: {
|
||||
time?: unknown;
|
||||
temperature_2m?: unknown;
|
||||
relative_humidity_2m?: unknown;
|
||||
is_day?: unknown;
|
||||
weather_code?: unknown;
|
||||
wind_speed_10m?: unknown;
|
||||
wind_direction_10m?: unknown;
|
||||
};
|
||||
hourly?: {
|
||||
time?: unknown;
|
||||
temperature_2m?: unknown;
|
||||
precipitation_probability?: unknown;
|
||||
weather_code?: unknown;
|
||||
wind_speed_10m?: unknown;
|
||||
wind_direction_10m?: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
type LoadedWeather = {
|
||||
source: WeatherSource;
|
||||
locationName: string;
|
||||
current: CurrentWeather;
|
||||
forecast: ForecastPeriod[];
|
||||
};
|
||||
|
||||
const NWS_API_ROOT = "https://api.weather.gov";
|
||||
const NWS_HEADERS = {
|
||||
Accept: "application/geo+json",
|
||||
// NWS asks callers to identify themselves with a contact address.
|
||||
"User-Agent": `${USER_AGENT} (https://github.com/jimrandomh/faceclaw)`,
|
||||
};
|
||||
// Free for non-commercial use without a key; data is CC BY 4.0, credited
|
||||
// on the Weather app's source line and in ACKNOWLEDGEMENTS.md.
|
||||
const OPEN_METEO_FORECAST_URL = "https://api.open-meteo.com/v1/forecast";
|
||||
/**
|
||||
* Days of hourly forecast to ask Open-Meteo for, from local midnight today:
|
||||
* enough that MAX_FORECAST_PERIODS periods from any hour end before it does.
|
||||
*/
|
||||
const OPEN_METEO_FORECAST_DAYS = 8;
|
||||
/** Local hours Open-Meteo forecast days and nights start at, as NWS periods do. */
|
||||
const DAY_START_HOUR = 6;
|
||||
const NIGHT_START_HOUR = 18;
|
||||
/** How long a place-name lookup may hold up an Open-Meteo refresh. */
|
||||
const GEOCODE_TIMEOUT_MS = 10_000;
|
||||
const HOUR_MS = 60 * 60 * 1000;
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
||||
/** 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. */
|
||||
@@ -127,6 +184,7 @@ const CACHE_VERSION = 1;
|
||||
const DEFAULT_STATE: WeatherState = {
|
||||
phase: "permission-required",
|
||||
status: "Location permission is required for local weather.",
|
||||
source: null,
|
||||
locationName: "",
|
||||
current: null,
|
||||
forecast: [],
|
||||
@@ -135,6 +193,8 @@ const DEFAULT_STATE: WeatherState = {
|
||||
|
||||
type WeatherCache = {
|
||||
version: number;
|
||||
/** Absent from caches written before Open-Meteo, which all came from NWS. */
|
||||
source?: WeatherSource;
|
||||
locationName: string;
|
||||
current: CurrentWeather | null;
|
||||
forecast: ForecastPeriod[];
|
||||
@@ -262,12 +322,13 @@ export class WeatherBridge {
|
||||
this.emit();
|
||||
const location = await getCurrentLocation();
|
||||
|
||||
this.state = { ...this.state, phase: "loading", status: "Loading National Weather Service data..." };
|
||||
this.state = { ...this.state, phase: "loading", status: "Loading weather..." };
|
||||
this.emit();
|
||||
const weather = await loadNwsWeather(location);
|
||||
const weather = await loadWeather(location);
|
||||
this.state = {
|
||||
phase: "ready",
|
||||
status: "Weather updated.",
|
||||
source: weather.source,
|
||||
locationName: weather.locationName,
|
||||
current: weather.current,
|
||||
forecast: weather.forecast,
|
||||
@@ -311,6 +372,7 @@ function loadCachedState(): WeatherState {
|
||||
return cloneState({
|
||||
phase: "ready",
|
||||
status: "Weather updated.",
|
||||
source: cache.source === "open-meteo" ? "open-meteo" : "nws",
|
||||
locationName: typeof cache.locationName === "string" ? cache.locationName : "",
|
||||
current: cache.current && typeof cache.current === "object" ? cache.current : null,
|
||||
forecast: cache.forecast,
|
||||
@@ -326,6 +388,7 @@ function saveCachedState(state: WeatherState): void {
|
||||
if (state.lastUpdatedMs === null) return;
|
||||
const cache: WeatherCache = {
|
||||
version: CACHE_VERSION,
|
||||
source: state.source ?? undefined,
|
||||
locationName: state.locationName,
|
||||
current: state.current,
|
||||
forecast: state.forecast,
|
||||
@@ -338,15 +401,23 @@ function saveCachedState(state: WeatherState): void {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadNwsWeather(location: CurrentLocation): Promise<{
|
||||
locationName: string;
|
||||
current: CurrentWeather;
|
||||
forecast: ForecastPeriod[];
|
||||
}> {
|
||||
/** NWS where it has coverage (the US and its territories), Open-Meteo everywhere else. */
|
||||
async function loadWeather(location: CurrentLocation): Promise<LoadedWeather> {
|
||||
return (await loadNwsWeather(location)) ?? loadOpenMeteoWeather(location);
|
||||
}
|
||||
|
||||
/** NWS weather, or null when the location is outside its coverage. */
|
||||
async function loadNwsWeather(location: CurrentLocation): Promise<LoadedWeather | null> {
|
||||
// NWS recommends no more than four decimals for its point lookup.
|
||||
const latitude = location.latitude.toFixed(4);
|
||||
const longitude = location.longitude.toFixed(4);
|
||||
const point = await fetchNwsJson<NwsPointResponse>(`${NWS_API_ROOT}/points/${latitude},${longitude}`);
|
||||
let point: NwsPointResponse;
|
||||
try {
|
||||
point = await fetchNwsJson<NwsPointResponse>(`${NWS_API_ROOT}/points/${latitude},${longitude}`);
|
||||
} catch (error) {
|
||||
if (error instanceof WeatherHttpError && error.status === 404) return null;
|
||||
throw error;
|
||||
}
|
||||
const properties = point.properties;
|
||||
const forecastUrl = stringValue(properties?.forecast);
|
||||
const hourlyUrl = stringValue(properties?.forecastHourly);
|
||||
@@ -369,6 +440,7 @@ async function loadNwsWeather(location: CurrentLocation): Promise<{
|
||||
.find((period): period is ForecastPeriod => period !== null);
|
||||
|
||||
return {
|
||||
source: "nws",
|
||||
locationName: pointLocationName(point, latitude, longitude),
|
||||
current: observation ? normalizeObservation(observation, hourly) : currentFromHourly(hourly, forecast[0]!),
|
||||
forecast,
|
||||
@@ -382,20 +454,26 @@ async function loadLatestObservation(stationsUrl: string): Promise<NwsObservatio
|
||||
return fetchNwsJson<NwsObservationResponse>(`${stationUrl}/observations/latest`);
|
||||
}
|
||||
|
||||
async function fetchNwsJson<T>(url: string): Promise<T> {
|
||||
const request = fetchWithUserAgent(url, { headers: NWS_HEADERS });
|
||||
function fetchNwsJson<T>(url: string): Promise<T> {
|
||||
return fetchWeatherJson<T>(url, "National Weather Service", NWS_HEADERS);
|
||||
}
|
||||
|
||||
/** A weather request the server answered with an error status. */
|
||||
class WeatherHttpError extends Error {
|
||||
constructor(sourceName: string, readonly status: number) {
|
||||
super(`${sourceName} request failed (HTTP ${status}).`);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchWeatherJson<T>(url: string, sourceName: string, headers?: Record<string, string>): Promise<T> {
|
||||
const request = fetchWithUserAgent(url, headers ? { headers } : undefined);
|
||||
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
|
||||
const timeout = new Promise<never>((_resolve, reject) => {
|
||||
timeoutHandle = setTimeout(() => reject(new Error("Weather request timed out.")), FETCH_TIMEOUT_MS);
|
||||
});
|
||||
try {
|
||||
const response = await Promise.race([request, timeout]);
|
||||
if (!response.ok) {
|
||||
if (response.status === 404 && url.includes("/points/")) {
|
||||
throw new Error("This location is outside National Weather Service coverage.");
|
||||
}
|
||||
throw new Error(`National Weather Service request failed (HTTP ${response.status}).`);
|
||||
}
|
||||
if (!response.ok) throw new WeatherHttpError(sourceName, response.status);
|
||||
return (await response.json()) as T;
|
||||
} finally {
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle);
|
||||
@@ -526,6 +604,193 @@ function conditionFromText(text: string): WeatherCondition | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function loadOpenMeteoWeather(location: CurrentLocation): Promise<LoadedWeather> {
|
||||
const latitude = location.latitude.toFixed(4);
|
||||
const longitude = location.longitude.toFixed(4);
|
||||
const query = [
|
||||
`latitude=${latitude}`,
|
||||
`longitude=${longitude}`,
|
||||
"current=temperature_2m,relative_humidity_2m,is_day,weather_code,wind_speed_10m,wind_direction_10m",
|
||||
"hourly=temperature_2m,precipitation_probability,weather_code,wind_speed_10m,wind_direction_10m",
|
||||
`forecast_days=${OPEN_METEO_FORECAST_DAYS}`,
|
||||
// Local-time periods need the location's UTC offset, which timezone=auto adds.
|
||||
"timezone=auto",
|
||||
"timeformat=unixtime",
|
||||
"temperature_unit=fahrenheit",
|
||||
"wind_speed_unit=mph",
|
||||
].join("&");
|
||||
const [response, placeName] = await Promise.all([
|
||||
fetchWeatherJson<OpenMeteoResponse>(`${OPEN_METEO_FORECAST_URL}?${query}`, "Open-Meteo"),
|
||||
lookUpPlaceName(location),
|
||||
]);
|
||||
const forecast = openMeteoForecastPeriods(response, Date.now()).slice(0, MAX_FORECAST_PERIODS);
|
||||
if (!forecast.length) throw new Error("Open-Meteo returned an empty forecast.");
|
||||
return {
|
||||
source: "open-meteo",
|
||||
locationName: placeName || `${latitude}, ${longitude}`,
|
||||
current: normalizeOpenMeteoCurrent(response) ?? currentFromHourly(undefined, forecast[0]!),
|
||||
forecast,
|
||||
};
|
||||
}
|
||||
|
||||
/** Open-Meteo's current conditions, which come from its forecast models rather than a station. */
|
||||
function normalizeOpenMeteoCurrent(response: OpenMeteoResponse): CurrentWeather | null {
|
||||
const current = response.current;
|
||||
if (!current || typeof current !== "object") return null;
|
||||
const wmo = wmoCode(finiteNumber(current.weather_code));
|
||||
const windDegrees = finiteNumber(current.wind_direction_10m);
|
||||
const time = finiteNumber(current.time);
|
||||
const isDay = finiteNumber(current.is_day);
|
||||
return {
|
||||
temperatureF: finiteNumber(current.temperature_2m),
|
||||
description: wmo?.description ?? "Current conditions",
|
||||
humidityPercent: finiteNumber(current.relative_humidity_2m),
|
||||
windSpeedMph: finiteNumber(current.wind_speed_10m),
|
||||
windDirection: windDegrees === null ? "" : degreesToCompass(windDegrees),
|
||||
timestampMs: time === null ? null : time * 1000,
|
||||
observed: false,
|
||||
condition: wmo?.condition ?? null,
|
||||
isDaytime: isDay === null ? isLocalDaytime() : isDay === 1,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* NWS-style day (6am-6pm) and night periods from Open-Meteo's hourly
|
||||
* forecast, in the location's local time: each has its warmest daytime or
|
||||
* coolest nighttime temperature, its highest chance of rain, and the weather
|
||||
* from periodWeatherCode. The current period counts only the hours left in
|
||||
* it. Local time uses today's UTC offset, so periods after a DST change are
|
||||
* an hour off.
|
||||
*/
|
||||
function openMeteoForecastPeriods(response: OpenMeteoResponse, nowMs: number): ForecastPeriod[] {
|
||||
const hourly = response.hourly;
|
||||
const times = numberArray(hourly?.time);
|
||||
const temperatures = numberArray(hourly?.temperature_2m);
|
||||
const precipitation = numberArray(hourly?.precipitation_probability);
|
||||
const codes = numberArray(hourly?.weather_code);
|
||||
const windSpeeds = numberArray(hourly?.wind_speed_10m);
|
||||
const windDirections = numberArray(hourly?.wind_direction_10m);
|
||||
const offsetMs = (finiteNumber(response.utc_offset_seconds) ?? 0) * 1000;
|
||||
const todayIndex = Math.floor((nowMs + offsetMs) / DAY_MS);
|
||||
|
||||
// The hourly indexes of each period still to come, in order.
|
||||
const groups: Array<{ dayIndex: number; isDaytime: boolean; hours: number[] }> = [];
|
||||
times.forEach((time, index) => {
|
||||
if (time === null || time * 1000 + HOUR_MS <= nowMs) return;
|
||||
const localMs = time * 1000 + offsetMs;
|
||||
const hour = new Date(localMs).getUTCHours();
|
||||
const isDaytime = hour >= DAY_START_HOUR && hour < NIGHT_START_HOUR;
|
||||
// A night belongs to the date it starts on.
|
||||
const dayIndex = Math.floor(localMs / DAY_MS) - (hour < DAY_START_HOUR ? 1 : 0);
|
||||
const last = groups[groups.length - 1];
|
||||
if (last && last.dayIndex === dayIndex && last.isDaytime === isDaytime) last.hours.push(index);
|
||||
else groups.push({ dayIndex, isDaytime, hours: [index] });
|
||||
});
|
||||
|
||||
return groups.map(({ dayIndex, isDaytime, hours }) => {
|
||||
const during = (values: Array<number | null>) => hours.map((index) => values[index] ?? null);
|
||||
const wmo = wmoCode(periodWeatherCode(during(codes)));
|
||||
const speeds = during(windSpeeds);
|
||||
const windiest = maxValue(speeds);
|
||||
const windDegrees = windiest === null ? null : windDirections[hours[speeds.indexOf(windiest)]!] ?? null;
|
||||
return {
|
||||
name: openMeteoPeriodName(dayIndex, isDaytime, todayIndex),
|
||||
startTimeMs: times[hours[0]!]! * 1000,
|
||||
temperatureF: isDaytime ? maxValue(during(temperatures)) : minValue(during(temperatures)),
|
||||
shortForecast: wmo?.description ?? "",
|
||||
detailedForecast: "",
|
||||
precipitationPercent: maxValue(during(precipitation)),
|
||||
windSpeed: windiest === null ? "" : `${Math.round(windiest)} mph`,
|
||||
windDirection: windDegrees === null ? "" : degreesToCompass(windDegrees),
|
||||
isDaytime,
|
||||
condition: wmo?.condition ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The most severe weather code that lasts at least two hours of a period (or
|
||||
* its only hour), so one stray hour of drizzle doesn't name it. WMO codes
|
||||
* rise with severity, as Open-Meteo's own daily summaries assume.
|
||||
*/
|
||||
function periodWeatherCode(codes: Array<number | null>): number | null {
|
||||
const known = codes.filter((code): code is number => code !== null).sort((a, b) => b - a);
|
||||
return known.length ? known[Math.min(1, known.length - 1)]! : null;
|
||||
}
|
||||
|
||||
/** "Today", "Tonight", "Friday", "Friday Night", or "Overnight" for last night's remainder. */
|
||||
function openMeteoPeriodName(dayIndex: number, isDaytime: boolean, todayIndex: number): string {
|
||||
if (dayIndex < todayIndex) return "Overnight";
|
||||
if (dayIndex === todayIndex) return isDaytime ? "Today" : "Tonight";
|
||||
const weekday = WEEKDAYS[new Date(dayIndex * DAY_MS).getUTCDay()]!;
|
||||
return isDaytime ? weekday : `${weekday} Night`;
|
||||
}
|
||||
|
||||
// WMO weather interpretation codes, as Open-Meteo reports them
|
||||
// (https://open-meteo.com/en/docs#weather_variable_documentation).
|
||||
const WMO_CODES: Record<number, { description: string; condition: WeatherCondition }> = {
|
||||
0: { description: "Clear", condition: "clear" },
|
||||
1: { description: "Mostly Clear", condition: "partly-cloudy" },
|
||||
2: { description: "Partly Cloudy", condition: "partly-cloudy" },
|
||||
3: { description: "Overcast", condition: "cloudy" },
|
||||
45: { description: "Fog", condition: "fog" },
|
||||
48: { description: "Freezing Fog", condition: "fog" },
|
||||
51: { description: "Light Drizzle", condition: "drizzle" },
|
||||
53: { description: "Drizzle", condition: "drizzle" },
|
||||
55: { description: "Heavy Drizzle", condition: "drizzle" },
|
||||
56: { description: "Light Freezing Drizzle", condition: "sleet" },
|
||||
57: { description: "Freezing Drizzle", condition: "sleet" },
|
||||
61: { description: "Light Rain", condition: "rain" },
|
||||
63: { description: "Rain", condition: "rain" },
|
||||
65: { description: "Heavy Rain", condition: "rain" },
|
||||
66: { description: "Light Freezing Rain", condition: "sleet" },
|
||||
67: { description: "Freezing Rain", condition: "sleet" },
|
||||
71: { description: "Light Snow", condition: "snow" },
|
||||
73: { description: "Snow", condition: "snow" },
|
||||
75: { description: "Heavy Snow", condition: "snow" },
|
||||
77: { description: "Snow Grains", condition: "snow" },
|
||||
80: { description: "Light Rain Showers", condition: "showers" },
|
||||
81: { description: "Rain Showers", condition: "showers" },
|
||||
82: { description: "Heavy Rain Showers", condition: "rain" },
|
||||
85: { description: "Light Snow Showers", condition: "snow" },
|
||||
86: { description: "Heavy Snow Showers", condition: "snow" },
|
||||
95: { description: "Thunderstorms", condition: "thunderstorm" },
|
||||
96: { description: "Thunderstorms and Hail", condition: "thunderstorm" },
|
||||
99: { description: "Thunderstorms and Heavy Hail", condition: "thunderstorm" },
|
||||
};
|
||||
|
||||
function wmoCode(code: number | null): { description: string; condition: WeatherCondition } | undefined {
|
||||
return code === null ? undefined : WMO_CODES[code];
|
||||
}
|
||||
|
||||
/** "Sydney, Australia" from the phone's geocoder, or "" when it can't name the place in time. */
|
||||
async function lookUpPlaceName(location: CurrentLocation): Promise<string> {
|
||||
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
|
||||
const timeout = new Promise<null>((resolve) => {
|
||||
timeoutHandle = setTimeout(() => resolve(null), GEOCODE_TIMEOUT_MS);
|
||||
});
|
||||
try {
|
||||
const place = await Promise.race([
|
||||
reverseGeocode(location.latitude, location.longitude).catch((error) => {
|
||||
console.warn(`weather place lookup failed: ${error}`);
|
||||
return null;
|
||||
}),
|
||||
timeout,
|
||||
]);
|
||||
return placeLabel(place);
|
||||
} finally {
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle);
|
||||
}
|
||||
}
|
||||
|
||||
/** The city (or failing that, the region) and country. */
|
||||
function placeLabel(place: Place | null): string {
|
||||
if (!place) return "";
|
||||
const local = place.locality || place.region;
|
||||
if (!local || local === place.country) return place.country;
|
||||
return place.country ? `${local}, ${place.country}` : local;
|
||||
}
|
||||
|
||||
/** Rough day/night by the phone's clock, for when NWS gives no hint. */
|
||||
function isLocalDaytime(): boolean {
|
||||
const hour = new Date().getHours();
|
||||
@@ -573,6 +838,20 @@ function finiteNumber(value: unknown): number | null {
|
||||
return Number.isFinite(number) ? number : null;
|
||||
}
|
||||
|
||||
function numberArray(value: unknown): Array<number | null> {
|
||||
return Array.isArray(value) ? value.map((item) => finiteNumber(item)) : [];
|
||||
}
|
||||
|
||||
function maxValue(values: Array<number | null>): number | null {
|
||||
const numbers = values.filter((value): value is number => value !== null);
|
||||
return numbers.length ? Math.max(...numbers) : null;
|
||||
}
|
||||
|
||||
function minValue(values: Array<number | null>): number | null {
|
||||
const numbers = values.filter((value): value is number => value !== null);
|
||||
return numbers.length ? Math.min(...numbers) : null;
|
||||
}
|
||||
|
||||
function timestampValue(value: unknown): number | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const timestamp = Date.parse(value);
|
||||
@@ -586,7 +865,7 @@ function stringValue(value: unknown): string {
|
||||
function friendlyWeatherError(error: unknown): string {
|
||||
const message = (error as Error)?.message || String(error);
|
||||
if (/network request failed|failed to fetch|unable to resolve host/i.test(message)) {
|
||||
return "Couldn't reach the National Weather Service. Check the phone's connection and retry.";
|
||||
return "Couldn't reach the weather service. Check the phone's connection and retry.";
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
@@ -97,6 +97,7 @@ test('Weather uses the portable location provider and preserves NWS parsing', as
|
||||
'./location-permissions': { hasLocationPermission: () => permission },
|
||||
'./settings-store': { getStringSetting: (_key, fallback) => fallback, setStringSetting() {} },
|
||||
'./location': { getCurrentLocation: async () => fix },
|
||||
'./reverse-geocode': { reverseGeocode: async () => null },
|
||||
'../version': { USER_AGENT: 'test' },
|
||||
'../util/http': { fetchWithUserAgent: async url => { requests.push(url); return { ok: true, json: async () =>
|
||||
url.includes('/points/') ? { properties: { forecast: 'https://fixture/forecast', relativeLocation: { properties: { city: 'San Francisco', state: 'CA' } } } }
|
||||
|
||||
+120
-3
@@ -5,22 +5,33 @@ 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 }) {
|
||||
/**
|
||||
* weather.ts with fake timers, settings store and NWS responses. Without
|
||||
* NWS periods, the NWS point lookup 404s and openMeteo answers instead.
|
||||
* nowMs, if given, fixes the module's clock.
|
||||
*/
|
||||
function weatherHarness({
|
||||
periods, observation = null, openMeteo = null, place = null, store = new Map(), permission = () => true, nowMs,
|
||||
}) {
|
||||
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),
|
||||
...(nowMs === undefined ? {} : { Date: class extends Date { static now() { return nowMs; } } }),
|
||||
}, {
|
||||
'./location-permissions': { hasLocationPermission: permission },
|
||||
'./location': { getCurrentLocation: async () => fix },
|
||||
'./reverse-geocode': { reverseGeocode: async () => place },
|
||||
'./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/')) {
|
||||
if (url.startsWith('https://api.open-meteo.com/')) {
|
||||
body = openMeteo;
|
||||
} else if (url.includes('/points/')) {
|
||||
if (!periods) return { ok: false, status: 404 };
|
||||
body = { properties: {
|
||||
forecast: 'https://fixture/forecast',
|
||||
observationStations: observation ? 'https://fixture/stations' : undefined,
|
||||
@@ -46,6 +57,27 @@ function weatherHarness({ periods, observation = null, store = new Map(), permis
|
||||
|
||||
const sunny = { name: 'Today', temperature: 70, temperatureUnit: 'F', shortForecast: 'Sunny', isDaytime: true };
|
||||
|
||||
/**
|
||||
* An Open-Meteo answer (Fahrenheit, mph, unix seconds) whose hourly
|
||||
* forecast starts at local midnight today, with hourly values from
|
||||
* hour(index) (all fields optional).
|
||||
*/
|
||||
function openMeteoResponse({ offsetHours = 0, nowMs = Date.now(), hours = 192, hour = () => ({}), current = {} } = {}) {
|
||||
const offsetMs = offsetHours * HOUR_MS;
|
||||
const midnightMs = Math.floor((nowMs + offsetMs) / (24 * HOUR_MS)) * 24 * HOUR_MS - offsetMs;
|
||||
const hourly = { time: [], temperature_2m: [], precipitation_probability: [], weather_code: [], wind_speed_10m: [], wind_direction_10m: [] };
|
||||
for (let index = 0; index < hours; index++) {
|
||||
const values = { temperature_2m: 60, precipitation_probability: 0, weather_code: 0, wind_speed_10m: 5, wind_direction_10m: 180, ...hour(index) };
|
||||
hourly.time.push((midnightMs + index * HOUR_MS) / 1000);
|
||||
for (const key of Object.keys(values)) hourly[key].push(values[key]);
|
||||
}
|
||||
return {
|
||||
utc_offset_seconds: offsetHours * 3600,
|
||||
current: { time: Math.floor(nowMs / 1000), temperature_2m: 64.2, relative_humidity_2m: 94, is_day: 1, weather_code: 2, wind_speed_10m: 2.7, wind_direction_10m: 292, ...current },
|
||||
hourly,
|
||||
};
|
||||
}
|
||||
|
||||
test('Weather takes the condition from the NWS icon, falling back to the text', async () => {
|
||||
const h = weatherHarness({
|
||||
periods: [
|
||||
@@ -128,6 +160,91 @@ test('Weather refreshes a stale cache at once and backs off after a failure', as
|
||||
assert.ok(retry > 9 * 60_000 && retry <= 10 * 60_000, `retry delay ${retry}`);
|
||||
});
|
||||
|
||||
test('Weather outside NWS coverage falls back to Open-Meteo and names the place with the geocoder', async () => {
|
||||
const h = weatherHarness({
|
||||
openMeteo: openMeteoResponse({ offsetHours: 10 }),
|
||||
place: { locality: 'Sydney', region: 'New South Wales', country: 'Australia' },
|
||||
});
|
||||
const bridge = new h.api.WeatherBridge();
|
||||
await bridge.refreshNow();
|
||||
const state = bridge.snapshot();
|
||||
assert.equal(state.phase, 'ready', state.status);
|
||||
assert.equal(state.source, 'open-meteo');
|
||||
assert.equal(state.locationName, 'Sydney, Australia');
|
||||
assert.equal(h.requests.length, 2, 'one NWS point lookup, then one Open-Meteo request');
|
||||
assert.match(h.requests[1], /latitude=37\.7000&longitude=-122\.4000/);
|
||||
assert.match(h.requests[1], /temperature_unit=fahrenheit/);
|
||||
assert.deepEqual({ ...state.current, timestampMs: null }, {
|
||||
temperatureF: 64.2, description: 'Partly Cloudy', humidityPercent: 94, windSpeedMph: 2.7, windDirection: 'W',
|
||||
timestampMs: null, observed: false, condition: 'partly-cloudy', isDaytime: true,
|
||||
});
|
||||
assert.equal(state.forecast.length, 14);
|
||||
|
||||
// The source survives a restart; a geocoder with nothing to say leaves the coordinates.
|
||||
const restarted = new (weatherHarness({ openMeteo: openMeteoResponse(), store: h.store }).api.WeatherBridge)();
|
||||
assert.equal(restarted.snapshot().source, 'open-meteo');
|
||||
const unnamed = weatherHarness({ openMeteo: openMeteoResponse() });
|
||||
const unnamedBridge = new unnamed.api.WeatherBridge();
|
||||
await unnamedBridge.refreshNow();
|
||||
assert.equal(unnamedBridge.snapshot().locationName, '37.7000, -122.4000');
|
||||
});
|
||||
|
||||
test('Open-Meteo hours group into NWS-style day and night periods in local time', async () => {
|
||||
// 3pm local, so the first period is the rest of today.
|
||||
const offsetHours = -5;
|
||||
const dayMs = 24 * HOUR_MS;
|
||||
const nowMs = Math.floor(Date.now() / dayMs) * dayMs + (15 - offsetHours) * HOUR_MS;
|
||||
const h = weatherHarness({
|
||||
nowMs,
|
||||
openMeteo: openMeteoResponse({
|
||||
offsetHours, nowMs,
|
||||
hour: index => ({
|
||||
// Peaks at 80 at 1pm and bottoms out at 20 at 1am; rain tomorrow
|
||||
// 3pm-5pm, then one stray hour of thunder; a windy 3am tonight.
|
||||
temperature_2m: 50 + 30 * Math.sin(((index % 24) - 7) / 24 * 2 * Math.PI),
|
||||
precipitation_probability: index === 24 + 15 ? 80 : 10,
|
||||
weather_code: { [24 + 15]: 63, [24 + 16]: 63, [24 + 20]: 95 }[index] ?? 1,
|
||||
wind_speed_10m: index === 24 + 3 ? 30 : 5,
|
||||
wind_direction_10m: index === 24 + 3 ? 90 : 180,
|
||||
}),
|
||||
}),
|
||||
place: { locality: '', region: 'Ontario', country: 'Canada' },
|
||||
});
|
||||
const bridge = new h.api.WeatherBridge();
|
||||
await bridge.refreshNow();
|
||||
const { forecast, locationName } = bridge.snapshot();
|
||||
assert.equal(locationName, 'Ontario, Canada');
|
||||
const weekday = days => ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][
|
||||
new Date(nowMs + offsetHours * HOUR_MS + days * dayMs).getUTCDay()];
|
||||
assert.deepEqual(Array.from(forecast.slice(0, 4), period => period.name), ['Today', 'Tonight', weekday(1), `${weekday(1)} Night`]);
|
||||
assert.deepEqual(Array.from(forecast, period => period.isDaytime), Array.from({ length: 14 }, (_, index) => index % 2 === 0));
|
||||
|
||||
// Today is only 3pm-6pm, past its 1pm peak.
|
||||
assert.equal(forecast[0].startTimeMs, nowMs);
|
||||
assert.equal(Math.round(forecast[0].temperatureF), 76);
|
||||
// Tonight runs to 6am and takes its low and its strongest wind.
|
||||
assert.equal(Math.round(forecast[1].temperatureF), 20);
|
||||
assert.equal(forecast[1].windSpeed, '30 mph');
|
||||
assert.equal(forecast[1].windDirection, 'E');
|
||||
// Tomorrow takes its most severe lasting code and its highest chance of rain.
|
||||
assert.equal(Math.round(forecast[2].temperatureF), 80);
|
||||
assert.equal(forecast[2].shortForecast, 'Rain');
|
||||
assert.equal(forecast[2].condition, 'rain');
|
||||
assert.equal(forecast[2].precipitationPercent, 80);
|
||||
// One hour of thunder doesn't name tomorrow night.
|
||||
assert.equal(forecast[3].shortForecast, 'Mostly Clear');
|
||||
assert.equal(forecast[3].condition, 'partly-cloudy');
|
||||
});
|
||||
|
||||
test('Open-Meteo after midnight starts with the rest of last night', async () => {
|
||||
const dayMs = 24 * HOUR_MS;
|
||||
const nowMs = Math.floor(Date.now() / dayMs) * dayMs + 2 * HOUR_MS;
|
||||
const h = weatherHarness({ nowMs, openMeteo: openMeteoResponse({ nowMs }) });
|
||||
const bridge = new h.api.WeatherBridge();
|
||||
await bridge.refreshNow();
|
||||
assert.deepEqual(Array.from(bridge.snapshot().forecast.slice(0, 3), period => period.name), ['Overnight', 'Today', 'Tonight']);
|
||||
});
|
||||
|
||||
/** weather-indicators.ts with a fake shell, settings and bridge. */
|
||||
function indicatorHarness() {
|
||||
const settings = new Map(), settingListeners = new Set(), stateListeners = new Set(), trays = [];
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
<ul class="links">
|
||||
<li>Mapbox: <a href="https://www.mapbox.com/legal/privacy">https://www.mapbox.com/legal/privacy</a></li>
|
||||
</ul>
|
||||
<p>The Weather app will retrieve the user's coarse location, and will use it to query a third-party weather information provider.</p>
|
||||
<p>The Weather app will retrieve the user's coarse location, and will use it to query a third-party weather information provider: the US National Weather Service, then <a href="https://open-meteo.com/en/terms">Open-Meteo</a> if the location is outside the US. Outside the US, it also asks the phone's built-in geocoder (Google's on most Android phones, Apple's on iOS) for the name of the place.</p>
|
||||
<h2>EvenHub</h2>
|
||||
<p>The EvenHub app store is subject to Even Realities' privacy policy: <a href="https://support.evenrealities.com/hc/en-us/articles/14127464826511-Privacy-Policy">https://support.evenrealities.com/hc/en-us/articles/14127464826511-Privacy-Policy</a>. Apps downloaded from the EvenHub app store come with their own privacy policies.</p>
|
||||
<h2>Wear OS Watch</h2>
|
||||
|
||||
Reference in new issue
Block a user