From bf759c72831c19992ffee657fabc8a8e6ed97ef4 Mon Sep 17 00:00:00 2001 From: Zoe Date: Sat, 23 Mar 2024 07:56:07 -0500 Subject: [PATCH] entity previous state --- package-lock.json | 4 ++-- package.json | 2 +- src/extensions/entity-manager.extension.ts | 19 +++++++++++++++++-- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 4ce7e84..4e48fea 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@digital-alchemy/hass", - "version": "0.3.3", + "version": "0.3.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@digital-alchemy/hass", - "version": "0.3.3", + "version": "0.3.5", "license": "MIT", "dependencies": { "@digital-alchemy/core": "^0.3.6", diff --git a/package.json b/package.json index 0b7bfa9..5e1fb39 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/extensions/entity-manager.extension.ts b/src/extensions/entity-manager.extension.ts index d12b18e..275d5b6 100644 --- a/src/extensions/entity-manager.extension.ts +++ b/src/extensions/entity-manager.extension.ts @@ -32,18 +32,28 @@ export type ByIdProxy = * Run callback */ onUpdate: ( - callback: (state: NonNullable>) => TBlackHole, + callback: ( + new_state: NonNullable>, + old_state: NonNullable>, + ) => TBlackHole, ) => void; /** * Run callback once, for next update */ once: ( - callback: (state: NonNullable>) => TBlackHole, + callback: ( + new_state: NonNullable>, + old_state: NonNullable>, + ) => TBlackHole, ) => void; /** * Will resolve with the next state of the next value. No time limit */ nextState: () => Promise>; + /** + * Access the immediate previous entity state + */ + previous: ENTITY_STATE; }; const MAX_ATTEMPTS = 50; @@ -65,6 +75,7 @@ export function EntityManager({ Record>> >; const ENTITY_PROXIES = new Map>(); + const PREVIOUS_STATE = new Map>(); let lastRefresh: Dayjs; // * Local event emitter for coordination of socket events @@ -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>(done => { event.once(entity_id, (entity: ENTITY_STATE) => @@ -285,6 +299,7 @@ export function EntityManager({ new_state: ENTITY_STATE, old_state: ENTITY_STATE, ) { + PREVIOUS_STATE.set(entity_id, old_state); if (new_state === null) { logger.warn( { name: EntityUpdateReceiver },