@glasshome/sync-layer 0.5.0 → 0.6.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.
@@ -0,0 +1,1974 @@
1
+ import { createStore, produce, reconcile } from "solid-js/store";
2
+
3
+ //#region src/core/store.ts
4
+ const initialState = {
5
+ connectionState: "disconnected",
6
+ connectionError: null,
7
+ hassUrl: null,
8
+ mediaProxyBase: null,
9
+ config: null,
10
+ entities: {},
11
+ entityRegistry: {},
12
+ devices: {},
13
+ areas: {},
14
+ floors: {},
15
+ labels: {},
16
+ statistics: {},
17
+ statisticsMetadata: {},
18
+ history: {},
19
+ forecasts: {},
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
+
28
+ //#endregion
29
+ //#region src/connection/subscription-manager.ts
30
+ 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.");
31
+ globalThis.__GH_SYNC_LAYER_SUB_MGR__ = true;
32
+ /** Ref counts — how many consumers need each entity */
33
+ const refCounts = /* @__PURE__ */ new Map();
34
+ /** Current HA subscription unsub function */
35
+ let currentEntityUnsub = null;
36
+ /** Snapshot of entity IDs in the current HA subscription */
37
+ let subscribedIds = /* @__PURE__ */ new Set();
38
+ /** Connection reference for resubscribing */
39
+ let conn = null;
40
+ /** Pending flush timer (microtask for register, timeout for unregister) */
41
+ let flushScheduled = false;
42
+ /** Delayed unregister timeout */
43
+ let unregisterTimeout = null;
44
+ /** Callback invoked on resubscribe — set by subscriptions.ts */
45
+ let onResubscribe = null;
46
+ /** Delay before unregistered entities are actually removed from subscription */
47
+ const UNREGISTER_DELAY_MS = 5e3;
48
+ /** Guard against concurrent flush() calls */
49
+ let flushInFlight = false;
50
+ /**
51
+ * Register an entity for live updates. Returns an unregister function.
52
+ * Call from useEntity/useEntities hooks via onCleanup.
53
+ */
54
+ function registerEntity(entityId) {
55
+ refCounts.set(entityId, (refCounts.get(entityId) ?? 0) + 1);
56
+ scheduleFlush();
57
+ return () => unregisterEntity(entityId);
58
+ }
59
+ /**
60
+ * Set the connection reference used for resubscribing.
61
+ */
62
+ function setManagerConnection(connection) {
63
+ conn = connection;
64
+ if (refCounts.size > 0) scheduleFlush();
65
+ }
66
+ /**
67
+ * Set the resubscribe callback. Called by subscriptions.ts to wire
68
+ * the manager into the actual WS subscription lifecycle.
69
+ */
70
+ function setResubscribeHandler(handler) {
71
+ onResubscribe = handler;
72
+ }
73
+ /**
74
+ * Force a resubscribe with the current active set.
75
+ * Used on reconnect.
76
+ */
77
+ async function forceResubscribe() {
78
+ await flush();
79
+ }
80
+ function unregisterEntity(entityId) {
81
+ const count = (refCounts.get(entityId) ?? 1) - 1;
82
+ if (count <= 0) refCounts.delete(entityId);
83
+ else refCounts.set(entityId, count);
84
+ scheduleDelayedFlush();
85
+ }
86
+ function scheduleFlush() {
87
+ if (flushScheduled) return;
88
+ flushScheduled = true;
89
+ queueMicrotask(() => {
90
+ flushScheduled = false;
91
+ flush();
92
+ });
93
+ }
94
+ function scheduleDelayedFlush() {
95
+ if (unregisterTimeout) return;
96
+ unregisterTimeout = setTimeout(() => {
97
+ unregisterTimeout = null;
98
+ flush();
99
+ }, UNREGISTER_DELAY_MS);
100
+ }
101
+ async function flush() {
102
+ if (!conn || !onResubscribe) return;
103
+ if (flushInFlight) return;
104
+ flushInFlight = true;
105
+ try {
106
+ const newIds = new Set(refCounts.keys());
107
+ if (setsEqual(newIds, subscribedIds)) return;
108
+ const oldUnsub = currentEntityUnsub;
109
+ const entityIds = [...newIds];
110
+ currentEntityUnsub = await onResubscribe(conn, entityIds);
111
+ subscribedIds = newIds;
112
+ if (oldUnsub) try {
113
+ await oldUnsub();
114
+ } catch {}
115
+ } finally {
116
+ flushInFlight = false;
117
+ }
118
+ }
119
+ function setsEqual(a, b) {
120
+ if (a.size !== b.size) return false;
121
+ for (const id of a) if (!b.has(id)) return false;
122
+ return true;
123
+ }
124
+
125
+ //#endregion
126
+ //#region src/core/types.ts
127
+ /**
128
+ * Extract domain from entity ID
129
+ */
130
+ function extractDomain(entityId) {
131
+ return entityId.split(".")[0] ?? "";
132
+ }
133
+
134
+ //#endregion
135
+ //#region src/demo/energy-sim.ts
136
+ const SOLAR_PEAK_W = 5200;
137
+ const SUNRISE_HOUR = 6.5;
138
+ const SUNSET_HOUR = 20.5;
139
+ const ALWAYS_ON_W = 285;
140
+ const FRIDGE_W = 95;
141
+ const FRIDGE_CYCLE_MIN = 45;
142
+ const FRIDGE_ON_MIN = 18;
143
+ const BATTERY_CAPACITY_WH = 1e4;
144
+ const BATTERY_MIN_SOC = 10;
145
+ const BATTERY_MAX_SOC = 100;
146
+ const BATTERY_POWER_CAP_W = 3e3;
147
+ const MIDNIGHT_SOC = 55;
148
+ const SOC_STEP_MIN = 5;
149
+ /** Integer hash -> uint32, used to seed mulberry32 deterministically. */
150
+ function hashInt(n) {
151
+ let h = n | 0;
152
+ h = Math.imul(h ^ h >>> 16, 73244475);
153
+ h = Math.imul(h ^ h >>> 16, 73244475);
154
+ h = (h ^ h >>> 16) >>> 0;
155
+ return h;
156
+ }
157
+ /** Deterministic [0,1) generator seeded by an integer. */
158
+ function mulberry32(seed) {
159
+ let a = seed >>> 0;
160
+ return () => {
161
+ a |= 0;
162
+ a = a + 1831565813 | 0;
163
+ let t = Math.imul(a ^ a >>> 15, 1 | a);
164
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
165
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
166
+ };
167
+ }
168
+ function localTime(timestampMs) {
169
+ const d = new Date(timestampMs);
170
+ const hours = d.getHours();
171
+ const minutes = d.getMinutes();
172
+ const seconds = d.getSeconds();
173
+ const hourFrac = hours + minutes / 60 + seconds / 3600;
174
+ const minuteOfDay = hours * 60 + minutes + seconds / 60;
175
+ const offsetMs = d.getTimezoneOffset() * 6e4;
176
+ const dayKey = Math.floor((timestampMs - offsetMs) / 864e5);
177
+ return {
178
+ hourFrac,
179
+ minuteOfDay,
180
+ dayOfWeek: d.getDay(),
181
+ dayKey
182
+ };
183
+ }
184
+ function localMidnightMs(timestampMs, lt) {
185
+ return timestampMs - lt.minuteOfDay * 6e4;
186
+ }
187
+ /** Smooth multiplicative cloud factor in [0.55, 1.0], seeded per day. */
188
+ function cloudFactor(lt) {
189
+ const rand = mulberry32(hashInt(lt.dayKey * 2654435761));
190
+ const phase1 = rand() * Math.PI * 2;
191
+ const phase2 = rand() * Math.PI * 2;
192
+ const phase3 = rand() * Math.PI * 2;
193
+ const m = lt.minuteOfDay;
194
+ const wave = .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);
195
+ const f = .85 + wave;
196
+ return Math.max(.55, Math.min(1, f));
197
+ }
198
+ function solarPower(lt) {
199
+ if (lt.hourFrac <= SUNRISE_HOUR || lt.hourFrac >= SUNSET_HOUR) return 0;
200
+ const frac = (lt.hourFrac - SUNRISE_HOUR) / (SUNSET_HOUR - SUNRISE_HOUR);
201
+ const shape = Math.sin(frac * Math.PI) ** 1.3;
202
+ return SOLAR_PEAK_W * shape * cloudFactor(lt);
203
+ }
204
+ /** Coarse solar elevation in degrees for sun.sun attributes. */
205
+ function sunElevation(lt) {
206
+ if (lt.hourFrac <= SUNRISE_HOUR || lt.hourFrac >= SUNSET_HOUR) return -12;
207
+ const frac = (lt.hourFrac - SUNRISE_HOUR) / (SUNSET_HOUR - SUNRISE_HOUR);
208
+ return 60 * Math.sin(frac * Math.PI);
209
+ }
210
+ function fridgePower(lt) {
211
+ const rand = mulberry32(hashInt(lt.dayKey * 40503 + 7));
212
+ const phase = rand() * FRIDGE_CYCLE_MIN;
213
+ const pos = (lt.minuteOfDay + phase) % FRIDGE_CYCLE_MIN;
214
+ return pos < FRIDGE_ON_MIN ? FRIDGE_W : 0;
215
+ }
216
+ /** A square wave: `power` while inside [start, start+durationMin). */
217
+ function windowPower(minuteOfDay, startMin, durationMin, power) {
218
+ return minuteOfDay >= startMin && minuteOfDay < startMin + durationMin ? power : 0;
219
+ }
220
+ function kettlePower(lt) {
221
+ return windowPower(lt.minuteOfDay, 430, 4, 2e3) + windowPower(lt.minuteOfDay, 1e3, 4, 2e3);
222
+ }
223
+ function ovenPower(lt) {
224
+ const start = 1125;
225
+ if (lt.minuteOfDay < start || lt.minuteOfDay >= start + 40) return 0;
226
+ const into = lt.minuteOfDay - start;
227
+ const cyclePos = into % 6.5;
228
+ return cyclePos < 4 ? 2200 : 0;
229
+ }
230
+ function dishwasherPower(lt) {
231
+ const start = 1270;
232
+ if (lt.minuteOfDay < start || lt.minuteOfDay >= start + 65) return 0;
233
+ const into = lt.minuteOfDay - start;
234
+ if (into < 12) return 1900;
235
+ if (into >= 57) return 1900;
236
+ return 120;
237
+ }
238
+ function washerPower(lt) {
239
+ if (![
240
+ 1,
241
+ 4,
242
+ 6
243
+ ].includes(lt.dayOfWeek)) return 0;
244
+ const start = 630;
245
+ if (lt.minuteOfDay < start || lt.minuteOfDay >= start + 50) return 0;
246
+ const into = lt.minuteOfDay - start;
247
+ return into < 14 ? 2100 : 250;
248
+ }
249
+ function evChargerPower(lt) {
250
+ if (![
251
+ 2,
252
+ 4,
253
+ 0
254
+ ].includes(lt.dayOfWeek)) return 0;
255
+ const start = 1100;
256
+ const stop = 1300;
257
+ if (lt.minuteOfDay < start || lt.minuteOfDay >= stop) return 0;
258
+ const into = lt.minuteOfDay - start;
259
+ const ramp = into < 2 ? into / 2 : 1;
260
+ return 7200 * ramp;
261
+ }
262
+ const HEAT_PUMP_PEAK_W = 3200;
263
+ /**
264
+ * A smooth heat-pump load: a slow morning/evening envelope carrying a
265
+ * few-minute shimmer. Its peaks push the home deficit past the battery's power
266
+ * cap, so grid import (and the running cost) visibly rise and fall on live
267
+ * ticks instead of sitting at zero. Gated out of the deep-night window so the
268
+ * quiet 02:00-03:00 baseline is unchanged.
269
+ */
270
+ function heatPumpPower(lt) {
271
+ const h = lt.hourFrac;
272
+ let envelope = 0;
273
+ if (h >= 6 && h <= 9) envelope = Math.sin((h - 6) / 3 * Math.PI);
274
+ else if (h >= 16 && h <= 23) envelope = Math.sin((h - 16) / 7 * Math.PI);
275
+ else return 0;
276
+ const shimmer = .7 + .3 * Math.sin(lt.minuteOfDay * Math.PI * 2);
277
+ return HEAT_PUMP_PEAK_W * envelope * shimmer;
278
+ }
279
+ /** Smooth occupancy envelope: extra load mornings and evenings. */
280
+ function occupancyEnvelope(lt) {
281
+ const h = lt.hourFrac;
282
+ let e = 0;
283
+ if (h >= 7 && h <= 9) e += 80 + 270 * Math.sin((h - 7) / 2 * Math.PI);
284
+ if (h >= 17.5 && h <= 23) e += 80 + 270 * Math.sin((h - 17.5) / 5.5 * Math.PI);
285
+ return e;
286
+ }
287
+ /** Low-amplitude smooth noise multiplier, ±4%, seeded per day. */
288
+ function homeNoise(lt) {
289
+ const rand = mulberry32(hashInt(lt.dayKey * 22699 + 13));
290
+ const phase = rand() * Math.PI * 2;
291
+ return 1 + .04 * Math.sin(lt.minuteOfDay / 23 * Math.PI * 2 + phase);
292
+ }
293
+ const socCache = /* @__PURE__ */ new Map();
294
+ /** Net surplus (solar - home) at a given local-time sample, in watts. */
295
+ function netSurplusAt(timestampMs) {
296
+ const lt = localTime(timestampMs);
297
+ const solar = solarPower(lt);
298
+ const home = homePower(lt);
299
+ return solar - home;
300
+ }
301
+ /**
302
+ * Battery SOC (%) at every {@link SOC_STEP_MIN}-minute step from local
303
+ * midnight. Returns step `i` = SOC after integrating `i` steps. Index 0 is
304
+ * the midnight SOC. Memoized per local day (pure computation).
305
+ */
306
+ function socPrefix(dayKey, midnightMs) {
307
+ const cached = socCache.get(dayKey);
308
+ if (cached) return cached;
309
+ const steps = Math.ceil(24 * 60 / SOC_STEP_MIN);
310
+ const arr = new Float64Array(steps + 1);
311
+ arr[0] = MIDNIGHT_SOC;
312
+ const stepMs = SOC_STEP_MIN * 6e4;
313
+ const stepHours = SOC_STEP_MIN / 60;
314
+ for (let i = 0; i < steps; i++) {
315
+ const soc = arr[i] ?? MIDNIGHT_SOC;
316
+ const sampleMs = midnightMs + i * stepMs;
317
+ const surplus = netSurplusAt(sampleMs);
318
+ let chargeW = 0;
319
+ let dischargeW = 0;
320
+ if (surplus > 0) {
321
+ const headroomWh = (BATTERY_MAX_SOC - soc) / 100 * BATTERY_CAPACITY_WH;
322
+ const headroomW = headroomWh / stepHours;
323
+ chargeW = Math.min(surplus, BATTERY_POWER_CAP_W, Math.max(0, headroomW));
324
+ } else if (surplus < 0) {
325
+ const availWh = (soc - BATTERY_MIN_SOC) / 100 * BATTERY_CAPACITY_WH;
326
+ const availW = availWh / stepHours;
327
+ dischargeW = Math.min(-surplus, BATTERY_POWER_CAP_W, Math.max(0, availW));
328
+ }
329
+ const deltaWh = (chargeW - dischargeW) * stepHours;
330
+ const nextSoc = soc + deltaWh / BATTERY_CAPACITY_WH * 100;
331
+ arr[i + 1] = Math.max(BATTERY_MIN_SOC, Math.min(BATTERY_MAX_SOC, nextSoc));
332
+ }
333
+ socCache.set(dayKey, arr);
334
+ return arr;
335
+ }
336
+ /** Battery SOC (%) at an exact timestamp, linearly interpolated between steps. */
337
+ function batterySoc(lt, midnightMs) {
338
+ const prefix = socPrefix(lt.dayKey, midnightMs);
339
+ const stepFloat = lt.minuteOfDay / SOC_STEP_MIN;
340
+ const i = Math.floor(stepFloat);
341
+ const frac = stepFloat - i;
342
+ const a = prefix[i] ?? MIDNIGHT_SOC;
343
+ const b = prefix[i + 1] ?? a;
344
+ return a + (b - a) * frac;
345
+ }
346
+ function homePower(lt) {
347
+ const base = ALWAYS_ON_W + fridgePower(lt) + kettlePower(lt) + ovenPower(lt) + dishwasherPower(lt) + washerPower(lt) + evChargerPower(lt) + heatPumpPower(lt) + occupancyEnvelope(lt);
348
+ return base * homeNoise(lt);
349
+ }
350
+ /**
351
+ * Compute every instantaneous energy value at a timestamp.
352
+ *
353
+ * Deterministic: equal timestamps always yield deep-equal samples. Obeys the
354
+ * conservation invariant
355
+ * `solar + gridImport + batteryDischarge === home + gridExport + batteryCharge`
356
+ * to within rounding.
357
+ */
358
+ function simulateEnergy(timestampMs) {
359
+ const lt = localTime(timestampMs);
360
+ const midnightMs = localMidnightMs(timestampMs, lt);
361
+ const solarW = solarPower(lt);
362
+ const fridgeW = fridgePower(lt);
363
+ const ovenW = ovenPower(lt);
364
+ const dishwasherW = dishwasherPower(lt);
365
+ const washerW = washerPower(lt);
366
+ const evChargerW = evChargerPower(lt);
367
+ const alwaysOnW = ALWAYS_ON_W;
368
+ const homeW = homePower(lt);
369
+ const soc = batterySoc(lt, midnightMs);
370
+ const surplus = solarW - homeW;
371
+ let batteryChargeW = 0;
372
+ let batteryDischargeW = 0;
373
+ if (surplus > 0) {
374
+ const headroom = soc < BATTERY_MAX_SOC ? BATTERY_POWER_CAP_W : 0;
375
+ batteryChargeW = Math.min(surplus, headroom);
376
+ } else if (surplus < 0) {
377
+ const avail = soc > BATTERY_MIN_SOC ? BATTERY_POWER_CAP_W : 0;
378
+ batteryDischargeW = Math.min(-surplus, avail);
379
+ }
380
+ const remainingDeficit = homeW - solarW - batteryDischargeW + batteryChargeW;
381
+ const gridImportW = Math.max(0, remainingDeficit);
382
+ const gridExportW = Math.max(0, -remainingDeficit);
383
+ return {
384
+ solarW,
385
+ homeW,
386
+ batteryChargeW,
387
+ batteryDischargeW,
388
+ batterySocPct: soc,
389
+ gridImportW,
390
+ gridExportW,
391
+ fridgeW,
392
+ dishwasherW,
393
+ washerW,
394
+ ovenW,
395
+ evChargerW,
396
+ alwaysOnW
397
+ };
398
+ }
399
+ /** Whether the sun is above the horizon at a timestamp. */
400
+ function isSunUp(timestampMs) {
401
+ const lt = localTime(timestampMs);
402
+ return lt.hourFrac > SUNRISE_HOUR && lt.hourFrac < SUNSET_HOUR;
403
+ }
404
+ /** Next sunrise/sunset ISO strings relative to a timestamp. */
405
+ function sunEvents(timestampMs) {
406
+ const lt = localTime(timestampMs);
407
+ const midnightMs = localMidnightMs(timestampMs, lt);
408
+ const sunriseMs = midnightMs + SUNRISE_HOUR * 36e5;
409
+ const sunsetMs = midnightMs + SUNSET_HOUR * 36e5;
410
+ const nextRising = timestampMs < sunriseMs ? sunriseMs : sunriseMs + 864e5;
411
+ const nextSetting = timestampMs < sunsetMs ? sunsetMs : sunsetMs + 864e5;
412
+ return {
413
+ nextRising: new Date(nextRising).toISOString(),
414
+ nextSetting: new Date(nextSetting).toISOString(),
415
+ elevation: Math.round(sunElevation(lt) * 100) / 100
416
+ };
417
+ }
418
+ /** The energy sensor entity ids the simulation drives. */
419
+ const ENERGY_ENTITY_IDS = [
420
+ "sensor.solar_power",
421
+ "sensor.grid_import_power",
422
+ "sensor.grid_export_power",
423
+ "sensor.battery_charge_power",
424
+ "sensor.battery_discharge_power",
425
+ "sensor.battery_soc",
426
+ "sensor.home_power",
427
+ "sensor.fridge_power",
428
+ "sensor.dishwasher_power",
429
+ "sensor.washing_machine_power",
430
+ "sensor.oven_power",
431
+ "sensor.ev_charger_power",
432
+ "sensor.always_on_power"
433
+ ];
434
+ /** Map an energy entity id to its numeric value from a sample (W, or % for SOC). */
435
+ function energyEntityValue(entityId, sample) {
436
+ switch (entityId) {
437
+ case "sensor.solar_power": return sample.solarW;
438
+ case "sensor.grid_import_power": return sample.gridImportW;
439
+ case "sensor.grid_export_power": return sample.gridExportW;
440
+ case "sensor.battery_charge_power": return sample.batteryChargeW;
441
+ case "sensor.battery_discharge_power": return sample.batteryDischargeW;
442
+ case "sensor.battery_soc": return sample.batterySocPct;
443
+ case "sensor.home_power": return sample.homeW;
444
+ case "sensor.fridge_power": return sample.fridgeW;
445
+ case "sensor.dishwasher_power": return sample.dishwasherW;
446
+ case "sensor.washing_machine_power": return sample.washerW;
447
+ case "sensor.oven_power": return sample.ovenW;
448
+ case "sensor.ev_charger_power": return sample.evChargerW;
449
+ case "sensor.always_on_power": return sample.alwaysOnW;
450
+ default: return void 0;
451
+ }
452
+ }
453
+ /** Whether an entity id is one of the simulated energy sensors. */
454
+ function isEnergyEntity(entityId) {
455
+ return energyEntityValue(entityId, ZERO_SAMPLE) !== void 0;
456
+ }
457
+ const ZERO_SAMPLE = {
458
+ solarW: 0,
459
+ homeW: 0,
460
+ batteryChargeW: 0,
461
+ batteryDischargeW: 0,
462
+ batterySocPct: 0,
463
+ gridImportW: 0,
464
+ gridExportW: 0,
465
+ fridgeW: 0,
466
+ dishwasherW: 0,
467
+ washerW: 0,
468
+ ovenW: 0,
469
+ evChargerW: 0,
470
+ alwaysOnW: 0
471
+ };
472
+ /** Round to 1 decimal for display-friendly state strings (whole % for SOC). */
473
+ function formatEnergyState(entityId, value) {
474
+ if (entityId === "sensor.battery_soc") return String(Math.round(value));
475
+ return String(Math.round(value));
476
+ }
477
+ /**
478
+ * Synthesize history points for one energy entity by sampling the model across
479
+ * the window at a fixed cadence (default 1-minute). Returns HA-compressed
480
+ * `{ lu, s }` points with `lu` in Unix seconds.
481
+ */
482
+ function synthesizeEnergyHistory(entityId, startMs, endMs, stepMs = 6e4) {
483
+ const points = [];
484
+ for (let t = startMs; t <= endMs; t += stepMs) {
485
+ const value = energyEntityValue(entityId, simulateEnergy(t));
486
+ if (value === void 0) continue;
487
+ points.push({
488
+ lu: Math.round(t / 1e3),
489
+ s: formatEnergyState(entityId, value)
490
+ });
491
+ }
492
+ return points;
493
+ }
494
+ /** Bucket length in ms for a statistics period. */
495
+ function bucketMs(period) {
496
+ return period === "hour" ? 36e5 : 864e5;
497
+ }
498
+ /**
499
+ * Synthesize statistics buckets for one energy entity across a window.
500
+ *
501
+ * `mean`/`min`/`max` come from 5-minute power samples in the bucket; `sum` is
502
+ * the energy in Wh (mean W times bucket hours). `sum` is cumulative across the
503
+ * window, matching HA's monotonically increasing meter semantics.
504
+ */
505
+ function synthesizeEnergyStatistics(entityId, startMs, endMs, period) {
506
+ const span = bucketMs(period);
507
+ const sampleMs = 5 * 6e4;
508
+ const buckets = [];
509
+ let cumulativeWh = 0;
510
+ for (let bStart = startMs; bStart < endMs; bStart += span) {
511
+ const bEnd = bStart + span;
512
+ let sum = 0;
513
+ let count = 0;
514
+ let min = Number.POSITIVE_INFINITY;
515
+ let max = Number.NEGATIVE_INFINITY;
516
+ for (let t = bStart; t < bEnd; t += sampleMs) {
517
+ const value = energyEntityValue(entityId, simulateEnergy(t));
518
+ if (value === void 0) continue;
519
+ sum += value;
520
+ count++;
521
+ if (value < min) min = value;
522
+ if (value > max) max = value;
523
+ }
524
+ if (count === 0) continue;
525
+ const mean = sum / count;
526
+ const bucketHours = span / 36e5;
527
+ const energyWh = entityId === "sensor.battery_soc" ? 0 : mean * bucketHours;
528
+ cumulativeWh += energyWh;
529
+ buckets.push({
530
+ start: bStart,
531
+ end: bEnd,
532
+ mean,
533
+ min: min === Number.POSITIVE_INFINITY ? mean : min,
534
+ max: max === Number.NEGATIVE_INFINITY ? mean : max,
535
+ sum: cumulativeWh,
536
+ change: energyWh / 1e3
537
+ });
538
+ }
539
+ return buckets;
540
+ }
541
+ /** The demo energy dashboard preferences wiring the simulated sensors. */
542
+ function demoEnergyPreferences() {
543
+ return {
544
+ energy_sources: [
545
+ {
546
+ type: "solar",
547
+ stat_energy_from: "sensor.solar_power"
548
+ },
549
+ {
550
+ type: "grid",
551
+ flow_from: [{ stat_energy_from: "sensor.grid_import_power" }],
552
+ flow_to: [{ stat_energy_to: "sensor.grid_export_power" }]
553
+ },
554
+ {
555
+ type: "battery",
556
+ stat_energy_from: "sensor.battery_discharge_power",
557
+ stat_energy_to: "sensor.battery_charge_power"
558
+ }
559
+ ],
560
+ device_consumption: [
561
+ {
562
+ stat_consumption: "sensor.fridge_power",
563
+ name: "Fridge"
564
+ },
565
+ {
566
+ stat_consumption: "sensor.dishwasher_power",
567
+ name: "Dishwasher"
568
+ },
569
+ {
570
+ stat_consumption: "sensor.washing_machine_power",
571
+ name: "Washing Machine"
572
+ },
573
+ {
574
+ stat_consumption: "sensor.oven_power",
575
+ name: "Oven"
576
+ },
577
+ {
578
+ stat_consumption: "sensor.ev_charger_power",
579
+ name: "EV Charger"
580
+ },
581
+ {
582
+ stat_consumption: "sensor.always_on_power",
583
+ name: "Always On"
584
+ }
585
+ ]
586
+ };
587
+ }
588
+
589
+ //#endregion
590
+ //#region src/demo/demo-data.ts
591
+ const now = (/* @__PURE__ */ new Date()).toISOString();
592
+ let contextCounter = 0;
593
+ function ctx() {
594
+ return {
595
+ id: `demo-${++contextCounter}`,
596
+ parent_id: null,
597
+ user_id: null
598
+ };
599
+ }
600
+ function makeEntity(entity_id, state$1, attributes = {}) {
601
+ return {
602
+ entity_id,
603
+ state: state$1,
604
+ attributes: {
605
+ friendly_name: friendlyName(entity_id),
606
+ ...attributes
607
+ },
608
+ last_changed: now,
609
+ last_updated: now,
610
+ context: ctx()
611
+ };
612
+ }
613
+ /**
614
+ * One entity per weather scene the widget can render. Entity IDs use the
615
+ * `weather.demo_<slug>` form so a demo dashboard can reference them directly.
616
+ */
617
+ const WEATHER_FIXTURES = [
618
+ {
619
+ slug: "sunny",
620
+ state: "sunny",
621
+ temp: 28,
622
+ apparent: 31,
623
+ humidity: 35,
624
+ pressure: 1018,
625
+ wind: 8,
626
+ low: 18
627
+ },
628
+ {
629
+ slug: "clear_night",
630
+ state: "clear-night",
631
+ temp: 14,
632
+ apparent: 12,
633
+ humidity: 55,
634
+ pressure: 1016,
635
+ wind: 5,
636
+ low: 9
637
+ },
638
+ {
639
+ slug: "cloudy",
640
+ state: "cloudy",
641
+ temp: 17,
642
+ apparent: 16,
643
+ humidity: 72,
644
+ pressure: 1010,
645
+ wind: 14,
646
+ low: 11
647
+ },
648
+ {
649
+ slug: "partly_cloudy",
650
+ state: "partlycloudy",
651
+ temp: 23,
652
+ apparent: 24,
653
+ humidity: 50,
654
+ pressure: 1014,
655
+ wind: 12,
656
+ low: 15
657
+ },
658
+ {
659
+ slug: "rainy",
660
+ state: "rainy",
661
+ temp: 12,
662
+ apparent: 10,
663
+ humidity: 88,
664
+ pressure: 1004,
665
+ wind: 18,
666
+ low: 8
667
+ },
668
+ {
669
+ slug: "pouring",
670
+ state: "pouring",
671
+ temp: 11,
672
+ apparent: 8,
673
+ humidity: 95,
674
+ pressure: 998,
675
+ wind: 26,
676
+ low: 7
677
+ },
678
+ {
679
+ slug: "snowy",
680
+ state: "snowy",
681
+ temp: -2,
682
+ apparent: -6,
683
+ humidity: 80,
684
+ pressure: 1020,
685
+ wind: 10,
686
+ low: -7
687
+ },
688
+ {
689
+ slug: "snowy_rainy",
690
+ state: "snowy-rainy",
691
+ temp: 1,
692
+ apparent: -2,
693
+ humidity: 92,
694
+ pressure: 1006,
695
+ wind: 16,
696
+ low: -2
697
+ },
698
+ {
699
+ slug: "lightning",
700
+ state: "lightning",
701
+ temp: 22,
702
+ apparent: 24,
703
+ humidity: 78,
704
+ pressure: 1001,
705
+ wind: 22,
706
+ low: 17
707
+ },
708
+ {
709
+ slug: "lightning_rainy",
710
+ state: "lightning-rainy",
711
+ temp: 19,
712
+ apparent: 18,
713
+ humidity: 90,
714
+ pressure: 996,
715
+ wind: 28,
716
+ low: 14
717
+ },
718
+ {
719
+ slug: "fog",
720
+ state: "fog",
721
+ temp: 8,
722
+ apparent: 6,
723
+ humidity: 98,
724
+ pressure: 1015,
725
+ wind: 4,
726
+ low: 6
727
+ },
728
+ {
729
+ slug: "hail",
730
+ state: "hail",
731
+ temp: 6,
732
+ apparent: 3,
733
+ humidity: 84,
734
+ pressure: 1002,
735
+ wind: 20,
736
+ low: 1
737
+ },
738
+ {
739
+ slug: "windy",
740
+ state: "windy",
741
+ temp: 18,
742
+ apparent: 15,
743
+ humidity: 60,
744
+ pressure: 1009,
745
+ wind: 42,
746
+ low: 12
747
+ },
748
+ {
749
+ slug: "exceptional",
750
+ state: "exceptional",
751
+ temp: 38,
752
+ apparent: 44,
753
+ humidity: 22,
754
+ pressure: 1005,
755
+ wind: 30,
756
+ low: 28
757
+ }
758
+ ];
759
+ function makeWeatherEntity(w) {
760
+ const today = /* @__PURE__ */ new Date();
761
+ const day = (n) => new Date(today.getTime() + n * 864e5).toISOString();
762
+ return makeEntity(`weather.demo_${w.slug}`, w.state, {
763
+ temperature: w.temp,
764
+ temperature_unit: "°C",
765
+ apparent_temperature: w.apparent ?? w.temp,
766
+ humidity: w.humidity,
767
+ pressure: w.pressure,
768
+ pressure_unit: "hPa",
769
+ wind_speed: w.wind,
770
+ wind_speed_unit: "km/h",
771
+ wind_bearing: w.bearing ?? 220,
772
+ visibility: 10,
773
+ visibility_unit: "km",
774
+ uv_index: w.state === "sunny" ? 8 : 2,
775
+ forecast: [
776
+ {
777
+ datetime: day(0),
778
+ condition: w.state,
779
+ temperature: w.temp,
780
+ templow: w.low
781
+ },
782
+ {
783
+ datetime: day(1),
784
+ condition: "partlycloudy",
785
+ temperature: w.temp + 2,
786
+ templow: w.low
787
+ },
788
+ {
789
+ datetime: day(2),
790
+ condition: "cloudy",
791
+ temperature: w.temp + 1,
792
+ templow: w.low - 1
793
+ },
794
+ {
795
+ datetime: day(3),
796
+ condition: "sunny",
797
+ temperature: w.temp + 4,
798
+ templow: w.low + 1
799
+ },
800
+ {
801
+ datetime: day(4),
802
+ condition: "rainy",
803
+ temperature: w.temp - 2,
804
+ templow: w.low - 2
805
+ }
806
+ ]
807
+ });
808
+ }
809
+ function friendlyName(entityId) {
810
+ const objectId = entityId.split(".")[1] ?? entityId;
811
+ return objectId.split("_").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
812
+ }
813
+ function makeRegistryEntry(entity_id, overrides = {}) {
814
+ const domain = entity_id.split(".")[0] ?? "";
815
+ return {
816
+ aliases: [],
817
+ area_id: null,
818
+ capabilities: null,
819
+ categories: {},
820
+ config_entry_id: "demo_config",
821
+ config_subentry_id: null,
822
+ created_at: now,
823
+ device_class: null,
824
+ device_id: null,
825
+ disabled_by: null,
826
+ entity_category: null,
827
+ entity_id,
828
+ has_entity_name: false,
829
+ hidden_by: null,
830
+ icon: null,
831
+ id: `reg-${entity_id.replace(".", "-")}`,
832
+ labels: [],
833
+ modified_at: now,
834
+ name: null,
835
+ options: {},
836
+ original_device_class: null,
837
+ original_icon: null,
838
+ original_name: null,
839
+ platform: domain === "weather" ? "met" : "demo",
840
+ previous_unique_id: null,
841
+ suggested_object_id: null,
842
+ supported_features: 0,
843
+ translation_key: null,
844
+ unique_id: `demo_${entity_id.replace(".", "_")}`,
845
+ unit_of_measurement: null,
846
+ ...overrides
847
+ };
848
+ }
849
+ function makeDevice(id, name, areaId, manufacturer = "Demo", model = "Virtual") {
850
+ return {
851
+ id,
852
+ name,
853
+ name_by_user: null,
854
+ manufacturer,
855
+ model,
856
+ model_id: null,
857
+ sw_version: "1.0.0",
858
+ hw_version: null,
859
+ area_id: areaId,
860
+ config_entries: ["demo_config"],
861
+ config_entries_subentries: {},
862
+ configuration_url: null,
863
+ connections: [],
864
+ created_at: now,
865
+ disabled_by: null,
866
+ entry_type: null,
867
+ identifiers: [["demo", id]],
868
+ labels: [],
869
+ modified_at: now,
870
+ primary_config_entry: "demo_config",
871
+ serial_number: null,
872
+ via_device_id: null
873
+ };
874
+ }
875
+ function makeArea(id, name, floorId = "ground_floor") {
876
+ return {
877
+ id,
878
+ name,
879
+ normalized_name: name.toLowerCase().replace(/\s+/g, "_"),
880
+ created_at: now,
881
+ modified_at: now,
882
+ aliases: [],
883
+ floor_id: floorId,
884
+ humidity_entity_id: null,
885
+ icon: null,
886
+ labels: [],
887
+ picture: null,
888
+ temperature_entity_id: null
889
+ };
890
+ }
891
+ /**
892
+ * Create ~30 curated apartment entity fixtures.
893
+ *
894
+ * Entities span lights, sensors, binary sensors, climate, covers,
895
+ * locks, switches, media player, weather, camera, scenes, and buttons
896
+ * across 6 areas: living_room, bedroom, kitchen, entry, utility, garage.
897
+ */
898
+ function createDemoFixtures() {
899
+ contextCounter = 0;
900
+ const areas = {
901
+ living_room: makeArea("living_room", "Living Room"),
902
+ bedroom: makeArea("bedroom", "Bedroom"),
903
+ kitchen: makeArea("kitchen", "Kitchen"),
904
+ entry: makeArea("entry", "Entry"),
905
+ utility: makeArea("utility", "Utility"),
906
+ garage: makeArea("garage", "Garage")
907
+ };
908
+ areas.living_room.temperature_entity_id = "sensor.temperature_living";
909
+ areas.living_room.humidity_entity_id = "sensor.humidity_living";
910
+ const devices = {
911
+ living_room_lights: makeDevice("living_room_lights", "Living Room Lights", "living_room", "Philips", "Hue"),
912
+ kitchen_lights: makeDevice("kitchen_lights", "Kitchen Lights", "kitchen", "IKEA", "Tradfri"),
913
+ bedroom_lights: makeDevice("bedroom_lights", "Bedroom Lights", "bedroom", "Philips", "Hue"),
914
+ hallway_lights: makeDevice("hallway_lights", "Hallway Lights", "entry", "IKEA", "Tradfri"),
915
+ bathroom_lights: makeDevice("bathroom_lights", "Bathroom Lights", null),
916
+ thermostat_lr: makeDevice("thermostat_lr", "Living Room Thermostat", "living_room", "Nest", "Learning Thermostat"),
917
+ thermostat_br: makeDevice("thermostat_br", "Bedroom AC", "bedroom", "Daikin", "Split AC"),
918
+ blinds_lr: makeDevice("blinds_lr", "Living Room Blinds", "living_room", "Somfy", "Roller Shade"),
919
+ curtains_br: makeDevice("curtains_br", "Bedroom Curtains", "bedroom", "IKEA", "Fyrtur"),
920
+ garage_door_opener: makeDevice("garage_door_opener", "Garage Door Opener", "garage", "Chamberlain", "MyQ"),
921
+ shutters_lr: makeDevice("shutters_lr", "Living Room Shutters", "living_room", "Somfy", "Venetian Shutter"),
922
+ blinds_kitchen: makeDevice("blinds_kitchen", "Kitchen Blinds", "kitchen", "IKEA", "Praktlysing"),
923
+ lock_front: makeDevice("lock_front", "Front Door Lock", "entry", "Yale", "Assure Lock 2"),
924
+ lock_back: makeDevice("lock_back", "Back Door Lock", "entry", "August", "Smart Lock Pro"),
925
+ speaker_lr: makeDevice("speaker_lr", "Living Room Speaker", "living_room", "Sonos", "One"),
926
+ camera_front: makeDevice("camera_front", "Front Door Camera", "entry", "Ring", "Video Doorbell"),
927
+ door_sensor: makeDevice("door_sensor", "Front Door Sensor", "entry", "Aqara", "Door Sensor"),
928
+ motion_sensor: makeDevice("motion_sensor", "Hallway Motion Sensor", "entry", "Aqara", "Motion Sensor")
929
+ };
930
+ const entities = {};
931
+ const entityRegistry = {};
932
+ function add(e, regOverrides = {}) {
933
+ entities[e.entity_id] = e;
934
+ entityRegistry[e.entity_id] = makeRegistryEntry(e.entity_id, regOverrides);
935
+ }
936
+ add(makeEntity("light.living_room_main", "on", {
937
+ brightness: 179,
938
+ color_temp_kelvin: 3e3,
939
+ color_mode: "color_temp",
940
+ supported_color_modes: ["color_temp", "xy"]
941
+ }), {
942
+ device_id: "living_room_lights",
943
+ area_id: "living_room",
944
+ supported_features: 44
945
+ });
946
+ add(makeEntity("light.kitchen_counter", "off", { supported_color_modes: ["brightness"] }), {
947
+ device_id: "kitchen_lights",
948
+ area_id: "kitchen",
949
+ supported_features: 1
950
+ });
951
+ add(makeEntity("light.bedroom_ceiling", "on", {
952
+ brightness: 77,
953
+ color_temp_kelvin: 2700,
954
+ color_mode: "color_temp",
955
+ supported_color_modes: ["color_temp"]
956
+ }), {
957
+ device_id: "bedroom_lights",
958
+ area_id: "bedroom",
959
+ supported_features: 44
960
+ });
961
+ add(makeEntity("light.bathroom", "off", { supported_color_modes: ["brightness"] }), { device_id: "bathroom_lights" });
962
+ add(makeEntity("light.hallway", "on", {
963
+ brightness: 128,
964
+ color_mode: "brightness",
965
+ supported_color_modes: ["brightness"]
966
+ }), {
967
+ device_id: "hallway_lights",
968
+ area_id: "entry",
969
+ supported_features: 1
970
+ });
971
+ add(makeEntity("light.studio_rgb", "on", {
972
+ brightness: 205,
973
+ hs_color: [265, 66],
974
+ color_mode: "hs",
975
+ supported_color_modes: ["hs", "color_temp"]
976
+ }), {
977
+ device_id: "studio_lights",
978
+ area_id: "living_room",
979
+ supported_features: 44
980
+ });
981
+ add(makeEntity("light.desk_rgb", "on", {
982
+ brightness: 200,
983
+ hs_color: [172, 79],
984
+ color_mode: "hs",
985
+ supported_color_modes: ["hs", "color_temp"]
986
+ }), {
987
+ device_id: "desk_lights",
988
+ area_id: "bedroom",
989
+ supported_features: 44
990
+ });
991
+ add(makeEntity("sensor.temperature_living", "22.5", {
992
+ unit_of_measurement: "°C",
993
+ device_class: "temperature",
994
+ state_class: "measurement"
995
+ }), {
996
+ area_id: "living_room",
997
+ device_class: "temperature",
998
+ unit_of_measurement: "°C"
999
+ });
1000
+ add(makeEntity("sensor.humidity_living", "45", {
1001
+ unit_of_measurement: "%",
1002
+ device_class: "humidity",
1003
+ state_class: "measurement"
1004
+ }), {
1005
+ area_id: "living_room",
1006
+ device_class: "humidity",
1007
+ unit_of_measurement: "%"
1008
+ });
1009
+ add(makeEntity("sensor.temperature_outdoor", "-2", {
1010
+ unit_of_measurement: "°C",
1011
+ device_class: "temperature",
1012
+ state_class: "measurement"
1013
+ }), {
1014
+ device_class: "temperature",
1015
+ unit_of_measurement: "°C"
1016
+ });
1017
+ add(makeEntity("sensor.power_consumption", "1.2", {
1018
+ unit_of_measurement: "kW",
1019
+ device_class: "power",
1020
+ state_class: "measurement"
1021
+ }), {
1022
+ device_class: "power",
1023
+ unit_of_measurement: "kW"
1024
+ });
1025
+ add(makeEntity("sensor.battery_door_sensor", "87", {
1026
+ unit_of_measurement: "%",
1027
+ device_class: "battery",
1028
+ state_class: "measurement"
1029
+ }), {
1030
+ device_id: "door_sensor",
1031
+ area_id: "entry",
1032
+ device_class: "battery",
1033
+ unit_of_measurement: "%"
1034
+ });
1035
+ add(makeEntity("binary_sensor.front_door", "off", { device_class: "door" }), {
1036
+ device_id: "door_sensor",
1037
+ area_id: "entry",
1038
+ device_class: "door"
1039
+ });
1040
+ add(makeEntity("binary_sensor.motion_hallway", "off", { device_class: "motion" }), {
1041
+ device_id: "motion_sensor",
1042
+ area_id: "entry",
1043
+ device_class: "motion"
1044
+ });
1045
+ add(makeEntity("binary_sensor.window_bedroom", "off", { device_class: "window" }), {
1046
+ area_id: "bedroom",
1047
+ device_class: "window"
1048
+ });
1049
+ add(makeEntity("climate.living_room_thermostat", "heat", {
1050
+ temperature: 22,
1051
+ current_temperature: 21.8,
1052
+ hvac_modes: [
1053
+ "off",
1054
+ "heat",
1055
+ "cool",
1056
+ "auto"
1057
+ ],
1058
+ hvac_action: "heating",
1059
+ min_temp: 7,
1060
+ max_temp: 35
1061
+ }), {
1062
+ device_id: "thermostat_lr",
1063
+ area_id: "living_room",
1064
+ supported_features: 385
1065
+ });
1066
+ add(makeEntity("climate.bedroom_ac", "off", {
1067
+ temperature: 20,
1068
+ current_temperature: 22.1,
1069
+ hvac_modes: [
1070
+ "off",
1071
+ "cool",
1072
+ "heat",
1073
+ "dry",
1074
+ "fan_only"
1075
+ ],
1076
+ hvac_action: "idle",
1077
+ min_temp: 16,
1078
+ max_temp: 30
1079
+ }), {
1080
+ device_id: "thermostat_br",
1081
+ area_id: "bedroom",
1082
+ supported_features: 385
1083
+ });
1084
+ add(makeEntity("water_heater.boiler", "eco", {
1085
+ temperature: 50,
1086
+ current_temperature: 47.5,
1087
+ operation_list: [
1088
+ "off",
1089
+ "eco",
1090
+ "performance"
1091
+ ],
1092
+ min_temp: 43,
1093
+ max_temp: 60,
1094
+ away_mode: "off"
1095
+ }), {
1096
+ device_id: "boiler",
1097
+ area_id: "utility",
1098
+ supported_features: 7
1099
+ });
1100
+ add(makeEntity("water_heater.heat_pump_tank", "heat_pump", {
1101
+ temperature: 55,
1102
+ current_temperature: 52.3,
1103
+ operation_list: [
1104
+ "off",
1105
+ "eco",
1106
+ "heat_pump",
1107
+ "high_demand"
1108
+ ],
1109
+ min_temp: 43,
1110
+ max_temp: 60
1111
+ }), {
1112
+ device_id: "hp_tank",
1113
+ area_id: "garage",
1114
+ supported_features: 3
1115
+ });
1116
+ add(makeEntity("fan.bedroom_ceiling", "on", {
1117
+ percentage: 200 / 3,
1118
+ percentage_step: 100 / 3,
1119
+ current_direction: "forward"
1120
+ }), {
1121
+ device_id: "ceiling_fan",
1122
+ area_id: "bedroom",
1123
+ supported_features: 5
1124
+ });
1125
+ add(makeEntity("fan.air_purifier", "on", {
1126
+ percentage: 40,
1127
+ preset_modes: [
1128
+ "auto",
1129
+ "sleep",
1130
+ "turbo"
1131
+ ],
1132
+ preset_mode: "auto",
1133
+ oscillating: false
1134
+ }), {
1135
+ device_id: "purifier",
1136
+ area_id: "living_room",
1137
+ supported_features: 11
1138
+ });
1139
+ add(makeEntity("cover.living_room_blinds", "open", {
1140
+ current_position: 80,
1141
+ device_class: "shade"
1142
+ }), {
1143
+ device_id: "blinds_lr",
1144
+ area_id: "living_room",
1145
+ device_class: "shade",
1146
+ supported_features: 15
1147
+ });
1148
+ add(makeEntity("cover.bedroom_curtains", "closed", {
1149
+ current_position: 0,
1150
+ device_class: "curtain"
1151
+ }), {
1152
+ device_id: "curtains_br",
1153
+ area_id: "bedroom",
1154
+ device_class: "curtain",
1155
+ supported_features: 15
1156
+ });
1157
+ add(makeEntity("cover.garage_door", "closed", { device_class: "garage" }), {
1158
+ device_id: "garage_door_opener",
1159
+ area_id: "garage",
1160
+ device_class: "garage",
1161
+ supported_features: 11
1162
+ });
1163
+ add(makeEntity("cover.driveway_gate", "open", {
1164
+ device_class: "gate",
1165
+ assumed_state: true
1166
+ }), {
1167
+ area_id: "garage",
1168
+ device_class: "gate",
1169
+ supported_features: 3
1170
+ });
1171
+ add(makeEntity("cover.living_room_shutters", "open", {
1172
+ current_position: 45,
1173
+ current_tilt_position: 30,
1174
+ device_class: "shutter"
1175
+ }), {
1176
+ device_id: "shutters_lr",
1177
+ area_id: "living_room",
1178
+ device_class: "shutter",
1179
+ supported_features: 255
1180
+ });
1181
+ add(makeEntity("cover.kitchen_blinds", "open", {
1182
+ current_position: 100,
1183
+ device_class: "blind"
1184
+ }), {
1185
+ device_id: "blinds_kitchen",
1186
+ area_id: "kitchen",
1187
+ device_class: "blind",
1188
+ supported_features: 127
1189
+ });
1190
+ add(makeEntity("lock.front_door_lock", "locked", {}), {
1191
+ device_id: "lock_front",
1192
+ area_id: "entry",
1193
+ supported_features: 1
1194
+ });
1195
+ add(makeEntity("lock.back_door_lock", "locked", {}), {
1196
+ device_id: "lock_back",
1197
+ area_id: "entry",
1198
+ supported_features: 1
1199
+ });
1200
+ add(makeEntity("switch.coffee_machine", "off", { device_class: "outlet" }), {
1201
+ area_id: "kitchen",
1202
+ device_class: "outlet"
1203
+ });
1204
+ add(makeEntity("switch.fan_living_room", "on", { device_class: "switch" }), {
1205
+ area_id: "living_room",
1206
+ device_class: "switch"
1207
+ });
1208
+ add(makeEntity("media_player.living_room_speaker", "playing", {
1209
+ media_title: "Lo-fi Beats",
1210
+ media_artist: "Chill Station",
1211
+ media_content_type: "music",
1212
+ volume_level: .4,
1213
+ is_volume_muted: false,
1214
+ supported_features: 152461
1215
+ }), {
1216
+ device_id: "speaker_lr",
1217
+ area_id: "living_room",
1218
+ supported_features: 152461
1219
+ });
1220
+ for (const w of WEATHER_FIXTURES) add(makeWeatherEntity(w), { platform: "met" });
1221
+ add(makeEntity("camera.front_door_camera", "streaming", {
1222
+ entity_picture: "/api/camera_proxy/camera.front_door_camera",
1223
+ frontend_stream_type: "hls",
1224
+ access_token: "demo-token"
1225
+ }), {
1226
+ device_id: "camera_front",
1227
+ area_id: "entry",
1228
+ supported_features: 2
1229
+ });
1230
+ add(makeEntity("scene.movie_night", "scening", { entity_id: [
1231
+ "light.living_room_main",
1232
+ "cover.living_room_blinds",
1233
+ "media_player.living_room_speaker"
1234
+ ] }), { area_id: "living_room" });
1235
+ add(makeEntity("scene.good_morning", "scening", { entity_id: [
1236
+ "light.bedroom_ceiling",
1237
+ "cover.bedroom_curtains",
1238
+ "switch.coffee_machine"
1239
+ ] }), {});
1240
+ add(makeEntity("button.restart_home_assistant", "unknown", { device_class: "restart" }), {
1241
+ entity_category: "config",
1242
+ device_class: "restart"
1243
+ });
1244
+ add(makeEntity("button.update_firmware", "unknown", { device_class: "update" }), {
1245
+ entity_category: "config",
1246
+ device_class: "update"
1247
+ });
1248
+ add(makeEntity("sensor.door_lock_battery", "92", {
1249
+ unit_of_measurement: "%",
1250
+ device_class: "battery",
1251
+ state_class: "measurement"
1252
+ }), {
1253
+ device_id: "lock_front",
1254
+ area_id: "entry",
1255
+ device_class: "battery",
1256
+ unit_of_measurement: "%"
1257
+ });
1258
+ add(makeEntity("sensor.motion_sensor_battery", "65", {
1259
+ unit_of_measurement: "%",
1260
+ device_class: "battery",
1261
+ state_class: "measurement"
1262
+ }), {
1263
+ device_id: "motion_sensor",
1264
+ area_id: "entry",
1265
+ device_class: "battery",
1266
+ unit_of_measurement: "%"
1267
+ });
1268
+ const nowMs = Date.now();
1269
+ const sample = simulateEnergy(nowMs);
1270
+ const sun = sunEvents(nowMs);
1271
+ add(makeEntity("sun.sun", isSunUp(nowMs) ? "above_horizon" : "below_horizon", {
1272
+ friendly_name: "Sun",
1273
+ elevation: sun.elevation,
1274
+ next_rising: sun.nextRising,
1275
+ next_setting: sun.nextSetting
1276
+ }), {});
1277
+ const powerSensors = [
1278
+ {
1279
+ id: "sensor.solar_power",
1280
+ name: "Solar Production",
1281
+ deviceClass: "power",
1282
+ unit: "W"
1283
+ },
1284
+ {
1285
+ id: "sensor.grid_import_power",
1286
+ name: "Grid Import",
1287
+ deviceClass: "power",
1288
+ unit: "W"
1289
+ },
1290
+ {
1291
+ id: "sensor.grid_export_power",
1292
+ name: "Grid Export",
1293
+ deviceClass: "power",
1294
+ unit: "W"
1295
+ },
1296
+ {
1297
+ id: "sensor.battery_charge_power",
1298
+ name: "Battery Charge",
1299
+ deviceClass: "power",
1300
+ unit: "W"
1301
+ },
1302
+ {
1303
+ id: "sensor.battery_discharge_power",
1304
+ name: "Battery Discharge",
1305
+ deviceClass: "power",
1306
+ unit: "W"
1307
+ },
1308
+ {
1309
+ id: "sensor.battery_soc",
1310
+ name: "Battery",
1311
+ deviceClass: "battery",
1312
+ unit: "%"
1313
+ },
1314
+ {
1315
+ id: "sensor.home_power",
1316
+ name: "Home Consumption",
1317
+ deviceClass: "power",
1318
+ unit: "W"
1319
+ },
1320
+ {
1321
+ id: "sensor.fridge_power",
1322
+ name: "Fridge",
1323
+ deviceClass: "power",
1324
+ unit: "W"
1325
+ },
1326
+ {
1327
+ id: "sensor.dishwasher_power",
1328
+ name: "Dishwasher",
1329
+ deviceClass: "power",
1330
+ unit: "W"
1331
+ },
1332
+ {
1333
+ id: "sensor.washing_machine_power",
1334
+ name: "Washing Machine",
1335
+ deviceClass: "power",
1336
+ unit: "W"
1337
+ },
1338
+ {
1339
+ id: "sensor.oven_power",
1340
+ name: "Oven",
1341
+ deviceClass: "power",
1342
+ unit: "W"
1343
+ },
1344
+ {
1345
+ id: "sensor.ev_charger_power",
1346
+ name: "EV Charger",
1347
+ deviceClass: "power",
1348
+ unit: "W"
1349
+ },
1350
+ {
1351
+ id: "sensor.always_on_power",
1352
+ name: "Always On",
1353
+ deviceClass: "power",
1354
+ unit: "W"
1355
+ }
1356
+ ];
1357
+ for (const s of powerSensors) {
1358
+ const value = energyEntityValue(s.id, sample) ?? 0;
1359
+ add(makeEntity(s.id, formatEnergyState(s.id, value), {
1360
+ friendly_name: s.name,
1361
+ unit_of_measurement: s.unit,
1362
+ device_class: s.deviceClass,
1363
+ state_class: "measurement"
1364
+ }), {
1365
+ area_id: "utility",
1366
+ device_class: s.deviceClass,
1367
+ unit_of_measurement: s.unit
1368
+ });
1369
+ }
1370
+ return {
1371
+ entities,
1372
+ entityRegistry,
1373
+ areas,
1374
+ devices
1375
+ };
1376
+ }
1377
+
1378
+ //#endregion
1379
+ //#region src/demo/demo-provider.ts
1380
+ let _isDemoMode = false;
1381
+ /**
1382
+ * Whether demo mode is currently active.
1383
+ */
1384
+ function isDemoMode() {
1385
+ return _isDemoMode;
1386
+ }
1387
+ /**
1388
+ * Load demo fixtures into the SolidJS store.
1389
+ *
1390
+ * Populates entities, entity registry, areas, and devices.
1391
+ * Sets connection state to "connected" (pretend connected).
1392
+ */
1393
+ async function loadDemoData() {
1394
+ const fixtures = createDemoFixtures();
1395
+ setState("entities", reconcile(fixtures.entities));
1396
+ setState("entityRegistry", reconcile(fixtures.entityRegistry));
1397
+ setState("areas", reconcile(fixtures.areas));
1398
+ setState("devices", reconcile(fixtures.devices));
1399
+ setState("hassUrl", "https://demo.home-assistant.local");
1400
+ setState("connectionState", "connected");
1401
+ _isDemoMode = true;
1402
+ startDemoEnergyTicker();
1403
+ }
1404
+ /**
1405
+ * Unload demo data and reset to disconnected state.
1406
+ */
1407
+ function unloadDemoData() {
1408
+ stopDemoEnergyTicker();
1409
+ setState("entities", reconcile({}));
1410
+ setState("entityRegistry", reconcile({}));
1411
+ setState("areas", reconcile({}));
1412
+ setState("devices", reconcile({}));
1413
+ setState("hassUrl", null);
1414
+ setState("connectionState", "disconnected");
1415
+ _isDemoMode = false;
1416
+ }
1417
+ const ENERGY_TICK_MS = 5e3;
1418
+ let _energyTicker = null;
1419
+ /** Write the current energy sample into the store as string states (like real HA). */
1420
+ function tickEnergy() {
1421
+ const nowMs = Date.now();
1422
+ const sample = simulateEnergy(nowMs);
1423
+ const sun = sunEvents(nowMs);
1424
+ const nowIso = new Date(nowMs).toISOString();
1425
+ setState(produce((s) => {
1426
+ for (const entityId of ENERGY_ENTITY_IDS) {
1427
+ const e = s.entities[entityId];
1428
+ if (!e) continue;
1429
+ const value = energyEntityValue(entityId, sample);
1430
+ if (value === void 0) continue;
1431
+ const next = formatEnergyState(entityId, value);
1432
+ if (e.state !== next) e.last_changed = nowIso;
1433
+ e.state = next;
1434
+ e.last_updated = nowIso;
1435
+ }
1436
+ const sunEntity = s.entities["sun.sun"];
1437
+ if (sunEntity) {
1438
+ const nextState = isSunUp(nowMs) ? "above_horizon" : "below_horizon";
1439
+ if (sunEntity.state !== nextState) sunEntity.last_changed = nowIso;
1440
+ sunEntity.state = nextState;
1441
+ sunEntity.last_updated = nowIso;
1442
+ sunEntity.attributes.elevation = sun.elevation;
1443
+ sunEntity.attributes.next_rising = sun.nextRising;
1444
+ sunEntity.attributes.next_setting = sun.nextSetting;
1445
+ }
1446
+ }));
1447
+ }
1448
+ /**
1449
+ * Start the demo energy ticker. Updates the energy sensors and `sun.sun`
1450
+ * every 5 seconds. Idempotent: clears any prior interval first. SSR-safe.
1451
+ */
1452
+ function startDemoEnergyTicker() {
1453
+ stopDemoEnergyTicker();
1454
+ if (typeof setInterval !== "function") return;
1455
+ tickEnergy();
1456
+ _energyTicker = setInterval(tickEnergy, ENERGY_TICK_MS);
1457
+ }
1458
+ /** Stop the demo energy ticker if running. */
1459
+ function stopDemoEnergyTicker() {
1460
+ if (_energyTicker !== null) {
1461
+ clearInterval(_energyTicker);
1462
+ _energyTicker = null;
1463
+ }
1464
+ }
1465
+ /**
1466
+ * Apply an optimistic state update for demo mode.
1467
+ *
1468
+ * When a service call is made in demo mode, this updates the entity
1469
+ * state locally (no WebSocket message sent). State resets on page refresh.
1470
+ */
1471
+ function applyDemoServiceCall(_domain, service, _serviceData = {}, target = {}) {
1472
+ if (!_isDemoMode) return;
1473
+ const entityIds = Array.isArray(target.entity_id) ? target.entity_id : target.entity_id ? [target.entity_id] : [];
1474
+ for (const entityId of entityIds) {
1475
+ const entity = state.entities[entityId];
1476
+ if (!entity) continue;
1477
+ const entityDomain = extractDomain(entityId);
1478
+ setState(produce((s) => {
1479
+ const e = s.entities[entityId];
1480
+ if (!e) return;
1481
+ const now$1 = (/* @__PURE__ */ new Date()).toISOString();
1482
+ e.last_changed = now$1;
1483
+ e.last_updated = now$1;
1484
+ if (service === "turn_on") applyTurnOn(e, entityDomain, _serviceData);
1485
+ else if (service === "press" && entityDomain === "button") e.state = now$1;
1486
+ else if (service === "turn_off") applyTurnOff(e, entityDomain);
1487
+ else if (service === "toggle") if (e.state === "on" || e.state === "playing" || e.state === "open") applyTurnOff(e, entityDomain);
1488
+ else applyTurnOn(e, entityDomain, _serviceData);
1489
+ else if (service === "lock") e.state = "locked";
1490
+ else if (service === "unlock") e.state = "unlocked";
1491
+ else if (service === "open_cover") {
1492
+ e.state = "open";
1493
+ if ("current_position" in e.attributes) e.attributes.current_position = 100;
1494
+ } else if (service === "close_cover") {
1495
+ e.state = "closed";
1496
+ if ("current_position" in e.attributes) e.attributes.current_position = 0;
1497
+ } else if (service === "set_cover_position" && _serviceData.position != null) {
1498
+ e.attributes.current_position = _serviceData.position;
1499
+ e.state = _serviceData.position > 0 ? "open" : "closed";
1500
+ } else if (service === "open_cover_tilt") e.attributes.current_tilt_position = 100;
1501
+ else if (service === "close_cover_tilt") e.attributes.current_tilt_position = 0;
1502
+ else if (service === "set_cover_tilt_position" && _serviceData.tilt_position != null) e.attributes.current_tilt_position = _serviceData.tilt_position;
1503
+ else if (service === "set_temperature") {
1504
+ if (_serviceData.temperature != null) e.attributes.temperature = _serviceData.temperature;
1505
+ if (_serviceData.target_temp_low != null) e.attributes.target_temp_low = _serviceData.target_temp_low;
1506
+ if (_serviceData.target_temp_high != null) e.attributes.target_temp_high = _serviceData.target_temp_high;
1507
+ } else if (service === "set_hvac_mode" && _serviceData.hvac_mode != null) e.state = _serviceData.hvac_mode;
1508
+ else if (service === "set_fan_mode" && _serviceData.fan_mode != null) e.attributes.fan_mode = _serviceData.fan_mode;
1509
+ else if (service === "set_preset_mode" && _serviceData.preset_mode != null) {
1510
+ e.attributes.preset_mode = _serviceData.preset_mode;
1511
+ if (entityDomain === "fan") e.state = "on";
1512
+ } else if (service === "set_percentage" && _serviceData.percentage != null) {
1513
+ e.attributes.percentage = _serviceData.percentage;
1514
+ e.state = _serviceData.percentage > 0 ? "on" : "off";
1515
+ } else if (service === "oscillate" && _serviceData.oscillating != null) e.attributes.oscillating = _serviceData.oscillating;
1516
+ else if (service === "set_direction" && _serviceData.direction != null) e.attributes.current_direction = _serviceData.direction;
1517
+ else if (service === "set_operation_mode" && _serviceData.operation_mode != null) e.state = _serviceData.operation_mode;
1518
+ else if (service === "set_away_mode" && _serviceData.away_mode != null) e.attributes.away_mode = _serviceData.away_mode ? "on" : "off";
1519
+ else if (service === "volume_set" && _serviceData.volume_level != null) e.attributes.volume_level = _serviceData.volume_level;
1520
+ else if (service === "media_play_pause") e.state = e.state === "playing" ? "paused" : "playing";
1521
+ else if (service === "media_next_track" || service === "media_previous_track") applyTrackSkip(e, service === "media_next_track" ? 1 : -1);
1522
+ else if (service === "select_source" && _serviceData.source != null) e.attributes.source = _serviceData.source;
1523
+ }));
1524
+ }
1525
+ }
1526
+ function applyTurnOn(e, domain, serviceData = {}) {
1527
+ if (domain === "light") {
1528
+ e.state = "on";
1529
+ if (serviceData.brightness_pct !== void 0) {
1530
+ const pct = Math.max(0, Math.min(100, serviceData.brightness_pct));
1531
+ e.attributes.brightness = Math.round(pct / 100 * 255);
1532
+ } else e.attributes.brightness = serviceData.brightness ?? e.attributes.brightness ?? 255;
1533
+ if (serviceData.color_temp_kelvin) e.attributes.color_temp_kelvin = serviceData.color_temp_kelvin;
1534
+ if (serviceData.hs_color) e.attributes.hs_color = serviceData.hs_color;
1535
+ } else if (domain === "scene") e.state = (/* @__PURE__ */ new Date()).toISOString();
1536
+ else if (domain === "media_player") e.state = "playing";
1537
+ else if (domain === "cover") {
1538
+ e.state = "open";
1539
+ if ("current_position" in e.attributes) e.attributes.current_position = 100;
1540
+ } else e.state = "on";
1541
+ }
1542
+ const DEMO_TRACKS = [
1543
+ {
1544
+ title: "Lo-fi Beats",
1545
+ artist: "Chill Station"
1546
+ },
1547
+ {
1548
+ title: "Golden Hour",
1549
+ artist: "Analog Sunset"
1550
+ },
1551
+ {
1552
+ title: "Night Drive",
1553
+ artist: "Neon Coast"
1554
+ }
1555
+ ];
1556
+ function applyTrackSkip(e, delta) {
1557
+ const current = DEMO_TRACKS.findIndex((t) => t.title === e.attributes.media_title);
1558
+ const next = DEMO_TRACKS[(current + delta + DEMO_TRACKS.length) % DEMO_TRACKS.length];
1559
+ if (!next) return;
1560
+ e.attributes.media_title = next.title;
1561
+ e.attributes.media_artist = next.artist;
1562
+ }
1563
+ function applyTurnOff(e, domain) {
1564
+ if (domain === "light") {
1565
+ e.state = "off";
1566
+ delete e.attributes.brightness;
1567
+ } else if (domain === "media_player") e.state = "paused";
1568
+ else if (domain === "cover") {
1569
+ e.state = "closed";
1570
+ if ("current_position" in e.attributes) e.attributes.current_position = 0;
1571
+ } else e.state = "off";
1572
+ }
1573
+
1574
+ //#endregion
1575
+ //#region src/core/privileged-conn.ts
1576
+ let privileged = null;
1577
+ /** Read the live connection. Null before connect and after disconnect. */
1578
+ function privilegedConn() {
1579
+ return privileged;
1580
+ }
1581
+ /** Set by the connection layer on connect/disconnect. Host-side callers only. */
1582
+ function setPrivilegedConn(conn$1) {
1583
+ privileged = conn$1;
1584
+ }
1585
+
1586
+ //#endregion
1587
+ //#region src/commands/service.ts
1588
+ /**
1589
+ * Call a Home Assistant service
1590
+ */
1591
+ async function callService(domain, service, serviceData = {}, target = {}) {
1592
+ const connection = privilegedConn();
1593
+ if (!connection) {
1594
+ applyDemoServiceCall(domain, service, serviceData, target);
1595
+ return;
1596
+ }
1597
+ try {
1598
+ const mockConnection = connection;
1599
+ if (mockConnection && typeof mockConnection.callService === "function") await mockConnection.callService(domain, service, serviceData, target);
1600
+ else await connection.sendMessagePromise({
1601
+ type: "call_service",
1602
+ domain,
1603
+ service,
1604
+ service_data: serviceData,
1605
+ target
1606
+ });
1607
+ } catch (error) {
1608
+ throw new Error(`Service call failed: ${error.message || String(error)}`);
1609
+ }
1610
+ }
1611
+ /**
1612
+ * Turn on entity or entities
1613
+ */
1614
+ async function turnOn(entityId, serviceData = {}) {
1615
+ const firstEntityId = Array.isArray(entityId) ? entityId[0] : entityId;
1616
+ if (!firstEntityId) throw new Error("Entity ID is required");
1617
+ const domain = firstEntityId.split(".")[0];
1618
+ if (!domain) throw new Error(`Invalid entity ID: ${firstEntityId}`);
1619
+ await callService(domain, "turn_on", serviceData, { entity_id: entityId });
1620
+ }
1621
+ /**
1622
+ * Turn off entity or entities
1623
+ */
1624
+ async function turnOff(entityId, serviceData = {}) {
1625
+ const firstEntityId = Array.isArray(entityId) ? entityId[0] : entityId;
1626
+ if (!firstEntityId) throw new Error("Entity ID is required");
1627
+ const domain = firstEntityId.split(".")[0];
1628
+ if (!domain) throw new Error(`Invalid entity ID: ${firstEntityId}`);
1629
+ await callService(domain, "turn_off", serviceData, { entity_id: entityId });
1630
+ }
1631
+ /**
1632
+ * Toggle entity or entities
1633
+ */
1634
+ async function toggle(entityId, serviceData = {}) {
1635
+ const firstEntityId = Array.isArray(entityId) ? entityId[0] : entityId;
1636
+ if (!firstEntityId) throw new Error("Entity ID is required");
1637
+ const domain = firstEntityId.split(".")[0];
1638
+ if (!domain) throw new Error(`Invalid entity ID: ${firstEntityId}`);
1639
+ await callService(domain, "toggle", serviceData, { entity_id: entityId });
1640
+ }
1641
+ /**
1642
+ * Update entity registry entry
1643
+ */
1644
+ async function updateEntity(entityId, updates) {
1645
+ const connection = privilegedConn();
1646
+ if (!connection) throw new Error("Not connected to Home Assistant. Call initConnection() first.");
1647
+ try {
1648
+ const result = await connection.sendMessagePromise({
1649
+ type: "config/entity_registry/update",
1650
+ entity_id: entityId,
1651
+ ...updates
1652
+ });
1653
+ if (result && typeof result === "object" && "_mockError" in result) throw new Error(`Entity registry entry not found: ${entityId}`);
1654
+ return result;
1655
+ } catch (error) {
1656
+ if (error?.message && error.message.includes("Entity registry entry not found")) throw error;
1657
+ throw new Error(`Entity update failed: ${error.message || String(error)}`);
1658
+ }
1659
+ }
1660
+ /**
1661
+ * Send a generic WebSocket command
1662
+ */
1663
+ async function sendCommand(command) {
1664
+ const connection = privilegedConn();
1665
+ if (!connection) throw new Error("Not connected");
1666
+ try {
1667
+ return await connection.sendMessagePromise(command);
1668
+ } catch (error) {
1669
+ throw new Error(`Command failed: ${error.message || String(error)}`);
1670
+ }
1671
+ }
1672
+ /**
1673
+ * Execute multiple service calls in parallel
1674
+ */
1675
+ async function batchServiceCalls(calls) {
1676
+ await Promise.all(calls.map((call) => callService(call.domain, call.service, call.serviceData, call.target)));
1677
+ }
1678
+ /**
1679
+ * Execute multiple entity updates in parallel
1680
+ */
1681
+ async function batchEntityUpdates(updates) {
1682
+ return Promise.all(updates.map((u) => updateEntity(u.entityId, u.updates)));
1683
+ }
1684
+
1685
+ //#endregion
1686
+ //#region src/entities/views.ts
1687
+ /**
1688
+ * Get icon for an entity from registry or attributes
1689
+ */
1690
+ function resolveIcon(entity, registry) {
1691
+ if (registry?.icon) return {
1692
+ icon: registry.icon,
1693
+ source: "registry"
1694
+ };
1695
+ if (entity.attributes?.icon) return {
1696
+ icon: entity.attributes.icon,
1697
+ source: "attribute"
1698
+ };
1699
+ return null;
1700
+ }
1701
+ /**
1702
+ * Build an EntityView from runtime state and registry metadata
1703
+ */
1704
+ function buildEntityView(entity, registry) {
1705
+ const domain = extractDomain(entity.entity_id);
1706
+ const attributes = entity.attributes ?? {};
1707
+ const friendlyName$1 = attributes.friendly_name ?? registry?.name ?? entity.entity_id;
1708
+ const name = registry?.name ?? friendlyName$1;
1709
+ const iconResolution = resolveIcon(entity, registry);
1710
+ const { device_class: _dc, unit_of_measurement: _uom, friendly_name: _fn, icon: _icon,...restAttributes } = attributes;
1711
+ let areaId = registry?.area_id ?? null;
1712
+ if (areaId === null && registry?.device_id) {
1713
+ const device = state.devices[registry.device_id];
1714
+ if (device) areaId = device.area_id ?? null;
1715
+ }
1716
+ return {
1717
+ id: entity.entity_id,
1718
+ domain,
1719
+ state: entity.state,
1720
+ attributes: restAttributes,
1721
+ lastChanged: new Date(entity.last_changed),
1722
+ lastUpdated: new Date(entity.last_updated),
1723
+ context: {
1724
+ id: entity.context?.id ?? "",
1725
+ parentId: entity.context?.parent_id ?? null,
1726
+ userId: entity.context?.user_id ?? null
1727
+ },
1728
+ name,
1729
+ friendlyName: friendlyName$1,
1730
+ areaId,
1731
+ deviceId: registry?.device_id ?? null,
1732
+ platform: registry?.platform ?? "unknown",
1733
+ uniqueId: registry?.unique_id ?? null,
1734
+ isDisabled: registry?.disabled_by !== null && registry?.disabled_by !== void 0,
1735
+ isHidden: registry?.hidden_by !== null && registry?.hidden_by !== void 0,
1736
+ icon: iconResolution?.icon ?? null,
1737
+ iconSource: iconResolution?.source ?? "default",
1738
+ entityCategory: registry?.entity_category ?? null,
1739
+ labels: registry?.labels ?? [],
1740
+ aliases: registry?.aliases ?? [],
1741
+ deviceClass: registry?.device_class ?? attributes.device_class ?? null,
1742
+ unitOfMeasurement: registry?.unit_of_measurement ?? attributes.unit_of_measurement ?? null,
1743
+ supportedFeatures: registry?.supported_features ?? attributes.supported_features
1744
+ };
1745
+ }
1746
+ /**
1747
+ * Get or build an EntityView
1748
+ */
1749
+ function getEntityView(entityId) {
1750
+ const entity = state.entities[entityId];
1751
+ if (!entity) return void 0;
1752
+ const registry = state.entityRegistry[entityId];
1753
+ return buildEntityView(entity, registry);
1754
+ }
1755
+ /**
1756
+ * Get multiple entity views
1757
+ */
1758
+ function getEntityViews(entityIds) {
1759
+ const views = [];
1760
+ for (const id of entityIds) {
1761
+ const view = getEntityView(id);
1762
+ if (view) views.push(view);
1763
+ }
1764
+ return views;
1765
+ }
1766
+ /**
1767
+ * Get all entity views
1768
+ */
1769
+ function getAllEntityViews() {
1770
+ return getEntityViews(Object.keys(state.entities));
1771
+ }
1772
+ /**
1773
+ * Shallow equality check for EntityView.
1774
+ * Compares fields that affect rendering; skips lastUpdated (heartbeat noise).
1775
+ */
1776
+ function entityViewEquals(a, b) {
1777
+ if (a === b) return true;
1778
+ if (!a || !b) return false;
1779
+ 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;
1780
+ }
1781
+
1782
+ //#endregion
1783
+ //#region src/entities/area-views.ts
1784
+ /** The area an entity belongs to: its own `area_id` wins; otherwise it inherits
1785
+ * the area of its device. Null when neither resolves. */
1786
+ function entityAreaId(entry) {
1787
+ if (entry.area_id) return entry.area_id;
1788
+ if (entry.device_id) return state.devices[entry.device_id]?.area_id ?? null;
1789
+ return null;
1790
+ }
1791
+ /** One pass over the device + entity registries → membership per area.
1792
+ * O(devices + entities) for the whole home, vs the O(areas × (devices +
1793
+ * entities)) of resolving each area independently. */
1794
+ function computeAreaMembership() {
1795
+ const byArea = /* @__PURE__ */ new Map();
1796
+ const ensure = (areaId) => {
1797
+ let m = byArea.get(areaId);
1798
+ if (!m) {
1799
+ m = {
1800
+ devices: [],
1801
+ entityIds: []
1802
+ };
1803
+ byArea.set(areaId, m);
1804
+ }
1805
+ return m;
1806
+ };
1807
+ for (const device of Object.values(state.devices)) if (device.area_id) ensure(device.area_id).devices.push(device);
1808
+ for (const [entityId, entry] of Object.entries(state.entityRegistry)) {
1809
+ const areaId = entityAreaId(entry);
1810
+ if (areaId) ensure(areaId).entityIds.push(entityId);
1811
+ }
1812
+ return byArea;
1813
+ }
1814
+ /** Membership for a single area, without indexing every other area. */
1815
+ function membershipFor(areaId) {
1816
+ const devices = [];
1817
+ for (const device of Object.values(state.devices)) if (device.area_id === areaId) devices.push(device);
1818
+ const entityIds = [];
1819
+ for (const [entityId, entry] of Object.entries(state.entityRegistry)) if (entityAreaId(entry) === areaId) entityIds.push(entityId);
1820
+ return {
1821
+ devices,
1822
+ entityIds
1823
+ };
1824
+ }
1825
+ /**
1826
+ * Build a DeviceView from registry data
1827
+ */
1828
+ function buildDeviceView(device) {
1829
+ return {
1830
+ id: device.id,
1831
+ name: device.name ?? "",
1832
+ nameByUser: device.name_by_user ?? null,
1833
+ manufacturer: device.manufacturer ?? null,
1834
+ model: device.model ?? null,
1835
+ swVersion: device.sw_version ?? null,
1836
+ areaId: device.area_id ?? null,
1837
+ configEntries: device.config_entries ?? [],
1838
+ connections: device.connections ?? [],
1839
+ identifiers: device.identifiers ?? [],
1840
+ disabledBy: device.disabled_by ?? null
1841
+ };
1842
+ }
1843
+ /** Assemble an AreaView from pre-resolved membership. `entities` is a lazy
1844
+ * getter: materializing live EntityViews reads entity state, so deferring it
1845
+ * keeps callers that only need names/ids/counts off the per-state-tick
1846
+ * recompute path. The getter stays reactive — read inside a tracking scope it
1847
+ * tracks those entities' state and updates like any other store read. */
1848
+ function assembleAreaView(areaId, membership) {
1849
+ const area = state.areas[areaId];
1850
+ if (!area) throw new Error(`Area ${areaId} not found`);
1851
+ const devices = membership.devices.map((device) => buildDeviceView(device));
1852
+ const entityIds = membership.entityIds;
1853
+ return {
1854
+ id: areaId,
1855
+ name: area.name,
1856
+ normalizedName: area.normalized_name ?? area.name.toLowerCase(),
1857
+ aliases: Array.isArray(area.aliases) ? area.aliases : [],
1858
+ floorId: area.floor_id ?? null,
1859
+ icon: area.icon ?? null,
1860
+ picture: area.picture ?? null,
1861
+ labels: Array.isArray(area.labels) ? area.labels : [],
1862
+ temperatureEntityId: area.temperature_entity_id ?? null,
1863
+ humidityEntityId: area.humidity_entity_id ?? null,
1864
+ createdAt: area.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
1865
+ modifiedAt: area.modified_at ?? (/* @__PURE__ */ new Date()).toISOString(),
1866
+ devices,
1867
+ entityIds,
1868
+ deviceIds: devices.map((d) => d.id),
1869
+ get entities() {
1870
+ return entityIds.length > 0 ? getEntityViews(entityIds) : [];
1871
+ }
1872
+ };
1873
+ }
1874
+ /**
1875
+ * Build an AreaView for a single area from registry data.
1876
+ */
1877
+ function buildAreaView(areaId) {
1878
+ return assembleAreaView(areaId, membershipFor(areaId));
1879
+ }
1880
+ /**
1881
+ * Get all area views. Membership is resolved in a single registry pass; entity
1882
+ * views stay lazy per area (see `assembleAreaView`).
1883
+ */
1884
+ function getAreaViews() {
1885
+ const membership = computeAreaMembership();
1886
+ return Object.keys(state.areas).map((areaId) => assembleAreaView(areaId, membership.get(areaId) ?? {
1887
+ devices: [],
1888
+ entityIds: []
1889
+ }));
1890
+ }
1891
+ /**
1892
+ * Get area view
1893
+ */
1894
+ function getAreaView(areaId) {
1895
+ try {
1896
+ return buildAreaView(areaId);
1897
+ } catch {
1898
+ return void 0;
1899
+ }
1900
+ }
1901
+
1902
+ //#endregion
1903
+ //#region src/history/statistics.ts
1904
+ const STATISTIC_TYPES = [
1905
+ "mean",
1906
+ "sum",
1907
+ "min",
1908
+ "max",
1909
+ "state",
1910
+ "change"
1911
+ ];
1912
+ /**
1913
+ * HA returns start/end as ISO strings or ms numbers depending on version.
1914
+ * Normalize both shapes to ms epoch numbers; unparseable values become NaN.
1915
+ */
1916
+ function normalizeStatisticTime(value) {
1917
+ if (typeof value === "number") return value;
1918
+ if (typeof value === "string") return new Date(value).getTime();
1919
+ return NaN;
1920
+ }
1921
+ function normalizeNumber(value) {
1922
+ return typeof value === "number" ? value : void 0;
1923
+ }
1924
+ function normalizeStatisticValue(raw) {
1925
+ const value = {
1926
+ start: normalizeStatisticTime(raw.start),
1927
+ end: normalizeStatisticTime(raw.end)
1928
+ };
1929
+ const mean = normalizeNumber(raw.mean);
1930
+ if (mean !== void 0) value.mean = mean;
1931
+ const sum = normalizeNumber(raw.sum);
1932
+ if (sum !== void 0) value.sum = sum;
1933
+ const min = normalizeNumber(raw.min);
1934
+ if (min !== void 0) value.min = min;
1935
+ const max = normalizeNumber(raw.max);
1936
+ if (max !== void 0) value.max = max;
1937
+ const stateVal = normalizeNumber(raw.state);
1938
+ if (stateVal !== void 0) value.state = stateVal;
1939
+ const change = normalizeNumber(raw.change);
1940
+ if (change !== void 0) value.change = change;
1941
+ return value;
1942
+ }
1943
+ /**
1944
+ * Fetch long-term statistics for one or more statistic ids during a period.
1945
+ *
1946
+ * Statistic ids with no data are returned as empty arrays so callers never
1947
+ * hit `undefined`.
1948
+ */
1949
+ async function fetchStatisticsDuringPeriod(connection, statisticIds, options) {
1950
+ const { startTime, endTime, period } = options;
1951
+ if (isDemoMode()) {
1952
+ const result$1 = {};
1953
+ const statPeriod = period === "hour" || period === "day" ? period : "day";
1954
+ const endMs = (endTime ?? /* @__PURE__ */ new Date()).getTime();
1955
+ for (const id of statisticIds) result$1[id] = isEnergyEntity(id) ? synthesizeEnergyStatistics(id, startTime.getTime(), endMs, statPeriod) : [];
1956
+ return result$1;
1957
+ }
1958
+ const params = {
1959
+ type: "recorder/statistics_during_period",
1960
+ start_time: startTime.toISOString(),
1961
+ statistic_ids: statisticIds,
1962
+ period,
1963
+ types: STATISTIC_TYPES
1964
+ };
1965
+ if (endTime) params.end_time = endTime.toISOString();
1966
+ const response = await connection.sendMessagePromise(params);
1967
+ const result = {};
1968
+ for (const id of statisticIds) result[id] = [];
1969
+ if (response && typeof response === "object") for (const [id, buckets] of Object.entries(response)) result[id] = Array.isArray(buckets) ? buckets.map(normalizeStatisticValue) : [];
1970
+ return result;
1971
+ }
1972
+
1973
+ //#endregion
1974
+ export { applyDemoServiceCall, batchEntityUpdates, batchServiceCalls, buildAreaView, buildDeviceView, buildEntityView, callService, createDemoFixtures, demoEnergyPreferences, entityViewEquals, extractDomain, fetchStatisticsDuringPeriod, forceResubscribe, getAllEntityViews, getAreaView, getAreaViews, getEntityView, getEntityViews, isDemoMode, isEnergyEntity, loadDemoData, normalizeStatisticTime, privilegedConn, registerEntity, sendCommand, setManagerConnection, setPrivilegedConn, setResubscribeHandler, setState, startDemoEnergyTicker, state, stopDemoEnergyTicker, synthesizeEnergyHistory, toggle, turnOff, turnOn, unloadDemoData, updateEntity };