@azohra/meteo.station 0.1.1 → 0.1.2
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/index.d.ts +2 -1
- package/dist/client/index.js +2 -1
- package/dist/client/live.d.ts +37 -0
- package/dist/client/live.js +241 -0
- package/dist/client/stores.d.ts +1 -0
- package/dist/client/stores.js +41 -6
- package/dist/contract.d.ts +237 -1
- package/dist/contract.js +57 -3
- package/dist/endpoints.d.ts +2 -1
- package/dist/endpoints.js +4 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -3
- package/dist/react/hooks/useStation.d.ts +1 -0
- package/dist/react/hooks/useStation.js +25 -5
- package/dist/react/hooks/useStationLive.d.ts +20 -0
- package/dist/react/hooks/useStationLive.js +33 -0
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.js +2 -1
- package/dist/server/adapter.d.ts +3 -1
- package/dist/server/adapter.js +3 -1
- package/dist/server/adapters/windnerd-live.d.ts +21 -0
- package/dist/server/adapters/windnerd-live.js +179 -0
- package/dist/server/adapters/windnerd.d.ts +36 -5
- package/dist/server/adapters/windnerd.js +177 -15
- package/dist/server/config.d.ts +2 -0
- package/dist/server/config.js +2 -1
- package/dist/server/environment.d.ts +25 -5
- package/dist/server/environment.js +65 -21
- package/dist/server/feed.d.ts +20 -2
- package/dist/server/feed.js +28 -1
- package/dist/server/handler.d.ts +1 -1
- package/dist/server/handler.js +37 -3
- package/dist/server/index.d.ts +6 -4
- package/dist/server/index.js +6 -4
- package/dist/server/live.d.ts +15 -0
- package/dist/server/live.js +19 -0
- package/dist/sse.js +56 -0
- package/package.json +1 -1
- package/schema/README.md +1 -1
- package/schema/example-feed.json +26 -1
- package/schema/example-live.json +74 -0
- package/schema/stationcurrent.schema.json +115 -0
- package/schema/stationfeed.schema.json +115 -0
- package/schema/stationlive.schema.json +868 -0
package/dist/server/adapter.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { History, Reading, Station, StationMeta } from "../contract.js";
|
|
1
|
+
import { History, LiveSamples, Reading, 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";
|
|
@@ -16,6 +16,8 @@ type StationAdapterContext<O extends StationAdapterOptions = StationAdapterOptio
|
|
|
16
16
|
type StationAdapterResult = {
|
|
17
17
|
readonly reading: Reading;
|
|
18
18
|
readonly history: History | null;
|
|
19
|
+
readonly telemetry?: StationTelemetry | null;
|
|
20
|
+
readonly samples?: LiveSamples | null;
|
|
19
21
|
readonly meta?: Partial<StationMeta>;
|
|
20
22
|
};
|
|
21
23
|
type StationAdapterDefinition<C, O extends StationAdapterOptions = StationAdapterOptions> = {
|
package/dist/server/adapter.js
CHANGED
|
@@ -20,7 +20,9 @@ function defineStationAdapter(definition) {
|
|
|
20
20
|
...result.meta,
|
|
21
21
|
status: "ok",
|
|
22
22
|
reading: result.reading,
|
|
23
|
-
history: mode === "current" ? null : result.history
|
|
23
|
+
history: mode === "current" ? null : result.history,
|
|
24
|
+
telemetry: result.telemetry ?? null,
|
|
25
|
+
samples: result.samples ?? null
|
|
24
26
|
};
|
|
25
27
|
} catch (error) {
|
|
26
28
|
logUpstreamFailure(environment, `${meta.name} live wind unavailable`, error, { station: meta.id });
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { StationLiveFrame } from "../../contract.js";
|
|
2
|
+
import { ServerEnvironment } from "../environment.js";
|
|
3
|
+
import { WindnerdStationConfig } from "../config.js";
|
|
4
|
+
//#region src/server/adapters/windnerd-live.d.ts
|
|
5
|
+
type WindnerdLiveOptions = {
|
|
6
|
+
environment?: ServerEnvironment;
|
|
7
|
+
signal?: AbortSignal;
|
|
8
|
+
liveUrl?: string;
|
|
9
|
+
idleTimeoutMs?: number;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Opens the station's live stream and returns our frames: one init, then
|
|
13
|
+
* samples/reading/ping as the upstream serves them. The connect phase —
|
|
14
|
+
* headers plus the upstream init frame — rejects on failure; once resolved,
|
|
15
|
+
* failures degrade to a terminal unavailable frame instead of throwing.
|
|
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
|
+
*/
|
|
19
|
+
declare function openWindnerdLive(config: WindnerdStationConfig, options?: WindnerdLiveOptions): Promise<ReadableStream<StationLiveFrame>>;
|
|
20
|
+
//#endregion
|
|
21
|
+
export { WindnerdLiveOptions, openWindnerdLive };
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import "../../contract.js";
|
|
2
|
+
import { sseEvents } from "../../sse.js";
|
|
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";
|
|
5
|
+
//#region src/server/adapters/windnerd-live.ts
|
|
6
|
+
const LIVE_IDLE_TIMEOUT_MS = 75e3;
|
|
7
|
+
/**
|
|
8
|
+
* Opens the station's live stream and returns our frames: one init, then
|
|
9
|
+
* samples/reading/ping as the upstream serves them. The connect phase —
|
|
10
|
+
* headers plus the upstream init frame — rejects on failure; once resolved,
|
|
11
|
+
* failures degrade to a terminal unavailable frame instead of throwing.
|
|
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
|
+
*/
|
|
15
|
+
async function openWindnerdLive(config, options = {}) {
|
|
16
|
+
const environment = resolveEnvironment(options.environment);
|
|
17
|
+
const subject = `WindNerd location ${config.locationId} live stream`;
|
|
18
|
+
const upstream = new AbortController();
|
|
19
|
+
const abortFromCaller = () => upstream.abort();
|
|
20
|
+
options.signal?.addEventListener("abort", abortFromCaller, { once: true });
|
|
21
|
+
if (options.signal?.aborted) upstream.abort();
|
|
22
|
+
const releaseCaller = () => options.signal?.removeEventListener("abort", abortFromCaller);
|
|
23
|
+
let events;
|
|
24
|
+
let initFrame;
|
|
25
|
+
try {
|
|
26
|
+
events = sseEvents((await fetchUpstreamStream(environment, {
|
|
27
|
+
url: windnerdLiveStreamUrl(config, options.liveUrl),
|
|
28
|
+
subject,
|
|
29
|
+
signal: upstream.signal
|
|
30
|
+
})).body, { signal: upstream.signal });
|
|
31
|
+
initFrame = await readInitFrame(events, config, environment, upstream, options, subject);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
upstream.abort();
|
|
34
|
+
releaseCaller();
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
let closed = false;
|
|
38
|
+
let watchdogFired = false;
|
|
39
|
+
let idleTimer = null;
|
|
40
|
+
return new ReadableStream({
|
|
41
|
+
start: (controller) => {
|
|
42
|
+
const enqueue = (frame) => {
|
|
43
|
+
if (closed) return;
|
|
44
|
+
try {
|
|
45
|
+
controller.enqueue(frame);
|
|
46
|
+
} catch {
|
|
47
|
+
closed = true;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
const finish = (reason) => {
|
|
51
|
+
if (reason) enqueue({
|
|
52
|
+
type: "unavailable",
|
|
53
|
+
stationId: config.id,
|
|
54
|
+
reason
|
|
55
|
+
});
|
|
56
|
+
if (!closed) {
|
|
57
|
+
closed = true;
|
|
58
|
+
try {
|
|
59
|
+
controller.close();
|
|
60
|
+
} catch {}
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const resetIdle = () => {
|
|
64
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
65
|
+
idleTimer = setTimeout(() => {
|
|
66
|
+
watchdogFired = true;
|
|
67
|
+
upstream.abort();
|
|
68
|
+
}, options.idleTimeoutMs ?? LIVE_IDLE_TIMEOUT_MS);
|
|
69
|
+
};
|
|
70
|
+
enqueue(initFrame);
|
|
71
|
+
(async () => {
|
|
72
|
+
resetIdle();
|
|
73
|
+
try {
|
|
74
|
+
for await (const event of events) {
|
|
75
|
+
resetIdle();
|
|
76
|
+
const frame = mapLiveEvent(event, config, environment);
|
|
77
|
+
if (frame) enqueue(frame);
|
|
78
|
+
}
|
|
79
|
+
finish("upstream_error");
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (options.signal?.aborted || closed) finish();
|
|
82
|
+
else if (watchdogFired) {
|
|
83
|
+
logUpstreamFailure(environment, `${config.name} live stream went quiet`, error, { station: config.id });
|
|
84
|
+
finish("timeout");
|
|
85
|
+
} else {
|
|
86
|
+
logUpstreamFailure(environment, `${config.name} live stream failed`, error, { station: config.id });
|
|
87
|
+
finish(unavailableReasonForError(error));
|
|
88
|
+
}
|
|
89
|
+
} finally {
|
|
90
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
91
|
+
upstream.abort();
|
|
92
|
+
releaseCaller();
|
|
93
|
+
}
|
|
94
|
+
})();
|
|
95
|
+
},
|
|
96
|
+
cancel: () => {
|
|
97
|
+
closed = true;
|
|
98
|
+
upstream.abort();
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
async function readInitFrame(events, config, environment, upstream, options, subject) {
|
|
103
|
+
const timer = setTimeout(() => upstream.abort(), WINDNERD_LIVE_INIT_TIMEOUT_MS);
|
|
104
|
+
try {
|
|
105
|
+
while (true) {
|
|
106
|
+
const result = await events.next();
|
|
107
|
+
if (result.done) throw new UpstreamError(`${subject} ended before its init frame`);
|
|
108
|
+
const event = result.value;
|
|
109
|
+
if (event.event !== "message") continue;
|
|
110
|
+
let type;
|
|
111
|
+
try {
|
|
112
|
+
const frame = JSON.parse(event.data);
|
|
113
|
+
type = isRecord(frame) ? frame.type : void 0;
|
|
114
|
+
} catch {
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (type !== "INIT") continue;
|
|
118
|
+
const init = parseWindnerdLiveInit(event.data, config.locationId);
|
|
119
|
+
const { reading, telemetry } = windnerdLiveReading(init.digest, config);
|
|
120
|
+
const station = {
|
|
121
|
+
...windnerdStationMeta(config),
|
|
122
|
+
recommendedPollSeconds: 15,
|
|
123
|
+
status: "ok",
|
|
124
|
+
reading,
|
|
125
|
+
history: null,
|
|
126
|
+
telemetry,
|
|
127
|
+
samples: windnerdLiveSamples(init.samples)
|
|
128
|
+
};
|
|
129
|
+
return {
|
|
130
|
+
type: "init",
|
|
131
|
+
schemaVersion: 2,
|
|
132
|
+
servedAt: environment.now().toISOString(),
|
|
133
|
+
station
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (upstream.signal.aborted && options.signal?.aborted !== true && !(error instanceof UpstreamError)) throw new UpstreamError(`${subject} timed out`, "timeout");
|
|
138
|
+
throw error;
|
|
139
|
+
} finally {
|
|
140
|
+
clearTimeout(timer);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function mapLiveEvent(event, config, environment) {
|
|
144
|
+
if (event.event === "ping") return {
|
|
145
|
+
type: "ping",
|
|
146
|
+
servedAt: environment.now().toISOString()
|
|
147
|
+
};
|
|
148
|
+
if (event.event !== "message") return null;
|
|
149
|
+
let frame;
|
|
150
|
+
try {
|
|
151
|
+
frame = JSON.parse(event.data);
|
|
152
|
+
} catch {
|
|
153
|
+
throw new Error(`WindNerd location ${config.locationId} sent an unparseable live frame`);
|
|
154
|
+
}
|
|
155
|
+
if (!isRecord(frame)) throw new Error(`WindNerd location ${config.locationId} sent an invalid live frame`);
|
|
156
|
+
switch (frame.type) {
|
|
157
|
+
case "WIND_SAMPLES": return {
|
|
158
|
+
type: "samples",
|
|
159
|
+
stationId: config.id,
|
|
160
|
+
samples: windnerdLiveSamples(parseWindnerdLiveSampleRecords(frame.samples, config.locationId))
|
|
161
|
+
};
|
|
162
|
+
case "LAST_DIGEST": {
|
|
163
|
+
const { reading, telemetry } = windnerdLiveReading(parseWindnerdLiveDigest(frame, config.locationId), config);
|
|
164
|
+
return {
|
|
165
|
+
type: "reading",
|
|
166
|
+
stationId: config.id,
|
|
167
|
+
servedAt: environment.now().toISOString(),
|
|
168
|
+
reading,
|
|
169
|
+
telemetry
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
default: return null;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function isRecord(value) {
|
|
176
|
+
return typeof value === "object" && value !== null;
|
|
177
|
+
}
|
|
178
|
+
//#endregion
|
|
179
|
+
export { openWindnerdLive };
|
|
@@ -1,19 +1,21 @@
|
|
|
1
|
-
import { HistoryPoint } from "../../contract.js";
|
|
1
|
+
import { HistoryPoint, LiveSamples, Reading, StationTelemetry } from "../../contract.js";
|
|
2
2
|
import { WindnerdStationConfig } from "../config.js";
|
|
3
3
|
import { StationAdapter, StationAdapterOptions } from "../adapter.js";
|
|
4
4
|
//#region src/server/adapters/windnerd.d.ts
|
|
5
5
|
declare const WINDNERD_RECORD_PERIODS_MINUTES: readonly [1, 15, 60, 180];
|
|
6
6
|
type WindnerdRecordPeriodMinutes = (typeof WINDNERD_RECORD_PERIODS_MINUTES)[number];
|
|
7
|
+
declare const WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS = 3;
|
|
7
8
|
type WindnerdAdapterOptions = StationAdapterOptions & {
|
|
8
9
|
recordsUrl?: string;
|
|
10
|
+
liveUrl?: string;
|
|
9
11
|
recordPeriodMinutes?: WindnerdRecordPeriodMinutes;
|
|
10
12
|
cacheTtlSeconds?: number;
|
|
11
13
|
};
|
|
12
14
|
type WindnerdRecords = {
|
|
13
|
-
|
|
15
|
+
averageSpeedMps: number[];
|
|
14
16
|
windDirectionDeg: number[];
|
|
15
|
-
|
|
16
|
-
|
|
17
|
+
gustSpeedMps: number[];
|
|
18
|
+
lullSpeedMps: number[];
|
|
17
19
|
observedAt: string[];
|
|
18
20
|
temperatureC: Array<number | null>;
|
|
19
21
|
stationPressureHpa: Array<number | null>;
|
|
@@ -24,6 +26,7 @@ declare const loadWindnerdStation: StationAdapter<{
|
|
|
24
26
|
locationId: number;
|
|
25
27
|
hasTemperature: boolean;
|
|
26
28
|
hasPressure: boolean;
|
|
29
|
+
hasBattery: boolean;
|
|
27
30
|
id: string;
|
|
28
31
|
name: string;
|
|
29
32
|
vendor: "windnerd";
|
|
@@ -34,6 +37,34 @@ declare const loadWindnerdStation: StationAdapter<{
|
|
|
34
37
|
longitude?: number | null | undefined;
|
|
35
38
|
}, WindnerdAdapterOptions>;
|
|
36
39
|
declare function windnerdHistoryPoints(records: WindnerdRecords, config: Pick<WindnerdStationConfig, "hasTemperature" | "hasPressure" | "elevationM">): HistoryPoint[];
|
|
40
|
+
type WindnerdLiveDigest = {
|
|
41
|
+
observedAt: string;
|
|
42
|
+
windAvgMps: number;
|
|
43
|
+
gustMps: number | null;
|
|
44
|
+
lullMps: number | null;
|
|
45
|
+
windDirectionDeg: number;
|
|
46
|
+
temperatureC: number | null;
|
|
47
|
+
stationPressureHpa: number | null;
|
|
48
|
+
batteryVoltage: number | null;
|
|
49
|
+
};
|
|
50
|
+
type WindnerdLiveSampleRecord = {
|
|
51
|
+
observedAt: string;
|
|
52
|
+
speedMps: number;
|
|
53
|
+
directionDeg: number;
|
|
54
|
+
};
|
|
55
|
+
type WindnerdLiveInit = {
|
|
56
|
+
digest: WindnerdLiveDigest;
|
|
57
|
+
samples: WindnerdLiveSampleRecord[];
|
|
58
|
+
};
|
|
59
|
+
declare function windnerdLiveStreamUrl(config: Pick<WindnerdStationConfig, "stationKey">, base?: string): URL;
|
|
60
|
+
declare function parseWindnerdLiveInit(value: string, locationId: number): WindnerdLiveInit;
|
|
61
|
+
declare function parseWindnerdLiveDigest(value: unknown, locationId: number): WindnerdLiveDigest;
|
|
62
|
+
declare function parseWindnerdLiveSampleRecords(value: unknown, locationId: number): WindnerdLiveSampleRecord[];
|
|
63
|
+
declare function windnerdLiveReading(digest: WindnerdLiveDigest, config: Pick<WindnerdStationConfig, "hasTemperature" | "hasPressure" | "hasBattery" | "elevationM">): {
|
|
64
|
+
reading: Reading;
|
|
65
|
+
telemetry: StationTelemetry | null;
|
|
66
|
+
};
|
|
67
|
+
declare function windnerdLiveSamples(records: WindnerdLiveSampleRecord[]): LiveSamples;
|
|
37
68
|
declare function parseWindnerdRecords(value: string, locationId: number, hasPressure?: boolean): WindnerdRecords;
|
|
38
69
|
//#endregion
|
|
39
|
-
export { WINDNERD_RECORD_PERIODS_MINUTES, WindnerdAdapterOptions, WindnerdRecordPeriodMinutes, WindnerdRecords, loadWindnerdStation, parseWindnerdRecords, windnerdHistoryPoints };
|
|
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 };
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { emptyConditions } from "../../contract.js";
|
|
2
2
|
import { isCalm, normalizeDegrees, pressureTendency, seaLevelPressureHpa } from "../../derive.js";
|
|
3
3
|
import { windnerdStationUrl } from "../../windnerd.js";
|
|
4
|
-
import {
|
|
4
|
+
import { sseEvents } from "../../sse.js";
|
|
5
|
+
import { coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure } from "../environment.js";
|
|
5
6
|
import { defineStationAdapter } from "../adapter.js";
|
|
6
|
-
import {
|
|
7
|
+
import { UpstreamError } from "@azohra/meteo.core";
|
|
7
8
|
//#region src/server/adapters/windnerd.ts
|
|
8
9
|
const WINDNERD_RECORDS_URL = "https://windnerd.net/api/records";
|
|
10
|
+
const WINDNERD_LIVE_URL = "https://windnerd.net/api/live-url";
|
|
9
11
|
const RECORD_PERIOD_MINUTES = 1;
|
|
10
12
|
const WINDNERD_RECORD_PERIODS_MINUTES = [
|
|
11
13
|
1,
|
|
@@ -15,13 +17,19 @@ const WINDNERD_RECORD_PERIODS_MINUTES = [
|
|
|
15
17
|
];
|
|
16
18
|
const CACHE_TTL_SECONDS = 60;
|
|
17
19
|
const AGGREGATE_CACHE_TTL_SECONDS = 900;
|
|
20
|
+
const LIVE_CACHE_TTL_SECONDS = 15;
|
|
21
|
+
const WINDNERD_LIVE_INIT_TIMEOUT_MS = 8e3;
|
|
22
|
+
const WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS = 3;
|
|
18
23
|
const SENSOR_VALUE_LOOKBACK_MS = 15 * 6e4;
|
|
24
|
+
const MAX_WIND_MPS = 140;
|
|
19
25
|
const STATION_PRESSURE_MIN_HPA = 300;
|
|
20
26
|
const STATION_PRESSURE_MAX_HPA = 1100;
|
|
27
|
+
const BATTERY_VOLTAGE_MIN = 0;
|
|
28
|
+
const BATTERY_VOLTAGE_MAX = 100;
|
|
21
29
|
const UTC_OFFSET_MIN_MINUTES = -720;
|
|
22
30
|
const UTC_OFFSET_MAX_MINUTES = 840;
|
|
23
|
-
|
|
24
|
-
|
|
31
|
+
function windnerdStationMeta(config) {
|
|
32
|
+
return {
|
|
25
33
|
id: config.id,
|
|
26
34
|
name: config.name,
|
|
27
35
|
sourceLabel: "WindNerd",
|
|
@@ -34,12 +42,22 @@ const loadWindnerdStation = defineStationAdapter({
|
|
|
34
42
|
gustLull: true,
|
|
35
43
|
temperature: config.hasTemperature,
|
|
36
44
|
conditions: config.hasPressure,
|
|
37
|
-
history: true
|
|
45
|
+
history: true,
|
|
46
|
+
live: true,
|
|
47
|
+
battery: config.hasBattery
|
|
38
48
|
},
|
|
39
49
|
samplingWindowSeconds: 60,
|
|
40
50
|
recommendedPollSeconds: 60
|
|
41
|
-
}
|
|
42
|
-
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
const loadWindnerdStation = defineStationAdapter({
|
|
54
|
+
meta: windnerdStationMeta,
|
|
55
|
+
load: async (config, { environment, historyHours, mode, options }) => {
|
|
56
|
+
if (mode === "current") try {
|
|
57
|
+
return await loadWindnerdLiveCurrent(config, environment, options);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
logUpstreamFailure(environment, `${config.name} live current unavailable, serving records`, error, { station: config.id });
|
|
60
|
+
}
|
|
43
61
|
const periodMinutes = options.recordPeriodMinutes ?? RECORD_PERIOD_MINUTES;
|
|
44
62
|
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}`);
|
|
45
63
|
const now = environment.now();
|
|
@@ -79,13 +97,13 @@ const loadWindnerdStation = defineStationAdapter({
|
|
|
79
97
|
function windnerdHistoryPoints(records, config) {
|
|
80
98
|
const barometerElevationM = config.hasPressure ? config.elevationM ?? null : null;
|
|
81
99
|
return records.observedAt.map((observedAt, index) => {
|
|
82
|
-
const windAvgMps =
|
|
100
|
+
const windAvgMps = records.averageSpeedMps[index];
|
|
83
101
|
const stationPressure = records.stationPressureHpa[index] ?? null;
|
|
84
102
|
return {
|
|
85
103
|
observedAt,
|
|
86
104
|
windAvgMps,
|
|
87
|
-
windGustMps:
|
|
88
|
-
windLullMps:
|
|
105
|
+
windGustMps: records.gustSpeedMps[index],
|
|
106
|
+
windLullMps: records.lullSpeedMps[index],
|
|
89
107
|
windDirectionDeg: isCalm(windAvgMps) ? null : normalizeDegrees(records.windDirectionDeg[index]),
|
|
90
108
|
temperatureC: config.hasTemperature ? records.temperatureC[index] ?? null : null,
|
|
91
109
|
seaLevelPressureHpa: barometerElevationM != null && stationPressure != null ? seaLevelPressureHpa(stationPressure, barometerElevationM, records.temperatureC[index] ?? null) : null
|
|
@@ -100,6 +118,150 @@ function windnerdConditions(records, points, config, readingObservedAtMs) {
|
|
|
100
118
|
seaLevelPressureHpa: reduced
|
|
101
119
|
});
|
|
102
120
|
}
|
|
121
|
+
function windnerdLiveStreamUrl(config, base = WINDNERD_LIVE_URL) {
|
|
122
|
+
const trimmed = base.endsWith("/") ? base.slice(0, -1) : base;
|
|
123
|
+
return new URL(`${trimmed}/${encodeURIComponent(config.stationKey)}`);
|
|
124
|
+
}
|
|
125
|
+
function parseWindnerdLiveInit(value, locationId) {
|
|
126
|
+
let data;
|
|
127
|
+
try {
|
|
128
|
+
data = JSON.parse(value);
|
|
129
|
+
} catch {
|
|
130
|
+
throw new Error(`WindNerd location ${locationId} returned an unparseable live frame`);
|
|
131
|
+
}
|
|
132
|
+
if (!isRecord(data) || data.type !== "INIT") throw new Error(`WindNerd location ${locationId} returned no live init frame`);
|
|
133
|
+
return {
|
|
134
|
+
digest: parseWindnerdLiveDigest(data.digest, locationId),
|
|
135
|
+
samples: parseWindnerdLiveSampleRecords(data.samples, locationId)
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function parseWindnerdLiveDigest(value, locationId) {
|
|
139
|
+
const fail = (name) => {
|
|
140
|
+
throw new Error(`WindNerd location ${locationId} returned an invalid live ${name}`);
|
|
141
|
+
};
|
|
142
|
+
if (!isRecord(value) || !isRecord(value.recent)) fail("digest");
|
|
143
|
+
const digest = value;
|
|
144
|
+
const recent = digest.recent;
|
|
145
|
+
const rangeOrNull = (entry, minimum, maximum, name) => {
|
|
146
|
+
if (entry == null) return null;
|
|
147
|
+
if (typeof entry !== "number" || !Number.isFinite(entry) || entry < minimum || entry > maximum) fail(name);
|
|
148
|
+
return entry;
|
|
149
|
+
};
|
|
150
|
+
if (typeof recent.date_utc !== "string") fail("digest time");
|
|
151
|
+
const observedAt = recordTimeToIso(recent.date_utc, locationId);
|
|
152
|
+
const minutes = Array.isArray(digest.last_10mn_by_1mn) ? digest.last_10mn_by_1mn : [];
|
|
153
|
+
const lastMinute = minutes.length > 0 ? minutes[minutes.length - 1] : null;
|
|
154
|
+
const wind = isRecord(lastMinute) ? lastMinute : recent;
|
|
155
|
+
const windAvgMps = rangeOrNull(wind.wind_avg_1D, 0, MAX_WIND_MPS, "wind_avg_1D") ?? rangeOrNull(wind.wind_avg_2D, 0, MAX_WIND_MPS, "wind_avg_2D") ?? fail("wind average");
|
|
156
|
+
const windDirectionDeg = rangeOrNull(wind.wind_dir, 0, 360, "wind_dir") ?? fail("wind_dir");
|
|
157
|
+
return {
|
|
158
|
+
observedAt,
|
|
159
|
+
windAvgMps,
|
|
160
|
+
gustMps: rangeOrNull(wind.wind_max, 0, MAX_WIND_MPS, "wind_max"),
|
|
161
|
+
lullMps: rangeOrNull(wind.wind_min, 0, MAX_WIND_MPS, "wind_min"),
|
|
162
|
+
windDirectionDeg,
|
|
163
|
+
temperatureC: rangeOrNull(recent.temperature, -Infinity, Infinity, "temperature"),
|
|
164
|
+
stationPressureHpa: rangeOrNull(recent.pressure_hpa, STATION_PRESSURE_MIN_HPA, STATION_PRESSURE_MAX_HPA, "pressure_hpa"),
|
|
165
|
+
batteryVoltage: rangeOrNull(recent.voltage, BATTERY_VOLTAGE_MIN, BATTERY_VOLTAGE_MAX, "voltage")
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function parseWindnerdLiveSampleRecords(value, locationId) {
|
|
169
|
+
const fail = (name) => {
|
|
170
|
+
throw new Error(`WindNerd location ${locationId} returned an invalid live ${name}`);
|
|
171
|
+
};
|
|
172
|
+
if (!Array.isArray(value)) fail("samples");
|
|
173
|
+
return value.filter((entry) => entry != null).map((entry) => {
|
|
174
|
+
if (!isRecord(entry) || typeof entry.ts !== "string") fail("sample");
|
|
175
|
+
const record = entry;
|
|
176
|
+
const speedMps = record.sp;
|
|
177
|
+
const directionDeg = record.dir;
|
|
178
|
+
if (typeof speedMps !== "number" || !Number.isFinite(speedMps) || speedMps < 0 || speedMps > MAX_WIND_MPS) fail("sample sp");
|
|
179
|
+
if (typeof directionDeg !== "number" || !Number.isFinite(directionDeg) || directionDeg < 0 || directionDeg > 360) fail("sample dir");
|
|
180
|
+
return {
|
|
181
|
+
observedAt: recordTimeToIso(record.ts, locationId),
|
|
182
|
+
speedMps,
|
|
183
|
+
directionDeg
|
|
184
|
+
};
|
|
185
|
+
}).sort((a, b) => Date.parse(a.observedAt) - Date.parse(b.observedAt));
|
|
186
|
+
}
|
|
187
|
+
function windnerdLiveReading(digest, config) {
|
|
188
|
+
const windAvgMps = digest.windAvgMps;
|
|
189
|
+
return {
|
|
190
|
+
reading: {
|
|
191
|
+
observedAt: digest.observedAt,
|
|
192
|
+
windAvgMps,
|
|
193
|
+
windDirectionDeg: isCalm(windAvgMps) ? null : normalizeDegrees(digest.windDirectionDeg),
|
|
194
|
+
windGustMps: digest.gustMps,
|
|
195
|
+
windLullMps: digest.lullMps,
|
|
196
|
+
temperatureC: config.hasTemperature ? digest.temperatureC : null,
|
|
197
|
+
windChillC: null,
|
|
198
|
+
conditions: config.hasPressure ? emptyConditions({ seaLevelPressureHpa: digest.stationPressureHpa != null && config.elevationM != null ? seaLevelPressureHpa(digest.stationPressureHpa, config.elevationM, digest.temperatureC) : null }) : null
|
|
199
|
+
},
|
|
200
|
+
telemetry: config.hasBattery ? { batteryVoltage: digest.batteryVoltage } : null
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
function windnerdLiveSamples(records) {
|
|
204
|
+
return {
|
|
205
|
+
intervalSeconds: 3,
|
|
206
|
+
points: records.map((record) => {
|
|
207
|
+
const windMps = record.speedMps;
|
|
208
|
+
return {
|
|
209
|
+
observedAt: record.observedAt,
|
|
210
|
+
windMps,
|
|
211
|
+
windDirectionDeg: isCalm(windMps) ? null : normalizeDegrees(record.directionDeg)
|
|
212
|
+
};
|
|
213
|
+
})
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
async function loadWindnerdLiveCurrent(config, environment, options) {
|
|
217
|
+
const init = parseWindnerdLiveInit(await fetchWindnerdLiveInitText(config, environment, options), config.locationId);
|
|
218
|
+
const { reading, telemetry } = windnerdLiveReading(init.digest, config);
|
|
219
|
+
return {
|
|
220
|
+
reading,
|
|
221
|
+
history: null,
|
|
222
|
+
telemetry,
|
|
223
|
+
samples: windnerdLiveSamples(init.samples),
|
|
224
|
+
meta: { recommendedPollSeconds: 15 }
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
async function fetchWindnerdLiveInitText(config, environment, options) {
|
|
228
|
+
const cacheKey = `windnerd/live/${config.locationId}`;
|
|
229
|
+
const cached = await environment.cache.get(cacheKey);
|
|
230
|
+
if (cached != null) return cached;
|
|
231
|
+
return coalesceUpstreamLoad(environment.cache, cacheKey, async () => {
|
|
232
|
+
const subject = `WindNerd location ${config.locationId} live stream`;
|
|
233
|
+
const controller = new AbortController();
|
|
234
|
+
const timer = setTimeout(() => controller.abort(), WINDNERD_LIVE_INIT_TIMEOUT_MS);
|
|
235
|
+
try {
|
|
236
|
+
const body = (await fetchUpstreamStream(environment, {
|
|
237
|
+
url: windnerdLiveStreamUrl(config, options.liveUrl),
|
|
238
|
+
subject,
|
|
239
|
+
signal: controller.signal
|
|
240
|
+
})).body;
|
|
241
|
+
for await (const event of sseEvents(body, { signal: controller.signal })) {
|
|
242
|
+
if (event.event !== "message") continue;
|
|
243
|
+
let type;
|
|
244
|
+
try {
|
|
245
|
+
const frame = JSON.parse(event.data);
|
|
246
|
+
type = isRecord(frame) ? frame.type : void 0;
|
|
247
|
+
} catch {
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
if (type === "INIT") {
|
|
251
|
+
await environment.cache.put(cacheKey, event.data, LIVE_CACHE_TTL_SECONDS);
|
|
252
|
+
return event.data;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
throw new UpstreamError(`${subject} ended before its init frame`);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
if (controller.signal.aborted && !(error instanceof UpstreamError)) throw new UpstreamError(`${subject} timed out`, "timeout");
|
|
258
|
+
throw error;
|
|
259
|
+
} finally {
|
|
260
|
+
clearTimeout(timer);
|
|
261
|
+
controller.abort();
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
}
|
|
103
265
|
function parseWindnerdRecords(value, locationId, hasPressure = false) {
|
|
104
266
|
const data = JSON.parse(value);
|
|
105
267
|
if (!isRecord(data) || !isRecord(data.records)) throw new Error(`WindNerd location ${locationId} returned no records`);
|
|
@@ -109,12 +271,12 @@ function parseWindnerdRecords(value, locationId, hasPressure = false) {
|
|
|
109
271
|
const fail = (name) => {
|
|
110
272
|
throw new Error(`WindNerd location ${locationId} returned an invalid ${name}`);
|
|
111
273
|
};
|
|
112
|
-
const speeds = (name) => numberSeries(records[name], dates.length, 0,
|
|
274
|
+
const speeds = (name) => numberSeries(records[name], dates.length, 0, MAX_WIND_MPS, name, fail);
|
|
113
275
|
return {
|
|
114
|
-
|
|
276
|
+
averageSpeedMps: speeds("wind_avg_1D"),
|
|
115
277
|
windDirectionDeg: numberSeries(records.wind_dir, dates.length, 0, 360, "wind_dir", fail),
|
|
116
|
-
|
|
117
|
-
|
|
278
|
+
gustSpeedMps: speeds("wind_max"),
|
|
279
|
+
lullSpeedMps: speeds("wind_min"),
|
|
118
280
|
observedAt: dates.map((date) => recordTimeToIso(date, locationId)),
|
|
119
281
|
temperatureC: nullableSeries(records.temperature_avg, dates.length, "temperature_avg", fail),
|
|
120
282
|
stationPressureHpa: hasPressure ? nullableSeries(records.pressure_hpa_avg, dates.length, "pressure_hpa_avg", fail, STATION_PRESSURE_MIN_HPA, STATION_PRESSURE_MAX_HPA) : dates.map(() => null),
|
|
@@ -156,4 +318,4 @@ function isRecord(value) {
|
|
|
156
318
|
return typeof value === "object" && value !== null;
|
|
157
319
|
}
|
|
158
320
|
//#endregion
|
|
159
|
-
export { WINDNERD_RECORD_PERIODS_MINUTES, loadWindnerdStation, parseWindnerdRecords, windnerdHistoryPoints };
|
|
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 };
|
package/dist/server/config.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ declare const windnerdStationConfigSchema: z.ZodObject<{
|
|
|
8
8
|
locationId: z.ZodNumber;
|
|
9
9
|
hasTemperature: z.ZodDefault<z.ZodBoolean>;
|
|
10
10
|
hasPressure: z.ZodDefault<z.ZodBoolean>;
|
|
11
|
+
hasBattery: z.ZodDefault<z.ZodBoolean>;
|
|
11
12
|
timeZone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
12
13
|
pageUrl: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
13
14
|
elevationM: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
@@ -82,6 +83,7 @@ declare const stationConfigSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
82
83
|
locationId: z.ZodNumber;
|
|
83
84
|
hasTemperature: z.ZodDefault<z.ZodBoolean>;
|
|
84
85
|
hasPressure: z.ZodDefault<z.ZodBoolean>;
|
|
86
|
+
hasBattery: z.ZodDefault<z.ZodBoolean>;
|
|
85
87
|
timeZone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
86
88
|
pageUrl: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
87
89
|
elevationM: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
package/dist/server/config.js
CHANGED
|
@@ -16,7 +16,8 @@ const windnerdStationConfigSchema = z.strictObject({
|
|
|
16
16
|
stationKey: windnerdStationKey,
|
|
17
17
|
locationId: z.number().int().positive(),
|
|
18
18
|
hasTemperature: z.boolean().default(true),
|
|
19
|
-
hasPressure: z.boolean().default(false)
|
|
19
|
+
hasPressure: z.boolean().default(false),
|
|
20
|
+
hasBattery: z.boolean().default(false)
|
|
20
21
|
}).refine((config) => !config.hasPressure || config.elevationM != null, {
|
|
21
22
|
message: "pressure needs the sensor's elevation to reduce to sea level — set elevationM to the sensor's elevation, not the launch's",
|
|
22
23
|
path: ["elevationM"]
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { UPSTREAM_FAILURE_REASONS as UPSTREAM_FAILURE_REASONS$1, UpstreamError, UpstreamErrorReason, UpstreamFailureReason, unavailableReasonForError } from "@azohra/meteo.core";
|
|
1
|
+
import { UPSTREAM_FAILURE_REASONS as UPSTREAM_FAILURE_REASONS$1, UpstreamError as UpstreamError$1, UpstreamErrorReason, UpstreamFailureReason, unavailableReasonForError } from "@azohra/meteo.core";
|
|
2
2
|
//#region src/server/environment.d.ts
|
|
3
3
|
type FeedCache = {
|
|
4
4
|
get(key: string): Promise<string | null>;
|
|
@@ -37,12 +37,32 @@ type UpstreamTextRequest = {
|
|
|
37
37
|
limitBytes?: number;
|
|
38
38
|
};
|
|
39
39
|
/**
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
|
|
40
|
+
* Coalesces concurrent misses on the same (cache instance, key) onto a single
|
|
41
|
+
* in-flight load. The load owns its own cache fill; this only deduplicates.
|
|
42
|
+
*/
|
|
43
|
+
declare function coalesceUpstreamLoad(cache: FeedCache, key: string, load: () => Promise<string>): Promise<string>;
|
|
44
|
+
/**
|
|
45
|
+
* The one road to an upstream document: cache lookup, bounded fetch under a
|
|
46
|
+
* timeout, cache fill. Concurrent misses on the same (cache instance,
|
|
47
|
+
* cacheKey) coalesce onto a single in-flight load.
|
|
43
48
|
*/
|
|
44
49
|
declare function fetchUpstreamText(environment: ResolvedEnvironment, request: UpstreamTextRequest): Promise<string>;
|
|
50
|
+
type UpstreamStreamRequest = {
|
|
51
|
+
url: string | URL;
|
|
52
|
+
subject: string;
|
|
53
|
+
accept?: string;
|
|
54
|
+
headers?: Record<string, string>;
|
|
55
|
+
connectTimeoutMs?: number;
|
|
56
|
+
signal?: AbortSignal;
|
|
57
|
+
};
|
|
58
|
+
declare const UPSTREAM_CONNECT_TIMEOUT_MS = 10000;
|
|
59
|
+
/**
|
|
60
|
+
* The road to a long-lived upstream body. No cache and no byte cap — the
|
|
61
|
+
* consumer bounds its own buffering — and never coalesced: every caller owns
|
|
62
|
+
* its connection and tears it down through its signal.
|
|
63
|
+
*/
|
|
64
|
+
declare function fetchUpstreamStream(environment: ResolvedEnvironment, request: UpstreamStreamRequest): Promise<Response>;
|
|
45
65
|
declare function boundedResponseText(response: Response, limitBytes: number, subject: string): Promise<string>;
|
|
46
66
|
declare function logUpstreamFailure(environment: ResolvedEnvironment, message: string, error: unknown, detail?: Record<string, unknown>): void;
|
|
47
67
|
//#endregion
|
|
48
|
-
export { DEFAULT_USER_AGENT, FeedCache, LogEvent, LogEventCode, ResolvedEnvironment, ServerEnvironment, UPSTREAM_FAILURE_REASONS$1 as UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError, type UpstreamErrorReason, type UpstreamFailureReason, UpstreamTextRequest, boundedResponseText, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError };
|
|
68
|
+
export { DEFAULT_USER_AGENT, FeedCache, LogEvent, LogEventCode, ResolvedEnvironment, ServerEnvironment, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS$1 as UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError$1 as UpstreamError, type UpstreamErrorReason, type UpstreamFailureReason, UpstreamStreamRequest, UpstreamTextRequest, boundedResponseText, coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError };
|