1 | import { getCollection } from "./collection.js";
|
2 | import { getStates } from "./commands.js";
|
3 | function processEvent(store, event) {
|
4 | const state = store.state;
|
5 | if (state === undefined)
|
6 | return;
|
7 | const { entity_id, new_state } = event.data;
|
8 | if (new_state) {
|
9 | store.setState({ [new_state.entity_id]: new_state });
|
10 | }
|
11 | else {
|
12 | const newEntities = Object.assign({}, state);
|
13 | delete newEntities[entity_id];
|
14 | store.setState(newEntities, true);
|
15 | }
|
16 | }
|
17 | async function fetchEntities(conn) {
|
18 | const states = await getStates(conn);
|
19 | const entities = {};
|
20 | for (let i = 0; i < states.length; i++) {
|
21 | const state = states[i];
|
22 | entities[state.entity_id] = state;
|
23 | }
|
24 | return entities;
|
25 | }
|
26 | const subscribeUpdates = (conn, store) => conn.subscribeEvents(ev => processEvent(store, ev), "state_changed");
|
27 | export const entitiesColl = (conn) => getCollection(conn, "_ent", fetchEntities, subscribeUpdates);
|
28 | export const subscribeEntities = (conn, onChange) => entitiesColl(conn).subscribe(onChange);
|