Skip to content

Home Information - Your home, your data, organized.

Python

Worked out state polling logic for HomeAssistant integration.

Anthony Cassandra1d13c1045a86
diff --git a/src/hi/apps/monitor/monitor_mixin.py b/src/hi/apps/monitor/monitor_mixin.py
index 18a4360e..7263e1c6 100644
--- a/src/hi/apps/monitor/monitor_mixin.py
+++ b/src/hi/apps/monitor/monitor_mixin.py
@@ -1,18 +1,65 @@
-from typing import List
+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.integrations.core.integration_key import IntegrationKey
+
+logger = logging.getLogger(__name__)
+
class SensorMonitorMixin:
def add_to_sensor_response_history( self, sensor_response_list : List[ SensorResponse ] ):
+ if not sensor_response_list:
+ return
# TODO: Implement me!
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 )
+ return
- # TODO: Implement me!
+ 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
+ keep the history of changed states, so we fetch previous values to
+ detect changes.
+ """
+ if not sensor_response_map:
+ 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 )
+ for integration_key, cached_value in zip( integration_keys, cached_values ):
+ latest_sensor_response = sensor_response_map.get( integration_key )
+ if cached_value:
+ previous_sensor_response = SensorResponse.from_string( cached_value )
+ if latest_sensor_response.value == previous_sensor_response.value:
+ continue
+
+ changed_sensor_response_list.append( latest_sensor_response )
+ continue
+
+ self.add_to_sensor_response_history( changed_sensor_response_list )
+ self.add_latest_sensor_responses( changed_sensor_response_list )
+ if self.TRACE:
+ logger.debug( f'HAss Changed: {len(changed_sensor_response_list)} of {len(sensor_response_map)}' )
return
-
+
+ def to_sensor_value_cache_key( self, integration_key : IntegrationKey ):
+ return f'hi.sr.{integration_key}'
diff --git a/src/hi/apps/sense/enums.py b/src/hi/apps/sense/enums.py
index bc6fc392..19307b7e 100644
--- a/src/hi/apps/sense/enums.py
+++ b/src/hi/apps/sense/enums.py
@@ -10,3 +10,7 @@ class SensorValue(LabeledEnum):
MOVEMENT_ACTIVE = ( 'Active', '' )
MOVEMENT_IDLE = ( 'Idle', '' )
+
+ BINARY_ON = ( 'On', '' )
+ BINARY_OFF = ( 'Off', '' )
+
diff --git a/src/hi/integrations/hass/hass_converter.py b/src/hi/integrations/hass/hass_converter.py
index 31310d4f..72a0259e 100644
--- a/src/hi/integrations/hass/hass_converter.py
+++ b/src/hi/integrations/hass/hass_converter.py
@@ -16,6 +16,7 @@ from hi.apps.entity.enums import (
)
from hi.apps.entity.models import Entity, EntityAttribute
from hi.apps.model_helper import HiModelHelper
+from hi.apps.sense.enums import SensorValue
from hi.integrations.core.integration_key import IntegrationKey
@@ -504,3 +505,34 @@ class HassConverter:
integration_name = hass_state.entity_id,
)
+ @classmethod
+ def hass_state_to_sensor_value_str( self, hass_state : HassState ) -> str:
+
+ if hass_state.entity_id_prefix == HassApi.SUN_ID_PREFIX:
+ return hass_state.state_value
+
+ elif hass_state.entity_id_prefix == HassApi.WEATHER_ID_PREFIX:
+ 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)
+ elif hass_state.state_value.lower() == 'off':
+ return str(SensorValue.BINARY_OFF)
+ else:
+ logger.warning( f'Unknown HAss binary stae value "{hass_state.state_value}".' )
+ return None
+
+ elif hass_state.device_class == HassApi.TEMPERATURE_DEVICE_CLASS:
+ return hass_state.state_value
+
+ elif hass_state.device_class == HassApi.HUMIDITY_DEVICE_CLASS:
+ return hass_state.state_value
+
+ elif hass_state.device_class == HassApi.TIMESTAMP_DEVICE_CLASS:
+ return hass_state.state_value
+
+ elif hass_state.device_class == HassApi.ENUM_DEVICE_CLASS:
+ return hass_state.state_value
+
+ return hass_state.state_value
diff --git a/src/hi/integrations/hass/hass_models.py b/src/hi/integrations/hass/hass_models.py
index 5e22416b..4530b6c3 100644
--- a/src/hi/integrations/hass/hass_models.py
+++ b/src/hi/integrations/hass/hass_models.py
@@ -95,7 +95,7 @@ class HassState:
@property
def state_value(self):
- return self.attributes.get( HassApi.STATE_FIELD )
+ return self.api_dict.get( HassApi.STATE_FIELD )
@property
def device_class(self):
diff --git a/src/hi/integrations/hass/hass_monitor.py b/src/hi/integrations/hass/hass_monitor.py
index 8645755e..5b241e89 100644
--- a/src/hi/integrations/hass/hass_monitor.py
+++ b/src/hi/integrations/hass/hass_monitor.py
@@ -1,7 +1,9 @@
import logging
+import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
from hi.apps.monitor.monitor_mixin import SensorMonitorMixin
+from hi.apps.monitor.transient_models import SensorResponse
from .hass_converter import HassConverter
from .hass_manager import HassManager
@@ -17,6 +19,7 @@ class HassMonitor( PeriodicMonitor, SensorMonitorMixin ):
interval_secs = 10,
)
self._manager = HassManager()
+ self._logger = logging.getLogger(__name__)
return
async def do_work(self):
@@ -25,32 +28,22 @@ class HassMonitor( PeriodicMonitor, SensorMonitorMixin ):
if self.TRACE:
logger.debug( f'Fetched {len(id_to_hass_state_map)} HAss States' )
+ current_datetime = datetimeproxy.now()
+ sensor_response_latest_map = dict()
for hass_state in id_to_hass_state_map.values():
- state_integration_key = HassConverter.hass_state_to_integration_key( hass_state = hass_state )
-
-
- hass_state.state_value
-
-
-
-
-
- # TODO: zzz Update Redis with state values
-
-
-
- # zzz How do Hass states roll up to hass entities and how to identify
- # if one entity has multiple states...do states need integration id too???
-
-
-
-
-
-
-
-
-
+ integration_key = HassConverter.hass_state_to_integration_key( hass_state = hass_state )
+ sensor_value_str = HassConverter.hass_state_to_sensor_value_str( hass_state )
+ if not sensor_value_str:
+ continue
+ sensor_response = SensorResponse(
+ integration_key = integration_key,
+ value = sensor_value_str,
+ timestamp = current_datetime,
+ )
+ sensor_response_latest_map[integration_key] = sensor_response
continue
+
+ self.update_with_latest_sensor_responses( sensor_response_latest_map )
return
diff --git a/src/hi/integrations/zoneminder/transient_models.py b/src/hi/integrations/zoneminder/zm_models.py
similarity index 100%
rename from src/hi/integrations/zoneminder/transient_models.py
rename to src/hi/integrations/zoneminder/zm_models.py
diff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.py
index 9682104d..5fad89ca 100644
--- a/src/hi/integrations/zoneminder/zm_monitor.py
+++ b/src/hi/integrations/zoneminder/zm_monitor.py
@@ -7,7 +7,7 @@ from hi.apps.monitor.monitor_mixin import SensorMonitorMixin
from hi.apps.monitor.transient_models import SensorResponse
from hi.apps.sense.enums import SensorValue
-from .transient_models import ZmEvent
+from .zm_models import ZmEvent
from .zm_manager import ZoneMinderManager
logger = logging.getLogger(__name__)