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