Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,29 @@ await coll.refresh();
coll.subscribe((states) => console.log(states));
```

Both `entityStatesColl` and `subscribeEntityStates` accept an optional `options` argument with `throttleUpdates` (opt-in; defaults to `false`). Options apply when the collection is first created. When enabled, entity state updates are coalesced in place on the store while subscriber notifications adaptively throttle based on measured publish and paint cost, fast-pathing user actions (matching `userId` or recent `call_service` entity targets) and deferring notifications while the tab is hidden.

```javascript
import {
subscribeEntityStates,
flushEntityStates,
} from "home-assistant-js-websocket";

subscribeEntityStates(conn, (states) => console.log("New states!", states), {
throttleUpdates: {
userId: () => currentUserId,
// targetDutyCycle: 0.12,
// minIntervalMs: 16,
// maxIntervalMs: 1000,
// snapshotThresholdMsPer1k: 4.0,
// pauseWhenHidden: true,
},
});

// Flush any pending throttled updates immediately if needed.
flushEntityStates(conn);
```

### Config

You can subscribe to the config of Home Assistant. Config can change when either a component gets loaded.
Expand Down
4 changes: 4 additions & 0 deletions lib/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import { HassEvent, MessageBase } from "./types.js";
import { HaWebSocket } from "./socket.js";
import type { Auth } from "./auth.js";
import { notifyServiceCall } from "./util.js";

const DEBUG = false;

Expand Down Expand Up @@ -320,6 +321,9 @@ export class Connection {
message.id = commandId;

this.socket!.send(JSON.stringify(message));
if (message.type === "call_service") {
notifyServiceCall(this, message);
}
}

sendMessagePromise<Result>(message: MessageBase): Promise<Result> {
Expand Down
143 changes: 114 additions & 29 deletions lib/states.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,19 @@ import { Connection } from "./connection.js";
import { Store } from "./store.js";
import { getStates } from "./commands.js";
import { atLeastHaVersion } from "./util.js";
import {
createStateUpdateThrottler,
ResolvedThrottleOptions,
resolveThrottleOptions,
throttleOptionsEqual,
ThrottleUpdatesOptions,
} from "./throttle.js";

export type { ThrottleUpdatesOptions };

export type EntityStatesCollectionOptions = {
throttleUpdates?: boolean | ThrottleUpdatesOptions;
};

interface EntityState {
/** state */
Expand Down Expand Up @@ -41,16 +54,10 @@ interface StatesUpdates {
/** remove */
r?: string[]; // remove
/** change */
c: Record<string, EntityDiff>;
c?: Record<string, EntityDiff>;
}

function processEvent(
store: Store<HassEntityStates>,
updates: StatesUpdates,
replace: boolean,
) {
const state = replace ? {} : { ...store.state };

function applyUpdates(state: HassEntityStates, updates: StatesUpdates) {
if (updates.a) {
for (const entityId in updates.a) {
const newState = updates.a[entityId];
Expand Down Expand Up @@ -127,38 +134,84 @@ function processEvent(
state[entityId] = entityState;
}
}

store.setState(state, true);
}

const activeFlushers = new WeakMap<Connection, () => void>();

export const flushEntityStates = (conn: Connection): void => {
activeFlushers.get(conn)?.();
};

const subscribeUpdates = async (
conn: Connection,
store: Store<HassEntityStates>,
throttleOptions?: ResolvedThrottleOptions,
) => {
let replace = true;
const markReplace = () => {
replace = true;
if (!throttleOptions) {
let replace = true;
const markReplace = () => {
replace = true;
};

conn.addEventListener("ready", markReplace);

try {
const unsub = await conn.subscribeMessage<StatesUpdates>(
(ev) => {
const state = replace ? {} : { ...store.state };
applyUpdates(state, ev);
replace = false;
store.setState(state, true);
},
{
type: "subscribe_entities",
},
);

return () => {
conn.removeEventListener("ready", markReplace);
void unsub();
};
} catch (err) {
conn.removeEventListener("ready", markReplace);
throw err;
}
}

const throttler = createStateUpdateThrottler(
conn,
store,
throttleOptions,
applyUpdates,
);
const markReplace = () => throttler.markReplace();
const flush = () => throttler.flush();

const cleanup = () => {
conn.removeEventListener("ready", markReplace);
if (activeFlushers.get(conn) === flush) {
activeFlushers.delete(conn);
}
throttler.destroy();
};

activeFlushers.set(conn, flush);
conn.addEventListener("ready", markReplace);

try {
const unsub = await conn.subscribeMessage<StatesUpdates>(
(ev) => {
processEvent(store, ev, replace);
replace = false;
},
(ev) => throttler.handleEvent(ev),
{
type: "subscribe_entities",
},
);

return () => {
conn.removeEventListener("ready", markReplace);
cleanup();
void unsub();
};
} catch (err) {
conn.removeEventListener("ready", markReplace);
cleanup();
throw err;
}
};
Expand Down Expand Up @@ -201,20 +254,52 @@ const legacySubscribeUpdates = (
"state_changed",
);

export const entityStatesColl = (conn: Connection) =>
atLeastHaVersion(conn.haVersion, 2022, 4, 0)
? getCollection(conn, "_ent", undefined, subscribeUpdates)
: getCollection(
conn,
"_ent",
legacyFetchEntityStates,
legacySubscribeUpdates,
);
const createdWithThrottleUpdates = new WeakMap<
object,
ResolvedThrottleOptions | false
>();

export const entityStatesColl = (
conn: Connection,
options?: EntityStatesCollectionOptions,
) => {
if (!atLeastHaVersion(conn.haVersion, 2022, 4, 0)) {
return getCollection(
Comment on lines +266 to +267
conn,
"_ent",
legacyFetchEntityStates,
legacySubscribeUpdates,
);
}
const throttleOptions = resolveThrottleOptions(options?.throttleUpdates);
const storedOption: ResolvedThrottleOptions | false =
throttleOptions ?? false;
const exists = Boolean((conn as unknown as Record<string, unknown>)._ent);
const coll = getCollection<HassEntityStates>(
conn,
"_ent",
undefined,
(conn, store) => subscribeUpdates(conn, store, throttleOptions),
);
if (!exists) {
createdWithThrottleUpdates.set(coll, storedOption);
} else if (
options?.throttleUpdates !== undefined &&
createdWithThrottleUpdates.has(coll) &&
!throttleOptionsEqual(createdWithThrottleUpdates.get(coll)!, storedOption)
) {
console.warn(
"Entity states collection already exists with different throttleUpdates options, ignoring new throttleUpdates option",
);
}
return coll;
};

export const subscribeEntityStates = (
conn: Connection,
onChange: (state: HassEntityStates) => void,
): UnsubscribeFunc => entityStatesColl(conn).subscribe(onChange);
options?: EntityStatesCollectionOptions,
): UnsubscribeFunc => entityStatesColl(conn, options).subscribe(onChange);

/** @deprecated Use entityStatesColl */
export const entitiesColl = entityStatesColl;
Expand Down
18 changes: 15 additions & 3 deletions lib/store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { UnsubscribeFunc } from "./types.js";
import { notifyStoreStateRead } from "./util.js";

// (c) Jason Miller
// Unistore - MIT license
Expand All @@ -14,7 +15,7 @@ type BoundAction<State> = (...args: any[]) => void;
export type Store<State> = {
state: State | undefined;
action(action: Action<State>): BoundAction<State>;
setState(update: Partial<State>, overwrite?: boolean): void;
setState(update: Partial<State>, overwrite?: boolean, notify?: boolean): void;
clearState(): void;
subscribe(listener: Listener<State>): UnsubscribeFunc;
};
Expand All @@ -34,8 +35,15 @@ export const createStore = <State>(state?: State): Store<State> => {
listeners = out;
}

function setState(update: Partial<State>, overwrite: boolean): void {
function setState(
update: Partial<State>,
overwrite = false,
notify = true,
): void {
state = overwrite ? (update as State) : { ...state!, ...update };
if (!notify) {
return;
}
let currentListeners = listeners;
for (let i = 0; i < currentListeners.length; i++) {
currentListeners[i](state);
Expand All @@ -47,8 +55,9 @@ export const createStore = <State>(state?: State): Store<State> => {
* @name store
*/

return {
const store: Store<State> = {
get state() {
notifyStoreStateRead(store);
return state;
},

Expand Down Expand Up @@ -80,6 +89,7 @@ export const createStore = <State>(state?: State): Store<State> => {
* Apply a partial state object to the current state, invoking registered listeners.
* @param {Object} update An object with properties to be merged into state
* @param {Boolean} [overwrite=false] If `true`, update will replace state instead of being merged into it
* @param {Boolean} [notify=true] If `false`, listeners are not called
*/
setState,

Expand All @@ -106,4 +116,6 @@ export const createStore = <State>(state?: State): Store<State> => {
// */
// unsubscribe,
};

return store;
};
Loading