Skip to content

Home Information - Your home, your data, organized.

Python

Added querying state values plumbing to location views.

Anthony Cassandra2b95d7f5ace4
diff --git a/src/hi/apps/control/migrations/0002_controller_controller_integration_key.py b/src/hi/apps/control/migrations/0002_controller_controller_integration_key.py
new file mode 100644
index 00000000..122e2e45
--- /dev/null
+++ b/src/hi/apps/control/migrations/0002_controller_controller_integration_key.py
@@ -0,0 +1,20 @@
+# Generated by Django 4.2.15 on 2024-11-25 17:31
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("control", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.AddConstraint(
+ model_name="controller",
+ constraint=models.UniqueConstraint(
+ fields=("integration_id", "integration_name"),
+ name="controller_integration_key",
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/entity/migrations/0004_entity_entity_integration_key.py b/src/hi/apps/entity/migrations/0004_entity_entity_integration_key.py
new file mode 100644
index 00000000..2a070838
--- /dev/null
+++ b/src/hi/apps/entity/migrations/0004_entity_entity_integration_key.py
@@ -0,0 +1,20 @@
+# Generated by Django 4.2.15 on 2024-11-25 17:31
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("entity", "0003_entityattribute_file_mime_type_and_more"),
+ ]
+
+ operations = [
+ migrations.AddConstraint(
+ model_name="entity",
+ constraint=models.UniqueConstraint(
+ fields=("integration_id", "integration_name"),
+ name="entity_integration_key",
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/location/edit/async_views.py b/src/hi/apps/location/edit/async_views.py
index 26edac88..bc2e949e 100644
--- a/src/hi/apps/location/edit/async_views.py
+++ b/src/hi/apps/location/edit/async_views.py
@@ -231,6 +231,7 @@ class LocationViewEntityToggleView( View, LocationViewMixin ):
location_view_data = LocationManager().get_location_view_data(
location_view = location_view,
+ include_status_display_data = bool( not request.is_editing ),
)
context = {
'location_view_data': location_view_data,
@@ -279,6 +280,7 @@ class LocationViewCollectionToggleView( View, LocationViewMixin ):
location_view_data = LocationManager().get_location_view_data(
location_view = location_view,
+ include_status_display_data = bool( not request.is_editing ),
)
context = {
'location_view_data': location_view_data,
diff --git a/src/hi/apps/location/enums.py b/src/hi/apps/location/enums.py
index bde8c239..b44ce8e7 100644
--- a/src/hi/apps/location/enums.py
+++ b/src/hi/apps/location/enums.py
@@ -1,4 +1,7 @@
+from typing import List
+
from hi.apps.common.enums import LabeledEnum
+from hi.apps.entity.enums import EntityStateType
class LocationViewType(LabeledEnum):
@@ -26,3 +29,78 @@ class SvgItemType(LabeledEnum):
return bool( self == SvgItemType.CLOSED_PATH )
+class StatusDisplayType(LabeledEnum):
+
+ def __init__( self,
+ label : str,
+ description : str,
+ entity_state_type_priority_list : List[ EntityStateType ] ):
+ super().__init__( label, description )
+ self.entity_state_type_priority_list = entity_state_type_priority_list
+ return
+
+ DEFAULT = (
+ 'Default',
+ '',
+ [ EntityStateType.MOVEMENT,
+ EntityStateType.PRESENCE,
+ EntityStateType.OPEN_CLOSE,
+ EntityStateType.LIGHT_LEVEL,
+ EntityStateType.SOUND_LEVEL,
+ EntityStateType.TEMPERATURE,
+ EntityStateType.HIGH_LOW,
+ EntityStateType.HUMIDITY,
+ EntityStateType.MOISTURE,
+ EntityStateType.WIND_SPEED,
+ EntityStateType.AIR_PRESSURE,
+ EntityStateType.ELECTRIC_USAGE,
+ EntityStateType.WATER_FLOW,
+ EntityStateType.HIGH_LOW,
+ ],
+
+ )
+ SECURITY = (
+ 'Security',
+ '',
+ [ EntityStateType.MOVEMENT,
+ EntityStateType.PRESENCE,
+ EntityStateType.OPEN_CLOSE,
+ ],
+ )
+ LIGHT = (
+ 'Light',
+ '',
+ [ EntityStateType.LIGHT_LEVEL,
+ ],
+ )
+ SOUND = (
+ 'Sound',
+ '',
+ [ EntityStateType.SOUND_LEVEL,
+ ],
+ )
+ CLIMATE = (
+ 'Climate',
+ '',
+ [ EntityStateType.TEMPERATURE,
+ EntityStateType.HIGH_LOW,
+ EntityStateType.HUMIDITY,
+ EntityStateType.MOISTURE,
+ EntityStateType.WIND_SPEED,
+ EntityStateType.AIR_PRESSURE,
+ ],
+ )
+ ENERGY = (
+ 'Energy',
+ '',
+ [ EntityStateType.ELECTRIC_USAGE,
+ EntityStateType.WATER_FLOW,
+ EntityStateType.HIGH_LOW,
+ ],
+ )
+ SUPPRESS = (
+ 'Suppress',
+ '',
+ [],
+ )
+
diff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.py
index 8f7722ac..bb4027a0 100644
--- a/src/hi/apps/location/location_manager.py
+++ b/src/hi/apps/location/location_manager.py
@@ -10,6 +10,7 @@ from hi.apps.common.singleton import Singleton
from hi.apps.common.svg_models import SvgViewBox
from .enums import LocationViewType
+from .status_display_helper import StatusDisplayHelper
from .transient_models import LocationViewData
from .models import (
Location,
@@ -152,23 +153,28 @@ class LocationManager(Singleton):
return location_view
- def get_location_view_data( self, location_view : LocationView ):
+ def get_location_view_data( self,
+ location_view : LocationView,
+ include_status_display_data : bool ):
location = location_view.location
entity_positions = list()
entity_paths = list()
+ displayed_entities = set()
non_displayed_entities = set()
- for entity_view in location_view.entity_views.all():
+ for entity_view in location_view.entity_views.select_related('entity').all():
entity = entity_view.entity
is_visible = False
entity_position = entity.positions.filter( location = location ).first()
if entity_position:
is_visible = True
entity_positions.append( entity_position )
+ displayed_entities.add( entity )
entity_path = entity.paths.filter( location = location ).first()
if entity_path:
is_visible = True
entity_paths.append( entity_path )
+ displayed_entities.add( entity )
if not is_visible:
non_displayed_entities.add( entity )
continue
@@ -176,7 +182,7 @@ class LocationManager(Singleton):
collection_positions = list()
collection_paths = list()
unpositioned_collections = list()
- for collection_view in location_view.collection_views.all():
+ for collection_view in location_view.collection_views.select_related('collection').all():
collection = collection_view.collection
collection_position = collection.positions.filter( location = location ).first()
if collection_position:
@@ -201,6 +207,14 @@ class LocationManager(Singleton):
# These become bottom buttons, which can be ordered
unpositioned_collections.sort( key = lambda item : item.order_id )
+ if include_status_display_data:
+ status_display_helper = StatusDisplayHelper( location_view = location_view )
+ status_display_data_map = status_display_helper.get_status_display_data_map(
+ displayed_entities = displayed_entities,
+ )
+ else:
+ status_display_data_map = dict()
+
return LocationViewData(
location_view = location_view,
entity_positions = entity_positions,
@@ -209,6 +223,7 @@ class LocationManager(Singleton):
collection_paths = collection_paths,
unpositioned_collections = unpositioned_collections,
orphan_entities = orphan_entities,
+ status_display_data_map = status_display_data_map,
)
def set_location_view_order( self, location_view_id_list : List[int] ):
diff --git a/src/hi/apps/location/migrations/0005_locationview_status_display_type_str.py b/src/hi/apps/location/migrations/0005_locationview_status_display_type_str.py
new file mode 100644
index 00000000..a6503f0d
--- /dev/null
+++ b/src/hi/apps/location/migrations/0005_locationview_status_display_type_str.py
@@ -0,0 +1,20 @@
+# Generated by Django 4.2.15 on 2024-11-25 17:31
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("location", "0004_locationattribute_file_mime_type_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="locationview",
+ name="status_display_type_str",
+ field=models.CharField(
+ default="default", max_length=32, verbose_name="Status Display Type"
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/location/models.py b/src/hi/apps/location/models.py
index 2cbee765..bf2f00ba 100644
--- a/src/hi/apps/location/models.py
+++ b/src/hi/apps/location/models.py
@@ -8,7 +8,7 @@ from hi.apps.attribute.models import AttributeModel
from hi.enums import ItemType
from hi.models import ItemTypeModelMixin
-from .enums import LocationViewType
+from .enums import LocationViewType, StatusDisplayType
logger = logging.getLogger(__name__)
@@ -144,6 +144,12 @@ class LocationView( models.Model, ItemTypeModelMixin ):
'Order Id',
default = 0,
)
+ status_display_type_str = models.CharField(
+ 'Status Display Type',
+ max_length = 32,
+ default = StatusDisplayType.default_value(),
+ null = False, blank = False,
+ )
created_datetime = models.DateTimeField(
'Created',
auto_now_add = True,
@@ -186,8 +192,17 @@ class LocationView( models.Model, ItemTypeModelMixin ):
def svg_view_box( self, svg_view_box : SvgViewBox ):
self.svg_view_box_str = str(svg_view_box)
return
-
+ @property
+ def status_display_type(self) -> StatusDisplayType:
+ return StatusDisplayType.from_name_safe( self.status_display_type_str )
+
+ @status_display_type.setter
+ def status_display_type( self, status_display_type : StatusDisplayType ):
+ self.status_display_type_str = str(status_display_type)
+ return
+
+
class LocationItemModelMixin( ItemTypeModelMixin ):
# A Location Item is a model that can be associated with a Location
# and that can visually appeay in one or more Location Views. This
diff --git a/src/hi/apps/location/status_display_helper.py b/src/hi/apps/location/status_display_helper.py
new file mode 100644
index 00000000..813699ba
--- /dev/null
+++ b/src/hi/apps/location/status_display_helper.py
@@ -0,0 +1,92 @@
+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 .enums import StatusDisplayType
+from .models import LocationView
+from .transient_models import StatusDisplayData
+
+
+class StatusDisplayHelper:
+
+ 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_latest_sensor_responses()
+ return
+
+ def get_status_display_data_map(
+ self,
+ displayed_entities : Set[ Entity ] ) -> Dict[ Entity, StatusDisplayData ]:
+ if self._status_display_type == StatusDisplayType.SUPPRESS:
+ return dict()
+
+ entity_to_status_display_data = dict()
+ for entity in displayed_entities:
+ status_display_data = self.get_status_display_data( entity = entity )
+ if not status_display_data:
+ continue
+ entity_to_status_display_data[entity] = status_display_data
+ continue
+
+ return entity_to_status_display_data
+
+ def get_status_display_data( self, entity : Entity ) -> StatusDisplayData:
+
+ entity_state_list = list( entity.states.all() )
+ 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,
+ )
+
+ # N.B. An entity is not limited to a single EntityState per
+ # EntityStateType, nor is a single EnttyStateType limited to a
+ # single sensor. In the (rare) cases there are multiples of these,
+ # we will always use the most recent sensor response.
+
+ sensors_for_status = set()
+ for entity_state in entity_state_list:
+ 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 )
+ continue
+
+ if not sensor_response_list:
+ return None
+
+ sensor_response_list.sort( key = lambda item: item.timestamp, reverse = True )
+ sensors_response_for_status = sensor_response_list[0]
+
+ return StatusDisplayData(
+ entity = entity,
+ sensor_response = sensors_response_for_status,
+ )
+
+ def _get_entity_state_type_for_status( self, entity_state_list : List[ EntityState ] ) -> EntityStateType:
+ entity_state_type_list = [ x.entity_state_type for x in entity_state_list ]
+
+ for priority_entity_state_type in self._entity_state_type_priority_list:
+ if priority_entity_state_type in entity_state_type_list:
+ return priority_entity_state_type
+ continue
+
+ # If no prioritizes state type matches, then fallback to an
+ # arbitrary, but deterministic choice by using all defined values.
+ #
+ for default_entity_state_type in EntityStateType:
+ if default_entity_state_type in entity_state_type_list:
+ return default_entity_state_type
+ continue
+
+ # This code should not really be reachable. Should always match one in fallback case.
+ return None
+
diff --git a/src/hi/apps/location/transient_models.py b/src/hi/apps/location/transient_models.py
index 75b3b056..830af95e 100644
--- a/src/hi/apps/location/transient_models.py
+++ b/src/hi/apps/location/transient_models.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass
-from typing import Generator, List, Set
+from typing import Dict, Generator, List, Set
from hi.apps.collection.models import Collection, CollectionPath, CollectionPosition
from hi.apps.common.svg_models import SvgIconItem, SvgPathItem
@@ -11,10 +11,17 @@ from hi.apps.location.edit.forms import (
LocationViewEditForm,
)
from hi.apps.location.svg_item_factory import SvgItemFactory
+from hi.apps.sense.transient_models import SensorResponse
from .models import Location, LocationView
+@dataclass
+class StatusDisplayData:
+ entity : Entity
+ sensor_response : SensorResponse
+
+
@dataclass
class LocationViewData:
"""
@@ -28,7 +35,8 @@ class LocationViewData:
collection_paths : List[ CollectionPath ]
unpositioned_collections : List[ Collection ]
orphan_entities : Set[ Entity ]
-
+ status_display_data_map : Dict[ Entity, StatusDisplayData ]
+
@property
def svg_icon_items(self) -> Generator[ SvgIconItem, None, None ]:
svg_item_factory = SvgItemFactory()
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index eb87d5bf..bf26d7a8 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -56,7 +56,9 @@ class LocationViewView( HiGridView, LocationViewMixin ):
location_view_data = LocationManager().get_location_view_data(
location_view = location_view,
+ include_status_display_data = bool( not request.is_editing ),
)
+
return {
'is_async_request': is_ajax( request ),
'location_view': location_view,
diff --git a/src/hi/apps/sense/migrations/0002_sensor_sensor_integration_key.py b/src/hi/apps/sense/migrations/0002_sensor_sensor_integration_key.py
new file mode 100644
index 00000000..50569379
--- /dev/null
+++ b/src/hi/apps/sense/migrations/0002_sensor_sensor_integration_key.py
@@ -0,0 +1,20 @@
+# Generated by Django 4.2.15 on 2024-11-25 17:31
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("sense", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.AddConstraint(
+ model_name="sensor",
+ constraint=models.UniqueConstraint(
+ fields=("integration_id", "integration_name"),
+ name="sensor_integration_key",
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/sense/sensor_history_manager.py b/src/hi/apps/sense/sensor_history_manager.py
new file mode 100644
index 00000000..1d0921a3
--- /dev/null
+++ b/src/hi/apps/sense/sensor_history_manager.py
@@ -0,0 +1,21 @@
+import logging
+from typing import List
+
+from hi.apps.common.singleton import Singleton
+
+from .transient_models import SensorResponse
+
+logger = logging.getLogger(__name__)
+
+
+class SensorHistoryManager( Singleton ):
+
+ def __init_singleton__( self ):
+ return
+
+ def add_to_sensor_response_history( self, sensor_response_list : List[ SensorResponse ] ):
+ if not sensor_response_list:
+ return
+
+ # TODO: Implement me!
+ return
diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.py
index 691bc135..662a4e36 100644
--- a/src/hi/apps/sense/sensor_response_manager.py
+++ b/src/hi/apps/sense/sensor_response_manager.py
@@ -2,37 +2,43 @@ import logging
from typing import Dict, List
from hi.apps.common.redis_client import get_redis_client
-from hi.apps.monitor.transient_models import SensorResponse
+from hi.apps.common.singleton import Singleton
from hi.integrations.core.integration_key import IntegrationKey
+from .sensor_history_manager import SensorHistoryManager
+from .transient_models import SensorResponse
+
logger = logging.getLogger(__name__)
-class SensorResponseManager:
+class SensorResponseManager( Singleton ):
"""
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.
+
+ 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.
"""
-
- def add_to_sensor_response_history( self, sensor_response_list : List[ SensorResponse ] ):
- if not sensor_response_list:
- return
- # TODO: Implement me!
+ LATEST_SENSOR_RESPONSE_HASH_NAME = 'hi.sr.all' # Name of redis cache grouping
+
+ def __init_singleton__( self ):
+ self._redis_client = get_redis_client()
+ self._sensor_history_manager = SensorHistoryManager()
return
-
+
def add_latest_sensor_responses( self, sensor_response_list : List[ SensorResponse ] ):
if not sensor_response_list:
return
- redis_client = get_redis_client()
cached_set = { self.to_sensor_value_cache_key(x.integration_key): str(x)
for x in sensor_response_list }
- redis_client.mset( cached_set )
+ self._redis_client.hset( self.LATEST_SENSOR_RESPONSE_HASH_NAME, mapping = cached_set )
return
def update_with_latest_sensor_responses( self,
@@ -47,10 +53,9 @@ class SensorResponseManager:
return
changed_sensor_response_list = list()
- redis_client = get_redis_client()
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 = redis_client.mget( cache_keys )
+ cached_values = self._redis_client.hmget( self.LATEST_SENSOR_RESPONSE_HASH_NAME, cache_keys )
for integration_key, cached_value in zip( integration_keys, cached_values ):
latest_sensor_response = sensor_response_map.get( integration_key )
if cached_value:
@@ -61,11 +66,17 @@ class SensorResponseManager:
changed_sensor_response_list.append( latest_sensor_response )
continue
- self.add_to_sensor_response_history( changed_sensor_response_list )
+ 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_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 to_sensor_value_cache_key( self, integration_key : IntegrationKey ):
return f'hi.sr.{integration_key}'
diff --git a/src/hi/apps/monitor/transient_models.py b/src/hi/apps/sense/transient_models.py
similarity index 100%
rename from src/hi/apps/monitor/transient_models.py
rename to src/hi/apps/sense/transient_models.py
diff --git a/src/hi/integrations/hass/hass_monitor.py b/src/hi/integrations/hass/hass_monitor.py
index 4cf0112f..63708397 100644
--- a/src/hi/integrations/hass/hass_monitor.py
+++ b/src/hi/integrations/hass/hass_monitor.py
@@ -2,8 +2,8 @@ import logging
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
-from hi.apps.monitor.transient_models import SensorResponse
from hi.apps.sense.sensor_response_manager import SensorResponseManager
+from hi.apps.sense.transient_models import SensorResponse
from .hass_converter import HassConverter
from .hass_manager import HassManager
diff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.py
index 708c4db2..e82769b6 100644
--- a/src/hi/integrations/zoneminder/zm_monitor.py
+++ b/src/hi/integrations/zoneminder/zm_monitor.py
@@ -3,9 +3,10 @@ import logging
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
-from hi.apps.monitor.transient_models import SensorResponse
from hi.apps.sense.enums import SensorValue
+from hi.apps.sense.sensor_history_manager import SensorHistoryManager
from hi.apps.sense.sensor_response_manager import SensorResponseManager
+from hi.apps.sense.transient_models import SensorResponse
from .zm_models import ZmEvent
from .zm_manager import ZoneMinderManager
@@ -24,6 +25,7 @@ class ZoneMinderMonitor( PeriodicMonitor ):
interval_secs = 10,
)
self._zm_manager = ZoneMinderManager()
+ self._sensor_history_manager = SensorHistoryManager()
self._sensor_response_manager = SensorResponseManager()
self._fully_processed_event_ids = TTLCache( maxsize = 1000, ttl = 100000 )
self._start_processed_event_ids = TTLCache( maxsize = 1000, ttl = 100000 )
@@ -100,7 +102,7 @@ class ZoneMinderMonitor( PeriodicMonitor ):
self._start_processed_event_ids[zm_event.event_id] = True
continue
- self._sensor_response_manager.add_to_sensor_response_history(
+ self._sensor_history_manager.add_to_sensor_response_history(
sensor_response_list = sensor_response_history_list,
)
self._sensor_response_manager.add_latest_sensor_responses(