Skip to content

Home Information - Your home, your data, organized.

Python

Refactored SensorResponseManager to keep last 'N' responses.

Anthony Cassandra3fe55937e9b3
diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.py
index fad67770..85f36ee9 100644
--- a/src/hi/apps/entity/entity_manager.py
+++ b/src/hi/apps/entity/entity_manager.py
@@ -37,7 +37,7 @@ class EntityManager(Singleton):
entity : Entity,
is_editing : bool ) -> EntityDetailsData:
entity_edit_data = EntityEditData( entity = entity )
- sensor_response_map = SensorResponseManager().get_entity_latest_sensor_responses( entity = entity )
+ sensor_response_list_map = SensorResponseManager().get_entity_latest_sensor_responses( entity = entity )
entity_state_list = list(
entity.states.all()
@@ -50,7 +50,7 @@ class EntityManager(Singleton):
return EntityInfoData(
entity_edit_data = entity_edit_data,
- sensor_response_map = sensor_response_map,
+ sensor_response_list_map = sensor_response_list_map,
entity_state_list = entity_state_list,
principal_state_list = principal_state_list,
principal_entity_list = principal_entity_list,
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_info.html b/src/hi/apps/entity/templates/entity/modals/entity_info.html
index 8285656b..65e6b3ec 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_info.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_info.html
@@ -8,8 +8,14 @@
<h5>Sensor Responses</h5>
<ul>
- {% for sensor, sensor_response in sensor_response_map.items %}
- <li>Sensor: {{ sensor.name }}, Response: {{ sensor_response.value }}</li>
+ {% for sensor, sensor_response_list in sensor_response_list_map.items %}
+ <li>Sensor: {{ sensor.name }}
+ <ul>
+ {% for sensor_response in sensor_response_list %}
+ <li>Response: {{ sensor_response.value }} [{{ sensor_response.timestamp }}]</li>
+ {% endfor %}
+ </ul>
+ </li>
{% empty %}
<div><em>No sensors</em></div>
{% endfor %}
diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.py
index d8f94de4..1def5d64 100644
--- a/src/hi/apps/entity/transient_models.py
+++ b/src/hi/apps/entity/transient_models.py
@@ -72,11 +72,11 @@ class EntityEditData:
class EntityInfoData:
""" All the data needed to render the Entity info modal. """
- entity_edit_data : EntityEditData
- sensor_response_map : Dict[ Sensor, SensorResponse ]
- entity_state_list : List[ EntityState ]
- principal_state_list : List[ EntityState ]
- principal_entity_list : List[ Entity ]
+ entity_edit_data : EntityEditData
+ sensor_response_list_map : Dict[ Sensor, List[ SensorResponse ] ]
+ entity_state_list : List[ EntityState ]
+ principal_state_list : List[ EntityState ]
+ principal_entity_list : List[ Entity ]
@property
def entity(self):
@@ -85,7 +85,7 @@ class EntityInfoData:
def to_template_context(self):
context = {
'entity': self.entity,
- 'sensor_response_map': self.sensor_response_map,
+ 'sensor_response_list_map': self.sensor_response_list_map,
'entity_state_list': self.entity_state_list,
'principal_state_list': self.principal_state_list,
'principal_entity_list': self.principal_entity_list,
diff --git a/src/hi/apps/location/status_display_helper.py b/src/hi/apps/location/status_display_helper.py
index 912fe731..09ee0ac7 100644
--- a/src/hi/apps/location/status_display_helper.py
+++ b/src/hi/apps/location/status_display_helper.py
@@ -3,8 +3,6 @@ from typing import Dict, List, Set
from hi.apps.entity.enums import EntityStateType
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.sensor_response_manager import SensorResponseManager
-from hi.apps.sense.models import Sensor
-from hi.apps.sense.transient_models import SensorResponse
from .enums import StatusDisplayType
from .models import LocationView
@@ -16,7 +14,7 @@ class StatusDisplayLocationHelper:
def __init__( self, location_view : LocationView ):
self._status_display_type = location_view.status_display_type
self._entity_state_type_priority_list = self._status_display_type.entity_state_type_priority_list
- self._latest_sensor_response_map = SensorResponseManager().get_all_latest_sensor_responses()
+ self._latest_sensor_response_list_map = SensorResponseManager().get_all_latest_sensor_responses()
return
def get_status_display_data_map(
@@ -38,8 +36,13 @@ class StatusDisplayLocationHelper:
def get_status_display_data( self, entity : Entity ) -> StatusDisplayData:
entity_state_list = list( entity.states.all() )
+
+ # Delegate entities include all their principal entity states as well.
+ entity_state_delegations = entity.entity_state_delegations.select_related('entity_state').all()
+ entity_state_list.extend([ x.entity_state for x in entity_state_delegations ])
if not entity_state_list:
return None
+
entity_state_type_for_status = self._get_entity_state_type_for_status(
entity_state_list = entity_state_list,
)
@@ -54,12 +57,12 @@ class StatusDisplayLocationHelper:
if entity_state.entity_state_type == entity_state_type_for_status:
sensors_for_status.update( entity_state.sensors.all() )
continue
-
+
sensor_response_list = list()
for sensor in sensors_for_status:
- sensor_response = self._latest_sensor_response_map.get( sensor.integration_key )
- if sensor_response:
- sensor_response_list.append( sensor_response )
+ sensor_response_list = self._latest_sensor_response_list_map.get( sensor.integration_key )
+ if sensor_response_list:
+ sensor_response_list.append( sensor_response_list[0] )
continue
if not sensor_response_list:
diff --git a/src/hi/apps/sense/enums.py b/src/hi/apps/sense/enums.py
index 19307b7e..cf582300 100644
--- a/src/hi/apps/sense/enums.py
+++ b/src/hi/apps/sense/enums.py
@@ -14,3 +14,5 @@ class SensorValue(LabeledEnum):
BINARY_ON = ( 'On', '' )
BINARY_OFF = ( 'Off', '' )
+ OPEN = ( 'Open', '' )
+ CLOSE = ( 'Close', '' )
diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.py
index 1b901271..f42741e5 100644
--- a/src/hi/apps/sense/sensor_response_manager.py
+++ b/src/hi/apps/sense/sensor_response_manager.py
@@ -14,19 +14,31 @@ logger = logging.getLogger(__name__)
class SensorResponseManager( Singleton ):
- """
- Integrations are responsible for monitoring sensor values and
+ """Integrations are responsible for monitoring sensor values and
normalizing them into SensorResponse objects. This module take it from
- there to store these for tracking the latest state and sensor history.
- i.e., Integrations should be using this module to submit sensor
- values changes.
+ there to store these for tracking the latest state. i.e., Integrations
+ should be using this module to submit sensor values changes.
N.B., Since the cached sensor responses are updated and fetched very
frequently, a design principle of this module is to avoid any database
queries.
+
+ Caching Strategy:
+
+ - For each sensor, we will cache the latest 'N' sensor responses in a
+ Redis list (using LPUSH and LTRIM list Redis functions).
+
+ - Then lists' cache keys are baseon the sensor's integration key.
+
+ - We will keep all the list cache keys in a Redis set so that we can
+ easily fetch them all without needing to know all the integration
+ keys (using the SADD and SMEMBERS Redis functions).
+
"""
+ SENSOR_RESPONSE_LIST_SIZE = 5
+ SENSOR_RESPONSE_LIST_KEYS = 'hi.sr.list.keys'
- LATEST_SENSOR_RESPONSE_HASH_NAME = 'hi.sr.all' # Name of redis cache grouping
+ zzzLATEST_SENSOR_RESPONSE_HASH_NAME = 'hi.sr.all' # Name of redis cache grouping
def __init_singleton__( self ):
self._redis_client = get_redis_client()
@@ -36,10 +48,20 @@ class SensorResponseManager( Singleton ):
def add_latest_sensor_responses( self, sensor_response_list : List[ SensorResponse ] ):
if not sensor_response_list:
return
-
- cached_set = { self.to_sensor_value_cache_key(x.integration_key): str(x)
- for x in sensor_response_list }
- self._redis_client.hset( self.LATEST_SENSOR_RESPONSE_HASH_NAME, mapping = cached_set )
+
+ pipeline = self._redis_client.pipeline()
+ for sensor_response in sensor_response_list:
+ list_cache_key = self.to_sensor_value_cache_key( sensor_response.integration_key )
+ cache_value = str(sensor_response)
+ pipeline.lpush( list_cache_key, cache_value )
+ pipeline.ltrim( list_cache_key, 0, self.SENSOR_RESPONSE_LIST_SIZE - 1 )
+ pipeline.sadd( self.SENSOR_RESPONSE_LIST_KEYS, list_cache_key )
+ continue
+ pipeline.execute()
+
+ self._sensor_history_manager.add_to_sensor_response_history(
+ sensor_response_list = sensor_response_list,
+ )
return
def update_with_latest_sensor_responses( self,
@@ -56,7 +78,13 @@ class SensorResponseManager( Singleton ):
cache_keys = [ self.to_sensor_value_cache_key(x) for x in sensor_response_map.keys() ]
integration_keys = list( sensor_response_map.keys() )
- cached_values = self._redis_client.hmget( self.LATEST_SENSOR_RESPONSE_HASH_NAME, cache_keys )
+
+ pipeline = self._redis_client.pipeline()
+ for list_cache_key in cache_keys:
+ pipeline.lindex( list_cache_key, 0 )
+ continue
+ cached_values = pipeline.execute()
+
for integration_key, cached_value in zip( integration_keys, cached_values ):
latest_sensor_response = sensor_response_map.get( integration_key )
if cached_value:
@@ -67,33 +95,59 @@ class SensorResponseManager( Singleton ):
changed_sensor_response_list.append( latest_sensor_response )
continue
- self._sensor_history_manager.add_to_sensor_response_history( changed_sensor_response_list )
self.add_latest_sensor_responses( changed_sensor_response_list )
logger.debug( f'Sensor changed: {len(changed_sensor_response_list)} of {len(sensor_response_map)}' )
return
- def get_all_latest_sensor_responses( self ) -> Dict[ IntegrationKey, SensorResponse ]:
- key_to_sensor_response_dict = self._redis_client.hgetall( self.LATEST_SENSOR_RESPONSE_HASH_NAME )
- key_to_sensor_response = { k: SensorResponse.from_string( v )
- for k, v in key_to_sensor_response_dict.items() }
- return { v.integration_key: v for k, v in key_to_sensor_response.items() }
+ def get_all_latest_sensor_responses( self ) -> Dict[ IntegrationKey, List[ SensorResponse ] ]:
+
+ list_cache_keys = self._redis_client.smembers( self.SENSOR_RESPONSE_LIST_KEYS )
- def get_entity_latest_sensor_responses( self, entity : Entity ) -> Dict[ Sensor, SensorResponse ]:
+ pipeline = self._redis_client.pipeline()
+ for list_cache_key in list_cache_keys:
+ pipeline.lrange( list_cache_key, 0, -1 )
+ continue
+ cached_list_list = pipeline.execute()
+
+ sensor_response_list_map = dict()
+ for cached_list in cached_list_list:
+ if not cached_list:
+ continue
+ sensor_response_list = [ SensorResponse.from_string( x ) for x in cached_list ]
+ integration_key = sensor_response_list[0].integration_key
+ sensor_response_list_map[integration_key] = sensor_response_list
+ continue
+
+ return sensor_response_list_map
+
+ def get_entity_latest_sensor_responses( self, entity : Entity ) -> Dict[ Sensor, List[ SensorResponse ] ]:
""" Maps all sensors to the latest response, but possibly 'None' if not latest response """
+
+ entity_state_list = list( entity.states.all() )
+ entity_state_delegations = entity.entity_state_delegations.select_related('entity_state').all()
+ entity_state_list.extend([ x.entity_state for x in entity_state_delegations ])
+
+ sensor_list = list()
+ for entity_state in entity_state_list:
+ sensor_list.extend( entity_state.sensors.all() )
+ continue
+
+ cache_keys = [ self.to_sensor_value_cache_key( x.integration_key ) for x in sensor_list ]
- sensor_response_map = dict()
- for entity_state in entity.states.all():
- for sensor in entity_state.sensors.all():
- cache_key = self.to_sensor_value_cache_key( sensor.integration_key )
- sensor_response_str = self._redis_client.hget( self.LATEST_SENSOR_RESPONSE_HASH_NAME,
- cache_key )
- sensor_response = SensorResponse.from_string( sensor_response_str )
- sensor_response_map[sensor] = sensor_response
- continue
+ pipeline = self._redis_client.pipeline()
+ for list_cache_key in cache_keys:
+ pipeline.lrange( list_cache_key, 0, -1 )
+ continue
+ cached_list_list = pipeline.execute()
+
+ sensor_response_list_map = dict()
+ for sensor, cached_list in zip( sensor_list, cached_list_list ):
+ sensor_response_list = [ SensorResponse.from_string( x ) for x in cached_list ]
+ sensor_response_list_map[sensor] = sensor_response_list
continue
- return sensor_response_map
+ return sensor_response_list_map
def to_sensor_value_cache_key( self, integration_key : IntegrationKey ) -> str:
- return f'hi.sr.{integration_key}'
+ return f'hi.sr.latest.{integration_key}'
diff --git a/src/hi/integrations/hass/hass_converter.py b/src/hi/integrations/hass/hass_converter.py
index 72a0259e..b0143521 100644
--- a/src/hi/integrations/hass/hass_converter.py
+++ b/src/hi/integrations/hass/hass_converter.py
@@ -400,7 +400,7 @@ class HassConverter:
integration_key = integration_key,
name = name,
)
- elif hass_state.device_class in HassApi.DOOR_DEVICE_CLASS_SET:
+ elif hass_state.device_class in HassApi.OPEN_CLOSE_DEVICE_CLASS_SET:
HiModelHelper.create_open_close_sensor(
entity = entity,
integration_key = integration_key,
@@ -467,7 +467,7 @@ class HassConverter:
if HassApi.TIMESTAMP_DEVICE_CLASS in device_class_set:
return EntityType.TIME_SOURCE
if ( HassApi.BINARY_SENSOR_ID_PREFIX in prefix_set
- and device_class_set.intersection( HassApi.DOOR_DEVICE_CLASS_SET )):
+ and device_class_set.intersection( HassApi.OPEN_CLOSE_DEVICE_CLASS_SET )):
return EntityType.OPEN_CLOSE_DETECTOR
if HassApi.MOTION_DEVICE_CLASS in device_class_set:
return EntityType.MOTION_SENSOR
@@ -515,12 +515,20 @@ class HassConverter:
return hass_state.state_value
elif hass_state.entity_id_prefix == HassApi.BINARY_SENSOR_ID_PREFIX:
+
if hass_state.state_value.lower() == 'on':
- return str(SensorValue.BINARY_ON)
+ if hass_state.device_class in HassApi.OPEN_CLOSE_DEVICE_CLASS_SET:
+ return str(SensorValue.OPEN)
+ else:
+ return str(SensorValue.BINARY_ON)
+
elif hass_state.state_value.lower() == 'off':
- return str(SensorValue.BINARY_OFF)
+ if hass_state.device_class in HassApi.OPEN_CLOSE_DEVICE_CLASS_SET:
+ return str(SensorValue.CLOSE)
+ else:
+ return str(SensorValue.BINARY_OFF)
else:
- logger.warning( f'Unknown HAss binary stae value "{hass_state.state_value}".' )
+ logger.warning( f'Unknown HAss binary state value "{hass_state.state_value}".' )
return None
elif hass_state.device_class == HassApi.TEMPERATURE_DEVICE_CLASS:
diff --git a/src/hi/integrations/hass/hass_models.py b/src/hi/integrations/hass/hass_models.py
index 4530b6c3..4a199d65 100644
--- a/src/hi/integrations/hass/hass_models.py
+++ b/src/hi/integrations/hass/hass_models.py
@@ -61,8 +61,11 @@ class HassApi:
OUTLET_DEVICE_CLASS = 'outlet'
TEMPERATURE_DEVICE_CLASS = 'temperature'
TIMESTAMP_DEVICE_CLASS = 'timestamp'
+ WINDOW_DEVICE_CLASS = 'window'
- DOOR_DEVICE_CLASS_SET = { DOOR_DEVICE_CLASS, GARAGE_DOOR_DEVICE_CLASS }
+ OPEN_CLOSE_DEVICE_CLASS_SET = { DOOR_DEVICE_CLASS,
+ GARAGE_DOOR_DEVICE_CLASS,
+ WINDOW_DEVICE_CLASS }
@dataclass
diff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.py
index e82769b6..736de3ad 100644
--- a/src/hi/integrations/zoneminder/zm_monitor.py
+++ b/src/hi/integrations/zoneminder/zm_monitor.py
@@ -81,32 +81,27 @@ class ZoneMinderMonitor( PeriodicMonitor ):
closed_zm_event_list.append( zm_event )
continue
- sensor_response_history_list = list()
- sensor_response_latest_list = list()
+ sensor_response_list = list()
+ for zm_event in open_zm_event_list:
+ if zm_event.event_id not in self._start_processed_event_ids:
+ active_sensor_response = self._create_movement_active_sensor_response( zm_event )
+ sensor_response_list.append( active_sensor_response )
+ self._start_processed_event_ids[zm_event.event_id] = True
+ continue
+
for zm_event in closed_zm_event_list:
if zm_event.event_id not in self._start_processed_event_ids:
active_sensor_response = self._create_movement_active_sensor_response( zm_event )
- sensor_response_history_list.append( active_sensor_response )
+ sensor_response_list.append( active_sensor_response )
idle_sensor_response = self._create_movement_idle_sensor_response( zm_event )
- sensor_response_history_list.append( idle_sensor_response )
- sensor_response_latest_list.append( idle_sensor_response )
+ sensor_response_list.append( idle_sensor_response )
self._fully_processed_event_ids[zm_event.event_id] = True
continue
- for zm_event in open_zm_event_list:
- if zm_event.event_id not in self._start_processed_event_ids:
- active_sensor_response = self._create_movement_active_sensor_response( zm_event )
- sensor_response_latest_list.append( active_sensor_response )
- self._start_processed_event_ids[zm_event.event_id] = True
- continue
-
- self._sensor_history_manager.add_to_sensor_response_history(
- sensor_response_list = sensor_response_history_list,
- )
self._sensor_response_manager.add_latest_sensor_responses(
- sensor_response_list = sensor_response_latest_list,
+ sensor_response_list = sensor_response_list,
)
if open_zm_event_list: