Trigger an EntityUpdateEvent when an entity state changes

This commit is contained in:
Fabio Manganiello 2022-04-07 01:46:37 +02:00
parent 44707731a8
commit 28026b0428
Signed by: blacklight
GPG key ID: D90FBA7F76362774
2 changed files with 25 additions and 0 deletions

View file

@ -7,6 +7,9 @@ from typing import Iterable, List
from sqlalchemy import and_, or_
from sqlalchemy.orm import Session
from platypush.context import get_bus
from platypush.message.event.entities import EntityUpdateEvent
from ._base import Entity
@ -130,3 +133,6 @@ class EntitiesEngine(Thread):
entities = self._merge_entities(entities, existing_entities) # type: ignore
session.add_all(entities)
session.commit()
for entity in entities:
get_bus().post(EntityUpdateEvent(entity=entity))

View file

@ -0,0 +1,19 @@
from typing import Union
from platypush.entities import Entity
from platypush.message.event import Event
class EntityUpdateEvent(Event):
"""
This even is triggered whenever an entity of any type (a switch, a light,
a sensor, a media player etc.) updates its state.
"""
def __init__(self, entity: Union[Entity, dict], *args, **kwargs):
if isinstance(entity, Entity):
entity = entity.to_json()
super().__init__(entity=entity, *args, **kwargs)
# vim:sw=4:ts=4:et: