@azohra/meteo.station 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/climatology.d.ts +27 -0
- package/dist/client/climatology.js +83 -0
- package/dist/client/history.d.ts +47 -0
- package/dist/client/history.js +112 -0
- package/dist/client/index.d.ts +3 -1
- package/dist/client/index.js +3 -1
- package/dist/client/live.js +15 -0
- package/dist/climatology.d.ts +66 -0
- package/dist/climatology.js +230 -0
- package/dist/contract-climatology.d.ts +73 -0
- package/dist/contract-climatology.js +52 -0
- package/dist/contract.d.ts +234 -1
- package/dist/contract.js +52 -4
- package/dist/derive.d.ts +23 -1
- package/dist/derive.js +43 -4
- package/dist/display.d.ts +4 -0
- package/dist/display.js +2 -1
- package/dist/elements/elements/AirExtremesElement.d.ts +8 -0
- package/dist/elements/elements/AirExtremesElement.js +33 -0
- package/dist/elements/elements/ClimatologyDailyPatternElement.d.ts +15 -0
- package/dist/elements/elements/ClimatologyDailyPatternElement.js +84 -0
- package/dist/elements/elements/ClimatologyRoseElement.d.ts +14 -0
- package/dist/elements/elements/ClimatologyRoseElement.js +51 -0
- package/dist/elements/elements/CompassFanElement.d.ts +14 -0
- package/dist/elements/elements/CompassFanElement.js +92 -0
- package/dist/elements/elements/DailyPatternElement.d.ts +1 -0
- package/dist/elements/elements/DailyPatternElement.js +24 -16
- package/dist/elements/elements/DialElement.js +14 -3
- package/dist/elements/elements/FavorableShareElement.d.ts +14 -0
- package/dist/elements/elements/FavorableShareElement.js +47 -0
- package/dist/elements/elements/RecentSummariesElement.d.ts +14 -0
- package/dist/elements/elements/RecentSummariesElement.js +54 -0
- package/dist/elements/elements/StationFeedElement.d.ts +3 -0
- package/dist/elements/elements/StationFeedElement.js +13 -2
- package/dist/elements/elements/WindHistoryChartElement.js +20 -7
- package/dist/elements/elements/WindRoseElement.d.ts +1 -3
- package/dist/elements/elements/WindRoseElement.js +60 -62
- package/dist/elements/elements/atoms.js +3 -3
- package/dist/elements/index.d.ts +13 -1
- package/dist/elements/index.js +15 -3
- package/dist/elements/lib/ambient.d.ts +2 -0
- package/dist/elements/lib/attributes.js +24 -1
- package/dist/elements/lib/base.d.ts +3 -0
- package/dist/elements/lib/base.js +14 -2
- package/dist/endpoints.d.ts +7 -1
- package/dist/endpoints.js +13 -1
- package/dist/geometry.d.ts +23 -4
- package/dist/geometry.js +44 -13
- package/dist/index.d.ts +8 -6
- package/dist/index.js +8 -6
- package/dist/instruments.d.ts +7 -5
- package/dist/instruments.js +20 -7
- package/dist/merge-current.js +2 -1
- package/dist/react/components/AirExtremes.d.ts +16 -0
- package/dist/react/components/AirExtremes.js +38 -0
- package/dist/react/components/ClimatologyDailyPattern.d.ts +20 -0
- package/dist/react/components/ClimatologyDailyPattern.js +59 -0
- package/dist/react/components/ClimatologyRose.d.ts +18 -0
- package/dist/react/components/ClimatologyRose.js +45 -0
- package/dist/react/components/CompassFan.d.ts +17 -0
- package/dist/react/components/CompassFan.js +93 -0
- package/dist/react/components/DailyPattern.d.ts +4 -1
- package/dist/react/components/DailyPattern.js +15 -8
- package/dist/react/components/Dial.d.ts +3 -1
- package/dist/react/components/Dial.js +13 -2
- package/dist/react/components/FavorableShare.d.ts +14 -0
- package/dist/react/components/FavorableShare.js +43 -0
- package/dist/react/components/RecentSummaries.d.ts +18 -0
- package/dist/react/components/RecentSummaries.js +64 -0
- package/dist/react/components/StationFeedProvider.d.ts +4 -1
- package/dist/react/components/StationFeedProvider.js +5 -3
- package/dist/react/components/WindHistoryChart.d.ts +6 -1
- package/dist/react/components/WindHistoryChart.js +20 -5
- package/dist/react/components/WindRose.d.ts +4 -2
- package/dist/react/components/WindRose.js +80 -71
- package/dist/react/components/WindSampleStrip.d.ts +3 -1
- package/dist/react/components/WindSampleStrip.js +8 -5
- package/dist/react/components/atoms.d.ts +4 -1
- package/dist/react/components/atoms.js +6 -3
- package/dist/react/hooks/useStationClimatology.d.ts +18 -0
- package/dist/react/hooks/useStationClimatology.js +25 -0
- package/dist/react/index.d.ts +10 -3
- package/dist/react/index.js +9 -2
- package/dist/scene/air-extremes.d.ts +2 -0
- package/dist/scene/air-extremes.js +42 -0
- package/dist/scene/atoms.d.ts +2 -1
- package/dist/scene/atoms.js +6 -4
- package/dist/scene/climatology-pattern.d.ts +6 -0
- package/dist/scene/climatology-pattern.js +35 -0
- package/dist/scene/climatology-rose.d.ts +5 -0
- package/dist/scene/climatology-rose.js +49 -0
- package/dist/scene/compass-fan.d.ts +3 -0
- package/dist/scene/compass-fan.js +115 -0
- package/dist/scene/daily-pattern.d.ts +1 -0
- package/dist/scene/daily-pattern.js +21 -7
- package/dist/scene/dial.d.ts +1 -0
- package/dist/scene/dial.js +16 -3
- package/dist/scene/favorable-share.d.ts +3 -0
- package/dist/scene/favorable-share.js +41 -0
- package/dist/scene/index.d.ts +9 -3
- package/dist/scene/recent-summaries.d.ts +4 -0
- package/dist/scene/recent-summaries.js +75 -0
- package/dist/scene/rose.d.ts +2 -1
- package/dist/scene/rose.js +18 -3
- package/dist/scene/sample-strip.d.ts +1 -0
- package/dist/scene/sample-strip.js +1 -1
- package/dist/scene/trend.js +2 -7
- package/dist/scene/wind-history.d.ts +1 -0
- package/dist/scene/wind-history.js +4 -3
- package/dist/scene/wind-plot.d.ts +1 -0
- package/dist/scene/wind-plot.js +44 -9
- package/dist/server/adapter.d.ts +2 -1
- package/dist/server/adapter.js +2 -1
- package/dist/server/adapters/windnerd-climatology.d.ts +30 -0
- package/dist/server/adapters/windnerd-climatology.js +82 -0
- package/dist/server/adapters/windnerd-live.d.ts +5 -8
- package/dist/server/adapters/windnerd-live.js +26 -21
- package/dist/server/adapters/windnerd.d.ts +31 -4
- package/dist/server/adapters/windnerd.js +196 -19
- package/dist/server/environment.d.ts +4 -10
- package/dist/server/environment.js +4 -10
- package/dist/server/feed.d.ts +44 -2
- package/dist/server/feed.js +63 -2
- package/dist/server/handler.d.ts +11 -1
- package/dist/server/handler.js +83 -2
- package/dist/server/index.d.ts +4 -3
- package/dist/server/index.js +4 -3
- package/dist/strings.d.ts +13 -1
- package/dist/strings.js +13 -1
- package/package.json +2 -2
- package/schema/example-climatology.json +86 -0
- package/schema/example-history.json +38 -0
- package/schema/stationclimatology.schema.json +221 -0
- package/schema/stationcurrent.schema.json +173 -0
- package/schema/stationfeed.schema.json +173 -0
- package/schema/stationhistory.schema.json +186 -0
- package/schema/stationlive.schema.json +202 -0
- package/styles.css +232 -19
package/dist/server/adapter.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { History, LiveSamples, Reading, Station, StationMeta, StationTelemetry } from "../contract.js";
|
|
1
|
+
import { History, LiveSamples, Reading, RecentSummary, Station, StationMeta, StationTelemetry } from "../contract.js";
|
|
2
2
|
import { ResolvedEnvironment, ServerEnvironment } from "./environment.js";
|
|
3
3
|
//#region src/server/adapter.d.ts
|
|
4
4
|
type StationAdapterMode = "full" | "current";
|
|
@@ -18,6 +18,7 @@ type StationAdapterResult = {
|
|
|
18
18
|
readonly history: History | null;
|
|
19
19
|
readonly telemetry?: StationTelemetry | null;
|
|
20
20
|
readonly samples?: LiveSamples | null;
|
|
21
|
+
readonly recentSummaries?: RecentSummary[] | null;
|
|
21
22
|
readonly meta?: Partial<StationMeta>;
|
|
22
23
|
};
|
|
23
24
|
type StationAdapterDefinition<C, O extends StationAdapterOptions = StationAdapterOptions> = {
|
package/dist/server/adapter.js
CHANGED
|
@@ -22,7 +22,8 @@ function defineStationAdapter(definition) {
|
|
|
22
22
|
reading: result.reading,
|
|
23
23
|
history: mode === "current" ? null : result.history,
|
|
24
24
|
telemetry: result.telemetry ?? null,
|
|
25
|
-
samples: result.samples ?? null
|
|
25
|
+
samples: result.samples ?? null,
|
|
26
|
+
recentSummaries: result.recentSummaries ?? null
|
|
26
27
|
};
|
|
27
28
|
} catch (error) {
|
|
28
29
|
logUpstreamFailure(environment, `${meta.name} live wind unavailable`, error, { station: meta.id });
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { StationClimatology } from "../../contract-climatology.js";
|
|
2
|
+
import { SpeedThresholds } from "../../derive.js";
|
|
3
|
+
import { ServerEnvironment } from "../environment.js";
|
|
4
|
+
import { WindnerdStationConfig } from "../config.js";
|
|
5
|
+
//#region src/server/adapters/windnerd-climatology.d.ts
|
|
6
|
+
declare const CLIMATOLOGY_RECORD_PERIOD_MINUTES = 180;
|
|
7
|
+
declare const CLIMATOLOGY_DEFAULT_YEARS = 8;
|
|
8
|
+
declare const CLIMATOLOGY_DEFAULT_SECTOR_COUNT = 16;
|
|
9
|
+
type WindnerdClimatologyOptions = {
|
|
10
|
+
/** The consumer's speed-band bounds — a judgment parameter with no
|
|
11
|
+
* default; it shapes every bandCounts stack and joins the cache key. */
|
|
12
|
+
thresholds: SpeedThresholds;
|
|
13
|
+
/** Calendar years to reach back, the current one included. */
|
|
14
|
+
years?: number;
|
|
15
|
+
sectorCount?: number;
|
|
16
|
+
/** Slot width in minutes: a multiple of the 180-minute record period that
|
|
17
|
+
* divides 1440 (180, 360, or 720). */
|
|
18
|
+
slotMinutes?: number;
|
|
19
|
+
environment?: ServerEnvironment;
|
|
20
|
+
recordsUrl?: string;
|
|
21
|
+
liveUrl?: string;
|
|
22
|
+
};
|
|
23
|
+
/** Builds the climatology cube from the vendor's yearly archive: one
|
|
24
|
+
* records request per calendar year (closed years cached ~30 days, the
|
|
25
|
+
* running year 6 hours), folded into (month, slot, sector) sums in the
|
|
26
|
+
* station's STANDARD time. Any refused year fails the whole document —
|
|
27
|
+
* a silently missing year would read as an outage. */
|
|
28
|
+
declare function loadWindnerdClimatology(config: WindnerdStationConfig, options: WindnerdClimatologyOptions): Promise<StationClimatology>;
|
|
29
|
+
//#endregion
|
|
30
|
+
export { CLIMATOLOGY_DEFAULT_SECTOR_COUNT, CLIMATOLOGY_DEFAULT_YEARS, CLIMATOLOGY_RECORD_PERIOD_MINUTES, WindnerdClimatologyOptions, loadWindnerdClimatology };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { thresholdsToMps } from "../../derive.js";
|
|
2
|
+
import "../../contract-climatology.js";
|
|
3
|
+
import { accumulatedCells, coveredSlotCountByYear, createClimatologyAccumulator, foldClimatologyPoints } from "../../climatology.js";
|
|
4
|
+
import { fetchUpstreamText, logUpstreamFailure, resolveEnvironment } from "../environment.js";
|
|
5
|
+
import { loadWindnerdLocation, parseWindnerdRecords, windnerdHistoryPoints } from "./windnerd.js";
|
|
6
|
+
//#region src/server/adapters/windnerd-climatology.ts
|
|
7
|
+
const CLIMATOLOGY_RECORD_PERIOD_MINUTES = 180;
|
|
8
|
+
const CLIMATOLOGY_DEFAULT_YEARS = 8;
|
|
9
|
+
const CLIMATOLOGY_DEFAULT_SECTOR_COUNT = 16;
|
|
10
|
+
const CLOSED_YEAR_CACHE_TTL_SECONDS = 2592e3;
|
|
11
|
+
const CURRENT_YEAR_CACHE_TTL_SECONDS = 21600;
|
|
12
|
+
/** Builds the climatology cube from the vendor's yearly archive: one
|
|
13
|
+
* records request per calendar year (closed years cached ~30 days, the
|
|
14
|
+
* running year 6 hours), folded into (month, slot, sector) sums in the
|
|
15
|
+
* station's STANDARD time. Any refused year fails the whole document —
|
|
16
|
+
* a silently missing year would read as an outage. */
|
|
17
|
+
async function loadWindnerdClimatology(config, options) {
|
|
18
|
+
const environment = resolveEnvironment(options.environment);
|
|
19
|
+
const yearsBack = options.years ?? 8;
|
|
20
|
+
if (!Number.isInteger(yearsBack) || yearsBack < 1) throw new Error(`WindNerd location ${config.locationId}: years must be a positive integer`);
|
|
21
|
+
const sectorCount = options.sectorCount ?? 16;
|
|
22
|
+
const slotMinutes = options.slotMinutes ?? 180;
|
|
23
|
+
if (slotMinutes % 180 !== 0 || 1440 % slotMinutes !== 0) throw new Error(`WindNerd location ${config.locationId}: slotMinutes must be a multiple of 180 that divides 1440, got ${slotMinutes}`);
|
|
24
|
+
const thresholdsMps = thresholdsToMps(options.thresholds);
|
|
25
|
+
const utcOffsetMinutes = await standardOffsetMinutes(config, environment, options);
|
|
26
|
+
const accumulator = createClimatologyAccumulator({
|
|
27
|
+
sectorCount,
|
|
28
|
+
slotMinutes,
|
|
29
|
+
thresholdsMps,
|
|
30
|
+
utcOffsetMinutes
|
|
31
|
+
});
|
|
32
|
+
const now = environment.now();
|
|
33
|
+
const currentYear = now.getUTCFullYear();
|
|
34
|
+
const years = [];
|
|
35
|
+
for (let year = currentYear - (yearsBack - 1); year <= currentYear; year += 1) {
|
|
36
|
+
const from = Date.UTC(year, 0, 1);
|
|
37
|
+
const to = Math.min(Date.UTC(year + 1, 0, 1), now.getTime());
|
|
38
|
+
const url = new URL(options.recordsUrl ?? "https://windnerd.net/api/records");
|
|
39
|
+
url.searchParams.set("location_id", String(config.locationId));
|
|
40
|
+
url.searchParams.set("from", new Date(from).toISOString());
|
|
41
|
+
url.searchParams.set("to", new Date(Date.UTC(year + 1, 0, 1)).toISOString());
|
|
42
|
+
url.searchParams.set("period", String(180));
|
|
43
|
+
const points = windnerdHistoryPoints(parseWindnerdRecords(await fetchUpstreamText(environment, {
|
|
44
|
+
url,
|
|
45
|
+
cacheKey: `windnerd/climo/${config.locationId}/${year}/180`,
|
|
46
|
+
cacheTtlSeconds: year < currentYear ? CLOSED_YEAR_CACHE_TTL_SECONDS : CURRENT_YEAR_CACHE_TTL_SECONDS,
|
|
47
|
+
subject: `WindNerd location ${config.locationId} climatology ${year}`
|
|
48
|
+
}), config.locationId, config.hasPressure), config);
|
|
49
|
+
foldClimatologyPoints(accumulator, points);
|
|
50
|
+
years.push({
|
|
51
|
+
year,
|
|
52
|
+
sampleCount: points.length,
|
|
53
|
+
expectedCount: Math.floor((to - from) / (180 * 6e4)),
|
|
54
|
+
coveredSlotCount: 0,
|
|
55
|
+
expectedSlotCount: Math.floor((to - from) / (slotMinutes * 6e4))
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
const coveredByYear = coveredSlotCountByYear(accumulator);
|
|
59
|
+
for (const ledger of years) ledger.coveredSlotCount = coveredByYear.get(ledger.year) ?? 0;
|
|
60
|
+
while (years.length > 1 && years[0]?.sampleCount === 0) years.shift();
|
|
61
|
+
return {
|
|
62
|
+
schemaVersion: 1,
|
|
63
|
+
servedAt: now.toISOString(),
|
|
64
|
+
stationId: config.id,
|
|
65
|
+
sectorCount,
|
|
66
|
+
slotMinutes,
|
|
67
|
+
thresholdsMps,
|
|
68
|
+
utcOffsetMinutes,
|
|
69
|
+
years,
|
|
70
|
+
cells: accumulatedCells(accumulator)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
async function standardOffsetMinutes(config, environment, options) {
|
|
74
|
+
try {
|
|
75
|
+
return (await loadWindnerdLocation(config, environment, { liveUrl: options.liveUrl })).location?.standardUtcOffsetMinutes ?? 0;
|
|
76
|
+
} catch (error) {
|
|
77
|
+
logUpstreamFailure(environment, `${config.name} standard offset unavailable, bucketing in UTC`, error, { station: config.id });
|
|
78
|
+
return 0;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
82
|
+
export { CLIMATOLOGY_DEFAULT_SECTOR_COUNT, CLIMATOLOGY_DEFAULT_YEARS, CLIMATOLOGY_RECORD_PERIOD_MINUTES, loadWindnerdClimatology };
|
|
@@ -8,14 +8,11 @@ type WindnerdLiveOptions = {
|
|
|
8
8
|
liveUrl?: string;
|
|
9
9
|
idleTimeoutMs?: number;
|
|
10
10
|
};
|
|
11
|
-
/**
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* One call is one upstream connection: reconnect and fan-out belong to the
|
|
17
|
-
* caller, and a reconnect's fresh init frame is the resume story.
|
|
18
|
-
*/
|
|
11
|
+
/** Opens the station's live stream: one init frame, then
|
|
12
|
+
* samples/reading/ping as served. The connect phase (headers plus the
|
|
13
|
+
* upstream init frame) rejects on failure; after that, failures degrade
|
|
14
|
+
* to a terminal unavailable frame. One call is one upstream connection;
|
|
15
|
+
* reconnect and fan-out belong to the caller. */
|
|
19
16
|
declare function openWindnerdLive(config: WindnerdStationConfig, options?: WindnerdLiveOptions): Promise<ReadableStream<StationLiveFrame>>;
|
|
20
17
|
//#endregion
|
|
21
18
|
export { WindnerdLiveOptions, openWindnerdLive };
|
|
@@ -1,17 +1,14 @@
|
|
|
1
1
|
import "../../contract.js";
|
|
2
2
|
import { sseEvents } from "../../sse.js";
|
|
3
3
|
import { UpstreamError, fetchUpstreamStream, logUpstreamFailure, resolveEnvironment, unavailableReasonForError } from "../environment.js";
|
|
4
|
-
import { WINDNERD_LIVE_INIT_TIMEOUT_MS, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl, windnerdStationMeta } from "./windnerd.js";
|
|
4
|
+
import { WINDNERD_LIVE_INIT_TIMEOUT_MS, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecentSummaries, windnerdEnrichedMeta, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl, windnerdStationMeta } from "./windnerd.js";
|
|
5
5
|
//#region src/server/adapters/windnerd-live.ts
|
|
6
6
|
const LIVE_IDLE_TIMEOUT_MS = 75e3;
|
|
7
|
-
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* One call is one upstream connection: reconnect and fan-out belong to the
|
|
13
|
-
* caller, and a reconnect's fresh init frame is the resume story.
|
|
14
|
-
*/
|
|
7
|
+
/** Opens the station's live stream: one init frame, then
|
|
8
|
+
* samples/reading/ping as served. The connect phase (headers plus the
|
|
9
|
+
* upstream init frame) rejects on failure; after that, failures degrade
|
|
10
|
+
* to a terminal unavailable frame. One call is one upstream connection;
|
|
11
|
+
* reconnect and fan-out belong to the caller. */
|
|
15
12
|
async function openWindnerdLive(config, options = {}) {
|
|
16
13
|
const environment = resolveEnvironment(options.environment);
|
|
17
14
|
const subject = `WindNerd location ${config.locationId} live stream`;
|
|
@@ -73,8 +70,7 @@ async function openWindnerdLive(config, options = {}) {
|
|
|
73
70
|
try {
|
|
74
71
|
for await (const event of events) {
|
|
75
72
|
resetIdle();
|
|
76
|
-
const frame
|
|
77
|
-
if (frame) enqueue(frame);
|
|
73
|
+
for (const frame of mapLiveEvent(event, config, environment)) enqueue(frame);
|
|
78
74
|
}
|
|
79
75
|
finish("upstream_error");
|
|
80
76
|
} catch (error) {
|
|
@@ -119,12 +115,14 @@ async function readInitFrame(events, config, environment, upstream, options, sub
|
|
|
119
115
|
const { reading, telemetry } = windnerdLiveReading(init.digest, config);
|
|
120
116
|
const station = {
|
|
121
117
|
...windnerdStationMeta(config),
|
|
118
|
+
...windnerdEnrichedMeta(config, init.location, init.broadcastDelaySeconds),
|
|
122
119
|
recommendedPollSeconds: 15,
|
|
123
120
|
status: "ok",
|
|
124
121
|
reading,
|
|
125
122
|
history: null,
|
|
126
123
|
telemetry,
|
|
127
|
-
samples: windnerdLiveSamples(init.samples)
|
|
124
|
+
samples: windnerdLiveSamples(init.samples),
|
|
125
|
+
recentSummaries: init.recentSummaries
|
|
128
126
|
};
|
|
129
127
|
return {
|
|
130
128
|
type: "init",
|
|
@@ -141,11 +139,11 @@ async function readInitFrame(events, config, environment, upstream, options, sub
|
|
|
141
139
|
}
|
|
142
140
|
}
|
|
143
141
|
function mapLiveEvent(event, config, environment) {
|
|
144
|
-
if (event.event === "ping") return {
|
|
142
|
+
if (event.event === "ping") return [{
|
|
145
143
|
type: "ping",
|
|
146
144
|
servedAt: environment.now().toISOString()
|
|
147
|
-
};
|
|
148
|
-
if (event.event !== "message") return
|
|
145
|
+
}];
|
|
146
|
+
if (event.event !== "message") return [];
|
|
149
147
|
let frame;
|
|
150
148
|
try {
|
|
151
149
|
frame = JSON.parse(event.data);
|
|
@@ -154,22 +152,29 @@ function mapLiveEvent(event, config, environment) {
|
|
|
154
152
|
}
|
|
155
153
|
if (!isRecord(frame)) throw new Error(`WindNerd location ${config.locationId} sent an invalid live frame`);
|
|
156
154
|
switch (frame.type) {
|
|
157
|
-
case "WIND_SAMPLES": return {
|
|
155
|
+
case "WIND_SAMPLES": return [{
|
|
158
156
|
type: "samples",
|
|
159
157
|
stationId: config.id,
|
|
160
158
|
samples: windnerdLiveSamples(parseWindnerdLiveSampleRecords(frame.samples, config.locationId))
|
|
161
|
-
};
|
|
159
|
+
}];
|
|
162
160
|
case "LAST_DIGEST": {
|
|
163
161
|
const { reading, telemetry } = windnerdLiveReading(parseWindnerdLiveDigest(frame, config.locationId), config);
|
|
164
|
-
|
|
162
|
+
const servedAt = environment.now().toISOString();
|
|
163
|
+
const summaries = parseWindnerdRecentSummaries(frame);
|
|
164
|
+
return [{
|
|
165
165
|
type: "reading",
|
|
166
166
|
stationId: config.id,
|
|
167
|
-
servedAt
|
|
167
|
+
servedAt,
|
|
168
168
|
reading,
|
|
169
169
|
telemetry
|
|
170
|
-
}
|
|
170
|
+
}, ...summaries != null ? [{
|
|
171
|
+
type: "summaries",
|
|
172
|
+
stationId: config.id,
|
|
173
|
+
servedAt,
|
|
174
|
+
summaries
|
|
175
|
+
}] : []];
|
|
171
176
|
}
|
|
172
|
-
default: return
|
|
177
|
+
default: return [];
|
|
173
178
|
}
|
|
174
179
|
}
|
|
175
180
|
function isRecord(value) {
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import { HistoryPoint, LiveSamples, Reading, StationTelemetry } from "../../contract.js";
|
|
1
|
+
import { History, HistoryPoint, LiveSamples, Reading, RecentSummary, StationMeta, StationTelemetry } from "../../contract.js";
|
|
2
|
+
import "../environment.js";
|
|
2
3
|
import { WindnerdStationConfig } from "../config.js";
|
|
3
4
|
import { StationAdapter, StationAdapterOptions } from "../adapter.js";
|
|
5
|
+
import { DirectionArc } from "@azohra/meteo.core";
|
|
4
6
|
//#region src/server/adapters/windnerd.d.ts
|
|
5
|
-
declare const WINDNERD_RECORD_PERIODS_MINUTES: readonly [1, 15, 60, 180];
|
|
7
|
+
declare const WINDNERD_RECORD_PERIODS_MINUTES: readonly [1, 5, 10, 15, 30, 60, 180, 360];
|
|
6
8
|
type WindnerdRecordPeriodMinutes = (typeof WINDNERD_RECORD_PERIODS_MINUTES)[number];
|
|
7
9
|
declare const WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS = 3;
|
|
8
10
|
type WindnerdAdapterOptions = StationAdapterOptions & {
|
|
@@ -13,13 +15,17 @@ type WindnerdAdapterOptions = StationAdapterOptions & {
|
|
|
13
15
|
};
|
|
14
16
|
type WindnerdRecords = {
|
|
15
17
|
averageSpeedMps: number[];
|
|
18
|
+
vectorAverageSpeedMps: Array<number | null>;
|
|
16
19
|
windDirectionDeg: number[];
|
|
17
20
|
gustSpeedMps: number[];
|
|
18
21
|
lullSpeedMps: number[];
|
|
19
22
|
observedAt: string[];
|
|
20
23
|
temperatureC: Array<number | null>;
|
|
24
|
+
temperatureMinC: Array<number | null>;
|
|
25
|
+
temperatureMaxC: Array<number | null>;
|
|
21
26
|
stationPressureHpa: Array<number | null>;
|
|
22
|
-
|
|
27
|
+
stationPressureMinHpa: Array<number | null>;
|
|
28
|
+
stationPressureMaxHpa: Array<number | null>;
|
|
23
29
|
};
|
|
24
30
|
declare const loadWindnerdStation: StationAdapter<{
|
|
25
31
|
stationKey: string;
|
|
@@ -37,6 +43,12 @@ declare const loadWindnerdStation: StationAdapter<{
|
|
|
37
43
|
longitude?: number | null | undefined;
|
|
38
44
|
}, WindnerdAdapterOptions>;
|
|
39
45
|
declare function windnerdHistoryPoints(records: WindnerdRecords, config: Pick<WindnerdStationConfig, "hasTemperature" | "hasPressure" | "elevationM">): HistoryPoint[];
|
|
46
|
+
type WindnerdHistoryQuery = {
|
|
47
|
+
fromMs: number;
|
|
48
|
+
toMs: number;
|
|
49
|
+
periodMinutes: WindnerdRecordPeriodMinutes;
|
|
50
|
+
};
|
|
51
|
+
declare function loadWindnerdHistory(config: WindnerdStationConfig, query: WindnerdHistoryQuery, options?: WindnerdAdapterOptions): Promise<History>;
|
|
40
52
|
type WindnerdLiveDigest = {
|
|
41
53
|
observedAt: string;
|
|
42
54
|
windAvgMps: number;
|
|
@@ -52,12 +64,26 @@ type WindnerdLiveSampleRecord = {
|
|
|
52
64
|
speedMps: number;
|
|
53
65
|
directionDeg: number;
|
|
54
66
|
};
|
|
67
|
+
type WindnerdLiveLocation = {
|
|
68
|
+
declaredFavorableDirections: DirectionArc[] | null;
|
|
69
|
+
altitudeM: number | null;
|
|
70
|
+
timeZone: string | null;
|
|
71
|
+
latitude: number | null;
|
|
72
|
+
longitude: number | null;
|
|
73
|
+
standardUtcOffsetMinutes: number | null;
|
|
74
|
+
};
|
|
55
75
|
type WindnerdLiveInit = {
|
|
56
76
|
digest: WindnerdLiveDigest;
|
|
57
77
|
samples: WindnerdLiveSampleRecord[];
|
|
78
|
+
location: WindnerdLiveLocation | null;
|
|
79
|
+
broadcastDelaySeconds: number | null;
|
|
80
|
+
recentSummaries: RecentSummary[] | null;
|
|
58
81
|
};
|
|
59
82
|
declare function windnerdLiveStreamUrl(config: Pick<WindnerdStationConfig, "stationKey">, base?: string): URL;
|
|
60
83
|
declare function parseWindnerdLiveInit(value: string, locationId: number): WindnerdLiveInit;
|
|
84
|
+
declare function parseWindnerdRecentSummaries(value: unknown): RecentSummary[] | null;
|
|
85
|
+
declare function parseWindnerdLiveLocation(value: unknown): WindnerdLiveLocation | null;
|
|
86
|
+
declare function parseStandardTimeOffset(value: unknown): number | null;
|
|
61
87
|
declare function parseWindnerdLiveDigest(value: unknown, locationId: number): WindnerdLiveDigest;
|
|
62
88
|
declare function parseWindnerdLiveSampleRecords(value: unknown, locationId: number): WindnerdLiveSampleRecord[];
|
|
63
89
|
declare function windnerdLiveReading(digest: WindnerdLiveDigest, config: Pick<WindnerdStationConfig, "hasTemperature" | "hasPressure" | "hasBattery" | "elevationM">): {
|
|
@@ -65,6 +91,7 @@ declare function windnerdLiveReading(digest: WindnerdLiveDigest, config: Pick<Wi
|
|
|
65
91
|
telemetry: StationTelemetry | null;
|
|
66
92
|
};
|
|
67
93
|
declare function windnerdLiveSamples(records: WindnerdLiveSampleRecord[]): LiveSamples;
|
|
94
|
+
declare function windnerdEnrichedMeta(config: Pick<WindnerdStationConfig, "latitude" | "longitude" | "timeZone" | "elevationM">, location: WindnerdLiveLocation | null, broadcastDelaySeconds: number | null): Partial<StationMeta>;
|
|
68
95
|
declare function parseWindnerdRecords(value: string, locationId: number, hasPressure?: boolean): WindnerdRecords;
|
|
69
96
|
//#endregion
|
|
70
|
-
export { WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, WINDNERD_RECORD_PERIODS_MINUTES, WindnerdAdapterOptions, WindnerdLiveDigest, WindnerdLiveInit, WindnerdLiveSampleRecord, WindnerdRecordPeriodMinutes, WindnerdRecords, loadWindnerdStation, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl };
|
|
97
|
+
export { WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, WINDNERD_RECORD_PERIODS_MINUTES, WindnerdAdapterOptions, WindnerdHistoryQuery, WindnerdLiveDigest, WindnerdLiveInit, WindnerdLiveLocation, WindnerdLiveSampleRecord, WindnerdRecordPeriodMinutes, WindnerdRecords, loadWindnerdHistory, loadWindnerdStation, parseStandardTimeOffset, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveLocation, parseWindnerdLiveSampleRecords, parseWindnerdRecentSummaries, parseWindnerdRecords, windnerdEnrichedMeta, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl };
|
|
@@ -2,7 +2,7 @@ import { emptyConditions } from "../../contract.js";
|
|
|
2
2
|
import { isCalm, normalizeDegrees, pressureTendency, seaLevelPressureHpa } from "../../derive.js";
|
|
3
3
|
import { windnerdStationUrl } from "../../windnerd.js";
|
|
4
4
|
import { sseEvents } from "../../sse.js";
|
|
5
|
-
import { coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure } from "../environment.js";
|
|
5
|
+
import { coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, resolveEnvironment } from "../environment.js";
|
|
6
6
|
import { defineStationAdapter } from "../adapter.js";
|
|
7
7
|
import { UpstreamError } from "@azohra/meteo.core";
|
|
8
8
|
//#region src/server/adapters/windnerd.ts
|
|
@@ -11,13 +11,19 @@ const WINDNERD_LIVE_URL = "https://windnerd.net/api/live-url";
|
|
|
11
11
|
const RECORD_PERIOD_MINUTES = 1;
|
|
12
12
|
const WINDNERD_RECORD_PERIODS_MINUTES = [
|
|
13
13
|
1,
|
|
14
|
+
5,
|
|
15
|
+
10,
|
|
14
16
|
15,
|
|
17
|
+
30,
|
|
15
18
|
60,
|
|
16
|
-
180
|
|
19
|
+
180,
|
|
20
|
+
360
|
|
17
21
|
];
|
|
18
22
|
const CACHE_TTL_SECONDS = 60;
|
|
19
23
|
const AGGREGATE_CACHE_TTL_SECONDS = 900;
|
|
20
24
|
const LIVE_CACHE_TTL_SECONDS = 15;
|
|
25
|
+
const LOCATION_CACHE_TTL_SECONDS = 21600;
|
|
26
|
+
const LOCATION_MISS_CACHE_TTL_SECONDS = 900;
|
|
21
27
|
const WINDNERD_LIVE_INIT_TIMEOUT_MS = 8e3;
|
|
22
28
|
const WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS = 3;
|
|
23
29
|
const SENSOR_VALUE_LOOKBACK_MS = 15 * 6e4;
|
|
@@ -44,7 +50,8 @@ function windnerdStationMeta(config) {
|
|
|
44
50
|
conditions: config.hasPressure,
|
|
45
51
|
history: true,
|
|
46
52
|
live: true,
|
|
47
|
-
battery: config.hasBattery
|
|
53
|
+
battery: config.hasBattery,
|
|
54
|
+
recentSummaries: true
|
|
48
55
|
},
|
|
49
56
|
samplingWindowSeconds: 60,
|
|
50
57
|
recommendedPollSeconds: 60
|
|
@@ -61,7 +68,7 @@ const loadWindnerdStation = defineStationAdapter({
|
|
|
61
68
|
const periodMinutes = options.recordPeriodMinutes ?? RECORD_PERIOD_MINUTES;
|
|
62
69
|
if (!WINDNERD_RECORD_PERIODS_MINUTES.includes(periodMinutes)) throw new Error(`WindNerd location ${config.locationId}: recordPeriodMinutes must be one of ${WINDNERD_RECORD_PERIODS_MINUTES.join(", ")}, got ${periodMinutes}`);
|
|
63
70
|
const now = environment.now();
|
|
64
|
-
const url = new URL(options.recordsUrl ??
|
|
71
|
+
const url = new URL(options.recordsUrl ?? "https://windnerd.net/api/records");
|
|
65
72
|
url.searchParams.set("location_id", String(config.locationId));
|
|
66
73
|
url.searchParams.set("from", (/* @__PURE__ */ new Date(now.getTime() - historyHours * 36e5)).toISOString());
|
|
67
74
|
url.searchParams.set("to", now.toISOString());
|
|
@@ -77,6 +84,7 @@ const loadWindnerdStation = defineStationAdapter({
|
|
|
77
84
|
if (!last) throw new Error(`WindNerd location ${config.locationId} returned no wind`);
|
|
78
85
|
const lastMs = Date.parse(last.observedAt);
|
|
79
86
|
return {
|
|
87
|
+
meta: await loadWindnerdLocationEnrichment(config, environment, options),
|
|
80
88
|
reading: {
|
|
81
89
|
observedAt: last.observedAt,
|
|
82
90
|
windAvgMps: last.windAvgMps,
|
|
@@ -98,15 +106,20 @@ function windnerdHistoryPoints(records, config) {
|
|
|
98
106
|
const barometerElevationM = config.hasPressure ? config.elevationM ?? null : null;
|
|
99
107
|
return records.observedAt.map((observedAt, index) => {
|
|
100
108
|
const windAvgMps = records.averageSpeedMps[index];
|
|
101
|
-
const
|
|
109
|
+
const reduced = (stationPressure) => barometerElevationM != null && stationPressure != null ? seaLevelPressureHpa(stationPressure, barometerElevationM, records.temperatureC[index] ?? null) : null;
|
|
102
110
|
return {
|
|
103
111
|
observedAt,
|
|
104
112
|
windAvgMps,
|
|
105
113
|
windGustMps: records.gustSpeedMps[index],
|
|
106
114
|
windLullMps: records.lullSpeedMps[index],
|
|
107
115
|
windDirectionDeg: isCalm(windAvgMps) ? null : normalizeDegrees(records.windDirectionDeg[index]),
|
|
116
|
+
windVectorAvgMps: records.vectorAverageSpeedMps[index] ?? null,
|
|
108
117
|
temperatureC: config.hasTemperature ? records.temperatureC[index] ?? null : null,
|
|
109
|
-
|
|
118
|
+
temperatureMinC: config.hasTemperature ? records.temperatureMinC[index] ?? null : null,
|
|
119
|
+
temperatureMaxC: config.hasTemperature ? records.temperatureMaxC[index] ?? null : null,
|
|
120
|
+
seaLevelPressureHpa: reduced(records.stationPressureHpa[index] ?? null),
|
|
121
|
+
seaLevelPressureMinHpa: reduced(records.stationPressureMinHpa[index] ?? null),
|
|
122
|
+
seaLevelPressureMaxHpa: reduced(records.stationPressureMaxHpa[index] ?? null)
|
|
110
123
|
};
|
|
111
124
|
});
|
|
112
125
|
}
|
|
@@ -118,6 +131,37 @@ function windnerdConditions(records, points, config, readingObservedAtMs) {
|
|
|
118
131
|
seaLevelPressureHpa: reduced
|
|
119
132
|
});
|
|
120
133
|
}
|
|
134
|
+
const ARCHIVE_PAST_CACHE_TTL_SECONDS = 2592e3;
|
|
135
|
+
const ARCHIVE_LIVE_CACHE_TTL_SECONDS = 300;
|
|
136
|
+
const DAY_MS = 864e5;
|
|
137
|
+
async function loadWindnerdHistory(config, query, options = {}) {
|
|
138
|
+
const { fromMs, toMs, periodMinutes } = query;
|
|
139
|
+
if (!WINDNERD_RECORD_PERIODS_MINUTES.includes(periodMinutes)) throw new Error(`WindNerd location ${config.locationId}: periodMinutes must be one of ${WINDNERD_RECORD_PERIODS_MINUTES.join(", ")}, got ${periodMinutes}`);
|
|
140
|
+
if (!Number.isFinite(fromMs) || !Number.isFinite(toMs) || fromMs >= toMs) throw new Error(`WindNerd location ${config.locationId}: history window is empty`);
|
|
141
|
+
const environment = resolveEnvironment(options.environment);
|
|
142
|
+
const fromDayMs = Math.floor(fromMs / DAY_MS) * DAY_MS;
|
|
143
|
+
const toDayMs = Math.ceil(toMs / DAY_MS) * DAY_MS;
|
|
144
|
+
const nowMs = environment.now().getTime();
|
|
145
|
+
const url = new URL(options.recordsUrl ?? "https://windnerd.net/api/records");
|
|
146
|
+
url.searchParams.set("location_id", String(config.locationId));
|
|
147
|
+
url.searchParams.set("from", new Date(fromDayMs).toISOString());
|
|
148
|
+
url.searchParams.set("to", new Date(toDayMs).toISOString());
|
|
149
|
+
url.searchParams.set("period", String(periodMinutes));
|
|
150
|
+
const fromDay = new Date(fromDayMs).toISOString().slice(0, 10);
|
|
151
|
+
const toDay = new Date(toDayMs).toISOString().slice(0, 10);
|
|
152
|
+
return {
|
|
153
|
+
periodMinutes,
|
|
154
|
+
points: windnerdHistoryPoints(parseWindnerdRecords(await fetchUpstreamText(environment, {
|
|
155
|
+
url,
|
|
156
|
+
cacheKey: `windnerd/${config.locationId}/archive/${periodMinutes}/${fromDay}-${toDay}`,
|
|
157
|
+
cacheTtlSeconds: options.cacheTtlSeconds ?? (toDayMs <= nowMs ? ARCHIVE_PAST_CACHE_TTL_SECONDS : ARCHIVE_LIVE_CACHE_TTL_SECONDS),
|
|
158
|
+
subject: `WindNerd location ${config.locationId} archive`
|
|
159
|
+
}), config.locationId, config.hasPressure), config).filter((point) => {
|
|
160
|
+
const observedMs = Date.parse(point.observedAt);
|
|
161
|
+
return observedMs >= fromMs && observedMs < toMs;
|
|
162
|
+
})
|
|
163
|
+
};
|
|
164
|
+
}
|
|
121
165
|
function windnerdLiveStreamUrl(config, base = WINDNERD_LIVE_URL) {
|
|
122
166
|
const trimmed = base.endsWith("/") ? base.slice(0, -1) : base;
|
|
123
167
|
return new URL(`${trimmed}/${encodeURIComponent(config.stationKey)}`);
|
|
@@ -130,11 +174,97 @@ function parseWindnerdLiveInit(value, locationId) {
|
|
|
130
174
|
throw new Error(`WindNerd location ${locationId} returned an unparseable live frame`);
|
|
131
175
|
}
|
|
132
176
|
if (!isRecord(data) || data.type !== "INIT") throw new Error(`WindNerd location ${locationId} returned no live init frame`);
|
|
177
|
+
const delay = data.delay;
|
|
133
178
|
return {
|
|
134
179
|
digest: parseWindnerdLiveDigest(data.digest, locationId),
|
|
135
|
-
samples: parseWindnerdLiveSampleRecords(data.samples, locationId)
|
|
180
|
+
samples: parseWindnerdLiveSampleRecords(data.samples, locationId),
|
|
181
|
+
location: parseWindnerdLiveLocation(data.location),
|
|
182
|
+
broadcastDelaySeconds: typeof delay === "number" && Number.isFinite(delay) && delay >= 0 ? delay : null,
|
|
183
|
+
recentSummaries: parseWindnerdRecentSummaries(data.digest)
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
function parseWindnerdRecentSummaries(value) {
|
|
187
|
+
if (!isRecord(value) || !isRecord(value.recent)) return null;
|
|
188
|
+
const anchor = value.recent.date_utc;
|
|
189
|
+
if (typeof anchor !== "string") return null;
|
|
190
|
+
const anchorMs = Date.parse(anchor);
|
|
191
|
+
if (!Number.isFinite(anchorMs)) return null;
|
|
192
|
+
const summaries = [];
|
|
193
|
+
const blocks = [{
|
|
194
|
+
entries: value.last_10mn_by_1mn,
|
|
195
|
+
stepMinutes: 1,
|
|
196
|
+
windowMinutes: 10
|
|
197
|
+
}, {
|
|
198
|
+
entries: value.last_60mn_by_5mn,
|
|
199
|
+
stepMinutes: 5,
|
|
200
|
+
windowMinutes: 60
|
|
201
|
+
}];
|
|
202
|
+
for (const { entries, stepMinutes, windowMinutes } of blocks) {
|
|
203
|
+
if (!Array.isArray(entries)) continue;
|
|
204
|
+
const points = summaryPoints(entries, anchorMs, stepMinutes);
|
|
205
|
+
if (points == null) continue;
|
|
206
|
+
summaries.push({
|
|
207
|
+
windowMinutes,
|
|
208
|
+
stepMinutes,
|
|
209
|
+
points
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
return summaries.length > 0 ? summaries : null;
|
|
213
|
+
}
|
|
214
|
+
function summaryPoints(entries, anchorMs, stepMinutes) {
|
|
215
|
+
const points = [];
|
|
216
|
+
const finiteIn = (entry, minimum, maximum) => typeof entry === "number" && Number.isFinite(entry) && entry >= minimum && entry <= maximum ? entry : null;
|
|
217
|
+
for (const [index, entry] of entries.entries()) {
|
|
218
|
+
if (entry == null) continue;
|
|
219
|
+
if (!isRecord(entry)) return null;
|
|
220
|
+
const windAvgMps = finiteIn(entry.wind_avg_1D, 0, MAX_WIND_MPS) ?? finiteIn(entry.wind_avg_2D, 0, MAX_WIND_MPS);
|
|
221
|
+
const windDirectionDeg = finiteIn(entry.wind_dir, 0, 360);
|
|
222
|
+
if (windAvgMps == null || windDirectionDeg == null) return null;
|
|
223
|
+
points.push({
|
|
224
|
+
observedAt: (/* @__PURE__ */ new Date(anchorMs - (entries.length - 1 - index) * stepMinutes * 6e4)).toISOString(),
|
|
225
|
+
windAvgMps,
|
|
226
|
+
windGustMps: finiteIn(entry.wind_max, 0, MAX_WIND_MPS),
|
|
227
|
+
windLullMps: finiteIn(entry.wind_min, 0, MAX_WIND_MPS),
|
|
228
|
+
windDirectionDeg: isCalm(windAvgMps) ? null : normalizeDegrees(windDirectionDeg),
|
|
229
|
+
windVectorAvgMps: finiteIn(entry.wind_avg_2D, 0, MAX_WIND_MPS),
|
|
230
|
+
temperatureC: null
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
return points;
|
|
234
|
+
}
|
|
235
|
+
function parseWindnerdLiveLocation(value) {
|
|
236
|
+
if (!isRecord(value)) return null;
|
|
237
|
+
const finiteOrNull = (entry) => typeof entry === "number" && Number.isFinite(entry) ? entry : null;
|
|
238
|
+
const position = isRecord(value.guessed_position) ? value.guessed_position : null;
|
|
239
|
+
return {
|
|
240
|
+
declaredFavorableDirections: parseDirRanges((isRecord(value.location_type_meta) ? value.location_type_meta : null)?.dir_ranges),
|
|
241
|
+
altitudeM: finiteOrNull(value.altitude),
|
|
242
|
+
timeZone: typeof value.timezone === "string" && value.timezone !== "" ? value.timezone : null,
|
|
243
|
+
latitude: finiteOrNull(position?.lat),
|
|
244
|
+
longitude: finiteOrNull(position?.lon),
|
|
245
|
+
standardUtcOffsetMinutes: parseStandardTimeOffset(value.standard_timeoffset)
|
|
136
246
|
};
|
|
137
247
|
}
|
|
248
|
+
function parseDirRanges(value) {
|
|
249
|
+
if (!Array.isArray(value)) return null;
|
|
250
|
+
const arcs = [];
|
|
251
|
+
for (const entry of value) {
|
|
252
|
+
if (!isRecord(entry) || typeof entry.from !== "number" || !Number.isFinite(entry.from) || typeof entry.to !== "number" || !Number.isFinite(entry.to)) return null;
|
|
253
|
+
arcs.push({
|
|
254
|
+
fromDeg: entry.from,
|
|
255
|
+
toDeg: entry.to
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
return arcs;
|
|
259
|
+
}
|
|
260
|
+
function parseStandardTimeOffset(value) {
|
|
261
|
+
if (typeof value !== "string") return null;
|
|
262
|
+
const match = /^([+-])(\d{2}):(\d{2})$/.exec(value.trim());
|
|
263
|
+
if (match == null) return null;
|
|
264
|
+
const minutes = (match[1] === "-" ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3]));
|
|
265
|
+
if (minutes < UTC_OFFSET_MIN_MINUTES || minutes > UTC_OFFSET_MAX_MINUTES) return null;
|
|
266
|
+
return minutes;
|
|
267
|
+
}
|
|
138
268
|
function parseWindnerdLiveDigest(value, locationId) {
|
|
139
269
|
const fail = (name) => {
|
|
140
270
|
throw new Error(`WindNerd location ${locationId} returned an invalid live ${name}`);
|
|
@@ -215,13 +345,61 @@ function windnerdLiveSamples(records) {
|
|
|
215
345
|
}
|
|
216
346
|
async function loadWindnerdLiveCurrent(config, environment, options) {
|
|
217
347
|
const init = parseWindnerdLiveInit(await fetchWindnerdLiveInitText(config, environment, options), config.locationId);
|
|
348
|
+
await cacheWindnerdLocation(config, environment, init);
|
|
218
349
|
const { reading, telemetry } = windnerdLiveReading(init.digest, config);
|
|
219
350
|
return {
|
|
220
351
|
reading,
|
|
221
352
|
history: null,
|
|
222
353
|
telemetry,
|
|
223
354
|
samples: windnerdLiveSamples(init.samples),
|
|
224
|
-
|
|
355
|
+
recentSummaries: init.recentSummaries,
|
|
356
|
+
meta: {
|
|
357
|
+
recommendedPollSeconds: 15,
|
|
358
|
+
...windnerdEnrichedMeta(config, init.location, init.broadcastDelaySeconds)
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
async function cacheWindnerdLocation(config, environment, init) {
|
|
363
|
+
const cached = {
|
|
364
|
+
location: init.location,
|
|
365
|
+
broadcastDelaySeconds: init.broadcastDelaySeconds
|
|
366
|
+
};
|
|
367
|
+
await environment.cache.put(`windnerd/location/${config.locationId}`, JSON.stringify(cached), LOCATION_CACHE_TTL_SECONDS);
|
|
368
|
+
}
|
|
369
|
+
/** Cached location block (6-hour TTL). Throws on a cold cache when the
|
|
370
|
+
* live stream is unreachable; callers choose degrade or fail. */
|
|
371
|
+
async function loadWindnerdLocation(config, environment, options = {}) {
|
|
372
|
+
const cached = await environment.cache.get(`windnerd/location/${config.locationId}`);
|
|
373
|
+
if (cached != null) return JSON.parse(cached);
|
|
374
|
+
const init = parseWindnerdLiveInit(await fetchWindnerdLiveInitText(config, environment, options), config.locationId);
|
|
375
|
+
await cacheWindnerdLocation(config, environment, init);
|
|
376
|
+
return {
|
|
377
|
+
location: init.location,
|
|
378
|
+
broadcastDelaySeconds: init.broadcastDelaySeconds
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
async function loadWindnerdLocationEnrichment(config, environment, options) {
|
|
382
|
+
try {
|
|
383
|
+
const parsed = await loadWindnerdLocation(config, environment, options);
|
|
384
|
+
return windnerdEnrichedMeta(config, parsed.location, parsed.broadcastDelaySeconds);
|
|
385
|
+
} catch (error) {
|
|
386
|
+
logUpstreamFailure(environment, `${config.name} location metadata unavailable`, error, { station: config.id });
|
|
387
|
+
await environment.cache.put(`windnerd/location/${config.locationId}`, JSON.stringify({
|
|
388
|
+
location: null,
|
|
389
|
+
broadcastDelaySeconds: null
|
|
390
|
+
}), LOCATION_MISS_CACHE_TTL_SECONDS);
|
|
391
|
+
return {};
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
function windnerdEnrichedMeta(config, location, broadcastDelaySeconds) {
|
|
395
|
+
if (location == null && broadcastDelaySeconds == null) return {};
|
|
396
|
+
return {
|
|
397
|
+
latitude: config.latitude ?? location?.latitude ?? null,
|
|
398
|
+
longitude: config.longitude ?? location?.longitude ?? null,
|
|
399
|
+
timeZone: config.timeZone ?? location?.timeZone ?? null,
|
|
400
|
+
elevationM: config.elevationM ?? location?.altitudeM ?? null,
|
|
401
|
+
declaredFavorableDirections: location?.declaredFavorableDirections ?? null,
|
|
402
|
+
broadcastDelaySeconds
|
|
225
403
|
};
|
|
226
404
|
}
|
|
227
405
|
async function fetchWindnerdLiveInitText(config, environment, options) {
|
|
@@ -272,24 +450,23 @@ function parseWindnerdRecords(value, locationId, hasPressure = false) {
|
|
|
272
450
|
throw new Error(`WindNerd location ${locationId} returned an invalid ${name}`);
|
|
273
451
|
};
|
|
274
452
|
const speeds = (name) => numberSeries(records[name], dates.length, 0, MAX_WIND_MPS, name, fail);
|
|
453
|
+
const optionalSeries = (name, minimum = -Infinity, maximum = Infinity) => records[name] == null ? dates.map(() => null) : nullableSeries(records[name], dates.length, name, fail, minimum, maximum);
|
|
454
|
+
const requiredSeries = (name, minimum = -Infinity, maximum = Infinity) => dates.length === 0 ? [] : nullableSeries(records[name], dates.length, name, fail, minimum, maximum);
|
|
275
455
|
return {
|
|
276
456
|
averageSpeedMps: speeds("wind_avg_1D"),
|
|
457
|
+
vectorAverageSpeedMps: optionalSeries("wind_avg_2D", 0, MAX_WIND_MPS),
|
|
277
458
|
windDirectionDeg: numberSeries(records.wind_dir, dates.length, 0, 360, "wind_dir", fail),
|
|
278
459
|
gustSpeedMps: speeds("wind_max"),
|
|
279
460
|
lullSpeedMps: speeds("wind_min"),
|
|
280
461
|
observedAt: dates.map((date) => recordTimeToIso(date, locationId)),
|
|
281
|
-
temperatureC:
|
|
282
|
-
|
|
283
|
-
|
|
462
|
+
temperatureC: requiredSeries("temperature_avg"),
|
|
463
|
+
temperatureMinC: optionalSeries("temperature_min"),
|
|
464
|
+
temperatureMaxC: optionalSeries("temperature_max"),
|
|
465
|
+
stationPressureHpa: hasPressure ? requiredSeries("pressure_hpa_avg", STATION_PRESSURE_MIN_HPA, STATION_PRESSURE_MAX_HPA) : dates.map(() => null),
|
|
466
|
+
stationPressureMinHpa: hasPressure ? optionalSeries("pressure_hpa_min", STATION_PRESSURE_MIN_HPA, STATION_PRESSURE_MAX_HPA) : dates.map(() => null),
|
|
467
|
+
stationPressureMaxHpa: hasPressure ? optionalSeries("pressure_hpa_max", STATION_PRESSURE_MIN_HPA, STATION_PRESSURE_MAX_HPA) : dates.map(() => null)
|
|
284
468
|
};
|
|
285
469
|
}
|
|
286
|
-
function parseUtcOffsetMinutes(value, locationId) {
|
|
287
|
-
if (!Array.isArray(value)) return null;
|
|
288
|
-
const first = value.find((entry) => typeof entry === "number" && Number.isFinite(entry));
|
|
289
|
-
if (first == null) return null;
|
|
290
|
-
if (first < UTC_OFFSET_MIN_MINUTES || first > UTC_OFFSET_MAX_MINUTES) throw new Error(`WindNerd location ${locationId} returned an invalid time_offset`);
|
|
291
|
-
return first;
|
|
292
|
-
}
|
|
293
470
|
function latestSensorValue(series, observedAt, readingObservedAtMs) {
|
|
294
471
|
for (let index = series.length - 1; index >= 0; index -= 1) {
|
|
295
472
|
const value = series[index];
|
|
@@ -318,4 +495,4 @@ function isRecord(value) {
|
|
|
318
495
|
return typeof value === "object" && value !== null;
|
|
319
496
|
}
|
|
320
497
|
//#endregion
|
|
321
|
-
export { WINDNERD_LIVE_INIT_TIMEOUT_MS, WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, WINDNERD_RECORD_PERIODS_MINUTES, loadWindnerdStation, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl, windnerdStationMeta };
|
|
498
|
+
export { WINDNERD_LIVE_INIT_TIMEOUT_MS, WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, WINDNERD_RECORDS_URL, WINDNERD_RECORD_PERIODS_MINUTES, loadWindnerdHistory, loadWindnerdLocation, loadWindnerdStation, parseStandardTimeOffset, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveLocation, parseWindnerdLiveSampleRecords, parseWindnerdRecentSummaries, parseWindnerdRecords, windnerdEnrichedMeta, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl, windnerdStationMeta };
|