Home Information - Your home, your data, organized.
Python
Added stub of Home Assistant Integration. WIP
Anthony Cassandrac06cecea17f5
diff --git a/src/hi/apps/entity_helpers.py b/src/hi/apps/entity_helpers.pyindex ae822cfa..b5452837 100644--- a/src/hi/apps/entity_helpers.py+++ b/src/hi/apps/entity_helpers.py@@ -70,4 +70,3 @@ class EntityHelpers:name = name,)return controller-diff --git a/src/hi/integrations/core/enums.py b/src/hi/integrations/core/enums.pyindex 43449bf1..d8dbd3a8 100644--- a/src/hi/integrations/core/enums.py+++ b/src/hi/integrations/core/enums.py@@ -11,6 +11,5 @@ class PropertyValueType(LabeledEnum):class IntegrationType(LabeledEnum):ZONEMINDER = ( 'ZoneMinder', 'ZoneMinder camera streaming and motion detection.' )- INSTEON_HASS = ( 'Insteon (hass)', 'Insteon devices via Home Assistant API and its integration' )- INSTEON_SERIAL = ( 'Insteon (serial)', 'Insteon devices via modem on serial port.' )+ HASS = ( 'Home Assistant (hass)', 'Home Assistant device access' )diff --git a/src/hi/integrations/core/integration_factory.py b/src/hi/integrations/core/integration_factory.pyindex 49f4e5dc..dccb6fa9 100644--- a/src/hi/integrations/core/integration_factory.py+++ b/src/hi/integrations/core/integration_factory.py@@ -3,6 +3,7 @@ from typing import Listfrom hi.apps.common.singleton import Singleton+from hi.integrations.hass.hass_gateway import HassGatewayfrom hi.integrations.zoneminder.zm_gateway import ZoneMinderGatewayfrom .enums import IntegrationType@@ -35,7 +36,9 @@ class IntegrationFactory( Singleton ):)def get_integration_gateway( self, integration_type : IntegrationType ) -> IntegrationGateway:- if integration_type == IntegrationType.ZONEMINDER:+ if integration_type == IntegrationType.HASS:+ return HassGateway()+ elif integration_type == IntegrationType.ZONEMINDER:return ZoneMinderGateway()else:raise ValueError( f'The "{integration_type}" integration is not yet implemented.' )diff --git a/src/hi/integrations/hass/__init__.py b/src/hi/integrations/hass/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/integrations/hass/admin.py b/src/hi/integrations/hass/admin.pynew file mode 100644index 00000000..8c38f3f3--- /dev/null+++ b/src/hi/integrations/hass/admin.py@@ -0,0 +1,3 @@+from django.contrib import admin++# Register your models here.diff --git a/src/hi/integrations/hass/apps.py b/src/hi/integrations/hass/apps.pynew file mode 100644index 00000000..3afa49da--- /dev/null+++ b/src/hi/integrations/hass/apps.py@@ -0,0 +1,6 @@+from django.apps import AppConfig+++class HassConfig(AppConfig):+ default_auto_field = "django.db.models.BigAutoField"+ name = "hi.integrations.hass"diff --git a/src/hi/integrations/hass/enums.py b/src/hi/integrations/hass/enums.pynew file mode 100644index 00000000..2fd43d94--- /dev/null+++ b/src/hi/integrations/hass/enums.py@@ -0,0 +1,37 @@+from hi.apps.common.enums import LabeledEnum++from hi.integrations.core.enums import PropertyValueType+++class HassPropertyName(LabeledEnum):++ def __init__( self,+ label : str,+ description : str,+ value_type : PropertyValueType,+ is_editable : bool,+ is_required : bool ):+ super().__init__( label, description )+ self.is_editable = is_editable+ self.is_required = is_required+ return++ API_BASE_URL = (+ ' URL',+ 'e.g., https://myhassserver:8123',+ PropertyValueType.STRING,+ True,+ True,+ )+ API_TOKEN = (+ 'API Token',+ '',+ PropertyValueType.STRING,+ True,+ True,+ )+++class HassAttributeName(LabeledEnum):++ HASS_ENTITY_ID = ( 'HAss Entity Id', '' )diff --git a/src/hi/integrations/hass/hass_client.py b/src/hi/integrations/hass/hass_client.pynew file mode 100644index 00000000..d3c264ff--- /dev/null+++ b/src/hi/integrations/hass/hass_client.py@@ -0,0 +1,50 @@+import json+from requests import get+from typing import Dict, List++from .hass_state import HassState+++class HassClient:++ # Docs: https://developers.home-assistant.io/docs/api/rest/++ API_BASE_URL = 'api_base_url'+ API_TOKEN = 'api_token'++ def __init__( self, api_options : Dict[ str, str ] ):++ self._api_base_url = api_options.get( self.API_BASE_URL )+ assert self._api_base_url is not None+ if self._api_base_url[-1] == '/':+ self._api_base_url = self._api_base_url[0:-1]++ token = api_options.get( self.API_TOKEN )+ assert token is not None++ self._headers = {+ 'Authorization': f'Bearer {token}',+ 'content-type':'application/json',+ }+ return++ def states(self) -> List[ HassState ]:++ url = f'{self._api_base_url}/api/states'+ response = get( url, headers = self._headers )+ data = json.loads(response.text)++++++++ print( json.dumps( data, indent=4, sort_keys=True ))+++++ return [ HassState(x) for x in data ]++diff --git a/src/hi/integrations/hass/hass_gateway.py b/src/hi/integrations/hass/hass_gateway.pynew file mode 100644index 00000000..1b2f2429--- /dev/null+++ b/src/hi/integrations/hass/hass_gateway.py@@ -0,0 +1,28 @@+import logging++from django.http import HttpRequest, HttpResponse++from hi.integrations.core.integration_gateway import IntegrationGateway++from . import views++logger = logging.getLogger(__name__)+++class HassGateway( IntegrationGateway ):++ def enable( self, request : HttpRequest ) -> HttpResponse:+ return views.HassEnableView().post( request )++ def disable( self, request : HttpRequest ) -> HttpResponse:+ return views.HassDisableView().post( request )++ def manage( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:++ post_action = request.POST.get('action')+ if post_action == 'sync':+ return views.HassSyncView().post( request, *args, **kwargs )++ return views.HassManageView().get( request, *args, **kwargs )++diff --git a/src/hi/integrations/hass/hass_manager.py b/src/hi/integrations/hass/hass_manager.pynew file mode 100644index 00000000..cf315db5--- /dev/null+++ b/src/hi/integrations/hass/hass_manager.py@@ -0,0 +1,190 @@+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.common.singleton import Singleton+from hi.apps.entity.enums import (+ AttributeName,+ EntityType,+ AttributeValueType,+ AttributeType,+)+from hi.apps.entity.models import Entity, Attribute++from hi.apps.entity_helpers import EntityHelpers++from hi.integrations.core.enums import IntegrationType+from hi.integrations.core.exceptions import IntegrationPropertyError+from hi.integrations.core.models import Integration++from .enums import (+ HassPropertyName,+ HassAttributeName,+)+from .hass_client import HassClient+from .hass_state import HassState++logger = logging.getLogger(__name__)+++class HassManager( Singleton ):++ SYNCHRONIZATION_LOCK_NAME = 'hass_integration_sync'++ def __init_singleton__( self ):+ self._is_loading = False+ self._hass_client = None+ self.reload()+ return++ @property+ def hass_client(self):+ return self._hass_client++ def reload( self ):+ if self._is_loading:+ logger.warning( 'HAss is already loading.' )+ return+ try:+ self._is_loading = True+ self._hass_client = self.create_hass_client()++ finally:+ self._is_loading = False+ logger.debug( 'HAss loading completed.' )+ return++ def create_hass_client(self):+ try:+ hass_integration = Integration.objects.get( integration_type_str = str(IntegrationType.HASS) )+ except Integration.DoesNotExist:+ logger.debug( 'HAss integration is not implemented.' )++ if not hass_integration.is_enabled:+ logger.debug( 'HAss integration is not enabled.' )+ return None++ # Verify integration+ property_dict = hass_integration.property_dict+ for hass_prop_name in HassPropertyName:+ hass_prop = property_dict.get( hass_prop_name.name )+ if not hass_prop:+ raise IntegrationPropertyError( f'Missing HAss property {hass_prop_name.name}' )+ if hass_prop.is_required and not hass_prop.value.strip():+ raise IntegrationPropertyError( f'Missing HAss property value for {hass_prop_name.name}' )++ continue++ api_options = {+ HassClient.API_BASE_URL: property_dict.get( HassPropertyName.API_BASE_URL.name ).value,+ HassClient.API_TOKEN: property_dict.get( HassPropertyName.API_TOKEN.name ).value,+ }+ 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:+ 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_id_to_entity = self._get_hass_entities( result = result )+ result.message_list.append( f'Found {len(hass_id_to_entity)} existing HAss entities.' )++ hass_id_to_state = self._get_hass_states( result = result )+ result.message_list.append( f'Found {len(hass_id_to_state)} current HAss states.' )++ for hass_id, hass_state in hass_id_to_state.items():+ entity = hass_id_to_entity.get( hass_id )+ if entity:+ self._update_entity( entity = entity,+ hass_state = hass_state,+ result = result )+ else:+ self._create_entity( hass_state = hass_state,+ result = result )+ continue++ for hass_id, entity in hass_id_to_entity.items():+ if hass_id not in hass_id_to_state:+ self._remove_entity( entity = entity,+ result = result )+ continue++ return result++ def _get_hass_entities( self, result : ProcessingResult ) -> Dict[ int, Entity ]:+ logger.debug( 'Getting existing HAss entities.' )+ hass_id_to_entity = dict()++ attribute_queryset = Attribute.objects.select_related( 'entity' ). filter(+ name = AttributeName.INTEGRATION_SOURCE,+ value = IntegrationType.HASS.name,+ )+ for attribute in attribute_queryset:+ hass_entity = attribute.entity+ attribute_map = hass_entity.get_attribute_map()+ attribute = attribute_map.get( str(HassAttributeName.HASS_ENTITY_ID) )+ if attribute and attribute.value:+ hass_id = attribute.value+ else:+ result.error_list.append( f'HAss entity found without valid HAss Id: {hass_entity}' )+ hass_id = 1000000 + hass_entity.id # We need a (unique) placeholder (will remove this later)+ hass_id_to_entity[hass_id] = hass_entity+ continue++ return hass_id_to_entity++ def _get_hass_states( self, result : ProcessingResult ) -> Dict[ int, HassState ]:++ logger.debug( 'Getting current HAss states.' )+ hass_id_to_state = dict()+ for hass_state in self.hass_client.states():+ hass_id = hass_state.entity_id++ hass_id_to_state[hass_id] = hass_state+ continue++ return hass_id_to_state++ def _create_entity( self,+ hass_state : HassState,+ result : ProcessingResult ):++ result.error_list.append( f'Create not yet implemented: {hass_state} [insteon={hass_state.is_insteon}]' )+ return++ def _update_entity( self,+ entity : Entity,+ hass_state : HassState,+ result : ProcessingResult ):++ result.error_list.append( f'Update not yet implemented: {entity}' )++ return++ def _remove_entity( self,+ entity : Entity,+ result : ProcessingResult ):++ result.error_list.append( f'Remove not yet implemented: {entity}' )+ return+diff --git a/src/hi/integrations/hass/hass_state.py b/src/hi/integrations/hass/hass_state.pynew file mode 100644index 00000000..de16d5e6--- /dev/null+++ b/src/hi/integrations/hass/hass_state.py@@ -0,0 +1,34 @@+from typing import Dict+++class HassState:++ def __init__( self, api_dict : Dict ):+ self._api_dict = api_dict+ return++ def __str__(self):+ return f'HassState: {self.entity_id}'++ def __repr__(self):+ return self.__str__()++ @property+ def entity_id(self):+ return self._api_dict.get( 'entity_id' )++ @property+ def attributes(self):+ attributes = self._api_dict.get( 'attributes' )+ if not attributes:+ attributes = dict()+ return attributes++ @property+ def insteon_address(self):+ return self.attributes.get( 'insteon_address' )++ @property+ def is_insteon(self):+ return bool( self.insteon_address is not None )+diff --git a/src/hi/integrations/hass/management/__init__.py b/src/hi/integrations/hass/management/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/integrations/hass/management/commands/__init__.py b/src/hi/integrations/hass/management/commands/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/integrations/hass/management/commands/hass_test.py b/src/hi/integrations/hass/management/commands/hass_test.pynew file mode 100644index 00000000..4f8dede5--- /dev/null+++ b/src/hi/integrations/hass/management/commands/hass_test.py@@ -0,0 +1,30 @@+import json+from requests import get++from django.core.management.base import BaseCommand++from hi.apps.common.command_utils import CommandLoggerMixin+++class Command( BaseCommand, CommandLoggerMixin ):+ """ Used for ad-hoc testing and explorations during development of the Zoneminder integration. """++ help = 'Check HAss API functionality.'++ def handle(self, *args, **options):+ self.info( 'HAss API Test' )++ url = 'http://bordeaux:8123/api/states'+ token = '--REDACTED--'++ headers = {+ 'Authorization': f'Bearer {token}',+ 'content-type':'application/json',+ }++ response = get(url, headers=headers)+ data = json.loads(response.text)+ print( json.dumps( data, indent=4, sort_keys=True ))++ print( f'Total states = {len(data)}' )+ returndiff --git a/src/hi/integrations/hass/migrations/__init__.py b/src/hi/integrations/hass/migrations/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/integrations/hass/templates/hass/panes/activate.html b/src/hi/integrations/hass/templates/hass/panes/activate.htmlnew file mode 100644index 00000000..9bc205cb--- /dev/null+++ b/src/hi/integrations/hass/templates/hass/panes/activate.html@@ -0,0 +1,3 @@+<h3>HAss Activate</h3>++TBDdiff --git a/src/hi/integrations/hass/templates/hass/panes/deactivate.html b/src/hi/integrations/hass/templates/hass/panes/deactivate.htmlnew file mode 100644index 00000000..0e518cb4--- /dev/null+++ b/src/hi/integrations/hass/templates/hass/panes/deactivate.html@@ -0,0 +1,3 @@+<h3>HAss Deactivate</h3>++TBDdiff --git a/src/hi/integrations/hass/templates/hass/panes/manage.html b/src/hi/integrations/hass/templates/hass/panes/manage.htmlnew file mode 100644index 00000000..3cf8b7b6--- /dev/null+++ b/src/hi/integrations/hass/templates/hass/panes/manage.html@@ -0,0 +1,14 @@+<h3>HAss Integration</h3>++{% if processing_result %}+{% include "common/processing_result.html" with processing_result=processing_result %}+{% endif %}++<div class="col-2">+ <form action="{% url 'integration_manage' name=integration_type.name %}"+ method="POST" role="form" data-async="#hi-config-integration-tab">+ {% csrf_token %}+ <button type="submit" class="btn btn-primary btn-control" role="button"+ name="action" value="sync" >SYNC</button>+ </form>+</div>diff --git a/src/hi/integrations/hass/views.py b/src/hi/integrations/hass/views.pynew file mode 100644index 00000000..f1a7b4cb--- /dev/null+++ b/src/hi/integrations/hass/views.py@@ -0,0 +1,53 @@+from django.shortcuts import render+from django.views.generic import View++from hi.integrations.core.enums import IntegrationType++from .hass_manager import HassManager+++class HassEnableView( View ):++ def post(self, request, *args, **kwargs):+++ # TODO:+ # Check if have all needed properties+ # If not, render form for entering with button to activate++ context = {+ }+ return render( request, 'hass/panes/activate.html', context )+++class HassDisableView( View ):++ def post(self, request, *args, **kwargs):++ context = {+ }+ return render( request, 'hass/panes/deactivate.html', context )+++class HassManageView( View ):++ def get(self, request, *args, **kwargs):++ context = {+ 'integration_type': IntegrationType.HASS+ }+ return render( request, 'hass/panes/manage.html', context )+++class HassSyncView( View ):++ def post(self, request, *args, **kwargs):++ processing_result = HassManager().sync()++ context = {+ 'integration_type': IntegrationType.HASS,+ 'processing_result': processing_result,+ }+ return render( request, 'hass/panes/manage.html', context )+diff --git a/src/hi/integrations/zoneminder/zm_manager.py b/src/hi/integrations/zoneminder/zm_manager.pyindex 4a71f3c1..a3f865c4 100644--- a/src/hi/integrations/zoneminder/zm_manager.py+++ b/src/hi/integrations/zoneminder/zm_manager.py@@ -63,7 +63,7 @@ class ZoneMinderManager( Singleton ):try:zm_integration = Integration.objects.get( integration_type_str = str(IntegrationType.ZONEMINDER) )except Integration.DoesNotExist:- logger.debug( 'ZoneMinder integration is not enabled.' )+ logger.debug( 'ZoneMinder integration is not implemented.' )if not zm_integration.is_enabled:logger.debug( 'ZoneMinder integration is not enabled.' )diff --git a/src/hi/requirements/base.txt b/src/hi/requirements/base.txtindex 45e7dddc..531caa9d 100644--- a/src/hi/requirements/base.txt+++ b/src/hi/requirements/base.txt@@ -1,22 +1,32 @@-Django==4.2.15-SQLAlchemy==1.3.24+aiofiles==24.1.0+aiohappyeyeballs==2.4.0+aiohttp==3.10.5+aiosignal==1.3.1asgiref==3.8.1+attrs==24.2.0certifi==2024.7.4charset-normalizer==3.3.2dateparser==1.2.0+Django==4.2.15django-constance==3.1.0django-csp==3.8django-picklefield==3.2django-pipeline-csscompressor==0.1django-pipeline==3.1.0+frozenlist==1.4.1idna==3.7imutils==0.5.4+multidict==6.0.5mysql-connector-python==9.0.0numpy==2.1.0pillow==10.4.0portalocker==2.10.1progressbar2==4.4.2psutil==6.0.0+pyinsteon==1.6.3+Pypubsub==4.0.3+pyserial-asyncio==0.6+pyserial==3.5python-dateutil==2.9.0.post0python-dotenv==1.0.1python-utils==3.8.2@@ -26,8 +36,11 @@ pyzm==0.3.64regex==2024.7.24shapely==2.0.6six==1.16.0+SQLAlchemy==1.3.24sqlparse==0.5.1typing_extensions==4.12.2tzlocal==5.2urllib3==2.2.2+voluptuous==0.15.2websocket-client==1.8.0+yarl==1.9.4diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex 7f07c30a..1f4c28bd 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -144,6 +144,7 @@ INSTALLED_APPS = ['hi.apps.control','hi.integrations.core','hi.integrations.zoneminder',+ 'hi.integrations.hass',]MIDDLEWARE = [