Skip to content

Home Information - Your home, your data, organized.

Python

Simulator support for setting HAss state + bug fixes.

Anthony Cassandraa4656b8cd47c
diff --git a/src/hi/services/hass/hass_client.py b/src/hi/services/hass/hass_client.py
index 4da5a410..feca95f7 100644
--- a/src/hi/services/hass/hass_client.py
+++ b/src/hi/services/hass/hass_client.py
@@ -48,7 +48,6 @@ class HassClient:
}
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}" )
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index 59854c9f..dacb71c0 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -396,16 +396,28 @@ class HassConverter:
# in our data model and we do not need the duplicates that are just
# a HAss-specific need.
- prefix_to_entity_state = dict()
+ prefixes_seen = set()
+ ignore_light_state_prefixes = set()
+
for hass_state in hass_state_list:
- state_integration_key = cls.hass_state_to_integration_key( hass_state = hass_state )
-
+
if (( hass_state.entity_id_prefix == HassApi.SWITCH_ID_PREFIX )
- and ( HassApi.LIGHT_ID_PREFIX in prefix_to_entity_state )):
- continue
+ and ( HassApi.LIGHT_ID_PREFIX in prefixes_seen )):
+ ignore_light_state_prefixes.add( hass_state.entity_id_prefix )
elif (( hass_state.entity_id_prefix == HassApi.LIGHT_ID_PREFIX )
- and ( HassApi.SWITCH_ID_PREFIX in prefix_to_entity_state )):
+ and ( HassApi.SWITCH_ID_PREFIX in prefixes_seen )):
+ ignore_light_state_prefixes.add( hass_state.entity_id_prefix )
+
+ prefixes_seen.add( hass_state.entity_id_prefix )
+ continue
+
+ prefix_to_entity_state = dict()
+ for hass_state in hass_state_list:
+ state_integration_key = cls.hass_state_to_integration_key( hass_state = hass_state )
+
+ if (( hass_state.entity_id_prefix == HassApi.LIGHT_ID_PREFIX )
+ and ( hass_state.entity_id_prefix in ignore_light_state_prefixes )):
continue
entity_state = cls._create_hass_state_sensor_or_controller(
diff --git a/src/hi/simulator/services/hass/api/urls.py b/src/hi/simulator/services/hass/api/urls.py
index 986f4314..702ebeed 100644
--- a/src/hi/simulator/services/hass/api/urls.py
+++ b/src/hi/simulator/services/hass/api/urls.py
@@ -5,10 +5,10 @@ from . import views
urlpatterns = [
re_path( r'^states$',
- views.StatesView.as_view(),
+ views.AllStatesView.as_view(),
name = 'hass_api_states' ),
- re_path( r'^states/(?P<entity_id>\w+)$',
- views.StatesView.as_view(),
+ re_path( r'^states/(?P<entity_id>[\w\._\-]+)$',
+ views.StateView.as_view(),
name = 'hass_api_states_set' ),
]
diff --git a/src/hi/simulator/services/hass/api/views.py b/src/hi/simulator/services/hass/api/views.py
index e51d9947..49218357 100644
--- a/src/hi/simulator/services/hass/api/views.py
+++ b/src/hi/simulator/services/hass/api/views.py
@@ -1,6 +1,10 @@
+import json
import logging
+from django.core.exceptions import BadRequest
from django.http import JsonResponse
+from django.utils.decorators import method_decorator
+from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from hi.simulator.services.hass.simulator import HassSimulator
@@ -8,18 +12,41 @@ from hi.simulator.services.hass.simulator import HassSimulator
logger = logging.getLogger(__name__)
-class StatesView( View ):
+class AllStatesView( 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 )
+ hass_sim_state_list = hass_simulator.get_hass_sim_state_list()
+ return JsonResponse( [ x.to_api_dict() for x in hass_sim_state_list ], safe = False )
except Exception as e:
logger.exception( 'Problem processing HAss states API request', e )
return JsonResponse( list(), safe = False )
+
+@method_decorator(csrf_exempt, name='dispatch')
+class StateView( View ):
+
def post(self, request, *args, **kwargs):
- pass
-
+ try:
+ hass_entity_id = kwargs.get('entity_id')
+ data = json.loads( request.body )
+ value_str = data.get('state')
+ if not value_str:
+ raise BadRequest( 'Request body is missing "state" value.' )
+ logger.debug( f'HAss set state: {hass_entity_id} = {value_str}' )
+
+ hass_simulator = HassSimulator()
+ sim_state = hass_simulator.set_sim_state_by_hass_entity_id(
+ hass_entity_id = hass_entity_id,
+ value_str = value_str,
+ )
+ return JsonResponse( sim_state.to_api_dict(), safe = False )
+
+ except json.JSONDecodeError as jde:
+ raise BadRequest( f'Request body is not JSON: {jde}' )
+
+ except KeyError as ke:
+ raise BadRequest( f'Unknown HAss state: {ke}' )
+
diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.py
index 05804899..a4096807 100644
--- a/src/hi/simulator/services/hass/sim_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -83,6 +83,10 @@ class HassInsteonState( HassState ):
def insteon_address(self):
return self.sim_entity_fields.insteon_address
+ @property
+ def insteon_address_id_suffix(self):
+ return self.insteon_address.replace( '.', '_' ).lower()
+
@property
def state(self):
is_on = str_to_bool( self.value )
@@ -109,7 +113,7 @@ class HassInsteonLightSwitchState( HassInsteonState ):
@property
def entity_id(self):
- return 'switch.switchlinc_relay_%s' % self.insteon_address.replace( '.', '_' )
+ return 'switch.switchlinc_relay_%s' % self.insteon_address_id_suffix
@property
def attributes(self) -> Dict[ str, str ]:
@@ -139,7 +143,7 @@ class HassInsteonDimmerLightLightState( HassInsteonState ):
@property
def entity_id(self):
- return 'light.switchlinc_dimmer_%s' % self.insteon_address.replace( '.', '_' )
+ return 'light.switchlinc_dimmer_%s' % self.insteon_address_id_suffix
@property
def attributes(self) -> Dict[ str, str ]:
@@ -164,7 +168,7 @@ class HassInsteonDualBandLightSwitchState( HassInsteonLightSwitchState ):
@property
def entity_id(self):
- return 'switch.switchlinc_relay_dual_band_%s' % self.insteon_address.replace( '.', '_' )
+ return 'switch.switchlinc_relay_dual_band_%s' % self.insteon_address_id_suffix
@dataclass( frozen = True )
@@ -185,7 +189,7 @@ class HassInsteonMotionDetectorMotionState( HassInsteonState ):
@property
def entity_id(self):
- return 'binary_sensor.motion_sensor_%s_motion' % self.insteon_address.replace( '.', '_' )
+ return 'binary_sensor.motion_sensor_%s_motion' % self.insteon_address_id_suffix
@property
def attributes(self) -> Dict[ str, str ]:
@@ -210,7 +214,7 @@ class HassInsteonMotionDetectorLightState( HassInsteonState ):
@property
def entity_id(self):
- return 'binary_sensor.motion_sensor_%s_light' % self.insteon_address.replace( '.', '_' )
+ return 'binary_sensor.motion_sensor_%s_light' % self.insteon_address_id_suffix
@property
def attributes(self) -> Dict[ str, str ]:
@@ -243,7 +247,7 @@ class HassInsteonMotionDetectorBatteryState( HassInsteonState ):
@property
def entity_id(self):
- return 'binary_sensor.motion_sensor_%s_battery' % self.insteon_address.replace( '.', '_' )
+ return 'binary_sensor.motion_sensor_%s_battery' % self.insteon_address_id_suffix
@property
def attributes(self) -> Dict[ str, str ]:
@@ -269,7 +273,7 @@ class HassInsteonOpenCloseSensorState( HassInsteonState ):
@property
def entity_id(self):
- return 'binary_sensor.open_close_sensor_%s' % self.insteon_address.replace( '.', '_' )
+ return 'binary_sensor.open_close_sensor_%s' % self.insteon_address_id_suffix
@property
def attributes(self) -> Dict[ str, str ]:
@@ -300,7 +304,7 @@ class HassInsteonOutletState( HassInsteonState ):
@property
def entity_id(self):
- return 'switch.outletlinc_relay_%s' % self.insteon_address.replace( '.', '_' )
+ return 'switch.outletlinc_relay_%s' % self.insteon_address_id_suffix
@property
def attributes(self) -> Dict[ str, str ]:
diff --git a/src/hi/simulator/simulator.py b/src/hi/simulator/simulator.py
index ef47cc66..646480f4 100644
--- a/src/hi/simulator/simulator.py
+++ b/src/hi/simulator/simulator.py
@@ -133,6 +133,18 @@ class Simulator( Singleton ):
value_str = value_str,
)
-
+ def set_sim_state_by_hass_entity_id( self,
+ hass_entity_id : str,
+ value_str : str ) -> SimState:
+ for sim_entity in self._sim_entity_map.values():
+ for sim_state in sim_entity.sim_state_list:
+ if sim_state.entity_id == hass_entity_id:
+ return sim_entity.set_sim_state(
+ sim_state_id = sim_state.sim_state_id,
+ value_str = value_str,
+ )
+ continue
+ continue
+ raise KeyError( f'HAss entity {hass_entity_id} does not exist.' )