@glasshome/sync-layer 0.9.0 → 0.10.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.
@@ -1,2537 +0,0 @@
1
- import { createStore, produce, reconcile } from "solid-js/store";
2
- //#region src/core/store.ts
3
- const initialState = {
4
- connectionState: "disconnected",
5
- connectionError: null,
6
- hassUrl: null,
7
- mediaProxyBase: null,
8
- config: null,
9
- entities: {},
10
- entityRegistry: {},
11
- devices: {},
12
- areas: {},
13
- floors: {},
14
- labels: {},
15
- statistics: {},
16
- statisticsMetadata: {},
17
- history: {},
18
- forecasts: {},
19
- calendars: {},
20
- streams: {}
21
- };
22
- if (globalThis.__GH_SYNC_LAYER_STORE__) console.error("[@glasshome/sync-layer] DUPLICATE store module instantiated. This means @glasshome/sync-layer was bundled into >1 chunk. Reads and writes will hit different singletons. Check vendor build externals and relative-vs-bare imports across entry points.");
23
- globalThis.__GH_SYNC_LAYER_STORE__ = true;
24
- const storeTuple = createStore(initialState);
25
- const state = storeTuple[0];
26
- const setState = storeTuple[1];
27
- //#endregion
28
- //#region src/core/privileged-conn.ts
29
- let privileged = null;
30
- /** Read the live connection. Null before connect and after disconnect. */
31
- function privilegedConn() {
32
- return privileged;
33
- }
34
- /** Set by the connection layer on connect/disconnect. Host-side callers only. */
35
- function setPrivilegedConn(conn) {
36
- privileged = conn;
37
- }
38
- //#endregion
39
- //#region src/calendar/track.ts
40
- /**
41
- * Ref-counted live calendar tracking, the per-entity analog of
42
- * `connection/subscription-manager`. Each tracked calendar entity holds one
43
- * upstream `calendar/event/subscribe` (HA pushes an initial snapshot, then
44
- * debounced updates); trackers declare desired windows and a reconciler keeps
45
- * the subscription matched to the union. Data lands in `state.calendars`;
46
- * read-scoping for widget consumers arrives with WS-8 like every other store
47
- * read.
48
- */
49
- const DEFAULT_DAYS_BEHIND = 7;
50
- const DEFAULT_DAYS_AHEAD = 35;
51
- /** Debounce for untrack, so dashboard switches don't churn subscriptions. */
52
- const UNTRACK_FLUSH_DELAY_MS$1 = 5e3;
53
- const DAY_MS$1 = 864e5;
54
- const trackers = /* @__PURE__ */ new Map();
55
- const active$1 = /* @__PURE__ */ new Map();
56
- /** Per-entity reconcile chain; serializes subscribe/unsubscribe per calendar. */
57
- const chains$1 = /* @__PURE__ */ new Map();
58
- let untrackTimer$1 = null;
59
- let rollTimer = null;
60
- /** Day-quantized union of all tracker windows, so equal requests within a day
61
- reconcile to the same subscription instead of churning. */
62
- function windowFor(list) {
63
- let behind = 0;
64
- let ahead = 0;
65
- for (const t of list) {
66
- if (t.daysBehind > behind) behind = t.daysBehind;
67
- if (t.daysAhead > ahead) ahead = t.daysAhead;
68
- }
69
- const dayStart = /* @__PURE__ */ new Date();
70
- dayStart.setHours(0, 0, 0, 0);
71
- return {
72
- start: (/* @__PURE__ */ new Date(dayStart.getTime() - behind * DAY_MS$1)).toISOString(),
73
- end: new Date(dayStart.getTime() + (ahead + 1) * DAY_MS$1).toISOString()
74
- };
75
- }
76
- /**
77
- * Start tracking live events for a calendar entity. Returns the untrack
78
- * function. Safe while disconnected: the subscription activates on the next
79
- * `forceResubscribeCalendars()` (called by the connection layer on connect
80
- * and reconnect).
81
- */
82
- function trackCalendarEvents(entityId, options) {
83
- const tracker = {
84
- daysBehind: options?.daysBehind ?? DEFAULT_DAYS_BEHIND,
85
- daysAhead: options?.daysAhead ?? DEFAULT_DAYS_AHEAD
86
- };
87
- const list = trackers.get(entityId) ?? [];
88
- list.push(tracker);
89
- trackers.set(entityId, list);
90
- scheduleFlush$1();
91
- ensureRollTimer();
92
- let untracked = false;
93
- return () => {
94
- if (untracked) return;
95
- untracked = true;
96
- untrackCalendarEvents(entityId, tracker);
97
- };
98
- }
99
- function untrackCalendarEvents(entityId, tracker) {
100
- const list = trackers.get(entityId);
101
- if (!list) return;
102
- const i = list.indexOf(tracker);
103
- if (i !== -1) list.splice(i, 1);
104
- if (list.length === 0) trackers.delete(entityId);
105
- if (untrackTimer$1) return;
106
- untrackTimer$1 = setTimeout(() => {
107
- untrackTimer$1 = null;
108
- flushAll$1();
109
- }, UNTRACK_FLUSH_DELAY_MS$1);
110
- }
111
- /**
112
- * Reconcile every tracked calendar, dropping current subscription handles
113
- * first. The connection layer calls this on connect and after reconnect:
114
- * an unchanged window is no proof the old subscription is alive, so each
115
- * tracked entity resubscribes (HA re-pushes the snapshot, refreshing the
116
- * store through any missed changes).
117
- */
118
- async function forceResubscribeCalendars() {
119
- for (const entry of active$1.values()) {
120
- const dead = entry.unsub;
121
- entry.unsub = null;
122
- if (dead) Promise.resolve().then(dead).catch(() => {});
123
- }
124
- await flushAll$1();
125
- }
126
- function scheduleFlush$1() {
127
- queueMicrotask(() => {
128
- flushAll$1();
129
- });
130
- }
131
- async function flushAll$1() {
132
- const ids = /* @__PURE__ */ new Set([...trackers.keys(), ...active$1.keys()]);
133
- await Promise.all([...ids].map(reconcileEntity));
134
- if (trackers.size === 0) stopRollTimer();
135
- }
136
- function reconcileEntity(entityId) {
137
- const next = (chains$1.get(entityId) ?? Promise.resolve()).then(() => runReconcile$1(entityId));
138
- chains$1.set(entityId, next.catch(() => {}));
139
- return next;
140
- }
141
- async function runReconcile$1(entityId) {
142
- const list = trackers.get(entityId);
143
- const current = active$1.get(entityId);
144
- if (!list || list.length === 0) {
145
- if (current) {
146
- active$1.delete(entityId);
147
- try {
148
- await current.unsub?.();
149
- } catch {}
150
- }
151
- chains$1.delete(entityId);
152
- setState(produce((s) => {
153
- delete s.calendars[entityId];
154
- }));
155
- return;
156
- }
157
- const conn = privilegedConn();
158
- if (!conn) return;
159
- const win = windowFor(list);
160
- if (current?.unsub && current.start === win.start && current.end === win.end) return;
161
- setState(produce((s) => {
162
- s.calendars[entityId] = {
163
- entityId,
164
- events: s.calendars[entityId]?.events ?? [],
165
- loading: true,
166
- error: null,
167
- start: win.start,
168
- end: win.end
169
- };
170
- }));
171
- const old = current?.unsub ?? null;
172
- const entry = {
173
- start: win.start,
174
- end: win.end,
175
- unsub: null
176
- };
177
- active$1.set(entityId, entry);
178
- try {
179
- entry.unsub = await conn.subscribeMessage((msg) => {
180
- setState(produce((s) => {
181
- const rec = s.calendars[entityId];
182
- if (!rec) return;
183
- rec.events = msg.events ?? [];
184
- rec.loading = false;
185
- rec.error = null;
186
- }));
187
- }, {
188
- type: "calendar/event/subscribe",
189
- entity_id: entityId,
190
- start: win.start,
191
- end: win.end
192
- });
193
- } catch (err) {
194
- active$1.delete(entityId);
195
- setState(produce((s) => {
196
- const rec = s.calendars[entityId];
197
- if (!rec) return;
198
- rec.loading = false;
199
- rec.error = err instanceof Error ? err : new Error(String(err));
200
- }));
201
- }
202
- if (old) try {
203
- await old();
204
- } catch {}
205
- }
206
- /** One timer for the whole module: at local midnight the day-quantized
207
- windows shift, so a reconcile slides every subscription forward. Only
208
- armed while something is tracked — an idle app holds no timer. */
209
- function ensureRollTimer() {
210
- if (rollTimer || trackers.size === 0) return;
211
- const now = /* @__PURE__ */ new Date();
212
- const next = new Date(now);
213
- next.setHours(24, 0, 30, 0);
214
- rollTimer = setTimeout(() => {
215
- rollTimer = null;
216
- flushAll$1().then(ensureRollTimer);
217
- }, next.getTime() - now.getTime());
218
- }
219
- function stopRollTimer() {
220
- if (rollTimer) {
221
- clearTimeout(rollTimer);
222
- rollTimer = null;
223
- }
224
- }
225
- //#endregion
226
- //#region src/core/types.ts
227
- /**
228
- * Extract domain from entity ID
229
- */
230
- function extractDomain(entityId) {
231
- return entityId.split(".")[0] ?? "";
232
- }
233
- //#endregion
234
- //#region src/demo/demo-album-cover.ts
235
- const DEMO_ALBUM_COVER = "data:image/webp;base64,UklGRkQqAABXRUJQVlA4IDgqAACQ4gCdASpAAUABPrFQoEynJKMrJ5QcoWAWCU2DebOqk3Yg0pyMZc19bp75H+tZ6fX3Xq02cSLsHBqwh+o3+wbzrnV92l9dil3ZfrdbGzkJxWfPPOJ3FzTwUPMi+l2o3inFi93ATZpsReQlnN/h9UQaNMl0igvPehaYxv9+fjjc+t20PTqrF6T8q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qRV6Tpfv8u4ZyMF/Wb/EWGTwQ/2ElL2egYk/F+cz7d7b2rMJUBbOLgnWUUqXr4BsoSVBhfLwBkJe4+IBtfTxQ/LKd+M9ss+mxmTjoZhfOEsrsTBY/kLjok/u08g7OhW7EASMKVXg7qvB6hozoShKGNji3tron3hOEJ+GdwstNcqrgAAA==";
236
- //#endregion
237
- //#region src/demo/energy-sim.ts
238
- const SOLAR_PEAK_W = 5200;
239
- const SUNRISE_HOUR = 6.5;
240
- const SUNSET_HOUR = 20.5;
241
- const ALWAYS_ON_W = 285;
242
- const FRIDGE_W = 95;
243
- const FRIDGE_CYCLE_MIN = 45;
244
- const FRIDGE_ON_MIN = 18;
245
- const BATTERY_CAPACITY_WH = 1e4;
246
- const BATTERY_MIN_SOC = 10;
247
- const BATTERY_MAX_SOC = 100;
248
- const BATTERY_POWER_CAP_W = 3e3;
249
- const MIDNIGHT_SOC = 55;
250
- const SOC_STEP_MIN = 5;
251
- /** Integer hash -> uint32, used to seed mulberry32 deterministically. */
252
- function hashInt(n) {
253
- let h = n | 0;
254
- h = Math.imul(h ^ h >>> 16, 73244475);
255
- h = Math.imul(h ^ h >>> 16, 73244475);
256
- h = (h ^ h >>> 16) >>> 0;
257
- return h;
258
- }
259
- /** Deterministic [0,1) generator seeded by an integer. */
260
- function mulberry32(seed) {
261
- let a = seed >>> 0;
262
- return () => {
263
- a |= 0;
264
- a = a + 1831565813 | 0;
265
- let t = Math.imul(a ^ a >>> 15, 1 | a);
266
- t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
267
- return ((t ^ t >>> 14) >>> 0) / 4294967296;
268
- };
269
- }
270
- function localTime(timestampMs) {
271
- const d = new Date(timestampMs);
272
- const hours = d.getHours();
273
- const minutes = d.getMinutes();
274
- const seconds = d.getSeconds();
275
- const hourFrac = hours + minutes / 60 + seconds / 3600;
276
- const minuteOfDay = hours * 60 + minutes + seconds / 60;
277
- const offsetMs = d.getTimezoneOffset() * 6e4;
278
- const dayKey = Math.floor((timestampMs - offsetMs) / 864e5);
279
- return {
280
- hourFrac,
281
- minuteOfDay,
282
- dayOfWeek: d.getDay(),
283
- dayKey
284
- };
285
- }
286
- function localMidnightMs(timestampMs, lt) {
287
- return timestampMs - lt.minuteOfDay * 6e4;
288
- }
289
- /** Smooth multiplicative cloud factor in [0.55, 1.0], seeded per day. */
290
- function cloudFactor(lt) {
291
- const rand = mulberry32(hashInt(lt.dayKey * 2654435761));
292
- const phase1 = rand() * Math.PI * 2;
293
- const phase2 = rand() * Math.PI * 2;
294
- const phase3 = rand() * Math.PI * 2;
295
- const m = lt.minuteOfDay;
296
- const f = .85 + (.16 * Math.sin(m / 37 * Math.PI * 2 + phase1) + .14 * Math.sin(m / 73 * Math.PI * 2 + phase2) + .05 * Math.sin(m / 11 * Math.PI * 2 + phase3));
297
- return Math.max(.55, Math.min(1, f));
298
- }
299
- function solarPower(lt) {
300
- if (lt.hourFrac <= SUNRISE_HOUR || lt.hourFrac >= SUNSET_HOUR) return 0;
301
- const frac = (lt.hourFrac - SUNRISE_HOUR) / 14;
302
- const shape = Math.sin(frac * Math.PI) ** 1.3;
303
- return SOLAR_PEAK_W * shape * cloudFactor(lt);
304
- }
305
- /** Coarse solar elevation in degrees for sun.sun attributes. */
306
- function sunElevation(lt) {
307
- if (lt.hourFrac <= SUNRISE_HOUR || lt.hourFrac >= SUNSET_HOUR) {
308
- const hoursFromHorizon = Math.min(Math.abs(lt.hourFrac - SUNRISE_HOUR), Math.abs(lt.hourFrac - SUNSET_HOUR), Math.abs(lt.hourFrac + 24 - SUNSET_HOUR));
309
- return -12 * Math.min(1, hoursFromHorizon / 1.5);
310
- }
311
- const frac = (lt.hourFrac - SUNRISE_HOUR) / 14;
312
- return 60 * Math.sin(frac * Math.PI);
313
- }
314
- function fridgePower(lt) {
315
- const phase = mulberry32(hashInt(lt.dayKey * 40503 + 7))() * FRIDGE_CYCLE_MIN;
316
- return (lt.minuteOfDay + phase) % FRIDGE_CYCLE_MIN < FRIDGE_ON_MIN ? FRIDGE_W : 0;
317
- }
318
- /** A square wave: `power` while inside [start, start+durationMin). */
319
- function windowPower(minuteOfDay, startMin, durationMin, power) {
320
- return minuteOfDay >= startMin && minuteOfDay < startMin + durationMin ? power : 0;
321
- }
322
- function kettlePower(lt) {
323
- return windowPower(lt.minuteOfDay, 430, 4, 2e3) + windowPower(lt.minuteOfDay, 1e3, 4, 2e3);
324
- }
325
- function ovenPower(lt) {
326
- const start = 1125;
327
- if (lt.minuteOfDay < start || lt.minuteOfDay >= 1165) return 0;
328
- return (lt.minuteOfDay - start) % 6.5 < 4 ? 2200 : 0;
329
- }
330
- function dishwasherPower(lt) {
331
- const start = 1270;
332
- if (lt.minuteOfDay < start || lt.minuteOfDay >= 1335) return 0;
333
- const into = lt.minuteOfDay - start;
334
- if (into < 12) return 1900;
335
- if (into >= 57) return 1900;
336
- return 120;
337
- }
338
- function washerPower(lt) {
339
- if (![
340
- 1,
341
- 4,
342
- 6
343
- ].includes(lt.dayOfWeek)) return 0;
344
- const start = 630;
345
- if (lt.minuteOfDay < start || lt.minuteOfDay >= 680) return 0;
346
- return lt.minuteOfDay - start < 14 ? 2100 : 250;
347
- }
348
- function evChargerPower(lt) {
349
- if (![
350
- 2,
351
- 4,
352
- 0
353
- ].includes(lt.dayOfWeek)) return 0;
354
- const start = 1100;
355
- if (lt.minuteOfDay < start || lt.minuteOfDay >= 1300) return 0;
356
- const into = lt.minuteOfDay - start;
357
- return 7200 * (into < 2 ? into / 2 : 1);
358
- }
359
- const HEAT_PUMP_PEAK_W = 3200;
360
- /**
361
- * A smooth heat-pump load: a slow morning/evening envelope carrying a
362
- * few-minute shimmer. Its peaks push the home deficit past the battery's power
363
- * cap, so grid import (and the running cost) visibly rise and fall on live
364
- * ticks instead of sitting at zero. Gated out of the deep-night window so the
365
- * quiet 02:00-03:00 baseline is unchanged.
366
- */
367
- function heatPumpPower(lt) {
368
- const h = lt.hourFrac;
369
- let envelope = 0;
370
- if (h >= 6 && h <= 9) envelope = Math.sin((h - 6) / 3 * Math.PI);
371
- else if (h >= 16 && h <= 23) envelope = Math.sin((h - 16) / 7 * Math.PI);
372
- else return 0;
373
- const shimmer = .7 + .3 * Math.sin(lt.minuteOfDay * Math.PI * 2);
374
- return HEAT_PUMP_PEAK_W * envelope * shimmer;
375
- }
376
- /** Smooth occupancy envelope: extra load mornings and evenings. */
377
- function occupancyEnvelope(lt) {
378
- const h = lt.hourFrac;
379
- let e = 0;
380
- if (h >= 7 && h <= 9) e += 80 + 270 * Math.sin((h - 7) / 2 * Math.PI);
381
- if (h >= 17.5 && h <= 23) e += 80 + 270 * Math.sin((h - 17.5) / 5.5 * Math.PI);
382
- return e;
383
- }
384
- /** Low-amplitude smooth noise multiplier, ±4%, seeded per day. */
385
- function homeNoise(lt) {
386
- const phase = mulberry32(hashInt(lt.dayKey * 22699 + 13))() * Math.PI * 2;
387
- return 1 + .04 * Math.sin(lt.minuteOfDay / 23 * Math.PI * 2 + phase);
388
- }
389
- const socCache = /* @__PURE__ */ new Map();
390
- /** Net surplus (solar - home) at a given local-time sample, in watts. */
391
- function netSurplusAt(timestampMs) {
392
- const lt = localTime(timestampMs);
393
- return solarPower(lt) - homePower(lt);
394
- }
395
- /**
396
- * Battery SOC (%) at every {@link SOC_STEP_MIN}-minute step from local
397
- * midnight. Returns step `i` = SOC after integrating `i` steps. Index 0 is
398
- * the midnight SOC. Memoized per local day (pure computation).
399
- */
400
- function socPrefix(dayKey, midnightMs) {
401
- const cached = socCache.get(dayKey);
402
- if (cached) return cached;
403
- const steps = Math.ceil(1440 / SOC_STEP_MIN);
404
- const arr = /* @__PURE__ */ new Float64Array(289);
405
- arr[0] = MIDNIGHT_SOC;
406
- const stepMs = SOC_STEP_MIN * 6e4;
407
- const stepHours = SOC_STEP_MIN / 60;
408
- for (let i = 0; i < steps; i++) {
409
- const soc = arr[i] ?? MIDNIGHT_SOC;
410
- const surplus = netSurplusAt(midnightMs + i * stepMs);
411
- let chargeW = 0;
412
- let dischargeW = 0;
413
- if (surplus > 0) {
414
- const headroomW = (BATTERY_MAX_SOC - soc) / 100 * BATTERY_CAPACITY_WH / stepHours;
415
- chargeW = Math.min(surplus, BATTERY_POWER_CAP_W, Math.max(0, headroomW));
416
- } else if (surplus < 0) {
417
- const availW = (soc - BATTERY_MIN_SOC) / 100 * BATTERY_CAPACITY_WH / stepHours;
418
- dischargeW = Math.min(-surplus, BATTERY_POWER_CAP_W, Math.max(0, availW));
419
- }
420
- const nextSoc = soc + (chargeW - dischargeW) * stepHours / BATTERY_CAPACITY_WH * 100;
421
- arr[i + 1] = Math.max(BATTERY_MIN_SOC, Math.min(BATTERY_MAX_SOC, nextSoc));
422
- }
423
- socCache.set(dayKey, arr);
424
- return arr;
425
- }
426
- /** Battery SOC (%) at an exact timestamp, linearly interpolated between steps. */
427
- function batterySoc(lt, midnightMs) {
428
- const prefix = socPrefix(lt.dayKey, midnightMs);
429
- const stepFloat = lt.minuteOfDay / SOC_STEP_MIN;
430
- const i = Math.floor(stepFloat);
431
- const frac = stepFloat - i;
432
- const a = prefix[i] ?? MIDNIGHT_SOC;
433
- return a + ((prefix[i + 1] ?? a) - a) * frac;
434
- }
435
- function homePower(lt) {
436
- return (ALWAYS_ON_W + fridgePower(lt) + kettlePower(lt) + ovenPower(lt) + dishwasherPower(lt) + washerPower(lt) + evChargerPower(lt) + heatPumpPower(lt) + occupancyEnvelope(lt)) * homeNoise(lt);
437
- }
438
- /**
439
- * Compute every instantaneous energy value at a timestamp.
440
- *
441
- * Deterministic: equal timestamps always yield deep-equal samples. Obeys the
442
- * conservation invariant
443
- * `solar + gridImport + batteryDischarge === home + gridExport + batteryCharge`
444
- * to within rounding.
445
- */
446
- function simulateEnergy(timestampMs) {
447
- const lt = localTime(timestampMs);
448
- const midnightMs = localMidnightMs(timestampMs, lt);
449
- const solarW = solarPower(lt);
450
- const fridgeW = fridgePower(lt);
451
- const ovenW = ovenPower(lt);
452
- const dishwasherW = dishwasherPower(lt);
453
- const washerW = washerPower(lt);
454
- const evChargerW = evChargerPower(lt);
455
- const alwaysOnW = ALWAYS_ON_W;
456
- const homeW = homePower(lt);
457
- const soc = batterySoc(lt, midnightMs);
458
- const surplus = solarW - homeW;
459
- let batteryChargeW = 0;
460
- let batteryDischargeW = 0;
461
- if (surplus > 0) batteryChargeW = Math.min(surplus, soc < BATTERY_MAX_SOC ? BATTERY_POWER_CAP_W : 0);
462
- else if (surplus < 0) {
463
- const avail = soc > BATTERY_MIN_SOC ? BATTERY_POWER_CAP_W : 0;
464
- batteryDischargeW = Math.min(-surplus, avail);
465
- }
466
- const remainingDeficit = homeW - solarW - batteryDischargeW + batteryChargeW;
467
- const gridImportW = Math.max(0, remainingDeficit);
468
- const gridExportW = Math.max(0, -remainingDeficit);
469
- return {
470
- solarW,
471
- homeW,
472
- batteryChargeW,
473
- batteryDischargeW,
474
- batterySocPct: soc,
475
- gridImportW,
476
- gridExportW,
477
- fridgeW,
478
- dishwasherW,
479
- washerW,
480
- ovenW,
481
- evChargerW,
482
- alwaysOnW
483
- };
484
- }
485
- /** Whether the sun is above the horizon at a timestamp. */
486
- function isSunUp(timestampMs) {
487
- const lt = localTime(timestampMs);
488
- return lt.hourFrac > SUNRISE_HOUR && lt.hourFrac < SUNSET_HOUR;
489
- }
490
- /** Next sunrise/sunset ISO strings relative to a timestamp. */
491
- function sunEvents(timestampMs) {
492
- const lt = localTime(timestampMs);
493
- const midnightMs = localMidnightMs(timestampMs, lt);
494
- const sunriseMs = midnightMs + SUNRISE_HOUR * 36e5;
495
- const sunsetMs = midnightMs + SUNSET_HOUR * 36e5;
496
- const nextRising = timestampMs < sunriseMs ? sunriseMs : sunriseMs + 864e5;
497
- const nextSetting = timestampMs < sunsetMs ? sunsetMs : sunsetMs + 864e5;
498
- return {
499
- nextRising: new Date(nextRising).toISOString(),
500
- nextSetting: new Date(nextSetting).toISOString(),
501
- elevation: Math.round(sunElevation(lt) * 100) / 100,
502
- rising: lt.hourFrac < 27 / 2 || lt.hourFrac >= 25.5
503
- };
504
- }
505
- /** The energy sensor entity ids the simulation drives. */
506
- const ENERGY_ENTITY_IDS = [
507
- "sensor.solar_power",
508
- "sensor.grid_import_power",
509
- "sensor.grid_export_power",
510
- "sensor.battery_charge_power",
511
- "sensor.battery_discharge_power",
512
- "sensor.battery_soc",
513
- "sensor.home_power",
514
- "sensor.fridge_power",
515
- "sensor.dishwasher_power",
516
- "sensor.washing_machine_power",
517
- "sensor.oven_power",
518
- "sensor.ev_charger_power",
519
- "sensor.always_on_power"
520
- ];
521
- /** Map an energy entity id to its numeric value from a sample (W, or % for SOC). */
522
- function energyEntityValue(entityId, sample) {
523
- switch (entityId) {
524
- case "sensor.solar_power": return sample.solarW;
525
- case "sensor.grid_import_power": return sample.gridImportW;
526
- case "sensor.grid_export_power": return sample.gridExportW;
527
- case "sensor.battery_charge_power": return sample.batteryChargeW;
528
- case "sensor.battery_discharge_power": return sample.batteryDischargeW;
529
- case "sensor.battery_soc": return sample.batterySocPct;
530
- case "sensor.home_power": return sample.homeW;
531
- case "sensor.fridge_power": return sample.fridgeW;
532
- case "sensor.dishwasher_power": return sample.dishwasherW;
533
- case "sensor.washing_machine_power": return sample.washerW;
534
- case "sensor.oven_power": return sample.ovenW;
535
- case "sensor.ev_charger_power": return sample.evChargerW;
536
- case "sensor.always_on_power": return sample.alwaysOnW;
537
- default: return;
538
- }
539
- }
540
- /** Whether an entity id is one of the simulated energy sensors. */
541
- function isEnergyEntity(entityId) {
542
- return energyEntityValue(entityId, ZERO_SAMPLE) !== void 0;
543
- }
544
- const ZERO_SAMPLE = {
545
- solarW: 0,
546
- homeW: 0,
547
- batteryChargeW: 0,
548
- batteryDischargeW: 0,
549
- batterySocPct: 0,
550
- gridImportW: 0,
551
- gridExportW: 0,
552
- fridgeW: 0,
553
- dishwasherW: 0,
554
- washerW: 0,
555
- ovenW: 0,
556
- evChargerW: 0,
557
- alwaysOnW: 0
558
- };
559
- /** Round to 1 decimal for display-friendly state strings (whole % for SOC). */
560
- function formatEnergyState(entityId, value) {
561
- if (entityId === "sensor.battery_soc") return String(Math.round(value));
562
- return String(Math.round(value));
563
- }
564
- /**
565
- * Synthesize history points for one energy entity by sampling the model across
566
- * the window at a fixed cadence (default 1-minute). Returns HA-compressed
567
- * `{ lu, s }` points with `lu` in Unix seconds.
568
- */
569
- function synthesizeEnergyHistory(entityId, startMs, endMs, stepMs = 6e4) {
570
- const points = [];
571
- for (let t = startMs; t <= endMs; t += stepMs) {
572
- const value = energyEntityValue(entityId, simulateEnergy(t));
573
- if (value === void 0) continue;
574
- points.push({
575
- lu: Math.round(t / 1e3),
576
- s: formatEnergyState(entityId, value)
577
- });
578
- }
579
- return points;
580
- }
581
- /** Bucket length in ms for a statistics period. */
582
- function bucketMs(period) {
583
- return period === "hour" ? 36e5 : 864e5;
584
- }
585
- /**
586
- * Synthesize statistics buckets for one energy entity across a window.
587
- *
588
- * `mean`/`min`/`max` come from 5-minute power samples in the bucket; `sum` is
589
- * the energy in Wh (mean W times bucket hours). `sum` is cumulative across the
590
- * window, matching HA's monotonically increasing meter semantics.
591
- */
592
- function synthesizeEnergyStatistics(entityId, startMs, endMs, period) {
593
- const span = bucketMs(period);
594
- const sampleMs = 3e5;
595
- const buckets = [];
596
- let cumulativeWh = 0;
597
- for (let bStart = startMs; bStart < endMs; bStart += span) {
598
- const bEnd = bStart + span;
599
- let sum = 0;
600
- let count = 0;
601
- let min = Number.POSITIVE_INFINITY;
602
- let max = Number.NEGATIVE_INFINITY;
603
- for (let t = bStart; t < bEnd; t += sampleMs) {
604
- const value = energyEntityValue(entityId, simulateEnergy(t));
605
- if (value === void 0) continue;
606
- sum += value;
607
- count++;
608
- if (value < min) min = value;
609
- if (value > max) max = value;
610
- }
611
- if (count === 0) continue;
612
- const mean = sum / count;
613
- const bucketHours = span / 36e5;
614
- const energyWh = entityId === "sensor.battery_soc" ? 0 : mean * bucketHours;
615
- cumulativeWh += energyWh;
616
- buckets.push({
617
- start: bStart,
618
- end: bEnd,
619
- mean,
620
- min: min === Number.POSITIVE_INFINITY ? mean : min,
621
- max: max === Number.NEGATIVE_INFINITY ? mean : max,
622
- sum: cumulativeWh,
623
- change: energyWh / 1e3
624
- });
625
- }
626
- return buckets;
627
- }
628
- /** The demo energy dashboard preferences wiring the simulated sensors. */
629
- function demoEnergyPreferences() {
630
- return {
631
- energy_sources: [
632
- {
633
- type: "solar",
634
- stat_energy_from: "sensor.solar_power"
635
- },
636
- {
637
- type: "grid",
638
- flow_from: [{ stat_energy_from: "sensor.grid_import_power" }],
639
- flow_to: [{ stat_energy_to: "sensor.grid_export_power" }]
640
- },
641
- {
642
- type: "battery",
643
- stat_energy_from: "sensor.battery_discharge_power",
644
- stat_energy_to: "sensor.battery_charge_power"
645
- }
646
- ],
647
- device_consumption: [
648
- {
649
- stat_consumption: "sensor.fridge_power",
650
- name: "Fridge"
651
- },
652
- {
653
- stat_consumption: "sensor.dishwasher_power",
654
- name: "Dishwasher"
655
- },
656
- {
657
- stat_consumption: "sensor.washing_machine_power",
658
- name: "Washing Machine"
659
- },
660
- {
661
- stat_consumption: "sensor.oven_power",
662
- name: "Oven"
663
- },
664
- {
665
- stat_consumption: "sensor.ev_charger_power",
666
- name: "EV Charger"
667
- },
668
- {
669
- stat_consumption: "sensor.always_on_power",
670
- name: "Always On"
671
- }
672
- ]
673
- };
674
- }
675
- //#endregion
676
- //#region src/demo/demo-data.ts
677
- function demoAssetUrl(path) {
678
- return globalThis.location ? new URL(path, globalThis.location.origin).href : path;
679
- }
680
- const now = (/* @__PURE__ */ new Date()).toISOString();
681
- let contextCounter = 0;
682
- function ctx() {
683
- return {
684
- id: `demo-${++contextCounter}`,
685
- parent_id: null,
686
- user_id: null
687
- };
688
- }
689
- function makeEntity(entity_id, state, attributes = {}) {
690
- return {
691
- entity_id,
692
- state,
693
- attributes: {
694
- friendly_name: friendlyName(entity_id),
695
- ...attributes
696
- },
697
- last_changed: now,
698
- last_updated: now,
699
- context: ctx()
700
- };
701
- }
702
- /**
703
- * One entity per weather scene the widget can render. Entity IDs use the
704
- * `weather.demo_<slug>` form so a demo dashboard can reference them directly.
705
- */
706
- const WEATHER_FIXTURES = [
707
- {
708
- slug: "sunny",
709
- state: "sunny",
710
- temp: 28,
711
- apparent: 31,
712
- humidity: 35,
713
- pressure: 1018,
714
- wind: 8,
715
- low: 18
716
- },
717
- {
718
- slug: "clear_night",
719
- state: "clear-night",
720
- temp: 14,
721
- apparent: 12,
722
- humidity: 55,
723
- pressure: 1016,
724
- wind: 5,
725
- low: 9
726
- },
727
- {
728
- slug: "cloudy",
729
- state: "cloudy",
730
- temp: 17,
731
- apparent: 16,
732
- humidity: 72,
733
- pressure: 1010,
734
- wind: 14,
735
- low: 11
736
- },
737
- {
738
- slug: "partly_cloudy",
739
- state: "partlycloudy",
740
- temp: 23,
741
- apparent: 24,
742
- humidity: 50,
743
- pressure: 1014,
744
- wind: 12,
745
- low: 15
746
- },
747
- {
748
- slug: "rainy",
749
- state: "rainy",
750
- temp: 12,
751
- apparent: 10,
752
- humidity: 88,
753
- pressure: 1004,
754
- wind: 18,
755
- low: 8
756
- },
757
- {
758
- slug: "pouring",
759
- state: "pouring",
760
- temp: 11,
761
- apparent: 8,
762
- humidity: 95,
763
- pressure: 998,
764
- wind: 26,
765
- low: 7
766
- },
767
- {
768
- slug: "snowy",
769
- state: "snowy",
770
- temp: -2,
771
- apparent: -6,
772
- humidity: 80,
773
- pressure: 1020,
774
- wind: 10,
775
- low: -7
776
- },
777
- {
778
- slug: "snowy_rainy",
779
- state: "snowy-rainy",
780
- temp: 1,
781
- apparent: -2,
782
- humidity: 92,
783
- pressure: 1006,
784
- wind: 16,
785
- low: -2
786
- },
787
- {
788
- slug: "lightning",
789
- state: "lightning",
790
- temp: 22,
791
- apparent: 24,
792
- humidity: 78,
793
- pressure: 1001,
794
- wind: 22,
795
- low: 17
796
- },
797
- {
798
- slug: "lightning_rainy",
799
- state: "lightning-rainy",
800
- temp: 19,
801
- apparent: 18,
802
- humidity: 90,
803
- pressure: 996,
804
- wind: 28,
805
- low: 14
806
- },
807
- {
808
- slug: "fog",
809
- state: "fog",
810
- temp: 8,
811
- apparent: 6,
812
- humidity: 98,
813
- pressure: 1015,
814
- wind: 4,
815
- low: 6
816
- },
817
- {
818
- slug: "hail",
819
- state: "hail",
820
- temp: 6,
821
- apparent: 3,
822
- humidity: 84,
823
- pressure: 1002,
824
- wind: 20,
825
- low: 1
826
- },
827
- {
828
- slug: "windy",
829
- state: "windy",
830
- temp: 18,
831
- apparent: 15,
832
- humidity: 60,
833
- pressure: 1009,
834
- wind: 42,
835
- low: 12
836
- },
837
- {
838
- slug: "exceptional",
839
- state: "exceptional",
840
- temp: 38,
841
- apparent: 44,
842
- humidity: 22,
843
- pressure: 1005,
844
- wind: 30,
845
- low: 28
846
- }
847
- ];
848
- function makeWeatherEntity(w) {
849
- const today = /* @__PURE__ */ new Date();
850
- const day = (n) => new Date(today.getTime() + n * 864e5).toISOString();
851
- return makeEntity(`weather.demo_${w.slug}`, w.state, {
852
- temperature: w.temp,
853
- temperature_unit: "°C",
854
- apparent_temperature: w.apparent ?? w.temp,
855
- humidity: w.humidity,
856
- pressure: w.pressure,
857
- pressure_unit: "hPa",
858
- wind_speed: w.wind,
859
- wind_speed_unit: "km/h",
860
- wind_bearing: w.bearing ?? 220,
861
- visibility: 10,
862
- visibility_unit: "km",
863
- uv_index: w.state === "sunny" ? 8 : 2,
864
- forecast: [
865
- {
866
- datetime: day(0),
867
- condition: w.state,
868
- temperature: w.temp,
869
- templow: w.low
870
- },
871
- {
872
- datetime: day(1),
873
- condition: "partlycloudy",
874
- temperature: w.temp + 2,
875
- templow: w.low
876
- },
877
- {
878
- datetime: day(2),
879
- condition: "cloudy",
880
- temperature: w.temp + 1,
881
- templow: w.low - 1
882
- },
883
- {
884
- datetime: day(3),
885
- condition: "sunny",
886
- temperature: w.temp + 4,
887
- templow: w.low + 1
888
- },
889
- {
890
- datetime: day(4),
891
- condition: "rainy",
892
- temperature: w.temp - 2,
893
- templow: w.low - 2
894
- },
895
- {
896
- datetime: day(5),
897
- condition: "cloudy",
898
- temperature: w.temp - 1,
899
- templow: w.low - 2
900
- },
901
- {
902
- datetime: day(6),
903
- condition: "partlycloudy",
904
- temperature: w.temp + 1,
905
- templow: w.low
906
- }
907
- ]
908
- });
909
- }
910
- function friendlyName(entityId) {
911
- return (entityId.split(".")[1] ?? entityId).split("_").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
912
- }
913
- function makeRegistryEntry(entity_id, overrides = {}) {
914
- const domain = entity_id.split(".")[0] ?? "";
915
- return {
916
- aliases: [],
917
- area_id: null,
918
- capabilities: null,
919
- categories: {},
920
- config_entry_id: "demo_config",
921
- config_subentry_id: null,
922
- created_at: now,
923
- device_class: null,
924
- device_id: null,
925
- disabled_by: null,
926
- entity_category: null,
927
- entity_id,
928
- has_entity_name: false,
929
- hidden_by: null,
930
- icon: null,
931
- id: `reg-${entity_id.replace(".", "-")}`,
932
- labels: [],
933
- modified_at: now,
934
- name: null,
935
- options: {},
936
- original_device_class: null,
937
- original_icon: null,
938
- original_name: null,
939
- platform: domain === "weather" ? "met" : "demo",
940
- previous_unique_id: null,
941
- suggested_object_id: null,
942
- supported_features: 0,
943
- translation_key: null,
944
- unique_id: `demo_${entity_id.replace(".", "_")}`,
945
- unit_of_measurement: null,
946
- ...overrides
947
- };
948
- }
949
- function makeDevice(id, name, areaId, manufacturer = "Demo", model = "Virtual") {
950
- return {
951
- id,
952
- name,
953
- name_by_user: null,
954
- manufacturer,
955
- model,
956
- model_id: null,
957
- sw_version: "1.0.0",
958
- hw_version: null,
959
- area_id: areaId,
960
- config_entries: ["demo_config"],
961
- config_entries_subentries: {},
962
- configuration_url: null,
963
- connections: [],
964
- created_at: now,
965
- disabled_by: null,
966
- entry_type: null,
967
- identifiers: [["demo", id]],
968
- labels: [],
969
- modified_at: now,
970
- primary_config_entry: "demo_config",
971
- serial_number: null,
972
- via_device_id: null
973
- };
974
- }
975
- function makeArea(id, name, floorId = "ground_floor") {
976
- return {
977
- id,
978
- name,
979
- normalized_name: name.toLowerCase().replace(/\s+/g, "_"),
980
- created_at: now,
981
- modified_at: now,
982
- aliases: [],
983
- floor_id: floorId,
984
- humidity_entity_id: null,
985
- icon: null,
986
- labels: [],
987
- picture: null,
988
- temperature_entity_id: null
989
- };
990
- }
991
- /**
992
- * Create ~30 curated apartment entity fixtures.
993
- *
994
- * Entities span lights, sensors, binary sensors, climate, covers,
995
- * locks, switches, media player, weather, camera, scenes, and buttons
996
- * across 6 areas: living_room, bedroom, kitchen, entry, utility, garage.
997
- */
998
- function createDemoFixtures() {
999
- contextCounter = 0;
1000
- const areas = {
1001
- living_room: makeArea("living_room", "Living Room"),
1002
- bedroom: makeArea("bedroom", "Bedroom"),
1003
- kitchen: makeArea("kitchen", "Kitchen"),
1004
- entry: makeArea("entry", "Entry"),
1005
- utility: makeArea("utility", "Utility"),
1006
- garage: makeArea("garage", "Garage")
1007
- };
1008
- areas.living_room.temperature_entity_id = "sensor.temperature_living";
1009
- areas.living_room.humidity_entity_id = "sensor.humidity_living";
1010
- const devices = {
1011
- living_room_lights: makeDevice("living_room_lights", "Living Room Lights", "living_room", "Philips", "Hue"),
1012
- kitchen_lights: makeDevice("kitchen_lights", "Kitchen Lights", "kitchen", "IKEA", "Tradfri"),
1013
- bedroom_lights: makeDevice("bedroom_lights", "Bedroom Lights", "bedroom", "Philips", "Hue"),
1014
- hallway_lights: makeDevice("hallway_lights", "Hallway Lights", "entry", "IKEA", "Tradfri"),
1015
- bathroom_lights: makeDevice("bathroom_lights", "Bathroom Lights", null),
1016
- thermostat_lr: makeDevice("thermostat_lr", "Living Room Thermostat", "living_room", "Nest", "Learning Thermostat"),
1017
- thermostat_br: makeDevice("thermostat_br", "Bedroom AC", "bedroom", "Daikin", "Split AC"),
1018
- blinds_lr: makeDevice("blinds_lr", "Living Room Blinds", "living_room", "Somfy", "Roller Shade"),
1019
- curtains_br: makeDevice("curtains_br", "Bedroom Curtains", "bedroom", "IKEA", "Fyrtur"),
1020
- garage_door_opener: makeDevice("garage_door_opener", "Garage Door Opener", "garage", "Chamberlain", "MyQ"),
1021
- shutters_lr: makeDevice("shutters_lr", "Living Room Shutters", "living_room", "Somfy", "Venetian Shutter"),
1022
- blinds_kitchen: makeDevice("blinds_kitchen", "Kitchen Blinds", "kitchen", "IKEA", "Praktlysing"),
1023
- lock_front: makeDevice("lock_front", "Front Door Lock", "entry", "Yale", "Assure Lock 2"),
1024
- lock_back: makeDevice("lock_back", "Back Door Lock", "entry", "August", "Smart Lock Pro"),
1025
- speaker_lr: makeDevice("speaker_lr", "Living Room Speaker", "living_room", "Sonos", "One"),
1026
- camera_front: makeDevice("camera_front", "Front Door Camera", "entry", "Ring", "Video Doorbell"),
1027
- door_sensor: makeDevice("door_sensor", "Front Door Sensor", "entry", "Aqara", "Door Sensor"),
1028
- motion_sensor: makeDevice("motion_sensor", "Hallway Motion Sensor", "entry", "Aqara", "Motion Sensor")
1029
- };
1030
- const entities = {};
1031
- const entityRegistry = {};
1032
- function add(e, regOverrides = {}) {
1033
- entities[e.entity_id] = e;
1034
- entityRegistry[e.entity_id] = makeRegistryEntry(e.entity_id, regOverrides);
1035
- }
1036
- add(makeEntity("light.living_room_main", "on", {
1037
- brightness: 179,
1038
- color_temp_kelvin: 3e3,
1039
- color_mode: "color_temp",
1040
- supported_color_modes: ["color_temp", "xy"]
1041
- }), {
1042
- device_id: "living_room_lights",
1043
- area_id: "living_room",
1044
- supported_features: 44
1045
- });
1046
- add(makeEntity("light.kitchen_counter", "off", { supported_color_modes: ["brightness"] }), {
1047
- device_id: "kitchen_lights",
1048
- area_id: "kitchen",
1049
- supported_features: 1
1050
- });
1051
- add(makeEntity("light.bedroom_ceiling", "on", {
1052
- brightness: 77,
1053
- color_temp_kelvin: 2700,
1054
- color_mode: "color_temp",
1055
- supported_color_modes: ["color_temp"]
1056
- }), {
1057
- device_id: "bedroom_lights",
1058
- area_id: "bedroom",
1059
- supported_features: 44
1060
- });
1061
- add(makeEntity("light.bathroom", "off", { supported_color_modes: ["brightness"] }), { device_id: "bathroom_lights" });
1062
- add(makeEntity("light.hallway", "on", {
1063
- brightness: 128,
1064
- color_mode: "brightness",
1065
- supported_color_modes: ["brightness"]
1066
- }), {
1067
- device_id: "hallway_lights",
1068
- area_id: "entry",
1069
- supported_features: 1
1070
- });
1071
- add(makeEntity("light.studio_rgb", "on", {
1072
- brightness: 205,
1073
- hs_color: [265, 66],
1074
- color_mode: "hs",
1075
- supported_color_modes: ["hs", "color_temp"]
1076
- }), {
1077
- device_id: "studio_lights",
1078
- area_id: "living_room",
1079
- supported_features: 44
1080
- });
1081
- add(makeEntity("light.desk_rgb", "on", {
1082
- brightness: 200,
1083
- hs_color: [172, 79],
1084
- color_mode: "hs",
1085
- supported_color_modes: ["hs", "color_temp"]
1086
- }), {
1087
- device_id: "desk_lights",
1088
- area_id: "bedroom",
1089
- supported_features: 44
1090
- });
1091
- add(makeEntity("sensor.temperature_living", "22.5", {
1092
- unit_of_measurement: "°C",
1093
- device_class: "temperature",
1094
- state_class: "measurement"
1095
- }), {
1096
- area_id: "living_room",
1097
- device_class: "temperature",
1098
- unit_of_measurement: "°C"
1099
- });
1100
- add(makeEntity("sensor.humidity_living", "45", {
1101
- unit_of_measurement: "%",
1102
- device_class: "humidity",
1103
- state_class: "measurement"
1104
- }), {
1105
- area_id: "living_room",
1106
- device_class: "humidity",
1107
- unit_of_measurement: "%"
1108
- });
1109
- add(makeEntity("sensor.temperature_outdoor", "-2", {
1110
- unit_of_measurement: "°C",
1111
- device_class: "temperature",
1112
- state_class: "measurement"
1113
- }), {
1114
- device_class: "temperature",
1115
- unit_of_measurement: "°C"
1116
- });
1117
- add(makeEntity("sensor.power_consumption", "1.2", {
1118
- unit_of_measurement: "kW",
1119
- device_class: "power",
1120
- state_class: "measurement"
1121
- }), {
1122
- device_class: "power",
1123
- unit_of_measurement: "kW"
1124
- });
1125
- add(makeEntity("sensor.battery_door_sensor", "87", {
1126
- unit_of_measurement: "%",
1127
- device_class: "battery",
1128
- state_class: "measurement"
1129
- }), {
1130
- device_id: "door_sensor",
1131
- area_id: "entry",
1132
- device_class: "battery",
1133
- unit_of_measurement: "%"
1134
- });
1135
- add(makeEntity("sensor.electricity_maps_co2_intensity", "214", {
1136
- unit_of_measurement: "gCO2eq/kWh",
1137
- state_class: "measurement"
1138
- }), { unit_of_measurement: "gCO2eq/kWh" });
1139
- add(makeEntity("sensor.electricity_maps_fossil_fuel_percentage", "31", {
1140
- unit_of_measurement: "%",
1141
- state_class: "measurement"
1142
- }), { unit_of_measurement: "%" });
1143
- for (const [zone, co2, fossil] of [[
1144
- "de",
1145
- "384",
1146
- "52"
1147
- ], [
1148
- "pl",
1149
- "692",
1150
- "81"
1151
- ]]) {
1152
- add(makeEntity(`sensor.electricity_maps_co2_intensity_${zone}`, co2, {
1153
- unit_of_measurement: "gCO2eq/kWh",
1154
- state_class: "measurement"
1155
- }), { unit_of_measurement: "gCO2eq/kWh" });
1156
- add(makeEntity(`sensor.electricity_maps_fossil_fuel_percentage_${zone}`, fossil, {
1157
- unit_of_measurement: "%",
1158
- state_class: "measurement"
1159
- }), { unit_of_measurement: "%" });
1160
- }
1161
- add(makeEntity("sensor.nordpool_current_price", "0.18", {
1162
- unit_of_measurement: "EUR/kWh",
1163
- state_class: "measurement"
1164
- }), { unit_of_measurement: "EUR/kWh" });
1165
- add(makeEntity("binary_sensor.front_door", "off", { device_class: "door" }), {
1166
- device_id: "door_sensor",
1167
- area_id: "entry",
1168
- device_class: "door"
1169
- });
1170
- add(makeEntity("binary_sensor.motion_hallway", "off", { device_class: "motion" }), {
1171
- device_id: "motion_sensor",
1172
- area_id: "entry",
1173
- device_class: "motion"
1174
- });
1175
- add(makeEntity("binary_sensor.window_bedroom", "off", { device_class: "window" }), {
1176
- area_id: "bedroom",
1177
- device_class: "window"
1178
- });
1179
- add(makeEntity("climate.living_room_thermostat", "heat", {
1180
- temperature: 22,
1181
- current_temperature: 21.8,
1182
- hvac_modes: [
1183
- "off",
1184
- "heat",
1185
- "cool",
1186
- "auto"
1187
- ],
1188
- hvac_action: "heating",
1189
- min_temp: 7,
1190
- max_temp: 35
1191
- }), {
1192
- device_id: "thermostat_lr",
1193
- area_id: "living_room",
1194
- supported_features: 385
1195
- });
1196
- add(makeEntity("climate.bedroom_ac", "off", {
1197
- temperature: 20,
1198
- current_temperature: 22.1,
1199
- hvac_modes: [
1200
- "off",
1201
- "cool",
1202
- "heat",
1203
- "dry",
1204
- "fan_only"
1205
- ],
1206
- hvac_action: "idle",
1207
- min_temp: 16,
1208
- max_temp: 30
1209
- }), {
1210
- device_id: "thermostat_br",
1211
- area_id: "bedroom",
1212
- supported_features: 385
1213
- });
1214
- add(makeEntity("water_heater.boiler", "eco", {
1215
- temperature: 50,
1216
- current_temperature: 47.5,
1217
- operation_list: [
1218
- "off",
1219
- "eco",
1220
- "performance"
1221
- ],
1222
- min_temp: 43,
1223
- max_temp: 60,
1224
- away_mode: "off"
1225
- }), {
1226
- device_id: "boiler",
1227
- area_id: "utility",
1228
- supported_features: 7
1229
- });
1230
- add(makeEntity("water_heater.heat_pump_tank", "heat_pump", {
1231
- temperature: 55,
1232
- current_temperature: 52.3,
1233
- operation_list: [
1234
- "off",
1235
- "eco",
1236
- "heat_pump",
1237
- "high_demand"
1238
- ],
1239
- min_temp: 43,
1240
- max_temp: 60
1241
- }), {
1242
- device_id: "hp_tank",
1243
- area_id: "garage",
1244
- supported_features: 3
1245
- });
1246
- add(makeEntity("fan.bedroom_ceiling", "on", {
1247
- percentage: 200 / 3,
1248
- percentage_step: 100 / 3,
1249
- current_direction: "forward"
1250
- }), {
1251
- device_id: "ceiling_fan",
1252
- area_id: "bedroom",
1253
- supported_features: 5
1254
- });
1255
- add(makeEntity("fan.air_purifier", "on", {
1256
- percentage: 40,
1257
- preset_modes: [
1258
- "auto",
1259
- "sleep",
1260
- "turbo"
1261
- ],
1262
- preset_mode: "auto",
1263
- oscillating: false
1264
- }), {
1265
- device_id: "purifier",
1266
- area_id: "living_room",
1267
- supported_features: 11
1268
- });
1269
- add(makeEntity("cover.living_room_blinds", "open", {
1270
- current_position: 80,
1271
- device_class: "shade"
1272
- }), {
1273
- device_id: "blinds_lr",
1274
- area_id: "living_room",
1275
- device_class: "shade",
1276
- supported_features: 15
1277
- });
1278
- add(makeEntity("cover.bedroom_curtains", "closed", {
1279
- current_position: 0,
1280
- device_class: "curtain"
1281
- }), {
1282
- device_id: "curtains_br",
1283
- area_id: "bedroom",
1284
- device_class: "curtain",
1285
- supported_features: 15
1286
- });
1287
- add(makeEntity("cover.garage_door", "closed", { device_class: "garage" }), {
1288
- device_id: "garage_door_opener",
1289
- area_id: "garage",
1290
- device_class: "garage",
1291
- supported_features: 11
1292
- });
1293
- add(makeEntity("cover.driveway_gate", "open", {
1294
- device_class: "gate",
1295
- assumed_state: true
1296
- }), {
1297
- area_id: "garage",
1298
- device_class: "gate",
1299
- supported_features: 3
1300
- });
1301
- add(makeEntity("cover.living_room_shutters", "open", {
1302
- current_position: 45,
1303
- current_tilt_position: 30,
1304
- device_class: "shutter"
1305
- }), {
1306
- device_id: "shutters_lr",
1307
- area_id: "living_room",
1308
- device_class: "shutter",
1309
- supported_features: 255
1310
- });
1311
- add(makeEntity("cover.kitchen_blinds", "open", {
1312
- current_position: 100,
1313
- device_class: "blind"
1314
- }), {
1315
- device_id: "blinds_kitchen",
1316
- area_id: "kitchen",
1317
- device_class: "blind",
1318
- supported_features: 127
1319
- });
1320
- add(makeEntity("lock.front_door_lock", "locked", {}), {
1321
- device_id: "lock_front",
1322
- area_id: "entry",
1323
- supported_features: 1
1324
- });
1325
- add(makeEntity("lock.back_door_lock", "locked", {}), {
1326
- device_id: "lock_back",
1327
- area_id: "entry",
1328
- supported_features: 1
1329
- });
1330
- add(makeEntity("lock.side_gate", "unlocked", {}), { supported_features: 1 });
1331
- add(makeEntity("binary_sensor.patio_door", "on", { device_class: "door" }), { device_class: "door" });
1332
- add(makeEntity("binary_sensor.motion_kitchen", "on", { device_class: "motion" }), { device_class: "motion" });
1333
- add(makeEntity("switch.coffee_machine", "off", { device_class: "outlet" }), {
1334
- area_id: "kitchen",
1335
- device_class: "outlet"
1336
- });
1337
- add(makeEntity("switch.fan_living_room", "on", { device_class: "switch" }), {
1338
- area_id: "living_room",
1339
- device_class: "switch"
1340
- });
1341
- add(makeEntity("media_player.living_room_speaker", "playing", {
1342
- media_title: "Lo-fi Beats",
1343
- media_artist: "Chill Station",
1344
- media_content_type: "music",
1345
- entity_picture: DEMO_ALBUM_COVER,
1346
- volume_level: .4,
1347
- is_volume_muted: false,
1348
- supported_features: 152509
1349
- }), {
1350
- device_id: "speaker_lr",
1351
- area_id: "living_room",
1352
- supported_features: 152509
1353
- });
1354
- for (const w of WEATHER_FIXTURES) add(makeWeatherEntity(w), { platform: "met" });
1355
- add(makeEntity("camera.front_door_camera", "streaming", {
1356
- entity_picture: demoAssetUrl("/demo/camera/front-door.webp"),
1357
- frontend_stream_type: "hls",
1358
- access_token: "demo-token"
1359
- }), {
1360
- device_id: "camera_front",
1361
- area_id: "entry",
1362
- supported_features: 2
1363
- });
1364
- add(makeEntity("scene.movie_night", "scening", { entity_id: [
1365
- "light.living_room_main",
1366
- "cover.living_room_blinds",
1367
- "media_player.living_room_speaker"
1368
- ] }), { area_id: "living_room" });
1369
- add(makeEntity("scene.good_morning", "scening", { entity_id: [
1370
- "light.bedroom_ceiling",
1371
- "cover.bedroom_curtains",
1372
- "switch.coffee_machine"
1373
- ] }), {});
1374
- add(makeEntity("button.restart_home_assistant", "unknown", { device_class: "restart" }), {
1375
- entity_category: "config",
1376
- device_class: "restart"
1377
- });
1378
- add(makeEntity("button.update_firmware", "unknown", { device_class: "update" }), {
1379
- entity_category: "config",
1380
- device_class: "update"
1381
- });
1382
- add(makeEntity("sensor.door_lock_battery", "92", {
1383
- unit_of_measurement: "%",
1384
- device_class: "battery",
1385
- state_class: "measurement"
1386
- }), {
1387
- device_id: "lock_front",
1388
- area_id: "entry",
1389
- device_class: "battery",
1390
- unit_of_measurement: "%"
1391
- });
1392
- add(makeEntity("sensor.motion_sensor_battery", "65", {
1393
- unit_of_measurement: "%",
1394
- device_class: "battery",
1395
- state_class: "measurement"
1396
- }), {
1397
- device_id: "motion_sensor",
1398
- area_id: "entry",
1399
- device_class: "battery",
1400
- unit_of_measurement: "%"
1401
- });
1402
- const nowMs = Date.now();
1403
- const sample = simulateEnergy(nowMs);
1404
- const sun = sunEvents(nowMs);
1405
- add(makeEntity("sun.sun", isSunUp(nowMs) ? "above_horizon" : "below_horizon", {
1406
- friendly_name: "Sun",
1407
- elevation: sun.elevation,
1408
- next_rising: sun.nextRising,
1409
- next_setting: sun.nextSetting,
1410
- rising: sun.rising
1411
- }), {});
1412
- for (const s of [
1413
- {
1414
- id: "sensor.solar_power",
1415
- name: "Solar Production",
1416
- deviceClass: "power",
1417
- unit: "W"
1418
- },
1419
- {
1420
- id: "sensor.grid_import_power",
1421
- name: "Grid Import",
1422
- deviceClass: "power",
1423
- unit: "W"
1424
- },
1425
- {
1426
- id: "sensor.grid_export_power",
1427
- name: "Grid Export",
1428
- deviceClass: "power",
1429
- unit: "W"
1430
- },
1431
- {
1432
- id: "sensor.battery_charge_power",
1433
- name: "Battery Charge",
1434
- deviceClass: "power",
1435
- unit: "W"
1436
- },
1437
- {
1438
- id: "sensor.battery_discharge_power",
1439
- name: "Battery Discharge",
1440
- deviceClass: "power",
1441
- unit: "W"
1442
- },
1443
- {
1444
- id: "sensor.battery_soc",
1445
- name: "Battery",
1446
- deviceClass: "battery",
1447
- unit: "%"
1448
- },
1449
- {
1450
- id: "sensor.home_power",
1451
- name: "Home Consumption",
1452
- deviceClass: "power",
1453
- unit: "W"
1454
- },
1455
- {
1456
- id: "sensor.fridge_power",
1457
- name: "Fridge",
1458
- deviceClass: "power",
1459
- unit: "W"
1460
- },
1461
- {
1462
- id: "sensor.dishwasher_power",
1463
- name: "Dishwasher",
1464
- deviceClass: "power",
1465
- unit: "W"
1466
- },
1467
- {
1468
- id: "sensor.washing_machine_power",
1469
- name: "Washing Machine",
1470
- deviceClass: "power",
1471
- unit: "W"
1472
- },
1473
- {
1474
- id: "sensor.oven_power",
1475
- name: "Oven",
1476
- deviceClass: "power",
1477
- unit: "W"
1478
- },
1479
- {
1480
- id: "sensor.ev_charger_power",
1481
- name: "EV Charger",
1482
- deviceClass: "power",
1483
- unit: "W"
1484
- },
1485
- {
1486
- id: "sensor.always_on_power",
1487
- name: "Always On",
1488
- deviceClass: "power",
1489
- unit: "W"
1490
- }
1491
- ]) {
1492
- const value = energyEntityValue(s.id, sample) ?? 0;
1493
- add(makeEntity(s.id, formatEnergyState(s.id, value), {
1494
- friendly_name: s.name,
1495
- unit_of_measurement: s.unit,
1496
- device_class: s.deviceClass,
1497
- state_class: "measurement"
1498
- }), {
1499
- area_id: "utility",
1500
- device_class: s.deviceClass,
1501
- unit_of_measurement: s.unit
1502
- });
1503
- }
1504
- return {
1505
- entities,
1506
- entityRegistry,
1507
- areas,
1508
- devices
1509
- };
1510
- }
1511
- //#endregion
1512
- //#region src/demo/demo-provider.ts
1513
- /**
1514
- * Demo Mode Provider
1515
- *
1516
- * Loads demo fixtures into the SolidJS store and provides
1517
- * optimistic local state updates for service calls (toggle, turnOn, turnOff).
1518
- *
1519
- * @packageDocumentation
1520
- */
1521
- let _isDemoMode = false;
1522
- /**
1523
- * Whether demo mode is currently active.
1524
- */
1525
- function isDemoMode() {
1526
- return _isDemoMode;
1527
- }
1528
- /**
1529
- * Load demo fixtures into the SolidJS store.
1530
- *
1531
- * Populates entities, entity registry, areas, and devices.
1532
- * Sets connection state to "connected" (pretend connected).
1533
- */
1534
- async function loadDemoData() {
1535
- const fixtures = createDemoFixtures();
1536
- setState("entities", reconcile(fixtures.entities));
1537
- setState("entityRegistry", reconcile(fixtures.entityRegistry));
1538
- setState("areas", reconcile(fixtures.areas));
1539
- setState("devices", reconcile(fixtures.devices));
1540
- setState("hassUrl", "https://demo.home-assistant.local");
1541
- setState("connectionState", "connected");
1542
- _isDemoMode = true;
1543
- startDemoEnergyTicker();
1544
- }
1545
- /**
1546
- * Unload demo data and reset to disconnected state.
1547
- */
1548
- function unloadDemoData() {
1549
- stopDemoEnergyTicker();
1550
- setState("entities", reconcile({}));
1551
- setState("entityRegistry", reconcile({}));
1552
- setState("areas", reconcile({}));
1553
- setState("devices", reconcile({}));
1554
- setState("hassUrl", null);
1555
- setState("connectionState", "disconnected");
1556
- _isDemoMode = false;
1557
- }
1558
- const ENERGY_TICK_MS = 5e3;
1559
- let _energyTicker = null;
1560
- /** Write the current energy sample into the store as string states (like real HA). */
1561
- function tickEnergy() {
1562
- const nowMs = Date.now();
1563
- const sample = simulateEnergy(nowMs);
1564
- const sun = sunEvents(nowMs);
1565
- const nowIso = new Date(nowMs).toISOString();
1566
- setState(produce((s) => {
1567
- for (const entityId of ENERGY_ENTITY_IDS) {
1568
- const e = s.entities[entityId];
1569
- if (!e) continue;
1570
- const value = energyEntityValue(entityId, sample);
1571
- if (value === void 0) continue;
1572
- const next = formatEnergyState(entityId, value);
1573
- if (e.state !== next) e.last_changed = nowIso;
1574
- e.state = next;
1575
- e.last_updated = nowIso;
1576
- }
1577
- const sunEntity = s.entities["sun.sun"];
1578
- if (sunEntity) {
1579
- const nextState = isSunUp(nowMs) ? "above_horizon" : "below_horizon";
1580
- if (sunEntity.state !== nextState) sunEntity.last_changed = nowIso;
1581
- sunEntity.state = nextState;
1582
- sunEntity.last_updated = nowIso;
1583
- sunEntity.attributes.elevation = sun.elevation;
1584
- sunEntity.attributes.next_rising = sun.nextRising;
1585
- sunEntity.attributes.next_setting = sun.nextSetting;
1586
- sunEntity.attributes.rising = sun.rising;
1587
- }
1588
- }));
1589
- }
1590
- /**
1591
- * Start the demo energy ticker. Updates the energy sensors and `sun.sun`
1592
- * every 5 seconds. Idempotent: clears any prior interval first. SSR-safe.
1593
- */
1594
- function startDemoEnergyTicker() {
1595
- stopDemoEnergyTicker();
1596
- if (typeof setInterval !== "function") return;
1597
- tickEnergy();
1598
- _energyTicker = setInterval(tickEnergy, ENERGY_TICK_MS);
1599
- }
1600
- /** Stop the demo energy ticker if running. */
1601
- function stopDemoEnergyTicker() {
1602
- if (_energyTicker !== null) {
1603
- clearInterval(_energyTicker);
1604
- _energyTicker = null;
1605
- }
1606
- }
1607
- /**
1608
- * Apply an optimistic state update for demo mode.
1609
- *
1610
- * When a service call is made in demo mode, this updates the entity
1611
- * state locally (no WebSocket message sent). State resets on page refresh.
1612
- */
1613
- function applyDemoServiceCall(_domain, service, _serviceData = {}, target = {}) {
1614
- if (!_isDemoMode) return;
1615
- const entityIds = Array.isArray(target.entity_id) ? target.entity_id : target.entity_id ? [target.entity_id] : [];
1616
- for (const entityId of entityIds) {
1617
- if (!state.entities[entityId]) continue;
1618
- const entityDomain = extractDomain(entityId);
1619
- setState(produce((s) => {
1620
- const e = s.entities[entityId];
1621
- if (!e) return;
1622
- const now = (/* @__PURE__ */ new Date()).toISOString();
1623
- e.last_changed = now;
1624
- e.last_updated = now;
1625
- if (service === "turn_on") applyTurnOn(e, entityDomain, _serviceData);
1626
- else if (service === "press" && entityDomain === "button") e.state = now;
1627
- else if (service === "turn_off") applyTurnOff(e, entityDomain);
1628
- else if (service === "toggle") {
1629
- if (e.state === "on" || e.state === "playing" || e.state === "open") applyTurnOff(e, entityDomain);
1630
- else applyTurnOn(e, entityDomain, _serviceData);
1631
- } else if (service === "lock") e.state = "locked";
1632
- else if (service === "unlock") e.state = "unlocked";
1633
- else if (service === "open_cover") {
1634
- e.state = "open";
1635
- if ("current_position" in e.attributes) e.attributes.current_position = 100;
1636
- } else if (service === "close_cover") {
1637
- e.state = "closed";
1638
- if ("current_position" in e.attributes) e.attributes.current_position = 0;
1639
- } else if (service === "set_cover_position" && _serviceData.position != null) {
1640
- e.attributes.current_position = _serviceData.position;
1641
- e.state = _serviceData.position > 0 ? "open" : "closed";
1642
- } else if (service === "open_cover_tilt") e.attributes.current_tilt_position = 100;
1643
- else if (service === "close_cover_tilt") e.attributes.current_tilt_position = 0;
1644
- else if (service === "set_cover_tilt_position" && _serviceData.tilt_position != null) e.attributes.current_tilt_position = _serviceData.tilt_position;
1645
- else if (service === "set_temperature") {
1646
- if (_serviceData.temperature != null) e.attributes.temperature = _serviceData.temperature;
1647
- if (_serviceData.target_temp_low != null) e.attributes.target_temp_low = _serviceData.target_temp_low;
1648
- if (_serviceData.target_temp_high != null) e.attributes.target_temp_high = _serviceData.target_temp_high;
1649
- } else if (service === "set_hvac_mode" && _serviceData.hvac_mode != null) e.state = _serviceData.hvac_mode;
1650
- else if (service === "set_fan_mode" && _serviceData.fan_mode != null) e.attributes.fan_mode = _serviceData.fan_mode;
1651
- else if (service === "set_preset_mode" && _serviceData.preset_mode != null) {
1652
- e.attributes.preset_mode = _serviceData.preset_mode;
1653
- if (entityDomain === "fan") e.state = "on";
1654
- } else if (service === "set_percentage" && _serviceData.percentage != null) {
1655
- e.attributes.percentage = _serviceData.percentage;
1656
- e.state = _serviceData.percentage > 0 ? "on" : "off";
1657
- } else if (service === "oscillate" && _serviceData.oscillating != null) e.attributes.oscillating = _serviceData.oscillating;
1658
- else if (service === "set_direction" && _serviceData.direction != null) e.attributes.current_direction = _serviceData.direction;
1659
- else if (service === "set_operation_mode" && _serviceData.operation_mode != null) e.state = _serviceData.operation_mode;
1660
- else if (service === "set_away_mode" && _serviceData.away_mode != null) e.attributes.away_mode = _serviceData.away_mode ? "on" : "off";
1661
- else if (service === "volume_set" && _serviceData.volume_level != null) e.attributes.volume_level = _serviceData.volume_level;
1662
- else if (service === "media_play_pause") e.state = e.state === "playing" ? "paused" : "playing";
1663
- else if (service === "media_next_track" || service === "media_previous_track") applyTrackSkip(e, service === "media_next_track" ? 1 : -1);
1664
- else if (service === "select_source" && _serviceData.source != null) e.attributes.source = _serviceData.source;
1665
- }));
1666
- }
1667
- }
1668
- function applyTurnOn(e, domain, serviceData = {}) {
1669
- if (domain === "light") {
1670
- e.state = "on";
1671
- if (serviceData.brightness_pct !== void 0) {
1672
- const pct = Math.max(0, Math.min(100, serviceData.brightness_pct));
1673
- e.attributes.brightness = Math.round(pct / 100 * 255);
1674
- } else e.attributes.brightness = serviceData.brightness ?? e.attributes.brightness ?? 255;
1675
- if (serviceData.color_temp_kelvin) e.attributes.color_temp_kelvin = serviceData.color_temp_kelvin;
1676
- if (serviceData.hs_color) e.attributes.hs_color = serviceData.hs_color;
1677
- } else if (domain === "scene") e.state = (/* @__PURE__ */ new Date()).toISOString();
1678
- else if (domain === "media_player") e.state = "playing";
1679
- else if (domain === "cover") {
1680
- e.state = "open";
1681
- if ("current_position" in e.attributes) e.attributes.current_position = 100;
1682
- } else e.state = "on";
1683
- }
1684
- const DEMO_TRACKS = [
1685
- {
1686
- title: "Lo-fi Beats",
1687
- artist: "Chill Station"
1688
- },
1689
- {
1690
- title: "Golden Hour",
1691
- artist: "Analog Sunset"
1692
- },
1693
- {
1694
- title: "Night Drive",
1695
- artist: "Neon Coast"
1696
- }
1697
- ];
1698
- function applyTrackSkip(e, delta) {
1699
- const current = DEMO_TRACKS.findIndex((t) => t.title === e.attributes.media_title);
1700
- const next = DEMO_TRACKS[(current + delta + DEMO_TRACKS.length) % DEMO_TRACKS.length];
1701
- if (!next) return;
1702
- e.attributes.media_title = next.title;
1703
- e.attributes.media_artist = next.artist;
1704
- }
1705
- function applyTurnOff(e, domain) {
1706
- if (domain === "light") {
1707
- e.state = "off";
1708
- delete e.attributes.brightness;
1709
- } else if (domain === "media_player") e.state = "paused";
1710
- else if (domain === "cover") {
1711
- e.state = "closed";
1712
- if ("current_position" in e.attributes) e.attributes.current_position = 0;
1713
- } else e.state = "off";
1714
- }
1715
- //#endregion
1716
- //#region src/weather/fetch.ts
1717
- /**
1718
- * Weather Forecast Fetching
1719
- *
1720
- * @packageDocumentation
1721
- */
1722
- const DEMO_RAIN_CHANCE = {
1723
- sunny: 0,
1724
- "clear-night": 0,
1725
- partlycloudy: 10,
1726
- cloudy: 20,
1727
- windy: 10,
1728
- fog: 10,
1729
- rainy: 80,
1730
- pouring: 95,
1731
- lightning: 60,
1732
- "lightning-rainy": 85,
1733
- snowy: 70,
1734
- "snowy-rainy": 75,
1735
- hail: 70,
1736
- exceptional: 40
1737
- };
1738
- /**
1739
- * In demo mode, derive forecasts from the entity's `forecast` attribute.
1740
- * Hourly and daily are synthesised from the same source (daily entries
1741
- * expanded into 24 hourly steps).
1742
- */
1743
- function buildDemoForecast(entityId, type) {
1744
- const entity = state.entities[entityId];
1745
- const raw = entity?.attributes?.forecast ?? [];
1746
- if (raw.length === 0) return [];
1747
- if (type === "daily" || type === "twice_daily") return raw.map((d) => {
1748
- const chance = DEMO_RAIN_CHANCE[d.condition ?? ""] ?? 10;
1749
- const templow = d.templow;
1750
- return {
1751
- ...d,
1752
- temp_high: d.temp_high ?? d.temperature,
1753
- temp_low: d.temp_low ?? templow,
1754
- precipitation_probability: d.precipitation_probability ?? chance
1755
- };
1756
- });
1757
- const start = /* @__PURE__ */ new Date();
1758
- start.setMinutes(0, 0, 0);
1759
- const today = raw[0];
1760
- const tomorrow = raw[1] ?? today;
1761
- const tHi = today?.temperature ?? 18;
1762
- const tLo = today?.templow ?? tHi - 5;
1763
- const tNext = tomorrow?.temperature ?? tHi;
1764
- const out = [];
1765
- for (let i = 0; i < 24; i++) {
1766
- const dt = new Date(start.getTime() + i * 60 * 60 * 1e3);
1767
- const hour = dt.getHours();
1768
- const dayMix = i < 12 ? 0 : (i - 12) / 12;
1769
- const baseHi = tHi * (1 - dayMix) + tNext * dayMix;
1770
- const phase = (hour - 6) / 24 * Math.PI * 2;
1771
- const swing = (baseHi - tLo) / 2;
1772
- const mid = (baseHi + tLo) / 2;
1773
- const source = i < 8 ? today : tomorrow;
1774
- const night = hour < 6 || hour >= 21;
1775
- const condition = source?.condition ?? entity?.state ?? "cloudy";
1776
- out.push({
1777
- datetime: dt.toISOString(),
1778
- temperature: Math.round((mid + Math.sin(phase) * swing) * 10) / 10,
1779
- condition: night && condition === "sunny" ? "clear-night" : condition,
1780
- precipitation_probability: DEMO_RAIN_CHANCE[condition] ?? 10
1781
- });
1782
- }
1783
- return out;
1784
- }
1785
- /**
1786
- * Fetch forecast for a single entity and type
1787
- */
1788
- async function fetchForecast(entityId, type) {
1789
- if (isDemoMode()) return buildDemoForecast(entityId, type);
1790
- const conn = privilegedConn();
1791
- if (!conn) throw new Error("Not connected");
1792
- return new Promise((resolve, reject) => {
1793
- let resolved = false;
1794
- let unsubscribe = null;
1795
- const timeout = setTimeout(() => {
1796
- if (!resolved && unsubscribe) {
1797
- resolved = true;
1798
- unsubscribe().then(() => reject(/* @__PURE__ */ new Error("Forecast subscription timeout"))).catch(() => reject(/* @__PURE__ */ new Error("Forecast subscription timeout")));
1799
- }
1800
- }, 1e4);
1801
- conn.subscribeMessage((event) => {
1802
- if (resolved) return;
1803
- if (event && typeof event === "object" && "forecast" in event) {
1804
- resolved = true;
1805
- clearTimeout(timeout);
1806
- const forecast = event.forecast;
1807
- const forecastArray = Array.isArray(forecast) ? forecast : [];
1808
- if (unsubscribe) unsubscribe().then(() => resolve(forecastArray)).catch(() => resolve(forecastArray));
1809
- else resolve(forecastArray);
1810
- }
1811
- }, {
1812
- type: "weather/subscribe_forecast",
1813
- entity_id: entityId,
1814
- forecast_type: type === "twice_daily" ? "twice_daily" : type
1815
- }).then((unsubFn) => {
1816
- unsubscribe = unsubFn;
1817
- }).catch((error) => {
1818
- resolved = true;
1819
- clearTimeout(timeout);
1820
- reject(error);
1821
- });
1822
- });
1823
- }
1824
- /**
1825
- * Fetch forecasts for a single entity and multiple types
1826
- */
1827
- async function fetchForecasts(entityId, types) {
1828
- const forecasts = {};
1829
- const loading = {};
1830
- const errors = {};
1831
- const lastFetched = {};
1832
- const fetchPromises = types.map(async (type) => {
1833
- loading[type] = true;
1834
- errors[type] = null;
1835
- try {
1836
- const forecast = await fetchForecast(entityId, type);
1837
- forecasts[type] = forecast;
1838
- lastFetched[type] = Date.now();
1839
- loading[type] = false;
1840
- } catch (error) {
1841
- errors[type] = error instanceof Error ? error : new Error(String(error));
1842
- forecasts[type] = [];
1843
- loading[type] = false;
1844
- lastFetched[type] = null;
1845
- }
1846
- });
1847
- await Promise.all(fetchPromises);
1848
- return {
1849
- entityId,
1850
- forecasts,
1851
- loading,
1852
- errors,
1853
- lastFetched
1854
- };
1855
- }
1856
- /**
1857
- * Fetch forecast data with error handling
1858
- */
1859
- async function fetchForecastData(entityId, type) {
1860
- try {
1861
- return {
1862
- entityId,
1863
- type,
1864
- forecast: await fetchForecast(entityId, type),
1865
- loading: false,
1866
- error: null,
1867
- lastFetched: Date.now()
1868
- };
1869
- } catch (error) {
1870
- return {
1871
- entityId,
1872
- type,
1873
- forecast: [],
1874
- loading: false,
1875
- error: error instanceof Error ? error : new Error(String(error)),
1876
- lastFetched: null
1877
- };
1878
- }
1879
- }
1880
- //#endregion
1881
- //#region src/weather/track.ts
1882
- /**
1883
- * Ref-counted live forecasts, the weather analog of `calendar/track`. Each
1884
- * tracked (entity, type) holds one `weather/subscribe_forecast`; Home Assistant
1885
- * pushes the current forecast, then every new one. Data lands in
1886
- * `state.forecasts`, the same place `getForecasts` writes.
1887
- */
1888
- /** Debounce for untrack, so dashboard switches don't churn subscriptions. */
1889
- const UNTRACK_FLUSH_DELAY_MS = 5e3;
1890
- const counts = /* @__PURE__ */ new Map();
1891
- const active = /* @__PURE__ */ new Map();
1892
- const chains = /* @__PURE__ */ new Map();
1893
- let untrackTimer = null;
1894
- const keyOf = (entityId, type) => `${entityId}|${type}`;
1895
- function parse(key) {
1896
- const i = key.lastIndexOf("|");
1897
- return [key.slice(0, i), key.slice(i + 1)];
1898
- }
1899
- /**
1900
- * Keep a forecast live while tracked. Returns the untrack function. Safe while
1901
- * disconnected: the subscription starts on the next `forceResubscribeForecasts()`.
1902
- */
1903
- function trackForecast(entityId, type) {
1904
- const key = keyOf(entityId, type);
1905
- counts.set(key, (counts.get(key) ?? 0) + 1);
1906
- queueMicrotask(() => {
1907
- reconcile$1(key);
1908
- });
1909
- let untracked = false;
1910
- return () => {
1911
- if (untracked) return;
1912
- untracked = true;
1913
- const n = (counts.get(key) ?? 1) - 1;
1914
- if (n > 0) counts.set(key, n);
1915
- else counts.delete(key);
1916
- if (untrackTimer) return;
1917
- untrackTimer = setTimeout(() => {
1918
- untrackTimer = null;
1919
- flushAll();
1920
- }, UNTRACK_FLUSH_DELAY_MS);
1921
- };
1922
- }
1923
- async function flushAll() {
1924
- const keys = /* @__PURE__ */ new Set([...counts.keys(), ...active.keys()]);
1925
- await Promise.all([...keys].map(reconcile$1));
1926
- }
1927
- function reconcile$1(key) {
1928
- const next = (chains.get(key) ?? Promise.resolve()).then(() => runReconcile(key));
1929
- chains.set(key, next.catch(() => {}));
1930
- return next;
1931
- }
1932
- function write(entityId, type, forecast, error) {
1933
- setState(produce((s) => {
1934
- const rec = s.forecasts[entityId] ??= {
1935
- entityId,
1936
- forecasts: {},
1937
- loading: {},
1938
- errors: {},
1939
- lastFetched: {}
1940
- };
1941
- if (forecast) {
1942
- rec.forecasts[type] = forecast;
1943
- rec.lastFetched[type] = Date.now();
1944
- }
1945
- rec.loading[type] = false;
1946
- rec.errors[type] = error;
1947
- }));
1948
- }
1949
- async function runReconcile(key) {
1950
- const [entityId, type] = parse(key);
1951
- const current = active.get(key);
1952
- if (!counts.has(key)) {
1953
- active.delete(key);
1954
- chains.delete(key);
1955
- try {
1956
- await current?.unsub?.();
1957
- } catch {}
1958
- return;
1959
- }
1960
- if (current?.unsub) return;
1961
- if (isDemoMode()) {
1962
- active.set(key, { unsub: () => {} });
1963
- write(entityId, type, buildDemoForecast(entityId, type), null);
1964
- return;
1965
- }
1966
- const conn = privilegedConn();
1967
- if (!conn) return;
1968
- const entry = { unsub: null };
1969
- active.set(key, entry);
1970
- try {
1971
- entry.unsub = await conn.subscribeMessage((msg) => write(entityId, type, Array.isArray(msg?.forecast) ? msg.forecast : [], null), {
1972
- type: "weather/subscribe_forecast",
1973
- entity_id: entityId,
1974
- forecast_type: type
1975
- });
1976
- } catch (err) {
1977
- active.delete(key);
1978
- write(entityId, type, null, err instanceof Error ? err : new Error(String(err)));
1979
- }
1980
- }
1981
- //#endregion
1982
- //#region src/connection/subscription-manager.ts
1983
- if (globalThis.__GH_SYNC_LAYER_SUB_MGR__) console.error("[@glasshome/sync-layer] DUPLICATE subscription-manager module instantiated. registerEntity() and the connection setter will hit different singletons → subscribe_entities will never be sent. Cause: relative import of subscription-manager from a separate entry point.");
1984
- globalThis.__GH_SYNC_LAYER_SUB_MGR__ = true;
1985
- /** Ref counts — how many consumers need each entity */
1986
- const refCounts = /* @__PURE__ */ new Map();
1987
- /** Current HA subscription unsub function */
1988
- let currentEntityUnsub = null;
1989
- /** Snapshot of entity IDs in the current HA subscription */
1990
- let subscribedIds = /* @__PURE__ */ new Set();
1991
- /** Connection reference for resubscribing */
1992
- let conn = null;
1993
- /** Pending flush timer (microtask for register, timeout for unregister) */
1994
- let flushScheduled = false;
1995
- /** Delayed unregister timeout */
1996
- let unregisterTimeout = null;
1997
- /** Callback invoked on resubscribe — set by subscriptions.ts */
1998
- let onResubscribe = null;
1999
- /** Delay before unregistered entities are actually removed from subscription */
2000
- const UNREGISTER_DELAY_MS = 5e3;
2001
- /** Guard against concurrent flush() calls */
2002
- let flushInFlight = false;
2003
- /**
2004
- * Register an entity for live updates. Returns an unregister function.
2005
- * Call from useEntity/useEntities hooks via onCleanup.
2006
- */
2007
- function registerEntity(entityId) {
2008
- refCounts.set(entityId, (refCounts.get(entityId) ?? 0) + 1);
2009
- scheduleFlush();
2010
- return () => unregisterEntity(entityId);
2011
- }
2012
- /**
2013
- * Set the connection reference used for resubscribing.
2014
- */
2015
- function setManagerConnection(connection) {
2016
- conn = connection;
2017
- if (refCounts.size > 0) scheduleFlush();
2018
- }
2019
- /**
2020
- * Set the resubscribe callback. Called by subscriptions.ts to wire
2021
- * the manager into the actual WS subscription lifecycle.
2022
- */
2023
- function setResubscribeHandler(handler) {
2024
- onResubscribe = handler;
2025
- }
2026
- /**
2027
- * Force a resubscribe with the current active set.
2028
- * Used on reconnect.
2029
- */
2030
- async function forceResubscribe() {
2031
- await flush();
2032
- }
2033
- function unregisterEntity(entityId) {
2034
- const count = (refCounts.get(entityId) ?? 1) - 1;
2035
- if (count <= 0) refCounts.delete(entityId);
2036
- else refCounts.set(entityId, count);
2037
- scheduleDelayedFlush();
2038
- }
2039
- function scheduleFlush() {
2040
- if (flushScheduled) return;
2041
- flushScheduled = true;
2042
- queueMicrotask(() => {
2043
- flushScheduled = false;
2044
- flush();
2045
- });
2046
- }
2047
- function scheduleDelayedFlush() {
2048
- if (unregisterTimeout) return;
2049
- unregisterTimeout = setTimeout(() => {
2050
- unregisterTimeout = null;
2051
- flush();
2052
- }, UNREGISTER_DELAY_MS);
2053
- }
2054
- async function flush() {
2055
- if (!conn || !onResubscribe) return;
2056
- if (flushInFlight) return;
2057
- flushInFlight = true;
2058
- try {
2059
- const newIds = new Set(refCounts.keys());
2060
- if (setsEqual(newIds, subscribedIds)) return;
2061
- const oldUnsub = currentEntityUnsub;
2062
- const entityIds = [...newIds];
2063
- currentEntityUnsub = await onResubscribe(conn, entityIds);
2064
- subscribedIds = newIds;
2065
- if (oldUnsub) try {
2066
- await oldUnsub();
2067
- } catch {}
2068
- } finally {
2069
- flushInFlight = false;
2070
- }
2071
- }
2072
- function setsEqual(a, b) {
2073
- if (a.size !== b.size) return false;
2074
- for (const id of a) if (!b.has(id)) return false;
2075
- return true;
2076
- }
2077
- //#endregion
2078
- //#region src/commands/service.ts
2079
- /**
2080
- * Call a Home Assistant service
2081
- */
2082
- async function callService(domain, service, serviceData = {}, target = {}) {
2083
- const connection = privilegedConn();
2084
- if (!connection) {
2085
- applyDemoServiceCall(domain, service, serviceData, target);
2086
- return;
2087
- }
2088
- try {
2089
- const mockConnection = connection;
2090
- if (mockConnection && typeof mockConnection.callService === "function") await mockConnection.callService(domain, service, serviceData, target);
2091
- else await connection.sendMessagePromise({
2092
- type: "call_service",
2093
- domain,
2094
- service,
2095
- service_data: serviceData,
2096
- target
2097
- });
2098
- } catch (error) {
2099
- throw new Error(`Service call failed: ${error.message || String(error)}`);
2100
- }
2101
- }
2102
- /**
2103
- * Turn on entity or entities
2104
- */
2105
- async function turnOn(entityId, serviceData = {}) {
2106
- const firstEntityId = Array.isArray(entityId) ? entityId[0] : entityId;
2107
- if (!firstEntityId) throw new Error("Entity ID is required");
2108
- const domain = firstEntityId.split(".")[0];
2109
- if (!domain) throw new Error(`Invalid entity ID: ${firstEntityId}`);
2110
- await callService(domain, "turn_on", serviceData, { entity_id: entityId });
2111
- }
2112
- /**
2113
- * Turn off entity or entities
2114
- */
2115
- async function turnOff(entityId, serviceData = {}) {
2116
- const firstEntityId = Array.isArray(entityId) ? entityId[0] : entityId;
2117
- if (!firstEntityId) throw new Error("Entity ID is required");
2118
- const domain = firstEntityId.split(".")[0];
2119
- if (!domain) throw new Error(`Invalid entity ID: ${firstEntityId}`);
2120
- await callService(domain, "turn_off", serviceData, { entity_id: entityId });
2121
- }
2122
- /**
2123
- * Toggle entity or entities
2124
- */
2125
- async function toggle(entityId, serviceData = {}) {
2126
- const firstEntityId = Array.isArray(entityId) ? entityId[0] : entityId;
2127
- if (!firstEntityId) throw new Error("Entity ID is required");
2128
- const domain = firstEntityId.split(".")[0];
2129
- if (!domain) throw new Error(`Invalid entity ID: ${firstEntityId}`);
2130
- await callService(domain, "toggle", serviceData, { entity_id: entityId });
2131
- }
2132
- /**
2133
- * Update entity registry entry
2134
- */
2135
- async function updateEntity(entityId, updates) {
2136
- const connection = privilegedConn();
2137
- if (!connection) throw new Error("Not connected to Home Assistant. Call initConnection() first.");
2138
- try {
2139
- const result = await connection.sendMessagePromise({
2140
- type: "config/entity_registry/update",
2141
- entity_id: entityId,
2142
- ...updates
2143
- });
2144
- if (result && typeof result === "object" && "_mockError" in result) throw new Error(`Entity registry entry not found: ${entityId}`);
2145
- return result;
2146
- } catch (error) {
2147
- if (error?.message && error.message.includes("Entity registry entry not found")) throw error;
2148
- throw new Error(`Entity update failed: ${error.message || String(error)}`);
2149
- }
2150
- }
2151
- /**
2152
- * Send a generic WebSocket command
2153
- */
2154
- async function sendCommand(command) {
2155
- const connection = privilegedConn();
2156
- if (!connection) throw new Error("Not connected");
2157
- try {
2158
- return await connection.sendMessagePromise(command);
2159
- } catch (error) {
2160
- throw new Error(`Command failed: ${error.message || String(error)}`);
2161
- }
2162
- }
2163
- /**
2164
- * Execute multiple service calls in parallel
2165
- */
2166
- async function batchServiceCalls(calls) {
2167
- await Promise.all(calls.map((call) => callService(call.domain, call.service, call.serviceData, call.target)));
2168
- }
2169
- /**
2170
- * Execute multiple entity updates in parallel
2171
- */
2172
- async function batchEntityUpdates(updates) {
2173
- return Promise.all(updates.map((u) => updateEntity(u.entityId, u.updates)));
2174
- }
2175
- //#endregion
2176
- //#region src/demo/sensor-history.ts
2177
- const DAY_MS = 864e5;
2178
- function seedOf(entityId) {
2179
- let h = 0;
2180
- for (let i = 0; i < entityId.length; i++) h = h * 31 + entityId.charCodeAt(i) | 0;
2181
- return Math.abs(h) % 1e3 / 1e3;
2182
- }
2183
- /**
2184
- * A slow daily swing plus a faster ripple, pinned so the last point is the reading
2185
- * the demo shows now. Deterministic per entity, so previews repeat.
2186
- */
2187
- function synthesizeSensorHistory(entityId, current, startMs, endMs, stepMs = 9e5) {
2188
- const amplitude = Math.max(Math.abs(current) * .08, .6);
2189
- const phase = seedOf(entityId) * 2 * Math.PI;
2190
- const wave = (t) => Math.sin(2 * Math.PI * t / DAY_MS + phase) + .15 * Math.sin(2 * Math.PI * t * 3 / DAY_MS + 2 * phase);
2191
- const decimals = Number.isInteger(current) ? 1 : 2;
2192
- const points = [];
2193
- for (let t = startMs; t <= endMs; t += stepMs) {
2194
- const value = current + amplitude * (wave(t) - wave(endMs));
2195
- points.push({
2196
- lu: Math.round(t / 1e3),
2197
- s: value.toFixed(decimals)
2198
- });
2199
- }
2200
- const last = points.at(-1);
2201
- if (last) last.s = String(current);
2202
- return points;
2203
- }
2204
- function currentReading(id) {
2205
- if (!id.startsWith("sensor.")) return void 0;
2206
- const current = Number(state.entities[id]?.state);
2207
- return Number.isFinite(current) ? current : void 0;
2208
- }
2209
- /** History for a demo sensor with a numeric reading; undefined for anything else. */
2210
- function numericSensorHistory(id, startMs, endMs) {
2211
- const current = currentReading(id);
2212
- return current === void 0 ? void 0 : synthesizeSensorHistory(id, current, startMs, endMs);
2213
- }
2214
- /** Hour or day buckets of the same curve, shaped like recorder statistics. */
2215
- function numericSensorStatistics(id, startMs, endMs, period) {
2216
- const points = numericSensorHistory(id, startMs, endMs);
2217
- if (!points) return [];
2218
- const span = period === "hour" ? 36e5 : DAY_MS;
2219
- const buckets = [];
2220
- for (let start = startMs; start < endMs; start += span) {
2221
- const end = start + span;
2222
- const values = points.filter((p) => p.lu * 1e3 >= start && p.lu * 1e3 < end).map((p) => Number(p.s));
2223
- if (values.length === 0) continue;
2224
- const mean = values.reduce((a, b) => a + b, 0) / values.length;
2225
- buckets.push({
2226
- start,
2227
- end,
2228
- mean,
2229
- min: Math.min(...values),
2230
- max: Math.max(...values),
2231
- sum: 0,
2232
- change: 0
2233
- });
2234
- }
2235
- return buckets;
2236
- }
2237
- //#endregion
2238
- //#region src/entities/views.ts
2239
- /**
2240
- * Get icon for an entity from registry or attributes
2241
- */
2242
- function resolveIcon(entity, registry) {
2243
- if (registry?.icon) return {
2244
- icon: registry.icon,
2245
- source: "registry"
2246
- };
2247
- if (entity.attributes?.icon) return {
2248
- icon: entity.attributes.icon,
2249
- source: "attribute"
2250
- };
2251
- return null;
2252
- }
2253
- /**
2254
- * Build an EntityView from runtime state and registry metadata
2255
- */
2256
- function buildEntityView(entity, registry) {
2257
- const domain = extractDomain(entity.entity_id);
2258
- const attributes = entity.attributes ?? {};
2259
- const friendlyName = attributes.friendly_name ?? registry?.name ?? entity.entity_id;
2260
- const name = registry?.name ?? friendlyName;
2261
- const iconResolution = resolveIcon(entity, registry);
2262
- const { device_class: _dc, unit_of_measurement: _uom, friendly_name: _fn, icon: _icon, ...restAttributes } = attributes;
2263
- let areaId = registry?.area_id ?? null;
2264
- if (areaId === null && registry?.device_id) {
2265
- const device = state.devices[registry.device_id];
2266
- if (device) areaId = device.area_id ?? null;
2267
- }
2268
- return {
2269
- id: entity.entity_id,
2270
- domain,
2271
- state: entity.state,
2272
- attributes: restAttributes,
2273
- lastChanged: new Date(entity.last_changed),
2274
- lastUpdated: new Date(entity.last_updated),
2275
- context: {
2276
- id: entity.context?.id ?? "",
2277
- parentId: entity.context?.parent_id ?? null,
2278
- userId: entity.context?.user_id ?? null
2279
- },
2280
- name,
2281
- friendlyName,
2282
- areaId,
2283
- deviceId: registry?.device_id ?? null,
2284
- platform: registry?.platform ?? "unknown",
2285
- uniqueId: registry?.unique_id ?? null,
2286
- isDisabled: registry?.disabled_by !== null && registry?.disabled_by !== void 0,
2287
- isHidden: registry?.hidden_by !== null && registry?.hidden_by !== void 0,
2288
- icon: iconResolution?.icon ?? null,
2289
- iconSource: iconResolution?.source ?? "default",
2290
- entityCategory: registry?.entity_category ?? null,
2291
- labels: registry?.labels ?? [],
2292
- aliases: registry?.aliases ?? [],
2293
- deviceClass: registry?.device_class ?? attributes.device_class ?? null,
2294
- unitOfMeasurement: registry?.unit_of_measurement ?? attributes.unit_of_measurement ?? null,
2295
- supportedFeatures: registry?.supported_features ?? attributes.supported_features
2296
- };
2297
- }
2298
- /**
2299
- * Get or build an EntityView
2300
- */
2301
- function getEntityView(entityId) {
2302
- const entity = state.entities[entityId];
2303
- if (!entity) return;
2304
- const registry = state.entityRegistry[entityId];
2305
- return buildEntityView(entity, registry);
2306
- }
2307
- /**
2308
- * Get multiple entity views
2309
- */
2310
- function getEntityViews(entityIds) {
2311
- const views = [];
2312
- for (const id of entityIds) {
2313
- const view = getEntityView(id);
2314
- if (view) views.push(view);
2315
- }
2316
- return views;
2317
- }
2318
- /**
2319
- * Get all entity views
2320
- */
2321
- function getAllEntityViews() {
2322
- return getEntityViews(Object.keys(state.entities));
2323
- }
2324
- /**
2325
- * Shallow equality check for EntityView.
2326
- * Compares fields that affect rendering; skips lastUpdated (heartbeat noise).
2327
- */
2328
- function entityViewEquals(a, b) {
2329
- if (a === b) return true;
2330
- if (!a || !b) return false;
2331
- return a.id === b.id && a.state === b.state && a.lastChanged.getTime() === b.lastChanged.getTime() && a.name === b.name && a.friendlyName === b.friendlyName && a.areaId === b.areaId && a.deviceId === b.deviceId && a.icon === b.icon && a.isDisabled === b.isDisabled && a.isHidden === b.isHidden && a.attributes === b.attributes;
2332
- }
2333
- //#endregion
2334
- //#region src/entities/area-views.ts
2335
- /**
2336
- * Area View Builder
2337
- *
2338
- * Constructs unified AreaView objects by combining registry data with computed
2339
- * entities and devices.
2340
- *
2341
- * Membership (which entities/devices belong to an area) is registry-driven and
2342
- * cheap; live entity *views* read entity state and are therefore exposed as a
2343
- * lazy `entities` getter. Callers that only need names, ids, or counts never
2344
- * touch entity state, so building the whole-area list does not recompute on
2345
- * every entity state tick.
2346
- *
2347
- * @packageDocumentation
2348
- */
2349
- /** The area an entity belongs to: its own `area_id` wins; otherwise it inherits
2350
- * the area of its device. Null when neither resolves. */
2351
- function entityAreaId(entry) {
2352
- if (entry.area_id) return entry.area_id;
2353
- if (entry.device_id) return state.devices[entry.device_id]?.area_id ?? null;
2354
- return null;
2355
- }
2356
- /** One pass over the device + entity registries → membership per area.
2357
- * O(devices + entities) for the whole home, vs the O(areas × (devices +
2358
- * entities)) of resolving each area independently. */
2359
- function computeAreaMembership() {
2360
- const byArea = /* @__PURE__ */ new Map();
2361
- const ensure = (areaId) => {
2362
- let m = byArea.get(areaId);
2363
- if (!m) {
2364
- m = {
2365
- devices: [],
2366
- entityIds: []
2367
- };
2368
- byArea.set(areaId, m);
2369
- }
2370
- return m;
2371
- };
2372
- for (const device of Object.values(state.devices)) if (device.area_id) ensure(device.area_id).devices.push(device);
2373
- for (const [entityId, entry] of Object.entries(state.entityRegistry)) {
2374
- const areaId = entityAreaId(entry);
2375
- if (areaId) ensure(areaId).entityIds.push(entityId);
2376
- }
2377
- return byArea;
2378
- }
2379
- /** Membership for a single area, without indexing every other area. */
2380
- function membershipFor(areaId) {
2381
- const devices = [];
2382
- for (const device of Object.values(state.devices)) if (device.area_id === areaId) devices.push(device);
2383
- const entityIds = [];
2384
- for (const [entityId, entry] of Object.entries(state.entityRegistry)) if (entityAreaId(entry) === areaId) entityIds.push(entityId);
2385
- return {
2386
- devices,
2387
- entityIds
2388
- };
2389
- }
2390
- /**
2391
- * Build a DeviceView from registry data
2392
- */
2393
- function buildDeviceView(device) {
2394
- return {
2395
- id: device.id,
2396
- name: device.name ?? "",
2397
- nameByUser: device.name_by_user ?? null,
2398
- manufacturer: device.manufacturer ?? null,
2399
- model: device.model ?? null,
2400
- swVersion: device.sw_version ?? null,
2401
- areaId: device.area_id ?? null,
2402
- configEntries: device.config_entries ?? [],
2403
- connections: device.connections ?? [],
2404
- identifiers: device.identifiers ?? [],
2405
- disabledBy: device.disabled_by ?? null
2406
- };
2407
- }
2408
- /** Assemble an AreaView from pre-resolved membership. `entities` is a lazy
2409
- * getter: materializing live EntityViews reads entity state, so deferring it
2410
- * keeps callers that only need names/ids/counts off the per-state-tick
2411
- * recompute path. The getter stays reactive — read inside a tracking scope it
2412
- * tracks those entities' state and updates like any other store read. */
2413
- function assembleAreaView(areaId, membership) {
2414
- const area = state.areas[areaId];
2415
- if (!area) throw new Error(`Area ${areaId} not found`);
2416
- const devices = membership.devices.map((device) => buildDeviceView(device));
2417
- const entityIds = membership.entityIds;
2418
- return {
2419
- id: areaId,
2420
- name: area.name,
2421
- normalizedName: area.normalized_name ?? area.name.toLowerCase(),
2422
- aliases: Array.isArray(area.aliases) ? area.aliases : [],
2423
- floorId: area.floor_id ?? null,
2424
- icon: area.icon ?? null,
2425
- picture: area.picture ?? null,
2426
- labels: Array.isArray(area.labels) ? area.labels : [],
2427
- temperatureEntityId: area.temperature_entity_id ?? null,
2428
- humidityEntityId: area.humidity_entity_id ?? null,
2429
- createdAt: area.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
2430
- modifiedAt: area.modified_at ?? (/* @__PURE__ */ new Date()).toISOString(),
2431
- devices,
2432
- entityIds,
2433
- deviceIds: devices.map((d) => d.id),
2434
- get entities() {
2435
- return entityIds.length > 0 ? getEntityViews(entityIds) : [];
2436
- }
2437
- };
2438
- }
2439
- /**
2440
- * Build an AreaView for a single area from registry data.
2441
- */
2442
- function buildAreaView(areaId) {
2443
- return assembleAreaView(areaId, membershipFor(areaId));
2444
- }
2445
- /**
2446
- * Get all area views. Membership is resolved in a single registry pass; entity
2447
- * views stay lazy per area (see `assembleAreaView`).
2448
- */
2449
- function getAreaViews() {
2450
- const membership = computeAreaMembership();
2451
- return Object.keys(state.areas).map((areaId) => assembleAreaView(areaId, membership.get(areaId) ?? {
2452
- devices: [],
2453
- entityIds: []
2454
- }));
2455
- }
2456
- /**
2457
- * Get area view
2458
- */
2459
- function getAreaView(areaId) {
2460
- try {
2461
- return buildAreaView(areaId);
2462
- } catch {
2463
- return;
2464
- }
2465
- }
2466
- //#endregion
2467
- //#region src/history/statistics.ts
2468
- const STATISTIC_TYPES = [
2469
- "mean",
2470
- "sum",
2471
- "min",
2472
- "max",
2473
- "state",
2474
- "change"
2475
- ];
2476
- /**
2477
- * HA returns start/end as ISO strings or ms numbers depending on version.
2478
- * Normalize both shapes to ms epoch numbers; unparseable values become NaN.
2479
- */
2480
- function normalizeStatisticTime(value) {
2481
- if (typeof value === "number") return value;
2482
- if (typeof value === "string") return new Date(value).getTime();
2483
- return NaN;
2484
- }
2485
- function normalizeNumber(value) {
2486
- return typeof value === "number" ? value : void 0;
2487
- }
2488
- function normalizeStatisticValue(raw) {
2489
- const value = {
2490
- start: normalizeStatisticTime(raw.start),
2491
- end: normalizeStatisticTime(raw.end)
2492
- };
2493
- const mean = normalizeNumber(raw.mean);
2494
- if (mean !== void 0) value.mean = mean;
2495
- const sum = normalizeNumber(raw.sum);
2496
- if (sum !== void 0) value.sum = sum;
2497
- const min = normalizeNumber(raw.min);
2498
- if (min !== void 0) value.min = min;
2499
- const max = normalizeNumber(raw.max);
2500
- if (max !== void 0) value.max = max;
2501
- const stateVal = normalizeNumber(raw.state);
2502
- if (stateVal !== void 0) value.state = stateVal;
2503
- const change = normalizeNumber(raw.change);
2504
- if (change !== void 0) value.change = change;
2505
- return value;
2506
- }
2507
- /**
2508
- * Fetch long-term statistics for one or more statistic ids during a period.
2509
- *
2510
- * Statistic ids with no data are returned as empty arrays so callers never
2511
- * hit `undefined`.
2512
- */
2513
- async function fetchStatisticsDuringPeriod(connection, statisticIds, options) {
2514
- const { startTime, endTime, period } = options;
2515
- if (isDemoMode()) {
2516
- const result = {};
2517
- const statPeriod = period === "hour" || period === "day" ? period : "day";
2518
- const endMs = (endTime ?? /* @__PURE__ */ new Date()).getTime();
2519
- for (const id of statisticIds) result[id] = isEnergyEntity(id) ? synthesizeEnergyStatistics(id, startTime.getTime(), endMs, statPeriod) : numericSensorStatistics(id, startTime.getTime(), endMs, statPeriod);
2520
- return result;
2521
- }
2522
- const params = {
2523
- type: "recorder/statistics_during_period",
2524
- start_time: startTime.toISOString(),
2525
- statistic_ids: statisticIds,
2526
- period,
2527
- types: STATISTIC_TYPES
2528
- };
2529
- if (endTime) params.end_time = endTime.toISOString();
2530
- const response = await connection.sendMessagePromise(params);
2531
- const result = {};
2532
- for (const id of statisticIds) result[id] = [];
2533
- if (response && typeof response === "object") for (const [id, buckets] of Object.entries(response)) result[id] = Array.isArray(buckets) ? buckets.map(normalizeStatisticValue) : [];
2534
- return result;
2535
- }
2536
- //#endregion
2537
- export { isDemoMode as A, extractDomain as B, setManagerConnection as C, fetchForecastData as D, fetchForecast as E, createDemoFixtures as F, setState as G, trackCalendarEvents as H, demoAssetUrl as I, state as K, demoEnergyPreferences as L, startDemoEnergyTicker as M, stopDemoEnergyTicker as N, fetchForecasts as O, unloadDemoData as P, isEnergyEntity as R, registerEntity as S, trackForecast as T, privilegedConn as U, forceResubscribeCalendars as V, setPrivilegedConn as W, toggle as _, getAreaView as a, updateEntity as b, entityViewEquals as c, getEntityViews as d, numericSensorHistory as f, sendCommand as g, callService as h, buildDeviceView as i, loadDemoData as j, applyDemoServiceCall as k, getAllEntityViews as l, batchServiceCalls as m, normalizeStatisticTime as n, getAreaViews as o, batchEntityUpdates as p, buildAreaView as r, buildEntityView as s, fetchStatisticsDuringPeriod as t, getEntityView as u, turnOff as v, setResubscribeHandler as w, forceResubscribe as x, turnOn as y, synthesizeEnergyHistory as z };