@azohra/meteo.station 0.1.1
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/LICENSE +21 -0
- package/README.md +53 -0
- package/dist/air.d.ts +13 -0
- package/dist/air.js +76 -0
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +4 -0
- package/dist/client/poll.d.ts +42 -0
- package/dist/client/poll.js +121 -0
- package/dist/client/stores.d.ts +46 -0
- package/dist/client/stores.js +128 -0
- package/dist/client/ticker.d.ts +4 -0
- package/dist/client/ticker.js +19 -0
- package/dist/contract.d.ts +381 -0
- package/dist/contract.js +143 -0
- package/dist/derive.d.ts +54 -0
- package/dist/derive.js +134 -0
- package/dist/display.d.ts +28 -0
- package/dist/display.js +27 -0
- package/dist/elements/elements/AirMatrixElement.d.ts +14 -0
- package/dist/elements/elements/AirMatrixElement.js +83 -0
- package/dist/elements/elements/CurrentConditionsElement.d.ts +9 -0
- package/dist/elements/elements/CurrentConditionsElement.js +52 -0
- package/dist/elements/elements/DailyPatternElement.d.ts +15 -0
- package/dist/elements/elements/DailyPatternElement.js +200 -0
- package/dist/elements/elements/DialElement.d.ts +9 -0
- package/dist/elements/elements/DialElement.js +128 -0
- package/dist/elements/elements/FreshnessBadgeElement.d.ts +8 -0
- package/dist/elements/elements/FreshnessBadgeElement.js +22 -0
- package/dist/elements/elements/SparklineElement.d.ts +9 -0
- package/dist/elements/elements/SparklineElement.js +74 -0
- package/dist/elements/elements/StationCardElement.d.ts +53 -0
- package/dist/elements/elements/StationCardElement.js +211 -0
- package/dist/elements/elements/StationFeedElement.d.ts +32 -0
- package/dist/elements/elements/StationFeedElement.js +215 -0
- package/dist/elements/elements/StationStripElement.d.ts +9 -0
- package/dist/elements/elements/StationStripElement.js +43 -0
- package/dist/elements/elements/StationTableElement.d.ts +18 -0
- package/dist/elements/elements/StationTableElement.js +102 -0
- package/dist/elements/elements/TrendChartElement.d.ts +10 -0
- package/dist/elements/elements/TrendChartElement.js +174 -0
- package/dist/elements/elements/WindArrowElement.d.ts +8 -0
- package/dist/elements/elements/WindArrowElement.js +14 -0
- package/dist/elements/elements/WindHistoryChartElement.d.ts +10 -0
- package/dist/elements/elements/WindHistoryChartElement.js +277 -0
- package/dist/elements/elements/WindRoseElement.d.ts +17 -0
- package/dist/elements/elements/WindRoseElement.js +106 -0
- package/dist/elements/elements/atoms.d.ts +48 -0
- package/dist/elements/elements/atoms.js +131 -0
- package/dist/elements/index.d.ts +48 -0
- package/dist/elements/index.js +57 -0
- package/dist/elements/lib/ambient.d.ts +15 -0
- package/dist/elements/lib/ambient.js +5 -0
- package/dist/elements/lib/attributes.js +21 -0
- package/dist/elements/lib/base.d.ts +45 -0
- package/dist/elements/lib/base.js +152 -0
- package/dist/elements/lib/context.js +28 -0
- package/dist/elements/lib/fragments.js +45 -0
- package/dist/elements/lib/h.js +35 -0
- package/dist/elements/register.d.ts +1 -0
- package/dist/elements/register.js +5 -0
- package/dist/endpoints.d.ts +5 -0
- package/dist/endpoints.js +10 -0
- package/dist/fixtures.d.ts +23 -0
- package/dist/fixtures.js +67 -0
- package/dist/format.d.ts +31 -0
- package/dist/format.js +82 -0
- package/dist/geometry.d.ts +84 -0
- package/dist/geometry.js +333 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +12 -0
- package/dist/instruments.d.ts +75 -0
- package/dist/instruments.js +173 -0
- package/dist/merge-current.d.ts +13 -0
- package/dist/merge-current.js +54 -0
- package/dist/react/components/AirMatrix.d.ts +11 -0
- package/dist/react/components/AirMatrix.js +82 -0
- package/dist/react/components/CurrentConditions.d.ts +17 -0
- package/dist/react/components/CurrentConditions.js +98 -0
- package/dist/react/components/DailyPattern.d.ts +19 -0
- package/dist/react/components/DailyPattern.js +212 -0
- package/dist/react/components/Dial.d.ts +17 -0
- package/dist/react/components/Dial.js +133 -0
- package/dist/react/components/FreshnessBadge.d.ts +10 -0
- package/dist/react/components/FreshnessBadge.js +20 -0
- package/dist/react/components/Sparkline.d.ts +17 -0
- package/dist/react/components/Sparkline.js +60 -0
- package/dist/react/components/StationCard.d.ts +46 -0
- package/dist/react/components/StationCard.js +140 -0
- package/dist/react/components/StationFeedProvider.d.ts +27 -0
- package/dist/react/components/StationFeedProvider.js +40 -0
- package/dist/react/components/StationStrip.d.ts +16 -0
- package/dist/react/components/StationStrip.js +84 -0
- package/dist/react/components/StationTable.d.ts +18 -0
- package/dist/react/components/StationTable.js +115 -0
- package/dist/react/components/TrendChart.d.ts +14 -0
- package/dist/react/components/TrendChart.js +150 -0
- package/dist/react/components/WindArrow.d.ts +7 -0
- package/dist/react/components/WindArrow.js +21 -0
- package/dist/react/components/WindHistoryChart.d.ts +18 -0
- package/dist/react/components/WindHistoryChart.js +278 -0
- package/dist/react/components/WindRose.d.ts +17 -0
- package/dist/react/components/WindRose.js +99 -0
- package/dist/react/components/atoms.d.ts +33 -0
- package/dist/react/components/atoms.js +136 -0
- package/dist/react/hooks/useFreshness.d.ts +6 -0
- package/dist/react/hooks/useFreshness.js +21 -0
- package/dist/react/hooks/usePolledJson.js +17 -0
- package/dist/react/hooks/useStation.d.ts +23 -0
- package/dist/react/hooks/useStation.js +42 -0
- package/dist/react/hooks/useStationCurrent.d.ts +23 -0
- package/dist/react/hooks/useStationCurrent.js +32 -0
- package/dist/react/hooks/useStationFeed.d.ts +22 -0
- package/dist/react/hooks/useStationFeed.js +28 -0
- package/dist/react/index.d.ts +20 -0
- package/dist/react/index.js +21 -0
- package/dist/react/lib/cells.js +29 -0
- package/dist/scene/air-matrix.js +71 -0
- package/dist/scene/atoms.js +102 -0
- package/dist/scene/card.js +54 -0
- package/dist/scene/chart.js +28 -0
- package/dist/scene/current.js +66 -0
- package/dist/scene/daily-pattern.js +81 -0
- package/dist/scene/dial.js +141 -0
- package/dist/scene/glyphs.js +24 -0
- package/dist/scene/rose.js +120 -0
- package/dist/scene/sparkline.js +73 -0
- package/dist/scene/strip.js +63 -0
- package/dist/scene/table.js +76 -0
- package/dist/scene/trend.js +160 -0
- package/dist/scene/wind-history.js +148 -0
- package/dist/scene/wind-plot.js +214 -0
- package/dist/server/adapter.d.ts +28 -0
- package/dist/server/adapter.js +32 -0
- package/dist/server/adapters/campbell.d.ts +112 -0
- package/dist/server/adapters/campbell.js +414 -0
- package/dist/server/adapters/tempest.d.ts +27 -0
- package/dist/server/adapters/tempest.js +137 -0
- package/dist/server/adapters/windnerd.d.ts +39 -0
- package/dist/server/adapters/windnerd.js +159 -0
- package/dist/server/config.d.ts +135 -0
- package/dist/server/config.js +57 -0
- package/dist/server/environment.d.ts +48 -0
- package/dist/server/environment.js +128 -0
- package/dist/server/feed.d.ts +31 -0
- package/dist/server/feed.js +216 -0
- package/dist/server/handler.d.ts +17 -0
- package/dist/server/handler.js +133 -0
- package/dist/server/index.d.ts +10 -0
- package/dist/server/index.js +10 -0
- package/dist/strings.d.ts +118 -0
- package/dist/strings.js +237 -0
- package/dist/windnerd.d.ts +5 -0
- package/dist/windnerd.js +25 -0
- package/package.json +97 -0
- package/schema/README.md +14 -0
- package/schema/example-current.json +48 -0
- package/schema/example-feed.json +147 -0
- package/schema/stationcurrent.schema.json +641 -0
- package/schema/stationfeed.schema.json +656 -0
- package/styles.css +1141 -0
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { isCalm, normalizeDegrees } from "../../derive.js";
|
|
2
|
+
import { fetchUpstreamText, logUpstreamFailure } from "../environment.js";
|
|
3
|
+
import { defineStationAdapter } from "../adapter.js";
|
|
4
|
+
import { kmhToMps } from "@azohra/meteo.core";
|
|
5
|
+
//#region src/server/adapters/campbell.ts
|
|
6
|
+
const HISTORY_CACHE_TTL_SECONDS = 120;
|
|
7
|
+
const MAX_RESPONSE_BYTES = 524288;
|
|
8
|
+
const CAMPBELL_FIELD_CONTRACTS = {
|
|
9
|
+
current: [
|
|
10
|
+
{
|
|
11
|
+
name: "Wind_Speed",
|
|
12
|
+
process: "Avg",
|
|
13
|
+
type: "xsd:float",
|
|
14
|
+
units: "kilometers/hour"
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: "Wind_Lull",
|
|
18
|
+
process: "Min",
|
|
19
|
+
type: "xsd:float",
|
|
20
|
+
units: "kilometers/hour"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
name: "Wind_Gust",
|
|
24
|
+
process: "Max",
|
|
25
|
+
type: "xsd:float",
|
|
26
|
+
units: "kilometers/hour"
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
name: "WindDir",
|
|
30
|
+
process: "Smp",
|
|
31
|
+
type: "xsd:float",
|
|
32
|
+
units: "degrees"
|
|
33
|
+
}
|
|
34
|
+
],
|
|
35
|
+
history: [
|
|
36
|
+
{
|
|
37
|
+
name: "Temp",
|
|
38
|
+
process: "Smp",
|
|
39
|
+
type: "xsd:float",
|
|
40
|
+
units: "Deg C"
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
name: "Wind_Chill",
|
|
44
|
+
process: "Smp",
|
|
45
|
+
type: "xsd:float",
|
|
46
|
+
units: "Deg C"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
name: "WindDir",
|
|
50
|
+
process: "Smp",
|
|
51
|
+
type: "xsd:float",
|
|
52
|
+
units: "degrees"
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
name: "WS_kph_Max",
|
|
56
|
+
process: "Max",
|
|
57
|
+
type: "xsd:float",
|
|
58
|
+
units: "kilometers/hour"
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
name: "WS_kph_Avg",
|
|
62
|
+
process: "Avg",
|
|
63
|
+
type: "xsd:float",
|
|
64
|
+
units: "kilometers/hour"
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
name: "WS_kph_Min",
|
|
68
|
+
process: "Min",
|
|
69
|
+
type: "xsd:float",
|
|
70
|
+
units: "kilometers/hour"
|
|
71
|
+
}
|
|
72
|
+
]
|
|
73
|
+
};
|
|
74
|
+
function sourceStationName(source) {
|
|
75
|
+
const colon = source.indexOf(":");
|
|
76
|
+
return colon >= 0 ? source.slice(colon + 1) : source;
|
|
77
|
+
}
|
|
78
|
+
function tableExpectation(config, role) {
|
|
79
|
+
const tableName = role === "current" ? config.currentTable : config.historyTable;
|
|
80
|
+
return {
|
|
81
|
+
role,
|
|
82
|
+
tableName,
|
|
83
|
+
stationName: sourceStationName(config.source),
|
|
84
|
+
intervalMs: role === "current" ? config.currentIntervalSeconds * 1e3 : config.historyPeriodMinutes * 6e4,
|
|
85
|
+
subject: `${config.name} ${tableName}`
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function stationMeta(config) {
|
|
89
|
+
return {
|
|
90
|
+
id: config.id,
|
|
91
|
+
name: config.name,
|
|
92
|
+
sourceLabel: "Campbell logger",
|
|
93
|
+
pageUrl: config.pageUrl ?? null,
|
|
94
|
+
latitude: config.latitude ?? null,
|
|
95
|
+
longitude: config.longitude ?? null,
|
|
96
|
+
timeZone: config.timeZone,
|
|
97
|
+
elevationM: config.elevationM ?? null,
|
|
98
|
+
capabilities: {
|
|
99
|
+
gustLull: true,
|
|
100
|
+
temperature: true,
|
|
101
|
+
conditions: false,
|
|
102
|
+
history: true
|
|
103
|
+
},
|
|
104
|
+
samplingWindowSeconds: config.currentIntervalSeconds,
|
|
105
|
+
recommendedPollSeconds: Math.max(config.currentIntervalSeconds, config.currentCacheTtlSeconds)
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function latestAirCacheKey(config) {
|
|
109
|
+
return `campbell/${config.baseUrl}/${config.source}/${config.historyTable}/latest-air`;
|
|
110
|
+
}
|
|
111
|
+
const loadCampbellStation = defineStationAdapter({
|
|
112
|
+
meta: stationMeta,
|
|
113
|
+
load: async (config, { environment, historyHours, mode }) => {
|
|
114
|
+
if (mode === "current") {
|
|
115
|
+
const currentText = await fetchCurrentTable(config, environment);
|
|
116
|
+
const nowMs = environment.now().getTime();
|
|
117
|
+
const reading = parseCampbellCurrent(currentText, config, nowMs);
|
|
118
|
+
warnOnHourSkew(environment, config, reading.observedAt, nowMs);
|
|
119
|
+
const air = await peekLatestAir(config, environment);
|
|
120
|
+
return {
|
|
121
|
+
reading: {
|
|
122
|
+
...reading,
|
|
123
|
+
temperatureC: air.temperatureC,
|
|
124
|
+
windChillC: air.windChillC
|
|
125
|
+
},
|
|
126
|
+
history: null
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
const [currentSettled, historySettled] = await Promise.allSettled([fetchCurrentTable(config, environment), fetchHistoryTable(config, environment, historyHours)]);
|
|
130
|
+
if (currentSettled.status === "rejected") throw currentSettled.reason;
|
|
131
|
+
const nowMs = environment.now().getTime();
|
|
132
|
+
const current = parseCampbellCurrent(currentSettled.value, config, nowMs);
|
|
133
|
+
warnOnHourSkew(environment, config, current.observedAt, nowMs);
|
|
134
|
+
let air = {
|
|
135
|
+
temperatureC: null,
|
|
136
|
+
windChillC: null
|
|
137
|
+
};
|
|
138
|
+
let history = null;
|
|
139
|
+
try {
|
|
140
|
+
if (historySettled.status === "rejected") throw historySettled.reason;
|
|
141
|
+
const parsed = parseCampbellHistory(historySettled.value, config);
|
|
142
|
+
air = {
|
|
143
|
+
temperatureC: parsed.latestTemperatureC,
|
|
144
|
+
windChillC: parsed.latestWindChillC
|
|
145
|
+
};
|
|
146
|
+
history = {
|
|
147
|
+
periodMinutes: config.historyPeriodMinutes,
|
|
148
|
+
points: parsed.points
|
|
149
|
+
};
|
|
150
|
+
await environment.cache.put(latestAirCacheKey(config), JSON.stringify(air), HISTORY_CACHE_TTL_SECONDS);
|
|
151
|
+
} catch (error) {
|
|
152
|
+
logUpstreamFailure(environment, `${config.name} history unavailable`, error, { station: config.id });
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
reading: {
|
|
156
|
+
...current,
|
|
157
|
+
temperatureC: air.temperatureC,
|
|
158
|
+
windChillC: air.windChillC
|
|
159
|
+
},
|
|
160
|
+
history
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
function loadCampbellCurrent(config, options = {}) {
|
|
165
|
+
return loadCampbellStation(config, {
|
|
166
|
+
...options,
|
|
167
|
+
mode: "current"
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
async function peekLatestAir(config, environment) {
|
|
171
|
+
const cached = await environment.cache.get(latestAirCacheKey(config));
|
|
172
|
+
if (cached == null) return {
|
|
173
|
+
temperatureC: null,
|
|
174
|
+
windChillC: null
|
|
175
|
+
};
|
|
176
|
+
try {
|
|
177
|
+
const parsed = JSON.parse(cached);
|
|
178
|
+
if (!isRecord(parsed)) throw new Error("not a record");
|
|
179
|
+
return {
|
|
180
|
+
temperatureC: finiteOrNull(parsed.temperatureC),
|
|
181
|
+
windChillC: finiteOrNull(parsed.windChillC)
|
|
182
|
+
};
|
|
183
|
+
} catch {
|
|
184
|
+
return {
|
|
185
|
+
temperatureC: null,
|
|
186
|
+
windChillC: null
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
function finiteOrNull(value) {
|
|
191
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
192
|
+
}
|
|
193
|
+
const HOUR_MS = 36e5;
|
|
194
|
+
const HOUR_SKEW_TOLERANCE_MS = 5 * 6e4;
|
|
195
|
+
function warnOnHourSkew(environment, config, observedAtIso, nowMs) {
|
|
196
|
+
const skewMs = Math.abs(Date.parse(observedAtIso) - nowMs);
|
|
197
|
+
if (Math.abs(skewMs - HOUR_MS) > HOUR_SKEW_TOLERANCE_MS) return;
|
|
198
|
+
environment.logger({
|
|
199
|
+
level: "warn",
|
|
200
|
+
code: "clock_skew",
|
|
201
|
+
message: `${config.name} current reading is ${Math.round(skewMs / 6e4)} min from now — the logger clock appears pinned to standard time; configure the fixed-offset zone (Etc/GMT+8 for Pacific) instead of ${config.timeZone}, or vice versa`,
|
|
202
|
+
detail: {
|
|
203
|
+
station: config.id,
|
|
204
|
+
timeZone: config.timeZone,
|
|
205
|
+
skewMs
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
function fetchCurrentTable(config, environment) {
|
|
210
|
+
return fetchCampbellTable(config, environment, {
|
|
211
|
+
table: config.currentTable,
|
|
212
|
+
mode: "most-recent",
|
|
213
|
+
period: 1,
|
|
214
|
+
order: "real-time",
|
|
215
|
+
cacheTtlSeconds: config.currentCacheTtlSeconds
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
function fetchHistoryTable(config, environment, historyHours) {
|
|
219
|
+
return fetchCampbellTable(config, environment, {
|
|
220
|
+
table: config.historyTable,
|
|
221
|
+
mode: "backfill",
|
|
222
|
+
period: historyHours * 3600,
|
|
223
|
+
order: "collected",
|
|
224
|
+
cacheTtlSeconds: HISTORY_CACHE_TTL_SECONDS
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
function fetchCampbellTable(config, environment, query) {
|
|
228
|
+
const url = new URL(config.baseUrl);
|
|
229
|
+
url.searchParams.set("command", "DataQuery");
|
|
230
|
+
url.searchParams.set("uri", `${config.source}.${query.table}`);
|
|
231
|
+
url.searchParams.set("format", "json");
|
|
232
|
+
url.searchParams.set("mode", query.mode);
|
|
233
|
+
url.searchParams.set("p1", String(query.period));
|
|
234
|
+
url.searchParams.set("p2", "");
|
|
235
|
+
url.searchParams.set("headsig", "0");
|
|
236
|
+
url.searchParams.set("nextpoll", "60000");
|
|
237
|
+
url.searchParams.set("order", query.order);
|
|
238
|
+
return fetchUpstreamText(environment, {
|
|
239
|
+
url,
|
|
240
|
+
cacheKey: `campbell/${config.baseUrl}/${config.source}/${query.table}/${query.mode}/${query.period}/${query.order}`,
|
|
241
|
+
cacheTtlSeconds: query.cacheTtlSeconds,
|
|
242
|
+
subject: `${config.name} ${query.table}`,
|
|
243
|
+
limitBytes: MAX_RESPONSE_BYTES
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
function parseCampbellCurrent(value, config, nowMs = Date.now()) {
|
|
247
|
+
const expectation = tableExpectation(config, "current");
|
|
248
|
+
const table = parseCampbellTable(value, expectation);
|
|
249
|
+
const record = lastRecord(table, expectation.subject);
|
|
250
|
+
const windAvgMps = kmhToMps(campbellSpeed(table, record, "Wind_Speed", expectation.subject));
|
|
251
|
+
return {
|
|
252
|
+
observedAt: naiveLocalToIso(record.time, config.timeZone, { nearMs: nowMs }),
|
|
253
|
+
windAvgMps,
|
|
254
|
+
windDirectionDeg: isCalm(windAvgMps) ? null : normalizeDegrees(campbellDirection(table, record, "WindDir", expectation.subject)),
|
|
255
|
+
windGustMps: kmhToMps(campbellSpeed(table, record, "Wind_Gust", expectation.subject)),
|
|
256
|
+
windLullMps: kmhToMps(campbellSpeed(table, record, "Wind_Lull", expectation.subject)),
|
|
257
|
+
temperatureC: null,
|
|
258
|
+
windChillC: null,
|
|
259
|
+
conditions: null
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
function parseCampbellHistory(value, config) {
|
|
263
|
+
const expectation = tableExpectation(config, "history");
|
|
264
|
+
const table = parseCampbellTable(value, expectation);
|
|
265
|
+
const latest = lastRecord(table, expectation.subject);
|
|
266
|
+
let previousMs = null;
|
|
267
|
+
return {
|
|
268
|
+
points: table.records.map((record) => {
|
|
269
|
+
const windAvgMps = kmhToMps(campbellSpeed(table, record, "WS_kph_Avg", expectation.subject));
|
|
270
|
+
const observedAt = naiveLocalToIso(record.time, config.timeZone, { afterMs: previousMs });
|
|
271
|
+
previousMs = Date.parse(observedAt);
|
|
272
|
+
return {
|
|
273
|
+
observedAt,
|
|
274
|
+
windAvgMps,
|
|
275
|
+
windGustMps: kmhToMps(campbellSpeed(table, record, "WS_kph_Max", expectation.subject)),
|
|
276
|
+
windLullMps: kmhToMps(campbellSpeed(table, record, "WS_kph_Min", expectation.subject)),
|
|
277
|
+
windDirectionDeg: isCalm(windAvgMps) ? null : normalizeDegrees(campbellDirection(table, record, "WindDir", expectation.subject)),
|
|
278
|
+
temperatureC: campbellNumber(table, record, "Temp", expectation.subject)
|
|
279
|
+
};
|
|
280
|
+
}),
|
|
281
|
+
latestTemperatureC: campbellNumber(table, latest, "Temp", expectation.subject),
|
|
282
|
+
latestWindChillC: campbellNumber(table, latest, "Wind_Chill", expectation.subject)
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
function parseCampbellTable(value, expectation) {
|
|
286
|
+
const subject = expectation.subject;
|
|
287
|
+
const data = JSON.parse(value);
|
|
288
|
+
if (!isRecord(data) || data.more !== false) throw new Error(`${subject} returned an incomplete response`);
|
|
289
|
+
const head = data.head;
|
|
290
|
+
if (!isRecord(head) || !isRecord(head.environment)) throw new Error(`${subject} returned no table definition`);
|
|
291
|
+
if (head.environment.station_name !== expectation.stationName || head.environment.table_name !== expectation.tableName || head.environment.interval !== expectation.intervalMs) throw new Error(`${subject} returned the wrong table`);
|
|
292
|
+
if (!Array.isArray(head.fields) || !Array.isArray(data.data)) throw new Error(`${subject} returned invalid records`);
|
|
293
|
+
const fields = head.fields.map((field) => {
|
|
294
|
+
if (!isRecord(field) || typeof field.name !== "string" || typeof field.process !== "string" || typeof field.type !== "string" || typeof field.units !== "string") throw new Error(`${subject} returned an invalid field`);
|
|
295
|
+
return {
|
|
296
|
+
name: field.name,
|
|
297
|
+
process: field.process,
|
|
298
|
+
type: field.type,
|
|
299
|
+
units: field.units
|
|
300
|
+
};
|
|
301
|
+
});
|
|
302
|
+
const records = data.data.map((record) => {
|
|
303
|
+
if (!isRecord(record) || typeof record.time !== "string" || !Array.isArray(record.vals)) throw new Error(`${subject} returned an invalid record`);
|
|
304
|
+
if (record.vals.length !== fields.length) throw new Error(`${subject} record does not match its fields`);
|
|
305
|
+
return {
|
|
306
|
+
time: record.time,
|
|
307
|
+
vals: record.vals
|
|
308
|
+
};
|
|
309
|
+
});
|
|
310
|
+
for (const contract of CAMPBELL_FIELD_CONTRACTS[expectation.role]) {
|
|
311
|
+
const field = fields.find(({ name }) => name === contract.name);
|
|
312
|
+
if (!field || field.type !== contract.type || field.process !== contract.process || field.units !== contract.units) throw new Error(`${subject} field ${contract.name} changed`);
|
|
313
|
+
}
|
|
314
|
+
return {
|
|
315
|
+
fields,
|
|
316
|
+
records
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
function lastRecord(table, subject) {
|
|
320
|
+
const record = table.records[table.records.length - 1];
|
|
321
|
+
if (!record) throw new Error(`${subject} returned no readings`);
|
|
322
|
+
return record;
|
|
323
|
+
}
|
|
324
|
+
function campbellNumber(table, record, fieldName, subject) {
|
|
325
|
+
const index = table.fields.findIndex(({ name }) => name === fieldName);
|
|
326
|
+
const value = index >= 0 ? record.vals[index] : null;
|
|
327
|
+
if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`${subject} is missing ${fieldName}`);
|
|
328
|
+
return value;
|
|
329
|
+
}
|
|
330
|
+
function campbellSpeed(table, record, fieldName, subject) {
|
|
331
|
+
const value = campbellNumber(table, record, fieldName, subject);
|
|
332
|
+
if (value < 0 || value > 500) throw new Error(`${subject} returned an invalid ${fieldName}`);
|
|
333
|
+
return value;
|
|
334
|
+
}
|
|
335
|
+
function campbellDirection(table, record, fieldName, subject) {
|
|
336
|
+
const value = campbellNumber(table, record, fieldName, subject);
|
|
337
|
+
if (value < 0 || value > 360) throw new Error(`${subject} returned an invalid ${fieldName}`);
|
|
338
|
+
return value;
|
|
339
|
+
}
|
|
340
|
+
function isRecord(value) {
|
|
341
|
+
return typeof value === "object" && value !== null;
|
|
342
|
+
}
|
|
343
|
+
const NAIVE_LOCAL_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/;
|
|
344
|
+
const DAY_MS = 864e5;
|
|
345
|
+
const zoneFormatters = /* @__PURE__ */ new Map();
|
|
346
|
+
function zoneFormatter(timeZone) {
|
|
347
|
+
const cached = zoneFormatters.get(timeZone);
|
|
348
|
+
if (cached) return cached;
|
|
349
|
+
const formatter = new Intl.DateTimeFormat("en-CA", {
|
|
350
|
+
timeZone,
|
|
351
|
+
hourCycle: "h23",
|
|
352
|
+
year: "numeric",
|
|
353
|
+
month: "2-digit",
|
|
354
|
+
day: "2-digit",
|
|
355
|
+
hour: "2-digit",
|
|
356
|
+
minute: "2-digit",
|
|
357
|
+
second: "2-digit"
|
|
358
|
+
});
|
|
359
|
+
zoneFormatters.set(timeZone, formatter);
|
|
360
|
+
return formatter;
|
|
361
|
+
}
|
|
362
|
+
function zoneOffsetMs(instantMs, timeZone) {
|
|
363
|
+
const parts = {};
|
|
364
|
+
for (const { type, value } of zoneFormatter(timeZone).formatToParts(new Date(instantMs))) parts[type] = value;
|
|
365
|
+
return Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), Number(parts.hour), Number(parts.minute), Number(parts.second)) - instantMs;
|
|
366
|
+
}
|
|
367
|
+
function pickCandidate(candidates, context) {
|
|
368
|
+
const earliest = candidates[0];
|
|
369
|
+
if (candidates.length === 1) return earliest;
|
|
370
|
+
if (context.afterMs != null) {
|
|
371
|
+
const afterMs = context.afterMs;
|
|
372
|
+
return candidates.find((candidate) => candidate > afterMs) ?? candidates[candidates.length - 1];
|
|
373
|
+
}
|
|
374
|
+
if (context.nearMs != null) {
|
|
375
|
+
const nearMs = context.nearMs;
|
|
376
|
+
return candidates.reduce((best, candidate) => Math.abs(candidate - nearMs) < Math.abs(best - nearMs) ? candidate : best);
|
|
377
|
+
}
|
|
378
|
+
return earliest;
|
|
379
|
+
}
|
|
380
|
+
function naiveLocalToIso(naive, timeZone, context = {}) {
|
|
381
|
+
const match = NAIVE_LOCAL_TIME.exec(naive);
|
|
382
|
+
if (!match) throw new Error(`invalid station-local time: ${naive}`);
|
|
383
|
+
const [, yearText, monthText, dayText, hourText, minuteText, secondText] = match;
|
|
384
|
+
const target = {
|
|
385
|
+
year: Number(yearText),
|
|
386
|
+
month: Number(monthText),
|
|
387
|
+
day: Number(dayText),
|
|
388
|
+
hour: Number(hourText),
|
|
389
|
+
minute: Number(minuteText),
|
|
390
|
+
second: Number(secondText)
|
|
391
|
+
};
|
|
392
|
+
const guess = Date.UTC(target.year, target.month - 1, target.day, target.hour, target.minute, target.second);
|
|
393
|
+
const normalized = new Date(guess);
|
|
394
|
+
if (normalized.getUTCFullYear() !== target.year || normalized.getUTCMonth() !== target.month - 1 || normalized.getUTCDate() !== target.day || normalized.getUTCHours() !== target.hour || normalized.getUTCMinutes() !== target.minute || normalized.getUTCSeconds() !== target.second) throw new Error(`invalid station-local time: ${naive}`);
|
|
395
|
+
const offsets = [.../* @__PURE__ */ new Set([
|
|
396
|
+
zoneOffsetMs(guess - DAY_MS, timeZone),
|
|
397
|
+
zoneOffsetMs(guess, timeZone),
|
|
398
|
+
zoneOffsetMs(guess + DAY_MS, timeZone)
|
|
399
|
+
])];
|
|
400
|
+
const valid = offsets.map((offset) => guess - offset).filter((candidate) => zoneOffsetMs(candidate, timeZone) === guess - candidate).sort((a, b) => a - b);
|
|
401
|
+
if (valid.length > 0) return new Date(pickCandidate(valid, context)).toISOString();
|
|
402
|
+
const before = Math.min(...offsets);
|
|
403
|
+
let low = guess - Math.max(...offsets);
|
|
404
|
+
let high = guess - before;
|
|
405
|
+
const lowOffset = zoneOffsetMs(low, timeZone);
|
|
406
|
+
while (high - low > 1e3) {
|
|
407
|
+
const middle = low + Math.floor((high - low) / 2e3) * 1e3;
|
|
408
|
+
if (zoneOffsetMs(middle, timeZone) === lowOffset) low = middle;
|
|
409
|
+
else high = middle;
|
|
410
|
+
}
|
|
411
|
+
return new Date(high).toISOString();
|
|
412
|
+
}
|
|
413
|
+
//#endregion
|
|
414
|
+
export { CAMPBELL_FIELD_CONTRACTS, loadCampbellCurrent, loadCampbellStation, naiveLocalToIso, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Reading } from "../../contract.js";
|
|
2
|
+
import { StationAdapter, StationAdapterOptions } from "../adapter.js";
|
|
3
|
+
//#region src/server/adapters/tempest.d.ts
|
|
4
|
+
type TempestAdapterOptions = StationAdapterOptions & {
|
|
5
|
+
observationsUrl?: string;
|
|
6
|
+
};
|
|
7
|
+
type TempestObservation = {
|
|
8
|
+
reading: Reading;
|
|
9
|
+
elevationM: number | null;
|
|
10
|
+
latitude: number | null;
|
|
11
|
+
longitude: number | null;
|
|
12
|
+
};
|
|
13
|
+
declare const loadTempestStation: StationAdapter<{
|
|
14
|
+
stationId: number;
|
|
15
|
+
token: string;
|
|
16
|
+
id: string;
|
|
17
|
+
name: string;
|
|
18
|
+
vendor: "tempest";
|
|
19
|
+
timeZone?: string | null | undefined;
|
|
20
|
+
pageUrl?: string | null | undefined;
|
|
21
|
+
elevationM?: number | null | undefined;
|
|
22
|
+
latitude?: number | null | undefined;
|
|
23
|
+
longitude?: number | null | undefined;
|
|
24
|
+
}, TempestAdapterOptions>;
|
|
25
|
+
declare function parseTempestWind(value: string, expectedStationId: number): TempestObservation;
|
|
26
|
+
//#endregion
|
|
27
|
+
export { TempestAdapterOptions, TempestObservation, loadTempestStation, parseTempestWind };
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { isCalm, normalizeDegrees } from "../../derive.js";
|
|
2
|
+
import { fetchUpstreamText } from "../environment.js";
|
|
3
|
+
import { defineStationAdapter } from "../adapter.js";
|
|
4
|
+
import { plausibleWindMps } from "@azohra/meteo.core";
|
|
5
|
+
//#region src/server/adapters/tempest.ts
|
|
6
|
+
const TEMPEST_OBSERVATIONS_URL = "https://swd.weatherflow.com/swd/rest/observations/station";
|
|
7
|
+
const CACHE_TTL_SECONDS = 60;
|
|
8
|
+
const loadTempestStation = defineStationAdapter({
|
|
9
|
+
meta: (config) => ({
|
|
10
|
+
id: config.id,
|
|
11
|
+
name: config.name,
|
|
12
|
+
sourceLabel: "Tempest",
|
|
13
|
+
pageUrl: config.pageUrl ?? `https://tempestwx.com/station/${config.stationId}`,
|
|
14
|
+
latitude: config.latitude ?? null,
|
|
15
|
+
longitude: config.longitude ?? null,
|
|
16
|
+
timeZone: config.timeZone ?? null,
|
|
17
|
+
elevationM: config.elevationM ?? null,
|
|
18
|
+
capabilities: {
|
|
19
|
+
gustLull: true,
|
|
20
|
+
temperature: true,
|
|
21
|
+
conditions: true,
|
|
22
|
+
history: false
|
|
23
|
+
},
|
|
24
|
+
samplingWindowSeconds: 60,
|
|
25
|
+
recommendedPollSeconds: 60
|
|
26
|
+
}),
|
|
27
|
+
load: async (config, { environment, options }) => {
|
|
28
|
+
const url = new URL(`${options.observationsUrl ?? TEMPEST_OBSERVATIONS_URL}/${config.stationId}`);
|
|
29
|
+
url.searchParams.set("token", config.token);
|
|
30
|
+
const observation = parseTempestWind(await fetchUpstreamText(environment, {
|
|
31
|
+
url,
|
|
32
|
+
cacheKey: `tempest/${config.stationId}`,
|
|
33
|
+
cacheTtlSeconds: CACHE_TTL_SECONDS,
|
|
34
|
+
subject: `Tempest station ${config.stationId}`
|
|
35
|
+
}), config.stationId);
|
|
36
|
+
return {
|
|
37
|
+
reading: observation.reading,
|
|
38
|
+
history: null,
|
|
39
|
+
meta: {
|
|
40
|
+
elevationM: observation.elevationM ?? config.elevationM ?? null,
|
|
41
|
+
latitude: observation.latitude ?? config.latitude ?? null,
|
|
42
|
+
longitude: observation.longitude ?? config.longitude ?? null
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
function parseTempestWind(value, expectedStationId) {
|
|
48
|
+
const data = JSON.parse(value);
|
|
49
|
+
if (!isRecord(data) || data.station_id !== expectedStationId) throw new Error("Tempest returned the wrong station");
|
|
50
|
+
const observation = Array.isArray(data.obs) ? data.obs[0] : null;
|
|
51
|
+
if (!isRecord(observation)) throw new Error("Tempest returned no observation");
|
|
52
|
+
const timestamp = numberField(observation, "timestamp");
|
|
53
|
+
const windAvgMps = windSpeedMps(numberField(observation, "wind_avg"));
|
|
54
|
+
const windDirectionDeg = directionDegrees(numberField(observation, "wind_direction"));
|
|
55
|
+
const conditions = {
|
|
56
|
+
dewPointC: nullableNumberField(observation, "dew_point"),
|
|
57
|
+
lastLightningStrikeAt: nullableEpochField(observation, "lightning_strike_last_epoch"),
|
|
58
|
+
lastLightningStrikeDistanceKm: nullableNumberField(observation, "lightning_strike_last_distance", nonnegativeNumber),
|
|
59
|
+
lightningStrikeCountLastHour: nullableNumberField(observation, "lightning_strike_count_last_1hr", nonnegativeInteger),
|
|
60
|
+
precipitationMinutesToday: nullableNumberField(observation, "precip_minutes_local_day", nonnegativeInteger),
|
|
61
|
+
precipitationRateMmPerHour: nullableNumberField(observation, "precip", (parsed) => nonnegativeNumber(parsed) * 60),
|
|
62
|
+
precipitationTodayMm: nullableNumberField(observation, "precip_accum_local_day", nonnegativeNumber),
|
|
63
|
+
pressureTrend: nullablePressureTrend(observation, "pressure_trend"),
|
|
64
|
+
relativeHumidityPercent: nullableNumberField(observation, "relative_humidity", percentage),
|
|
65
|
+
seaLevelPressureHpa: nullableNumberField(observation, "sea_level_pressure", positiveNumber),
|
|
66
|
+
solarRadiationWm2: nullableNumberField(observation, "solar_radiation", nonnegativeNumber),
|
|
67
|
+
uvIndex: nullableNumberField(observation, "uv", nonnegativeNumber)
|
|
68
|
+
};
|
|
69
|
+
return {
|
|
70
|
+
elevationM: nullableNumberField(data, "elevation"),
|
|
71
|
+
latitude: nullableNumberField(data, "latitude", latitudeDegrees),
|
|
72
|
+
longitude: nullableNumberField(data, "longitude", longitudeDegrees),
|
|
73
|
+
reading: {
|
|
74
|
+
observedAt: (/* @__PURE__ */ new Date(timestamp * 1e3)).toISOString(),
|
|
75
|
+
windAvgMps,
|
|
76
|
+
windDirectionDeg: isCalm(windAvgMps) ? null : normalizeDegrees(windDirectionDeg),
|
|
77
|
+
windGustMps: windSpeedMps(numberField(observation, "wind_gust")),
|
|
78
|
+
windLullMps: nullableNumberField(observation, "wind_lull", windSpeedMps),
|
|
79
|
+
temperatureC: numberField(observation, "air_temperature"),
|
|
80
|
+
windChillC: nullableNumberField(observation, "wind_chill"),
|
|
81
|
+
conditions
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function isRecord(value) {
|
|
86
|
+
return typeof value === "object" && value !== null;
|
|
87
|
+
}
|
|
88
|
+
function numberField(value, name) {
|
|
89
|
+
const parsed = value[name];
|
|
90
|
+
if (typeof parsed !== "number" || !Number.isFinite(parsed)) throw new Error(`Tempest is missing ${name}`);
|
|
91
|
+
return parsed;
|
|
92
|
+
}
|
|
93
|
+
function nullableNumberField(value, name, transform = (parsed) => parsed) {
|
|
94
|
+
return value[name] == null ? null : transform(numberField(value, name));
|
|
95
|
+
}
|
|
96
|
+
function nullableEpochField(value, name) {
|
|
97
|
+
return value[name] == null ? null : (/* @__PURE__ */ new Date(nonnegativeInteger(numberField(value, name)) * 1e3)).toISOString();
|
|
98
|
+
}
|
|
99
|
+
function nullablePressureTrend(value, name) {
|
|
100
|
+
const parsed = value[name];
|
|
101
|
+
if (parsed == null) return null;
|
|
102
|
+
if (parsed === "falling" || parsed === "rising" || parsed === "steady" || parsed === "unknown") return parsed;
|
|
103
|
+
throw new Error("Tempest returned an invalid pressure trend");
|
|
104
|
+
}
|
|
105
|
+
function nonnegativeNumber(value) {
|
|
106
|
+
if (value < 0) throw new Error("Tempest returned a negative value");
|
|
107
|
+
return value;
|
|
108
|
+
}
|
|
109
|
+
function positiveNumber(value) {
|
|
110
|
+
if (value <= 0) throw new Error("Tempest returned a non-positive value");
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
function nonnegativeInteger(value) {
|
|
114
|
+
if (!Number.isInteger(value) || value < 0) throw new Error("Tempest returned an invalid count");
|
|
115
|
+
return value;
|
|
116
|
+
}
|
|
117
|
+
function percentage(value) {
|
|
118
|
+
if (value < 0 || value > 100) throw new Error("Tempest returned an invalid percentage");
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
function windSpeedMps(value) {
|
|
122
|
+
return plausibleWindMps(value, "Tempest");
|
|
123
|
+
}
|
|
124
|
+
function directionDegrees(value) {
|
|
125
|
+
if (value < 0 || value > 360) throw new Error("Tempest returned an invalid wind direction");
|
|
126
|
+
return value;
|
|
127
|
+
}
|
|
128
|
+
function latitudeDegrees(value) {
|
|
129
|
+
if (value < -90 || value > 90) throw new Error("Tempest returned an invalid latitude");
|
|
130
|
+
return value;
|
|
131
|
+
}
|
|
132
|
+
function longitudeDegrees(value) {
|
|
133
|
+
if (value < -180 || value > 180) throw new Error("Tempest returned an invalid longitude");
|
|
134
|
+
return value === 180 ? -180 : value;
|
|
135
|
+
}
|
|
136
|
+
//#endregion
|
|
137
|
+
export { loadTempestStation, parseTempestWind };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { HistoryPoint } from "../../contract.js";
|
|
2
|
+
import { WindnerdStationConfig } from "../config.js";
|
|
3
|
+
import { StationAdapter, StationAdapterOptions } from "../adapter.js";
|
|
4
|
+
//#region src/server/adapters/windnerd.d.ts
|
|
5
|
+
declare const WINDNERD_RECORD_PERIODS_MINUTES: readonly [1, 15, 60, 180];
|
|
6
|
+
type WindnerdRecordPeriodMinutes = (typeof WINDNERD_RECORD_PERIODS_MINUTES)[number];
|
|
7
|
+
type WindnerdAdapterOptions = StationAdapterOptions & {
|
|
8
|
+
recordsUrl?: string;
|
|
9
|
+
recordPeriodMinutes?: WindnerdRecordPeriodMinutes;
|
|
10
|
+
cacheTtlSeconds?: number;
|
|
11
|
+
};
|
|
12
|
+
type WindnerdRecords = {
|
|
13
|
+
averageSpeedKmh: number[];
|
|
14
|
+
windDirectionDeg: number[];
|
|
15
|
+
gustSpeedKmh: number[];
|
|
16
|
+
lullSpeedKmh: number[];
|
|
17
|
+
observedAt: string[];
|
|
18
|
+
temperatureC: Array<number | null>;
|
|
19
|
+
stationPressureHpa: Array<number | null>;
|
|
20
|
+
utcOffsetMinutes: number | null;
|
|
21
|
+
};
|
|
22
|
+
declare const loadWindnerdStation: StationAdapter<{
|
|
23
|
+
stationKey: string;
|
|
24
|
+
locationId: number;
|
|
25
|
+
hasTemperature: boolean;
|
|
26
|
+
hasPressure: boolean;
|
|
27
|
+
id: string;
|
|
28
|
+
name: string;
|
|
29
|
+
vendor: "windnerd";
|
|
30
|
+
timeZone?: string | null | undefined;
|
|
31
|
+
pageUrl?: string | null | undefined;
|
|
32
|
+
elevationM?: number | null | undefined;
|
|
33
|
+
latitude?: number | null | undefined;
|
|
34
|
+
longitude?: number | null | undefined;
|
|
35
|
+
}, WindnerdAdapterOptions>;
|
|
36
|
+
declare function windnerdHistoryPoints(records: WindnerdRecords, config: Pick<WindnerdStationConfig, "hasTemperature" | "hasPressure" | "elevationM">): HistoryPoint[];
|
|
37
|
+
declare function parseWindnerdRecords(value: string, locationId: number, hasPressure?: boolean): WindnerdRecords;
|
|
38
|
+
//#endregion
|
|
39
|
+
export { WINDNERD_RECORD_PERIODS_MINUTES, WindnerdAdapterOptions, WindnerdRecordPeriodMinutes, WindnerdRecords, loadWindnerdStation, parseWindnerdRecords, windnerdHistoryPoints };
|