@glasshome/sync-layer 0.9.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -16
- package/dist/index.d.ts +20 -48
- package/dist/index.js +1141 -1177
- package/dist/{service-C8H42I-Q.d.ts → service-B1gegd-N.d.ts} +2 -2
- package/dist/solid/index.d.ts +1 -1
- package/dist/solid/index.js +103 -1
- package/dist/{statistics-C5j1DLGM.js → track-IkwP6XmO.js} +737 -826
- package/dist/worker/worker-main.js +1 -1
- package/dist/{worker-main-DamaVb7B.js → worker-main-B6eeHPDQ.js} +4 -3
- package/package.json +6 -4
package/dist/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { t as runHaBridgeWorker } from "./worker-main-
|
|
3
|
-
import "home-assistant-js-websocket";
|
|
1
|
+
import { A as buildDeviceView, B as registerEntity, C as unloadDemoData, D as isEnergyEntity, E as demoEnergyPreferences, F as getAllEntityViews, G as setState, H as setResubscribeHandler, I as getEntityView, K as state, L as getEntityViews, M as getAreaViews, N as buildEntityView, O as synthesizeEnergyHistory, P as entityViewEquals, R as extractDomain, S as stopDemoEnergyTicker, T as demoAssetUrl, U as privilegedConn, V as setManagerConnection, W as setPrivilegedConn, _ as updateEntity, a as fetchForecastData, b as loadDemoData, c as normalizeStatisticTime, d as batchServiceCalls, f as callService, g as turnOn, h as turnOff, i as fetchForecast, j as getAreaView, k as buildAreaView, l as numericSensorHistory, m as toggle, o as fetchForecasts, p as sendCommand, s as fetchStatisticsDuringPeriod, t as forceResubscribeCalendars, u as batchEntityUpdates, v as applyDemoServiceCall, w as createDemoFixtures, x as startDemoEnergyTicker, y as isDemoMode, z as forceResubscribe } from "./track-IkwP6XmO.js";
|
|
2
|
+
import { t as runHaBridgeWorker } from "./worker-main-B6eeHPDQ.js";
|
|
4
3
|
import { produce } from "solid-js/store";
|
|
5
4
|
//#region src/core/reducers.ts
|
|
6
5
|
/**
|
|
@@ -136,640 +135,370 @@ function updateStatisticsMetadata(metadata) {
|
|
|
136
135
|
}));
|
|
137
136
|
}
|
|
138
137
|
//#endregion
|
|
139
|
-
//#region src/
|
|
138
|
+
//#region src/connection/manager.ts
|
|
140
139
|
/**
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
* Constants and utilities for history fetching and processing.
|
|
144
|
-
* Based on Home Assistant frontend implementation.
|
|
145
|
-
*
|
|
146
|
-
* @packageDocumentation
|
|
140
|
+
* Disconnect from Home Assistant
|
|
147
141
|
*/
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
"climate",
|
|
155
|
-
"humidifier",
|
|
156
|
-
"input_datetime",
|
|
157
|
-
"water_heater",
|
|
158
|
-
"person",
|
|
159
|
-
"device_tracker"
|
|
160
|
-
];
|
|
161
|
-
const LINE_ATTRIBUTES_TO_KEEP = [
|
|
162
|
-
"temperature",
|
|
163
|
-
"current_temperature",
|
|
164
|
-
"target_temp_low",
|
|
165
|
-
"target_temp_high",
|
|
166
|
-
"hvac_action",
|
|
167
|
-
"humidity",
|
|
168
|
-
"mode",
|
|
169
|
-
"action",
|
|
170
|
-
"current_humidity"
|
|
171
|
-
];
|
|
142
|
+
function disconnect() {
|
|
143
|
+
setState(produce((s) => {
|
|
144
|
+
setPrivilegedConn(null);
|
|
145
|
+
s.connectionState = "disconnected";
|
|
146
|
+
}));
|
|
147
|
+
}
|
|
172
148
|
/**
|
|
173
|
-
* Check if
|
|
149
|
+
* Check if currently connected
|
|
174
150
|
*/
|
|
175
|
-
function
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
151
|
+
function isConnected() {
|
|
152
|
+
return state.connectionState === "connected";
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Get the connection's connected flag, for a connection indicator in the UI.
|
|
156
|
+
*/
|
|
157
|
+
function getConnectionState() {
|
|
158
|
+
return state.connectionState === "connected";
|
|
159
|
+
}
|
|
160
|
+
async function loadInitialData(conn) {
|
|
161
|
+
try {
|
|
162
|
+
const [states, entityRegistry, deviceRegistry, areaRegistry, floorRegistry, labelRegistry, config] = await Promise.all([
|
|
163
|
+
conn.sendMessagePromise({ type: "get_states" }),
|
|
164
|
+
conn.sendMessagePromise({ type: "config/entity_registry/list" }),
|
|
165
|
+
conn.sendMessagePromise({ type: "config/device_registry/list" }),
|
|
166
|
+
conn.sendMessagePromise({ type: "config/area_registry/list" }),
|
|
167
|
+
conn.sendMessagePromise({ type: "config/floor_registry/list" }),
|
|
168
|
+
conn.sendMessagePromise({ type: "config/label_registry/list" }),
|
|
169
|
+
conn.sendMessagePromise({ type: "get_config" })
|
|
170
|
+
]);
|
|
171
|
+
bulkUpdateEntities(states);
|
|
172
|
+
bulkUpdateEntityRegistry(entityRegistry);
|
|
173
|
+
setState("config", config);
|
|
174
|
+
setState(produce((s) => {
|
|
175
|
+
for (const device of deviceRegistry) s.devices[device.id] = device;
|
|
176
|
+
for (const areaApi of areaRegistry) {
|
|
177
|
+
const area = {
|
|
178
|
+
id: (areaApi.area_id || areaApi.id) ?? "",
|
|
179
|
+
name: areaApi.name,
|
|
180
|
+
normalized_name: areaApi.normalized_name || areaApi.name.toLowerCase().replace(/\s+/g, "_"),
|
|
181
|
+
aliases: Array.isArray(areaApi.aliases) ? areaApi.aliases : [],
|
|
182
|
+
floor_id: areaApi.floor_id ?? null,
|
|
183
|
+
humidity_entity_id: areaApi.humidity_entity_id ?? null,
|
|
184
|
+
icon: areaApi.icon ?? null,
|
|
185
|
+
labels: Array.isArray(areaApi.labels) ? areaApi.labels : [],
|
|
186
|
+
picture: areaApi.picture ?? null,
|
|
187
|
+
temperature_entity_id: areaApi.temperature_entity_id ?? null,
|
|
188
|
+
created_at: typeof areaApi.created_at === "number" ? (/* @__PURE__ */ new Date(areaApi.created_at * 1e3)).toISOString() : areaApi.created_at,
|
|
189
|
+
modified_at: typeof areaApi.modified_at === "number" ? (/* @__PURE__ */ new Date(areaApi.modified_at * 1e3)).toISOString() : areaApi.modified_at
|
|
190
|
+
};
|
|
191
|
+
s.areas[area.id] = area;
|
|
192
|
+
}
|
|
193
|
+
for (const floor of floorRegistry) s.floors[floor.floor_id] = floor;
|
|
194
|
+
for (const label of labelRegistry) s.labels[label.label_id] = label;
|
|
195
|
+
}));
|
|
196
|
+
} catch (error) {
|
|
197
|
+
console.error("Error loading initial data:", error);
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
179
200
|
}
|
|
180
201
|
//#endregion
|
|
181
|
-
//#region src/
|
|
202
|
+
//#region src/query/projections.ts
|
|
182
203
|
/**
|
|
183
|
-
*
|
|
204
|
+
* Project entities to IDs only
|
|
184
205
|
*
|
|
185
|
-
* @
|
|
206
|
+
* @param entities - Array of entity views
|
|
207
|
+
* @returns Array of entity IDs
|
|
186
208
|
*/
|
|
209
|
+
function projectToIds(entities) {
|
|
210
|
+
return entities.map((e) => e.id);
|
|
211
|
+
}
|
|
187
212
|
/**
|
|
188
|
-
*
|
|
213
|
+
* Pick specific fields from entities
|
|
214
|
+
*
|
|
215
|
+
* @param entities - Array of entity views
|
|
216
|
+
* @param keys - Array of field names to include
|
|
217
|
+
* @returns Array of objects with only specified fields
|
|
189
218
|
*/
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
if (isDemoMode()) {
|
|
193
|
-
const endMs = (endTime ?? /* @__PURE__ */ new Date()).getTime();
|
|
219
|
+
function projectPick(entities, keys) {
|
|
220
|
+
return entities.map((entity) => {
|
|
194
221
|
const result = {};
|
|
195
|
-
for (const
|
|
196
|
-
const points = isEnergyEntity(id) ? synthesizeEnergyHistory(id, startTime.getTime(), endMs) : numericSensorHistory(id, startTime.getTime(), endMs);
|
|
197
|
-
if (!points) continue;
|
|
198
|
-
result[id] = points.map((p) => ({
|
|
199
|
-
s: p.s,
|
|
200
|
-
a: {},
|
|
201
|
-
lu: p.lu
|
|
202
|
-
}));
|
|
203
|
-
}
|
|
222
|
+
for (const key of keys) result[key] = entity[key];
|
|
204
223
|
return result;
|
|
205
|
-
}
|
|
206
|
-
const startTimeStr = startTime.toISOString();
|
|
207
|
-
const endTimeStr = endTime?.toISOString();
|
|
208
|
-
const params = {
|
|
209
|
-
type: "history/history_during_period",
|
|
210
|
-
start_time: startTimeStr,
|
|
211
|
-
minimal_response: minimalResponse,
|
|
212
|
-
no_attributes: noAttributesOverride ?? (entityIds.length === 0 ? false : !entityIds.some((entityId) => entityIdHistoryNeedsAttributes(entityId))),
|
|
213
|
-
include_start_time_state: includeStartTimeState,
|
|
214
|
-
significant_changes_only: significantChangesOnly
|
|
215
|
-
};
|
|
216
|
-
if (endTimeStr) params.end_time = endTimeStr;
|
|
217
|
-
if (entityIds.length !== 0) params.entity_ids = entityIds;
|
|
218
|
-
return await sendCommand(params) ?? {};
|
|
224
|
+
});
|
|
219
225
|
}
|
|
220
226
|
/**
|
|
221
|
-
*
|
|
227
|
+
* Pluck a single field from entities
|
|
228
|
+
*
|
|
229
|
+
* Supports dot-notation for nested fields (e.g., "attributes.brightness")
|
|
230
|
+
*
|
|
231
|
+
* @param entities - Array of entity views
|
|
232
|
+
* @param key - Field name or dot-path to extract
|
|
233
|
+
* @returns Array of field values
|
|
222
234
|
*/
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
try {
|
|
226
|
-
const entityHistory = (await fetchHistory({
|
|
227
|
-
startTime,
|
|
228
|
-
endTime,
|
|
229
|
-
entityIds: [entityId],
|
|
230
|
-
includeStartTimeState,
|
|
231
|
-
significantChangesOnly,
|
|
232
|
-
minimalResponse,
|
|
233
|
-
noAttributes
|
|
234
|
-
}))[entityId] ?? [];
|
|
235
|
-
return {
|
|
236
|
-
entityId,
|
|
237
|
-
timeline: entityHistory.map((s) => ({
|
|
238
|
-
timestamp: s.lu,
|
|
239
|
-
state: s.s,
|
|
240
|
-
attributes: s.a,
|
|
241
|
-
lastChanged: s.lc,
|
|
242
|
-
lastUpdated: s.lu
|
|
243
|
-
})),
|
|
244
|
-
entityHistory,
|
|
245
|
-
loading: false,
|
|
246
|
-
error: null,
|
|
247
|
-
lastFetched: Date.now()
|
|
248
|
-
};
|
|
249
|
-
} catch (error) {
|
|
250
|
-
return {
|
|
251
|
-
entityId,
|
|
252
|
-
timeline: [],
|
|
253
|
-
entityHistory: [],
|
|
254
|
-
loading: false,
|
|
255
|
-
error: error instanceof Error ? error : new Error(String(error)),
|
|
256
|
-
lastFetched: null
|
|
257
|
-
};
|
|
258
|
-
}
|
|
235
|
+
function projectPluck(entities, key) {
|
|
236
|
+
return entities.map((entity) => getNestedValue(entity, key));
|
|
259
237
|
}
|
|
260
238
|
/**
|
|
261
|
-
*
|
|
239
|
+
* Map entities using a custom function
|
|
240
|
+
*
|
|
241
|
+
* @param entities - Array of entity views
|
|
242
|
+
* @param mapper - Function to transform each entity
|
|
243
|
+
* @returns Array of mapped values
|
|
262
244
|
*/
|
|
263
|
-
function
|
|
264
|
-
return
|
|
265
|
-
timestamp: s.lu,
|
|
266
|
-
state: s.s,
|
|
267
|
-
attributes: s.a,
|
|
268
|
-
lastChanged: s.lc,
|
|
269
|
-
lastUpdated: s.lu
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
//#endregion
|
|
273
|
-
//#region src/history/query.ts
|
|
274
|
-
/** Hard cap on retained points per entity timeline. */
|
|
275
|
-
const MAX_HISTORY_POINTS = 5760;
|
|
276
|
-
/** Live tracker count per entity. Ref-counted because a timeline is shared: two
|
|
277
|
-
* widgets on the same entity must not let the first unmount delete the store
|
|
278
|
-
* data the second is still rendering (appendHistoryPoint would then silently
|
|
279
|
-
* drop every update and the survivor's chart would freeze). */
|
|
280
|
-
const trackedEntities = /* @__PURE__ */ new Map();
|
|
281
|
-
/** Check if an entity has active history tracking. */
|
|
282
|
-
function isHistoryTracked(entityId) {
|
|
283
|
-
return trackedEntities.has(entityId);
|
|
284
|
-
}
|
|
285
|
-
/** Start tracking history for an entity. Fetches initial backfill. */
|
|
286
|
-
async function trackEntityHistory(entityId, options) {
|
|
287
|
-
trackedEntities.set(entityId, (trackedEntities.get(entityId) ?? 0) + 1);
|
|
288
|
-
const historyData = await fetchEntityHistory(entityId, options);
|
|
289
|
-
setState(produce((s) => {
|
|
290
|
-
s.history[entityId] = historyData;
|
|
291
|
-
}));
|
|
292
|
-
return historyData;
|
|
293
|
-
}
|
|
294
|
-
/** Release one tracker. The entity's data is cleared only when the last one goes. */
|
|
295
|
-
function untrackEntityHistory(entityId) {
|
|
296
|
-
const remaining = (trackedEntities.get(entityId) ?? 0) - 1;
|
|
297
|
-
if (remaining > 0) {
|
|
298
|
-
trackedEntities.set(entityId, remaining);
|
|
299
|
-
return;
|
|
300
|
-
}
|
|
301
|
-
trackedEntities.delete(entityId);
|
|
302
|
-
setState(produce((s) => {
|
|
303
|
-
delete s.history[entityId];
|
|
304
|
-
}));
|
|
245
|
+
function projectMap(entities, mapper) {
|
|
246
|
+
return entities.map(mapper);
|
|
305
247
|
}
|
|
306
248
|
/**
|
|
307
|
-
*
|
|
308
|
-
*
|
|
249
|
+
* Get nested value from object using dot-notation
|
|
250
|
+
*
|
|
251
|
+
* @param obj - Object to extract value from
|
|
252
|
+
* @param path - Dot-notation path (e.g., "attributes.brightness")
|
|
253
|
+
* @returns Value at path or undefined
|
|
254
|
+
*
|
|
255
|
+
* @example
|
|
256
|
+
* ```typescript
|
|
257
|
+
* const entity = { attributes: { brightness: 255 } };
|
|
258
|
+
* getNestedValue(entity, "attributes.brightness"); // 255
|
|
259
|
+
* ```
|
|
309
260
|
*/
|
|
310
|
-
function
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
261
|
+
function getNestedValue(obj, path) {
|
|
262
|
+
const parts = path.split(".");
|
|
263
|
+
let current = obj;
|
|
264
|
+
for (const part of parts) {
|
|
265
|
+
if (current === null || current === void 0) return;
|
|
266
|
+
current = current[part];
|
|
267
|
+
}
|
|
268
|
+
return current;
|
|
269
|
+
}
|
|
270
|
+
//#endregion
|
|
271
|
+
//#region src/query/area-builder.ts
|
|
272
|
+
var AreaQueryBuilderImpl = class AreaQueryBuilderImpl {
|
|
273
|
+
queryState;
|
|
274
|
+
constructor(initialState) {
|
|
275
|
+
this.queryState = initialState ?? {
|
|
276
|
+
filters: [],
|
|
277
|
+
sorts: []
|
|
319
278
|
};
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
279
|
+
}
|
|
280
|
+
byFloor(floorId) {
|
|
281
|
+
return this.clone({ filters: [...this.queryState.filters, {
|
|
282
|
+
type: "floor",
|
|
283
|
+
value: floorId
|
|
284
|
+
}] });
|
|
285
|
+
}
|
|
286
|
+
byLabel(labelId) {
|
|
287
|
+
return this.clone({ filters: [...this.queryState.filters, {
|
|
288
|
+
type: "label",
|
|
289
|
+
value: labelId
|
|
290
|
+
}] });
|
|
291
|
+
}
|
|
292
|
+
where(predicate) {
|
|
293
|
+
return this.clone({ filters: [...this.queryState.filters, {
|
|
294
|
+
type: "predicate",
|
|
295
|
+
value: predicate
|
|
296
|
+
}] });
|
|
297
|
+
}
|
|
298
|
+
orderBy(key, direction = "asc") {
|
|
299
|
+
return this.clone({ sorts: [...this.queryState.sorts, {
|
|
300
|
+
key,
|
|
301
|
+
direction
|
|
302
|
+
}] });
|
|
303
|
+
}
|
|
304
|
+
get() {
|
|
305
|
+
return this.execute();
|
|
306
|
+
}
|
|
307
|
+
first() {
|
|
308
|
+
return this.execute()[0];
|
|
309
|
+
}
|
|
310
|
+
subscribe(callback) {
|
|
311
|
+
callback(this.get());
|
|
312
|
+
return () => {};
|
|
313
|
+
}
|
|
314
|
+
clone(updates) {
|
|
315
|
+
return new AreaQueryBuilderImpl({
|
|
316
|
+
...this.queryState,
|
|
317
|
+
...updates
|
|
327
318
|
});
|
|
328
|
-
}
|
|
319
|
+
}
|
|
320
|
+
execute() {
|
|
321
|
+
let areas = getAreaViews();
|
|
322
|
+
for (const filter of this.queryState.filters) if (filter.type === "floor") areas = areas.filter((area) => area.floorId === filter.value);
|
|
323
|
+
else if (filter.type === "label") areas = areas.filter((area) => area.labels.includes(filter.value));
|
|
324
|
+
else if (filter.type === "predicate") areas = areas.filter(filter.value);
|
|
325
|
+
if (this.queryState.sorts.length > 0) areas = this.sortAreas(areas);
|
|
326
|
+
return areas;
|
|
327
|
+
}
|
|
328
|
+
sortAreas(areas) {
|
|
329
|
+
return [...areas].sort((a, b) => {
|
|
330
|
+
for (const sort of this.queryState.sorts) {
|
|
331
|
+
const aValue = getNestedValue(a, sort.key);
|
|
332
|
+
const bValue = getNestedValue(b, sort.key);
|
|
333
|
+
let comparison = 0;
|
|
334
|
+
if (aValue < bValue) comparison = -1;
|
|
335
|
+
else if (aValue > bValue) comparison = 1;
|
|
336
|
+
if (comparison !== 0) return sort.direction === "asc" ? comparison : -comparison;
|
|
337
|
+
}
|
|
338
|
+
return 0;
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
/**
|
|
343
|
+
* Create a query builder for areas
|
|
344
|
+
*/
|
|
345
|
+
function areas() {
|
|
346
|
+
return new AreaQueryBuilderImpl();
|
|
329
347
|
}
|
|
330
348
|
/**
|
|
331
|
-
*
|
|
332
|
-
* Called by the rAF-batched subscription flush.
|
|
349
|
+
* Create a query for a single area
|
|
333
350
|
*/
|
|
334
|
-
function
|
|
335
|
-
|
|
336
|
-
setState(produce((s) => {
|
|
337
|
-
const touched = /* @__PURE__ */ new Set();
|
|
338
|
-
for (const { entityId, stateValue, attributes, lastUpdated, lastChanged } of points) {
|
|
339
|
-
const history = s.history[entityId];
|
|
340
|
-
if (!history) continue;
|
|
341
|
-
history.entityHistory.push({
|
|
342
|
-
s: stateValue,
|
|
343
|
-
a: attributes,
|
|
344
|
-
lu: lastUpdated,
|
|
345
|
-
lc: lastChanged
|
|
346
|
-
});
|
|
347
|
-
history.timeline.push({
|
|
348
|
-
timestamp: lastUpdated,
|
|
349
|
-
state: stateValue,
|
|
350
|
-
attributes,
|
|
351
|
-
lastChanged,
|
|
352
|
-
lastUpdated
|
|
353
|
-
});
|
|
354
|
-
touched.add(entityId);
|
|
355
|
-
}
|
|
356
|
-
for (const entityId of touched) {
|
|
357
|
-
const history = s.history[entityId];
|
|
358
|
-
if (!history) continue;
|
|
359
|
-
if (history.entityHistory.length > 5760) history.entityHistory.splice(0, history.entityHistory.length - MAX_HISTORY_POINTS);
|
|
360
|
-
if (history.timeline.length > 5760) history.timeline.splice(0, history.timeline.length - MAX_HISTORY_POINTS);
|
|
361
|
-
}
|
|
362
|
-
}));
|
|
351
|
+
function area(areaId) {
|
|
352
|
+
return getAreaView(areaId);
|
|
363
353
|
}
|
|
364
354
|
//#endregion
|
|
365
|
-
//#region src/
|
|
366
|
-
/**
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
355
|
+
//#region src/entities/index.ts
|
|
356
|
+
/**
|
|
357
|
+
* Entity Index Queries
|
|
358
|
+
*
|
|
359
|
+
* Provides utilities for querying entities by various criteria.
|
|
360
|
+
* In the SolidJS port, indices are NOT stored in state -- they are
|
|
361
|
+
* computed on the fly here (and will be derived reactively in Plan 03).
|
|
362
|
+
*
|
|
363
|
+
* @packageDocumentation
|
|
364
|
+
*/
|
|
365
|
+
/**
|
|
366
|
+
* Get all entity IDs
|
|
367
|
+
*/
|
|
368
|
+
function getAllEntityIds() {
|
|
369
|
+
return Object.keys(state.entities);
|
|
377
370
|
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
setState(produce((s) => {
|
|
384
|
-
for (const message of messages) {
|
|
385
|
-
if (message.a) for (const [entityId, compressedState] of Object.entries(message.a)) applyCompressedState(s, entityId, compressedState);
|
|
386
|
-
if (message.c) for (const [entityId, diff] of Object.entries(message.c)) applyStateDiff(s, entityId, diff);
|
|
387
|
-
if (message.r) for (const entityId of message.r) delete s.entities[entityId];
|
|
388
|
-
}
|
|
389
|
-
}));
|
|
390
|
-
const historyPoints = [];
|
|
391
|
-
for (const message of messages) {
|
|
392
|
-
if (message.a) for (const [entityId, compressedState] of Object.entries(message.a)) collectHistoryFromCompressed(historyPoints, entityId, compressedState);
|
|
393
|
-
if (message.c) {
|
|
394
|
-
for (const [entityId, diff] of Object.entries(message.c)) if (diff["+"]) collectHistoryFromDiff(historyPoints, entityId, diff["+"]);
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
if (historyPoints.length > 0) bulkAppendHistoryPoints(historyPoints);
|
|
371
|
+
/**
|
|
372
|
+
* Get entities by domain
|
|
373
|
+
*/
|
|
374
|
+
function getEntitiesByDomain(domain) {
|
|
375
|
+
return Object.keys(state.entities).filter((id) => extractDomain(id) === domain);
|
|
398
376
|
}
|
|
399
377
|
/**
|
|
400
|
-
*
|
|
401
|
-
*
|
|
378
|
+
* Get entities via devices in area
|
|
379
|
+
*
|
|
380
|
+
* Only includes entities that inherit area from device (entity.area_id is null).
|
|
402
381
|
*/
|
|
403
|
-
|
|
404
|
-
const
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
382
|
+
function getEntitiesViaDevices(areaId) {
|
|
383
|
+
const devicesInArea = Object.values(state.devices).filter((device) => device.area_id === areaId);
|
|
384
|
+
const entityIds = [];
|
|
385
|
+
for (const device of devicesInArea) {
|
|
386
|
+
const deviceEntities = getEntitiesByDevice(device.id);
|
|
387
|
+
for (const entityId of deviceEntities) if (!state.entityRegistry[entityId]?.area_id) entityIds.push(entityId);
|
|
388
|
+
}
|
|
389
|
+
return entityIds;
|
|
409
390
|
}
|
|
410
391
|
/**
|
|
411
|
-
*
|
|
392
|
+
* Get entities by area
|
|
393
|
+
*
|
|
394
|
+
* Returns entities with direct area_id assignments and entities that inherit their area from devices.
|
|
412
395
|
*/
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
handleRegistryUpdate(event);
|
|
419
|
-
}, "entity_registry_updated");
|
|
420
|
-
registrySubscriptions.push(() => registryUpdatedSub());
|
|
421
|
-
const deviceRegistrySub = await conn.subscribeEvents((event) => {
|
|
422
|
-
handleDeviceRegistryUpdate(event);
|
|
423
|
-
}, "device_registry_updated");
|
|
424
|
-
registrySubscriptions.push(() => deviceRegistrySub());
|
|
425
|
-
const areaRegistrySub = await conn.subscribeEvents((event) => {
|
|
426
|
-
handleAreaRegistryUpdate(event);
|
|
427
|
-
}, "area_registry_updated");
|
|
428
|
-
registrySubscriptions.push(() => areaRegistrySub());
|
|
429
|
-
const floorRegistrySub = await conn.subscribeEvents((event) => {
|
|
430
|
-
handleFloorRegistryUpdate(event);
|
|
431
|
-
}, "floor_registry_updated");
|
|
432
|
-
registrySubscriptions.push(() => floorRegistrySub());
|
|
433
|
-
const labelRegistrySub = await conn.subscribeEvents((event) => {
|
|
434
|
-
handleLabelRegistryUpdate(event);
|
|
435
|
-
}, "label_registry_updated");
|
|
436
|
-
registrySubscriptions.push(() => labelRegistrySub());
|
|
437
|
-
const statisticsSub = await conn.subscribeEvents((event) => {
|
|
438
|
-
handleStatisticsUpdate(event);
|
|
439
|
-
}, "recorder_5min_statistics_generated");
|
|
440
|
-
registrySubscriptions.push(() => statisticsSub());
|
|
441
|
-
const coreConfigSub = await conn.subscribeEvents(() => {
|
|
442
|
-
handleCoreConfigUpdate();
|
|
443
|
-
}, "core_config_updated");
|
|
444
|
-
registrySubscriptions.push(() => coreConfigSub());
|
|
396
|
+
function getEntitiesByArea(areaId) {
|
|
397
|
+
const directEntityIds = [];
|
|
398
|
+
for (const [entityId, entry] of Object.entries(state.entityRegistry)) if (entry.area_id === areaId) directEntityIds.push(entityId);
|
|
399
|
+
const deviceEntityIds = getEntitiesViaDevices(areaId);
|
|
400
|
+
return Array.from(/* @__PURE__ */ new Set([...directEntityIds, ...deviceEntityIds]));
|
|
445
401
|
}
|
|
446
402
|
/**
|
|
447
|
-
*
|
|
403
|
+
* Get entities by device
|
|
448
404
|
*/
|
|
449
|
-
|
|
450
|
-
const
|
|
451
|
-
for (const
|
|
452
|
-
|
|
405
|
+
function getEntitiesByDevice(deviceId) {
|
|
406
|
+
const entityIds = [];
|
|
407
|
+
for (const [entityId, entry] of Object.entries(state.entityRegistry)) if (entry.device_id === deviceId) entityIds.push(entityId);
|
|
408
|
+
return entityIds;
|
|
453
409
|
}
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
}
|
|
464
|
-
async function handleRegistryUpdate(event) {
|
|
465
|
-
const { action, entity_id } = event.data;
|
|
466
|
-
if (action === "create" || action === "update") {
|
|
467
|
-
const conn = privilegedConn();
|
|
468
|
-
if (!conn) return;
|
|
469
|
-
try {
|
|
470
|
-
const entry = await conn.sendMessagePromise({
|
|
471
|
-
type: "config/entity_registry/get",
|
|
472
|
-
entity_id
|
|
473
|
-
});
|
|
474
|
-
if (entry) updateEntityRegistry(entry);
|
|
475
|
-
} catch (error) {
|
|
476
|
-
console.error("Error fetching registry entry:", error);
|
|
477
|
-
}
|
|
478
|
-
} else if (action === "remove") removeEntityRegistry(entity_id);
|
|
479
|
-
}
|
|
480
|
-
async function handleDeviceRegistryUpdate(event) {
|
|
481
|
-
const { action, device_id } = event.data;
|
|
482
|
-
if (action === "create" || action === "update") {
|
|
483
|
-
const conn = privilegedConn();
|
|
484
|
-
if (!conn) return;
|
|
485
|
-
try {
|
|
486
|
-
const device = (await conn.sendMessagePromise({ type: "config/device_registry/list" })).find((d) => d.id === device_id);
|
|
487
|
-
if (device) updateDevice(device);
|
|
488
|
-
} catch (error) {
|
|
489
|
-
console.error("Error fetching device:", error);
|
|
490
|
-
}
|
|
491
|
-
} else if (action === "remove") removeDevice(device_id);
|
|
492
|
-
}
|
|
493
|
-
async function handleAreaRegistryUpdate(event) {
|
|
494
|
-
const { action, area_id } = event.data;
|
|
495
|
-
if (action === "create" || action === "update") {
|
|
496
|
-
const conn = privilegedConn();
|
|
497
|
-
if (!conn) return;
|
|
498
|
-
try {
|
|
499
|
-
const area = (await conn.sendMessagePromise({ type: "config/area_registry/list" })).find((a) => a.id === area_id);
|
|
500
|
-
if (area) updateArea(area);
|
|
501
|
-
} catch (error) {
|
|
502
|
-
console.error("Error fetching area:", error);
|
|
503
|
-
}
|
|
504
|
-
} else if (action === "remove") removeArea(area_id);
|
|
505
|
-
}
|
|
506
|
-
async function handleFloorRegistryUpdate(event) {
|
|
507
|
-
const { action, floor_id } = event.data;
|
|
508
|
-
if (action === "create" || action === "update") {
|
|
509
|
-
const conn = privilegedConn();
|
|
510
|
-
if (!conn) return;
|
|
511
|
-
try {
|
|
512
|
-
const floor = (await conn.sendMessagePromise({ type: "config/floor_registry/list" })).find((f) => f.floor_id === floor_id);
|
|
513
|
-
if (floor) updateFloor(floor);
|
|
514
|
-
} catch (error) {
|
|
515
|
-
console.error("Error fetching floor:", error);
|
|
516
|
-
}
|
|
517
|
-
} else if (action === "remove") removeFloor(floor_id);
|
|
518
|
-
}
|
|
519
|
-
async function handleLabelRegistryUpdate(event) {
|
|
520
|
-
const { action, label_id } = event.data;
|
|
521
|
-
if (action === "create" || action === "update") {
|
|
522
|
-
const conn = privilegedConn();
|
|
523
|
-
if (!conn) return;
|
|
524
|
-
try {
|
|
525
|
-
const label = (await conn.sendMessagePromise({ type: "config/label_registry/list" })).find((l) => l.label_id === label_id);
|
|
526
|
-
if (label) updateLabel(label);
|
|
527
|
-
} catch (error) {
|
|
528
|
-
console.error("Error fetching label:", error);
|
|
529
|
-
}
|
|
530
|
-
} else if (action === "remove") removeLabel(label_id);
|
|
531
|
-
}
|
|
532
|
-
async function handleStatisticsUpdate(event) {
|
|
533
|
-
const { statistic_ids } = event.data;
|
|
534
|
-
if (!statistic_ids || statistic_ids.length === 0) return;
|
|
535
|
-
const conn = privilegedConn();
|
|
536
|
-
if (!conn) return;
|
|
537
|
-
try {
|
|
538
|
-
const metadata = await conn.sendMessagePromise({
|
|
539
|
-
type: "recorder/get_statistics_metadata",
|
|
540
|
-
statistic_ids
|
|
541
|
-
});
|
|
542
|
-
if (metadata && Array.isArray(metadata)) updateStatisticsMetadata(metadata);
|
|
543
|
-
} catch (error) {
|
|
544
|
-
console.error("Error fetching statistics metadata:", error);
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
function timestampToIso(timestamp) {
|
|
548
|
-
if (timestamp === void 0) return (/* @__PURE__ */ new Date()).toISOString();
|
|
549
|
-
if (typeof timestamp === "string") return timestamp;
|
|
550
|
-
return (/* @__PURE__ */ new Date(timestamp * 1e3)).toISOString();
|
|
551
|
-
}
|
|
552
|
-
function collectHistoryFromCompressed(points, entityId, compressed) {
|
|
553
|
-
if (!isHistoryTracked(entityId)) return;
|
|
554
|
-
const stateVal = compressed.s ?? compressed.state ?? "unknown";
|
|
555
|
-
const attributes = compressed.a ?? compressed.attributes ?? {};
|
|
556
|
-
const lu = compressed.lu ?? (compressed.last_updated ? new Date(compressed.last_updated).getTime() / 1e3 : Date.now() / 1e3);
|
|
557
|
-
const lc = compressed.lc ?? (compressed.last_changed ? new Date(compressed.last_changed).getTime() / 1e3 : void 0);
|
|
558
|
-
points.push({
|
|
559
|
-
entityId,
|
|
560
|
-
stateValue: stateVal,
|
|
561
|
-
attributes,
|
|
562
|
-
lastUpdated: lu,
|
|
563
|
-
lastChanged: lc
|
|
564
|
-
});
|
|
565
|
-
}
|
|
566
|
-
function collectHistoryFromDiff(points, entityId, additions) {
|
|
567
|
-
if (!isHistoryTracked(entityId)) return;
|
|
568
|
-
const stateVal = additions.s ?? additions.state;
|
|
569
|
-
if (stateVal === void 0) return;
|
|
570
|
-
const lu = additions.lu ?? Date.now() / 1e3;
|
|
571
|
-
const lc = additions.lc;
|
|
572
|
-
const attributes = additions.a ?? additions.attributes ?? {};
|
|
573
|
-
points.push({
|
|
574
|
-
entityId,
|
|
575
|
-
stateValue: stateVal,
|
|
576
|
-
attributes,
|
|
577
|
-
lastUpdated: lu,
|
|
578
|
-
lastChanged: lc
|
|
579
|
-
});
|
|
580
|
-
}
|
|
581
|
-
function shallowEqualAttributes(existing, incoming) {
|
|
582
|
-
const incomingKeys = Object.keys(incoming);
|
|
583
|
-
for (const key of incomingKeys) if (existing[key] !== incoming[key]) return false;
|
|
584
|
-
return true;
|
|
585
|
-
}
|
|
586
|
-
function applyCompressedState(s, entityId, compressed) {
|
|
587
|
-
const stateVal = compressed.s ?? compressed.state ?? "unknown";
|
|
588
|
-
const attributes = compressed.a ?? compressed.attributes ?? {};
|
|
589
|
-
const context = compressed.c ?? compressed.context ?? {
|
|
590
|
-
id: "",
|
|
591
|
-
parent_id: null,
|
|
592
|
-
user_id: null
|
|
593
|
-
};
|
|
594
|
-
const lastChanged = timestampToIso(compressed.lc ?? compressed.last_changed);
|
|
595
|
-
const lastUpdated = timestampToIso(compressed.lu ?? compressed.last_updated);
|
|
596
|
-
const existing = s.entities[entityId];
|
|
597
|
-
if (existing) {
|
|
598
|
-
const stateChanged = existing.state !== stateVal;
|
|
599
|
-
const changedAt = existing.last_changed !== lastChanged;
|
|
600
|
-
if (stateChanged) existing.state = stateVal;
|
|
601
|
-
if (changedAt) existing.last_changed = lastChanged;
|
|
602
|
-
if (stateChanged || changedAt) existing.last_updated = lastUpdated;
|
|
603
|
-
if (!shallowEqualAttributes(existing.attributes, attributes)) Object.assign(existing.attributes, attributes);
|
|
604
|
-
if (existing.context.id !== context.id) existing.context = context;
|
|
605
|
-
} else s.entities[entityId] = {
|
|
606
|
-
entity_id: entityId,
|
|
607
|
-
state: stateVal,
|
|
608
|
-
attributes,
|
|
609
|
-
last_changed: lastChanged,
|
|
610
|
-
last_updated: lastUpdated,
|
|
611
|
-
context
|
|
612
|
-
};
|
|
613
|
-
}
|
|
614
|
-
function applyStateDiff(s, entityId, diff) {
|
|
615
|
-
const existing = s.entities[entityId];
|
|
616
|
-
if (!existing) return;
|
|
617
|
-
const additions = diff["+"];
|
|
618
|
-
if (additions) {
|
|
619
|
-
let stateChanged = false;
|
|
620
|
-
if (additions.s !== void 0 && existing.state !== additions.s) {
|
|
621
|
-
existing.state = additions.s;
|
|
622
|
-
stateChanged = true;
|
|
623
|
-
}
|
|
624
|
-
if (additions.a) {
|
|
625
|
-
for (const [key, value] of Object.entries(additions.a)) if (existing.attributes[key] !== value) {
|
|
626
|
-
existing.attributes[key] = value;
|
|
627
|
-
stateChanged = true;
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
if (additions.lc !== void 0) {
|
|
631
|
-
const lcIso = timestampToIso(additions.lc);
|
|
632
|
-
if (existing.last_changed !== lcIso) {
|
|
633
|
-
existing.last_changed = lcIso;
|
|
634
|
-
stateChanged = true;
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
if (additions.lu !== void 0 && stateChanged) existing.last_updated = timestampToIso(additions.lu);
|
|
638
|
-
if (additions.c && existing.context.id !== additions.c.id) existing.context = additions.c;
|
|
639
|
-
}
|
|
640
|
-
const removals = diff["-"];
|
|
641
|
-
if (removals?.a) for (const key of removals.a) delete existing.attributes[key];
|
|
642
|
-
}
|
|
643
|
-
//#endregion
|
|
644
|
-
//#region src/connection/manager.ts
|
|
645
|
-
let activeConn = null;
|
|
646
|
-
let heartbeatInterval = null;
|
|
647
|
-
let suspendTimeout = null;
|
|
648
|
-
let visiblePromiseResolve = null;
|
|
649
|
-
let visibilityHandler = null;
|
|
650
|
-
let pageshowHandler = null;
|
|
651
|
-
function clearSuspendTimeout() {
|
|
652
|
-
if (suspendTimeout !== null) {
|
|
653
|
-
clearTimeout(suspendTimeout);
|
|
654
|
-
suspendTimeout = null;
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
function resolveVisiblePromise() {
|
|
658
|
-
if (visiblePromiseResolve) {
|
|
659
|
-
visiblePromiseResolve();
|
|
660
|
-
visiblePromiseResolve = null;
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
function stopHeartbeat() {
|
|
664
|
-
if (heartbeatInterval !== null) {
|
|
665
|
-
clearInterval(heartbeatInterval);
|
|
666
|
-
heartbeatInterval = null;
|
|
410
|
+
/**
|
|
411
|
+
* Get entities by floor
|
|
412
|
+
*/
|
|
413
|
+
function getEntitiesByFloor(floorId) {
|
|
414
|
+
const entityIds = [];
|
|
415
|
+
const areasOnFloor = Object.values(state.areas).filter((area) => area.floor_id === floorId);
|
|
416
|
+
for (const area of areasOnFloor) {
|
|
417
|
+
const areaEntities = getEntitiesByArea(area.id);
|
|
418
|
+
entityIds.push(...areaEntities);
|
|
667
419
|
}
|
|
668
|
-
|
|
669
|
-
function teardownLifecycleListeners() {
|
|
670
|
-
if (typeof document !== "undefined" && visibilityHandler) document.removeEventListener("visibilitychange", visibilityHandler);
|
|
671
|
-
if (typeof window !== "undefined" && pageshowHandler) window.removeEventListener("pageshow", pageshowHandler);
|
|
672
|
-
visibilityHandler = null;
|
|
673
|
-
pageshowHandler = null;
|
|
674
|
-
clearSuspendTimeout();
|
|
675
|
-
resolveVisiblePromise();
|
|
420
|
+
return entityIds;
|
|
676
421
|
}
|
|
677
422
|
/**
|
|
678
|
-
*
|
|
423
|
+
* Get entities by label
|
|
679
424
|
*/
|
|
680
|
-
function
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
activeConn = null;
|
|
685
|
-
setState(produce((s) => {
|
|
686
|
-
setPrivilegedConn(null);
|
|
687
|
-
s.connectionState = "disconnected";
|
|
688
|
-
}));
|
|
425
|
+
function getEntitiesByLabel(labelId) {
|
|
426
|
+
const entityIds = [];
|
|
427
|
+
for (const [entityId, entry] of Object.entries(state.entityRegistry)) if (entry.labels?.includes(labelId)) entityIds.push(entityId);
|
|
428
|
+
return entityIds;
|
|
689
429
|
}
|
|
430
|
+
//#endregion
|
|
431
|
+
//#region src/query/memoization.ts
|
|
690
432
|
/**
|
|
691
|
-
*
|
|
433
|
+
* Build a unique signature for a query
|
|
692
434
|
*/
|
|
693
|
-
function
|
|
694
|
-
|
|
435
|
+
function buildQuerySignature(query) {
|
|
436
|
+
const sig = {
|
|
437
|
+
index: query.indexFilters.map((f) => `${f.type}:${f.value}`).join(","),
|
|
438
|
+
predicates: query.predicateFilters.length,
|
|
439
|
+
sorts: query.sorts.map((s) => `${s.key}:${s.direction}`).join(","),
|
|
440
|
+
projection: query.projection ? JSON.stringify(query.projection) : null
|
|
441
|
+
};
|
|
442
|
+
return JSON.stringify(sig);
|
|
695
443
|
}
|
|
696
444
|
/**
|
|
697
|
-
*
|
|
698
|
-
*
|
|
699
|
-
* Exposed so apps can render a connection indicator in the UI. Distinct from
|
|
700
|
-
* `isConnected()` which reflects the manager's internal lifecycle state.
|
|
445
|
+
* Execute query (no caching -- SolidJS createMemo handles this in Plan 03)
|
|
701
446
|
*/
|
|
702
|
-
function
|
|
703
|
-
return
|
|
704
|
-
}
|
|
705
|
-
async function loadInitialData(conn) {
|
|
706
|
-
try {
|
|
707
|
-
const [states, entityRegistry, deviceRegistry, areaRegistry, floorRegistry, labelRegistry, config] = await Promise.all([
|
|
708
|
-
conn.sendMessagePromise({ type: "get_states" }),
|
|
709
|
-
conn.sendMessagePromise({ type: "config/entity_registry/list" }),
|
|
710
|
-
conn.sendMessagePromise({ type: "config/device_registry/list" }),
|
|
711
|
-
conn.sendMessagePromise({ type: "config/area_registry/list" }),
|
|
712
|
-
conn.sendMessagePromise({ type: "config/floor_registry/list" }),
|
|
713
|
-
conn.sendMessagePromise({ type: "config/label_registry/list" }),
|
|
714
|
-
conn.sendMessagePromise({ type: "get_config" })
|
|
715
|
-
]);
|
|
716
|
-
bulkUpdateEntities(states);
|
|
717
|
-
bulkUpdateEntityRegistry(entityRegistry);
|
|
718
|
-
setState("config", config);
|
|
719
|
-
setState(produce((s) => {
|
|
720
|
-
for (const device of deviceRegistry) s.devices[device.id] = device;
|
|
721
|
-
for (const areaApi of areaRegistry) {
|
|
722
|
-
const area = {
|
|
723
|
-
id: areaApi.area_id || areaApi.id,
|
|
724
|
-
name: areaApi.name,
|
|
725
|
-
normalized_name: areaApi.normalized_name || areaApi.name.toLowerCase().replace(/\s+/g, "_"),
|
|
726
|
-
aliases: Array.isArray(areaApi.aliases) ? areaApi.aliases : [],
|
|
727
|
-
floor_id: areaApi.floor_id ?? null,
|
|
728
|
-
humidity_entity_id: areaApi.humidity_entity_id ?? null,
|
|
729
|
-
icon: areaApi.icon ?? null,
|
|
730
|
-
labels: Array.isArray(areaApi.labels) ? areaApi.labels : [],
|
|
731
|
-
picture: areaApi.picture ?? null,
|
|
732
|
-
temperature_entity_id: areaApi.temperature_entity_id ?? null,
|
|
733
|
-
created_at: typeof areaApi.created_at === "number" ? (/* @__PURE__ */ new Date(areaApi.created_at * 1e3)).toISOString() : areaApi.created_at,
|
|
734
|
-
modified_at: typeof areaApi.modified_at === "number" ? (/* @__PURE__ */ new Date(areaApi.modified_at * 1e3)).toISOString() : areaApi.modified_at
|
|
735
|
-
};
|
|
736
|
-
s.areas[area.id] = area;
|
|
737
|
-
}
|
|
738
|
-
for (const floor of floorRegistry) s.floors[floor.floor_id] = floor;
|
|
739
|
-
for (const label of labelRegistry) s.labels[label.label_id] = label;
|
|
740
|
-
}));
|
|
741
|
-
} catch (error) {
|
|
742
|
-
console.error("Error loading initial data:", error);
|
|
743
|
-
throw error;
|
|
744
|
-
}
|
|
447
|
+
function memoizedExecute(_signature, compute) {
|
|
448
|
+
return compute();
|
|
745
449
|
}
|
|
746
450
|
//#endregion
|
|
747
|
-
//#region src/query/
|
|
748
|
-
var
|
|
451
|
+
//#region src/query/builder.ts
|
|
452
|
+
var EntitiesQueryBuilderImpl = class EntitiesQueryBuilderImpl {
|
|
749
453
|
queryState;
|
|
750
454
|
constructor(initialState) {
|
|
751
455
|
this.queryState = initialState ?? {
|
|
752
|
-
|
|
753
|
-
|
|
456
|
+
indexFilters: [],
|
|
457
|
+
predicateFilters: [],
|
|
458
|
+
sorts: [],
|
|
459
|
+
projection: void 0,
|
|
460
|
+
searchText: void 0,
|
|
461
|
+
take: void 0,
|
|
462
|
+
skip: void 0,
|
|
463
|
+
distinct: void 0
|
|
754
464
|
};
|
|
755
465
|
}
|
|
466
|
+
byArea(areaId) {
|
|
467
|
+
return this.clone({ indexFilters: [...this.queryState.indexFilters, {
|
|
468
|
+
type: "area",
|
|
469
|
+
value: areaId
|
|
470
|
+
}] });
|
|
471
|
+
}
|
|
472
|
+
byDomain(domain) {
|
|
473
|
+
return this.clone({ indexFilters: [...this.queryState.indexFilters, {
|
|
474
|
+
type: "domain",
|
|
475
|
+
value: domain
|
|
476
|
+
}] });
|
|
477
|
+
}
|
|
478
|
+
byDevice(deviceId) {
|
|
479
|
+
return this.clone({ indexFilters: [...this.queryState.indexFilters, {
|
|
480
|
+
type: "device",
|
|
481
|
+
value: deviceId
|
|
482
|
+
}] });
|
|
483
|
+
}
|
|
756
484
|
byFloor(floorId) {
|
|
757
|
-
return this.clone({
|
|
485
|
+
return this.clone({ indexFilters: [...this.queryState.indexFilters, {
|
|
758
486
|
type: "floor",
|
|
759
487
|
value: floorId
|
|
760
488
|
}] });
|
|
761
489
|
}
|
|
762
490
|
byLabel(labelId) {
|
|
763
|
-
return this.clone({
|
|
491
|
+
return this.clone({ indexFilters: [...this.queryState.indexFilters, {
|
|
764
492
|
type: "label",
|
|
765
493
|
value: labelId
|
|
766
494
|
}] });
|
|
767
495
|
}
|
|
768
496
|
where(predicate) {
|
|
769
|
-
return this.clone({
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
497
|
+
return this.clone({ predicateFilters: [...this.queryState.predicateFilters, predicate] });
|
|
498
|
+
}
|
|
499
|
+
search(searchText) {
|
|
500
|
+
const searchLower = searchText.toLowerCase();
|
|
501
|
+
return this.where((e) => e.id.toLowerCase().includes(searchLower) || e.name.toLowerCase().includes(searchLower) || e.friendlyName.toLowerCase().includes(searchLower));
|
|
773
502
|
}
|
|
774
503
|
orderBy(key, direction = "asc") {
|
|
775
504
|
return this.clone({ sorts: [...this.queryState.sorts, {
|
|
@@ -777,519 +506,559 @@ var AreaQueryBuilderImpl = class AreaQueryBuilderImpl {
|
|
|
777
506
|
direction
|
|
778
507
|
}] });
|
|
779
508
|
}
|
|
509
|
+
ids() {
|
|
510
|
+
return this.clone({ projection: { type: "ids" } });
|
|
511
|
+
}
|
|
512
|
+
pick(keys) {
|
|
513
|
+
return this.clone({ projection: {
|
|
514
|
+
type: "pick",
|
|
515
|
+
keys
|
|
516
|
+
} });
|
|
517
|
+
}
|
|
518
|
+
pluck(key) {
|
|
519
|
+
return this.clone({ projection: {
|
|
520
|
+
type: "pluck",
|
|
521
|
+
key
|
|
522
|
+
} });
|
|
523
|
+
}
|
|
524
|
+
map(mapper) {
|
|
525
|
+
return this.clone({ projection: {
|
|
526
|
+
type: "map",
|
|
527
|
+
mapper
|
|
528
|
+
} });
|
|
529
|
+
}
|
|
530
|
+
take(limit) {
|
|
531
|
+
return this.clone({ take: limit });
|
|
532
|
+
}
|
|
533
|
+
skip(count) {
|
|
534
|
+
return this.clone({ skip: count });
|
|
535
|
+
}
|
|
536
|
+
distinct(key) {
|
|
537
|
+
return this.clone({ distinct: key });
|
|
538
|
+
}
|
|
780
539
|
get() {
|
|
781
|
-
return this.execute();
|
|
540
|
+
return memoizedExecute(buildQuerySignature(this.queryState), () => this.execute());
|
|
782
541
|
}
|
|
783
542
|
first() {
|
|
784
|
-
return this.
|
|
543
|
+
return this.get()[0];
|
|
785
544
|
}
|
|
786
545
|
subscribe(callback) {
|
|
787
546
|
callback(this.get());
|
|
788
547
|
return () => {};
|
|
789
548
|
}
|
|
790
549
|
clone(updates) {
|
|
791
|
-
return new
|
|
550
|
+
return new EntitiesQueryBuilderImpl({
|
|
792
551
|
...this.queryState,
|
|
793
552
|
...updates
|
|
794
553
|
});
|
|
795
554
|
}
|
|
796
555
|
execute() {
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
if (this.queryState.
|
|
802
|
-
|
|
556
|
+
const entityIds = this.getEntityIdsFromIndices();
|
|
557
|
+
let entities = getEntityViews(entityIds);
|
|
558
|
+
for (const filter of this.queryState.predicateFilters) entities = entities.filter(filter);
|
|
559
|
+
if (this.queryState.sorts.length > 0) entities = this.sortEntities(entities);
|
|
560
|
+
if (this.queryState.distinct) entities = this.applyDistinct(entities);
|
|
561
|
+
if (this.queryState.skip !== void 0) entities = entities.slice(this.queryState.skip);
|
|
562
|
+
if (this.queryState.take !== void 0) entities = entities.slice(0, this.queryState.take);
|
|
563
|
+
if (this.queryState.projection) return this.applyProjection(entities);
|
|
564
|
+
return entities;
|
|
803
565
|
}
|
|
804
|
-
|
|
805
|
-
|
|
566
|
+
getEntityIdsFromIndices() {
|
|
567
|
+
if (this.queryState.indexFilters.length === 0) return getAllEntityIds();
|
|
568
|
+
const idSets = this.queryState.indexFilters.map((filter) => this.getIdsForFilter(filter));
|
|
569
|
+
return this.intersectArrays(idSets);
|
|
570
|
+
}
|
|
571
|
+
getIdsForFilter(filter) {
|
|
572
|
+
switch (filter.type) {
|
|
573
|
+
case "domain": return getEntitiesByDomain(filter.value);
|
|
574
|
+
case "area": return getEntitiesByArea(filter.value);
|
|
575
|
+
case "device": return getEntitiesByDevice(filter.value);
|
|
576
|
+
case "floor": return getEntitiesByFloor(filter.value);
|
|
577
|
+
case "label": return getEntitiesByLabel(filter.value);
|
|
578
|
+
default: return [];
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
intersectArrays(arrays) {
|
|
582
|
+
if (arrays.length === 0) return [];
|
|
583
|
+
if (arrays.length === 1) return arrays[0] ?? [];
|
|
584
|
+
let result = arrays[0] ?? [];
|
|
585
|
+
for (let i = 1; i < arrays.length; i++) {
|
|
586
|
+
const set = new Set(arrays[i]);
|
|
587
|
+
result = result.filter((item) => set.has(item));
|
|
588
|
+
}
|
|
589
|
+
return result;
|
|
590
|
+
}
|
|
591
|
+
sortEntities(entities) {
|
|
592
|
+
const sorted = [...entities];
|
|
593
|
+
sorted.sort((a, b) => {
|
|
806
594
|
for (const sort of this.queryState.sorts) {
|
|
807
|
-
const
|
|
808
|
-
const
|
|
809
|
-
|
|
810
|
-
if (aValue < bValue) comparison = -1;
|
|
811
|
-
else if (aValue > bValue) comparison = 1;
|
|
595
|
+
const aVal = getNestedValue(a, sort.key);
|
|
596
|
+
const bVal = getNestedValue(b, sort.key);
|
|
597
|
+
const comparison = this.compareValues(aVal, bVal);
|
|
812
598
|
if (comparison !== 0) return sort.direction === "asc" ? comparison : -comparison;
|
|
813
599
|
}
|
|
814
600
|
return 0;
|
|
815
601
|
});
|
|
602
|
+
return sorted;
|
|
603
|
+
}
|
|
604
|
+
compareValues(a, b) {
|
|
605
|
+
if (a === b) return 0;
|
|
606
|
+
if (a === null || a === void 0) return 1;
|
|
607
|
+
if (b === null || b === void 0) return -1;
|
|
608
|
+
if (typeof a === "string" && typeof b === "string") return a.localeCompare(b);
|
|
609
|
+
if (typeof a === "number" && typeof b === "number") return a - b;
|
|
610
|
+
return String(a).localeCompare(String(b));
|
|
611
|
+
}
|
|
612
|
+
applyProjection(entities) {
|
|
613
|
+
if (!this.queryState.projection) return entities;
|
|
614
|
+
switch (this.queryState.projection.type) {
|
|
615
|
+
case "ids": return projectToIds(entities);
|
|
616
|
+
case "pick": return projectPick(entities, this.queryState.projection.keys);
|
|
617
|
+
case "pluck": return projectPluck(entities, this.queryState.projection.key);
|
|
618
|
+
case "map": return projectMap(entities, this.queryState.projection.mapper);
|
|
619
|
+
default: return entities;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
applyDistinct(entities) {
|
|
623
|
+
if (!this.queryState.distinct) return entities;
|
|
624
|
+
const seen = /* @__PURE__ */ new Set();
|
|
625
|
+
const result = [];
|
|
626
|
+
for (const entity of entities) {
|
|
627
|
+
const value = getNestedValue(entity, this.queryState.distinct);
|
|
628
|
+
const key = JSON.stringify(value);
|
|
629
|
+
if (!seen.has(key)) {
|
|
630
|
+
seen.add(key);
|
|
631
|
+
result.push(entity);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return result;
|
|
816
635
|
}
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
636
|
+
};
|
|
637
|
+
var EntityQueryBuilderImpl = class {
|
|
638
|
+
entityId;
|
|
639
|
+
constructor(entityId) {
|
|
640
|
+
this.entityId = entityId;
|
|
641
|
+
}
|
|
642
|
+
get() {
|
|
643
|
+
return getEntityView(this.entityId);
|
|
644
|
+
}
|
|
645
|
+
pluck(key) {
|
|
646
|
+
const view = this.get();
|
|
647
|
+
return view ? view[key] : void 0;
|
|
648
|
+
}
|
|
649
|
+
subscribe(callback) {
|
|
650
|
+
callback(this.get());
|
|
651
|
+
return () => {};
|
|
823
652
|
}
|
|
824
653
|
};
|
|
825
654
|
/**
|
|
826
|
-
* Create a query builder for
|
|
655
|
+
* Create a query builder for multiple entities
|
|
827
656
|
*/
|
|
828
|
-
function
|
|
829
|
-
return new
|
|
657
|
+
function entities() {
|
|
658
|
+
return new EntitiesQueryBuilderImpl();
|
|
830
659
|
}
|
|
831
660
|
/**
|
|
832
|
-
* Create a query for a single
|
|
661
|
+
* Create a query builder for a single entity
|
|
833
662
|
*/
|
|
834
|
-
function
|
|
835
|
-
return
|
|
663
|
+
function entity(entityId) {
|
|
664
|
+
return new EntityQueryBuilderImpl(entityId);
|
|
836
665
|
}
|
|
837
666
|
//#endregion
|
|
838
|
-
//#region src/
|
|
839
|
-
/**
|
|
840
|
-
* Entity Index Queries
|
|
841
|
-
*
|
|
842
|
-
* Provides utilities for querying entities by various criteria.
|
|
843
|
-
* In the SolidJS port, indices are NOT stored in state -- they are
|
|
844
|
-
* computed on the fly here (and will be derived reactively in Plan 03).
|
|
845
|
-
*
|
|
846
|
-
* @packageDocumentation
|
|
847
|
-
*/
|
|
667
|
+
//#region src/query/helpers.ts
|
|
848
668
|
/**
|
|
849
|
-
*
|
|
669
|
+
* Create a search query builder
|
|
850
670
|
*/
|
|
851
|
-
function
|
|
852
|
-
|
|
671
|
+
function searchEntities(searchText) {
|
|
672
|
+
const searchLower = searchText.toLowerCase();
|
|
673
|
+
return entities().where((e) => e.id.toLowerCase().includes(searchLower) || e.name.toLowerCase().includes(searchLower) || e.friendlyName.toLowerCase().includes(searchLower));
|
|
853
674
|
}
|
|
854
675
|
/**
|
|
855
|
-
*
|
|
676
|
+
* Create a query for entities in an area by domain
|
|
856
677
|
*/
|
|
857
|
-
function
|
|
858
|
-
return
|
|
678
|
+
function entitiesByAreaAndDomain(areaId, domain) {
|
|
679
|
+
return entities().byArea(areaId).byDomain(domain);
|
|
859
680
|
}
|
|
860
681
|
/**
|
|
861
|
-
*
|
|
862
|
-
*
|
|
863
|
-
* Only includes entities that inherit area from device (entity.area_id is null).
|
|
682
|
+
* Create a query for entities matching a predicate
|
|
864
683
|
*/
|
|
865
|
-
function
|
|
866
|
-
|
|
867
|
-
const entityIds = [];
|
|
868
|
-
for (const device of devicesInArea) {
|
|
869
|
-
const deviceEntities = getEntitiesByDevice(device.id);
|
|
870
|
-
for (const entityId of deviceEntities) if (!state.entityRegistry[entityId]?.area_id) entityIds.push(entityId);
|
|
871
|
-
}
|
|
872
|
-
return entityIds;
|
|
684
|
+
function entitiesWhere(predicate) {
|
|
685
|
+
return entities().where(predicate);
|
|
873
686
|
}
|
|
687
|
+
//#endregion
|
|
688
|
+
//#region src/camera/fetch.ts
|
|
874
689
|
/**
|
|
875
|
-
*
|
|
690
|
+
* Camera Stream Fetching
|
|
876
691
|
*
|
|
877
|
-
*
|
|
692
|
+
* @packageDocumentation
|
|
878
693
|
*/
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
for (const [entityId, entry] of Object.entries(state.entityRegistry)) if (entry.area_id === areaId) directEntityIds.push(entityId);
|
|
882
|
-
const deviceEntityIds = getEntitiesViaDevices(areaId);
|
|
883
|
-
return Array.from(/* @__PURE__ */ new Set([...directEntityIds, ...deviceEntityIds]));
|
|
884
|
-
}
|
|
694
|
+
/** The demo's front door feed, served by the dashboard itself so the demo never reaches a third party. */
|
|
695
|
+
const DEMO_HLS_STREAM = "/demo/camera/front-door.m3u8";
|
|
885
696
|
/**
|
|
886
|
-
*
|
|
697
|
+
* Fetch stream for a camera entity.
|
|
698
|
+
* Returns the dashboard's own demo HLS feed in demo mode.
|
|
887
699
|
*/
|
|
888
|
-
function
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
return
|
|
700
|
+
async function fetchStream(entityId, format = "hls") {
|
|
701
|
+
if (isDemoMode()) return format === "hls" ? demoAssetUrl(DEMO_HLS_STREAM) : null;
|
|
702
|
+
if (!privilegedConn()) return null;
|
|
703
|
+
return (await sendCommand({
|
|
704
|
+
type: "camera/stream",
|
|
705
|
+
entity_id: entityId,
|
|
706
|
+
format
|
|
707
|
+
}))?.url ?? null;
|
|
892
708
|
}
|
|
893
709
|
/**
|
|
894
|
-
*
|
|
710
|
+
* Transform relative stream URL to absolute URL
|
|
895
711
|
*/
|
|
896
|
-
function
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
const
|
|
901
|
-
|
|
712
|
+
function transformStreamUrl(streamUrl) {
|
|
713
|
+
if (!streamUrl) return null;
|
|
714
|
+
if (streamUrl.startsWith("http://") || streamUrl.startsWith("https://")) return streamUrl;
|
|
715
|
+
if (streamUrl.startsWith("/")) {
|
|
716
|
+
const hassUrl = state.hassUrl;
|
|
717
|
+
if (!hassUrl) {
|
|
718
|
+
console.warn("[fetchStreamData] No Home Assistant URL available to resolve relative stream URL");
|
|
719
|
+
return streamUrl;
|
|
720
|
+
}
|
|
721
|
+
return `${hassUrl.replace(/\/$/, "")}${streamUrl}`;
|
|
902
722
|
}
|
|
903
|
-
return
|
|
723
|
+
return streamUrl;
|
|
904
724
|
}
|
|
905
725
|
/**
|
|
906
|
-
*
|
|
726
|
+
* Fetch stream data for a camera entity
|
|
907
727
|
*/
|
|
908
|
-
function
|
|
909
|
-
const
|
|
910
|
-
|
|
911
|
-
|
|
728
|
+
async function fetchStreamData(entityId, options = {}) {
|
|
729
|
+
const { format = "hls" } = options;
|
|
730
|
+
try {
|
|
731
|
+
return {
|
|
732
|
+
entityId,
|
|
733
|
+
stream: {
|
|
734
|
+
url: transformStreamUrl(await fetchStream(entityId, format)),
|
|
735
|
+
loading: false,
|
|
736
|
+
error: null,
|
|
737
|
+
lastFetched: Date.now(),
|
|
738
|
+
format,
|
|
739
|
+
expiresAt: null
|
|
740
|
+
},
|
|
741
|
+
loading: false,
|
|
742
|
+
error: null,
|
|
743
|
+
lastFetched: Date.now()
|
|
744
|
+
};
|
|
745
|
+
} catch (error) {
|
|
746
|
+
return {
|
|
747
|
+
entityId,
|
|
748
|
+
stream: {
|
|
749
|
+
url: null,
|
|
750
|
+
loading: false,
|
|
751
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
752
|
+
lastFetched: null,
|
|
753
|
+
format,
|
|
754
|
+
expiresAt: null
|
|
755
|
+
},
|
|
756
|
+
loading: false,
|
|
757
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
758
|
+
lastFetched: null
|
|
759
|
+
};
|
|
760
|
+
}
|
|
912
761
|
}
|
|
913
762
|
//#endregion
|
|
914
|
-
//#region src/query
|
|
763
|
+
//#region src/camera/query.ts
|
|
915
764
|
/**
|
|
916
|
-
*
|
|
765
|
+
* Camera Stream Query Builder
|
|
766
|
+
*
|
|
767
|
+
* @packageDocumentation
|
|
917
768
|
*/
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
sorts: query.sorts.map((s) => `${s.key}:${s.direction}`).join(","),
|
|
923
|
-
projection: query.projection ? JSON.stringify(query.projection) : null
|
|
924
|
-
};
|
|
925
|
-
return JSON.stringify(sig);
|
|
769
|
+
const DEFAULT_REFRESH_INTERVAL = 24e4;
|
|
770
|
+
function needsStreamRefresh(streamData, refreshInterval = DEFAULT_REFRESH_INTERVAL) {
|
|
771
|
+
if (!streamData || !streamData.lastFetched) return true;
|
|
772
|
+
return Date.now() - streamData.lastFetched >= refreshInterval;
|
|
926
773
|
}
|
|
927
774
|
/**
|
|
928
|
-
*
|
|
775
|
+
* Get stream for a camera entity
|
|
929
776
|
*/
|
|
930
|
-
function
|
|
931
|
-
|
|
777
|
+
async function getStream(entityId, options = {}) {
|
|
778
|
+
const { format = "hls", autoRefresh = true, refreshInterval } = options;
|
|
779
|
+
const cached = state.streams[entityId];
|
|
780
|
+
if (cached && cached.stream.format === format) {
|
|
781
|
+
if (autoRefresh && needsStreamRefresh(cached, refreshInterval)) fetchStreamData(entityId, {
|
|
782
|
+
format,
|
|
783
|
+
autoRefresh,
|
|
784
|
+
refreshInterval
|
|
785
|
+
}).then((streamData) => {
|
|
786
|
+
setState(produce((s) => {
|
|
787
|
+
s.streams[entityId] = streamData;
|
|
788
|
+
}));
|
|
789
|
+
});
|
|
790
|
+
return cached;
|
|
791
|
+
}
|
|
792
|
+
const streamData = await fetchStreamData(entityId, {
|
|
793
|
+
format,
|
|
794
|
+
autoRefresh,
|
|
795
|
+
refreshInterval
|
|
796
|
+
});
|
|
797
|
+
setState(produce((s) => {
|
|
798
|
+
s.streams[entityId] = streamData;
|
|
799
|
+
}));
|
|
800
|
+
return streamData;
|
|
932
801
|
}
|
|
933
|
-
//#endregion
|
|
934
|
-
//#region src/query/projections.ts
|
|
935
802
|
/**
|
|
936
|
-
*
|
|
937
|
-
*
|
|
938
|
-
* @param entities - Array of entity views
|
|
939
|
-
* @returns Array of entity IDs
|
|
803
|
+
* Refresh stream for a camera entity
|
|
940
804
|
*/
|
|
941
|
-
function
|
|
942
|
-
|
|
805
|
+
async function refreshStream(entityId, format = "hls") {
|
|
806
|
+
setState(produce((s) => {
|
|
807
|
+
delete s.streams[entityId];
|
|
808
|
+
}));
|
|
809
|
+
return getStream(entityId, { format });
|
|
810
|
+
}
|
|
811
|
+
//#endregion
|
|
812
|
+
//#region src/energy/prefs.ts
|
|
813
|
+
function isRecord(value) {
|
|
814
|
+
return typeof value === "object" && value !== null;
|
|
943
815
|
}
|
|
944
816
|
/**
|
|
945
|
-
*
|
|
817
|
+
* Fetch the HA energy dashboard preferences.
|
|
946
818
|
*
|
|
947
|
-
*
|
|
948
|
-
*
|
|
949
|
-
*
|
|
819
|
+
* Returns `null` when no energy dashboard is configured (HA raises an error
|
|
820
|
+
* for `energy/get_prefs` in that case); callers treat `null` as "not
|
|
821
|
+
* configured".
|
|
950
822
|
*/
|
|
951
|
-
function
|
|
952
|
-
|
|
953
|
-
const
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
823
|
+
async function fetchEnergyPreferences(connection) {
|
|
824
|
+
if (isDemoMode()) {
|
|
825
|
+
const prefs = demoEnergyPreferences();
|
|
826
|
+
return {
|
|
827
|
+
...prefs,
|
|
828
|
+
energy_sources: prefs.energy_sources,
|
|
829
|
+
device_consumption: prefs.device_consumption
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
let response;
|
|
833
|
+
try {
|
|
834
|
+
response = await connection.sendMessagePromise({ type: "energy/get_prefs" });
|
|
835
|
+
} catch {
|
|
836
|
+
return null;
|
|
837
|
+
}
|
|
838
|
+
if (!isRecord(response)) return null;
|
|
839
|
+
const sources = Array.isArray(response.energy_sources) ? response.energy_sources.filter(isRecord) : [];
|
|
840
|
+
const devices = Array.isArray(response.device_consumption) ? response.device_consumption.filter(isRecord) : [];
|
|
841
|
+
return {
|
|
842
|
+
...response,
|
|
843
|
+
energy_sources: sources,
|
|
844
|
+
device_consumption: devices
|
|
845
|
+
};
|
|
957
846
|
}
|
|
847
|
+
//#endregion
|
|
848
|
+
//#region src/media/url.ts
|
|
958
849
|
/**
|
|
959
|
-
*
|
|
850
|
+
* Resolve an HA media reference (e.g. an entity's `entity_picture`, a camera
|
|
851
|
+
* proxy path) to a URL the page can actually load.
|
|
960
852
|
*
|
|
961
|
-
*
|
|
853
|
+
* HA gives these as origin-relative paths (`/api/media_player_proxy/...?token=`)
|
|
854
|
+
* carrying their own signed token. A bare `<img src>` would resolve them against
|
|
855
|
+
* the dash origin and 404. When the host set `mediaProxyBase`, route through the
|
|
856
|
+
* same-origin media proxy so the page CSP (`img-src 'self'`) covers it in every
|
|
857
|
+
* mode, LAN and remote. Otherwise fall back to prefixing `hassUrl` directly
|
|
858
|
+
* (the LAN-only path, used until a transport sets the proxy base).
|
|
962
859
|
*
|
|
963
|
-
*
|
|
964
|
-
* @param key - Field name or dot-path to extract
|
|
965
|
-
* @returns Array of field values
|
|
860
|
+
* Absolute URLs and non-path values pass through untouched.
|
|
966
861
|
*/
|
|
967
|
-
function
|
|
968
|
-
|
|
862
|
+
function hassMediaUrl(path) {
|
|
863
|
+
if (!path) return void 0;
|
|
864
|
+
if (/^https?:\/\//i.test(path)) return path;
|
|
865
|
+
if (!path.startsWith("/")) return path;
|
|
866
|
+
const base = state.mediaProxyBase;
|
|
867
|
+
if (base) return `${base}?path=${encodeURIComponent(path)}`;
|
|
868
|
+
return state.hassUrl ? `${state.hassUrl}${path}` : path;
|
|
969
869
|
}
|
|
870
|
+
//#endregion
|
|
871
|
+
//#region src/camera/webrtc.ts
|
|
970
872
|
/**
|
|
971
|
-
*
|
|
972
|
-
*
|
|
973
|
-
* @param entities - Array of entity views
|
|
974
|
-
* @param mapper - Function to transform each entity
|
|
975
|
-
* @returns Array of mapped values
|
|
873
|
+
* Get WebRTC client configuration (STUN/TURN servers) from HA
|
|
976
874
|
*/
|
|
977
|
-
function
|
|
978
|
-
|
|
875
|
+
async function getWebRtcClientConfig(entityId) {
|
|
876
|
+
const conn = privilegedConn();
|
|
877
|
+
if (!conn) throw new Error("No connection available");
|
|
878
|
+
return conn.sendMessagePromise({
|
|
879
|
+
type: "camera/webrtc/get_client_config",
|
|
880
|
+
entity_id: entityId
|
|
881
|
+
});
|
|
979
882
|
}
|
|
980
883
|
/**
|
|
981
|
-
*
|
|
982
|
-
*
|
|
983
|
-
*
|
|
984
|
-
*
|
|
985
|
-
* @returns Value at path or undefined
|
|
986
|
-
*
|
|
987
|
-
* @example
|
|
988
|
-
* ```typescript
|
|
989
|
-
* const entity = { attributes: { brightness: 255 } };
|
|
990
|
-
* getNestedValue(entity, "attributes.brightness"); // 255
|
|
991
|
-
* ```
|
|
884
|
+
* Start WebRTC session with HA.
|
|
885
|
+
* Returns a promise that resolves when the answer SDP is received.
|
|
886
|
+
* ICE candidates from HA are forwarded to the provided callback.
|
|
887
|
+
* Local ICE candidates should be sent via sendWebRtcCandidate().
|
|
992
888
|
*/
|
|
993
|
-
function
|
|
994
|
-
const
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
return current;
|
|
1001
|
-
}
|
|
1002
|
-
//#endregion
|
|
1003
|
-
//#region src/query/builder.ts
|
|
1004
|
-
var EntitiesQueryBuilderImpl = class EntitiesQueryBuilderImpl {
|
|
1005
|
-
queryState;
|
|
1006
|
-
constructor(initialState) {
|
|
1007
|
-
this.queryState = initialState ?? {
|
|
1008
|
-
indexFilters: [],
|
|
1009
|
-
predicateFilters: [],
|
|
1010
|
-
sorts: [],
|
|
1011
|
-
projection: void 0,
|
|
1012
|
-
searchText: void 0,
|
|
1013
|
-
take: void 0,
|
|
1014
|
-
skip: void 0,
|
|
1015
|
-
distinct: void 0
|
|
889
|
+
function startWebRtcSession(entityId, sdpOffer, onCandidate) {
|
|
890
|
+
const conn = privilegedConn();
|
|
891
|
+
if (!conn) return Promise.reject(/* @__PURE__ */ new Error("Not connected"));
|
|
892
|
+
return new Promise((resolve, reject) => {
|
|
893
|
+
const session = {
|
|
894
|
+
sessionId: null,
|
|
895
|
+
unsubscribe: null
|
|
1016
896
|
};
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
}] });
|
|
1023
|
-
}
|
|
1024
|
-
byDomain(domain) {
|
|
1025
|
-
return this.clone({ indexFilters: [...this.queryState.indexFilters, {
|
|
1026
|
-
type: "domain",
|
|
1027
|
-
value: domain
|
|
1028
|
-
}] });
|
|
1029
|
-
}
|
|
1030
|
-
byDevice(deviceId) {
|
|
1031
|
-
return this.clone({ indexFilters: [...this.queryState.indexFilters, {
|
|
1032
|
-
type: "device",
|
|
1033
|
-
value: deviceId
|
|
1034
|
-
}] });
|
|
1035
|
-
}
|
|
1036
|
-
byFloor(floorId) {
|
|
1037
|
-
return this.clone({ indexFilters: [...this.queryState.indexFilters, {
|
|
1038
|
-
type: "floor",
|
|
1039
|
-
value: floorId
|
|
1040
|
-
}] });
|
|
1041
|
-
}
|
|
1042
|
-
byLabel(labelId) {
|
|
1043
|
-
return this.clone({ indexFilters: [...this.queryState.indexFilters, {
|
|
1044
|
-
type: "label",
|
|
1045
|
-
value: labelId
|
|
1046
|
-
}] });
|
|
1047
|
-
}
|
|
1048
|
-
where(predicate) {
|
|
1049
|
-
return this.clone({ predicateFilters: [...this.queryState.predicateFilters, predicate] });
|
|
1050
|
-
}
|
|
1051
|
-
search(searchText) {
|
|
1052
|
-
const searchLower = searchText.toLowerCase();
|
|
1053
|
-
return this.where((e) => e.id.toLowerCase().includes(searchLower) || e.name.toLowerCase().includes(searchLower) || e.friendlyName.toLowerCase().includes(searchLower));
|
|
1054
|
-
}
|
|
1055
|
-
orderBy(key, direction = "asc") {
|
|
1056
|
-
return this.clone({ sorts: [...this.queryState.sorts, {
|
|
1057
|
-
key,
|
|
1058
|
-
direction
|
|
1059
|
-
}] });
|
|
1060
|
-
}
|
|
1061
|
-
ids() {
|
|
1062
|
-
return this.clone({ projection: { type: "ids" } });
|
|
1063
|
-
}
|
|
1064
|
-
pick(keys) {
|
|
1065
|
-
return this.clone({ projection: {
|
|
1066
|
-
type: "pick",
|
|
1067
|
-
keys
|
|
1068
|
-
} });
|
|
1069
|
-
}
|
|
1070
|
-
pluck(key) {
|
|
1071
|
-
return this.clone({ projection: {
|
|
1072
|
-
type: "pluck",
|
|
1073
|
-
key
|
|
1074
|
-
} });
|
|
1075
|
-
}
|
|
1076
|
-
map(mapper) {
|
|
1077
|
-
return this.clone({ projection: {
|
|
1078
|
-
type: "map",
|
|
1079
|
-
mapper
|
|
1080
|
-
} });
|
|
1081
|
-
}
|
|
1082
|
-
take(limit) {
|
|
1083
|
-
return this.clone({ take: limit });
|
|
1084
|
-
}
|
|
1085
|
-
skip(count) {
|
|
1086
|
-
return this.clone({ skip: count });
|
|
1087
|
-
}
|
|
1088
|
-
distinct(key) {
|
|
1089
|
-
return this.clone({ distinct: key });
|
|
1090
|
-
}
|
|
1091
|
-
get() {
|
|
1092
|
-
return memoizedExecute(buildQuerySignature(this.queryState), () => this.execute());
|
|
1093
|
-
}
|
|
1094
|
-
first() {
|
|
1095
|
-
return this.get()[0];
|
|
1096
|
-
}
|
|
1097
|
-
subscribe(callback) {
|
|
1098
|
-
callback(this.get());
|
|
1099
|
-
return () => {};
|
|
1100
|
-
}
|
|
1101
|
-
clone(updates) {
|
|
1102
|
-
return new EntitiesQueryBuilderImpl({
|
|
1103
|
-
...this.queryState,
|
|
1104
|
-
...updates
|
|
1105
|
-
});
|
|
1106
|
-
}
|
|
1107
|
-
execute() {
|
|
1108
|
-
const entityIds = this.getEntityIdsFromIndices();
|
|
1109
|
-
let entities = getEntityViews(entityIds);
|
|
1110
|
-
for (const filter of this.queryState.predicateFilters) entities = entities.filter(filter);
|
|
1111
|
-
if (this.queryState.sorts.length > 0) entities = this.sortEntities(entities);
|
|
1112
|
-
if (this.queryState.distinct) entities = this.applyDistinct(entities);
|
|
1113
|
-
if (this.queryState.skip !== void 0) entities = entities.slice(this.queryState.skip);
|
|
1114
|
-
if (this.queryState.take !== void 0) entities = entities.slice(0, this.queryState.take);
|
|
1115
|
-
if (this.queryState.projection) return this.applyProjection(entities);
|
|
1116
|
-
return entities;
|
|
1117
|
-
}
|
|
1118
|
-
getEntityIdsFromIndices() {
|
|
1119
|
-
if (this.queryState.indexFilters.length === 0) return getAllEntityIds();
|
|
1120
|
-
const idSets = this.queryState.indexFilters.map((filter) => this.getIdsForFilter(filter));
|
|
1121
|
-
return this.intersectArrays(idSets);
|
|
1122
|
-
}
|
|
1123
|
-
getIdsForFilter(filter) {
|
|
1124
|
-
switch (filter.type) {
|
|
1125
|
-
case "domain": return getEntitiesByDomain(filter.value);
|
|
1126
|
-
case "area": return getEntitiesByArea(filter.value);
|
|
1127
|
-
case "device": return getEntitiesByDevice(filter.value);
|
|
1128
|
-
case "floor": return getEntitiesByFloor(filter.value);
|
|
1129
|
-
case "label": return getEntitiesByLabel(filter.value);
|
|
1130
|
-
default: return [];
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
intersectArrays(arrays) {
|
|
1134
|
-
if (arrays.length === 0) return [];
|
|
1135
|
-
if (arrays.length === 1) return arrays[0] ?? [];
|
|
1136
|
-
let result = arrays[0] ?? [];
|
|
1137
|
-
for (let i = 1; i < arrays.length; i++) {
|
|
1138
|
-
const set = new Set(arrays[i]);
|
|
1139
|
-
result = result.filter((item) => set.has(item));
|
|
1140
|
-
}
|
|
1141
|
-
return result;
|
|
1142
|
-
}
|
|
1143
|
-
sortEntities(entities) {
|
|
1144
|
-
const sorted = [...entities];
|
|
1145
|
-
sorted.sort((a, b) => {
|
|
1146
|
-
for (const sort of this.queryState.sorts) {
|
|
1147
|
-
const aVal = getNestedValue(a, sort.key);
|
|
1148
|
-
const bVal = getNestedValue(b, sort.key);
|
|
1149
|
-
const comparison = this.compareValues(aVal, bVal);
|
|
1150
|
-
if (comparison !== 0) return sort.direction === "asc" ? comparison : -comparison;
|
|
897
|
+
let answered = false;
|
|
898
|
+
const timeout = setTimeout(() => {
|
|
899
|
+
if (!answered) {
|
|
900
|
+
session.unsubscribe?.().catch(logUnsubscribeError);
|
|
901
|
+
reject(/* @__PURE__ */ new Error("WebRTC offer timed out"));
|
|
1151
902
|
}
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
if (!this.queryState.distinct) return entities;
|
|
1176
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1177
|
-
const result = [];
|
|
1178
|
-
for (const entity of entities) {
|
|
1179
|
-
const value = getNestedValue(entity, this.queryState.distinct);
|
|
1180
|
-
const key = JSON.stringify(value);
|
|
1181
|
-
if (!seen.has(key)) {
|
|
1182
|
-
seen.add(key);
|
|
1183
|
-
result.push(entity);
|
|
903
|
+
}, 15e3);
|
|
904
|
+
conn.subscribeMessage((event) => {
|
|
905
|
+
switch (event.type) {
|
|
906
|
+
case "session":
|
|
907
|
+
session.sessionId = event.session_id ?? null;
|
|
908
|
+
break;
|
|
909
|
+
case "answer":
|
|
910
|
+
if (event.answer) {
|
|
911
|
+
answered = true;
|
|
912
|
+
clearTimeout(timeout);
|
|
913
|
+
resolve({
|
|
914
|
+
answer: event.answer,
|
|
915
|
+
session
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
break;
|
|
919
|
+
case "candidate":
|
|
920
|
+
if (event.candidate) onCandidate(event.candidate);
|
|
921
|
+
break;
|
|
922
|
+
case "error":
|
|
923
|
+
clearTimeout(timeout);
|
|
924
|
+
session.unsubscribe?.().catch(logUnsubscribeError);
|
|
925
|
+
reject(new Error(event.message || event.code || "WebRTC offer failed"));
|
|
1184
926
|
}
|
|
1185
|
-
}
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
}
|
|
1197
|
-
pluck(key) {
|
|
1198
|
-
const view = this.get();
|
|
1199
|
-
return view ? view[key] : void 0;
|
|
1200
|
-
}
|
|
1201
|
-
subscribe(callback) {
|
|
1202
|
-
callback(this.get());
|
|
1203
|
-
return () => {};
|
|
1204
|
-
}
|
|
1205
|
-
};
|
|
1206
|
-
/**
|
|
1207
|
-
* Create a query builder for multiple entities
|
|
1208
|
-
*/
|
|
1209
|
-
function entities() {
|
|
1210
|
-
return new EntitiesQueryBuilderImpl();
|
|
927
|
+
}, {
|
|
928
|
+
type: "camera/webrtc/offer",
|
|
929
|
+
entity_id: entityId,
|
|
930
|
+
offer: sdpOffer
|
|
931
|
+
}).then((unsub) => {
|
|
932
|
+
session.unsubscribe = unsub;
|
|
933
|
+
}).catch((err) => {
|
|
934
|
+
clearTimeout(timeout);
|
|
935
|
+
reject(err);
|
|
936
|
+
});
|
|
937
|
+
});
|
|
1211
938
|
}
|
|
1212
939
|
/**
|
|
1213
|
-
*
|
|
940
|
+
* Send a local ICE candidate to HA
|
|
1214
941
|
*/
|
|
1215
|
-
function
|
|
1216
|
-
|
|
942
|
+
async function sendWebRtcCandidate(entityId, sessionId, candidate) {
|
|
943
|
+
const conn = privilegedConn();
|
|
944
|
+
if (!conn) throw new Error("Not connected");
|
|
945
|
+
await conn.sendMessagePromise({
|
|
946
|
+
type: "camera/webrtc/candidate",
|
|
947
|
+
entity_id: entityId,
|
|
948
|
+
session_id: sessionId,
|
|
949
|
+
candidate
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
function logUnsubscribeError(error) {
|
|
953
|
+
console.error("[@glasshome/sync-layer] WebRTC unsubscribe failed:", error);
|
|
1217
954
|
}
|
|
1218
955
|
//#endregion
|
|
1219
|
-
//#region src/
|
|
956
|
+
//#region src/history/constants.ts
|
|
1220
957
|
/**
|
|
1221
|
-
*
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
/**
|
|
1228
|
-
* Create a query for entities in an area by domain
|
|
958
|
+
* History Constants
|
|
959
|
+
*
|
|
960
|
+
* Constants and utilities for history fetching and processing.
|
|
961
|
+
* Based on Home Assistant frontend implementation.
|
|
962
|
+
*
|
|
963
|
+
* @packageDocumentation
|
|
1229
964
|
*/
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
965
|
+
const DOMAINS_USE_LAST_UPDATED = [
|
|
966
|
+
"climate",
|
|
967
|
+
"humidifier",
|
|
968
|
+
"water_heater"
|
|
969
|
+
];
|
|
970
|
+
const NEED_ATTRIBUTE_DOMAINS = [
|
|
971
|
+
"climate",
|
|
972
|
+
"humidifier",
|
|
973
|
+
"input_datetime",
|
|
974
|
+
"water_heater",
|
|
975
|
+
"person",
|
|
976
|
+
"device_tracker"
|
|
977
|
+
];
|
|
978
|
+
const LINE_ATTRIBUTES_TO_KEEP = [
|
|
979
|
+
"temperature",
|
|
980
|
+
"current_temperature",
|
|
981
|
+
"target_temp_low",
|
|
982
|
+
"target_temp_high",
|
|
983
|
+
"hvac_action",
|
|
984
|
+
"humidity",
|
|
985
|
+
"mode",
|
|
986
|
+
"action",
|
|
987
|
+
"current_humidity"
|
|
988
|
+
];
|
|
1233
989
|
/**
|
|
1234
|
-
*
|
|
990
|
+
* Check if an entity needs attributes in history response
|
|
1235
991
|
*/
|
|
1236
|
-
function
|
|
1237
|
-
|
|
992
|
+
function entityIdHistoryNeedsAttributes(entityId) {
|
|
993
|
+
const domain = extractDomain(entityId);
|
|
994
|
+
if (!state.entities[entityId]) return NEED_ATTRIBUTE_DOMAINS.includes(domain);
|
|
995
|
+
return NEED_ATTRIBUTE_DOMAINS.includes(domain);
|
|
1238
996
|
}
|
|
1239
997
|
//#endregion
|
|
1240
|
-
//#region src/
|
|
998
|
+
//#region src/history/fetch.ts
|
|
1241
999
|
/**
|
|
1242
|
-
*
|
|
1000
|
+
* History Fetching
|
|
1243
1001
|
*
|
|
1244
1002
|
* @packageDocumentation
|
|
1245
1003
|
*/
|
|
1246
|
-
/** The demo's front door feed, served by the dashboard itself so the demo never reaches a third party. */
|
|
1247
|
-
const DEMO_HLS_STREAM = "/demo/camera/front-door.m3u8";
|
|
1248
|
-
/**
|
|
1249
|
-
* Fetch stream for a camera entity.
|
|
1250
|
-
* Returns the dashboard's own demo HLS feed in demo mode.
|
|
1251
|
-
*/
|
|
1252
|
-
async function fetchStream(entityId, format = "hls") {
|
|
1253
|
-
if (isDemoMode()) return format === "hls" ? demoAssetUrl(DEMO_HLS_STREAM) : null;
|
|
1254
|
-
if (!privilegedConn()) return null;
|
|
1255
|
-
return (await sendCommand({
|
|
1256
|
-
type: "camera/stream",
|
|
1257
|
-
entity_id: entityId,
|
|
1258
|
-
format
|
|
1259
|
-
}))?.url ?? null;
|
|
1260
|
-
}
|
|
1261
1004
|
/**
|
|
1262
|
-
*
|
|
1005
|
+
* Fetch history for entities during a time period
|
|
1263
1006
|
*/
|
|
1264
|
-
function
|
|
1265
|
-
|
|
1266
|
-
if (
|
|
1267
|
-
|
|
1268
|
-
const
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1007
|
+
async function fetchHistory(options) {
|
|
1008
|
+
const { startTime, endTime, entityIds = [], includeStartTimeState = true, significantChangesOnly = true, minimalResponse = true, noAttributes: noAttributesOverride } = options;
|
|
1009
|
+
if (isDemoMode()) {
|
|
1010
|
+
const endMs = (endTime ?? /* @__PURE__ */ new Date()).getTime();
|
|
1011
|
+
const result = {};
|
|
1012
|
+
for (const id of entityIds) {
|
|
1013
|
+
const points = isEnergyEntity(id) ? synthesizeEnergyHistory(id, startTime.getTime(), endMs) : numericSensorHistory(id, startTime.getTime(), endMs);
|
|
1014
|
+
if (!points) continue;
|
|
1015
|
+
result[id] = points.map((p) => ({
|
|
1016
|
+
s: p.s,
|
|
1017
|
+
a: {},
|
|
1018
|
+
lu: p.lu
|
|
1019
|
+
}));
|
|
1272
1020
|
}
|
|
1273
|
-
return
|
|
1021
|
+
return result;
|
|
1274
1022
|
}
|
|
1275
|
-
|
|
1023
|
+
const startTimeStr = startTime.toISOString();
|
|
1024
|
+
const endTimeStr = endTime?.toISOString();
|
|
1025
|
+
const params = {
|
|
1026
|
+
type: "history/history_during_period",
|
|
1027
|
+
start_time: startTimeStr,
|
|
1028
|
+
minimal_response: minimalResponse,
|
|
1029
|
+
no_attributes: noAttributesOverride ?? (entityIds.length === 0 ? false : !entityIds.some((entityId) => entityIdHistoryNeedsAttributes(entityId))),
|
|
1030
|
+
include_start_time_state: includeStartTimeState,
|
|
1031
|
+
significant_changes_only: significantChangesOnly
|
|
1032
|
+
};
|
|
1033
|
+
if (endTimeStr) params.end_time = endTimeStr;
|
|
1034
|
+
if (entityIds.length !== 0) params.entity_ids = entityIds;
|
|
1035
|
+
return await sendCommand(params) ?? {};
|
|
1276
1036
|
}
|
|
1277
1037
|
/**
|
|
1278
|
-
* Fetch
|
|
1038
|
+
* Fetch history for a single entity
|
|
1279
1039
|
*/
|
|
1280
|
-
async function
|
|
1281
|
-
const {
|
|
1040
|
+
async function fetchEntityHistory(entityId, options) {
|
|
1041
|
+
const { startTime, endTime, includeStartTimeState = true, significantChangesOnly = true, minimalResponse = false, noAttributes = false } = options;
|
|
1282
1042
|
try {
|
|
1043
|
+
const entityHistory = (await fetchHistory({
|
|
1044
|
+
startTime,
|
|
1045
|
+
endTime,
|
|
1046
|
+
entityIds: [entityId],
|
|
1047
|
+
includeStartTimeState,
|
|
1048
|
+
significantChangesOnly,
|
|
1049
|
+
minimalResponse,
|
|
1050
|
+
noAttributes
|
|
1051
|
+
}))[entityId] ?? [];
|
|
1283
1052
|
return {
|
|
1284
1053
|
entityId,
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1054
|
+
timeline: entityHistory.map((s) => ({
|
|
1055
|
+
timestamp: s.lu,
|
|
1056
|
+
state: s.s,
|
|
1057
|
+
attributes: s.a,
|
|
1058
|
+
lastChanged: s.lc,
|
|
1059
|
+
lastUpdated: s.lu
|
|
1060
|
+
})),
|
|
1061
|
+
entityHistory,
|
|
1293
1062
|
loading: false,
|
|
1294
1063
|
error: null,
|
|
1295
1064
|
lastFetched: Date.now()
|
|
@@ -1297,209 +1066,117 @@ async function fetchStreamData(entityId, options = {}) {
|
|
|
1297
1066
|
} catch (error) {
|
|
1298
1067
|
return {
|
|
1299
1068
|
entityId,
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
loading: false,
|
|
1303
|
-
error: error instanceof Error ? error : new Error(String(error)),
|
|
1304
|
-
lastFetched: null,
|
|
1305
|
-
format,
|
|
1306
|
-
expiresAt: null
|
|
1307
|
-
},
|
|
1069
|
+
timeline: [],
|
|
1070
|
+
entityHistory: [],
|
|
1308
1071
|
loading: false,
|
|
1309
1072
|
error: error instanceof Error ? error : new Error(String(error)),
|
|
1310
1073
|
lastFetched: null
|
|
1311
1074
|
};
|
|
1312
1075
|
}
|
|
1313
1076
|
}
|
|
1314
|
-
//#endregion
|
|
1315
|
-
//#region src/camera/query.ts
|
|
1316
1077
|
/**
|
|
1317
|
-
*
|
|
1318
|
-
*
|
|
1319
|
-
* @packageDocumentation
|
|
1078
|
+
* Convert compressed history state to timeline state
|
|
1320
1079
|
*/
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1080
|
+
function historyStateToTimeline(s) {
|
|
1081
|
+
return {
|
|
1082
|
+
timestamp: s.lu,
|
|
1083
|
+
state: s.s,
|
|
1084
|
+
attributes: s.a,
|
|
1085
|
+
lastChanged: s.lc,
|
|
1086
|
+
lastUpdated: s.lu
|
|
1087
|
+
};
|
|
1325
1088
|
}
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
*/
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1089
|
+
//#endregion
|
|
1090
|
+
//#region src/history/query.ts
|
|
1091
|
+
/** Hard cap on retained points per entity timeline. */
|
|
1092
|
+
const MAX_HISTORY_POINTS = 5760;
|
|
1093
|
+
/** Live tracker count per entity. Ref-counted because a timeline is shared: two
|
|
1094
|
+
* widgets on the same entity must not let the first unmount delete the store
|
|
1095
|
+
* data the second is still rendering (appendHistoryPoint would then silently
|
|
1096
|
+
* drop every update and the survivor's chart would freeze). */
|
|
1097
|
+
const trackedEntities = /* @__PURE__ */ new Map();
|
|
1098
|
+
/** Check if an entity has active history tracking. */
|
|
1099
|
+
function isHistoryTracked(entityId) {
|
|
1100
|
+
return trackedEntities.has(entityId);
|
|
1101
|
+
}
|
|
1102
|
+
/** Start tracking history for an entity. Fetches initial backfill. */
|
|
1103
|
+
async function trackEntityHistory(entityId, options) {
|
|
1104
|
+
trackedEntities.set(entityId, (trackedEntities.get(entityId) ?? 0) + 1);
|
|
1105
|
+
const historyData = await fetchEntityHistory(entityId, options);
|
|
1106
|
+
setState(produce((s) => {
|
|
1107
|
+
s.history[entityId] = historyData;
|
|
1108
|
+
}));
|
|
1109
|
+
return historyData;
|
|
1110
|
+
}
|
|
1111
|
+
/** Release one tracker. The entity's data is cleared only when the last one goes. */
|
|
1112
|
+
function untrackEntityHistory(entityId) {
|
|
1113
|
+
const remaining = (trackedEntities.get(entityId) ?? 0) - 1;
|
|
1114
|
+
if (remaining > 0) {
|
|
1115
|
+
trackedEntities.set(entityId, remaining);
|
|
1116
|
+
return;
|
|
1343
1117
|
}
|
|
1344
|
-
|
|
1345
|
-
format,
|
|
1346
|
-
autoRefresh,
|
|
1347
|
-
refreshInterval
|
|
1348
|
-
});
|
|
1118
|
+
trackedEntities.delete(entityId);
|
|
1349
1119
|
setState(produce((s) => {
|
|
1350
|
-
s.
|
|
1120
|
+
delete s.history[entityId];
|
|
1351
1121
|
}));
|
|
1352
|
-
return streamData;
|
|
1353
1122
|
}
|
|
1354
1123
|
/**
|
|
1355
|
-
*
|
|
1124
|
+
* Append a state change to an entity's history.
|
|
1125
|
+
* Called by the entity subscription handler when a tracked entity changes.
|
|
1356
1126
|
*/
|
|
1357
|
-
|
|
1127
|
+
function appendHistoryPoint(entityId, stateValue, attributes, lastUpdated, lastChanged) {
|
|
1358
1128
|
setState(produce((s) => {
|
|
1359
|
-
|
|
1129
|
+
const history = s.history[entityId];
|
|
1130
|
+
if (!history) return;
|
|
1131
|
+
const point = {
|
|
1132
|
+
s: stateValue,
|
|
1133
|
+
a: attributes,
|
|
1134
|
+
lu: lastUpdated,
|
|
1135
|
+
lc: lastChanged
|
|
1136
|
+
};
|
|
1137
|
+
history.entityHistory.push(point);
|
|
1138
|
+
history.timeline.push({
|
|
1139
|
+
timestamp: lastUpdated,
|
|
1140
|
+
state: stateValue,
|
|
1141
|
+
attributes,
|
|
1142
|
+
lastChanged,
|
|
1143
|
+
lastUpdated
|
|
1144
|
+
});
|
|
1360
1145
|
}));
|
|
1361
|
-
return getStream(entityId, { format });
|
|
1362
|
-
}
|
|
1363
|
-
//#endregion
|
|
1364
|
-
//#region src/energy/prefs.ts
|
|
1365
|
-
function isRecord(value) {
|
|
1366
|
-
return typeof value === "object" && value !== null;
|
|
1367
1146
|
}
|
|
1368
1147
|
/**
|
|
1369
|
-
*
|
|
1370
|
-
*
|
|
1371
|
-
* Returns `null` when no energy dashboard is configured (HA raises an error
|
|
1372
|
-
* for `energy/get_prefs` in that case); callers treat `null` as "not
|
|
1373
|
-
* configured".
|
|
1148
|
+
* Append multiple history points in a single setState(produce(...)).
|
|
1149
|
+
* Called by the rAF-batched subscription flush.
|
|
1374
1150
|
*/
|
|
1375
|
-
|
|
1376
|
-
if (
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
*
|
|
1405
|
-
* HA gives these as origin-relative paths (`/api/media_player_proxy/...?token=`)
|
|
1406
|
-
* carrying their own signed token. A bare `<img src>` would resolve them against
|
|
1407
|
-
* the dash origin and 404. When the host set `mediaProxyBase`, route through the
|
|
1408
|
-
* same-origin media proxy so the page CSP (`img-src 'self'`) covers it in every
|
|
1409
|
-
* mode, LAN and remote. Otherwise fall back to prefixing `hassUrl` directly
|
|
1410
|
-
* (the LAN-only path, used until a transport sets the proxy base).
|
|
1411
|
-
*
|
|
1412
|
-
* Absolute URLs and non-path values pass through untouched.
|
|
1413
|
-
*/
|
|
1414
|
-
function hassMediaUrl(path) {
|
|
1415
|
-
if (!path) return void 0;
|
|
1416
|
-
if (/^https?:\/\//i.test(path)) return path;
|
|
1417
|
-
if (!path.startsWith("/")) return path;
|
|
1418
|
-
const base = state.mediaProxyBase;
|
|
1419
|
-
if (base) return `${base}?path=${encodeURIComponent(path)}`;
|
|
1420
|
-
return state.hassUrl ? `${state.hassUrl}${path}` : path;
|
|
1421
|
-
}
|
|
1422
|
-
//#endregion
|
|
1423
|
-
//#region src/camera/webrtc.ts
|
|
1424
|
-
/**
|
|
1425
|
-
* Get WebRTC client configuration (STUN/TURN servers) from HA
|
|
1426
|
-
*/
|
|
1427
|
-
async function getWebRtcClientConfig(entityId) {
|
|
1428
|
-
const conn = privilegedConn();
|
|
1429
|
-
if (!conn) throw new Error("No connection available");
|
|
1430
|
-
return conn.sendMessagePromise({
|
|
1431
|
-
type: "camera/webrtc/get_client_config",
|
|
1432
|
-
entity_id: entityId
|
|
1433
|
-
});
|
|
1434
|
-
}
|
|
1435
|
-
/**
|
|
1436
|
-
* Start WebRTC session with HA.
|
|
1437
|
-
* Returns a promise that resolves when the answer SDP is received.
|
|
1438
|
-
* ICE candidates from HA are forwarded to the provided callback.
|
|
1439
|
-
* Local ICE candidates should be sent via sendWebRtcCandidate().
|
|
1440
|
-
*/
|
|
1441
|
-
function startWebRtcSession(entityId, sdpOffer, onCandidate) {
|
|
1442
|
-
const conn = privilegedConn();
|
|
1443
|
-
if (!conn) return Promise.reject(/* @__PURE__ */ new Error("Not connected"));
|
|
1444
|
-
return new Promise((resolve, reject) => {
|
|
1445
|
-
const session = {
|
|
1446
|
-
sessionId: null,
|
|
1447
|
-
unsubscribe: null
|
|
1448
|
-
};
|
|
1449
|
-
let answered = false;
|
|
1450
|
-
const timeout = setTimeout(() => {
|
|
1451
|
-
if (!answered) {
|
|
1452
|
-
session.unsubscribe?.();
|
|
1453
|
-
reject(/* @__PURE__ */ new Error("WebRTC offer timed out"));
|
|
1454
|
-
}
|
|
1455
|
-
}, 15e3);
|
|
1456
|
-
conn.subscribeMessage((event) => {
|
|
1457
|
-
switch (event.type) {
|
|
1458
|
-
case "session":
|
|
1459
|
-
session.sessionId = event.session_id ?? null;
|
|
1460
|
-
break;
|
|
1461
|
-
case "answer":
|
|
1462
|
-
if (event.answer) {
|
|
1463
|
-
answered = true;
|
|
1464
|
-
clearTimeout(timeout);
|
|
1465
|
-
resolve({
|
|
1466
|
-
answer: event.answer,
|
|
1467
|
-
session
|
|
1468
|
-
});
|
|
1469
|
-
}
|
|
1470
|
-
break;
|
|
1471
|
-
case "candidate":
|
|
1472
|
-
if (event.candidate) onCandidate(event.candidate);
|
|
1473
|
-
break;
|
|
1474
|
-
case "error":
|
|
1475
|
-
clearTimeout(timeout);
|
|
1476
|
-
session.unsubscribe?.();
|
|
1477
|
-
reject(new Error(event.message || event.code || "WebRTC offer failed"));
|
|
1478
|
-
}
|
|
1479
|
-
}, {
|
|
1480
|
-
type: "camera/webrtc/offer",
|
|
1481
|
-
entity_id: entityId,
|
|
1482
|
-
offer: sdpOffer
|
|
1483
|
-
}).then((unsub) => {
|
|
1484
|
-
session.unsubscribe = unsub;
|
|
1485
|
-
}).catch((err) => {
|
|
1486
|
-
clearTimeout(timeout);
|
|
1487
|
-
reject(err);
|
|
1488
|
-
});
|
|
1489
|
-
});
|
|
1490
|
-
}
|
|
1491
|
-
/**
|
|
1492
|
-
* Send a local ICE candidate to HA
|
|
1493
|
-
*/
|
|
1494
|
-
async function sendWebRtcCandidate(entityId, sessionId, candidate) {
|
|
1495
|
-
const conn = privilegedConn();
|
|
1496
|
-
if (!conn) throw new Error("Not connected");
|
|
1497
|
-
await conn.sendMessagePromise({
|
|
1498
|
-
type: "camera/webrtc/candidate",
|
|
1499
|
-
entity_id: entityId,
|
|
1500
|
-
session_id: sessionId,
|
|
1501
|
-
candidate
|
|
1502
|
-
});
|
|
1151
|
+
function bulkAppendHistoryPoints(points) {
|
|
1152
|
+
if (points.length === 0) return;
|
|
1153
|
+
setState(produce((s) => {
|
|
1154
|
+
const touched = /* @__PURE__ */ new Set();
|
|
1155
|
+
for (const { entityId, stateValue, attributes, lastUpdated, lastChanged } of points) {
|
|
1156
|
+
const history = s.history[entityId];
|
|
1157
|
+
if (!history) continue;
|
|
1158
|
+
history.entityHistory.push({
|
|
1159
|
+
s: stateValue,
|
|
1160
|
+
a: attributes,
|
|
1161
|
+
lu: lastUpdated,
|
|
1162
|
+
lc: lastChanged
|
|
1163
|
+
});
|
|
1164
|
+
history.timeline.push({
|
|
1165
|
+
timestamp: lastUpdated,
|
|
1166
|
+
state: stateValue,
|
|
1167
|
+
attributes,
|
|
1168
|
+
lastChanged,
|
|
1169
|
+
lastUpdated
|
|
1170
|
+
});
|
|
1171
|
+
touched.add(entityId);
|
|
1172
|
+
}
|
|
1173
|
+
for (const entityId of touched) {
|
|
1174
|
+
const history = s.history[entityId];
|
|
1175
|
+
if (!history) continue;
|
|
1176
|
+
if (history.entityHistory.length > 5760) history.entityHistory.splice(0, history.entityHistory.length - MAX_HISTORY_POINTS);
|
|
1177
|
+
if (history.timeline.length > 5760) history.timeline.splice(0, history.timeline.length - MAX_HISTORY_POINTS);
|
|
1178
|
+
}
|
|
1179
|
+
}));
|
|
1503
1180
|
}
|
|
1504
1181
|
//#endregion
|
|
1505
1182
|
//#region src/weather/query.ts
|
|
@@ -1513,10 +1190,11 @@ async function sendWebRtcCandidate(entityId, sessionId, candidate) {
|
|
|
1513
1190
|
*/
|
|
1514
1191
|
async function getForecast(entityId, type) {
|
|
1515
1192
|
const cached = state.forecasts[entityId];
|
|
1516
|
-
|
|
1193
|
+
const cachedForecast = cached?.forecasts[type];
|
|
1194
|
+
if (cached && cachedForecast && cached.lastFetched[type]) return {
|
|
1517
1195
|
entityId,
|
|
1518
1196
|
type,
|
|
1519
|
-
forecast:
|
|
1197
|
+
forecast: cachedForecast,
|
|
1520
1198
|
loading: cached.loading[type] ?? false,
|
|
1521
1199
|
error: cached.errors[type] ?? null,
|
|
1522
1200
|
lastFetched: cached.lastFetched[type] ?? null
|
|
@@ -1544,15 +1222,18 @@ async function getForecasts(entityId, types) {
|
|
|
1544
1222
|
const cachedData = {};
|
|
1545
1223
|
const typesToFetch = [];
|
|
1546
1224
|
const forecastsRecord = state.forecasts[entityId];
|
|
1547
|
-
for (const type of types)
|
|
1548
|
-
|
|
1549
|
-
type
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1225
|
+
for (const type of types) {
|
|
1226
|
+
const cachedForecast = forecastsRecord?.forecasts[type];
|
|
1227
|
+
if (forecastsRecord && cachedForecast && forecastsRecord.lastFetched[type]) cachedData[type] = {
|
|
1228
|
+
entityId,
|
|
1229
|
+
type,
|
|
1230
|
+
forecast: cachedForecast,
|
|
1231
|
+
loading: forecastsRecord.loading[type] ?? false,
|
|
1232
|
+
error: forecastsRecord.errors[type] ?? null,
|
|
1233
|
+
lastFetched: forecastsRecord.lastFetched[type] ?? null
|
|
1234
|
+
};
|
|
1235
|
+
else typesToFetch.push(type);
|
|
1236
|
+
}
|
|
1556
1237
|
let fetchedData;
|
|
1557
1238
|
if (typesToFetch.length > 0) {
|
|
1558
1239
|
fetchedData = await fetchForecasts(entityId, typesToFetch);
|
|
@@ -1571,11 +1252,14 @@ async function getForecasts(entityId, types) {
|
|
|
1571
1252
|
s.forecasts[entityId].lastFetched[type] = fetchedData.lastFetched[type] ?? null;
|
|
1572
1253
|
}
|
|
1573
1254
|
}));
|
|
1574
|
-
for (const type of types)
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1255
|
+
for (const type of types) {
|
|
1256
|
+
const cached = cachedData[type];
|
|
1257
|
+
if (cached) {
|
|
1258
|
+
fetchedData.forecasts[type] = cached.forecast;
|
|
1259
|
+
fetchedData.loading[type] = cached.loading;
|
|
1260
|
+
fetchedData.errors[type] = cached.error;
|
|
1261
|
+
fetchedData.lastFetched[type] = cached.lastFetched;
|
|
1262
|
+
}
|
|
1579
1263
|
}
|
|
1580
1264
|
} else {
|
|
1581
1265
|
fetchedData = {
|
|
@@ -1587,6 +1271,7 @@ async function getForecasts(entityId, types) {
|
|
|
1587
1271
|
};
|
|
1588
1272
|
for (const type of types) {
|
|
1589
1273
|
const cached = cachedData[type];
|
|
1274
|
+
if (!cached) continue;
|
|
1590
1275
|
fetchedData.forecasts[type] = cached.forecast;
|
|
1591
1276
|
fetchedData.loading[type] = cached.loading;
|
|
1592
1277
|
fetchedData.errors[type] = cached.error;
|
|
@@ -1782,6 +1467,285 @@ function createHaBridge(worker, events = {}) {
|
|
|
1782
1467
|
};
|
|
1783
1468
|
}
|
|
1784
1469
|
//#endregion
|
|
1470
|
+
//#region src/connection/subscriptions.ts
|
|
1471
|
+
/** Registry subscription cleanup functions (entity sub managed by subscription-manager) */
|
|
1472
|
+
let registrySubscriptions = [];
|
|
1473
|
+
/** Buffered messages waiting for next animation frame */
|
|
1474
|
+
let messageBuffer = [];
|
|
1475
|
+
let rafScheduled = false;
|
|
1476
|
+
function bufferMessage(message) {
|
|
1477
|
+
messageBuffer.push(message);
|
|
1478
|
+
if (!rafScheduled) {
|
|
1479
|
+
rafScheduled = true;
|
|
1480
|
+
(typeof requestAnimationFrame === "function" ? requestAnimationFrame : queueMicrotask)(flushMessageBuffer);
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
function flushMessageBuffer() {
|
|
1484
|
+
rafScheduled = false;
|
|
1485
|
+
const messages = messageBuffer;
|
|
1486
|
+
messageBuffer = [];
|
|
1487
|
+
if (messages.length === 0) return;
|
|
1488
|
+
setState(produce((s) => {
|
|
1489
|
+
for (const message of messages) {
|
|
1490
|
+
if (message.a) for (const [entityId, compressedState] of Object.entries(message.a)) applyCompressedState(s, entityId, compressedState);
|
|
1491
|
+
if (message.c) for (const [entityId, diff] of Object.entries(message.c)) applyStateDiff(s, entityId, diff);
|
|
1492
|
+
if (message.r) for (const entityId of message.r) delete s.entities[entityId];
|
|
1493
|
+
}
|
|
1494
|
+
}));
|
|
1495
|
+
const historyPoints = [];
|
|
1496
|
+
for (const message of messages) {
|
|
1497
|
+
if (message.a) for (const [entityId, compressedState] of Object.entries(message.a)) collectHistoryFromCompressed(historyPoints, entityId, compressedState);
|
|
1498
|
+
if (message.c) {
|
|
1499
|
+
for (const [entityId, diff] of Object.entries(message.c)) if (diff["+"]) collectHistoryFromDiff(historyPoints, entityId, diff["+"]);
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
if (historyPoints.length > 0) bulkAppendHistoryPoints(historyPoints);
|
|
1503
|
+
}
|
|
1504
|
+
/**
|
|
1505
|
+
* Subscribe to entity state updates with an entity_ids filter.
|
|
1506
|
+
* Called by the subscription manager on flush.
|
|
1507
|
+
*/
|
|
1508
|
+
async function subscribeEntities(connection, entityIds) {
|
|
1509
|
+
const subscribeMsg = { type: "subscribe_entities" };
|
|
1510
|
+
if (entityIds.length > 0) subscribeMsg.entity_ids = entityIds;
|
|
1511
|
+
return await connection.subscribeMessage((message) => {
|
|
1512
|
+
bufferMessage(message);
|
|
1513
|
+
}, subscribeMsg);
|
|
1514
|
+
}
|
|
1515
|
+
/**
|
|
1516
|
+
* Subscribe to all relevant events from Home Assistant
|
|
1517
|
+
*/
|
|
1518
|
+
async function subscribeToUpdates(conn) {
|
|
1519
|
+
await cleanupSubscriptions();
|
|
1520
|
+
setManagerConnection(conn);
|
|
1521
|
+
setResubscribeHandler(subscribeEntities);
|
|
1522
|
+
const registryUpdatedSub = await conn.subscribeEvents((event) => {
|
|
1523
|
+
handleRegistryUpdate(event);
|
|
1524
|
+
}, "entity_registry_updated");
|
|
1525
|
+
registrySubscriptions.push(() => registryUpdatedSub());
|
|
1526
|
+
const deviceRegistrySub = await conn.subscribeEvents((event) => {
|
|
1527
|
+
handleDeviceRegistryUpdate(event);
|
|
1528
|
+
}, "device_registry_updated");
|
|
1529
|
+
registrySubscriptions.push(() => deviceRegistrySub());
|
|
1530
|
+
const areaRegistrySub = await conn.subscribeEvents((event) => {
|
|
1531
|
+
handleAreaRegistryUpdate(event);
|
|
1532
|
+
}, "area_registry_updated");
|
|
1533
|
+
registrySubscriptions.push(() => areaRegistrySub());
|
|
1534
|
+
const floorRegistrySub = await conn.subscribeEvents((event) => {
|
|
1535
|
+
handleFloorRegistryUpdate(event);
|
|
1536
|
+
}, "floor_registry_updated");
|
|
1537
|
+
registrySubscriptions.push(() => floorRegistrySub());
|
|
1538
|
+
const labelRegistrySub = await conn.subscribeEvents((event) => {
|
|
1539
|
+
handleLabelRegistryUpdate(event);
|
|
1540
|
+
}, "label_registry_updated");
|
|
1541
|
+
registrySubscriptions.push(() => labelRegistrySub());
|
|
1542
|
+
const statisticsSub = await conn.subscribeEvents((event) => {
|
|
1543
|
+
handleStatisticsUpdate(event);
|
|
1544
|
+
}, "recorder_5min_statistics_generated");
|
|
1545
|
+
registrySubscriptions.push(() => statisticsSub());
|
|
1546
|
+
const coreConfigSub = await conn.subscribeEvents(() => {
|
|
1547
|
+
handleCoreConfigUpdate();
|
|
1548
|
+
}, "core_config_updated");
|
|
1549
|
+
registrySubscriptions.push(() => coreConfigSub());
|
|
1550
|
+
}
|
|
1551
|
+
/**
|
|
1552
|
+
* Clean up all active subscriptions
|
|
1553
|
+
*/
|
|
1554
|
+
async function cleanupSubscriptions() {
|
|
1555
|
+
const subscriptions = [...registrySubscriptions];
|
|
1556
|
+
for (const unsub of subscriptions) await unsub();
|
|
1557
|
+
registrySubscriptions = [];
|
|
1558
|
+
}
|
|
1559
|
+
async function handleCoreConfigUpdate() {
|
|
1560
|
+
const conn = privilegedConn();
|
|
1561
|
+
if (!conn) return;
|
|
1562
|
+
try {
|
|
1563
|
+
const config = await conn.sendMessagePromise({ type: "get_config" });
|
|
1564
|
+
if (config) setState("config", config);
|
|
1565
|
+
} catch (error) {
|
|
1566
|
+
console.error("Error refreshing core config:", error);
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
async function handleRegistryUpdate(event) {
|
|
1570
|
+
const { action, entity_id } = event.data;
|
|
1571
|
+
if (action === "create" || action === "update") {
|
|
1572
|
+
const conn = privilegedConn();
|
|
1573
|
+
if (!conn) return;
|
|
1574
|
+
try {
|
|
1575
|
+
const entry = await conn.sendMessagePromise({
|
|
1576
|
+
type: "config/entity_registry/get",
|
|
1577
|
+
entity_id
|
|
1578
|
+
});
|
|
1579
|
+
if (entry) updateEntityRegistry(entry);
|
|
1580
|
+
} catch (error) {
|
|
1581
|
+
console.error("Error fetching registry entry:", error);
|
|
1582
|
+
}
|
|
1583
|
+
} else if (action === "remove") removeEntityRegistry(entity_id);
|
|
1584
|
+
}
|
|
1585
|
+
async function handleDeviceRegistryUpdate(event) {
|
|
1586
|
+
const { action, device_id } = event.data;
|
|
1587
|
+
if (action === "create" || action === "update") {
|
|
1588
|
+
const conn = privilegedConn();
|
|
1589
|
+
if (!conn) return;
|
|
1590
|
+
try {
|
|
1591
|
+
const device = (await conn.sendMessagePromise({ type: "config/device_registry/list" })).find((d) => d.id === device_id);
|
|
1592
|
+
if (device) updateDevice(device);
|
|
1593
|
+
} catch (error) {
|
|
1594
|
+
console.error("Error fetching device:", error);
|
|
1595
|
+
}
|
|
1596
|
+
} else if (action === "remove") removeDevice(device_id);
|
|
1597
|
+
}
|
|
1598
|
+
async function handleAreaRegistryUpdate(event) {
|
|
1599
|
+
const { action, area_id } = event.data;
|
|
1600
|
+
if (action === "create" || action === "update") {
|
|
1601
|
+
const conn = privilegedConn();
|
|
1602
|
+
if (!conn) return;
|
|
1603
|
+
try {
|
|
1604
|
+
const area = (await conn.sendMessagePromise({ type: "config/area_registry/list" })).find((a) => a.id === area_id);
|
|
1605
|
+
if (area) updateArea(area);
|
|
1606
|
+
} catch (error) {
|
|
1607
|
+
console.error("Error fetching area:", error);
|
|
1608
|
+
}
|
|
1609
|
+
} else if (action === "remove") removeArea(area_id);
|
|
1610
|
+
}
|
|
1611
|
+
async function handleFloorRegistryUpdate(event) {
|
|
1612
|
+
const { action, floor_id } = event.data;
|
|
1613
|
+
if (action === "create" || action === "update") {
|
|
1614
|
+
const conn = privilegedConn();
|
|
1615
|
+
if (!conn) return;
|
|
1616
|
+
try {
|
|
1617
|
+
const floor = (await conn.sendMessagePromise({ type: "config/floor_registry/list" })).find((f) => f.floor_id === floor_id);
|
|
1618
|
+
if (floor) updateFloor(floor);
|
|
1619
|
+
} catch (error) {
|
|
1620
|
+
console.error("Error fetching floor:", error);
|
|
1621
|
+
}
|
|
1622
|
+
} else if (action === "remove") removeFloor(floor_id);
|
|
1623
|
+
}
|
|
1624
|
+
async function handleLabelRegistryUpdate(event) {
|
|
1625
|
+
const { action, label_id } = event.data;
|
|
1626
|
+
if (action === "create" || action === "update") {
|
|
1627
|
+
const conn = privilegedConn();
|
|
1628
|
+
if (!conn) return;
|
|
1629
|
+
try {
|
|
1630
|
+
const label = (await conn.sendMessagePromise({ type: "config/label_registry/list" })).find((l) => l.label_id === label_id);
|
|
1631
|
+
if (label) updateLabel(label);
|
|
1632
|
+
} catch (error) {
|
|
1633
|
+
console.error("Error fetching label:", error);
|
|
1634
|
+
}
|
|
1635
|
+
} else if (action === "remove") removeLabel(label_id);
|
|
1636
|
+
}
|
|
1637
|
+
async function handleStatisticsUpdate(event) {
|
|
1638
|
+
const { statistic_ids } = event.data;
|
|
1639
|
+
if (!statistic_ids || statistic_ids.length === 0) return;
|
|
1640
|
+
const conn = privilegedConn();
|
|
1641
|
+
if (!conn) return;
|
|
1642
|
+
try {
|
|
1643
|
+
const metadata = await conn.sendMessagePromise({
|
|
1644
|
+
type: "recorder/get_statistics_metadata",
|
|
1645
|
+
statistic_ids
|
|
1646
|
+
});
|
|
1647
|
+
if (metadata && Array.isArray(metadata)) updateStatisticsMetadata(metadata);
|
|
1648
|
+
} catch (error) {
|
|
1649
|
+
console.error("Error fetching statistics metadata:", error);
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
function timestampToIso(timestamp) {
|
|
1653
|
+
if (timestamp === void 0) return (/* @__PURE__ */ new Date()).toISOString();
|
|
1654
|
+
if (typeof timestamp === "string") return timestamp;
|
|
1655
|
+
return (/* @__PURE__ */ new Date(timestamp * 1e3)).toISOString();
|
|
1656
|
+
}
|
|
1657
|
+
function collectHistoryFromCompressed(points, entityId, compressed) {
|
|
1658
|
+
if (!isHistoryTracked(entityId)) return;
|
|
1659
|
+
const stateVal = compressed.s ?? compressed.state ?? "unknown";
|
|
1660
|
+
const attributes = compressed.a ?? compressed.attributes ?? {};
|
|
1661
|
+
const lu = compressed.lu ?? (compressed.last_updated ? new Date(compressed.last_updated).getTime() / 1e3 : Date.now() / 1e3);
|
|
1662
|
+
const lc = compressed.lc ?? (compressed.last_changed ? new Date(compressed.last_changed).getTime() / 1e3 : void 0);
|
|
1663
|
+
points.push({
|
|
1664
|
+
entityId,
|
|
1665
|
+
stateValue: stateVal,
|
|
1666
|
+
attributes,
|
|
1667
|
+
lastUpdated: lu,
|
|
1668
|
+
lastChanged: lc
|
|
1669
|
+
});
|
|
1670
|
+
}
|
|
1671
|
+
function collectHistoryFromDiff(points, entityId, additions) {
|
|
1672
|
+
if (!isHistoryTracked(entityId)) return;
|
|
1673
|
+
const stateVal = additions.s ?? additions.state;
|
|
1674
|
+
if (stateVal === void 0) return;
|
|
1675
|
+
const lu = additions.lu ?? Date.now() / 1e3;
|
|
1676
|
+
const lc = additions.lc;
|
|
1677
|
+
const attributes = additions.a ?? additions.attributes ?? {};
|
|
1678
|
+
points.push({
|
|
1679
|
+
entityId,
|
|
1680
|
+
stateValue: stateVal,
|
|
1681
|
+
attributes,
|
|
1682
|
+
lastUpdated: lu,
|
|
1683
|
+
lastChanged: lc
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
function shallowEqualAttributes(existing, incoming) {
|
|
1687
|
+
const incomingKeys = Object.keys(incoming);
|
|
1688
|
+
for (const key of incomingKeys) if (existing[key] !== incoming[key]) return false;
|
|
1689
|
+
return true;
|
|
1690
|
+
}
|
|
1691
|
+
function applyCompressedState(s, entityId, compressed) {
|
|
1692
|
+
const stateVal = compressed.s ?? compressed.state ?? "unknown";
|
|
1693
|
+
const attributes = compressed.a ?? compressed.attributes ?? {};
|
|
1694
|
+
const context = compressed.c ?? compressed.context ?? {
|
|
1695
|
+
id: "",
|
|
1696
|
+
parent_id: null,
|
|
1697
|
+
user_id: null
|
|
1698
|
+
};
|
|
1699
|
+
const lastChanged = timestampToIso(compressed.lc ?? compressed.last_changed);
|
|
1700
|
+
const lastUpdated = timestampToIso(compressed.lu ?? compressed.last_updated);
|
|
1701
|
+
const existing = s.entities[entityId];
|
|
1702
|
+
if (existing) {
|
|
1703
|
+
const stateChanged = existing.state !== stateVal;
|
|
1704
|
+
const changedAt = existing.last_changed !== lastChanged;
|
|
1705
|
+
if (stateChanged) existing.state = stateVal;
|
|
1706
|
+
if (changedAt) existing.last_changed = lastChanged;
|
|
1707
|
+
if (stateChanged || changedAt) existing.last_updated = lastUpdated;
|
|
1708
|
+
if (!shallowEqualAttributes(existing.attributes, attributes)) Object.assign(existing.attributes, attributes);
|
|
1709
|
+
if (existing.context.id !== context.id) existing.context = context;
|
|
1710
|
+
} else s.entities[entityId] = {
|
|
1711
|
+
entity_id: entityId,
|
|
1712
|
+
state: stateVal,
|
|
1713
|
+
attributes,
|
|
1714
|
+
last_changed: lastChanged,
|
|
1715
|
+
last_updated: lastUpdated,
|
|
1716
|
+
context
|
|
1717
|
+
};
|
|
1718
|
+
}
|
|
1719
|
+
function applyStateDiff(s, entityId, diff) {
|
|
1720
|
+
const existing = s.entities[entityId];
|
|
1721
|
+
if (!existing) return;
|
|
1722
|
+
const additions = diff["+"];
|
|
1723
|
+
if (additions) {
|
|
1724
|
+
let stateChanged = false;
|
|
1725
|
+
if (additions.s !== void 0 && existing.state !== additions.s) {
|
|
1726
|
+
existing.state = additions.s;
|
|
1727
|
+
stateChanged = true;
|
|
1728
|
+
}
|
|
1729
|
+
if (additions.a) {
|
|
1730
|
+
for (const [key, value] of Object.entries(additions.a)) if (existing.attributes[key] !== value) {
|
|
1731
|
+
existing.attributes[key] = value;
|
|
1732
|
+
stateChanged = true;
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
if (additions.lc !== void 0) {
|
|
1736
|
+
const lcIso = timestampToIso(additions.lc);
|
|
1737
|
+
if (existing.last_changed !== lcIso) {
|
|
1738
|
+
existing.last_changed = lcIso;
|
|
1739
|
+
stateChanged = true;
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
if (additions.lu !== void 0 && stateChanged) existing.last_updated = timestampToIso(additions.lu);
|
|
1743
|
+
if (additions.c && existing.context.id !== additions.c.id) existing.context = additions.c;
|
|
1744
|
+
}
|
|
1745
|
+
const removals = diff["-"];
|
|
1746
|
+
if (removals?.a) for (const key of removals.a) delete existing.attributes[key];
|
|
1747
|
+
}
|
|
1748
|
+
//#endregion
|
|
1785
1749
|
//#region src/connection/bridged.ts
|
|
1786
1750
|
/**
|
|
1787
1751
|
* Wire an HA bridge (worker-backed connection) into the store. The bridge's
|