krz/moonrise

Night-sky companion for iPhone, Apple Watch and Vision Pro: what's up tonight, the Moon, planets, launches and missions, and a Library of the solar system. SwiftUI app with a Cloudflare Workers backend. astronomy cloudflare-workers ios night-sky space swiftui visionos watchos

Commit a40dab3f37

a40dab3f374d619917bee0845c3ca7738c40d5cc

parent: 496e19d445

Unsigned

cmc <hello@cleberg.net> · 2026-10-22 03:43 UTC

Sun: solar wind from RTSW and earlier aurora alerts from Bz (!116)

- `server/src/solarwind.ts`: `rtsw_mag_1m.json` and `rtsw_wind_1m.json` fetched one after the other on the 5-minute cron (User-Agent), active spacecraft only, reduced to 5-minute means over 6 h; stored as `rtsw` (last good kept, `rtsw:error` on failure). Live: 72 points, 5.7 KB, SOLAR1.
- `stormLikely`: last 30 min mean Bz ≤ −10 nT and speed ≥ 450 km/s. A rule of thumb for "aurora often follows within the hour"; I found no source I could check for a Kp-from-solar-wind regression, so none is used. When it holds and the forecast Kp is below 6, alerts go to the Kp 6 bands with "The solar wind has turned strongly south…". Same dedupe as Kp alerts.
- `/v1/today` gains `solarWind`. App: `SolarWind` (Feeds) and a Sun tab section with speed, density, Bz, Bt and a 6-hour Bz chart.
- Tests: reduction, the rule, and an end-to-end alert at Kp 2 with southward wind (65/65 server); decoding (Feeds). iOS builds.

Layout: unified · split

App/Sources/SunScreen.swift +27
@@ -12,6 +12,7 @@ struct SunScreen: View {
1212 @State private var imageID = Date.now
1313 @State private var picture: Picture?
1414 @State private var imageFailed = false
15 @State private var solarWind: SolarWind?
1516 @Environment(\.dynamicTypeSize) private var typeSize
1617
1718 private var kp: [KpBar] { data?.kp ?? [] }
@@ -51,6 +52,9 @@ struct SunScreen: View {
5152 Text(SolarImage.credit).font(.caption2).dimmed(0.5).padding(.top, 4)
5253
5354 section("Aurora tonight", note: "NOAA's forecast of where the aurora may be overhead in the next hour; brighter green is more likely. From a few hundred kilometres further from the pole it can still be seen low on the horizon.") { auroraMap }
55 if let solarWind {
56 section("Solar wind", note: "Measured 1.5 million km sunward of Earth, 30 to 60 minutes before it arrives. When Bz, the north–south part of its magnetic field, turns strongly negative (south), aurora often follows.") { solarWindPanel(solarWind) }
57 }
5458 section("Solar flares, last 24 h", note: "X-rays from the Sun, measured by NOAA's GOES satellites. Spikes are flares: M and X class can disrupt radio and GPS, and the biggest can bring a storm a day or two later.") {
5559 flares
5660 if let p = data?.probabilities { probabilityTable(p) }
@@ -73,6 +77,7 @@ struct SunScreen: View {
7377
7478 private func load(force: Bool) async {
7579 if data == nil { await show(SunFeeds.lastSaved()) }
80 if let apiBase { solarWind = (try? await SolarWind.fetch(base: apiBase)) ?? solarWind }
7681 if force { imageID = .now }
7782 let result = await SunFeeds.load(force: force)
7883 await show(result?.snapshot)
@@ -345,6 +350,28 @@ struct SunScreen: View {
345350 }
346351 }
347352
353 private func solarWindPanel(_ w: SolarWind) -> some View {
354 let n = { (v: Double?, f: Int) in v.map { $0.formatted(.number.precision(.fractionLength(f))) } ?? "–" }
355 return VStack(alignment: .leading, spacing: 10) {
356 HStack(spacing: 20) {
357 stat("Speed, km/s", n(w.speed, 0))
358 stat("Density, /cm³", n(w.density, 1))
359 stat("Bz, nT", n(w.bz, 1))
360 stat("Field, nT", n(w.bt, 1))
361 }
362 Chart(w.series.filter { $0.bz != nil }) { p in
363 LineMark(x: .value("Time", p.t), y: .value("Bz", p.bz ?? 0)).foregroundStyle(ink)
364 RuleMark(y: .value("Zero", 0)).foregroundStyle(ink.opacity(0.3))
365 RuleMark(y: .value("Strong south", -10)).foregroundStyle(accent.opacity(0.6)).lineStyle(StrokeStyle(lineWidth: 0.5, dash: [3, 3]))
366 }
367 .chartYAxis { AxisMarks { _ in AxisGridLine().foregroundStyle(ink.opacity(0.15)); AxisValueLabel().foregroundStyle(ink.opacity(0.6)) } }
368 .chartXAxis { AxisMarks(values: .stride(by: .hour, count: 2)) { _ in AxisValueLabel(format: .dateTime.hour()).foregroundStyle(ink.opacity(0.6)) } }
369 .frame(height: 110)
370 Text("Bz over 6 hours, 5-minute means. Dashed: −10 nT. From \(w.source), \(w.observedAt.formatted(date: .omitted, time: .shortened)).")
371 .font(.caption2).dimmed(0.6)
372 }
373 }
374
348375 private func stat(_ label: String, _ value: String) -> some View {
349376 VStack(alignment: .leading, spacing: 2) {
350377 Text(label).font(.caption2).dimmed(0.6)
PLAN.org +3 −1
@@ -515,7 +515,9 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled.
515515** v5.1: Sun
516516- Solar wind from SWPC RTSW (=json/rtsw/rtsw_mag_1m.json=,
517517 =rtsw_wind_1m.json=), reduced on the Worker; earlier aurora alerts from
518 Bz.
518 Bz. Done: 5-minute means over 6 h in =/v1/today=; Sun tab panel and Bz
519 chart; alerts to the Kp 6 bands when the last 30 min average Bz ≤ −10 nT
520 and speed ≥ 450 km/s (a rule of thumb, not a Kp model).
519521- Active-region labels on the SDO image.
520522- Sun path, golden and blue hour, day length.
521523- CCOR-2 coronagraph loop, WSA-Enlil forecast line, solar cycle progress.
Packages/MoonriseKit/Sources/Feeds/SolarWind.swift added +41
@@ -0,0 +1,41 @@
1import Foundation
2
3/// Solar wind at L1 from the backend's /v1/today: 5-minute means over 6 hours from SWPC's real-time solar wind
4/// (SOLAR-1, ACE or IMAP).
5public struct SolarWind: Sendable, Equatable, Decodable {
6 public struct Point: Sendable, Equatable, Decodable, Identifiable {
7 public var t: Date
8 public var speed: Double?
9 public var density: Double?
10 public var bz: Double?
11 public var bt: Double?
12 public var id: Date { t }
13 }
14
15 public var observedAt: Date
16 public var source: String
17 public var series: [Point]
18
19 /// The latest bin with each value.
20 public var speed: Double? { series.last { $0.speed != nil }?.speed }
21 public var density: Double? { series.last { $0.density != nil }?.density }
22 public var bz: Double? { series.last { $0.bz != nil }?.bz }
23 public var bt: Double? { series.last { $0.bt != nil }?.bt }
24
25 static func decodeToday(_ data: Data) throws -> SolarWind? {
26 struct Today: Decodable { var solarWind: SolarWind? }
27 let d = JSONDecoder()
28 d.dateDecodingStrategy = .custom { decoder in
29 let s = try decoder.singleValueContainer().decode(String.self)
30 guard let date = try? Date(s, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) else {
31 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "bad date \(s)"))
32 }
33 return date
34 }
35 return try d.decode(Today.self, from: data).solarWind
36 }
37
38 public static func fetch(base: URL, session: URLSession = .shared) async throws -> SolarWind? {
39 try decodeToday(await session.data(from: base.appending(path: "v1/today")).0)
40 }
41}
Packages/MoonriseKit/Tests/FeedsTests/SpaceWeatherTests.swift +10
@@ -34,3 +34,13 @@ let forecast = Data("""
3434 let w = try SpaceWeather.decodeToday(data)
3535 #expect(w == SpaceWeather(kpNow: 2.33, observedAt: try Date("2026-10-22T00:05:00Z", strategy: .iso8601), kpNext24h: 4.67))
3636}
37
38@Test func decodesBackendSolarWind() throws {
39 let data = Data(#"{"spaceWeather":{"kpNow":2,"observedAt":"2026-10-22T00:05:00.000Z","kpNext24h":null,"fetchedAt":"x"},"solarWind":{"observedAt":"2026-10-22T03:36:00.000Z","source":"SOLAR1","series":[{"t":"2026-10-22T03:30:00.000Z","speed":477.8,"density":5.8,"bz":4.6,"bt":7.8},{"t":"2026-10-22T03:35:00.000Z","speed":467.5,"density":null,"bz":-3.5,"bt":7.7}]}}"#.utf8)
40 let w = try #require(try SolarWind.decodeToday(data))
41 #expect(w.source == "SOLAR1")
42 #expect(w.series.count == 2)
43 #expect(w.bz == -3.5)
44 #expect(w.density == 5.8)
45 #expect(try SolarWind.decodeToday(Data(#"{"spaceWeather":null}"#.utf8)) == nil)
46}
server/src/index.ts +26 −4
@@ -5,6 +5,7 @@ import { compose, fetchGroups, fetchSupGP, fitsLaunch, retryDue, retryTick, supg
55import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live";
66import { fetchLaunch, fetchLaunches, PREVIOUS_URL, throttleSeconds, Throttled, UPCOMING_URL, type Launch } from "./ll2";
77import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines, type Article } from "./news";
8import { fetchSolarWind, STORM_KP, stormLikely, type SolarWind } from "./solarwind";
89import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc";
910
1011interface Env {
@@ -105,8 +106,10 @@ async function today(env: Env, now: Date): Promise<Response> {
105106 if (!row) return json({ spaceWeather: null }, 200, MAX_AGE.today);
106107 const w = JSON.parse(row.body) as SpaceWeather;
107108 w.forecast = w.forecast.map((f) => ({ ...f, start: new Date(f.start) }));
109 const wind = await env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'rtsw' AND ok = 1").first<{ body: string }>();
108110 return json({
109111 spaceWeather: { kpNow: w.kpNow, observedAt: w.observedAt, kpNext24h: next24h(w, now), fetchedAt: row.fetched_at },
112 solarWind: wind ? JSON.parse(wind.body) : null,
110113 }, 200, MAX_AGE.today);
111114}
112115
@@ -469,11 +472,28 @@ async function pollSpaceWeather(env: Env, now: Date): Promise<void> {
469472 await env.DB.prepare(
470473 "INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES ('swpc', ?1, 1, ?2) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1, ok = 1, body = ?2",
471474 ).bind(now.toISOString(), JSON.stringify(w)).run();
472 await sendAuroraAlerts(env, w, now);
475 await sendAuroraAlerts(env, w, await pollSolarWind(env, now), now);
473476}
474477
475async function sendAuroraAlerts(env: Env, w: SpaceWeather, now: Date): Promise<void> {
476 const kp = actionableKp(w.kpNow, w.forecast, now);
478/** RTSW, reduced; the last good copy is kept on failure, and null is returned so no alert rests on old wind. */
479async function pollSolarWind(env: Env, now: Date): Promise<SolarWind | null> {
480 try {
481 const wind = await fetchSolarWind(now);
482 if (!wind) return null;
483 await env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES ('rtsw', ?1, 1, ?2) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1, ok = 1, body = ?2")
484 .bind(now.toISOString(), JSON.stringify(wind)).run();
485 return wind;
486 } catch (e) {
487 console.error("rtsw", String(e));
488 await env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok) VALUES ('rtsw:error', ?1, 0) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1").bind(now.toISOString()).run();
489 return null;
490 }
491}
492
493async function sendAuroraAlerts(env: Env, w: SpaceWeather, wind: SolarWind | null, now: Date): Promise<void> {
494 const forecastKp = actionableKp(w.kpNow, w.forecast, now);
495 const early = stormLikely(wind, now) && forecastKp < STORM_KP;
496 const kp = early ? STORM_KP : forecastKp;
477497 const bandRows = await env.DB.prepare("SELECT DISTINCT band FROM devices WHERE aurora = 1").all<{ band: number }>();
478498 const bands = alertBands(kp, bandRows.results.map((r) => r.band));
479499 if (!bands.length || !env.APNS_KEY) return;
@@ -485,7 +505,9 @@ async function sendAuroraAlerts(env: Env, w: SpaceWeather, now: Date): Promise<v
485505 ).bind(JSON.stringify(bands), event).all<{ token: string; environment: string; band: number; utc_offset_minutes: number }>();
486506 const due = devices.results.filter((d) => isNight(now, d.utc_offset_minutes)).map((d) => ({ ...d, event: `${d.token}:${event}` }));
487507 await sendAlerts(env, "aurora", due, now, (d) => ({
488 aps: { alert: { title: "Aurora possible tonight", body: `Kp ${kp.toFixed(1)}. Look toward the ${d.band >= 0 ? "north" : "south"} after dark.` }, sound: "default" },
508 aps: { alert: { title: "Aurora possible tonight", body: early
509 ? `The solar wind has turned strongly south; aurora often follows within the hour. Look toward the ${d.band >= 0 ? "north" : "south"} after dark.`
510 : `Kp ${kp.toFixed(1)}. Look toward the ${d.band >= 0 ? "north" : "south"} after dark.` }, sound: "default" },
489511 }));
490512}
491513
server/src/solarwind.ts added +89
@@ -0,0 +1,89 @@
1// Real-time solar wind at L1 (SWPC RTSW: SOLAR-1, ACE or IMAP, whichever is active). The 1-minute files are
2// about 1.5 and 2.5 MB; they are reduced here to 5-minute means over 6 hours for the app and the aurora rule.
3import { USER_AGENT } from "./agent.ts";
4
5export const MAG_URL = "https://services.swpc.noaa.gov/json/rtsw/rtsw_mag_1m.json";
6export const WIND_URL = "https://services.swpc.noaa.gov/json/rtsw/rtsw_wind_1m.json";
7
8export interface SolarWindPoint {
9 /** Start of the 5-minute bin, ISO 8601. */
10 t: string;
11 speed: number | null;
12 density: number | null;
13 bz: number | null;
14 bt: number | null;
15}
16
17export interface SolarWind {
18 observedAt: string;
19 source: string;
20 series: SolarWindPoint[];
21}
22
23interface MagRow { time_tag: string; active: boolean; source: string; bz_gsm: number | null; bt: number | null }
24interface WindRow { time_tag: string; active: boolean; source: string; proton_speed: number | null; proton_density: number | null }
25
26const BIN = 5 * 60_000;
27const HOURS = 6;
28
29const mean = (xs: number[]) => (xs.length ? Math.round((xs.reduce((a, b) => a + b, 0) / xs.length) * 10) / 10 : null);
30const ok = (v: number | null | undefined): v is number => typeof v === "number" && Number.isFinite(v);
31
32export function reduce(mag: MagRow[], wind: WindRow[], now: Date): SolarWind | null {
33 const start = Math.floor((now.getTime() - HOURS * 3600_000) / BIN) * BIN;
34 const bins = new Map<number, { speed: number[]; density: number[]; bz: number[]; bt: number[] }>();
35 const bin = (tag: string) => {
36 const t = Date.parse(tag + "Z");
37 if (!(t >= start)) return undefined;
38 const k = Math.floor(t / BIN) * BIN;
39 if (!bins.has(k)) bins.set(k, { speed: [], density: [], bz: [], bt: [] });
40 return bins.get(k)!;
41 };
42 let observed = 0, source = "";
43 for (const r of mag) {
44 if (!r.active) continue;
45 const b = bin(r.time_tag);
46 if (!b) continue;
47 if (ok(r.bz_gsm)) b.bz.push(r.bz_gsm);
48 if (ok(r.bt)) b.bt.push(r.bt);
49 const t = Date.parse(r.time_tag + "Z");
50 if (t > observed) { observed = t; source = r.source; }
51 }
52 for (const r of wind) {
53 if (!r.active) continue;
54 const b = bin(r.time_tag);
55 if (!b) continue;
56 if (ok(r.proton_speed)) b.speed.push(r.proton_speed);
57 if (ok(r.proton_density)) b.density.push(r.proton_density);
58 }
59 if (!bins.size) return null;
60 const series = [...bins.entries()].sort((a, b) => a[0] - b[0]).map(([k, b]) => ({
61 t: new Date(k).toISOString(), speed: mean(b.speed), density: mean(b.density), bz: mean(b.bz), bt: mean(b.bt),
62 }));
63 return { observedAt: new Date(observed).toISOString(), source, series };
64}
65
66/**
67 * Southward field strong enough, for long enough, that aurora usually follows within the hour (the wind takes
68 * about 30 to 60 minutes from L1): the last 30 minutes average Bz ≤ −10 nT and speed ≥ 450 km/s.
69 * A rule of thumb, not a forecast; it raises alerts to the bands that see aurora at Kp 6.
70 */
71export function stormLikely(w: SolarWind | null, now: Date): boolean {
72 if (!w) return false;
73 const recent = w.series.filter((p) => Date.parse(p.t) >= now.getTime() - 30 * 60_000);
74 const bz = recent.map((p) => p.bz).filter(ok), speed = recent.map((p) => p.speed).filter(ok);
75 if (bz.length < 4 || speed.length < 4) return false;
76 return mean(bz)! <= -10 && mean(speed)! >= 450;
77}
78
79export const STORM_KP = 6;
80
81export async function fetchSolarWind(now: Date): Promise<SolarWind | null> {
82 const headers = { "user-agent": USER_AGENT };
83 const m = await fetch(MAG_URL, { headers });
84 if (!m.ok) throw new Error(`RTSW mag ${m.status}`);
85 const mag = (await m.json()) as MagRow[];
86 const w = await fetch(WIND_URL, { headers });
87 if (!w.ok) throw new Error(`RTSW wind ${w.status}`);
88 return reduce(mag, (await w.json()) as WindRow[], now);
89}
server/test/solarwind.test.ts added +26
@@ -0,0 +1,26 @@
1import assert from "node:assert/strict";
2import { test } from "node:test";
3import { reduce, stormLikely } from "../src/solarwind.ts";
4
5const now = new Date("2026-10-22T06:00:00Z");
6const minutes = (n: number, f: (i: number) => object) =>
7 Array.from({ length: n }, (_, i) => ({ time_tag: new Date(now.getTime() - (n - i) * 60_000).toISOString().slice(0, 19), active: true, source: "SOLAR1", ...f(i) }));
8
9test("reduces 1-minute rows to 5-minute means from the active spacecraft", () => {
10 const mag = [...minutes(60, () => ({ bz_gsm: -4, bt: 6 })), { time_tag: "2026-10-22T05:58:00", active: false, source: "ACE", bz_gsm: 50, bt: 50 }];
11 const wind = minutes(60, (i) => ({ proton_speed: 400 + i, proton_density: 5 }));
12 const w = reduce(mag, wind, now)!;
13 assert.equal(w.source, "SOLAR1");
14 assert.equal(w.series.length, 12);
15 assert.ok(w.series.every((p) => p.bz === -4 && p.bt === 6 && p.density === 5));
16 assert.equal(w.series[0].speed, 402);
17});
18
19test("storm likely only after 30 minutes of strong southward field and fast wind", () => {
20 const wind = minutes(60, () => ({ proton_speed: 520, proton_density: 8 }));
21 assert.equal(stormLikely(reduce(minutes(60, () => ({ bz_gsm: -12, bt: 14 })), wind, now), now), true);
22 assert.equal(stormLikely(reduce(minutes(60, () => ({ bz_gsm: -6, bt: 14 })), wind, now), now), false);
23 assert.equal(stormLikely(reduce(minutes(60, (i) => ({ bz_gsm: i < 45 ? 5 : -15, bt: 15 })), wind, now), now), false);
24 assert.equal(stormLikely(reduce(minutes(60, () => ({ bz_gsm: -12, bt: 14 })), minutes(60, () => ({ proton_speed: 380, proton_density: 8 })), now), now), false);
25 assert.equal(stormLikely(null, now), false);
26});
server/test/worker.test.ts +25
@@ -244,6 +244,31 @@ test("aurora alerts go out in bounded slices and are recorded per device once an
244244 assert.deepEqual(push.state.sent, [token(3)]);
245245});
246246
247test("a strongly southward solar wind alerts the Kp 6 bands before Kp rises", async () => {
248 const { db, env } = await setup();
249 device(db, 0, { band: 45 });
250 const push = apns();
251 let bz = -3;
252 const rows = (f: (m: number) => object) => Array.from({ length: 60 }, (_, m) =>
253 ({ time_tag: new Date(Date.parse("2026-10-20T22:05:00Z") - (60 - m) * 60_000).toISOString().slice(0, 19), active: true, source: "SOLAR1", ...f(m) }));
254 const payloads: string[] = [];
255 network({
256 ...push.handlers,
257 "api.push.apple.com": (url, init) => { payloads.push(String(init.body)); return push.handlers["api.push.apple.com"](url, init); },
258 "services.swpc.noaa.gov": (url) => {
259 if (url.pathname.endsWith("rtsw_mag_1m.json")) return Response.json(rows(() => ({ bz_gsm: bz, bt: 14 })));
260 if (url.pathname.endsWith("rtsw_wind_1m.json")) return Response.json(rows(() => ({ proton_speed: 540, proton_density: 9 })));
261 return Response.json(url.pathname.includes("planetary_k_index_1m") ? [{ time_tag: "2026-10-20T22:00:00", estimated_kp: 2 }] : []);
262 },
263 });
264 await run(env, FIVE, "2026-10-20T22:05:00Z");
265 assert.equal(push.state.sent.length, 0, "quiet wind, Kp 2");
266 bz = -13;
267 await run(env, FIVE, "2026-10-20T22:05:00Z");
268 assert.deepEqual(push.state.sent, [token(0)]);
269 assert.match(payloads.at(-1)!, /turned strongly south/);
270});
271
247272test("an aurora run cut short leaves the remaining devices for the next run", async () => {
248273 const { db, env } = await setup();
249274 for (let i = 0; i < 5; i++) device(db, i);