@khalido/home 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/.env.example +25 -0
  2. package/CHANGELOG.md +25 -0
  3. package/LICENSE +21 -0
  4. package/README.md +77 -2
  5. package/dist/clock.d.ts +17 -0
  6. package/dist/clock.js +43 -0
  7. package/dist/config.d.ts +273 -0
  8. package/dist/config.js +392 -0
  9. package/dist/connector.d.ts +34 -0
  10. package/dist/connector.js +47 -0
  11. package/dist/connectors/amber/client.d.ts +61 -0
  12. package/dist/connectors/amber/client.js +106 -0
  13. package/dist/connectors/amber/index.d.ts +30 -0
  14. package/dist/connectors/amber/index.js +94 -0
  15. package/dist/connectors/cast/codec.d.ts +38 -0
  16. package/dist/connectors/cast/codec.js +102 -0
  17. package/dist/connectors/cast/index.d.ts +60 -0
  18. package/dist/connectors/cast/index.js +426 -0
  19. package/dist/connectors/cast/schemas.d.ts +167 -0
  20. package/dist/connectors/cast/schemas.js +87 -0
  21. package/dist/connectors/cast/serve.d.ts +11 -0
  22. package/dist/connectors/cast/serve.js +57 -0
  23. package/dist/connectors/cast/state.d.ts +62 -0
  24. package/dist/connectors/cast/state.js +133 -0
  25. package/dist/connectors/cast/tls.d.ts +3 -0
  26. package/dist/connectors/cast/tls.js +67 -0
  27. package/dist/connectors/cast/writes.d.ts +80 -0
  28. package/dist/connectors/cast/writes.js +390 -0
  29. package/dist/connectors/daikin/client.d.ts +65 -0
  30. package/dist/connectors/daikin/client.js +221 -0
  31. package/dist/connectors/daikin/index.d.ts +41 -0
  32. package/dist/connectors/daikin/index.js +108 -0
  33. package/dist/connectors/enphase/client.d.ts +65 -0
  34. package/dist/connectors/enphase/client.js +173 -0
  35. package/dist/connectors/enphase/index.d.ts +43 -0
  36. package/dist/connectors/enphase/index.js +174 -0
  37. package/dist/connectors/enphase/schemas.d.ts +51 -0
  38. package/dist/connectors/enphase/schemas.js +34 -0
  39. package/dist/connectors/hue/client.d.ts +48 -0
  40. package/dist/connectors/hue/client.js +95 -0
  41. package/dist/connectors/hue/events.d.ts +41 -0
  42. package/dist/connectors/hue/events.js +156 -0
  43. package/dist/connectors/hue/index.d.ts +42 -0
  44. package/dist/connectors/hue/index.js +205 -0
  45. package/dist/connectors/hue/schemas.d.ts +65 -0
  46. package/dist/connectors/hue/schemas.js +48 -0
  47. package/dist/connectors/hue/state.d.ts +43 -0
  48. package/dist/connectors/hue/state.js +84 -0
  49. package/dist/connectors/printers/client.d.ts +28 -0
  50. package/dist/connectors/printers/client.js +74 -0
  51. package/dist/connectors/printers/codec.d.ts +76 -0
  52. package/dist/connectors/printers/codec.js +246 -0
  53. package/dist/connectors/printers/found.d.ts +15 -0
  54. package/dist/connectors/printers/found.js +35 -0
  55. package/dist/connectors/printers/index.d.ts +52 -0
  56. package/dist/connectors/printers/index.js +282 -0
  57. package/dist/connectors/printers/state.d.ts +60 -0
  58. package/dist/connectors/printers/state.js +99 -0
  59. package/dist/connectors/spotify/changes.d.ts +32 -0
  60. package/dist/connectors/spotify/changes.js +84 -0
  61. package/dist/connectors/spotify/client.d.ts +199 -0
  62. package/dist/connectors/spotify/client.js +270 -0
  63. package/dist/connectors/spotify/index.d.ts +92 -0
  64. package/dist/connectors/spotify/index.js +745 -0
  65. package/dist/connectors/up/client.d.ts +183 -0
  66. package/dist/connectors/up/client.js +308 -0
  67. package/dist/connectors/up/index.d.ts +91 -0
  68. package/dist/connectors/up/index.js +213 -0
  69. package/dist/connectors/up/spend.d.ts +78 -0
  70. package/dist/connectors/up/spend.js +213 -0
  71. package/dist/connectors/up/webhook.d.ts +13 -0
  72. package/dist/connectors/up/webhook.js +32 -0
  73. package/dist/connectors/weather/blocks.d.ts +51 -0
  74. package/dist/connectors/weather/blocks.js +106 -0
  75. package/dist/connectors/weather/bom.d.ts +37 -0
  76. package/dist/connectors/weather/bom.js +237 -0
  77. package/dist/connectors/weather/ftp.d.ts +5 -0
  78. package/dist/connectors/weather/ftp.js +46 -0
  79. package/dist/connectors/weather/google.d.ts +31 -0
  80. package/dist/connectors/weather/google.js +364 -0
  81. package/dist/connectors/weather/index.d.ts +53 -0
  82. package/dist/connectors/weather/index.js +267 -0
  83. package/dist/connectors/weather/open-meteo.d.ts +15 -0
  84. package/dist/connectors/weather/open-meteo.js +285 -0
  85. package/dist/connectors/weather/rain.d.ts +19 -0
  86. package/dist/connectors/weather/rain.js +51 -0
  87. package/dist/connectors/weather/source.d.ts +149 -0
  88. package/dist/connectors/weather/source.js +77 -0
  89. package/dist/connectors/weather/sun.d.ts +48 -0
  90. package/dist/connectors/weather/sun.js +65 -0
  91. package/dist/discover.d.ts +195 -0
  92. package/dist/discover.js +446 -0
  93. package/dist/energy.d.ts +61 -0
  94. package/dist/energy.js +162 -0
  95. package/dist/finders-entry.d.ts +1 -0
  96. package/dist/finders-entry.js +2 -0
  97. package/dist/finders.d.ts +45 -0
  98. package/dist/finders.js +173 -0
  99. package/dist/health.d.ts +28 -0
  100. package/dist/health.js +35 -0
  101. package/dist/home.d.ts +81 -0
  102. package/dist/home.js +114 -0
  103. package/dist/index.d.ts +11 -0
  104. package/dist/index.js +11 -0
  105. package/dist/lane.d.ts +17 -0
  106. package/dist/lane.js +74 -0
  107. package/dist/locate.d.ts +27 -0
  108. package/dist/locate.js +59 -0
  109. package/dist/manifest.d.ts +31 -0
  110. package/dist/manifest.js +4 -0
  111. package/dist/manifests.d.ts +5 -0
  112. package/dist/manifests.js +23 -0
  113. package/dist/node-fetch.d.ts +9 -0
  114. package/dist/node-fetch.js +25 -0
  115. package/dist/poll.d.ts +10 -0
  116. package/dist/poll.js +33 -0
  117. package/docs/cast.md +133 -0
  118. package/docs/cli.md +39 -0
  119. package/docs/config.md +36 -0
  120. package/docs/decisions.md +150 -0
  121. package/docs/devices.md +128 -0
  122. package/docs/enphase-notes.md +24 -0
  123. package/docs/google.md +92 -0
  124. package/docs/ideas.md +69 -0
  125. package/docs/matter.md +55 -0
  126. package/docs/performance.md +12 -0
  127. package/docs/philosophy.md +23 -0
  128. package/docs/up.md +84 -0
  129. package/docs/using.md +65 -0
  130. package/docs/weather-probe.md +63 -0
  131. package/examples/home.jsonc +74 -0
  132. package/examples/home.svg +76 -0
  133. package/home.schema.json +474 -0
  134. package/llms.txt +32 -0
  135. package/package.json +143 -4
  136. package/skills/draw-home/README.md +26 -0
  137. package/skills/draw-home/SKILL.md +82 -0
  138. package/skills/use-home/SKILL.md +86 -0
  139. package/src/cli/cache.ts +29 -0
  140. package/src/cli/cast.ts +172 -0
  141. package/src/cli/config.ts +52 -0
  142. package/src/cli/context.ts +118 -0
  143. package/src/cli/discover.ts +175 -0
  144. package/src/cli/enphase.ts +62 -0
  145. package/src/cli/hue.ts +124 -0
  146. package/src/cli/locate.ts +47 -0
  147. package/src/cli/main.ts +182 -0
  148. package/src/cli/printers.ts +21 -0
  149. package/src/cli/probe.ts +274 -0
  150. package/src/cli/spotify.ts +76 -0
  151. package/src/cli/status.ts +228 -0
  152. package/src/cli/up.ts +350 -0
  153. package/src/clock.ts +62 -0
  154. package/src/config.ts +578 -0
  155. package/src/connector.ts +77 -0
  156. package/src/connectors/amber/README.md +40 -0
  157. package/src/connectors/amber/client.ts +157 -0
  158. package/src/connectors/amber/index.ts +118 -0
  159. package/src/connectors/cast/README.md +43 -0
  160. package/src/connectors/cast/codec.ts +126 -0
  161. package/src/connectors/cast/index.ts +551 -0
  162. package/src/connectors/cast/schemas.ts +101 -0
  163. package/src/connectors/cast/serve.ts +72 -0
  164. package/src/connectors/cast/state.ts +203 -0
  165. package/src/connectors/cast/tls.ts +100 -0
  166. package/src/connectors/cast/writes.ts +572 -0
  167. package/src/connectors/daikin/README.md +78 -0
  168. package/src/connectors/daikin/client.ts +295 -0
  169. package/src/connectors/daikin/index.ts +145 -0
  170. package/src/connectors/enphase/README.md +64 -0
  171. package/src/connectors/enphase/client.ts +244 -0
  172. package/src/connectors/enphase/index.ts +241 -0
  173. package/src/connectors/enphase/schemas.ts +45 -0
  174. package/src/connectors/hue/README.md +50 -0
  175. package/src/connectors/hue/client.ts +157 -0
  176. package/src/connectors/hue/events.ts +182 -0
  177. package/src/connectors/hue/index.ts +261 -0
  178. package/src/connectors/hue/schemas.ts +60 -0
  179. package/src/connectors/hue/state.ts +124 -0
  180. package/src/connectors/printers/README.md +46 -0
  181. package/src/connectors/printers/client.ts +114 -0
  182. package/src/connectors/printers/codec.ts +292 -0
  183. package/src/connectors/printers/found.ts +46 -0
  184. package/src/connectors/printers/index.ts +385 -0
  185. package/src/connectors/printers/state.ts +182 -0
  186. package/src/connectors/spotify/README.md +80 -0
  187. package/src/connectors/spotify/changes.ts +127 -0
  188. package/src/connectors/spotify/client.ts +387 -0
  189. package/src/connectors/spotify/index.ts +929 -0
  190. package/src/connectors/up/README.md +35 -0
  191. package/src/connectors/up/client.ts +518 -0
  192. package/src/connectors/up/index.ts +370 -0
  193. package/src/connectors/up/spend.ts +280 -0
  194. package/src/connectors/up/webhook.ts +62 -0
  195. package/src/connectors/weather/README.md +84 -0
  196. package/src/connectors/weather/blocks.ts +173 -0
  197. package/src/connectors/weather/bom.ts +344 -0
  198. package/src/connectors/weather/ftp.ts +48 -0
  199. package/src/connectors/weather/google.ts +425 -0
  200. package/src/connectors/weather/index.ts +380 -0
  201. package/src/connectors/weather/open-meteo.ts +309 -0
  202. package/src/connectors/weather/rain.ts +73 -0
  203. package/src/connectors/weather/source.ts +236 -0
  204. package/src/connectors/weather/sun.ts +114 -0
  205. package/src/discover.ts +634 -0
  206. package/src/energy.ts +221 -0
  207. package/src/finders-entry.ts +2 -0
  208. package/src/finders.ts +247 -0
  209. package/src/health.ts +74 -0
  210. package/src/home.ts +205 -0
  211. package/src/index.ts +62 -0
  212. package/src/lane.ts +110 -0
  213. package/src/locate.ts +85 -0
  214. package/src/manifest.ts +43 -0
  215. package/src/manifests.ts +27 -0
  216. package/src/node-fetch.ts +41 -0
  217. package/src/poll.ts +33 -0
@@ -0,0 +1,73 @@
1
+ import { RAIN_HORIZON_MINUTES, type WeatherRain } from "./source.ts";
2
+
3
+ /** What the rain forecast says about the next stretch. The one owner: every consumer calls `rainSoon`. */
4
+ export type RainSoon = {
5
+ wet: boolean; // rain somewhere in the covered part of the window
6
+ startsInMin?: number; // 0 when it is raining now
7
+ endsInMin?: number; // when the first wet stretch ends; missing when it runs past the window or the forecast stops while it is still wet
8
+ chance?: number; // percent, the highest in that stretch
9
+ mm?: number; // total over that stretch; missing if any segment lacks an amount
10
+ intensity?: string; // the heaviest in that stretch
11
+ type?: string; // the source's own, of the first wet segment
12
+ coveredMin: number; // how much of the window the forecast actually covers
13
+ };
14
+
15
+ const WET = (type?: string) => type !== undefined && type !== "NONE";
16
+ /** Google's intensities, lightest first. An unknown one is noted by the source, never ranked. */
17
+ export const RAIN_INTENSITIES = ["NO_INTENSITY", "LIGHT", "MODERATE", "HEAVY"];
18
+ const minutes = (ms: number) => Math.round(ms / 60_000);
19
+
20
+ /**
21
+ * Rain in the next `windowMin` minutes from `at` (epoch ms). A segment counts while its end is still ahead, so one that began a few minutes ago is used.
22
+ * A segment with no `type` is unknown, not dry: it adds nothing to `coveredMin`. Returns nothing when the forecast covers none of the window.
23
+ */
24
+ export function rainSoon(
25
+ rain: WeatherRain | undefined,
26
+ at: number,
27
+ windowMin = RAIN_HORIZON_MINUTES,
28
+ ): RainSoon | undefined {
29
+ if (!rain) return undefined;
30
+ const end = at + windowMin * 60_000;
31
+ const segs = rain.segments
32
+ .map((s) => ({ ...s, f: Date.parse(s.from), t: Date.parse(s.to) }))
33
+ .filter((s) => s.t > at && s.f < end && s.type !== undefined)
34
+ .sort((a, b) => a.f - b.f);
35
+ const covered = segs.reduce(
36
+ (sum, s) => sum + Math.min(s.t, end) - Math.max(s.f, at),
37
+ 0,
38
+ );
39
+ if (covered <= 0) return undefined;
40
+ const coveredMin = minutes(covered);
41
+ const first = segs.findIndex((s) => WET(s.type));
42
+ if (first < 0) return { wet: false, coveredMin };
43
+ let last = first;
44
+ while (
45
+ last + 1 < segs.length &&
46
+ WET(segs[last + 1]!.type) &&
47
+ segs[last + 1]!.f <= segs[last]!.t
48
+ )
49
+ last++;
50
+ const run = segs.slice(first, last + 1);
51
+ const chances = run.map((s) => s.chance).filter((c) => c !== undefined);
52
+ const mms = run.map((s) => s.mm);
53
+ const heaviest = run
54
+ .map((s) => s.intensity)
55
+ .filter((i) => i !== undefined)
56
+ .sort(
57
+ (a, b) => RAIN_INTENSITIES.indexOf(b) - RAIN_INTENSITIES.indexOf(a),
58
+ )[0];
59
+ const runEnd = run[run.length - 1]!.t;
60
+ const after = segs[last + 1]; // a known dry segment right after the run proves it ended
61
+ return {
62
+ wet: true,
63
+ startsInMin: Math.max(0, minutes(run[0]!.f - at)),
64
+ endsInMin: after && after.f <= runEnd ? minutes(runEnd - at) : undefined,
65
+ chance: chances.length ? Math.max(...chances) : undefined,
66
+ mm: mms.every((m) => m !== undefined)
67
+ ? mms.reduce((sum, m) => sum + m!, 0)
68
+ : undefined,
69
+ intensity: heaviest,
70
+ type: run[0]!.type,
71
+ coveredMin,
72
+ };
73
+ }
@@ -0,0 +1,236 @@
1
+ import { ConnectorError, fetchTimeout } from "../../connector.ts";
2
+
3
+ // The one place a weather provider plugs in: a `WeatherSource` returns slices, and `mergeWeather` picks one per slice.
4
+
5
+ /** Sent on every request, so each service can see who is calling rather than a runtime's default string. */
6
+ export const USER_AGENT = "home (+https://github.com/khalido/home.ts)";
7
+
8
+ export type Place = { latitude: number; longitude: number };
9
+
10
+ /** The one polling number for observations and sky: every 15 minutes, KO's call. Forecasts follow their issue times. */
11
+ export const DEFAULT_POLL_MINUTES = 15;
12
+ /** Reads land this far past each slot, so BOM's 10-minutely file (sent about 3 minutes past) is there: :05, :20, :35, :50. */
13
+ const SLOT_OFFSET_MS = 5 * 60_000;
14
+
15
+ /** The next read slot after `at`: every `pollMinutes` from 5 minutes past the hour when `pollMinutes` divides 60 (else from the epoch, plus 5 minutes). */
16
+ export function nextPoll(
17
+ at: number,
18
+ pollMinutes = DEFAULT_POLL_MINUTES,
19
+ ): number {
20
+ const step = pollMinutes * 60_000;
21
+ return (
22
+ Math.floor((at - SLOT_OFFSET_MS) / step) * step + step + SLOT_OFFSET_MS
23
+ );
24
+ }
25
+
26
+ /** What a source is asked to read: where, at what instant (epoch ms), the polling interval to schedule by, and `force` to read everything now. */
27
+ export type ReadRequest = {
28
+ place: Place;
29
+ at: number;
30
+ pollMinutes: number;
31
+ force?: boolean;
32
+ signal?: AbortSignal;
33
+ };
34
+
35
+ /** Every slice says who made it, whether it is a model rather than an instrument, the time it is for, and when it was fetched. */
36
+ export type SliceMeta = {
37
+ source: string;
38
+ modelled: boolean;
39
+ at: string;
40
+ fetchedAt: string;
41
+ };
42
+
43
+ /** Outside now. Speeds in km/h, direction where the wind comes from. */
44
+ export type WeatherNow = SliceMeta & {
45
+ tempC?: number;
46
+ apparentC?: number;
47
+ humidity?: number; // percent
48
+ windKmh?: number;
49
+ windDir?: string; // compass point as the source gives it, e.g. "ESE"
50
+ windDeg?: number;
51
+ gustKmh?: number;
52
+ rainMm?: number; // rain since 9am, over rainFrom..rainTo, which can differ from `at`
53
+ rainFrom?: string;
54
+ rainTo?: string;
55
+ station?: { name: string; distanceKm: number };
56
+ };
57
+
58
+ /** One forecast day. Any field can be missing: after BOM's afternoon issue, today has no min, max or rain range. */
59
+ export type ForecastDay = {
60
+ date: string; // local YYYY-MM-DD
61
+ minC?: number;
62
+ maxC?: number;
63
+ rainChance?: number; // percent
64
+ rainMm?: number; // a model's single amount
65
+ rainRangeMm?: [number, number]; // a forecaster's range, e.g. "0 to 1 mm"
66
+ text?: string;
67
+ code?: string; // the source's own icon or condition code (BOM 1–19, WMO for Open-Meteo, a type name for Google)
68
+ };
69
+
70
+ export type WeatherForecast = SliceMeta & {
71
+ issuedAt?: string;
72
+ today?: ForecastDay;
73
+ tomorrow?: ForecastDay;
74
+ };
75
+
76
+ /** Cloud, UV and sunlight on the ground. `radiationWm2` is shortwave (global horizontal) irradiance. */
77
+ export type SkyHour = {
78
+ at: string;
79
+ cloudPct?: number;
80
+ uvIndex?: number;
81
+ radiationWm2?: number;
82
+ };
83
+ export type WeatherSky = SliceMeta & Omit<SkyHour, "at"> & { hours: SkyHour[] };
84
+
85
+ /** One stretch of the minute-by-minute rain forecast. `from` and `to` are UTC ISO; `type` is the source's own (`NONE`, `RAIN`, ...). */
86
+ export type RainSegment = {
87
+ from: string;
88
+ to: string;
89
+ type?: string;
90
+ chance?: number;
91
+ mm?: number;
92
+ intensity?: string;
93
+ };
94
+ /** Rain minute by minute, up to `RAIN_HORIZON_MINUTES` ahead. `at` is when the forecast starts. Ask `rainSoon` what it means. */
95
+ export type WeatherRain = SliceMeta & { segments: RainSegment[] };
96
+ /** How far ahead the rain forecast is kept and read: two hours, KO's call. */
97
+ export const RAIN_HORIZON_MINUTES = 120;
98
+
99
+ /** Weather in words, mildest first, so an hour from any source reads the same and a stretch of hours takes its worst. */
100
+ export const CONDITIONS = [
101
+ "clear",
102
+ "partly cloudy",
103
+ "cloudy",
104
+ "fog",
105
+ "drizzle",
106
+ "showers",
107
+ "rain",
108
+ "snow",
109
+ "storm",
110
+ ] as const;
111
+ export type Condition = (typeof CONDITIONS)[number];
112
+
113
+ /** One forecast hour, starting at `at`. `rainChance` in percent, `rainMm` over the hour, `code` the source's own, `condition` it in a word. */
114
+ export type ForecastHour = {
115
+ at: string;
116
+ tempC?: number;
117
+ apparentC?: number;
118
+ rainChance?: number;
119
+ rainMm?: number;
120
+ windKmh?: number;
121
+ gustKmh?: number;
122
+ cloudPct?: number;
123
+ uvIndex?: number;
124
+ code?: string;
125
+ condition?: Condition;
126
+ };
127
+ /** The hourly forecast for today and tomorrow, from the home's midnight. `at` is when it was read. Ask `dayBlocks` for mornings and evenings. */
128
+ export type WeatherHourly = SliceMeta & { hours: ForecastHour[] };
129
+
130
+ export type SliceName = "now" | "forecast" | "hourly" | "sky" | "rain";
131
+ export type Slices = {
132
+ now?: WeatherNow;
133
+ forecast?: WeatherForecast;
134
+ hourly?: WeatherHourly;
135
+ sky?: WeatherSky;
136
+ rain?: WeatherRain;
137
+ };
138
+
139
+ /** One read of a source: the slices it has (last good ones included), when to call again, and anything to report. */
140
+ export type SourceReading = Slices & {
141
+ nextAt: number; // epoch ms; the integration never calls sooner
142
+ problem?: string; // a failed product, a missing option; the source keeps going
143
+ anomaly?: string; // a value the source sent that could not be read as given
144
+ stop?: string; // a terminal problem (a rejected key): the integration stops calling this source
145
+ };
146
+
147
+ /**
148
+ * A weather provider. `owns` names the slices it can fill and how old each may get (by its `at`, beyond one polling
149
+ * interval) before the next source's is used. `read` fetches what is due and returns every slice it holds; it throws only on a bug.
150
+ */
151
+ export type WeatherSource = {
152
+ name: string;
153
+ owns: Partial<Record<SliceName, number>>; // slice → ms of age allowed on top of one polling interval
154
+ minPollMinutes?: number; // a floor under the shared interval, for a source billed per call
155
+ read(request: ReadRequest): Promise<SourceReading>;
156
+ };
157
+
158
+ /** The interval a source actually reads at: the shared `pollMinutes`, or its own floor if that is longer. */
159
+ export const sourcePollMinutes = (source: WeatherSource, pollMinutes: number) =>
160
+ Math.max(pollMinutes, source.minPollMinutes ?? 0);
161
+
162
+ /** Hourly: how often forecast and hourly-sky reads happen where nothing documented changes faster. */
163
+ export const HOURLY_MINUTES = 60;
164
+
165
+ /**
166
+ * One owner for which source fills each slice, so the integration and `home status` show the same thing.
167
+ * `readings` are in preference order; a slice older than its source's `owns` age plus one polling interval falls through.
168
+ */
169
+ export function mergeWeather(
170
+ readings: { source: WeatherSource; reading?: SourceReading }[],
171
+ at: number,
172
+ pollMinutes = DEFAULT_POLL_MINUTES,
173
+ ): Slices {
174
+ const pick = <K extends SliceName>(name: K): Slices[K] => {
175
+ for (const { source, reading } of readings) {
176
+ const slice = reading?.[name];
177
+ const maxAge = source.owns[name];
178
+ if (
179
+ slice &&
180
+ maxAge !== undefined &&
181
+ at - Date.parse(slice.at) <=
182
+ maxAge + sourcePollMinutes(source, pollMinutes) * 60_000
183
+ )
184
+ return slice;
185
+ }
186
+ return undefined;
187
+ };
188
+ return {
189
+ now: pick("now"),
190
+ forecast: pick("forecast"),
191
+ hourly: pick("hourly"),
192
+ sky: pick("sky"),
193
+ rain: pick("rain"),
194
+ };
195
+ }
196
+
197
+ /** GET a URL as text (BOM's XML), with the timeout and user agent every source sends. A non-ok status throws `ConnectorError` with it. */
198
+ export async function getText(
199
+ fetcher: typeof fetch,
200
+ url: string,
201
+ signal?: AbortSignal,
202
+ ): Promise<string> {
203
+ const res = await fetchTimeout(
204
+ fetcher,
205
+ url,
206
+ { headers: { "user-agent": USER_AGENT } },
207
+ { signal },
208
+ );
209
+ if (!res.ok)
210
+ throw new ConnectorError(
211
+ `HTTP ${res.status} on GET ${new URL(url).pathname}`,
212
+ { status: res.status },
213
+ );
214
+ return res.text();
215
+ }
216
+
217
+ /** A number from a string the source sent, or undefined plus a note in `odd`. Never rounds or clamps. */
218
+ export function num(
219
+ value: unknown,
220
+ what: string,
221
+ odd: string[],
222
+ ): number | undefined {
223
+ if (value === undefined || value === null || value === "") return undefined;
224
+ const n = typeof value === "number" ? value : Number(value);
225
+ if (Number.isFinite(n)) return n;
226
+ odd.push(`${what} is not a number: ${String(value)}`);
227
+ return undefined;
228
+ }
229
+
230
+ /** A source's timestamp as UTC ISO, or undefined when it does not parse: one odd time never sinks a whole read. */
231
+ export const iso = (s: string | undefined) =>
232
+ s && !Number.isNaN(Date.parse(s)) ? new Date(s).toISOString() : undefined;
233
+
234
+ /** The local calendar date (YYYY-MM-DD) of an instant at a UTC offset in seconds. */
235
+ export const localDate = (at: number, offsetSeconds: number) =>
236
+ new Date(at + offsetSeconds * 1000).toISOString().slice(0, 10);
@@ -0,0 +1,114 @@
1
+ import { getPosition, getTimes } from "suncalc";
2
+
3
+ const DAY_MS = 86_400_000;
4
+
5
+ /** The next of each event after `at`: today's while it is still ahead, else tomorrow's; missing when that day has none (polar). */
6
+ export type SunNext = {
7
+ dawn?: string;
8
+ sunrise?: string;
9
+ sunset?: string;
10
+ dusk?: string;
11
+ };
12
+
13
+ /**
14
+ * The sun at a place and instant, computed locally (suncalc 2: degrees, azimuth clockwise from north). No network.
15
+ * Times are ISO instants for the local solar day containing `at` (the one whose solar noon is nearest); any can be
16
+ * missing at high latitudes when the sun never reaches that altitude.
17
+ *
18
+ * `sunNow(latitude, longitude, now)` is the owner. The weather snapshot holds one recomputed every 5 minutes, so its
19
+ * position, `rising`, `daylight` and `next` can be that old; a consumer that shows them calls `sunNow` with its own clock,
20
+ * as `home status` does.
21
+ */
22
+ export type SunNow = {
23
+ at: string;
24
+ nightEnd?: string; // astronomical dawn, sun 18° below the horizon
25
+ dawn?: string; // civil dawn, 6° below
26
+ sunrise?: string; // missing on a polar day or night
27
+ goldenHourEnd?: string; // morning golden hour ends, 6° above
28
+ solarNoon: string;
29
+ goldenHour?: string; // evening golden hour starts, 6° above
30
+ sunset?: string;
31
+ dusk?: string; // civil dusk, 6° below
32
+ night?: string; // astronomical dusk, 18° below
33
+ azimuthDeg: number; // 0 north, 90 east
34
+ altitudeDeg: number; // refraction-corrected; negative below the horizon
35
+ rising: boolean; // before solar noon: the sun is climbing (from solar midnight)
36
+ daylight: boolean; // altitude above 0°
37
+ next: SunNext;
38
+ alwaysUp?: boolean;
39
+ alwaysDown?: boolean;
40
+ };
41
+
42
+ const isoOf = (d: Date | null) => d?.toISOString();
43
+
44
+ /** One owner for the sun's numbers. `at` is epoch ms. */
45
+ export function sunNow(
46
+ latitude: number,
47
+ longitude: number,
48
+ at: number,
49
+ ): SunNow {
50
+ const date = new Date(at);
51
+ const times = getTimes(date, latitude, longitude);
52
+ const tomorrow = getTimes(new Date(at + DAY_MS), latitude, longitude);
53
+ const { azimuth, altitude } = getPosition(date, latitude, longitude);
54
+ const next = (name: "dawn" | "sunrise" | "sunset" | "dusk") => {
55
+ const today = times[name];
56
+ return today && today.getTime() > at
57
+ ? today.toISOString()
58
+ : isoOf(tomorrow[name]);
59
+ };
60
+ return {
61
+ at: date.toISOString(),
62
+ nightEnd: isoOf(times.nightEnd),
63
+ dawn: isoOf(times.dawn),
64
+ sunrise: isoOf(times.sunrise),
65
+ goldenHourEnd: isoOf(times.goldenHourEnd),
66
+ solarNoon: times.solarNoon.toISOString(),
67
+ goldenHour: isoOf(times.goldenHour),
68
+ sunset: isoOf(times.sunset),
69
+ dusk: isoOf(times.dusk),
70
+ night: isoOf(times.night),
71
+ azimuthDeg: azimuth,
72
+ altitudeDeg: altitude,
73
+ rising: at < times.solarNoon.getTime(),
74
+ daylight: altitude > 0,
75
+ next: {
76
+ dawn: next("dawn"),
77
+ sunrise: next("sunrise"),
78
+ sunset: next("sunset"),
79
+ dusk: next("dusk"),
80
+ },
81
+ alwaysUp: times.alwaysUp,
82
+ alwaysDown: times.alwaysDown,
83
+ };
84
+ }
85
+
86
+ /** How far a source's sunrise or sunset may be from the computed one before it is worth saying. */
87
+ export const SUN_TOLERANCE_MS = 2 * 60_000;
88
+
89
+ /**
90
+ * A source's sunrise and sunset checked against the computed sun, which stays the owner: a note per event more than
91
+ * two minutes out, else undefined. Each is compared with the nearest computed event of the solar days either side of it,
92
+ * so near solar midnight at high latitude, where the solar day containing it can be the neighbouring one, it still pairs.
93
+ */
94
+ export function sunDisagrees(
95
+ source: string,
96
+ latitude: number,
97
+ longitude: number,
98
+ reported: { sunrise?: string; sunset?: string },
99
+ ): string | undefined {
100
+ const notes = (["sunrise", "sunset"] as const).flatMap((name) => {
101
+ const t = Date.parse(reported[name] ?? "");
102
+ if (Number.isNaN(t)) return [];
103
+ const nearest = [t - DAY_MS, t, t + DAY_MS]
104
+ .map((day) => sunNow(latitude, longitude, day)[name])
105
+ .filter((c) => c !== undefined)
106
+ .map((c) => ({ computed: c, offMs: Math.abs(t - Date.parse(c)) }))
107
+ .sort((a, b) => a.offMs - b.offMs)[0];
108
+ if (nearest && nearest.offMs <= SUN_TOLERANCE_MS) return [];
109
+ return [
110
+ `${source} ${name} ${reported[name]} ${nearest ? `is ${(nearest.offMs / 60_000).toFixed(1)} min from the computed ${nearest.computed}` : "on a day the computed sun has none"}`,
111
+ ];
112
+ });
113
+ return notes.length ? notes.join("; ") : undefined;
114
+ }