Home Information - Your home, your data, organized.
Python
Added Home Assistant controller and some refactoring of sync code.
Anthony Cassandra944a2a9b629b
diff --git a/src/hi/apps/control/views.py b/src/hi/apps/control/views.pyindex a1da8de8..c4c259eb 100644--- a/src/hi/apps/control/views.py+++ b/src/hi/apps/control/views.py@@ -3,6 +3,7 @@ import loggingfrom django.views.generic import Viewfrom hi.integrations.core.integration_factory import IntegrationFactory+from .view_mixin import ControlViewMixinlogger = logging.getLogger(__name__)@@ -13,6 +14,7 @@ class ControllerView( View, ControlViewMixin ):def post( self, request, *args, **kwargs ):controller = self.get_controller( request, *args, **kwargs )control_value = request.POST.get( 'value' )+logger.debug( f'Setting discrete controller = "{control_value}"' )integration_gateway = IntegrationFactory().get_integration_gateway(diff --git a/src/hi/integrations/hass/hass_client.py b/src/hi/integrations/hass/hass_client.pyindex e1ae5da0..999c7f51 100644--- a/src/hi/integrations/hass/hass_client.py+++ b/src/hi/integrations/hass/hass_client.py@@ -1,5 +1,5 @@import json-from requests import get+from requests import get, postfrom typing import Dict, Listfrom .hass_converter import HassConverter@@ -35,3 +35,20 @@ class HassClient:response = get( url, headers = self._headers )data = json.loads(response.text)return [ HassConverter.create_hass_state(x) for x in data ]++ def set_state( self, entity_id: str, state: str, attributes: dict = None ) -> dict:++ url = f'{self._api_base_url}/api/states/{entity_id}'+ data = {+ 'state': state,+ }+ if attributes:+ data["attributes"] = attributes++ response = post( url, json = data, headers = self._headers )+ if response.status_code != 200:+ raise ValueError( f"Failed to set state: {response.status_code} {response.text}" )++ return response.json()++diff --git a/src/hi/integrations/hass/hass_controller.py b/src/hi/integrations/hass/hass_controller.pyindex 65a5381c..fe1ffd4b 100644--- a/src/hi/integrations/hass/hass_controller.py+++ b/src/hi/integrations/hass/hass_controller.py@@ -20,8 +20,20 @@ class HassController( IntegrationController ):control_value : str ) -> IntegrationControlResult:try:- raise ValueError( 'HAss controls not implemented.' )-+ entity_id = integration_key.integration_name+ if not control_value:+ control_value = "off"++ response = self._hass_manager.hass_client.set_state(+ entity_id = entity_id,+ state = control_value,+ )+ logger.debug( f'HAss set state: {entity_id}={control_value}, response={response}' )+ return IntegrationControlResult(+ new_value = control_value,+ error_list = [],+ )+except Exception as e:logger.warning( f'Exception in HAss do_control: {e}' )return IntegrationControlResult(diff --git a/src/hi/integrations/hass/hass_manager.py b/src/hi/integrations/hass/hass_manager.pyindex 07a8a5ff..2b918122 100644--- a/src/hi/integrations/hass/hass_manager.py+++ b/src/hi/integrations/hass/hass_manager.py@@ -1,12 +1,7 @@import loggingfrom typing import Dict-from django.db import transaction--from hi.apps.common.database_lock import ExclusionLockContext-from hi.apps.common.processing_result import ProcessingResultfrom hi.apps.common.singleton import Singleton-from hi.apps.entity.models import Entityfrom hi.integrations.core.exceptions import IntegrationAttributeErrorfrom hi.integrations.core.integration_key import IntegrationKey@@ -14,17 +9,14 @@ from hi.integrations.core.models import Integrationfrom .enums import HassAttributeTypefrom .hass_client import HassClient-from .hass_converter import HassConverterfrom .hass_metadata import HassMetaData-from .hass_models import HassState, HassDevice+from .hass_models import HassStatelogger = logging.getLogger(__name__)class HassManager( Singleton ):- SYNCHRONIZATION_LOCK_NAME = 'hass_integration_sync'-def __init_singleton__( self ):self._is_loading = Falseself._hass_client = None@@ -88,65 +80,6 @@ class HassManager( Singleton ):logger.debug( f'Home Assistant client options: {api_options}' )return HassClient( api_options = api_options )-- def sync( self ) -> ProcessingResult:- try:- with ExclusionLockContext( name = self.SYNCHRONIZATION_LOCK_NAME ):- logger.debug( 'HAss integration sync started.' )- return self._sync_helper()- except RuntimeError as e:- logger.exception( e )- return ProcessingResult(- title = 'HAss Sync Result',- error_list = [ str(e) ],- )- finally:- logger.debug( 'HAss integration sync ended.' )-- def _sync_helper( self ) -> ProcessingResult:- result = ProcessingResult( title = 'HAss Sync Result' )-- hass_client = self.hass_client- if not hass_client:- logger.debug( 'HAss client not created. HAss integration disabled?' )- result.error_list.append( 'Sync problem. HAss integration disabled?' )- return result-- hass_entity_id_to_state = self.fetch_hass_states_from_api()- result.message_list.append( f'Found {len(hass_entity_id_to_state)} current HAss states.' )-- integration_key_to_entity = self._get_existing_hass_entities( result = result )- result.message_list.append( f'Found {len(integration_key_to_entity)} existing HAss entities.' )-- hass_device_id_to_device = HassConverter.hass_states_to_hass_devices(- hass_entity_id_to_state = hass_entity_id_to_state,- )- result.message_list.append( f'Found {len(hass_device_id_to_device)} current HAss devices.' )-- integration_key_to_hass_device = {- HassConverter.hass_device_to_integration_key( hass_device ): hass_device- for hass_device in hass_device_id_to_device.values()- }-- with transaction.atomic():- for integration_key, hass_device in integration_key_to_hass_device.items():- entity = integration_key_to_entity.get( integration_key )- if entity:- self._update_entity( entity = entity,- hass_device = hass_device,- result = result )- else:- self._create_entity( hass_device = hass_device,- result = result )- continue-- for integration_key, entity in integration_key_to_entity.items():- if integration_key not in integration_key_to_hass_device:- self._remove_entity( entity = entity,- result = result )- continue-- return resultdef fetch_hass_states_from_api( self, verbose : bool = True ) -> Dict[ str, HassState ]:if verbose:@@ -159,50 +92,3 @@ class HassManager( Singleton ):continuereturn hass_entity_id_to_state-- def _get_existing_hass_entities( self, result : ProcessingResult ) -> Dict[ IntegrationKey, Entity ]:- logger.debug( 'Getting existing HAss entities.' )- integration_key_to_entity = dict()-- entity_queryset = Entity.objects.filter( integration_id = HassMetaData.integration_id )- for entity in entity_queryset:- integration_key = entity.integration_key- if not integration_key:- result.error_list.append( f'Entity found without valid HAss Id: {entity}' )- mock_hass_device_id = 1000000 + entity.id # We need a (unique) placeholder for removals- integration_key = IntegrationKey(- integration_id = HassMetaData.integration_id,- integration_name = str( mock_hass_device_id ),- )- integration_key_to_entity[integration_key] = entity- continue-- return integration_key_to_entity-- def _create_entity( self,- hass_device : HassDevice,- result : ProcessingResult ):- entity = HassConverter.create_models_for_hass_device( hass_device = hass_device )- result.message_list.append( f'Created HAss entity: {entity}' )- return-- def _update_entity( self,- entity : Entity,- hass_device : HassDevice,- result : ProcessingResult ):-- message_list = HassConverter.update_models_for_hass_device(- entity = entity,- hass_device = hass_device,- )- for message in message_list:- result.message_list.append( message )- continue- return-- def _remove_entity( self,- entity : Entity,- result : ProcessingResult ):- entity.delete() # Deletion cascades to attributes, positions, sensors, controllers, etc.- result.message_list.append( f'Removed stale HAss entity: {entity}' )- returndiff --git a/src/hi/integrations/hass/hass_sync.py b/src/hi/integrations/hass/hass_sync.pynew file mode 100644index 00000000..c89e76f2--- /dev/null+++ b/src/hi/integrations/hass/hass_sync.py@@ -0,0 +1,134 @@+import logging+from typing import Dict++from django.db import transaction++from hi.apps.common.database_lock import ExclusionLockContext+from hi.apps.common.processing_result import ProcessingResult+from hi.apps.entity.models import Entity++from hi.integrations.core.integration_key import IntegrationKey++from .hass_converter import HassConverter+from .hass_models import HassDevice+from .hass_manager import HassManager+from .hass_metadata import HassMetaData++logger = logging.getLogger(__name__)+++class HassSynchronizer:++ SYNCHRONIZATION_LOCK_NAME = 'hass_integration_sync'++ def __init__(self):+ self._hass_manager = HassManager()+ return++ def sync( self ) -> ProcessingResult:+ try:+ with ExclusionLockContext( name = self.SYNCHRONIZATION_LOCK_NAME ):+ logger.debug( 'HAss integration sync started.' )+ return self._sync_helper()+ except RuntimeError as e:+ logger.exception( e )+ return ProcessingResult(+ title = 'HAss Sync Result',+ error_list = [ str(e) ],+ )+ finally:+ logger.debug( 'HAss integration sync ended.' )++ def _sync_helper( self ) -> ProcessingResult:+ result = ProcessingResult( title = 'HAss Sync Result' )++ hass_client = self._hass_manager.hass_client+ if not hass_client:+ logger.debug( 'HAss client not created. HAss integration disabled?' )+ result.error_list.append( 'Sync problem. HAss integration disabled?' )+ return result++ hass_entity_id_to_state = self._hass_manager.fetch_hass_states_from_api()+ result.message_list.append( f'Found {len(hass_entity_id_to_state)} current HAss states.' )++ integration_key_to_entity = self._get_existing_hass_entities( result = result )+ result.message_list.append( f'Found {len(integration_key_to_entity)} existing HAss entities.' )++ hass_device_id_to_device = HassConverter.hass_states_to_hass_devices(+ hass_entity_id_to_state = hass_entity_id_to_state,+ )+ result.message_list.append( f'Found {len(hass_device_id_to_device)} current HAss devices.' )++ integration_key_to_hass_device = {+ HassConverter.hass_device_to_integration_key( hass_device ): hass_device+ for hass_device in hass_device_id_to_device.values()+ }++ with transaction.atomic():+ for integration_key, hass_device in integration_key_to_hass_device.items():+ entity = integration_key_to_entity.get( integration_key )+ if entity:+ self._update_entity( entity = entity,+ hass_device = hass_device,+ result = result )+ else:+ self._create_entity( hass_device = hass_device,+ result = result )+ continue++ for integration_key, entity in integration_key_to_entity.items():+ if integration_key not in integration_key_to_hass_device:+ self._remove_entity( entity = entity,+ result = result )+ continue++ return result++ def _get_existing_hass_entities( self, result : ProcessingResult ) -> Dict[ IntegrationKey, Entity ]:+ logger.debug( 'Getting existing HAss entities.' )+ integration_key_to_entity = dict()++ entity_queryset = Entity.objects.filter( integration_id = HassMetaData.integration_id )+ for entity in entity_queryset:+ integration_key = entity.integration_key+ if not integration_key:+ result.error_list.append( f'Entity found without valid HAss Id: {entity}' )+ mock_hass_device_id = 1000000 + entity.id # We need a (unique) placeholder for removals+ integration_key = IntegrationKey(+ integration_id = HassMetaData.integration_id,+ integration_name = str( mock_hass_device_id ),+ )+ integration_key_to_entity[integration_key] = entity+ continue++ return integration_key_to_entity++ def _create_entity( self,+ hass_device : HassDevice,+ result : ProcessingResult ):+ entity = HassConverter.create_models_for_hass_device( hass_device = hass_device )+ result.message_list.append( f'Created HAss entity: {entity}' )+ return++ def _update_entity( self,+ entity : Entity,+ hass_device : HassDevice,+ result : ProcessingResult ):++ message_list = HassConverter.update_models_for_hass_device(+ entity = entity,+ hass_device = hass_device,+ )+ for message in message_list:+ result.message_list.append( message )+ continue+ return++ def _remove_entity( self,+ entity : Entity,+ result : ProcessingResult ):+ entity.delete() # Deletion cascades to attributes, positions, sensors, controllers, etc.+ result.message_list.append( f'Removed stale HAss entity: {entity}' )+ return++diff --git a/src/hi/integrations/hass/views.py b/src/hi/integrations/hass/views.pyindex 76c7fb0e..9f0bd53b 100644--- a/src/hi/integrations/hass/views.py+++ b/src/hi/integrations/hass/views.py@@ -16,6 +16,7 @@ from hi.hi_async_view import HiModalViewfrom .hass_metadata import HassMetaDatafrom .hass_manager import HassManager+from .hass_sync import HassSynchronizerclass HassEnableView( HiModalView, IntegrationHelperMixin ):@@ -153,7 +154,7 @@ class HassSyncView( HiModalView ):def post(self, request, *args, **kwargs):- processing_result = HassManager().sync()+ processing_result = HassSynchronizer().sync()context = {'processing_result': processing_result,}