Home Information - Your home, your data, organized.
Python
Home Assistant API simulator now working.
Anthony Cassandra5e1e5cd5c48f
diff --git a/src/hi/apps/common/templatetags/common_template_helpers.py b/src/hi/apps/common/templatetags/common_template_helpers.pyindex 44269342..44bff201 100644--- a/src/hi/apps/common/templatetags/common_template_helpers.py+++ b/src/hi/apps/common/templatetags/common_template_helpers.py@@ -19,9 +19,7 @@ def get_item(dictionary, key):@register.simple_tagdef generate_uuid():- uuid_value = str(uuid.uuid4())- print(f"\n\nGenerated UUID: {uuid_value}\n")- return uuid_value+ return str(uuid.uuid4())@register.simple_tagdiff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/status_display_data.pyindex 081bced9..88f85492 100644--- a/src/hi/apps/monitor/status_display_data.py+++ b/src/hi/apps/monitor/status_display_data.py@@ -58,9 +58,23 @@ class StatusStyle:)Open = SvgStatusStyle(status_value = 'open',- stroke_color = 'green',+ stroke_color = 'red',stroke_width = DEFAULT_STROKE_WIDTH,- fill_color = 'green',+ fill_color = 'red',+ fill_opacity = 0.5,+ )+ OpenRecent = SvgStatusStyle(+ status_value = 'recent',+ stroke_color = 'orange',+ stroke_width = DEFAULT_STROKE_WIDTH,+ fill_color = 'orange',+ fill_opacity = 0.5,+ )+ OpenPast = SvgStatusStyle(+ status_value = 'past',+ stroke_color = 'yellow',+ stroke_width = DEFAULT_STROKE_WIDTH,+ fill_color = 'yellow',fill_opacity = 0.5,)Closed = SvgStatusStyle(@@ -115,6 +129,9 @@ class StatusDisplayData:RECENT_MOVEMENT_THRESHOLD_SECS = 90PAST_MOVEMENT_THRESHOLD_SECS = 180+ RECENT_OPEN_THRESHOLD_SECS = 90+ PAST_OPEN_THRESHOLD_SECS = 180+def __init__( self, entity_state_status_data : EntityStateStatusData ):self._entity_state = entity_state_status_data.entity_stateself._sensor_response_list = entity_state_status_data.sensor_response_list@@ -258,9 +275,16 @@ class StatusDisplayData:if self.latest_sensor_value == str(EntityStateValue.OPEN):return StatusStyle.Open- if self.latest_sensor_value == str(EntityStateValue.CLOSED):- return StatusStyle.Closed- return None++ if self.penultimate_sensor_value == str(EntityStateValue.OPEN):+ open_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp+ if open_timedelta.total_seconds() < self.RECENT_OPEN_THRESHOLD_SECS:+ return StatusStyle.OpenRecent++ elif open_timedelta.total_seconds() < self.PAST_OPEN_THRESHOLD_SECS:+ return StatusStyle.OpenPast++ return StatusStyle.Closeddef _get_connectivity_status_style( self ):diff --git a/src/hi/services/hass/hass_client.py b/src/hi/services/hass/hass_client.pyindex 999c7f51..a87a00bc 100644--- a/src/hi/services/hass/hass_client.py+++ b/src/hi/services/hass/hass_client.py@@ -1,10 +1,13 @@import json+import loggingfrom requests import get, postfrom typing import Dict, Listfrom .hass_converter import HassConverterfrom .hass_models import HassState+logger = logging.getLogger(__name__)+class HassClient:@@ -13,6 +16,8 @@ class HassClient:API_BASE_URL = 'api_base_url'API_TOKEN = 'api_token'+ TRACE = True+def __init__( self, api_options : Dict[ str, str ] ):self._api_base_url = api_options.get( self.API_BASE_URL )@@ -34,6 +39,8 @@ class HassClient:url = f'{self._api_base_url}/api/states'response = get( url, headers = self._headers )data = json.loads(response.text)+ if self.TRACE:+ logger.debug( f'HAss Response = {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:diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.pyindex 22b16395..5da7931c 100644--- a/src/hi/services/zoneminder/monitors.py+++ b/src/hi/services/zoneminder/monitors.py@@ -23,7 +23,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )ZONEMINDER_SERVER_TIMEZONE = 'America/Chicago'ZONEMINDER_POLLING_INTERVAL_SECS = 10- TRACE = True+ TRACE = FalseCACHING_DISABLED = Truedef __init__( self ):diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.pyindex cdd6d875..2e6af913 100644--- a/src/hi/services/zoneminder/zm_manager.py+++ b/src/hi/services/zoneminder/zm_manager.py@@ -28,7 +28,7 @@ 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 = True+ TRACE = FalseZM_ENTITY_NAME = 'ZoneMinder'ZM_SYSTEM_INTEGRATION_NAME = 'system'diff --git a/src/hi/simulator/services/hass/api/views.py b/src/hi/simulator/services/hass/api/views.pyindex 917a8b11..e51d9947 100644--- a/src/hi/simulator/services/hass/api/views.py+++ b/src/hi/simulator/services/hass/api/views.py@@ -1,19 +1,25 @@+import logging+from django.http import JsonResponsefrom django.views.generic import View-from hi.simulator.services.hass.sim_models import HassInsteonLightSwitch+from hi.simulator.services.hass.simulator import HassSimulator++logger = logging.getLogger(__name__)class StatesView( View ):def get(self, request, *args, **kwargs):+ try:+ hass_simulator = HassSimulator()+ zm_monitor_sim_entity_list = hass_simulator.get_hass_sim_state_list()+ return JsonResponse( [ x.to_api_dict() for x in zm_monitor_sim_entity_list ], safe = False )++ except Exception as e:+ logger.exception( 'Problem processing HAss states API request', e )+ return JsonResponse( list(), safe = False )- hass_device = HassInsteonLightSwitch(- friendly_name = 'Kitchen Light',- insteon_address = 'F0.65.D2',- )- return JsonResponse( hass_device.to_api_list(), safe = False )-def post(self, request, *args, **kwargs):passdiff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.pyindex 677814f3..face950a 100644--- a/src/hi/simulator/services/hass/sim_models.py+++ b/src/hi/simulator/services/hass/sim_models.py@@ -5,6 +5,7 @@ import timefrom typing import Dict, List, Tupleimport hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.common.utils import str_to_boolfrom hi.simulator.base_models import SimEntityFields, SimState, SimEntityDefinitionfrom hi.simulator.enums import SimEntityType, SimStateType@@ -81,7 +82,14 @@ class HassInsteonState( HassState ):@propertydef insteon_address(self):return self.sim_entity_fields.insteon_address-++ @property+ def state(self):+ is_on = str_to_bool( self.value )+ if is_on:+ return "on"+ return "off"+@dataclass( frozen = True )class HassInsteonLightSwitchFields( HassInsteonSimEntityFields ):@@ -89,11 +97,11 @@ class HassInsteonLightSwitchFields( HassInsteonSimEntityFields ):@dataclass-class HassInsteonLightSwitchLightState( HassInsteonState ):+class HassInsteonLightSwitchState( HassInsteonState ):sim_entity_fields : HassInsteonLightSwitchFieldssim_state_type : SimStateType = SimStateType.ON_OFF- sim_state_id : str = 'light'+ sim_state_id : str = 'switch'@propertydef name(self):@@ -101,7 +109,7 @@ class HassInsteonLightSwitchLightState( HassInsteonState ):@propertydef entity_id(self):- return 'light.switchlinc_relay_%s' % self.insteon_address.replace( '.', '_' )+ return 'switch.switchlinc_relay_%s' % self.insteon_address.replace( '.', '_' )@propertydef attributes(self) -> Dict[ str, str ]:@@ -112,22 +120,17 @@ class HassInsteonLightSwitchLightState( HassInsteonState ):"insteon_group": 1,}- @property- def state(self):- # TODO: Do translation to HAss state values- return 'unknown'-@dataclass-class HassInsteonLightSwitchColorState( HassInsteonState ):+class HassInsteonLightLightState( HassInsteonState ):sim_entity_fields : HassInsteonLightSwitchFieldssim_state_type : SimStateType = SimStateType.ON_OFF- sim_state_id : str = 'color'+ sim_state_id : str = 'light'@propertydef name(self):- return f'{self.entity_name} Color'+ return f'{self.entity_name} Light'@propertydef entity_id(self):@@ -143,11 +146,22 @@ class HassInsteonLightSwitchColorState( HassInsteonState ):],'supported_features': 0,}++@dataclass+class HassInsteonDualBandLightSwitchState( HassInsteonLightSwitchState ):+@property- def state(self):- # TODO: Do translation to HAss state values- return 'unknown'+ def entity_id(self):+ return 'switch.switchlinc_relay_dual_band_%s' % self.insteon_address.replace( '.', '_' )+++@dataclass+class HassInsteonDualBandLightLightState( HassInsteonLightLightState ):++ @property+ def entity_id(self):+ return 'light.switchlinc_relay_dual_band_%s' % self.insteon_address.replace( '.', '_' )@dataclass( frozen = True )@@ -178,11 +192,6 @@ class HassInsteonMotionDetectorMotionState( HassInsteonState ):"insteon_address": self.insteon_address,"insteon_group": 1,}-- @property- def state(self):- # TODO: Do translation to HAss state values- return 'unknown'@dataclass@@ -208,11 +217,6 @@ class HassInsteonMotionDetectorLightState( HassInsteonState ):"insteon_address": self.insteon_address,"insteon_group": 1,}-- @property- def state(self):- # TODO: Do translation to HAss state values- return 'unknown'@dataclass@@ -246,11 +250,6 @@ class HassInsteonMotionDetectorBatteryState( HassInsteonState ):"insteon_address": self.insteon_address,"insteon_group": 1,}-- @property- def state(self):- # TODO: Do translation to HAss state values- return 'unknown'@dataclass( frozen = True )@@ -278,11 +277,6 @@ class HassInsteonOpenCloseSensorState( HassInsteonState ):"insteon_address": self.insteon_address,"insteon_group": 1,}-- @property- def state(self):- # TODO: Do translation to HAss state values- return 'unknown'HASS_SIM_ENTITY_DEFINITION_LIST = [@@ -291,8 +285,17 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [sim_entity_type = SimEntityType.LIGHT,sim_entity_fields_class = HassInsteonLightSwitchFields,sim_state_class_list = [- HassInsteonLightSwitchLightState,- HassInsteonLightSwitchColorState,+ HassInsteonLightSwitchState,+ HassInsteonLightLightState,+ ],+ ),+ SimEntityDefinition(+ class_label = 'Insteon Light Switch (dual band)',+ sim_entity_type = SimEntityType.LIGHT,+ sim_entity_fields_class = HassInsteonLightSwitchFields,+ sim_state_class_list = [+ HassInsteonDualBandLightSwitchState,+ HassInsteonDualBandLightLightState,],),SimEntityDefinition(diff --git a/src/hi/simulator/services/hass/simulator.py b/src/hi/simulator/services/hass/simulator.pyindex 3a4ee5ef..4e9fa4a3 100644--- a/src/hi/simulator/services/hass/simulator.py+++ b/src/hi/simulator/services/hass/simulator.py@@ -5,7 +5,7 @@ from hi.simulator.exceptions import SimEntityValidationErrorfrom hi.simulator.simulator import Simulatorfrom hi.simulator.sim_entity import SimEntity-from .sim_models import HASS_SIM_ENTITY_DEFINITION_LIST, HassInsteonSimEntityFields+from .sim_models import HASS_SIM_ENTITY_DEFINITION_LIST, HassInsteonSimEntityFields, HassStateclass HassSimulator( Simulator ):@@ -18,6 +18,13 @@ class HassSimulator( Simulator ):def label(self):return 'Home Assistant'+ def get_hass_sim_state_list( self ) -> List[ HassState ]:+ sim_state_list = list()+ for sim_entity in self.sim_entities:+ sim_state_list.extend( sim_entity.sim_state_list )+ continue+ return sim_state_list+@propertydef sim_entity_definition_list(self) -> List[ SimEntityDefinition ]:return HASS_SIM_ENTITY_DEFINITION_LIST