Skip to content

Home Information - Your home, your data, organized.

Python

Added tracking sensor value history in Database.

Anthony Cassandra4fbc40e798a7
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 23d8a90b..64fb792d 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -152,12 +152,6 @@ class EntityState( models.Model ):
class Meta:
verbose_name = 'Entity State'
verbose_name_plural = 'Entity States'
- constraints = [
- models.UniqueConstraint(
- fields = [ 'entity_id', 'entity_state_type_str' ],
- name = 'entity_state_entity_entity_type',
- ),
- ]
def __str__(self):
return f'State[{self.id}]: {self.name} [{self.entity_state_type_str}]'
diff --git a/src/hi/apps/location/migrations/0006_remove_locationview_status_display_type_str.py b/src/hi/apps/location/migrations/0006_remove_locationview_status_display_type_str.py
new file mode 100644
index 00000000..313f970b
--- /dev/null
+++ b/src/hi/apps/location/migrations/0006_remove_locationview_status_display_type_str.py
@@ -0,0 +1,17 @@
+# Generated by Django 4.2.15 on 2024-11-26 21:09
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("location", "0005_locationview_status_display_type_str"),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name="locationview",
+ name="status_display_type_str",
+ ),
+ ]
diff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/status_display_data.py
index 4a201ecf..81cb95e9 100644
--- a/src/hi/apps/monitor/status_display_data.py
+++ b/src/hi/apps/monitor/status_display_data.py
@@ -176,7 +176,6 @@ class StatusDisplayData:
if self.entity_state.entity_state_type == EntityStateType.HIGH_LOW:
return self._get_high_low_status_style()
-
# TODO: These should map the latest value into a continuous range of colors/opacity
#
# EntityStateType.AIR_PRESSURE
diff --git a/src/hi/apps/monitor/status_display_helper.py b/src/hi/apps/monitor/status_display_helper.py
index 0919f493..bba7926c 100644
--- a/src/hi/apps/monitor/status_display_helper.py
+++ b/src/hi/apps/monitor/status_display_helper.py
@@ -1,4 +1,4 @@
-from typing import Dict, List, Set
+from typing import Dict, List, Set, Sequence
from hi.apps.entity.enums import EntityStateType
from hi.apps.entity.models import Entity, EntityState
@@ -30,36 +30,42 @@ class StatusDisplayLocationHelper:
def get_status_entity_state( self, entity : Entity ) -> EntityState:
- entity_state_type_map = dict()
-
# Delegate entities include will include all their principal entity
# states, though any direct state will take precendence
-
- delegations_queryset = entity.entity_state_delegations.select_related('entity_state').all()
- for entity_state_delegation in delegations_queryset:
- entity_state = entity_state_delegation.entity_state
- entity_state_type_map[entity_state.entity_state_type] = entity_state
- continue
- states_queryset = entity.states.all()
- for entity_state in states_queryset:
- entity_state_type_map[entity_state.entity_state_type] = entity_state
+ delegations_queryset = entity.entity_state_delegations.select_related('entity_state').all()
+ all_entity_states = [ x.entity_state for x in delegations_queryset ]
+ all_entity_states.extend( entity.states.all() )
+
+ entity_state_list_map = dict()
+ for entity_state in all_entity_states:
+ if entity_state.entity_state_type not in entity_state_list_map:
+ entity_state_list_map[entity_state.entity_state_type] = list()
+ entity_state_list_map[entity_state.entity_state_type].append( entity_state )
continue
- if not entity_state_type_map:
+ if not entity_state_list_map:
return None
entity_state_type_for_status = self._get_entity_state_type_for_status(
- entity_states = entity_state_type_map.values(),
+ entity_state_types = entity_state_list_map.keys(),
)
+ entity_state_list = entity_state_list_map.get( entity_state_type_for_status )
- return entity_state_type_map.get( entity_state_type_for_status )
+ # TODO: It is possible to have multiple EntityState instances with
+ # the same EntityStateType, but it is rare in the cases where we
+ # care about showing dynamic status display changes. If/when it
+ # matters, we would need to add some reconcilliation logic here for
+ # picking the entity state to use.
+ #
+ return entity_state_list[0]
- def _get_entity_state_type_for_status( self, entity_states : List[ EntityState ] ) -> EntityStateType:
- entity_state_type_list = [ x.entity_state_type for x in entity_states ]
+ def _get_entity_state_type_for_status(
+ self,
+ entity_state_types : Sequence[ EntityStateType ] ) -> EntityStateType:
for priority_entity_state_type in self._entity_state_type_priority_list:
- if priority_entity_state_type in entity_state_type_list:
+ if priority_entity_state_type in entity_state_types:
return priority_entity_state_type
continue
@@ -67,7 +73,7 @@ class StatusDisplayLocationHelper:
# 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:
+ if default_entity_state_type in entity_state_types:
return default_entity_state_type
continue
diff --git a/src/hi/apps/sense/admin.py b/src/hi/apps/sense/admin.py
index b74ac35b..7de30c55 100644
--- a/src/hi/apps/sense/admin.py
+++ b/src/hi/apps/sense/admin.py
@@ -28,10 +28,10 @@ class SensorHistoryAdmin(admin.ModelAdmin):
list_display = (
'sensor',
'value',
- 'created_datetime',
+ 'response_datetime',
)
search_fields = ['sensor__name']
readonly_fields = ( 'sensor', )
- ordering = ( '-created_datetime', )
+ ordering = ( '-response_datetime', )
diff --git a/src/hi/apps/sense/migrations/0003_alter_sensorhistory_options_and_more.py b/src/hi/apps/sense/migrations/0003_alter_sensorhistory_options_and_more.py
new file mode 100644
index 00000000..9b3c28d3
--- /dev/null
+++ b/src/hi/apps/sense/migrations/0003_alter_sensorhistory_options_and_more.py
@@ -0,0 +1,41 @@
+# Generated by Django 4.2.15 on 2024-11-26 21:09
+
+from django.db import migrations, models
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("sense", "0002_sensor_sensor_integration_key"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="sensorhistory",
+ options={
+ "ordering": ["-response_datetime"],
+ "verbose_name": "Sensor History",
+ "verbose_name_plural": "Sensor History",
+ },
+ ),
+ migrations.RemoveField(
+ model_name="sensorhistory",
+ name="created_datetime",
+ ),
+ migrations.AddField(
+ model_name="sensorhistory",
+ name="response_datetime",
+ field=models.DateTimeField(
+ default=django.utils.timezone.now, verbose_name="Timestamp"
+ ),
+ preserve_default=False,
+ ),
+ migrations.AddIndex(
+ model_name="sensorhistory",
+ index=models.Index(
+ fields=["sensor", "-response_datetime"],
+ name="sense_senso_sensor__e2513c_idx",
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/sense/models.py b/src/hi/apps/sense/models.py
index b50bfc9e..25154cd5 100644
--- a/src/hi/apps/sense/models.py
+++ b/src/hi/apps/sense/models.py
@@ -65,11 +65,15 @@ class SensorHistory(models.Model):
'Value',
max_length = 255
)
- created_datetime = models.DateTimeField(
- 'Created',
- auto_now_add = True,
+ response_datetime = models.DateTimeField(
+ 'Timestamp',
)
class Meta:
verbose_name = 'Sensor History'
verbose_name_plural = 'Sensor History'
+ ordering = [ '-response_datetime' ]
+ indexes = [
+ models.Index( fields = [ 'sensor', '-response_datetime'] ),
+ ]
+
diff --git a/src/hi/apps/sense/sensor_history_manager.py b/src/hi/apps/sense/sensor_history_manager.py
index 1d0921a3..aa4cb0c3 100644
--- a/src/hi/apps/sense/sensor_history_manager.py
+++ b/src/hi/apps/sense/sensor_history_manager.py
@@ -1,8 +1,10 @@
+from asgiref.sync import async_to_sync, sync_to_async
import logging
from typing import List
from hi.apps.common.singleton import Singleton
+from .models import SensorHistory
from .transient_models import SensorResponse
logger = logging.getLogger(__name__)
@@ -13,9 +15,25 @@ class SensorHistoryManager( Singleton ):
def __init_singleton__( self ):
return
- def add_to_sensor_response_history( self, sensor_response_list : List[ SensorResponse ] ):
+ async def add_to_sensor_response_history( self, sensor_response_list : List[ SensorResponse ] ):
if not sensor_response_list:
return
- # TODO: Implement me!
+ sensor_history_list = list()
+ for sensor_response in sensor_response_list:
+ if sensor_response.sensor:
+ sensor_history_list.append(
+ SensorHistory(
+ sensor = sensor_response.sensor,
+ value = sensor_response.value,
+ response_datetime = sensor_response.timestamp,
+ )
+ )
+ continue
+
+ await self._bulk_create_sensor_history_async( sensor_history_list )
+ return
+
+ async def _bulk_create_sensor_history_async( self, sensor_history_list : List[ SensorHistory ] ):
+ await sync_to_async( SensorHistory.objects.bulk_create)( sensor_history_list )
return
diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.py
index 1cb0b4e5..b119053c 100644
--- a/src/hi/apps/sense/sensor_response_manager.py
+++ b/src/hi/apps/sense/sensor_response_manager.py
@@ -45,7 +45,7 @@ class SensorResponseManager( Singleton ):
self._sensor_cache = TTLCache( maxsize = 1000, ttl = 3600 )
return
- def add_latest_sensor_responses( self, sensor_response_list : List[ SensorResponse ] ):
+ async def add_latest_sensor_responses( self, sensor_response_list : List[ SensorResponse ] ):
if not sensor_response_list:
return
@@ -59,13 +59,14 @@ class SensorResponseManager( Singleton ):
continue
pipeline.execute()
- self._sensor_history_manager.add_to_sensor_response_history(
+ self._add_sensors( sensor_response_list = sensor_response_list )
+ await self._sensor_history_manager.add_to_sensor_response_history(
sensor_response_list = sensor_response_list,
)
return
- def update_with_latest_sensor_responses( self,
- sensor_response_map : Dict[ IntegrationKey, SensorResponse ] ):
+ async def update_with_latest_sensor_responses( self,
+ sensor_response_map : Dict[ IntegrationKey, SensorResponse ] ):
"""
Used when states are polled and get current state at a point in time
which may or may not represent a change in state. We only want to
@@ -95,7 +96,7 @@ class SensorResponseManager( Singleton ):
changed_sensor_response_list.append( latest_sensor_response )
continue
- self.add_latest_sensor_responses( changed_sensor_response_list )
+ await 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
@@ -152,6 +153,13 @@ class SensorResponseManager( Singleton ):
def to_sensor_response_list_cache_key( self, integration_key : IntegrationKey ) -> str:
return f'hi.sr.latest.{integration_key}'
+ def _add_sensors( self, sensor_response_list : List[ SensorResponse ] ):
+ for sensor_response in sensor_response_list:
+ if sensor_response.sensor is None:
+ sensor_response.sensor = self._get_sensor( integration_key = sensor_response.integration_key )
+ continue
+ return
+
def _get_sensor( self, integration_key : IntegrationKey ):
if integration_key not in self._sensor_cache:
try:
diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.py
index 20748f50..65a78656 100644
--- a/src/hi/apps/sense/transient_models.py
+++ b/src/hi/apps/sense/transient_models.py
@@ -4,13 +4,16 @@ import json
from hi.integrations.core.integration_key import IntegrationKey
+from .models import Sensor
+
@dataclass
class SensorResponse:
integration_key : IntegrationKey
value : str
timestamp : datetime
-
+ sensor : Sensor = None
+
def __str__(self):
return json.dumps( self.to_dict() )
@@ -19,6 +22,7 @@ class SensorResponse:
'key': str(self.integration_key),
'value': self.value,
'timestamp': self.timestamp.isoformat(),
+ 'sensor_id': self.sensor.id if self.sensor else None,
}
@classmethod
diff --git a/src/hi/integrations/hass/hass_monitor.py b/src/hi/integrations/hass/hass_monitor.py
index 63708397..2f5d422a 100644
--- a/src/hi/integrations/hass/hass_monitor.py
+++ b/src/hi/integrations/hass/hass_monitor.py
@@ -45,7 +45,7 @@ class HassMonitor( PeriodicMonitor ):
sensor_response_latest_map[integration_key] = sensor_response
continue
- self._sensor_response_manager.update_with_latest_sensor_responses(
+ await self._sensor_response_manager.update_with_latest_sensor_responses(
sensor_response_map = sensor_response_latest_map,
)
return
diff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.py
index 736de3ad..2bed05ba 100644
--- a/src/hi/integrations/zoneminder/zm_monitor.py
+++ b/src/hi/integrations/zoneminder/zm_monitor.py
@@ -100,7 +100,7 @@ class ZoneMinderMonitor( PeriodicMonitor ):
self._fully_processed_event_ids[zm_event.event_id] = True
continue
- self._sensor_response_manager.add_latest_sensor_responses(
+ await self._sensor_response_manager.add_latest_sensor_responses(
sensor_response_list = sensor_response_list,
)