Home Information - Your home, your data, organized.
Python
Fixes and refactoring preparing for HAss controller implementation.
Anthony Cassandra99f45c3c473b
diff --git a/src/hi/apps/control/controller_manager.py b/src/hi/apps/control/controller_manager.pyindex d084a039..1e9b437f 100644--- a/src/hi/apps/control/controller_manager.py+++ b/src/hi/apps/control/controller_manager.py@@ -15,7 +15,7 @@ class ControllerManager( Singleton ):def __init_singleton__( self ):return- def get_controller_data( self, controller : Controller, error_messages : List[ str ] = None ):+ def get_controller_data( self, controller : Controller, error_list : List[ str ] = None ):latest_sensor_response = StatusDisplayControllerHelper().get_latest_sensor_response(controller = controller,@@ -23,5 +23,5 @@ class ControllerManager( Singleton ):return ControllerData(controller = controller,latest_sensor_response = latest_sensor_response,- error_messages = error_messages,+ error_list = error_list,)diff --git a/src/hi/apps/control/templates/control/panes/controller_data.html b/src/hi/apps/control/templates/control/panes/controller_data.htmlindex 01c12159..dee35529 100644--- a/src/hi/apps/control/templates/control/panes/controller_data.html+++ b/src/hi/apps/control/templates/control/panes/controller_data.html@@ -7,6 +7,14 @@{% csrf_token %}{% include_with_fallback controller_data.controller.entity_state.entity_state_type.controller_template_name "control/panes/controller_default.html" %}-+ {% if controller_data.error_list %}+ <div class="text-danger">+ <ul>+ {% for msg in controller_data.error_list %}+ <li>{{ msg }}</li>+ {% endfor %}+ </ul>+ </div>+ {% endif %}</form></div>diff --git a/src/hi/apps/control/transient_models.py b/src/hi/apps/control/transient_models.pyindex e8d3c144..fdf4bcc6 100644--- a/src/hi/apps/control/transient_models.py+++ b/src/hi/apps/control/transient_models.py@@ -10,6 +10,6 @@ from .models import Controllerclass ControllerData:controller : Controllerlatest_sensor_response : SensorResponse- error_messages : List[ str ] = None+ error_list : List[ str ] = Nonediff --git a/src/hi/apps/control/view_mixin.py b/src/hi/apps/control/view_mixin.pyindex 4ab47050..14e82bbd 100644--- a/src/hi/apps/control/view_mixin.py+++ b/src/hi/apps/control/view_mixin.py@@ -23,14 +23,18 @@ class ControlViewMixin:raise Http404( request )def controller_data_response( self,- request : HttpRequest,- controller : Controller,- error_messages : List[ str ] ) -> HttpResponse:+ request : HttpRequest,+ controller : Controller,+ error_list : List[ str ],+ override_sensor_value : str = None ) -> HttpResponse:controller_data = ControllerManager().get_controller_data(controller = controller,- error_messages = error_messages,+ error_list = error_list,)+ if controller_data.latest_sensor_response and ( override_sensor_value is not None ):+ controller_data.latest_sensor_response.value = override_sensor_value+context = {'controller_data': controller_data,}diff --git a/src/hi/apps/control/views.py b/src/hi/apps/control/views.pyindex 70ef7f09..a1da8de8 100644--- a/src/hi/apps/control/views.py+++ b/src/hi/apps/control/views.py@@ -15,34 +15,23 @@ class ControllerView( View, ControlViewMixin ):control_value = request.POST.get( 'value' )logger.debug( f'Setting discrete controller = "{control_value}"' )----- # Check the entity_state_type and sanity check/conmvert as needed.-- # zzz Sanity check value is in value_range--- # zzz Check against latest state value????-- integration_factory = IntegrationFactory()integration_gateway = IntegrationFactory().get_integration_gateway(integration_id = controller.integration_id,)integration_controller = integration_gateway.get_controller()-- error_messages = list()--control_result = integration_controller.do_control(integration_key = controller.integration_key,control_value = control_value,)-+ if control_result.has_errors:+ override_sensor_value = None+ else:+ override_sensor_value = control_value+return self.controller_data_response(request = request,controller = controller,- error_messages = error_messages,+ error_list = control_result.error_list,+ override_sensor_value = override_sensor_value,)diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.pyindex 46e53971..de5e0f52 100644--- a/src/hi/apps/sense/sensor_response_manager.py+++ b/src/hi/apps/sense/sensor_response_manager.py@@ -69,6 +69,7 @@ class SensorResponseManager( Singleton ):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:diff --git a/src/hi/integrations/core/transient_models.py b/src/hi/integrations/core/transient_models.pyindex d68397e9..fd8f152d 100644--- a/src/hi/integrations/core/transient_models.py+++ b/src/hi/integrations/core/transient_models.py@@ -1,6 +1,5 @@from dataclasses import dataclass--from hi.apps.common.processing_result import ProcessingResult+from typing import Listfrom .enums import IntegrationAttributeTypefrom .models import Integration@@ -25,5 +24,11 @@ class IntegrationData:@dataclassclass IntegrationControlResult:- new_value : str- processing_result : ProcessingResult++ new_value : str+ error_list : List[ str ]++ @property+ def has_errors(self):+ return bool( self.error_list )+diff --git a/src/hi/integrations/hass/hass_controller.py b/src/hi/integrations/hass/hass_controller.pyindex 59c0ae45..65a5381c 100644--- a/src/hi/integrations/hass/hass_controller.py+++ b/src/hi/integrations/hass/hass_controller.py@@ -1,15 +1,30 @@+import logging+from hi.integrations.core.integration_controller import IntegrationControllerfrom hi.integrations.core.integration_key import IntegrationKeyfrom hi.integrations.core.transient_models import IntegrationControlResult+from .hass_manager import HassManager++logger = logging.getLogger(__name__)+class HassController( IntegrationController ):+ def __init__(self):+ self._hass_manager = HassManager()+ return+def do_control( self,integration_key : IntegrationKey,control_value : str ) -> IntegrationControlResult:+ try:- # zzz Needs implementation-- return IntegrationControlResult()+ raise ValueError( 'HAss controls not implemented.' )+ except Exception as e:+ logger.warning( f'Exception in HAss do_control: {e}' )+ return IntegrationControlResult(+ new_value = None,+ error_list = [ str(e) ],+ )diff --git a/src/hi/integrations/zoneminder/zm_controller.py b/src/hi/integrations/zoneminder/zm_controller.pyindex 64e9fb62..4370a0e7 100644--- a/src/hi/integrations/zoneminder/zm_controller.py+++ b/src/hi/integrations/zoneminder/zm_controller.py@@ -1,8 +1,6 @@import loggingimport re-from hi.apps.common.processing_result import ProcessingResult-from hi.integrations.core.integration_controller import IntegrationControllerfrom hi.integrations.core.integration_key import IntegrationKeyfrom hi.integrations.core.transient_models import IntegrationControlResult@@ -21,77 +19,58 @@ class ZoneMinderController( IntegrationController ):def do_control( self,integration_key : IntegrationKey,control_value : str ) -> IntegrationControlResult:+ try:+ if integration_key.integration_name == self._zm_manager.ZM_RUN_STATE_SENSOR_INTEGRATION_NAME:+ return self.set_run_state( run_state_value = control_value )- if integration_key.integration_name == self._zm_manager.ZM_RUN_STATE_SENSOR_INTEGRATION_NAME:- return self.set_run_state( run_state_value = control_value )-- if integration_key.integration_name.startswith( self._zm_manager.MONITOR_FUNCTION_SENSOR_PREFIX ):- m = re.match( r'.+\D(\d+)', integration_key.integration_name )- if m:- return self.set_monitor_function(- monitor_id = m.group(1),- function_value = control_value,- )-- logger.warning( f'Unknown ZM control action. key={integration_key}, value={control_value}' )- return IntegrationControlResult(- new_value = None,- error_messages = [ 'Unknown ZM control action.' ]- )+ if integration_key.integration_name.startswith( self._zm_manager.MONITOR_FUNCTION_SENSOR_PREFIX ):+ m = re.match( r'.+\D(\d+)', integration_key.integration_name )+ if m:+ return self.set_monitor_function(+ monitor_id = m.group(1),+ function_value = control_value,+ )++ logger.warning( f'ZM action undefined. key={integration_key}, value={control_value}' )+ raise ValueError( 'Unknown ZM control action.' )- def set_run_state( self, run_state_value : str ):- result = ProcessingResult( title = 'ZM Set Monitors' )- try:- response = self._zm_manager._zm_client.set_state( run_state_value )- logger.debug( f'ZM Set run state to "{run_state_value}" = {response}' )- return IntegrationControlResult(- new_value = run_state_value,- processing_result = result,- )except Exception as e:- logger.error( f'Exception setting ZM run state: {e}' )- result.error_list.append( str(e) )+ logger.warning( f'Exception in ZM do_control: {e}' )return IntegrationControlResult(new_value = None,- processing_result = result,+ error_list = [ str(e) ],)finally:self._zm_manager.clear_caches()+ def set_run_state( self, run_state_value : str ):+ response = self._zm_manager._zm_client.set_state( run_state_value )+ logger.debug( f'ZM Set run state to "{run_state_value}" = {response}' )+ return IntegrationControlResult(+ new_value = run_state_value,+ error_list = [],+ )+def set_monitor_function( self,monitor_id : str,function_value : str ):- result = ProcessingResult( title = 'ZM Set Monitor Function' )- try:- zm_monitor_list = self._zm_manager.get_zm_monitors()- for zm_monitor in zm_monitor_list:- if str(zm_monitor.id()) == str(monitor_id):- response = zm_monitor.set_parameter({- 'function': function_value,- })- logger.debug( f'ZM Set monitor: {monitor_id}={function_value}, response={response}' )- response_message = response.get('message')- if response_message and ( 'error' in response_message.lower() ):- result.error_list.append( 'Problen setting ZM monitor function.')- return IntegrationControlResult(- new_value = function_value,- processing_result = result,- )- else:- logger.debug( f'Skipping ZM monitor: {zm_monitor.id()} != {monitor_id}' )- continue+ zm_monitor_list = self._zm_manager.get_zm_monitors()+ for zm_monitor in zm_monitor_list:+ if str(zm_monitor.id()) == str(monitor_id):+ response = zm_monitor.set_parameter({+ 'function': function_value,+ })+ logger.debug( f'ZM Set monitor: {monitor_id}={function_value}, response={response}' )+ response_message = response.get('message')+ if response_message and ( 'error' in response_message.lower() ):+ raise ValueError( 'Problen setting ZM monitor function.')- result.error_list.append( 'Unknown ZM monitor.')- return IntegrationControlResult(- new_value = None,- processing_result = result,- )- except Exception as e:- logger.error( f'Exception setting ZM monitor function: {e}' )- result.error_list.append( str(e) )- return IntegrationControlResult(- new_value = None,- processing_result = result,- )- finally:- self._zm_manager.clear_caches()+ return IntegrationControlResult(+ new_value = function_value,+ error_list = [],+ )+ else:+ logger.debug( f'Skipping ZM monitor: {zm_monitor.id()} != {monitor_id}' )+ continue++ raise ValueError( 'Unknown ZM entity.')diff --git a/src/hi/integrations/zoneminder/zm_manager.py b/src/hi/integrations/zoneminder/zm_manager.pyindex 56bfc81b..4d0fa0d6 100644--- a/src/hi/integrations/zoneminder/zm_manager.py+++ b/src/hi/integrations/zoneminder/zm_manager.py@@ -26,7 +26,8 @@ class ZoneMinderManager( Singleton ):ZM Api code: https://github.com/ZoneMinder/zoneminder/tree/master/web/api/app/ControllerPyZM code: https://github.com/pliablepixels/pyzm/tree/357fdbd1937dab8027882598b61258ef43dc366a"""-+ TRACE = False+ZM_ENTITY_NAME = 'ZoneMinder'ZM_SYSTEM_INTEGRATION_NAME = 'system'ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'@@ -128,7 +129,8 @@ class ZoneMinderManager( Singleton ):or ( state_list_age.seconds > self.STATE_REFRESH_INTERVAL_SECS )):self._zm_state_list = self.zm_client.states().list()self._zm_state_timestamp = datetimeproxy.now()- logger.debug( f'Fetched ZM states: {self._zm_state_list}' )+ if self.TRACE:+ logger.debug( f'Fetched ZM states: {[ x.get() for x in self._zm_state_list ]}' )return self._zm_state_listdef get_zm_monitors( self, force_load : bool = False ) -> List[ ZmMonitor ]:@@ -136,9 +138,14 @@ class ZoneMinderManager( Singleton ):if ( force_loador ( not self._zm_monitor_list )or ( monitor_list_age.seconds > self.MONITOR_REFRESH_INTERVAL_SECS )):- self._zm_monitor_list = self.zm_client.monitors().list()+ options = {+ 'force_reload': True, # pyzm caches monitors so need to force api call+ }+ self._zm_monitor_list = self.zm_client.monitors( options ).list()self._zm_monitor_timestamp = datetimeproxy.now()- logger.debug( f'Fetched ZM monitors: {self._zm_monitor_list}' )+ if self.TRACE:+ logger.debug( f'\n\nFetched ZM monitors: {[ x.get() for x in self._zm_monitor_list ]}\n\n' )+return self._zm_monitor_listdef get_zm_events( self, options : Dict[ str, str ] ) -> List[ ZmEvent ]: