Skip to content

Commit

Permalink
entity previous state
Browse files Browse the repository at this point in the history
  • Loading branch information
Zoe committed Mar 23, 2024
1 parent a7aab9b commit bf759c7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "@digital-alchemy/hass",
"repository": "https://github.com/Digital-Alchemy-TS/hass",
"homepage": "https://docs.digital-alchemy.app/Hass",
"version": "0.3.4",
"version": "0.3.5",
"scripts": {
"build": "rm -rf dist/; tsc",
"lint": "eslint src",
Expand Down
19 changes: 17 additions & 2 deletions src/extensions/entity-manager.extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,28 @@ export type ByIdProxy<ENTITY_ID extends PICK_ENTITY> =
* Run callback
*/
onUpdate: (
callback: (state: NonNullable<ENTITY_STATE<ENTITY_ID>>) => TBlackHole,
callback: (
new_state: NonNullable<ENTITY_STATE<ENTITY_ID>>,
old_state: NonNullable<ENTITY_STATE<ENTITY_ID>>,
) => TBlackHole,
) => void;
/**
* Run callback once, for next update
*/
once: (
callback: (state: NonNullable<ENTITY_STATE<ENTITY_ID>>) => TBlackHole,
callback: (
new_state: NonNullable<ENTITY_STATE<ENTITY_ID>>,
old_state: NonNullable<ENTITY_STATE<ENTITY_ID>>,
) => TBlackHole,
) => void;
/**
* Will resolve with the next state of the next value. No time limit
*/
nextState: () => Promise<ENTITY_STATE<ENTITY_ID>>;
/**
* Access the immediate previous entity state
*/
previous: ENTITY_STATE<ENTITY_ID>;
};

const MAX_ATTEMPTS = 50;
Expand All @@ -65,6 +75,7 @@ export function EntityManager({
Record<ALL_DOMAINS, Record<string, ENTITY_STATE<PICK_ENTITY>>>
>;
const ENTITY_PROXIES = new Map<PICK_ENTITY, ByIdProxy<PICK_ENTITY>>();
const PREVIOUS_STATE = new Map<PICK_ENTITY, ENTITY_STATE<PICK_ENTITY>>();
let lastRefresh: Dayjs;

// * Local event emitter for coordination of socket events
Expand Down Expand Up @@ -136,6 +147,9 @@ export function EntityManager({
if (property === "entity_id") {
return entity_id;
}
if (property === "previous") {
return PREVIOUS_STATE.get(entity_id);
}
if (property === "nextState") {
return new Promise<ENTITY_STATE<ENTITY_ID>>(done => {
event.once(entity_id, (entity: ENTITY_STATE<ENTITY_ID>) =>
Expand Down Expand Up @@ -285,6 +299,7 @@ export function EntityManager({
new_state: ENTITY_STATE<ENTITY>,
old_state: ENTITY_STATE<ENTITY>,
) {
PREVIOUS_STATE.set(entity_id, old_state);
if (new_state === null) {
logger.warn(
{ name: EntityUpdateReceiver },
Expand Down

0 comments on commit bf759c7

Please sign in to comment.