@azohra/meteo.station 0.2.0 → 0.3.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/README.md +6 -6
- package/dist/connectivity.d.ts +46 -0
- package/dist/connectivity.js +44 -0
- package/dist/geometry.d.ts +2 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/react/hooks/useMeasuredChartWidth.js +6 -3
- package/dist/server/adapters/ecowitt.d.ts +28 -0
- package/dist/server/adapters/ecowitt.js +150 -0
- package/dist/server/config.d.ts +29 -1
- package/dist/server/config.js +14 -1
- package/dist/server/environment.d.ts +8 -1
- package/dist/server/environment.js +23 -1
- package/dist/server/feed.js +6 -0
- package/dist/server/hologram.d.ts +22 -0
- package/dist/server/hologram.js +113 -0
- package/dist/server/index.d.ts +5 -3
- package/dist/server/index.js +5 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,19 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
The **station** capability of meteo by Azohra: one wire contract, vendor
|
|
4
4
|
adapters that normalize into it (WindNerd, WeatherFlow Tempest, Campbell
|
|
5
|
-
Scientific loggers, or your own), a mountable `Request → Response` handler
|
|
5
|
+
Scientific loggers, Ecowitt, or your own), a mountable `Request → Response` handler
|
|
6
6
|
that serves the whole inventory as a single feed, and hooks and components
|
|
7
|
-
that render it
|
|
7
|
+
that render it natively, in your design system, with no vendor iframe.
|
|
8
8
|
|
|
9
9
|
## Surface
|
|
10
10
|
|
|
11
11
|
| Entry point | What it is |
|
|
12
12
|
|---|---|
|
|
13
|
-
| `@azohra/meteo.station` | The isomorphic root: the wire contract (zod), pure derivations (period stats, compass, freshness, unit and threshold conversion), framework-free chart and instrument geometry, and the shared display rules (strings, formatting, air sentences, display resolution, merge policy) every binding renders from. |
|
|
13
|
+
| `@azohra/meteo.station` | The isomorphic root: the wire contract (zod), the standalone connectivity contract (`StationConnectivity` — cellular backhaul health for the operator's own routes, never the public feed), pure derivations (period stats, compass, freshness, unit and threshold conversion), framework-free chart and instrument geometry, and the shared display rules (strings, formatting, air sentences, display resolution, merge policy) every binding renders from. |
|
|
14
14
|
| `@azohra/meteo.station/client` | The framework-free client data layer: `createJsonPoller` and the station stores (`createStationFeedStore`, `createStationCurrentStore`, `createStationStore`) every binding subscribes to. Client-only at runtime, import-safe anywhere. |
|
|
15
|
-
| `@azohra/meteo.station/server` | Vendor adapters plus the custom-adapter interface and `defineStationAdapter`, data-level `loadStationFeed()` / `loadStationCurrent()`, and the mountable feed handler. Server-only, so it can never leak into a client bundle. |
|
|
16
|
-
| `@azohra/meteo.station/react` | `StationFeedProvider`, polling hooks (`useStation`, `useStationFeed`, `useStationCurrent`), the component set
|
|
17
|
-
| `@azohra/meteo.station/elements` | The same surface as light-DOM custom elements (`<meteo-station-feed>`, `<meteo-station-card>`, `<meteo-station-table>`, the charts, the atoms…)
|
|
15
|
+
| `@azohra/meteo.station/server` | Vendor adapters plus the custom-adapter interface and `defineStationAdapter`, data-level `loadStationFeed()` / `loadStationCurrent()`, the Hologram connectivity loader (`loadHologramConnectivity`), and the mountable feed handler. Server-only, so it can never leak into a client bundle. |
|
|
16
|
+
| `@azohra/meteo.station/react` | `StationFeedProvider`, polling hooks (`useStation`, `useStationFeed`, `useStationCurrent`), the component set (`StationCard`, `CurrentConditions`, `WindHistoryChart`, `WindSampleStrip`, `TrendChart`, `WindRose`, `DailyPattern`, `StationTable`, `StationStrip`, `AirMatrix`, `FreshnessBadge`), and an atoms layer of inline primitives (`Speed`, `Gust`, `Lull`, `Temperature`, `Pressure`, `Direction`, `UpdatedAt`, `BandChip`, `Dial`, `Sparkline`, `Readout`) for composing your own layouts. |
|
|
17
|
+
| `@azohra/meteo.station/elements` | The same surface as light-DOM custom elements (`<meteo-station-feed>`, `<meteo-station-card>`, `<meteo-station-table>`, the charts, the atoms…), a full peer of the react binding, framework-free, held byte-identical by a parity suite. `/register` is the auto-defining one-liner. |
|
|
18
18
|
| `@azohra/meteo.station/styles.css` | The default skin (an intentional side effect), shared by both bindings. |
|
|
19
19
|
|
|
20
20
|
## Taste
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region src/connectivity.d.ts
|
|
3
|
+
declare const CONNECTIVITY_SERVICE_STATES: readonly ["active", "paused", "inactive", "retired", "unknown"];
|
|
4
|
+
type ConnectivityServiceState = (typeof CONNECTIVITY_SERVICE_STATES)[number];
|
|
5
|
+
declare const connectivitySessionSchema: z.ZodObject<{
|
|
6
|
+
beganAt: z.ZodString;
|
|
7
|
+
endedAt: z.ZodNullable<z.ZodString>;
|
|
8
|
+
bytes: z.ZodNullable<z.ZodNumber>;
|
|
9
|
+
}, z.core.$strip>;
|
|
10
|
+
type ConnectivitySession = z.infer<typeof connectivitySessionSchema>;
|
|
11
|
+
declare const stationConnectivitySchema: z.ZodObject<{
|
|
12
|
+
sourceLabel: z.ZodString;
|
|
13
|
+
checkedAt: z.ZodString;
|
|
14
|
+
deviceName: z.ZodNullable<z.ZodString>;
|
|
15
|
+
online: z.ZodNullable<z.ZodBoolean>;
|
|
16
|
+
lastConnectedAt: z.ZodNullable<z.ZodString>;
|
|
17
|
+
carrier: z.ZodNullable<z.ZodString>;
|
|
18
|
+
radioTechnology: z.ZodNullable<z.ZodString>;
|
|
19
|
+
sim: z.ZodObject<{
|
|
20
|
+
service: z.ZodEnum<{
|
|
21
|
+
unknown: "unknown";
|
|
22
|
+
active: "active";
|
|
23
|
+
paused: "paused";
|
|
24
|
+
inactive: "inactive";
|
|
25
|
+
retired: "retired";
|
|
26
|
+
}>;
|
|
27
|
+
vendorState: z.ZodNullable<z.ZodString>;
|
|
28
|
+
expiresAt: z.ZodNullable<z.ZodString>;
|
|
29
|
+
}, z.core.$strip>;
|
|
30
|
+
usage: z.ZodObject<{
|
|
31
|
+
currentPeriodBytes: z.ZodNullable<z.ZodNumber>;
|
|
32
|
+
previousPeriodBytes: z.ZodNullable<z.ZodNumber>;
|
|
33
|
+
planName: z.ZodNullable<z.ZodString>;
|
|
34
|
+
planIncludedBytes: z.ZodNullable<z.ZodNumber>;
|
|
35
|
+
overageLimitBytes: z.ZodNullable<z.ZodNumber>;
|
|
36
|
+
}, z.core.$strip>;
|
|
37
|
+
lastSession: z.ZodNullable<z.ZodObject<{
|
|
38
|
+
beganAt: z.ZodString;
|
|
39
|
+
endedAt: z.ZodNullable<z.ZodString>;
|
|
40
|
+
bytes: z.ZodNullable<z.ZodNumber>;
|
|
41
|
+
}, z.core.$strip>>;
|
|
42
|
+
}, z.core.$strip>;
|
|
43
|
+
type StationConnectivity = z.infer<typeof stationConnectivitySchema>;
|
|
44
|
+
declare function parseStationConnectivity(value: unknown): StationConnectivity | null;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { CONNECTIVITY_SERVICE_STATES, ConnectivityServiceState, ConnectivitySession, StationConnectivity, connectivitySessionSchema, parseStationConnectivity, stationConnectivitySchema };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region src/connectivity.ts
|
|
3
|
+
const isoTime = z.string().refine((value) => Number.isFinite(Date.parse(value)), { message: "not an ISO timestamp" }).meta({ format: "date-time" });
|
|
4
|
+
const dataBytes = z.number().int().min(0);
|
|
5
|
+
const CONNECTIVITY_SERVICE_STATES = [
|
|
6
|
+
"active",
|
|
7
|
+
"paused",
|
|
8
|
+
"inactive",
|
|
9
|
+
"retired",
|
|
10
|
+
"unknown"
|
|
11
|
+
];
|
|
12
|
+
const connectivitySessionSchema = z.object({
|
|
13
|
+
beganAt: isoTime,
|
|
14
|
+
endedAt: isoTime.nullable().describe("null exactly while the session is still open — an open session has no end."),
|
|
15
|
+
bytes: dataBytes.nullable().describe("Bytes moved in this session. null means 'not reported', never zero traffic.")
|
|
16
|
+
}).meta({ id: "ConnectivitySession" });
|
|
17
|
+
const stationConnectivitySchema = z.object({
|
|
18
|
+
sourceLabel: z.string().describe("The backhaul provider, e.g. 'Hologram'."),
|
|
19
|
+
checkedAt: isoTime.describe("When this snapshot was taken from the provider, to within the loader's cache lifetime — never when the device last answered."),
|
|
20
|
+
deviceName: z.string().nullable(),
|
|
21
|
+
online: z.boolean().nullable().describe("In a data session right now. null when the provider does not say — never inferred from usage recency."),
|
|
22
|
+
lastConnectedAt: isoTime.nullable().describe("When the current or most recent data session began."),
|
|
23
|
+
carrier: z.string().nullable().describe("Network name the device last attached to, as the provider spells it."),
|
|
24
|
+
radioTechnology: z.string().nullable().describe("Radio access technology of the last session, e.g. 'LTE'. Cellular providers do not expose signal strength through their clouds — RSSI lives modem-side — so technology plus session recency is the honest connection-quality signal, and this contract carries no signal field that would have to be invented."),
|
|
25
|
+
sim: z.object({
|
|
26
|
+
service: z.enum(CONNECTIVITY_SERVICE_STATES).describe("The SIM lifecycle, normalized across providers."),
|
|
27
|
+
vendorState: z.string().nullable().describe("The provider's own lifecycle word, e.g. 'LIVE' or 'PAUSED-USER'."),
|
|
28
|
+
expiresAt: isoTime.nullable().describe("When the SIM's current term ends, in the provider's meaning of expiry — rolling plans renew through this boundary.")
|
|
29
|
+
}),
|
|
30
|
+
usage: z.object({
|
|
31
|
+
currentPeriodBytes: dataBytes.nullable().describe("Data used in the current billing period. null means 'not reported'."),
|
|
32
|
+
previousPeriodBytes: dataBytes.nullable(),
|
|
33
|
+
planName: z.string().nullable(),
|
|
34
|
+
planIncludedBytes: dataBytes.min(1).nullable().describe("Bytes the plan includes per period. null when the plan declares no allotment (flat-rate or pay-per-byte) — never zero."),
|
|
35
|
+
overageLimitBytes: dataBytes.min(1).nullable().describe("The operator-set usage cap. null means uncapped — never zero.")
|
|
36
|
+
}),
|
|
37
|
+
lastSession: connectivitySessionSchema.nullable()
|
|
38
|
+
}).meta({ id: "StationConnectivity" });
|
|
39
|
+
function parseStationConnectivity(value) {
|
|
40
|
+
const result = stationConnectivitySchema.safeParse(value);
|
|
41
|
+
return result.success ? result.data : null;
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { CONNECTIVITY_SERVICE_STATES, connectivitySessionSchema, parseStationConnectivity, stationConnectivitySchema };
|
package/dist/geometry.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ type ChartScaleOptions = {
|
|
|
33
33
|
declare function chartScales(points: ReadonlyArray<HistoryPoint>, frame: ChartFrame, options?: ChartScaleOptions): ChartScales;
|
|
34
34
|
declare function bandPoints(points: ReadonlyArray<HistoryPoint>, scales: ChartScales): string | null;
|
|
35
35
|
declare function averagePoints(points: ReadonlyArray<HistoryPoint>, scales: ChartScales): string;
|
|
36
|
+
declare function meanDirectionDeg(points: ReadonlyArray<HistoryPoint>): number | null;
|
|
36
37
|
type Vane = {
|
|
37
38
|
windAvgMps: number;
|
|
38
39
|
windDirectionDeg: number | null;
|
|
@@ -88,4 +89,4 @@ declare function windowPoints(points: ReadonlyArray<HistoryPoint>, hours?: numbe
|
|
|
88
89
|
declare function compareWindow(points: ReadonlyArray<HistoryPoint>, offsetDays: number, windowHours?: number): HistoryPoint[] | null;
|
|
89
90
|
declare function compareTracePoints(comparePoints: ReadonlyArray<HistoryPoint>, scales: ChartScales, offsetDays: number): string;
|
|
90
91
|
//#endregion
|
|
91
|
-
export { CHART_FALLBACK_WIDTH, ChartFrame, ChartScaleOptions, ChartScales, ChartTick, DAILY_PATTERN_DEFAULT_SLOT_MINUTES, DailyPatternSlot, METEOROLOGICAL_SEASON_MONTHS, RoseSector, TickAnchor, TrendSeries, Vane, WindRoseSummary, averagePoints, bandPoints, chartFrame, chartScales, compareTracePoints, compareWindow, dailyPattern, filterByMonth, filterByTimeOfDay, historyGaps, measuredChartWidth, nearestIndex, speedBand, thinVanes, tickAnchor, vanePath, vaneTicks, windRose, windowPoints };
|
|
92
|
+
export { CHART_FALLBACK_WIDTH, ChartFrame, ChartScaleOptions, ChartScales, ChartTick, DAILY_PATTERN_DEFAULT_SLOT_MINUTES, DailyPatternSlot, METEOROLOGICAL_SEASON_MONTHS, RoseSector, TickAnchor, TrendSeries, Vane, WindRoseSummary, averagePoints, bandPoints, chartFrame, chartScales, compareTracePoints, compareWindow, dailyPattern, filterByMonth, filterByTimeOfDay, historyGaps, meanDirectionDeg, measuredChartWidth, nearestIndex, speedBand, thinVanes, tickAnchor, vanePath, vaneTicks, windRose, windowPoints };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { AirConditions, History, HistoryPoint, LiveSample, LiveSamples, Reading, STATION_SCHEMA_VERSION, Station, StationCapabilities, StationCurrent, StationFeed, StationLiveFrame, StationMeta, StationTelemetry, UNAVAILABLE_REASONS, UnavailableReason, airConditionsSchema, capabilitiesSchema, emptyConditions, historyPointSchema, historySchema, liveSampleSchema, liveSamplesSchema, parseStationCurrent, parseStationCurrentJson, parseStationFeed, parseStationFeedJson, parseStationLiveFrame, parseStationLiveFrameJson, readingSchema, stationCurrentSchema, stationFeedSchema, stationLiveFrameSchema, stationMetaSchema, stationSchema, telemetrySchema, unavailableStation } from "./contract.js";
|
|
2
|
-
import { CALM_THRESHOLD_MPS, CompassPoint, FreshnessStatus, FreshnessThresholds, PeriodSummary, PressureTendency, SpeedThresholds, SpeedUnit, compassDirection, freshness, isCalm, normalizeDegrees, periodSummary, pressureTendency, seaLevelPressureHpa, speedFromMps, speedToMps, speedUnitLabel, stationFreshnessThresholds, thresholdsToMps } from "./derive.js";
|
|
2
|
+
import { CALM_THRESHOLD_MPS, COMPASS_POINTS, CompassPoint, FreshnessStatus, FreshnessThresholds, PeriodSummary, PressureTendency, SpeedThresholds, SpeedUnit, compassDirection, freshness, isCalm, normalizeDegrees, periodSummary, pressureTendency, seaLevelPressureHpa, speedFromMps, speedToMps, speedUnitLabel, stationFreshnessThresholds, thresholdsToMps } from "./derive.js";
|
|
3
3
|
import { FormatTime, StationStringOverrides, StationStrings, defaultFormatTime, defaultStrings, localeFormatTime, mergeStringOverrides, resolveStrings } from "./strings.js";
|
|
4
4
|
import { DirectionCellData, SummaryEntry, directionCell, optionalSpeed, roundSpeed, summaryEntries, temperatureText, temperatureValue, updatedAtText } from "./format.js";
|
|
5
|
+
import { CONNECTIVITY_SERVICE_STATES, ConnectivityServiceState, ConnectivitySession, StationConnectivity, connectivitySessionSchema, parseStationConnectivity, stationConnectivitySchema } from "./connectivity.js";
|
|
5
6
|
import { DisplayDefaults, DisplayProps, ResolvedDisplay, requireResolved, resolveDisplay, resolveStation } from "./display.js";
|
|
6
7
|
import { currentEndpoint, feedEndpoint, liveEndpoint } from "./endpoints.js";
|
|
7
|
-
import { CHART_FALLBACK_WIDTH, ChartFrame, ChartScaleOptions, ChartScales, ChartTick, DAILY_PATTERN_DEFAULT_SLOT_MINUTES, DailyPatternSlot, METEOROLOGICAL_SEASON_MONTHS, RoseSector, TickAnchor, Vane, WindRoseSummary, averagePoints, bandPoints, chartFrame, chartScales, compareTracePoints, compareWindow, dailyPattern, filterByMonth, filterByTimeOfDay, historyGaps, measuredChartWidth, nearestIndex, speedBand, thinVanes, tickAnchor, vanePath, vaneTicks, windRose, windowPoints } from "./geometry.js";
|
|
8
|
+
import { CHART_FALLBACK_WIDTH, ChartFrame, ChartScaleOptions, ChartScales, ChartTick, DAILY_PATTERN_DEFAULT_SLOT_MINUTES, DailyPatternSlot, METEOROLOGICAL_SEASON_MONTHS, RoseSector, TickAnchor, Vane, WindRoseSummary, averagePoints, bandPoints, chartFrame, chartScales, compareTracePoints, compareWindow, dailyPattern, filterByMonth, filterByTimeOfDay, historyGaps, meanDirectionDeg, measuredChartWidth, nearestIndex, speedBand, thinVanes, tickAnchor, vanePath, vaneTicks, windRose, windowPoints } from "./geometry.js";
|
|
8
9
|
import { DIAL_CARDINALS, DIAL_CARDINAL_TICK_INNER, DIAL_CENTRE, DIAL_COUNTERWEIGHT_RADIUS, DIAL_COUNTERWEIGHT_REACH, DIAL_HUB_RADIUS, DIAL_LETTER_RADIUS, DIAL_MIN_MAX_MPS, DIAL_RING_RADIUS, DIAL_SIZE, DIAL_TICK_INNER, FavorableDirection, HistoryRun, ROSE_CARDINAL_LETTERS, ROSE_CENTRE, ROSE_FAVORABLE_RING_RADIUS, ROSE_HUB_DOT_RADIUS, ROSE_HUB_RADIUS, ROSE_INTERCARDINAL_BEARINGS, ROSE_LETTER_RADIUS, ROSE_MAX_RADIUS, ROSE_PETAL_FILL, ROSE_SIZE, ROSE_TICK_REACH, SPARKLINE_EDGE_INSET, SPARKLINE_MAX_PADDING, bandStrips, dialNeedlePoints, dialPolar, dialScaleMaxMps, dialSpeedArcPath, historyRuns, rosePetalPath, rosePolar, roseRingArcPath, sparklineScale } from "./instruments.js";
|
|
9
10
|
import { MergeResult, foldCurrent, mergeCurrent } from "./merge-current.js";
|
|
10
11
|
import { SAMPLE_GAP_TOLERANCE_FACTOR, SamplesSummary, sampleMeanDirectionDeg, samplePoints, sampleRuns, sampleScales, samplesSummary, thinSampleVanes } from "./samples.js";
|
|
11
12
|
import { AirRow, airRows, airSummary, lastStrikeWords } from "./air.js";
|
|
12
13
|
import { normalizeWindnerdStationKey, windnerdStationUrl } from "./windnerd.js";
|
|
13
|
-
export { type AirConditions, type AirRow, CALM_THRESHOLD_MPS, CHART_FALLBACK_WIDTH, type ChartFrame, type ChartScaleOptions, type ChartScales, type ChartTick, type CompassPoint, DAILY_PATTERN_DEFAULT_SLOT_MINUTES, DIAL_CARDINALS, DIAL_CARDINAL_TICK_INNER, DIAL_CENTRE, DIAL_COUNTERWEIGHT_RADIUS, DIAL_COUNTERWEIGHT_REACH, DIAL_HUB_RADIUS, DIAL_LETTER_RADIUS, DIAL_MIN_MAX_MPS, DIAL_RING_RADIUS, DIAL_SIZE, DIAL_TICK_INNER, type DailyPatternSlot, type DirectionCellData, type DisplayDefaults, type DisplayProps, type FavorableDirection, type FormatTime, type FreshnessStatus, type FreshnessThresholds, type History, type HistoryPoint, type HistoryRun, type LiveSample, type LiveSamples, METEOROLOGICAL_SEASON_MONTHS, type MergeResult, type PeriodSummary, type PressureTendency, ROSE_CARDINAL_LETTERS, ROSE_CENTRE, ROSE_FAVORABLE_RING_RADIUS, ROSE_HUB_DOT_RADIUS, ROSE_HUB_RADIUS, ROSE_INTERCARDINAL_BEARINGS, ROSE_LETTER_RADIUS, ROSE_MAX_RADIUS, ROSE_PETAL_FILL, ROSE_SIZE, ROSE_TICK_REACH, type Reading, type ResolvedDisplay, type RoseSector, SAMPLE_GAP_TOLERANCE_FACTOR, SPARKLINE_EDGE_INSET, SPARKLINE_MAX_PADDING, STATION_SCHEMA_VERSION, type SamplesSummary, type SpeedThresholds, type SpeedUnit, type Station, type StationCapabilities, type StationCurrent, type StationFeed, type StationLiveFrame, type StationMeta, type StationStringOverrides, type StationStrings, type StationTelemetry, type SummaryEntry, type TickAnchor, UNAVAILABLE_REASONS, type UnavailableReason, type Vane, type WindRoseSummary, airConditionsSchema, airRows, airSummary, averagePoints, bandPoints, bandStrips, capabilitiesSchema, chartFrame, chartScales, compareTracePoints, compareWindow, compassDirection, currentEndpoint, dailyPattern, defaultFormatTime, defaultStrings, dialNeedlePoints, dialPolar, dialScaleMaxMps, dialSpeedArcPath, directionCell, emptyConditions, feedEndpoint, filterByMonth, filterByTimeOfDay, foldCurrent, freshness, historyGaps, historyPointSchema, historyRuns, historySchema, isCalm, lastStrikeWords, liveEndpoint, liveSampleSchema, liveSamplesSchema, localeFormatTime, measuredChartWidth, mergeCurrent, mergeStringOverrides, nearestIndex, normalizeDegrees, normalizeWindnerdStationKey, optionalSpeed, parseStationCurrent, parseStationCurrentJson, parseStationFeed, parseStationFeedJson, parseStationLiveFrame, parseStationLiveFrameJson, periodSummary, pressureTendency, readingSchema, requireResolved, resolveDisplay, resolveStation, resolveStrings, rosePetalPath, rosePolar, roseRingArcPath, roundSpeed, sampleMeanDirectionDeg, samplePoints, sampleRuns, sampleScales, samplesSummary, seaLevelPressureHpa, sparklineScale, speedBand, speedFromMps, speedToMps, speedUnitLabel, stationCurrentSchema, stationFeedSchema, stationFreshnessThresholds, stationLiveFrameSchema, stationMetaSchema, stationSchema, summaryEntries, telemetrySchema, temperatureText, temperatureValue, thinSampleVanes, thinVanes, thresholdsToMps, tickAnchor, unavailableStation, updatedAtText, vanePath, vaneTicks, windRose, windnerdStationUrl, windowPoints };
|
|
14
|
+
export { type AirConditions, type AirRow, CALM_THRESHOLD_MPS, CHART_FALLBACK_WIDTH, COMPASS_POINTS, CONNECTIVITY_SERVICE_STATES, type ChartFrame, type ChartScaleOptions, type ChartScales, type ChartTick, type CompassPoint, type ConnectivityServiceState, type ConnectivitySession, DAILY_PATTERN_DEFAULT_SLOT_MINUTES, DIAL_CARDINALS, DIAL_CARDINAL_TICK_INNER, DIAL_CENTRE, DIAL_COUNTERWEIGHT_RADIUS, DIAL_COUNTERWEIGHT_REACH, DIAL_HUB_RADIUS, DIAL_LETTER_RADIUS, DIAL_MIN_MAX_MPS, DIAL_RING_RADIUS, DIAL_SIZE, DIAL_TICK_INNER, type DailyPatternSlot, type DirectionCellData, type DisplayDefaults, type DisplayProps, type FavorableDirection, type FormatTime, type FreshnessStatus, type FreshnessThresholds, type History, type HistoryPoint, type HistoryRun, type LiveSample, type LiveSamples, METEOROLOGICAL_SEASON_MONTHS, type MergeResult, type PeriodSummary, type PressureTendency, ROSE_CARDINAL_LETTERS, ROSE_CENTRE, ROSE_FAVORABLE_RING_RADIUS, ROSE_HUB_DOT_RADIUS, ROSE_HUB_RADIUS, ROSE_INTERCARDINAL_BEARINGS, ROSE_LETTER_RADIUS, ROSE_MAX_RADIUS, ROSE_PETAL_FILL, ROSE_SIZE, ROSE_TICK_REACH, type Reading, type ResolvedDisplay, type RoseSector, SAMPLE_GAP_TOLERANCE_FACTOR, SPARKLINE_EDGE_INSET, SPARKLINE_MAX_PADDING, STATION_SCHEMA_VERSION, type SamplesSummary, type SpeedThresholds, type SpeedUnit, type Station, type StationCapabilities, type StationConnectivity, type StationCurrent, type StationFeed, type StationLiveFrame, type StationMeta, type StationStringOverrides, type StationStrings, type StationTelemetry, type SummaryEntry, type TickAnchor, UNAVAILABLE_REASONS, type UnavailableReason, type Vane, type WindRoseSummary, airConditionsSchema, airRows, airSummary, averagePoints, bandPoints, bandStrips, capabilitiesSchema, chartFrame, chartScales, compareTracePoints, compareWindow, compassDirection, connectivitySessionSchema, currentEndpoint, dailyPattern, defaultFormatTime, defaultStrings, dialNeedlePoints, dialPolar, dialScaleMaxMps, dialSpeedArcPath, directionCell, emptyConditions, feedEndpoint, filterByMonth, filterByTimeOfDay, foldCurrent, freshness, historyGaps, meanDirectionDeg as historyMeanDirectionDeg, historyPointSchema, historyRuns, historySchema, isCalm, lastStrikeWords, liveEndpoint, liveSampleSchema, liveSamplesSchema, localeFormatTime, measuredChartWidth, mergeCurrent, mergeStringOverrides, nearestIndex, normalizeDegrees, normalizeWindnerdStationKey, optionalSpeed, parseStationConnectivity, parseStationCurrent, parseStationCurrentJson, parseStationFeed, parseStationFeedJson, parseStationLiveFrame, parseStationLiveFrameJson, periodSummary, pressureTendency, readingSchema, requireResolved, resolveDisplay, resolveStation, resolveStrings, rosePetalPath, rosePolar, roseRingArcPath, roundSpeed, sampleMeanDirectionDeg, samplePoints, sampleRuns, sampleScales, samplesSummary, seaLevelPressureHpa, sparklineScale, speedBand, speedFromMps, speedToMps, speedUnitLabel, stationConnectivitySchema, stationCurrentSchema, stationFeedSchema, stationFreshnessThresholds, stationLiveFrameSchema, stationMetaSchema, stationSchema, summaryEntries, telemetrySchema, temperatureText, temperatureValue, thinSampleVanes, thinVanes, thresholdsToMps, tickAnchor, unavailableStation, updatedAtText, vanePath, vaneTicks, windRose, windnerdStationUrl, windowPoints };
|
package/dist/index.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { STATION_SCHEMA_VERSION, UNAVAILABLE_REASONS, airConditionsSchema, capabilitiesSchema, emptyConditions, historyPointSchema, historySchema, liveSampleSchema, liveSamplesSchema, parseStationCurrent, parseStationCurrentJson, parseStationFeed, parseStationFeedJson, parseStationLiveFrame, parseStationLiveFrameJson, readingSchema, stationCurrentSchema, stationFeedSchema, stationLiveFrameSchema, stationMetaSchema, stationSchema, telemetrySchema, unavailableStation } from "./contract.js";
|
|
2
|
-
import {
|
|
2
|
+
import { CONNECTIVITY_SERVICE_STATES, connectivitySessionSchema, parseStationConnectivity, stationConnectivitySchema } from "./connectivity.js";
|
|
3
|
+
import { CALM_THRESHOLD_MPS, COMPASS_POINTS, compassDirection, freshness, isCalm, normalizeDegrees, periodSummary, pressureTendency, seaLevelPressureHpa, speedFromMps, speedToMps, speedUnitLabel, stationFreshnessThresholds, thresholdsToMps } from "./derive.js";
|
|
3
4
|
import { defaultFormatTime, defaultStrings, localeFormatTime, mergeStringOverrides, resolveStrings } from "./strings.js";
|
|
4
5
|
import { requireResolved, resolveDisplay, resolveStation } from "./display.js";
|
|
5
6
|
import { currentEndpoint, feedEndpoint, liveEndpoint } from "./endpoints.js";
|
|
6
7
|
import { directionCell, optionalSpeed, roundSpeed, summaryEntries, temperatureText, temperatureValue, updatedAtText } from "./format.js";
|
|
7
|
-
import { CHART_FALLBACK_WIDTH, DAILY_PATTERN_DEFAULT_SLOT_MINUTES, METEOROLOGICAL_SEASON_MONTHS, averagePoints, bandPoints, chartFrame, chartScales, compareTracePoints, compareWindow, dailyPattern, filterByMonth, filterByTimeOfDay, historyGaps, measuredChartWidth, nearestIndex, speedBand, thinVanes, tickAnchor, vanePath, vaneTicks, windRose, windowPoints } from "./geometry.js";
|
|
8
|
+
import { CHART_FALLBACK_WIDTH, DAILY_PATTERN_DEFAULT_SLOT_MINUTES, METEOROLOGICAL_SEASON_MONTHS, averagePoints, bandPoints, chartFrame, chartScales, compareTracePoints, compareWindow, dailyPattern, filterByMonth, filterByTimeOfDay, historyGaps, meanDirectionDeg, measuredChartWidth, nearestIndex, speedBand, thinVanes, tickAnchor, vanePath, vaneTicks, windRose, windowPoints } from "./geometry.js";
|
|
8
9
|
import { DIAL_CARDINALS, DIAL_CARDINAL_TICK_INNER, DIAL_CENTRE, DIAL_COUNTERWEIGHT_RADIUS, DIAL_COUNTERWEIGHT_REACH, DIAL_HUB_RADIUS, DIAL_LETTER_RADIUS, DIAL_MIN_MAX_MPS, DIAL_RING_RADIUS, DIAL_SIZE, DIAL_TICK_INNER, ROSE_CARDINAL_LETTERS, ROSE_CENTRE, ROSE_FAVORABLE_RING_RADIUS, ROSE_HUB_DOT_RADIUS, ROSE_HUB_RADIUS, ROSE_INTERCARDINAL_BEARINGS, ROSE_LETTER_RADIUS, ROSE_MAX_RADIUS, ROSE_PETAL_FILL, ROSE_SIZE, ROSE_TICK_REACH, SPARKLINE_EDGE_INSET, SPARKLINE_MAX_PADDING, bandStrips, dialNeedlePoints, dialPolar, dialScaleMaxMps, dialSpeedArcPath, historyRuns, rosePetalPath, rosePolar, roseRingArcPath, sparklineScale } from "./instruments.js";
|
|
9
10
|
import { foldCurrent, mergeCurrent } from "./merge-current.js";
|
|
10
11
|
import { SAMPLE_GAP_TOLERANCE_FACTOR, sampleMeanDirectionDeg, samplePoints, sampleRuns, sampleScales, samplesSummary, thinSampleVanes } from "./samples.js";
|
|
11
12
|
import { airRows, airSummary, lastStrikeWords } from "./air.js";
|
|
12
13
|
import { normalizeWindnerdStationKey, windnerdStationUrl } from "./windnerd.js";
|
|
13
|
-
export { CALM_THRESHOLD_MPS, CHART_FALLBACK_WIDTH, DAILY_PATTERN_DEFAULT_SLOT_MINUTES, DIAL_CARDINALS, DIAL_CARDINAL_TICK_INNER, DIAL_CENTRE, DIAL_COUNTERWEIGHT_RADIUS, DIAL_COUNTERWEIGHT_REACH, DIAL_HUB_RADIUS, DIAL_LETTER_RADIUS, DIAL_MIN_MAX_MPS, DIAL_RING_RADIUS, DIAL_SIZE, DIAL_TICK_INNER, METEOROLOGICAL_SEASON_MONTHS, ROSE_CARDINAL_LETTERS, ROSE_CENTRE, ROSE_FAVORABLE_RING_RADIUS, ROSE_HUB_DOT_RADIUS, ROSE_HUB_RADIUS, ROSE_INTERCARDINAL_BEARINGS, ROSE_LETTER_RADIUS, ROSE_MAX_RADIUS, ROSE_PETAL_FILL, ROSE_SIZE, ROSE_TICK_REACH, SAMPLE_GAP_TOLERANCE_FACTOR, SPARKLINE_EDGE_INSET, SPARKLINE_MAX_PADDING, STATION_SCHEMA_VERSION, UNAVAILABLE_REASONS, airConditionsSchema, airRows, airSummary, averagePoints, bandPoints, bandStrips, capabilitiesSchema, chartFrame, chartScales, compareTracePoints, compareWindow, compassDirection, currentEndpoint, dailyPattern, defaultFormatTime, defaultStrings, dialNeedlePoints, dialPolar, dialScaleMaxMps, dialSpeedArcPath, directionCell, emptyConditions, feedEndpoint, filterByMonth, filterByTimeOfDay, foldCurrent, freshness, historyGaps, historyPointSchema, historyRuns, historySchema, isCalm, lastStrikeWords, liveEndpoint, liveSampleSchema, liveSamplesSchema, localeFormatTime, measuredChartWidth, mergeCurrent, mergeStringOverrides, nearestIndex, normalizeDegrees, normalizeWindnerdStationKey, optionalSpeed, parseStationCurrent, parseStationCurrentJson, parseStationFeed, parseStationFeedJson, parseStationLiveFrame, parseStationLiveFrameJson, periodSummary, pressureTendency, readingSchema, requireResolved, resolveDisplay, resolveStation, resolveStrings, rosePetalPath, rosePolar, roseRingArcPath, roundSpeed, sampleMeanDirectionDeg, samplePoints, sampleRuns, sampleScales, samplesSummary, seaLevelPressureHpa, sparklineScale, speedBand, speedFromMps, speedToMps, speedUnitLabel, stationCurrentSchema, stationFeedSchema, stationFreshnessThresholds, stationLiveFrameSchema, stationMetaSchema, stationSchema, summaryEntries, telemetrySchema, temperatureText, temperatureValue, thinSampleVanes, thinVanes, thresholdsToMps, tickAnchor, unavailableStation, updatedAtText, vanePath, vaneTicks, windRose, windnerdStationUrl, windowPoints };
|
|
14
|
+
export { CALM_THRESHOLD_MPS, CHART_FALLBACK_WIDTH, COMPASS_POINTS, CONNECTIVITY_SERVICE_STATES, DAILY_PATTERN_DEFAULT_SLOT_MINUTES, DIAL_CARDINALS, DIAL_CARDINAL_TICK_INNER, DIAL_CENTRE, DIAL_COUNTERWEIGHT_RADIUS, DIAL_COUNTERWEIGHT_REACH, DIAL_HUB_RADIUS, DIAL_LETTER_RADIUS, DIAL_MIN_MAX_MPS, DIAL_RING_RADIUS, DIAL_SIZE, DIAL_TICK_INNER, METEOROLOGICAL_SEASON_MONTHS, ROSE_CARDINAL_LETTERS, ROSE_CENTRE, ROSE_FAVORABLE_RING_RADIUS, ROSE_HUB_DOT_RADIUS, ROSE_HUB_RADIUS, ROSE_INTERCARDINAL_BEARINGS, ROSE_LETTER_RADIUS, ROSE_MAX_RADIUS, ROSE_PETAL_FILL, ROSE_SIZE, ROSE_TICK_REACH, SAMPLE_GAP_TOLERANCE_FACTOR, SPARKLINE_EDGE_INSET, SPARKLINE_MAX_PADDING, STATION_SCHEMA_VERSION, UNAVAILABLE_REASONS, airConditionsSchema, airRows, airSummary, averagePoints, bandPoints, bandStrips, capabilitiesSchema, chartFrame, chartScales, compareTracePoints, compareWindow, compassDirection, connectivitySessionSchema, currentEndpoint, dailyPattern, defaultFormatTime, defaultStrings, dialNeedlePoints, dialPolar, dialScaleMaxMps, dialSpeedArcPath, directionCell, emptyConditions, feedEndpoint, filterByMonth, filterByTimeOfDay, foldCurrent, freshness, historyGaps, meanDirectionDeg as historyMeanDirectionDeg, historyPointSchema, historyRuns, historySchema, isCalm, lastStrikeWords, liveEndpoint, liveSampleSchema, liveSamplesSchema, localeFormatTime, measuredChartWidth, mergeCurrent, mergeStringOverrides, nearestIndex, normalizeDegrees, normalizeWindnerdStationKey, optionalSpeed, parseStationConnectivity, parseStationCurrent, parseStationCurrentJson, parseStationFeed, parseStationFeedJson, parseStationLiveFrame, parseStationLiveFrameJson, periodSummary, pressureTendency, readingSchema, requireResolved, resolveDisplay, resolveStation, resolveStrings, rosePetalPath, rosePolar, roseRingArcPath, roundSpeed, sampleMeanDirectionDeg, samplePoints, sampleRuns, sampleScales, samplesSummary, seaLevelPressureHpa, sparklineScale, speedBand, speedFromMps, speedToMps, speedUnitLabel, stationConnectivitySchema, stationCurrentSchema, stationFeedSchema, stationFreshnessThresholds, stationLiveFrameSchema, stationMetaSchema, stationSchema, summaryEntries, telemetrySchema, temperatureText, temperatureValue, thinSampleVanes, thinVanes, thresholdsToMps, tickAnchor, unavailableStation, updatedAtText, vanePath, vaneTicks, windRose, windnerdStationUrl, windowPoints };
|
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { measuredChartWidth } from "../../geometry.js";
|
|
3
|
-
import { useEffect, useState } from "react";
|
|
3
|
+
import { useEffect, useLayoutEffect, useState } from "react";
|
|
4
4
|
//#region src/react/hooks/useMeasuredChartWidth.ts
|
|
5
|
+
const useMeasureEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
|
|
5
6
|
function useMeasuredChartWidth(ref, { enabled = true } = {}) {
|
|
6
7
|
const [width, setWidth] = useState(null);
|
|
7
|
-
|
|
8
|
+
useMeasureEffect(() => {
|
|
8
9
|
const element = ref.current;
|
|
9
10
|
if (!enabled || element == null) return;
|
|
10
11
|
if (typeof ResizeObserver === "undefined") {
|
|
11
12
|
setWidth(360);
|
|
12
13
|
return;
|
|
13
14
|
}
|
|
15
|
+
if (element.clientWidth > 0) setWidth(measuredChartWidth(element.clientWidth));
|
|
14
16
|
const observer = new ResizeObserver((entries) => {
|
|
15
|
-
|
|
17
|
+
const measured = entries[0]?.contentRect.width ?? 0;
|
|
18
|
+
if (measured > 0) setWidth(measuredChartWidth(measured));
|
|
16
19
|
});
|
|
17
20
|
observer.observe(element);
|
|
18
21
|
return () => observer.disconnect();
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Reading, StationTelemetry } from "../../contract.js";
|
|
2
|
+
import { EcowittStationConfig } from "../config.js";
|
|
3
|
+
import { StationAdapter, StationAdapterOptions } from "../adapter.js";
|
|
4
|
+
//#region src/server/adapters/ecowitt.d.ts
|
|
5
|
+
type EcowittAdapterOptions = StationAdapterOptions & {
|
|
6
|
+
realTimeUrl?: string;
|
|
7
|
+
};
|
|
8
|
+
type EcowittObservation = {
|
|
9
|
+
reading: Reading;
|
|
10
|
+
telemetry: StationTelemetry | null;
|
|
11
|
+
};
|
|
12
|
+
declare const loadEcowittStation: StationAdapter<{
|
|
13
|
+
applicationKey: string;
|
|
14
|
+
apiKey: string;
|
|
15
|
+
mac: string;
|
|
16
|
+
hasBattery: boolean;
|
|
17
|
+
id: string;
|
|
18
|
+
name: string;
|
|
19
|
+
vendor: "ecowitt";
|
|
20
|
+
timeZone?: string | null | undefined;
|
|
21
|
+
pageUrl?: string | null | undefined;
|
|
22
|
+
elevationM?: number | null | undefined;
|
|
23
|
+
latitude?: number | null | undefined;
|
|
24
|
+
longitude?: number | null | undefined;
|
|
25
|
+
}, EcowittAdapterOptions>;
|
|
26
|
+
declare function parseEcowittRealTime(value: string, config: Pick<EcowittStationConfig, "mac" | "elevationM">): EcowittObservation;
|
|
27
|
+
//#endregion
|
|
28
|
+
export { EcowittAdapterOptions, EcowittObservation, loadEcowittStation, parseEcowittRealTime };
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { emptyConditions } from "../../contract.js";
|
|
2
|
+
import { isCalm, normalizeDegrees, seaLevelPressureHpa } from "../../derive.js";
|
|
3
|
+
import { fetchUpstreamText } from "../environment.js";
|
|
4
|
+
import { defineStationAdapter } from "../adapter.js";
|
|
5
|
+
import { UpstreamError, plausibleWindMps } from "@azohra/meteo.core";
|
|
6
|
+
//#region src/server/adapters/ecowitt.ts
|
|
7
|
+
const ECOWITT_REAL_TIME_URL = "https://api.ecowitt.net/api/v3/device/real_time";
|
|
8
|
+
const CACHE_TTL_SECONDS = 60;
|
|
9
|
+
const ECOWITT_CALL_BACK = "outdoor,wind,pressure,rainfall,rainfall_piezo,solar_and_uvi,battery";
|
|
10
|
+
const ECOWITT_UNIT_PARAMS = {
|
|
11
|
+
temp_unitid: "1",
|
|
12
|
+
pressure_unitid: "3",
|
|
13
|
+
wind_speed_unitid: "6",
|
|
14
|
+
rainfall_unitid: "12",
|
|
15
|
+
solar_irradiance_unitid: "16"
|
|
16
|
+
};
|
|
17
|
+
const loadEcowittStation = defineStationAdapter({
|
|
18
|
+
meta: (config) => ({
|
|
19
|
+
id: config.id,
|
|
20
|
+
name: config.name,
|
|
21
|
+
sourceLabel: "Ecowitt",
|
|
22
|
+
pageUrl: config.pageUrl ?? null,
|
|
23
|
+
latitude: config.latitude ?? null,
|
|
24
|
+
longitude: config.longitude ?? null,
|
|
25
|
+
timeZone: config.timeZone ?? null,
|
|
26
|
+
elevationM: config.elevationM ?? null,
|
|
27
|
+
capabilities: {
|
|
28
|
+
gustLull: true,
|
|
29
|
+
temperature: true,
|
|
30
|
+
conditions: true,
|
|
31
|
+
history: false,
|
|
32
|
+
battery: config.hasBattery
|
|
33
|
+
},
|
|
34
|
+
samplingWindowSeconds: null,
|
|
35
|
+
recommendedPollSeconds: 60
|
|
36
|
+
}),
|
|
37
|
+
load: async (config, { environment, options }) => {
|
|
38
|
+
const url = new URL(options.realTimeUrl ?? ECOWITT_REAL_TIME_URL);
|
|
39
|
+
url.searchParams.set("application_key", config.applicationKey);
|
|
40
|
+
url.searchParams.set("api_key", config.apiKey);
|
|
41
|
+
url.searchParams.set("mac", config.mac);
|
|
42
|
+
url.searchParams.set("call_back", ECOWITT_CALL_BACK);
|
|
43
|
+
for (const [name, value] of Object.entries(ECOWITT_UNIT_PARAMS)) url.searchParams.set(name, value);
|
|
44
|
+
const observation = parseEcowittRealTime(await fetchUpstreamText(environment, {
|
|
45
|
+
url,
|
|
46
|
+
cacheKey: `ecowitt/${config.mac}`,
|
|
47
|
+
cacheTtlSeconds: CACHE_TTL_SECONDS,
|
|
48
|
+
subject: `Ecowitt device ${config.mac}`
|
|
49
|
+
}), config);
|
|
50
|
+
return {
|
|
51
|
+
reading: observation.reading,
|
|
52
|
+
history: null,
|
|
53
|
+
telemetry: config.hasBattery ? observation.telemetry : null
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
function parseEcowittRealTime(value, config) {
|
|
58
|
+
const envelope = JSON.parse(value);
|
|
59
|
+
if (!isRecord(envelope) || typeof envelope.code !== "number") throw new Error("Ecowitt returned no response envelope");
|
|
60
|
+
if (envelope.code !== 0) {
|
|
61
|
+
const message = `Ecowitt refused the request: ${String(envelope.msg)} (code ${envelope.code})`;
|
|
62
|
+
throw envelope.code === -1 || envelope.code === 45001 ? new UpstreamError(message, "rate_limited") : new UpstreamError(message);
|
|
63
|
+
}
|
|
64
|
+
const data = isRecord(envelope.data) ? envelope.data : {};
|
|
65
|
+
const wind = section(data, "wind");
|
|
66
|
+
if (!wind) throw new UpstreamError(`Ecowitt device ${config.mac} has not reported recently`);
|
|
67
|
+
const observedAtSeconds = leafTime(wind, "wind_speed");
|
|
68
|
+
const windAvgMps = windSpeedMps(numberLeaf(wind, "wind_speed"));
|
|
69
|
+
const windDirectionDeg = directionDegrees(numberLeaf(wind, "wind_direction"));
|
|
70
|
+
const outdoor = section(data, "outdoor");
|
|
71
|
+
const pressure = section(data, "pressure");
|
|
72
|
+
const solar = section(data, "solar_and_uvi");
|
|
73
|
+
const rain = section(data, "rainfall_piezo") ?? section(data, "rainfall");
|
|
74
|
+
const temperatureC = outdoor ? nullableNumberLeaf(outdoor, "temperature") : null;
|
|
75
|
+
const stationPressureHpa = pressure ? nullableNumberLeaf(pressure, "absolute", positiveNumber) : null;
|
|
76
|
+
const conditions = emptyConditions({
|
|
77
|
+
dewPointC: outdoor ? nullableNumberLeaf(outdoor, "dew_point") : null,
|
|
78
|
+
relativeHumidityPercent: outdoor ? nullableNumberLeaf(outdoor, "humidity", percentage) : null,
|
|
79
|
+
seaLevelPressureHpa: stationPressureHpa != null && config.elevationM != null ? seaLevelPressureHpa(stationPressureHpa, config.elevationM, temperatureC) : null,
|
|
80
|
+
precipitationRateMmPerHour: rain ? nullableNumberLeaf(rain, "rain_rate", nonnegativeNumber) : null,
|
|
81
|
+
precipitationTodayMm: rain ? nullableNumberLeaf(rain, "daily", nonnegativeNumber) : null,
|
|
82
|
+
solarRadiationWm2: solar ? nullableNumberLeaf(solar, "solar", nonnegativeNumber) : null,
|
|
83
|
+
uvIndex: solar ? nullableNumberLeaf(solar, "uvi", nonnegativeNumber) : null
|
|
84
|
+
});
|
|
85
|
+
const battery = section(data, "battery");
|
|
86
|
+
return {
|
|
87
|
+
telemetry: battery ? { batteryVoltage: nullableNumberLeaf(battery, "haptic_array_battery", positiveNumber) } : null,
|
|
88
|
+
reading: {
|
|
89
|
+
observedAt: (/* @__PURE__ */ new Date(observedAtSeconds * 1e3)).toISOString(),
|
|
90
|
+
windAvgMps,
|
|
91
|
+
windDirectionDeg: isCalm(windAvgMps) ? null : normalizeDegrees(windDirectionDeg),
|
|
92
|
+
windGustMps: nullableNumberLeaf(wind, "wind_gust", windSpeedMps),
|
|
93
|
+
windLullMps: null,
|
|
94
|
+
temperatureC,
|
|
95
|
+
windChillC: null,
|
|
96
|
+
conditions
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function isRecord(value) {
|
|
101
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
102
|
+
}
|
|
103
|
+
function section(data, name) {
|
|
104
|
+
const parsed = data[name];
|
|
105
|
+
return isRecord(parsed) && Object.keys(parsed).length > 0 ? parsed : null;
|
|
106
|
+
}
|
|
107
|
+
function leaf(group, name) {
|
|
108
|
+
const parsed = group[name];
|
|
109
|
+
return isRecord(parsed) ? parsed : null;
|
|
110
|
+
}
|
|
111
|
+
function leafNumber(entry, name, field) {
|
|
112
|
+
const raw = entry[field];
|
|
113
|
+
const parsed = typeof raw === "number" ? raw : typeof raw === "string" && raw !== "" ? Number(raw) : NaN;
|
|
114
|
+
if (!Number.isFinite(parsed)) throw new Error(`Ecowitt sent a non-numeric ${name}.${field}`);
|
|
115
|
+
return parsed;
|
|
116
|
+
}
|
|
117
|
+
function numberLeaf(group, name, transform = (parsed) => parsed) {
|
|
118
|
+
const entry = leaf(group, name);
|
|
119
|
+
if (!entry) throw new Error(`Ecowitt is missing ${name}`);
|
|
120
|
+
return transform(leafNumber(entry, name, "value"));
|
|
121
|
+
}
|
|
122
|
+
function nullableNumberLeaf(group, name, transform = (parsed) => parsed) {
|
|
123
|
+
return leaf(group, name) == null ? null : numberLeaf(group, name, transform);
|
|
124
|
+
}
|
|
125
|
+
function leafTime(group, name) {
|
|
126
|
+
const entry = leaf(group, name);
|
|
127
|
+
if (!entry) throw new Error(`Ecowitt is missing ${name}`);
|
|
128
|
+
return nonnegativeNumber(leafNumber(entry, name, "time"));
|
|
129
|
+
}
|
|
130
|
+
function nonnegativeNumber(value) {
|
|
131
|
+
if (value < 0) throw new Error("Ecowitt returned a negative value");
|
|
132
|
+
return value;
|
|
133
|
+
}
|
|
134
|
+
function positiveNumber(value) {
|
|
135
|
+
if (value <= 0) throw new Error("Ecowitt returned a non-positive value");
|
|
136
|
+
return value;
|
|
137
|
+
}
|
|
138
|
+
function percentage(value) {
|
|
139
|
+
if (value < 0 || value > 100) throw new Error("Ecowitt returned an invalid percentage");
|
|
140
|
+
return value;
|
|
141
|
+
}
|
|
142
|
+
function windSpeedMps(value) {
|
|
143
|
+
return plausibleWindMps(value, "Ecowitt");
|
|
144
|
+
}
|
|
145
|
+
function directionDegrees(value) {
|
|
146
|
+
if (value < 0 || value > 360) throw new Error("Ecowitt returned an invalid wind direction");
|
|
147
|
+
return value;
|
|
148
|
+
}
|
|
149
|
+
//#endregion
|
|
150
|
+
export { loadEcowittStation, parseEcowittRealTime };
|
package/dist/server/config.d.ts
CHANGED
|
@@ -32,6 +32,21 @@ declare const tempestStationConfigSchema: z.ZodObject<{
|
|
|
32
32
|
vendor: z.ZodLiteral<"tempest">;
|
|
33
33
|
}, z.core.$strict>;
|
|
34
34
|
type TempestStationConfig = z.output<typeof tempestStationConfigSchema>;
|
|
35
|
+
declare const ecowittStationConfigSchema: z.ZodObject<{
|
|
36
|
+
applicationKey: z.ZodString;
|
|
37
|
+
apiKey: z.ZodString;
|
|
38
|
+
mac: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
39
|
+
hasBattery: z.ZodDefault<z.ZodBoolean>;
|
|
40
|
+
timeZone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
41
|
+
pageUrl: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
42
|
+
elevationM: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
43
|
+
latitude: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
44
|
+
longitude: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
45
|
+
id: z.ZodString;
|
|
46
|
+
name: z.ZodString;
|
|
47
|
+
vendor: z.ZodLiteral<"ecowitt">;
|
|
48
|
+
}, z.core.$strict>;
|
|
49
|
+
type EcowittStationConfig = z.output<typeof ecowittStationConfigSchema>;
|
|
35
50
|
declare const campbellStationConfigSchema: z.ZodObject<{
|
|
36
51
|
baseUrl: z.ZodString;
|
|
37
52
|
source: z.ZodString;
|
|
@@ -119,6 +134,19 @@ declare const stationConfigSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
119
134
|
id: z.ZodString;
|
|
120
135
|
name: z.ZodString;
|
|
121
136
|
vendor: z.ZodLiteral<"campbell">;
|
|
137
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
138
|
+
applicationKey: z.ZodString;
|
|
139
|
+
apiKey: z.ZodString;
|
|
140
|
+
mac: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
141
|
+
hasBattery: z.ZodDefault<z.ZodBoolean>;
|
|
142
|
+
timeZone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
143
|
+
pageUrl: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
144
|
+
elevationM: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
145
|
+
latitude: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
146
|
+
longitude: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
147
|
+
id: z.ZodString;
|
|
148
|
+
name: z.ZodString;
|
|
149
|
+
vendor: z.ZodLiteral<"ecowitt">;
|
|
122
150
|
}, z.core.$strict>, z.ZodObject<{
|
|
123
151
|
load: z.ZodCustom<CustomStationLoader, CustomStationLoader>;
|
|
124
152
|
timeZone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
@@ -134,4 +162,4 @@ type StationConfig = z.output<typeof stationConfigSchema>;
|
|
|
134
162
|
type StationConfigInput = z.input<typeof stationConfigSchema>;
|
|
135
163
|
declare function parseStationConfig(value: unknown): StationConfig;
|
|
136
164
|
//#endregion
|
|
137
|
-
export { CampbellStationConfig, CustomStationConfig, CustomStationContext, CustomStationIdentity, CustomStationLoader, StationConfig, StationConfigInput, TempestStationConfig, WindnerdStationConfig, campbellStationConfigSchema, customStationConfigSchema, normalizeWindnerdStationKey, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema, windnerdStationUrl };
|
|
165
|
+
export { CampbellStationConfig, CustomStationConfig, CustomStationContext, CustomStationIdentity, CustomStationLoader, EcowittStationConfig, StationConfig, StationConfigInput, TempestStationConfig, WindnerdStationConfig, campbellStationConfigSchema, customStationConfigSchema, ecowittStationConfigSchema, normalizeWindnerdStationKey, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema, windnerdStationUrl };
|
package/dist/server/config.js
CHANGED
|
@@ -28,6 +28,18 @@ const tempestStationConfigSchema = z.strictObject({
|
|
|
28
28
|
stationId: z.number().int().positive(),
|
|
29
29
|
token: z.string().min(1)
|
|
30
30
|
});
|
|
31
|
+
const ecowittMac = z.string().regex(/^[0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5}$/, { message: "not a colon-separated MAC address (FF:FF:FF:FF:FF:FF)" }).transform((value) => value.toUpperCase());
|
|
32
|
+
const ecowittStationConfigSchema = z.strictObject({
|
|
33
|
+
vendor: z.literal("ecowitt"),
|
|
34
|
+
...stationIdentity,
|
|
35
|
+
applicationKey: z.string().min(1),
|
|
36
|
+
apiKey: z.string().min(1),
|
|
37
|
+
mac: ecowittMac,
|
|
38
|
+
hasBattery: z.boolean().default(true)
|
|
39
|
+
}).refine((config) => config.elevationM != null, {
|
|
40
|
+
message: "pressure needs the barometer's elevation to reduce to sea level — set elevationM to the gateway's elevation (the barometer lives in the gateway, not the outdoor array)",
|
|
41
|
+
path: ["elevationM"]
|
|
42
|
+
});
|
|
31
43
|
const campbellStationConfigSchema = z.strictObject({
|
|
32
44
|
vendor: z.literal("campbell"),
|
|
33
45
|
...stationIdentity,
|
|
@@ -49,10 +61,11 @@ const stationConfigSchema = z.discriminatedUnion("vendor", [
|
|
|
49
61
|
windnerdStationConfigSchema,
|
|
50
62
|
tempestStationConfigSchema,
|
|
51
63
|
campbellStationConfigSchema,
|
|
64
|
+
ecowittStationConfigSchema,
|
|
52
65
|
customStationConfigSchema
|
|
53
66
|
]);
|
|
54
67
|
function parseStationConfig(value) {
|
|
55
68
|
return stationConfigSchema.parse(value);
|
|
56
69
|
}
|
|
57
70
|
//#endregion
|
|
58
|
-
export { campbellStationConfigSchema, customStationConfigSchema, normalizeWindnerdStationKey, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema, windnerdStationUrl };
|
|
71
|
+
export { campbellStationConfigSchema, customStationConfigSchema, ecowittStationConfigSchema, normalizeWindnerdStationKey, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema, windnerdStationUrl };
|
|
@@ -22,6 +22,13 @@ type ResolvedEnvironment = Required<ServerEnvironment>;
|
|
|
22
22
|
declare const UPSTREAM_FETCH_TIMEOUT_MS = 4000;
|
|
23
23
|
declare const UPSTREAM_RESPONSE_LIMIT_BYTES = 524288;
|
|
24
24
|
declare function memoryCache(): FeedCache;
|
|
25
|
+
/**
|
|
26
|
+
* A FeedCache over the ambient Cloudflare Workers cache (`caches.default`),
|
|
27
|
+
* shared across the isolates of a deployment. Returns undefined where no
|
|
28
|
+
* ambient cache exists (node, vitest), so `cache: workersCache()` falls
|
|
29
|
+
* through to the memory-cache default.
|
|
30
|
+
*/
|
|
31
|
+
declare function workersCache(): FeedCache | undefined;
|
|
25
32
|
declare const DEFAULT_USER_AGENT = "azohra-meteo/0.1 (+https://meteo.azohra.com)";
|
|
26
33
|
declare function resolveEnvironment(environment?: ServerEnvironment): ResolvedEnvironment;
|
|
27
34
|
type UpstreamTextRequest = {
|
|
@@ -65,4 +72,4 @@ declare function fetchUpstreamStream(environment: ResolvedEnvironment, request:
|
|
|
65
72
|
declare function boundedResponseText(response: Response, limitBytes: number, subject: string): Promise<string>;
|
|
66
73
|
declare function logUpstreamFailure(environment: ResolvedEnvironment, message: string, error: unknown, detail?: Record<string, unknown>): void;
|
|
67
74
|
//#endregion
|
|
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 };
|
|
75
|
+
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, workersCache };
|
|
@@ -29,6 +29,28 @@ function memoryCache() {
|
|
|
29
29
|
}
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* A FeedCache over the ambient Cloudflare Workers cache (`caches.default`),
|
|
34
|
+
* shared across the isolates of a deployment. Returns undefined where no
|
|
35
|
+
* ambient cache exists (node, vitest), so `cache: workersCache()` falls
|
|
36
|
+
* through to the memory-cache default.
|
|
37
|
+
*/
|
|
38
|
+
function workersCache() {
|
|
39
|
+
const cache = globalThis.caches?.default;
|
|
40
|
+
if (!cache) return void 0;
|
|
41
|
+
return {
|
|
42
|
+
async get(key) {
|
|
43
|
+
const hit = await cache.match(workersCacheRequest(key));
|
|
44
|
+
return hit ? hit.text() : null;
|
|
45
|
+
},
|
|
46
|
+
async put(key, value, ttlSeconds) {
|
|
47
|
+
await cache.put(workersCacheRequest(key), new Response(value, { headers: { "Cache-Control": `max-age=${ttlSeconds}` } }));
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function workersCacheRequest(key) {
|
|
52
|
+
return new Request(`https://meteo-cache.internal/${encodeURIComponent(key)}`);
|
|
53
|
+
}
|
|
32
54
|
const sharedDefaultCache = memoryCache();
|
|
33
55
|
function consoleLogger(event) {
|
|
34
56
|
const log = event.level === "warn" ? console.warn : console.error;
|
|
@@ -169,4 +191,4 @@ function logUpstreamFailure(environment, message, error, detail = {}) {
|
|
|
169
191
|
});
|
|
170
192
|
}
|
|
171
193
|
//#endregion
|
|
172
|
-
export { DEFAULT_USER_AGENT, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS$1 as UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError$1 as UpstreamError, boundedResponseText, coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError };
|
|
194
|
+
export { DEFAULT_USER_AGENT, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS$1 as UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError$1 as UpstreamError, boundedResponseText, coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError, workersCache };
|
package/dist/server/feed.js
CHANGED
|
@@ -2,6 +2,7 @@ import { stationSchema, unavailableStation } from "../contract.js";
|
|
|
2
2
|
import { logUpstreamFailure, resolveEnvironment, unavailableReasonForError } from "./environment.js";
|
|
3
3
|
import { stationConfigSchema } from "./config.js";
|
|
4
4
|
import { loadCampbellStation } from "./adapters/campbell.js";
|
|
5
|
+
import { loadEcowittStation } from "./adapters/ecowitt.js";
|
|
5
6
|
import { loadTempestStation } from "./adapters/tempest.js";
|
|
6
7
|
import { loadWindnerdStation } from "./adapters/windnerd.js";
|
|
7
8
|
import { openWindnerdLive } from "./adapters/windnerd-live.js";
|
|
@@ -182,6 +183,11 @@ async function loadStation(config, environment, historyHours, mode) {
|
|
|
182
183
|
mode,
|
|
183
184
|
environment
|
|
184
185
|
});
|
|
186
|
+
case "ecowitt": return loadEcowittStation(config, {
|
|
187
|
+
historyHours,
|
|
188
|
+
mode,
|
|
189
|
+
environment
|
|
190
|
+
});
|
|
185
191
|
case "custom": return loadCustomStation(config, environment, historyHours, mode);
|
|
186
192
|
}
|
|
187
193
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { ConnectivityServiceState, StationConnectivity } from "../connectivity.js";
|
|
2
|
+
import { ServerEnvironment } from "./environment.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
//#region src/server/hologram.d.ts
|
|
5
|
+
declare const HOLOGRAM_API_BASE = "https://dashboard.hologram.io/api/1";
|
|
6
|
+
declare const TRIAL_HOLOGRAM_CACHE_TTL_SECONDS = 300;
|
|
7
|
+
declare const hologramConnectivityConfigSchema: z.ZodObject<{
|
|
8
|
+
apiKey: z.ZodString;
|
|
9
|
+
deviceId: z.ZodNumber;
|
|
10
|
+
}, z.core.$strict>;
|
|
11
|
+
type HologramConnectivityConfig = z.output<typeof hologramConnectivityConfigSchema>;
|
|
12
|
+
type HologramConnectivityOptions = {
|
|
13
|
+
environment?: ServerEnvironment;
|
|
14
|
+
cacheTtlSeconds?: number;
|
|
15
|
+
apiBase?: string;
|
|
16
|
+
};
|
|
17
|
+
declare function hologramTimeToIso(value: string | null | undefined): string | null;
|
|
18
|
+
declare function hologramServiceState(state: string | null | undefined): ConnectivityServiceState;
|
|
19
|
+
declare function parseHologramConnectivity(value: string, expectedDeviceId: number, checkedAt: string): StationConnectivity;
|
|
20
|
+
declare function loadHologramConnectivity(config: HologramConnectivityConfig, options?: HologramConnectivityOptions): Promise<StationConnectivity>;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { HOLOGRAM_API_BASE, HologramConnectivityConfig, HologramConnectivityOptions, TRIAL_HOLOGRAM_CACHE_TTL_SECONDS, hologramConnectivityConfigSchema, hologramServiceState, hologramTimeToIso, loadHologramConnectivity, parseHologramConnectivity };
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { fetchUpstreamText, resolveEnvironment } from "./environment.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { UpstreamError } from "@azohra/meteo.core";
|
|
4
|
+
//#region src/server/hologram.ts
|
|
5
|
+
const HOLOGRAM_API_BASE = "https://dashboard.hologram.io/api/1";
|
|
6
|
+
const TRIAL_HOLOGRAM_CACHE_TTL_SECONDS = 300;
|
|
7
|
+
const hologramConnectivityConfigSchema = z.strictObject({
|
|
8
|
+
apiKey: z.string().min(1),
|
|
9
|
+
deviceId: z.number().int().positive()
|
|
10
|
+
});
|
|
11
|
+
function hologramTimeToIso(value) {
|
|
12
|
+
if (!value || value.startsWith("0000-00-00")) return null;
|
|
13
|
+
const iso = `${value.replace(" ", "T")}Z`;
|
|
14
|
+
return Number.isFinite(Date.parse(iso)) ? iso : null;
|
|
15
|
+
}
|
|
16
|
+
const nonEmpty = (value) => value ? value : null;
|
|
17
|
+
const hologramLastSessionSchema = z.object({
|
|
18
|
+
active: z.boolean().nullish(),
|
|
19
|
+
bytes: z.coerce.number().int().min(0).nullish(),
|
|
20
|
+
network_name: z.string().nullish(),
|
|
21
|
+
radio_access_technology: z.string().nullish(),
|
|
22
|
+
session_begin: z.string().nullish(),
|
|
23
|
+
session_end: z.string().nullish()
|
|
24
|
+
});
|
|
25
|
+
const hologramPlanSchema = z.object({
|
|
26
|
+
name: z.string().nullish(),
|
|
27
|
+
data: z.coerce.number().int().min(0).nullish()
|
|
28
|
+
});
|
|
29
|
+
const hologramLinkSchema = z.object({
|
|
30
|
+
state: z.string().nullish(),
|
|
31
|
+
cur_billing_data_used: z.number().int().min(0).nullish(),
|
|
32
|
+
last_billing_data_used: z.number().int().min(0).nullish(),
|
|
33
|
+
last_connect_time: z.string().nullish(),
|
|
34
|
+
last_network_used: z.string().nullish(),
|
|
35
|
+
overagelimit: z.number().int().nullish(),
|
|
36
|
+
plan: hologramPlanSchema.nullish(),
|
|
37
|
+
whenexpires: z.string().nullish()
|
|
38
|
+
});
|
|
39
|
+
const hologramDeviceSchema = z.object({
|
|
40
|
+
id: z.number().int(),
|
|
41
|
+
name: z.string().nullish(),
|
|
42
|
+
lastsession: hologramLastSessionSchema.nullish(),
|
|
43
|
+
links: z.object({ cellular: z.array(hologramLinkSchema) }).nullish()
|
|
44
|
+
});
|
|
45
|
+
const hologramEnvelopeSchema = z.object({
|
|
46
|
+
success: z.boolean(),
|
|
47
|
+
data: z.unknown().nullish(),
|
|
48
|
+
error: z.string().nullish()
|
|
49
|
+
});
|
|
50
|
+
function hologramServiceState(state) {
|
|
51
|
+
if (!state) return "unknown";
|
|
52
|
+
if (state.startsWith("LIVE")) return "active";
|
|
53
|
+
if (state.startsWith("PAUSED")) return "paused";
|
|
54
|
+
if (state.startsWith("DEAD")) return "retired";
|
|
55
|
+
if (state.startsWith("INACTIVE") || state.startsWith("FACTORY") || state.startsWith("TEST")) return "inactive";
|
|
56
|
+
return "unknown";
|
|
57
|
+
}
|
|
58
|
+
function parseHologramConnectivity(value, expectedDeviceId, checkedAt) {
|
|
59
|
+
let json;
|
|
60
|
+
try {
|
|
61
|
+
json = JSON.parse(value);
|
|
62
|
+
} catch {
|
|
63
|
+
throw new UpstreamError("Hologram returned malformed JSON");
|
|
64
|
+
}
|
|
65
|
+
const envelope = hologramEnvelopeSchema.safeParse(json);
|
|
66
|
+
if (!envelope.success) throw new UpstreamError("Hologram returned an unrecognized envelope");
|
|
67
|
+
if (!envelope.data.success) throw new UpstreamError(`Hologram refused the request: ${envelope.data.error ?? "no reason"}`);
|
|
68
|
+
const device = hologramDeviceSchema.safeParse(envelope.data.data);
|
|
69
|
+
if (!device.success || device.data.id !== expectedDeviceId) throw new UpstreamError("Hologram returned the wrong device");
|
|
70
|
+
const session = device.data.lastsession ?? null;
|
|
71
|
+
const link = device.data.links?.cellular[0] ?? null;
|
|
72
|
+
const sessionBeganAt = hologramTimeToIso(session?.session_begin);
|
|
73
|
+
const planIncludedBytes = link?.plan?.data || null;
|
|
74
|
+
const overageLimitBytes = link?.overagelimit != null && link.overagelimit > 0 ? link.overagelimit : null;
|
|
75
|
+
return {
|
|
76
|
+
sourceLabel: "Hologram",
|
|
77
|
+
checkedAt,
|
|
78
|
+
deviceName: nonEmpty(device.data.name),
|
|
79
|
+
online: session?.active ?? null,
|
|
80
|
+
lastConnectedAt: hologramTimeToIso(link?.last_connect_time) ?? sessionBeganAt,
|
|
81
|
+
carrier: nonEmpty(link?.last_network_used) ?? nonEmpty(session?.network_name),
|
|
82
|
+
radioTechnology: nonEmpty(session?.radio_access_technology),
|
|
83
|
+
sim: {
|
|
84
|
+
service: hologramServiceState(link?.state),
|
|
85
|
+
vendorState: link?.state ?? null,
|
|
86
|
+
expiresAt: hologramTimeToIso(link?.whenexpires)
|
|
87
|
+
},
|
|
88
|
+
usage: {
|
|
89
|
+
currentPeriodBytes: link?.cur_billing_data_used ?? null,
|
|
90
|
+
previousPeriodBytes: link?.last_billing_data_used ?? null,
|
|
91
|
+
planName: nonEmpty(link?.plan?.name),
|
|
92
|
+
planIncludedBytes,
|
|
93
|
+
overageLimitBytes
|
|
94
|
+
},
|
|
95
|
+
lastSession: sessionBeganAt ? {
|
|
96
|
+
beganAt: sessionBeganAt,
|
|
97
|
+
endedAt: hologramTimeToIso(session?.session_end),
|
|
98
|
+
bytes: session?.bytes ?? null
|
|
99
|
+
} : null
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
async function loadHologramConnectivity(config, options = {}) {
|
|
103
|
+
const environment = resolveEnvironment(options.environment);
|
|
104
|
+
return parseHologramConnectivity(await fetchUpstreamText(environment, {
|
|
105
|
+
url: `${options.apiBase ?? "https://dashboard.hologram.io/api/1"}/devices/${config.deviceId}`,
|
|
106
|
+
cacheKey: `hologram/device/${config.deviceId}`,
|
|
107
|
+
cacheTtlSeconds: options.cacheTtlSeconds ?? 300,
|
|
108
|
+
subject: `Hologram device ${config.deviceId}`,
|
|
109
|
+
headers: { Authorization: `Basic ${btoa(`apikey:${config.apiKey}`)}` }
|
|
110
|
+
}), config.deviceId, environment.now().toISOString());
|
|
111
|
+
}
|
|
112
|
+
//#endregion
|
|
113
|
+
export { HOLOGRAM_API_BASE, TRIAL_HOLOGRAM_CACHE_TTL_SECONDS, hologramConnectivityConfigSchema, hologramServiceState, hologramTimeToIso, loadHologramConnectivity, parseHologramConnectivity };
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { normalizeWindnerdStationKey, windnerdStationUrl } from "../windnerd.js";
|
|
2
|
-
import { DEFAULT_USER_AGENT, FeedCache, LogEvent, LogEventCode, ResolvedEnvironment, ServerEnvironment, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError, UpstreamErrorReason, UpstreamFailureReason, UpstreamStreamRequest, UpstreamTextRequest, boundedResponseText, coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError } from "./environment.js";
|
|
3
|
-
import { CampbellStationConfig, CustomStationConfig, CustomStationContext, CustomStationIdentity, CustomStationLoader, StationConfig, StationConfigInput, TempestStationConfig, WindnerdStationConfig, campbellStationConfigSchema, customStationConfigSchema, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema } from "./config.js";
|
|
2
|
+
import { DEFAULT_USER_AGENT, FeedCache, LogEvent, LogEventCode, ResolvedEnvironment, ServerEnvironment, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError, UpstreamErrorReason, UpstreamFailureReason, UpstreamStreamRequest, UpstreamTextRequest, boundedResponseText, coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError, workersCache } from "./environment.js";
|
|
3
|
+
import { CampbellStationConfig, CustomStationConfig, CustomStationContext, CustomStationIdentity, CustomStationLoader, EcowittStationConfig, StationConfig, StationConfigInput, TempestStationConfig, WindnerdStationConfig, campbellStationConfigSchema, customStationConfigSchema, ecowittStationConfigSchema, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema } from "./config.js";
|
|
4
4
|
import { StationAdapter, StationAdapterContext, StationAdapterDefinition, StationAdapterMode, StationAdapterOptions, StationAdapterResult, defineStationAdapter } from "./adapter.js";
|
|
5
5
|
import { DEFAULT_HISTORY_HOURS, LoadStationCurrentOptions, LoadStationFeedOptions, OpenStationLiveOptions, StationLiveUnsupportedError, StationsInput, StationsResolver, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed, openStationLive } from "./feed.js";
|
|
6
6
|
import { StationFeedHandler, StationFeedHandlerOptions, StationFeedHandlerRoute, createStationFeedHandler } from "./handler.js";
|
|
7
7
|
import { STATION_LIVE_SSE_HEADERS, encodeStationLiveSse } from "./live.js";
|
|
8
8
|
import { WindnerdLiveOptions, openWindnerdLive } from "./adapters/windnerd-live.js";
|
|
9
9
|
import { WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, WindnerdAdapterOptions, WindnerdLiveDigest, WindnerdLiveInit, WindnerdLiveSampleRecord, WindnerdRecords, loadWindnerdStation, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl } from "./adapters/windnerd.js";
|
|
10
|
+
import { HOLOGRAM_API_BASE, HologramConnectivityConfig, HologramConnectivityOptions, TRIAL_HOLOGRAM_CACHE_TTL_SECONDS, hologramConnectivityConfigSchema, hologramServiceState, hologramTimeToIso, loadHologramConnectivity, parseHologramConnectivity } from "./hologram.js";
|
|
10
11
|
import { TempestAdapterOptions, TempestObservation, loadTempestStation, parseTempestWind } from "./adapters/tempest.js";
|
|
12
|
+
import { EcowittAdapterOptions, EcowittObservation, loadEcowittStation, parseEcowittRealTime } from "./adapters/ecowitt.js";
|
|
11
13
|
import { CAMPBELL_FIELD_CONTRACTS, CampbellAdapterOptions, CampbellTable, CampbellTableExpectation, loadCampbellCurrent, loadCampbellStation, naiveLocalToIso, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable } from "./adapters/campbell.js";
|
|
12
|
-
export { CAMPBELL_FIELD_CONTRACTS, type CampbellAdapterOptions, CampbellStationConfig, type CampbellTable, type CampbellTableExpectation, CustomStationConfig, CustomStationContext, CustomStationIdentity, CustomStationLoader, DEFAULT_HISTORY_HOURS, DEFAULT_USER_AGENT, FeedCache, LoadStationCurrentOptions, LoadStationFeedOptions, LogEvent, LogEventCode, OpenStationLiveOptions, ResolvedEnvironment, STATION_LIVE_SSE_HEADERS, ServerEnvironment, StationAdapter, StationAdapterContext, StationAdapterDefinition, StationAdapterMode, StationAdapterOptions, StationAdapterResult, StationConfig, StationConfigInput, StationFeedHandler, StationFeedHandlerOptions, StationFeedHandlerRoute, StationLiveUnsupportedError, StationsInput, StationsResolver, type TempestAdapterOptions, type TempestObservation, TempestStationConfig, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UnknownStationError, UpstreamError, type UpstreamErrorReason, type UpstreamFailureReason, UpstreamStreamRequest, UpstreamTextRequest, WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, type WindnerdAdapterOptions, type WindnerdLiveDigest, type WindnerdLiveInit, type WindnerdLiveOptions, type WindnerdLiveSampleRecord, type WindnerdRecords, WindnerdStationConfig, assembleStations, boundedResponseText, campbellStationConfigSchema, coalesceUpstreamLoad, createStationFeedHandler, customStationConfigSchema, defineStationAdapter, encodeStationLiveSse, fetchUpstreamStream, fetchUpstreamText, loadCampbellCurrent, loadCampbellStation, loadStationCurrent, loadStationFeed, loadTempestStation, loadWindnerdStation, logUpstreamFailure, memoryCache, naiveLocalToIso, normalizeWindnerdStationKey, openStationLive, openWindnerdLive, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable, parseStationConfig, parseTempestWind, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, resolveEnvironment, stationConfigSchema, tempestStationConfigSchema, unavailableReasonForError, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl, windnerdStationConfigSchema, windnerdStationUrl };
|
|
14
|
+
export { CAMPBELL_FIELD_CONTRACTS, type CampbellAdapterOptions, CampbellStationConfig, type CampbellTable, type CampbellTableExpectation, CustomStationConfig, CustomStationContext, CustomStationIdentity, CustomStationLoader, DEFAULT_HISTORY_HOURS, DEFAULT_USER_AGENT, type EcowittAdapterOptions, type EcowittObservation, EcowittStationConfig, FeedCache, HOLOGRAM_API_BASE, type HologramConnectivityConfig, type HologramConnectivityOptions, LoadStationCurrentOptions, LoadStationFeedOptions, LogEvent, LogEventCode, OpenStationLiveOptions, ResolvedEnvironment, STATION_LIVE_SSE_HEADERS, ServerEnvironment, StationAdapter, StationAdapterContext, StationAdapterDefinition, StationAdapterMode, StationAdapterOptions, StationAdapterResult, StationConfig, StationConfigInput, StationFeedHandler, StationFeedHandlerOptions, StationFeedHandlerRoute, StationLiveUnsupportedError, StationsInput, StationsResolver, TRIAL_HOLOGRAM_CACHE_TTL_SECONDS, type TempestAdapterOptions, type TempestObservation, TempestStationConfig, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UnknownStationError, UpstreamError, type UpstreamErrorReason, type UpstreamFailureReason, UpstreamStreamRequest, UpstreamTextRequest, WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, type WindnerdAdapterOptions, type WindnerdLiveDigest, type WindnerdLiveInit, type WindnerdLiveOptions, type WindnerdLiveSampleRecord, type WindnerdRecords, WindnerdStationConfig, assembleStations, boundedResponseText, campbellStationConfigSchema, coalesceUpstreamLoad, createStationFeedHandler, customStationConfigSchema, defineStationAdapter, ecowittStationConfigSchema, encodeStationLiveSse, fetchUpstreamStream, fetchUpstreamText, hologramConnectivityConfigSchema, hologramServiceState, hologramTimeToIso, loadCampbellCurrent, loadCampbellStation, loadEcowittStation, loadHologramConnectivity, loadStationCurrent, loadStationFeed, loadTempestStation, loadWindnerdStation, logUpstreamFailure, memoryCache, naiveLocalToIso, normalizeWindnerdStationKey, openStationLive, openWindnerdLive, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable, parseEcowittRealTime, parseHologramConnectivity, parseStationConfig, parseTempestWind, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, resolveEnvironment, stationConfigSchema, tempestStationConfigSchema, unavailableReasonForError, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl, windnerdStationConfigSchema, windnerdStationUrl, workersCache };
|
package/dist/server/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { normalizeWindnerdStationKey, windnerdStationUrl } from "../windnerd.js";
|
|
2
|
-
import { DEFAULT_USER_AGENT, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError, boundedResponseText, coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError } from "./environment.js";
|
|
3
|
-
import { campbellStationConfigSchema, customStationConfigSchema, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema } from "./config.js";
|
|
2
|
+
import { DEFAULT_USER_AGENT, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError, boundedResponseText, coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError, workersCache } from "./environment.js";
|
|
3
|
+
import { campbellStationConfigSchema, customStationConfigSchema, ecowittStationConfigSchema, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema } from "./config.js";
|
|
4
4
|
import { CAMPBELL_FIELD_CONTRACTS, loadCampbellCurrent, loadCampbellStation, naiveLocalToIso, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable } from "./adapters/campbell.js";
|
|
5
|
+
import { loadEcowittStation, parseEcowittRealTime } from "./adapters/ecowitt.js";
|
|
5
6
|
import { loadTempestStation, parseTempestWind } from "./adapters/tempest.js";
|
|
6
7
|
import { WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, loadWindnerdStation, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl } from "./adapters/windnerd.js";
|
|
7
8
|
import { openWindnerdLive } from "./adapters/windnerd-live.js";
|
|
@@ -9,4 +10,5 @@ import { DEFAULT_HISTORY_HOURS, StationLiveUnsupportedError, UnknownStationError
|
|
|
9
10
|
import { defineStationAdapter } from "./adapter.js";
|
|
10
11
|
import { STATION_LIVE_SSE_HEADERS, encodeStationLiveSse } from "./live.js";
|
|
11
12
|
import { createStationFeedHandler } from "./handler.js";
|
|
12
|
-
|
|
13
|
+
import { HOLOGRAM_API_BASE, TRIAL_HOLOGRAM_CACHE_TTL_SECONDS, hologramConnectivityConfigSchema, hologramServiceState, hologramTimeToIso, loadHologramConnectivity, parseHologramConnectivity } from "./hologram.js";
|
|
14
|
+
export { CAMPBELL_FIELD_CONTRACTS, DEFAULT_HISTORY_HOURS, DEFAULT_USER_AGENT, HOLOGRAM_API_BASE, STATION_LIVE_SSE_HEADERS, StationLiveUnsupportedError, TRIAL_HOLOGRAM_CACHE_TTL_SECONDS, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UnknownStationError, UpstreamError, WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, assembleStations, boundedResponseText, campbellStationConfigSchema, coalesceUpstreamLoad, createStationFeedHandler, customStationConfigSchema, defineStationAdapter, ecowittStationConfigSchema, encodeStationLiveSse, fetchUpstreamStream, fetchUpstreamText, hologramConnectivityConfigSchema, hologramServiceState, hologramTimeToIso, loadCampbellCurrent, loadCampbellStation, loadEcowittStation, loadHologramConnectivity, loadStationCurrent, loadStationFeed, loadTempestStation, loadWindnerdStation, logUpstreamFailure, memoryCache, naiveLocalToIso, normalizeWindnerdStationKey, openStationLive, openWindnerdLive, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable, parseEcowittRealTime, parseHologramConnectivity, parseStationConfig, parseTempestWind, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, resolveEnvironment, stationConfigSchema, tempestStationConfigSchema, unavailableReasonForError, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl, windnerdStationConfigSchema, windnerdStationUrl, workersCache };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@azohra/meteo.station",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "The station capability of meteo by Azohra: live weather-station reading, derivation, and display - the wire contract, provider adapters, a polling client, a Node server, and React and custom-element display bindings.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"weather-station",
|