Home Information - Your home, your data, organized.
Python
Issue #319: EntityStateRole for semantic role per EntityState (#322)
Tony Cd2449ef0fc2e
diff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.mdindex a554306f..d45fe933 100644--- a/docs/dev/integrations/integration-guidelines.md+++ b/docs/dev/integrations/integration-guidelines.md@@ -29,6 +29,22 @@ The symmetric server ↔ UI boundary uses `ConsoleConverterHelper`; see [Fronten### Responsibility BoundariesIntegrations create `SensorResponse` objects which become `Event` objects with duration. The Event duration is the only accessible duration data - Event objects don't know about underlying integration specifics.+### EntityStateType vs. EntityStateRole+Each `EntityState` carries two independent axes:++- **`EntityStateType`** — local value semantics: value storage, unit handling, value-to-label translation, per-value rendering template. Answers "how do I store / interpret / render this value?"+- **`EntityStateRole`** — the state's contextual identity within its enclosing entity. Answers "what role does this state play in its entity's composite presentation?"++For multi-state entities where multiple `EntityState` instances share the same `EntityStateType` (a thermostat's current vs. target temperatures; a fan's direction vs. preset_mode), the role is what disambiguates them downstream. Every `EntityStateType` has a default `EntityStateRole` with the same name (e.g., `EntityStateType.TEMPERATURE` → `EntityStateRole.TEMPERATURE`), so an `EntityState` saved without an explicit role still has one — automatically.++Two tiers of role member coexist in the same enum:+- **Type-default roles** — one per `EntityStateType`, name-matched. Applied automatically at `EntityState` save time when no explicit role is set. Unchanged integrations get these for free.+- **Domain-prefixed refinements** — `THERMOSTAT_CURRENT_TEMPERATURE`, `FAN_SPEED`, `LIGHT_BRIGHTNESS`, etc. Integrations set these explicitly where the domain calls for it (typically in substate spec lists).++The integration's job is to **declare what each state means** via its role. Presentation order is HI's responsibility, applied via per-EntityType `EntityStateRoleOrdering` instances in `hi.apps.entity.entity_state_role_order`. New EntityTypes or new roles get added to those tables as needed.++See `hi/services/hass/hass_converter.py` (climate / fan / light state-spec lists) for the pattern: each `_StateSpec` may carry an explicit `role` field; the spec → `EntityState` creation passes it through.+## Code Conventions### File layout and namingdiff --git a/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html b/src/hi/apps/collection/templates/collection/panes/entity_card_grid.htmlindex 96ac642e..06ea9783 100644--- a/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html+++ b/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html@@ -6,7 +6,7 @@{% include "console/panes/entity_video_stream_w_link.html" with entity=entity_status_data.entity %}</div>{% else %}- {% include "collection/panes/entity_state_list.html" with entity_state_status_data_list=entity_status_data.entity_state_status_data_list %}+ {% include "collection/panes/entity_state_list.html" with entity_state_status_data_list=entity_status_data.state_status_data_list %}{% endif %}</div></div>diff --git a/src/hi/apps/collection/templates/collection/panes/entity_card_list.html b/src/hi/apps/collection/templates/collection/panes/entity_card_list.htmlindex 40c0b7f9..e789a1a3 100644--- a/src/hi/apps/collection/templates/collection/panes/entity_card_list.html+++ b/src/hi/apps/collection/templates/collection/panes/entity_card_list.html@@ -10,7 +10,7 @@</div>{% else %}<div class="entity-content-section flex-grow-1 ml-3">- {% include "collection/panes/entity_state_list.html" with entity_state_status_data_list=entity_status_data.entity_state_status_data_list %}+ {% include "collection/panes/entity_state_list.html" with entity_state_status_data_list=entity_status_data.state_status_data_list %}</div>{% endif %}</div>diff --git a/src/hi/apps/collection/templates/collection/panes/entity_state_row.html b/src/hi/apps/collection/templates/collection/panes/entity_state_row.htmlindex d114222e..b7f9dbc7 100644--- a/src/hi/apps/collection/templates/collection/panes/entity_state_row.html+++ b/src/hi/apps/collection/templates/collection/panes/entity_state_row.html@@ -10,7 +10,11 @@{% elif entity_state_status_data.sensor_response_list %}<div class="text-muted text-center"><small>{{ sensor_response.sensor.name }}</small></div>-{% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}+{# Per-state CSS class wrapper so polling updates land via the #}+{# entity_state_status.js dispatcher (selector: .{css_class}). #}+<div class="{{ sensor_response.css_class }}">+ {% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}+</div>{% elif entity_state_status_data.has_sensor %}<div class="alert alert-info">{{ entity_state_status_data.entity_state.name }}: awaiting sensor reading.</div>diff --git a/src/hi/apps/control/one_click_control_service.py b/src/hi/apps/control/one_click_control_service.pyindex 3948ae54..8a1f9ba9 100644--- a/src/hi/apps/control/one_click_control_service.py+++ b/src/hi/apps/control/one_click_control_service.py@@ -3,8 +3,8 @@ from typing import Optionalfrom hi.apps.control.controller_manager import ControllerManagerfrom hi.apps.control.models import Controller+from hi.apps.entity.entity_state_role_order import ENTITY_CONTROL_STATE_ORDERINGfrom hi.apps.entity.models import Entity, EntityState-from hi.apps.location.enums import LocationViewTypefrom hi.apps.monitor.status_display_manager import StatusDisplayManagerfrom .transient_models import ControllerOutcome@@ -13,43 +13,30 @@ logger = logging.getLogger(__name__)class OneClickNotSupported(Exception):- """Raised when EntityStateType doesn't support one-click control."""+ """Raised when an entity has no one-click control target."""passclass OneClickError(Exception):- """Raised when EntityStateType has erro being set."""+ """Raised when a one-click control attempt fails."""passclass OneClickControlService:- """- Service responsible for complete one-click control flow:- - Priority resolution and controller selection- - Current state detection for proper toggle behavior- - Control execution and outcome reporting+ """One-click control flow: pick a target state via role priority,+ determine the next toggle value, dispatch the control. Whether+ one-click is *invoked* in a given context is the caller's+ decision (currently only the AUTOMATION LocationViewType does so);+ this service answers "for this entity, what would one-click do?""""- # Although we can cycle through a value enumeration of any length to- # have a one-click behavior. This is not going to be useful past a- # certain point, so we best limit one-click behavior to simpler- # controllers.- #+ # Toggling cycles through ``EntityState.toggle_values()``. Past a+ # certain length the cycle stops being a usable one-click+ # affordance, so we cap discrete one-click eligibility here.ONE_CLICK_CHOICE_LIMIT = 3-- def execute_one_click_control(- self,- entity : Entity,- location_view_type : LocationViewType = None ) -> ControllerOutcome:- """- Execute complete one-click control flow: decision, state detection, execution.- Convenience wrapper around ControllerManager.do_control().- Raises OneClickNotSupported if control cannot be attempted.- """- controller = self._find_controller(- entity = entity,- location_view_type = location_view_type,- )++ def execute_one_click_control( self, entity : Entity ) -> ControllerOutcome:+ controller = self._find_controller( entity = entity )current_value = self._get_current_state_value(entity_state = controller.entity_state,)@@ -58,41 +45,54 @@ class OneClickControlService:current_value = current_value,)logger.debug( f'Calling control: {entity} : {current_value} -> {target_value}' )-+return ControllerManager().do_control(controller = controller,control_value = target_value,)-- def _find_controller( self,- entity : Entity,- location_view_type : LocationViewType = None ) -> Controller:- """Find highest priority EntityState that has controllers and is supported.-- We only want one-click controls to apply the entity state being- used in the display status. Thus, we make sure we use the same- logic to pick the entity state, then see if it has a controller.- """-- if not location_view_type:- location_view_type = LocationViewType.default()- priority_list = location_view_type.entity_state_type_priority_list-- entity_state_list = StatusDisplayManager().get_entity_state_list_for_status(++ def _find_controller( self, entity : Entity ) -> Controller:+ """Find a toggle-eligible controller on a state whose role+ is listed in ``ENTITY_CONTROL_STATE_ORDERING.order_for`` for+ the entity's EntityType. Walks the role order strictly: only+ states with roles in that list are considered. States with+ unlisted roles (e.g., a thermostat's+ ``THERMOSTAT_TARGET_TEMPERATURE``) are not eligible for+ one-click even when controllable. Raises+ ``OneClickNotSupported`` when no listed role yields a+ toggle-eligible controller."""++ all_states = StatusDisplayManager().all_entity_states_including_delegations(entity = entity,- entity_state_type_priority_list = priority_list,)-- for entity_state in entity_state_list:- if entity_state.entity_state_type:- controller = entity_state.controllers.first()- if controller:+ states_by_role = {}+ for state in all_states:+ states_by_role.setdefault( state.entity_state_role, [] ).append( state )++ role_order = ENTITY_CONTROL_STATE_ORDERING.order_for( entity.entity_type )+ for role in role_order:+ for state in states_by_role.get( role, [] ):+ controller = state.controllers.first()+ if controller and self._is_toggle_eligible( state ):return controller+ continuecontinue-- raise OneClickNotSupported(f'No priority states found for {entity}')-- def _get_current_state_value( self, entity_state: EntityState ) -> Optional[str]:+ raise OneClickNotSupported( f'No one-click target for {entity}' )++ def _is_toggle_eligible( self, entity_state : EntityState ) -> bool:+ """A state is toggle-eligible when it has a non-empty+ ``toggle_values`` list within ``ONE_CLICK_CHOICE_LIMIT``.+ States outside this range exist (continuous sensors, large+ discrete enums) but don't have a meaningful one-click+ affordance."""+ toggle_values = entity_state.toggle_values()+ if not toggle_values:+ return False+ if len( toggle_values ) > self.ONE_CLICK_CHOICE_LIMIT:+ return False+ return True++ def _get_current_state_value( self, entity_state : EntityState ) -> Optional[str]:try:sensor_response = StatusDisplayManager().get_latest_sensor_response(entity_state = entity_state,@@ -111,7 +111,7 @@ class OneClickControlService:logger.warning( f'Problem getting latest response for: {entity_state} - {e}' )passreturn None-+def _determine_control_value( self,entity_state : EntityState,current_value : Optional[str] ) -> str:@@ -122,7 +122,7 @@ class OneClickControlService:if len(toggle_state_value_list) > self.ONE_CLICK_CHOICE_LIMIT:raise OneClickNotSupported(f'Too many values to toggle for {entity_state}')-+for idx, toggle_state_value in enumerate( toggle_state_value_list ):if toggle_state_value != current_value:continuediff --git a/src/hi/apps/control/tests/test_one_click_control_service.py b/src/hi/apps/control/tests/test_one_click_control_service.pynew file mode 100644index 00000000..f77731d0--- /dev/null+++ b/src/hi/apps/control/tests/test_one_click_control_service.py@@ -0,0 +1,301 @@+import json+import logging+from datetime import datetime, timezone+from unittest.mock import Mock, patch++from hi.apps.control.controller_manager import ControllerManager+from hi.apps.control.models import Controller+from hi.apps.control.one_click_control_service import (+ OneClickControlService,+ OneClickNotSupported,+)+from hi.apps.entity.enums import EntityStateRole, EntityStateType, EntityType+from hi.apps.entity.models import Entity, EntityState+from hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationControlResult+from hi.testing.base_test_case import BaseTestCase++logging.disable(logging.CRITICAL)+++def _make_state( entity, state_type, role = None, value_range_str = '' ):+ state = EntityState.objects.create(+ entity = entity,+ entity_state_type_str = str(state_type),+ name = f'{state_type.label} State',+ value_range_str = value_range_str,+ )+ if role is not None:+ state.entity_state_role = role+ state.save()+ return state+++def _add_controller( state, name = 'ctrl' ):+ return Controller.objects.create(+ entity_state = state,+ name = name,+ controller_type_str = 'DEFAULT',+ )+++class TestOneClickFindController(BaseTestCase):++ def test_unknown_entity_type_falls_back_to_default_on_off(self):+ # No override entry → curated default ON_OFF applies.+ # A WALL_SWITCH-style entity with an ON_OFF-role controlled+ # state gets one-clicked.+ entity = Entity.objects.create(+ name = 'Wall Switch',+ entity_type_str = str(EntityType.WALL_SWITCH),+ )+ state = _make_state( entity, EntityStateType.ON_OFF, EntityStateRole.ON_OFF )+ controller = _add_controller( state )++ picked = OneClickControlService()._find_controller( entity = entity )+ self.assertEqual( picked, controller )++ def test_light_override_prefers_light_on_off_over_other_roles(self):+ # LIGHT override = [LIGHT_ON_OFF]; the LIGHT_BRIGHTNESS role+ # state is ignored even though it has a controller. The+ # default ON_OFF tail still applies if no LIGHT_ON_OFF state+ # is present (covered in the next test).+ entity = Entity.objects.create(+ name = 'Smart Bulb',+ entity_type_str = str(EntityType.LIGHT),+ )+ brightness = _make_state(+ entity, EntityStateType.LIGHT_DIMMER, EntityStateRole.LIGHT_BRIGHTNESS,+ value_range_str = json.dumps({ 'min': 0, 'max': 100 }),+ )+ _add_controller( brightness, name = 'brightness-ctrl' )++ on_off = _make_state(+ entity, EntityStateType.ON_OFF, EntityStateRole.LIGHT_ON_OFF,+ )+ on_off_controller = _add_controller( on_off, name = 'on-off-ctrl' )++ picked = OneClickControlService()._find_controller( entity = entity )+ self.assertEqual( picked, on_off_controller )++ def test_color_bulb_without_light_on_off_uses_light_brightness(self):+ # Fully-modeled color bulbs (HA's substate-decomposition+ # path) carry refined roles only — LIGHT_BRIGHTNESS, HUE,+ # SATURATION, COLOR_TEMPERATURE, COLOR_MODE — with no plain+ # ON_OFF or LIGHT_ON_OFF state. The LIGHT override falls+ # through to LIGHT_BRIGHTNESS so the bulb's brightness+ # slider toggles between off and full on one-click.+ entity = Entity.objects.create(+ name = 'Color Bulb',+ entity_type_str = str(EntityType.LIGHT),+ )+ brightness = _make_state(+ entity, EntityStateType.LIGHT_DIMMER, EntityStateRole.LIGHT_BRIGHTNESS,+ value_range_str = json.dumps({ 'min': 0, 'max': 100 }),+ )+ controller = _add_controller( brightness, name = 'brightness-ctrl' )+ _make_state( entity, EntityStateType.HUE, EntityStateRole.LIGHT_HUE )++ picked = OneClickControlService()._find_controller( entity = entity )+ self.assertEqual( picked, controller )++ def test_light_without_light_on_off_falls_through_to_default_on_off(self):+ # LIGHT override is [LIGHT_ON_OFF]; default appends ON_OFF.+ # A light minimally modeled (only an ON_OFF-role state) still+ # gets one-click via the default fallback.+ entity = Entity.objects.create(+ name = 'Plain Light',+ entity_type_str = str(EntityType.LIGHT),+ )+ on_off = _make_state(+ entity, EntityStateType.ON_OFF, EntityStateRole.ON_OFF,+ )+ controller = _add_controller( on_off )++ picked = OneClickControlService()._find_controller( entity = entity )+ self.assertEqual( picked, controller )++ def test_thermometer_with_no_controllable_state_is_unsupported(self):+ # Sensor-only entity: no controllers → no one-click target.+ entity = Entity.objects.create(+ name = 'Thermometer',+ entity_type_str = str(EntityType.THERMOMETER),+ )+ _make_state( entity, EntityStateType.TEMPERATURE )++ with self.assertRaises( OneClickNotSupported ):+ OneClickControlService()._find_controller( entity = entity )++ def test_thermostat_with_only_complex_substates_is_unsupported(self):+ # THERMOSTAT has no override and no plain ON_OFF state — the+ # default ON_OFF fallback finds nothing. The setpoint and+ # mode substates carry domain-prefixed roles+ # (THERMOSTAT_TARGET_TEMPERATURE_*, HVAC_MODE, etc.) that+ # aren't in the curated default or any override, so one-click+ # is correctly refused even though those states have+ # controllers.+ entity = Entity.objects.create(+ name = 'Thermostat',+ entity_type_str = str(EntityType.THERMOSTAT),+ )+ setpoint = _make_state(+ entity, EntityStateType.TEMPERATURE,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,+ value_range_str = json.dumps({ 'min': 60, 'max': 80 }),+ )+ _add_controller( setpoint, name = 'setpoint-ctrl' )++ with self.assertRaises( OneClickNotSupported ):+ OneClickControlService()._find_controller( entity = entity )++ def test_speed_only_fan_falls_through_to_power_level_default(self):+ # Speed-only fans (no oscillation / direction / presets) are+ # imported as a bare-key POWER_LEVEL state — not the+ # FAN_SPEED-role substate. The default tail includes+ # POWER_LEVEL so the bare-key shape is still one-clickable.+ entity = Entity.objects.create(+ name = 'Speed Fan',+ entity_type_str = str(EntityType.CEILING_FAN),+ )+ speed = _make_state(+ entity, EntityStateType.POWER_LEVEL, EntityStateRole.POWER_LEVEL,+ value_range_str = json.dumps({ 'min': 0, 'max': 100 }),+ )+ controller = _add_controller( speed )++ picked = OneClickControlService()._find_controller( entity = entity )+ self.assertEqual( picked, controller )++ def test_open_close_position_cover_falls_through_to_default(self):+ # Covers with position (blinds, shades, generic covers)+ # carry the OPEN_CLOSE_POSITION role. The default tail+ # includes it so the bare-key continuous cover toggles+ # between closed and open.+ entity = Entity.objects.create(+ name = 'Window Blind',+ entity_type_str = str(EntityType.OPEN_CLOSE_ACTUATOR),+ )+ position = _make_state(+ entity, EntityStateType.OPEN_CLOSE_POSITION, EntityStateRole.OPEN_CLOSE_POSITION,+ value_range_str = json.dumps({ 'min': 0, 'max': 100 }),+ )+ controller = _add_controller( position )++ picked = OneClickControlService()._find_controller( entity = entity )+ self.assertEqual( picked, controller )++ def test_execute_one_click_toggles_on_to_off_through_full_pipeline(self):+ # End-to-end glue test: a controllable ON_OFF state whose+ # latest sensor reading is "on" should one-click to "off" via+ # _find_controller → _get_current_state_value →+ # _determine_control_value → ControllerManager.do_control.+ # Mocks at the integration boundary (do_control) and at the+ # sensor-response boundary (latest reading); everything in+ # between is exercised for real.+ entity = Entity.objects.create(+ name = 'Wall Switch',+ entity_type_str = str(EntityType.WALL_SWITCH),+ )+ state = _make_state( entity, EntityStateType.ON_OFF, EntityStateRole.ON_OFF )+ controller = Controller.objects.create(+ entity_state = state,+ name = 'wall-ctrl',+ controller_type_str = 'DEFAULT',+ integration_id = 'home_assistant',+ integration_name = 'Home Assistant',+ )++ latest_response = SensorResponse(+ integration_key = controller.integration_key,+ value = 'on',+ timestamp = datetime.now( timezone.utc ),+ )++ mock_control_result = IntegrationControlResult(+ new_value = 'off', error_list = [],+ )+ mock_integration_controller = Mock()+ mock_integration_controller.do_control.return_value = mock_control_result+ mock_integration_gateway = Mock()+ mock_integration_gateway.get_controller.return_value = mock_integration_controller+ mock_integration_manager = Mock()+ mock_integration_manager.get_integration_gateway.return_value = mock_integration_gateway++ with patch.object( ControllerManager, '_instance', None ), \+ patch( 'hi.apps.control.controller_manager.IntegrationManager',+ return_value = mock_integration_manager ), \+ patch( 'hi.apps.monitor.status_display_manager.StatusDisplayManager'+ '.get_latest_sensor_response',+ return_value = latest_response ):+ outcome = OneClickControlService().execute_one_click_control( entity = entity )++ # do_control received the toggle target value derived from the+ # current "on" sensor reading.+ call_kwargs = mock_integration_controller.do_control.call_args.kwargs+ self.assertEqual( call_kwargs[ 'hi_control_value' ], 'off' )+ self.assertEqual( call_kwargs[ 'integration_details' ].key,+ controller.integration_key )++ self.assertFalse( outcome.has_errors )+ self.assertEqual( outcome.new_value, 'off' )+ self.assertEqual( outcome.controller, controller )++ def test_execute_one_click_picks_first_value_when_no_sensor_history(self):+ # When there's no sensor history, _get_current_state_value+ # returns None and _determine_control_value falls through to+ # toggle_values()[0]. End-to-end: pipeline still dispatches.+ entity = Entity.objects.create(+ name = 'Wall Switch',+ entity_type_str = str(EntityType.WALL_SWITCH),+ )+ state = _make_state( entity, EntityStateType.ON_OFF, EntityStateRole.ON_OFF )+ controller = Controller.objects.create(+ entity_state = state,+ name = 'wall-ctrl',+ controller_type_str = 'DEFAULT',+ integration_id = 'home_assistant',+ integration_name = 'Home Assistant',+ )+ first_toggle = state.toggle_values()[ 0 ]++ mock_control_result = IntegrationControlResult(+ new_value = first_toggle, error_list = [],+ )+ mock_integration_controller = Mock()+ mock_integration_controller.do_control.return_value = mock_control_result+ mock_integration_gateway = Mock()+ mock_integration_gateway.get_controller.return_value = mock_integration_controller+ mock_integration_manager = Mock()+ mock_integration_manager.get_integration_gateway.return_value = mock_integration_gateway++ with patch.object( ControllerManager, '_instance', None ), \+ patch( 'hi.apps.control.controller_manager.IntegrationManager',+ return_value = mock_integration_manager ), \+ patch( 'hi.apps.monitor.status_display_manager.StatusDisplayManager'+ '.get_latest_sensor_response',+ return_value = None ):+ outcome = OneClickControlService().execute_one_click_control( entity = entity )++ call_kwargs = mock_integration_controller.do_control.call_args.kwargs+ self.assertEqual( call_kwargs[ 'hi_control_value' ], first_toggle )+ self.assertFalse( outcome.has_errors )+ self.assertEqual( outcome.controller, controller )++ def test_too_many_toggle_values_disqualifies_state(self):+ # A controllable state with more than ONE_CLICK_CHOICE_LIMIT+ # toggle values isn't one-click eligible (cycling through+ # many discrete options isn't a usable single-click+ # affordance). With no other eligible state, the entity is+ # NotSupported.+ entity = Entity.objects.create(+ name = 'Multi-mode',+ entity_type_str = str(EntityType.WALL_SWITCH),+ )+ many_values = _make_state(+ entity, EntityStateType.ON_OFF, EntityStateRole.ON_OFF,+ value_range_str = json.dumps([ 'a', 'b', 'c', 'd', 'e' ]),+ )+ _add_controller( many_values )++ with self.assertRaises( OneClickNotSupported ):+ OneClickControlService()._find_controller( entity = entity )diff --git a/src/hi/apps/entity/entity_state_role_order.py b/src/hi/apps/entity/entity_state_role_order.pynew file mode 100644index 00000000..44ad188c--- /dev/null+++ b/src/hi/apps/entity/entity_state_role_order.py@@ -0,0 +1,239 @@+"""Per-EntityType ordering of EntityStateRoles.++Three module-level instances:++- ``ENTITY_STATUS_VIEW_ORDERING`` orders states for the+ EntityStatusView modal listing.+- ``ENTITY_PRIMARY_STATE_ORDERING`` selects the single state whose+ value represents the entity's visual status (the ``status``+ attribute on the entity's rendered element). Used by rendering+ paths that show one entity element — initial location-view+ render, full-entity re-render after a one-click action, etc.+- ``ENTITY_CONTROL_STATE_ORDERING`` selects the state targeted by+ one-click control. Distinct from the visual primary: a light's+ visual primary is brightness, but the one-click target is its+ on/off state. The default is intentionally short (just ``ON_OFF``)+ so unrecognized EntityTypes get a safe toggle-or-skip behavior.++Resolution rule: a per-EntityType override is a *prefix*; roles not+in the override follow in the default order. Roles absent from both+sort to the end."""++from dataclasses import dataclass+from typing import Dict, List++from .enums import EntityStateRole, EntityType+++DEFAULT_ENTITY_STATE_ROLE_ORDER : List[ EntityStateRole ] = [+ # Alarm-bearing / safety roles.+ EntityStateRole.SMOKE,+ EntityStateRole.CO,+ EntityStateRole.GAS,+ EntityStateRole.MOISTURE,+ EntityStateRole.MOVEMENT,+ EntityStateRole.PRESENCE,+ EntityStateRole.OPEN_CLOSE,++ # Primary control axes.+ EntityStateRole.FAN_SPEED,+ EntityStateRole.LIGHT_BRIGHTNESS,+ EntityStateRole.POWER_LEVEL,+ EntityStateRole.LIGHT_DIMMER,+ EntityStateRole.OPEN_CLOSE_POSITION,++ # Discrete / on-off.+ EntityStateRole.LIGHT_ON_OFF,+ EntityStateRole.ON_OFF,+ EntityStateRole.DISCRETE,+ EntityStateRole.MULTIVALUED,++ # Environmental readings.+ EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+ EntityStateRole.TEMPERATURE,+ EntityStateRole.HUMIDITY,+ EntityStateRole.AIR_PRESSURE,+ EntityStateRole.WIND_SPEED,+ EntityStateRole.LIGHT_LEVEL,+ EntityStateRole.SOUND_LEVEL,+ EntityStateRole.WATER_FLOW,++ # Thermostat setpoints.+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_HIGH,++ # HVAC / fan auxiliary axes.+ EntityStateRole.HVAC_MODE,+ EntityStateRole.HVAC_ACTION,+ EntityStateRole.FAN_MODE,+ EntityStateRole.PRESET_MODE,+ EntityStateRole.SWING_MODE,+ EntityStateRole.FAN_OSCILLATION,+ EntityStateRole.FAN_DIRECTION,+ EntityStateRole.FAN_PRESET_MODE,++ # Color & lighting attributes.+ EntityStateRole.LIGHT_COLOR_TEMPERATURE,+ EntityStateRole.COLOR_TEMPERATURE,+ EntityStateRole.LIGHT_HUE,+ EntityStateRole.HUE,+ EntityStateRole.LIGHT_SATURATION,+ EntityStateRole.SATURATION,+ EntityStateRole.LIGHT_COLOR_MODE,+ EntityStateRole.COLOR_MODE,++ # Utility / maintenance / diagnostic.+ EntityStateRole.ELECTRIC_USAGE,+ EntityStateRole.BANDWIDTH_USAGE,+ EntityStateRole.BATTERY_LEVEL,+ EntityStateRole.HIGH_LOW,+ EntityStateRole.CONNECTIVITY,+ EntityStateRole.DATETIME,++ # Generic fallbacks.+ EntityStateRole.CONTINUOUS,+ EntityStateRole.BLOB,+]+++ENTITY_STATUS_VIEW_ENTITY_TYPE_OVERRIDES : Dict[ EntityType, List[ EntityStateRole ] ] = {+ EntityType.THERMOSTAT: [+ EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+ EntityStateRole.HUMIDITY,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_HIGH,+ EntityStateRole.HVAC_MODE,+ EntityStateRole.HVAC_ACTION,+ EntityStateRole.FAN_MODE,+ EntityStateRole.PRESET_MODE,+ EntityStateRole.SWING_MODE,+ ],+ EntityType.CEILING_FAN: [+ EntityStateRole.FAN_SPEED,+ EntityStateRole.ON_OFF,+ EntityStateRole.FAN_OSCILLATION,+ EntityStateRole.FAN_DIRECTION,+ EntityStateRole.FAN_PRESET_MODE,+ ],+ EntityType.EXHAUST_FAN: [+ EntityStateRole.FAN_SPEED,+ EntityStateRole.ON_OFF,+ EntityStateRole.FAN_OSCILLATION,+ EntityStateRole.FAN_DIRECTION,+ EntityStateRole.FAN_PRESET_MODE,+ ],+ EntityType.LIGHT: [+ EntityStateRole.LIGHT_BRIGHTNESS,+ EntityStateRole.LIGHT_COLOR_TEMPERATURE,+ EntityStateRole.LIGHT_HUE,+ EntityStateRole.LIGHT_SATURATION,+ EntityStateRole.LIGHT_COLOR_MODE,+ EntityStateRole.LIGHT_ON_OFF,+ ],+ EntityType.SMOKE_DETECTOR: [+ EntityStateRole.SMOKE,+ EntityStateRole.BATTERY_LEVEL,+ ],+ EntityType.LEAK_SENSOR: [+ EntityStateRole.MOISTURE,+ EntityStateRole.BATTERY_LEVEL,+ ],+ EntityType.CARBON_MONOXIDE_DETECTOR: [+ EntityStateRole.CO,+ EntityStateRole.BATTERY_LEVEL,+ ],+ EntityType.GAS_DETECTOR: [+ EntityStateRole.GAS,+ EntityStateRole.BATTERY_LEVEL,+ ],+}+++@dataclass( frozen = True )+class EntityStateRoleOrdering:++ default_order : List[ EntityStateRole ]+ overrides : Dict[ EntityType, List[ EntityStateRole ] ]++ def order_for( self, entity_type : EntityType ) -> List[ EntityStateRole ]:+ override = self.overrides.get( entity_type, [] )+ in_override = set( override )+ tail = [ r for r in self.default_order if r not in in_override ]+ return list( override ) + tail++ def sort_key( self,+ entity_state_role : EntityStateRole,+ entity_type : EntityType ) -> int:+ order = self.order_for( entity_type )+ try:+ return order.index( entity_state_role )+ except ValueError:+ # Defensive: EntityStateRoles not yet placed in the order+ # tables sort to the end.+ return len( order )+++ENTITY_STATUS_VIEW_ORDERING = EntityStateRoleOrdering(+ default_order = DEFAULT_ENTITY_STATE_ROLE_ORDER,+ overrides = ENTITY_STATUS_VIEW_ENTITY_TYPE_OVERRIDES,+)+++# Primary-state overrides need only declare the winning role+# (position 0); the default order positions the rest. Each entry is+# a sensible starting point; per-EntityType audit can refine later.+ENTITY_PRIMARY_STATE_ENTITY_TYPE_OVERRIDES : Dict[ EntityType, List[ EntityStateRole ] ] = {+ EntityType.THERMOSTAT : [ EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE ],+ EntityType.CEILING_FAN : [ EntityStateRole.FAN_SPEED ],+ EntityType.EXHAUST_FAN : [ EntityStateRole.FAN_SPEED ],+ EntityType.LIGHT : [ EntityStateRole.LIGHT_BRIGHTNESS ],+ EntityType.SMOKE_DETECTOR : [ EntityStateRole.SMOKE ],+ EntityType.LEAK_SENSOR : [ EntityStateRole.MOISTURE ],+ EntityType.CARBON_MONOXIDE_DETECTOR : [ EntityStateRole.CO ],+ EntityType.GAS_DETECTOR : [ EntityStateRole.GAS ],+}+++ENTITY_PRIMARY_STATE_ORDERING = EntityStateRoleOrdering(+ default_order = DEFAULT_ENTITY_STATE_ROLE_ORDER,+ overrides = ENTITY_PRIMARY_STATE_ENTITY_TYPE_OVERRIDES,+)+++# Curated default for one-click control target selection. Each+# entry is a role with universally clear toggle semantics (binary+# pair, or a min/max-bounded continuous slider). EntityTypes without+# a specific override fall through this list in order. Binary roles+# come first so they win when both binary and continuous variants+# exist on the same entity.+#+# Sensor-only roles (MOVEMENT, PRESENCE, SMOKE, MOISTURE, CO, GAS,+# CONNECTIVITY, BATTERY_LEVEL, ...) are intentionally absent: they+# have no controllers in practice and inclusion would only add dead+# matches to _find_controller's eligibility walk.+DEFAULT_CONTROL_STATE_ROLE_ORDER : List[ EntityStateRole ] = [+ EntityStateRole.ON_OFF,+ EntityStateRole.OPEN_CLOSE,+ EntityStateRole.OPEN_CLOSE_POSITION,+ EntityStateRole.POWER_LEVEL,+ EntityStateRole.LIGHT_DIMMER,+]+++ENTITY_CONTROL_STATE_ENTITY_TYPE_OVERRIDES : Dict[ EntityType, List[ EntityStateRole ] ] = {+ EntityType.LIGHT : [ EntityStateRole.LIGHT_ON_OFF,+ EntityStateRole.LIGHT_BRIGHTNESS ],+ EntityType.CEILING_FAN : [ EntityStateRole.FAN_SPEED ],+ EntityType.EXHAUST_FAN : [ EntityStateRole.FAN_SPEED ],+ EntityType.GARAGE_DOOR_OPENER : [ EntityStateRole.OPEN_CLOSE ],+ # WALL_SWITCH / ON_OFF_SWITCH / ELECTRICAL_OUTLET / DOOR_LOCK+ # rely on the default ON_OFF fallback — no override needed.+}+++ENTITY_CONTROL_STATE_ORDERING = EntityStateRoleOrdering(+ default_order = DEFAULT_CONTROL_STATE_ROLE_ORDER,+ overrides = ENTITY_CONTROL_STATE_ENTITY_TYPE_OVERRIDES,+)diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex c4a5f4fe..3d951f6f 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -188,8 +188,16 @@ class EntityType(LabeledEnum):def requires_open_path(self) -> bool:"""True if EntityType requires an open path"""return self in self.get_open_path_types()--++ def entity_status_template_name(self) -> str:+ """Template used to render the EntityStatusView modal's body+ for this EntityType. Create the template at the returned+ path to define an EntityType-specific layout (e.g., a+ graphical thermostat widget); otherwise the dispatcher+ falls back to the default flat-list rendering."""+ return f'entity/modals/entity_status_{self.name.lower()}.html'++class EntityStateValue(LabeledEnum):# Alarm-style values (e.g., ACTIVE, OPEN, SMOKE_DETECTED) are# rendered as the ``status`` attribute on both the SVG icon@@ -244,25 +252,102 @@ class EntityStateValue(LabeledEnum):COLOR_MODE_WHITE = ( 'White', '' )@classmethod- def to_display_label( cls, wire_value : str ) -> str:- """Resolve a stored wire value to a display label. Known- enum members return their authoritative ``.label``;- free-form wire values (e.g., HA's ``'heating'``,- ``'fan_only'``) are humanized into title case. Numeric- values pass through unchanged so the humanizer doesn't- mangle them."""- if not wire_value:- return wire_value+ def to_display_label( cls, entity_state_value : str ) -> str:+ """Resolve a stored EntityState value to a display label.+ Known enum members return their authoritative ``.label``;+ free-form values (e.g., HA-derived ``'heating'``,+ ``'fan_only'`` after integration-boundary normalization)+ are humanized into title case. Numeric values pass through+ unchanged so the humanizer doesn't mangle them."""+ if not entity_state_value:+ return entity_state_valuetry:- return cls.from_name( wire_value ).label+ return cls.from_name( entity_state_value ).labelexcept ValueError:- if wire_value[ 0 ].isdigit():- return wire_value- return get_humanized_name( wire_value )+ if entity_state_value[ 0 ].isdigit():+ return entity_state_value+ return get_humanized_name( entity_state_value )+++class EntityStateRole(LabeledEnum):+ """Semantic role an EntityState plays within its enclosing entity's+ presentation. Type defaults (member name matches an EntityStateType+ member) provide a baseline for any EntityState; domain-prefixed+ members refine the role when multiple EntityStates of the same type+ coexist on an entity (e.g., a thermostat's current vs. target+ temperatures).++ Some labels collide between a type-default member and a domain+ refinement (e.g., ON_OFF / LIGHT_ON_OFF both display "On/Off";+ BRIGHTNESS-like roles share labels). This is intentional: labels+ describe what the user reads; the enum *name* is the disambiguator+ used internally (admin, debug, role-priority lookups)."""++ # Type defaults. One member per EntityStateType; names match+ # so EntityStateType.default_role() can resolve by name.+ DISCRETE = ( 'Discrete' , '' )+ CONTINUOUS = ( 'Continuous' , '' )+ MULTIVALUED = ( 'Multi-valued' , '' )+ BLOB = ( 'Blob' , '' )+ AIR_PRESSURE = ( 'Air Pressure' , '' )+ BANDWIDTH_USAGE = ( 'Bandwidth Usage' , '' )+ BATTERY_LEVEL = ( 'Battery' , '' )+ COLOR_MODE = ( 'Color Mode' , '' )+ COLOR_TEMPERATURE = ( 'Color Temperature' , '' )+ CONNECTIVITY = ( 'Connectivity' , '' )+ DATETIME = ( 'Date/Time' , '' )+ ELECTRIC_USAGE = ( 'Electric Usage' , '' )+ HIGH_LOW = ( 'High/Low' , '' )+ HUE = ( 'Hue' , '' )+ HUMIDITY = ( 'Humidity' , '' )+ LIGHT_DIMMER = ( 'Light Dimmer' , '' )+ LIGHT_LEVEL = ( 'Light Level' , '' )+ MOISTURE = ( 'Moisture' , '' )+ MOVEMENT = ( 'Movement' , '' )+ ON_OFF = ( 'On/Off' , '' )+ OPEN_CLOSE = ( 'Open/Close' , '' )+ OPEN_CLOSE_POSITION = ( 'Open/Close Position', '' )+ POWER_LEVEL = ( 'Power Level' , '' )+ PRESENCE = ( 'Presence' , '' )+ SATURATION = ( 'Saturation' , '' )+ SMOKE = ( 'Smoke' , '' )+ CO = ( 'Carbon Monoxide' , '' )+ GAS = ( 'Gas' , '' )+ SOUND_LEVEL = ( 'Sound Level' , '' )+ TEMPERATURE = ( 'Temperature' , '' )+ WATER_FLOW = ( 'Water Flow' , '' )+ WIND_SPEED = ( 'Wind Speed' , '' )++ # Domain-prefixed refinements for multi-state entities.+ THERMOSTAT_CURRENT_TEMPERATURE = ( 'Current Temperature' , '' )+ THERMOSTAT_TARGET_TEMPERATURE = ( 'Setpoint' , '' )+ THERMOSTAT_TARGET_TEMPERATURE_LOW = ( 'Setpoint Low' , '' )+ THERMOSTAT_TARGET_TEMPERATURE_HIGH = ( 'Setpoint High' , '' )+ HVAC_MODE = ( 'HVAC Mode' , '' )+ HVAC_ACTION = ( 'HVAC Action' , '' )+ FAN_MODE = ( 'Fan Mode' , '' )+ PRESET_MODE = ( 'Preset Mode' , '' )+ SWING_MODE = ( 'Swing Mode' , '' )++ FAN_SPEED = ( 'Fan Speed' , '' )+ FAN_OSCILLATION = ( 'Fan Oscillation' , '' )+ FAN_DIRECTION = ( 'Fan Direction' , '' )+ FAN_PRESET_MODE = ( 'Fan Preset Mode' , '' )++ LIGHT_BRIGHTNESS = ( 'Brightness' , '' )+ LIGHT_HUE = ( 'Hue' , '' )+ LIGHT_SATURATION = ( 'Saturation' , '' )+ LIGHT_COLOR_TEMPERATURE = ( 'Color Temperature' , '' )+ LIGHT_COLOR_MODE = ( 'Color Mode' , '' )+ LIGHT_ON_OFF = ( 'On/Off' , '' )++ @classmethod+ def default(cls):+ return cls.DISCRETEclass EntityStateType(LabeledEnum):-+# General typesDISCRETE = ( 'Discrete' , 'Single value, fixed set of possible values',[] )@@ -402,8 +487,14 @@ class EntityStateType(LabeledEnum):"entity/panes/controller_value_default.html""""return f'control/panes/controller_{self.name.lower()}.html'--++ def default_role(self) -> EntityStateRole:+ """The default EntityStateRole for an EntityState of this type.+ Type-default ``EntityStateRole`` members share their name with+ the matching ``EntityStateType`` member; lookup is by name."""+ return EntityStateRole[ self.name ]++class TemperatureUnit(LabeledEnum):FAHRENHEIT = ( 'Fahrenheit', '' )diff --git a/src/hi/apps/entity/migrations/0016_add_entity_state_role.py b/src/hi/apps/entity/migrations/0016_add_entity_state_role.pynew file mode 100644index 00000000..3bce1a2a--- /dev/null+++ b/src/hi/apps/entity/migrations/0016_add_entity_state_role.py@@ -0,0 +1,30 @@+from django.db import migrations, models+++def populate_role_str(apps, schema_editor):+ # Backfill role_str on existing EntityStates with the+ # type-default role. New rows are populated at creation time by+ # EntityState.save() / factory paths.+ from hi.apps.entity.enums import EntityStateType+ EntityState = apps.get_model("entity", "EntityState")+ for state in EntityState.objects.filter(role_str=""):+ state_type = EntityStateType.from_name_safe(state.entity_state_type_str)+ state.role_str = str(state_type.default_role())+ state.save(update_fields=["role_str"])+++class Migration(migrations.Migration):++ dependencies = [+ ("entity", "0015_add_previous_integration_identity"),+ ]++ operations = [+ migrations.AddField(+ model_name="entitystate",+ name="role_str",+ field=models.CharField(default="", max_length=64, verbose_name="Role"),+ preserve_default=False,+ ),+ migrations.RunPython(populate_role_str, migrations.RunPython.noop),+ ]diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.pyindex 869341f8..2e52f0c6 100644--- a/src/hi/apps/entity/models.py+++ b/src/hi/apps/entity/models.py@@ -17,6 +17,7 @@ from hi.enums import ItemTypefrom .enums import (EntityType,+ EntityStateRole,EntityStateType,)@@ -157,6 +158,11 @@ class EntityState( models.Model ):null = False, blank = False,db_index = True,)+ role_str = models.CharField(+ 'Role',+ max_length = 64,+ null = False, blank = False,+ )name = models.CharField('Name',max_length = 64,@@ -186,6 +192,16 @@ class EntityState( models.Model ):def __repr__(self):return self.__str__()+ def save(self, *args, **kwargs):+ # Default the role to the EntityStateType's default when not+ # explicitly set. Catches direct ``EntityState.objects.create``+ # paths; the factory layer also sets it explicitly when callers+ # don't provide one.+ if not self.role_str and self.entity_state_type_str:+ self.role_str = str( self.entity_state_type.default_role() )+ super().save( *args, **kwargs )+ return+@propertydef entity_state_type(self):return EntityStateType.from_name_safe( self.entity_state_type_str )@@ -195,6 +211,15 @@ class EntityState( models.Model ):self.entity_state_type_str = str(entity_state_type)return+ @property+ def entity_state_role(self) -> EntityStateRole:+ return EntityStateRole.from_name_safe( self.role_str )++ @entity_state_role.setter+ def entity_state_role( self, entity_state_role : EntityStateRole ):+ self.role_str = str(entity_state_role)+ return+@propertydef css_class(self):return f'hi-entity-state-{self.id}'@@ -221,7 +246,7 @@ class EntityState( models.Model ):# (OPEN_CLOSE, SMOKE, ON_OFF, ...) carry authoritative# labels on their EntityStateValue members. Free-form# discrete sets (DISCRETE state type, e.g., HA hvac_mode /- # fan preset) store only wire values in+ # fan preset) store only the value strings in# ``value_range_str`` and rely on the humanizer for# readable labels.type_choices = self.entity_state_type.choices()@@ -239,12 +264,12 @@ class EntityState( models.Model ):and 'max' in value_range ):return list()if isinstance( value_range, dict ):- wire_values = list( value_range.keys() )+ stored_values = list( value_range.keys() )elif isinstance( value_range, list ):- wire_values = value_range+ stored_values = value_rangeelse:return list()- return [ ( str(v), get_humanized_name( str(v) ) ) for v in wire_values ]+ return [ ( str(v), get_humanized_name( str(v) ) ) for v in stored_values ]def toggle_values(self) -> List[str]:if self.value_range_str:diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status.html b/src/hi/apps/entity/templates/entity/modals/entity_status.htmlindex d4da42ed..76d6506c 100644--- a/src/hi/apps/entity/templates/entity/modals/entity_status.html+++ b/src/hi/apps/entity/templates/entity/modals/entity_status.html@@ -1,7 +1,6 @@{% extends "modals/action_3.html" %}-{% load icons static %}-{% load video_tags %}-{% load integration_tags %}+{% load icons %}+{% load common_tags %}{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}@@ -10,42 +9,7 @@ Status{% endblock %}{% block body %}-<div class="d-flex justify-content-between mb-2">- {% if display_only_svg_icon_item %}- <div class="display-only-svg-icon pr-2">- {% include "entity/panes/entity_display_only_svg_icon.html" with svg_icon_item=display_only_svg_icon_item %}- </div>- {% endif %}- <div class="text-center">- <div class="h4 mb-0">{{ entity.name }}</div>- {% if entity.integration_id %}- <div class="text-muted">- <small>- {% integration_logo_path entity as logo_path %}- {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline mr-1">{% endif %}- From: {% integration_display_name entity %}- </small>- </div>- {% elif entity.previous_integration_id %}- <div class="text-muted font-italic">- <small>- {% previous_integration_logo_path entity as prev_logo_path %}- {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}- Detached from: {% previous_integration_display_name entity %}- </small>- </div>- {% endif %}- </div>- <div>- <div class="h5 text-muted">{{ entity.entity_type.label }}</div>- </div>-</div>--<div>- {% include "console/panes/entity_video_stream_w_link.html" with entity=entity_for_video %}-</div>--{% include "entity/panes/entity_state_status_list.html" with entity_state_status_data_list=entity_state_status_data_list in_modal_context=True %}+{% include_with_fallback entity.entity_type.entity_status_template_name "entity/modals/entity_status_default.html" %}{% endblock %}{% block action_left %}diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status_ceiling_fan.html b/src/hi/apps/entity/templates/entity/modals/entity_status_ceiling_fan.htmlnew file mode 100644index 00000000..6c72371b--- /dev/null+++ b/src/hi/apps/entity/templates/entity/modals/entity_status_ceiling_fan.html@@ -0,0 +1,4 @@+{# Reserved for ceiling-fan-specific EntityStatusView layout. #}+{# Delegates to the default flat-list template until a custom #}+{# layout is needed. #}+{% include "entity/modals/entity_status_default.html" %}diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status_default.html b/src/hi/apps/entity/templates/entity/modals/entity_status_default.htmlnew file mode 100644index 00000000..868396f7--- /dev/null+++ b/src/hi/apps/entity/templates/entity/modals/entity_status_default.html@@ -0,0 +1,40 @@+{% load static %}+{% load video_tags %}+{% load integration_tags %}++<div class="d-flex justify-content-between mb-2">+ {% if display_only_svg_icon_item %}+ <div class="display-only-svg-icon pr-2">+ {% include "entity/panes/entity_display_only_svg_icon.html" with svg_icon_item=display_only_svg_icon_item %}+ </div>+ {% endif %}+ <div class="text-center">+ <div class="h4 mb-0">{{ entity.name }}</div>+ {% if entity.integration_id %}+ <div class="text-muted">+ <small>+ {% integration_logo_path entity as logo_path %}+ {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline mr-1">{% endif %}+ From: {% integration_display_name entity %}+ </small>+ </div>+ {% elif entity.previous_integration_id %}+ <div class="text-muted font-italic">+ <small>+ {% previous_integration_logo_path entity as prev_logo_path %}+ {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}+ Detached from: {% previous_integration_display_name entity %}+ </small>+ </div>+ {% endif %}+ </div>+ <div>+ <div class="h5 text-muted">{{ entity.entity_type.label }}</div>+ </div>+</div>++<div>+ {% include "console/panes/entity_video_stream_w_link.html" with entity=entity_for_video %}+</div>++{% include "entity/panes/entity_state_status_list.html" with entity_state_status_data_list=state_status_data_list in_modal_context=True %}diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status_thermostat.html b/src/hi/apps/entity/templates/entity/modals/entity_status_thermostat.htmlnew file mode 100644index 00000000..f187c03c--- /dev/null+++ b/src/hi/apps/entity/templates/entity/modals/entity_status_thermostat.html@@ -0,0 +1,4 @@+{# Reserved for thermostat-specific EntityStatusView layout. #}+{# Delegates to the default flat-list template until a custom #}+{# layout (e.g., graphical dial / mode picker) is needed. #}+{% include "entity/modals/entity_status_default.html" %}diff --git a/src/hi/apps/entity/templatetags/entity_tags.py b/src/hi/apps/entity/templatetags/entity_tags.pyindex d5a8adb4..aa862cd5 100644--- a/src/hi/apps/entity/templatetags/entity_tags.py+++ b/src/hi/apps/entity/templatetags/entity_tags.py@@ -7,7 +7,7 @@ register = template.Library()@register.filterdef value_label( value ):- """Resolve a stored wire value to its display label via+ """Resolve a stored EntityState value to its display label via``EntityStateValue.to_display_label`` — enum members returntheir authoritative label, free-form names get humanized,numeric values pass through."""diff --git a/src/hi/apps/entity/tests/test_entity_state_role_order.py b/src/hi/apps/entity/tests/test_entity_state_role_order.pynew file mode 100644index 00000000..47e424de--- /dev/null+++ b/src/hi/apps/entity/tests/test_entity_state_role_order.py@@ -0,0 +1,79 @@+import logging++from hi.apps.entity.entity_state_role_order import (+ DEFAULT_ENTITY_STATE_ROLE_ORDER,+ ENTITY_STATUS_VIEW_ORDERING,+ EntityStateRoleOrdering,+)+from hi.apps.entity.enums import EntityStateRole, EntityType+from hi.testing.base_test_case import BaseTestCase++logging.disable(logging.CRITICAL)+++class TestEntityStateRoleOrdering(BaseTestCase):++ def test_unoverridden_entity_type_uses_default_order(self):+ # OTHER has no override; resolved order matches the default.+ self.assertEqual(+ ENTITY_STATUS_VIEW_ORDERING.order_for( EntityType.OTHER ),+ DEFAULT_ENTITY_STATE_ROLE_ORDER,+ )+ return++ def test_thermostat_override_prefixes_default_tail(self):+ # Override is the prefix; remaining default-order roles follow,+ # deduplicated against the override.+ order = ENTITY_STATUS_VIEW_ORDERING.order_for( EntityType.THERMOSTAT )+ self.assertEqual( order[0], EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE )+ self.assertEqual( order[1], EntityStateRole.HUMIDITY )+ self.assertEqual( order[2], EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW )+ self.assertEqual( order[3], EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE )+ self.assertEqual( order[4], EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_HIGH )+ return++ def test_sort_key_drives_thermostat_listing_order(self):+ # End-to-end: feeding a shuffled list of roles through sort_key+ # produces THERMOSTAT_CURRENT_TEMPERATURE first for a thermostat,+ # with the three setpoints in low / single / high order.+ shuffled = [+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_HIGH,+ EntityStateRole.HUMIDITY,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,+ EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW,+ ]+ ordered = sorted(+ shuffled,+ key = lambda r: ENTITY_STATUS_VIEW_ORDERING.sort_key( r, EntityType.THERMOSTAT ),+ )+ self.assertEqual( ordered, [+ EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+ EntityStateRole.HUMIDITY,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_HIGH,+ ])+ return++ def test_parameterizable_for_parallel_orderings(self):+ # A separate instance with its own override map produces a+ # different resolved order — locks in that the class is+ # parameterizable for future parallel use cases (icon-status+ # selection, one-click controller selection).+ alt = EntityStateRoleOrdering(+ default_order = DEFAULT_ENTITY_STATE_ROLE_ORDER,+ overrides = {+ EntityType.OTHER: [ EntityStateRole.BATTERY_LEVEL ],+ },+ )+ self.assertEqual(+ alt.order_for( EntityType.OTHER )[0],+ EntityStateRole.BATTERY_LEVEL,+ )+ # The display ordering's resolution for OTHER is unaffected.+ self.assertEqual(+ ENTITY_STATUS_VIEW_ORDERING.order_for( EntityType.OTHER )[0],+ DEFAULT_ENTITY_STATE_ROLE_ORDER[0],+ )+ returndiff --git a/src/hi/apps/entity/tests/test_entity_tags.py b/src/hi/apps/entity/tests/test_entity_tags.pyindex 6c91bd51..caf1dfb1 100644--- a/src/hi/apps/entity/tests/test_entity_tags.py+++ b/src/hi/apps/entity/tests/test_entity_tags.py@@ -7,14 +7,14 @@ logging.disable(logging.CRITICAL)class TestValueLabel(BaseTestCase):- """``value_label`` resolves a stored EntityStateValue wire string+ """``value_label`` resolves a stored EntityStateValue string(the lowercased enum name) to its human-readable label sotemplate-rendered sensor displays show ``"Smoke Detected"``rather than ``"smoke_detected"``."""def test_resolves_underscore_separated_value(self):- # The motivating case: multi-word values that look broken- # in their wire form.+ # The motivating case: multi-word stored values that look+ # broken in their raw form.self.assertEqual( value_label( 'smoke_detected' ), 'Smoke Detected' )def test_resolves_single_word_value(self):@@ -29,9 +29,10 @@ class TestValueLabel(BaseTestCase):self.assertEqual( value_label( '72.5' ), '72.5' )def test_non_enum_name_value_humanized(self):- # Free-form wire values that aren't enum members (e.g., HA- # hvac_action values like 'heating') get humanized into a- # readable label.+ # Free-form values that aren't enum members (e.g., HA+ # hvac_action values like 'heating' after integration-+ # boundary normalization) get humanized into a readable+ # label.self.assertEqual( value_label( 'heating' ), 'Heating' )self.assertEqual( value_label( 'fan_only' ), 'Fan Only' )diff --git a/src/hi/apps/entity/tests/test_enums.py b/src/hi/apps/entity/tests/test_enums.pyindex b38be328..bf05fadc 100644--- a/src/hi/apps/entity/tests/test_enums.py+++ b/src/hi/apps/entity/tests/test_enums.py@@ -41,6 +41,19 @@ class TestEntityStateType(BaseTestCase):return+class TestEntityStateTypeDefaultRole(BaseTestCase):++ def test_every_entity_state_type_resolves_to_a_role(self):+ # Locks in the type-default coverage convention: every+ # EntityStateType has a same-named EntityStateRole member.+ # Adding an EntityStateType without the matching role would+ # KeyError at runtime; this test surfaces that at test time.+ for entity_state_type in EntityStateType:+ role = entity_state_type.default_role()+ self.assertEqual( role.name, entity_state_type.name )+ return++class TestEntityGroupType(BaseTestCase):def test_entity_type_to_group_mapping_supports_logical_ui_organization(self):diff --git a/src/hi/apps/entity/tests/test_models.py b/src/hi/apps/entity/tests/test_models.pyindex 111e4b9d..4943e540 100644--- a/src/hi/apps/entity/tests/test_models.py+++ b/src/hi/apps/entity/tests/test_models.py@@ -3,7 +3,7 @@ import loggingfrom django.db import IntegrityErrorfrom hi.apps.entity.models import Entity, EntityAttribute, EntityState-from hi.apps.entity.enums import EntityType, EntityStateType+from hi.apps.entity.enums import EntityStateRole, EntityType, EntityStateTypefrom hi.apps.attribute.enums import AttributeValueTypefrom hi.testing.base_test_case import BaseTestCase@@ -206,16 +206,63 @@ class TestEntityState(BaseTestCase):entity_state_type_str=str(EntityStateType.ON_OFF),name='Power State',)-+# Test getter converts string to enumself.assertEqual(state.entity_state_type, EntityStateType.ON_OFF)-+# Test setter converts enum to string (lowercase)state.entity_state_type = EntityStateType.TEMPERATUREself.assertEqual(state.entity_state_type_str, str(EntityStateType.TEMPERATURE).lower())self.assertEqual(state.entity_state_type, EntityStateType.TEMPERATURE)return+ def test_save_defaults_role_to_entity_state_type_default(self):+ # An EntityState created without an explicit role gets the+ # EntityStateType's default_role at save() time. Locks in the+ # creation-time defaulting contract so callers that bypass the+ # HiModelHelper factories (e.g., direct objects.create) still+ # produce rows with a populated role.+ state = EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str=str(EntityStateType.TEMPERATURE),+ name='Test Temperature',+ )+ self.assertEqual( state.entity_state_role, EntityStateRole.TEMPERATURE )+ return++ def test_save_preserves_explicit_role(self):+ # An EntityState created with an explicit role keeps it.+ state = EntityState(+ entity=self.entity,+ entity_state_type_str=str(EntityStateType.TEMPERATURE),+ name='Thermostat Current',+ )+ state.entity_state_role = EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE+ state.save()+ state.refresh_from_db()+ self.assertEqual(+ state.entity_state_role, EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+ )+ return++ def test_create_sensor_factory_passes_explicit_role(self):+ # The HiModelHelper.create_sensor factory threads the+ # entity_state_role kwarg into EntityState creation.+ # Substate-creating callers (HA converter) rely on this to+ # assign domain-prefixed roles for multi-of-same-type cases.+ from hi.apps.model_helper import HiModelHelper+ sensor = HiModelHelper.create_sensor(+ entity = self.entity,+ entity_state_type = EntityStateType.TEMPERATURE,+ name = 'Setpoint Low',+ entity_state_role = EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW,+ )+ self.assertEqual(+ sensor.entity_state.entity_state_role,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW,+ )+ return+def test_value_range_dict_provides_flexible_state_value_handling(self):"""Test value_range_dict JSON serialization/deserialization - flexible state value support."""# Test with dictionary format (key-value mapping for display)@@ -455,7 +502,7 @@ class TestEntityStateChoices(BaseTestCase):"""``EntityState.choices()`` derives labels for the discretecontroller dropdown. Two paths: enum-bound state types useEntityStateValue labels directly; free-form discrete state- types humanize wire values."""+ types humanize the stored values."""def setUp(self):super().setUp()diff --git a/src/hi/apps/location/enums.py b/src/hi/apps/location/enums.pyindex a68f661a..4b0726f6 100644--- a/src/hi/apps/location/enums.py+++ b/src/hi/apps/location/enums.py@@ -1,70 +1,17 @@-from typing import List-from hi.apps.common.enums import LabeledEnum-from hi.apps.entity.enums import EntityStateTypeclass LocationViewType(LabeledEnum):-- def __init__( self,- label : str,- description : str,- entity_state_type_priority_list : List[ EntityStateType ] ):- super().__init__( label, description )- self.entity_state_type_priority_list = entity_state_type_priority_list- return-- DEFAULT = (- 'Default',- '',- [ EntityStateType.MOVEMENT,- EntityStateType.PRESENCE,- EntityStateType.OPEN_CLOSE,- EntityStateType.ON_OFF,- EntityStateType.LIGHT_DIMMER,- EntityStateType.LIGHT_LEVEL,- EntityStateType.SOUND_LEVEL,- EntityStateType.TEMPERATURE,- EntityStateType.HIGH_LOW,- EntityStateType.HUMIDITY,- EntityStateType.MOISTURE,- EntityStateType.WIND_SPEED,- EntityStateType.AIR_PRESSURE,- EntityStateType.ELECTRIC_USAGE,- EntityStateType.WATER_FLOW,- EntityStateType.HIGH_LOW,- ],-- )- SECURITY = (- 'Security',- '',- [ EntityStateType.MOVEMENT,- EntityStateType.PRESENCE,- EntityStateType.OPEN_CLOSE,- EntityStateType.OPEN_CLOSE_POSITION,- EntityStateType.ON_OFF,- EntityStateType.LIGHT_DIMMER,- ],- )- AUTOMATION = (- 'Automation',- '',- [ EntityStateType.MOVEMENT,- EntityStateType.PRESENCE,- EntityStateType.OPEN_CLOSE,- EntityStateType.OPEN_CLOSE_POSITION,- EntityStateType.ON_OFF,- EntityStateType.LIGHT_DIMMER,- EntityStateType.POWER_LEVEL,- EntityStateType.LIGHT_LEVEL,- EntityStateType.CONNECTIVITY,- EntityStateType.HIGH_LOW,- EntityStateType.SOUND_LEVEL,- EntityStateType.DISCRETE,- EntityStateType.CONTINUOUS,- ],- )+ """View-level intent for a LocationView. Drives which interactions+ are offered: AUTOMATION enables one-click control on entity icons;+ DEFAULT and SECURITY route the click to the EntityStatus modal.+ Per-entity state selection (visual primary, one-click target) is+ handled by the role-based orderings in+ ``hi.apps.entity.entity_state_role_order``."""++ DEFAULT = ( 'Default' , '' )+ SECURITY = ( 'Security' , '' )+ AUTOMATION = ( 'Automation', '' )class SvgItemType(LabeledEnum):diff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.pyindex db2c36d7..65fec8aa 100644--- a/src/hi/apps/location/location_manager.py+++ b/src/hi/apps/location/location_manager.py@@ -347,7 +347,6 @@ class LocationManager(Singleton):if include_status_display_data:manager = StatusDisplayManager()entity_to_entity_state_status_data_list = manager.get_entity_to_entity_state_status_data_list(- location_view = location_view,entities = displayed_entities,)else:diff --git a/src/hi/apps/location/location_view_data.py b/src/hi/apps/location/location_view_data.pyindex 5db08c00..fcb43175 100644--- a/src/hi/apps/location/location_view_data.py+++ b/src/hi/apps/location/location_view_data.py@@ -3,6 +3,7 @@ from typing import Dict, Generator, List, Setfrom hi.apps.collection.models import Collection, CollectionPath, CollectionPositionfrom hi.apps.common.svg_models import SvgIconItem, SvgPathItem+from hi.apps.entity.entity_state_role_order import ENTITY_PRIMARY_STATE_ORDERINGfrom hi.apps.entity.models import Entity, EntityPosition, EntityPathfrom hi.apps.location.svg_item_factory import SvgItemFactoryfrom hi.apps.monitor.status_display_data import StatusDisplayData@@ -28,8 +29,13 @@ class LocationViewData:def __post_init__(self):self._svg_item_factory = SvgItemFactory()- self._css_class_map = self._get_css_class_map()+ # Primary-state map is computed first; the CSS class map is+ # derived from it so the entity's ``<g>`` element carries+ # exactly one ``hi-entity-state-*`` class (the primary).+ # That keeps the polling update path's per-state CSS class+ # selectors from clobbering the icon's ``status`` attribute.self._latest_entity_state_status_data_map = self._get_latest_entity_state_status_data_map()+ self._css_class_map = self._get_css_class_map()returndef svg_icon_items(self) -> Generator[ SvgIconItem, None, None ]:@@ -103,16 +109,24 @@ class LocationViewData:returndef _get_css_class_map(self):+ # One ``hi-entity-state-*`` class per entity — the primary+ # state's class. Entities without a primary state (no states+ # with sensor responses) get no class.css_class_map = dict()- for entity, entity_state_status_data_list in self.entity_to_entity_state_status_data_list.items():- if not entity_state_status_data_list:- continue- entity_states = [ x.entity_state for x in entity_state_status_data_list ]- css_class_map[entity] = ' '.join([ x.css_class for x in entity_states ])+ for entity, picked in self._latest_entity_state_status_data_map.items():+ css_class_map[entity] = picked.entity_state.css_classcontinuereturn css_class_mapdef _get_latest_entity_state_status_data_map(self):+ # Per-entity primary-state selection: among states with a+ # sensor response, pick the one whose role ranks highest in+ # ``ENTITY_PRIMARY_STATE_ORDERING`` for the entity's+ # EntityType. The picked state's value drives the entity's+ # rendered ``status`` attribute (and from there, the CSS-bound+ # visual styling). Multi-sensor correctness is inherited: each+ # EntityStateStatusData.latest_sensor_response already reflects+ # the time-latest response across all of that state's sensors.latest_entity_state_status_data_map = dict()for entity, entity_state_status_data_list in self.entity_to_entity_state_status_data_list.items():if not entity_state_status_data_list:@@ -120,8 +134,11 @@ class LocationViewData:with_responses_list = [ x for x in entity_state_status_data_list if x.latest_sensor_response ]if not with_responses_list:continue- with_responses_list.sort( key = lambda item : item.latest_sensor_response.timestamp,- reverse = True )+ with_responses_list.sort(+ key = lambda d: ENTITY_PRIMARY_STATE_ORDERING.sort_key(+ d.entity_state.entity_state_role, entity.entity_type,+ ),+ )latest_entity_state_status_data_map[entity] = with_responses_list[0]continuereturn latest_entity_state_status_data_mapdiff --git a/src/hi/apps/location/tests/test_location_view_data.py b/src/hi/apps/location/tests/test_location_view_data.pynew file mode 100644index 00000000..d0289bd6--- /dev/null+++ b/src/hi/apps/location/tests/test_location_view_data.py@@ -0,0 +1,107 @@+import logging+from datetime import datetime, timezone++from hi.apps.entity.enums import EntityStateRole, EntityStateType, EntityType+from hi.apps.entity.models import Entity, EntityState+from hi.apps.location.location_view_data import LocationViewData+from hi.apps.monitor.transient_models import EntityStateStatusData+from hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationKey+from hi.testing.base_test_case import BaseTestCase++logging.disable(logging.CRITICAL)+++def _make_status_data( entity_state : EntityState, value : str, timestamp : datetime ):+ response = SensorResponse(+ integration_key = IntegrationKey( integration_id='test', integration_name='test' ),+ value = value,+ timestamp = timestamp,+ )+ return EntityStateStatusData(+ entity_state = entity_state,+ sensor_response_list = [ response ],+ controller_data_list = [],+ has_sensor = True,+ )+++class TestLatestEntityStateStatusDataPicker(BaseTestCase):++ def _make_location_view_data( self, entity_to_list ):+ # Minimal construction — only the picker path needs the+ # entity-to-status-data map; other fields can be empty.+ return LocationViewData(+ location_view = None,+ entity_positions = [],+ entity_paths = [],+ collection_positions = [],+ collection_paths = [],+ unpositioned_collections = [],+ orphan_entities = set(),+ entity_to_entity_state_status_data_list = entity_to_list,+ )++ def test_role_priority_picks_primary_regardless_of_timestamp(self):+ # The picker selects the state whose role ranks highest in+ # ENTITY_PRIMARY_STATE_ORDERING for the entity's type, NOT+ # the most-recently-timestamped state. For a ceiling fan,+ # FAN_SPEED is the configured primary and must win even when+ # another state's response is more recent.+ fan = Entity.objects.create(+ name = 'Test Fan',+ entity_type_str = str( EntityType.CEILING_FAN ),+ )+ speed_state = EntityState.objects.create(+ entity = fan,+ entity_state_type_str = str( EntityStateType.POWER_LEVEL ),+ name = 'Speed',+ )+ speed_state.entity_state_role = EntityStateRole.FAN_SPEED+ speed_state.save()++ oscillation_state = EntityState.objects.create(+ entity = fan,+ entity_state_type_str = str( EntityStateType.ON_OFF ),+ name = 'Oscillation',+ )+ oscillation_state.entity_state_role = EntityStateRole.FAN_OSCILLATION+ oscillation_state.save()++ older = datetime( 2026, 1, 1, 10, 0, 0, tzinfo = timezone.utc )+ newer = datetime( 2026, 1, 1, 11, 0, 0, tzinfo = timezone.utc )+ status_list = [+ # Oscillation has the newer timestamp; the old picker+ # would have selected it. The role-based picker selects+ # FAN_SPEED.+ _make_status_data( oscillation_state, 'on', newer ),+ _make_status_data( speed_state, '75', older ),+ ]++ data = self._make_location_view_data({ fan: status_list })+ picked = data._latest_entity_state_status_data_map[ fan ]+ self.assertEqual( picked.entity_state, speed_state )++ def test_states_without_responses_are_skipped(self):+ # Locks in the "must have a response to be picked" guard.+ fan = Entity.objects.create(+ name = 'Test Fan',+ entity_type_str = str( EntityType.CEILING_FAN ),+ )+ speed_state = EntityState.objects.create(+ entity = fan,+ entity_state_type_str = str( EntityStateType.POWER_LEVEL ),+ name = 'Speed',+ )+ # No response — should be filtered out, leaving nothing+ # for the picker to choose.+ status_list = [+ EntityStateStatusData(+ entity_state = speed_state,+ sensor_response_list = [],+ controller_data_list = [],+ has_sensor = True,+ ),+ ]+ data = self._make_location_view_data({ fan: status_list })+ self.assertNotIn( fan, data._latest_entity_state_status_data_map )diff --git a/src/hi/apps/location/tests/test_models.py b/src/hi/apps/location/tests/test_models.pyindex 0dc37e1d..093e60cd 100644--- a/src/hi/apps/location/tests/test_models.py+++ b/src/hi/apps/location/tests/test_models.py@@ -233,13 +233,9 @@ class TestLocationView(BaseTestCase):# Test setter conversions work correctlylocation_view.location_view_type = LocationViewType.AUTOMATIONlocation_view.svg_style_name = SvgStyleName.COLOR-+self.assertEqual(location_view.location_view_type_str, 'automation')self.assertEqual(location_view.svg_style_name_str, 'color')-- # Test that enum business logic is accessible- automation_priorities = location_view.location_view_type.entity_state_type_priority_list- self.assertGreater(len(automation_priorities), 0)returndef test_location_view_cascade_deletion_from_location(self):diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.pyindex 9fcfd7be..a101548d 100644--- a/src/hi/apps/location/views.py+++ b/src/hi/apps/location/views.py@@ -137,7 +137,6 @@ class LocationItemStatusView( View, LocationViewMixin, EntityViewMixin ):logger.debug( f'Trying one-click: {entity}' )controller_outcome = OneClickControlService().execute_one_click_control(entity = entity,- location_view_type = location_view.location_view_type,)if controller_outcome.has_errors:raise OneClickError(diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.pyindex ad6549fb..efed1de0 100644--- a/src/hi/apps/model_helper.py+++ b/src/hi/apps/model_helper.py@@ -6,11 +6,12 @@ from hi.apps.alert.enums import AlarmLevelfrom hi.apps.control.enums import ControllerTypefrom hi.apps.control.models import Controllerfrom hi.apps.entity.enums import (+ EntityStateRole,EntityStateType,EntityStateValue,HumidityUnit,TemperatureUnit,-)+)from hi.apps.entity.models import Entity, EntityStatefrom hi.apps.event.enums import EventClauseOperator, EventTypefrom hi.apps.event.event_manager import EventManager@@ -538,17 +539,21 @@ class HiModelHelper:integration_key : IntegrationKey = None,value_range_str : str = '',units : str = None,+ entity_state_role : EntityStateRole = None,provides_video_stream : bool = False ) -> Sensor:if not name:name = f'{entity.name}'- entity_state = EntityState.objects.create(+ entity_state_kwargs = dict(entity = entity,entity_state_type_str = str( entity_state_type ),name = name,value_range_str = value_range_str,units = units,)+ if entity_state_role is not None:+ entity_state_kwargs['role_str'] = str( entity_state_role )+ entity_state = EntityState.objects.create( **entity_state_kwargs )sensor = Sensor(entity_state = entity_state,name = name,@@ -559,7 +564,7 @@ class HiModelHelper:sensor.integration_key = integration_keysensor.save()return sensor-+@classmethoddef create_controller( cls,entity : Entity,@@ -569,17 +574,21 @@ class HiModelHelper:is_sensed : bool = True,integration_key : IntegrationKey = None,value_range_str : str = '',- units : str = None ) -> Controller:+ units : str = None,+ entity_state_role : EntityStateRole = None ) -> Controller:if not name:name = f'{entity.name}'-- entity_state = EntityState.objects.create(++ entity_state_kwargs = dict(entity = entity,entity_state_type_str = str( entity_state_type ),name = name,value_range_str = value_range_str,units = units,)+ if entity_state_role is not None:+ entity_state_kwargs['role_str'] = str( entity_state_role )+ entity_state = EntityState.objects.create( **entity_state_kwargs )return cls.add_controller(entity = entity,diff --git a/src/hi/apps/monitor/status_display_manager.py b/src/hi/apps/monitor/status_display_manager.pyindex 64816454..626b6a5b 100644--- a/src/hi/apps/monitor/status_display_manager.py+++ b/src/hi/apps/monitor/status_display_manager.py@@ -3,12 +3,11 @@ from cachetools import TTLCachefrom typing import Dict, List, Set, Sequencefrom django.conf import settings+from django.db.models import prefetch_related_objectsfrom hi.apps.control.transient_models import ControllerDatafrom hi.apps.common.singleton import Singleton-from hi.apps.entity.enums import EntityStateTypefrom hi.apps.entity.models import Entity, EntityState-from hi.apps.location.models import LocationViewfrom hi.apps.location.svg_item_factory import SvgItemFactoryfrom hi.apps.sense.models import Sensorfrom hi.apps.sense.sensor_response_manager import SensorResponseMixin@@ -293,33 +292,43 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):def get_entity_to_entity_state_status_data_list(self,- location_view : LocationView,entities : Set[ Entity ] ) -> Dict[ Entity, List[ EntityStateStatusData ] ]:- """- Builds a map from Entity to EntityStateStatusData for the single EntityState- that is the highest display priority for the given- LocationView. i.e., Picks a single EntityState for each Entity to- define the visual display used in the LocationView where we can- really only represent one thing at a time (visually).- """-- entity_to_entity_state_list = self._get_entity_to_entity_state_list(- location_view = location_view,- entities = entities,+ """Builds a map from Entity to its EntityStateStatusData list+ (covering all of the entity's states, including any delegated+ principal states). Per-entity primary-state selection happens+ downstream in ``LocationViewData`` via+ ``ENTITY_PRIMARY_STATE_ORDERING`` — no EntityStateType+ pre-filter is applied here."""++ # Batch-prefetch the relations this flow will walk so the+ # per-entity loop below doesn't issue 2N delegation/states+ # queries and the downstream sensor/controller fetches don't+ # add 2M more.+ prefetch_related_objects(+ list( entities ),+ 'states__sensors',+ 'states__controllers',+ 'entity_state_delegations__entity_state__sensors',+ 'entity_state_delegations__entity_state__controllers',)++ entity_to_entity_state_list = dict()all_entity_states = set()- for entity_state_list in entity_to_entity_state_list.values():- all_entity_states.update( entity_state_list )+ for entity in entities:+ entity_states = self.all_entity_states_including_delegations( entity )+ if not entity_states:+ continue+ entity_to_entity_state_list[entity] = entity_states+ all_entity_states.update( entity_states )continue-+entity_state_to_status_data = self._get_entity_state_to_entity_state_status_data(entity_states = all_entity_states,)entity_to_entity_state_status_data_list = dict()for entity, entity_state_list in entity_to_entity_state_list.items():- if entity not in entity_to_entity_state_status_data_list:- entity_to_entity_state_status_data_list[entity] = list()+ entity_to_entity_state_status_data_list[entity] = list()for entity_state in entity_state_list:entity_state_status_data = entity_state_to_status_data.get( entity_state )if entity_state_status_data:@@ -329,88 +338,32 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):return entity_to_entity_state_status_data_list- def _get_entity_to_entity_state_list(- self,- location_view : LocationView,- entities : Set[ Entity ] ) -> Dict[ Entity, List[ EntityState ] ]:- """- A map from Entity to EntityState for the list of EntityState with- EntityStateTyoe that is the highest display priority for the given- LocationView.- """- location_view_type = location_view.location_view_type-- entity_state_type_priority_list = location_view_type.entity_state_type_priority_list-- entity_to_entity_state_list = dict()- for entity in entities:- entity_state_list = self.get_entity_state_list_for_status(- entity = entity,- entity_state_type_priority_list = entity_state_type_priority_list,- )- if entity_state_list:- entity_to_entity_state_list[entity] = entity_state_list- continue-- return entity_to_entity_state_list-- def get_entity_state_list_for_status(- self,- entity : Entity,- entity_state_type_priority_list : List[ EntityStateType ] ) -> List[ EntityState ]:- """- Finds all EntityState for the highest priority EntityStateType.- """-- # Delegate entities include will include all their principal entity- # states, though any direct state will take precendence-- delegations_queryset = entity.entity_state_delegations.select_related('entity_state').all()- all_entity_states = [ x.entity_state for x in delegations_queryset ]- all_entity_states.extend( entity.states.all() )-- # Gather all possible EntityStateType for the Entity and its principals.- entity_state_list_map = dict()- for entity_state in all_entity_states:- if entity_state.entity_state_type not in entity_state_list_map:- entity_state_list_map[entity_state.entity_state_type] = list()- entity_state_list_map[entity_state.entity_state_type].append( entity_state )- continue-- if not entity_state_list_map:- return None-- entity_state_type_for_status = self.get_entity_state_type_for_status(- entity_state_types = entity_state_list_map.keys(),- entity_state_type_priority_list = entity_state_type_priority_list,- )- entity_state_list = entity_state_list_map.get( entity_state_type_for_status )- return entity_state_list-- def get_entity_state_type_for_status(- self,- entity_state_types : Sequence[ EntityStateType ],- entity_state_type_priority_list : List[ EntityStateType ] ) -> EntityStateType:- """- Determines the single EntityStateType that is the highest display priority- from the given priority list. This defined what status will be visually displayed.- """-- for priority_entity_state_type in entity_state_type_priority_list:- if priority_entity_state_type in entity_state_types:- return priority_entity_state_type- continue-- # If no prioritizes state type matches, then fallback to an- # arbitrary, but deterministic choice by using all defined values.- #- for default_entity_state_type in EntityStateType:- if default_entity_state_type in entity_state_types:- return default_entity_state_type- continue-- # This code should not really be reachable. Should always match one in fallback case.- return None+ def all_entity_states_including_delegations(+ self, entity : Entity ) -> List[ EntityState ]:+ """All EntityStates the entity exposes for status display:+ its own ``states`` plus any states delegated from principals+ via ``EntityStateDelegation``. Deduplicated to guard against+ the unusual case of an entity delegating one of its own+ states or two delegations resolving to the same state.++ ``.all()`` is used (not ``.select_related(...).all()``) so+ callers that have prefetched ``entity_state_delegations__+ entity_state`` use the cache. For single-entity callers with+ no prefetch, the additional FK fetch per delegation is+ bounded and acceptable."""+ seen = set()+ result = []+ for d in entity.entity_state_delegations.all():+ if d.entity_state.id in seen:+ continue+ seen.add( d.entity_state.id )+ result.append( d.entity_state )+ for state in entity.states.all():+ if state.id in seen:+ continue+ seen.add( state.id )+ result.append( state )+ return resultdef get_latest_sensor_response( self, entity_state : EntityState ) -> SensorResponse:sensor_list = list( entity_state.sensors.all() )diff --git a/src/hi/apps/monitor/tests/test_transient_models.py b/src/hi/apps/monitor/tests/test_transient_models.pyindex 34741208..2402a983 100644--- a/src/hi/apps/monitor/tests/test_transient_models.py+++ b/src/hi/apps/monitor/tests/test_transient_models.py@@ -149,12 +149,12 @@ class TestEntityStatusData(BaseTestCase):)context = status_data.to_template_context()-+# Should include all data needed for template renderingself.assertIn('entity', context)- self.assertIn('entity_state_status_data_list', context)+ self.assertIn('state_status_data_list', context)self.assertEqual(context['entity'], entity)- self.assertEqual(len(context['entity_state_status_data_list']), 2)+ self.assertEqual(len(context['state_status_data_list']), 2)def test_entity_status_data_supports_optional_display_icon(self):"""Test entity status data with optional SVG icon for display."""@@ -195,7 +195,7 @@ class TestEntityStatusData(BaseTestCase):# Template context should still be validcontext = status_data.to_template_context()self.assertEqual(context['entity'], entity)- self.assertEqual(len(context['entity_state_status_data_list']), 0)+ self.assertEqual(len(context['state_status_data_list']), 0)def test_entity_status_data_aggregates_multiple_state_types(self):"""Test entity status data aggregation across different state types."""diff --git a/src/hi/apps/monitor/transient_models.py b/src/hi/apps/monitor/transient_models.pyindex 6fca0da4..f827688d 100644--- a/src/hi/apps/monitor/transient_models.py+++ b/src/hi/apps/monitor/transient_models.py@@ -3,6 +3,7 @@ from typing import Listfrom hi.apps.control.transient_models import ControllerDatafrom hi.apps.common.svg_models import SvgIconItem+from hi.apps.entity.entity_state_role_order import ENTITY_STATUS_VIEW_ORDERINGfrom hi.apps.entity.models import Entity, EntityStatefrom hi.apps.sense.transient_models import SensorResponse@@ -42,10 +43,26 @@ class EntityStatusData:self.entity_for_video = self.entityreturn+ @property+ def state_status_data_list(self) -> List[ EntityStateStatusData ]:+ """Display-ordered EntityStateStatusData list, sorted by+ ``ENTITY_STATUS_VIEW_ORDERING`` for the entity's EntityType.+ Use this in templates and other consumers that need the+ canonical display order. The underlying+ ``entity_state_status_data_list`` field stays order-neutral+ for consumers (e.g., per-state CSS-class update paths) that+ don't care about listing order."""+ return sorted(+ self.entity_state_status_data_list,+ key = lambda d: ENTITY_STATUS_VIEW_ORDERING.sort_key(+ d.entity_state.entity_state_role, self.entity.entity_type,+ ),+ )+def to_template_context(self):context = {'entity': self.entity,- 'entity_state_status_data_list': self.entity_state_status_data_list,+ 'state_status_data_list': self.state_status_data_list,'entity_for_video': self.entity_for_video,'display_only_svg_icon_item': self.display_only_svg_icon_item,'display_category': self.display_category,diff --git a/src/hi/requirements/base.txt b/src/hi/requirements/base.txtindex 67bc1fb3..01caf017 100644--- a/src/hi/requirements/base.txt+++ b/src/hi/requirements/base.txt@@ -27,6 +27,6 @@ six==1.17.0sqlparse==0.5.5typing_extensions==4.15.0tzlocal==5.3.1-urllib3==2.6.3+urllib3==2.7.0websocket-client==1.8.0yarl==1.12.0diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.pyindex aa4ef853..354ccfb6 100644--- a/src/hi/services/hass/hass_converter.py+++ b/src/hi/services/hass/hass_converter.py@@ -11,6 +11,7 @@ from hi.apps.attribute.enums import (AttributeValueType,)from hi.apps.entity.enums import (+ EntityStateRole,EntityStateType,EntityType,EntityStateValue,@@ -641,10 +642,10 @@ class HassConverter:# controller payloads so payload-shape changes# propagate to existing records.any_existing_substate = False- for substate_spec in cls._substate_specs_for_hass_state( hass_state ):+ for state_spec in cls._state_specs_for_hass_state( hass_state ):sub_key = cls._substate_integration_key(hass_state = hass_state,- suffix = substate_spec.suffix,+ suffix = state_spec.suffix,)seen_state_integration_keys.add( sub_key )sub_controller = entiity_controllers.get( sub_key )@@ -654,7 +655,7 @@ class HassConverter:if sub_controller:sub_payload = cls._substate_integration_payload(hass_state = hass_state,- spec = substate_spec,+ spec = state_spec,)changed_fields = sub_controller.update_integration_payload( sub_payload )if changed_fields:@@ -777,8 +778,8 @@ class HassConverter:and ( hass_state.domain in ignore_light_state_prefixes )):continue- substate_specs = cls._substate_specs_for_hass_state( hass_state )- if substate_specs:+ state_specs = cls._state_specs_for_hass_state( hass_state )+ if state_specs:# Multi-substate decomposition: ALL EntityStates# are created as peer substates (no asymmetric# bare-key parent). The Entity itself is still@@ -814,7 +815,7 @@ class HassConverter:exist. Pass the entity's existing``Controller``/``Sensor`` maps so re-sync avoidsre-creation. Returns the list of newly-created models."""- specs = cls._substate_specs_for_hass_state( hass_state )+ specs = cls._state_specs_for_hass_state( hass_state )if not specs:return []if existing_controllers is None:@@ -845,6 +846,7 @@ class HassConverter:integration_key = substate_integration_key,value_range_str = value_range_str,units = spec.units,+ entity_state_role = spec.role,)controller.integration_payload = cls._substate_integration_payload(hass_state = hass_state,@@ -860,6 +862,7 @@ class HassConverter:integration_key = substate_integration_key,value_range_str = value_range_str,units = spec.units,+ entity_state_role = spec.role,)created.append( sensor )continue@@ -869,7 +872,7 @@ class HassConverter:def _substate_integration_payload(cls,hass_state : HassState,- spec : '_SubstateSpec',+ spec : '_StateSpec',) -> dict:payload = {'domain': hass_state.domain,@@ -1070,13 +1073,19 @@ class HassConverter:# context (e.g., "Speed" for a fan POWER_LEVEL substate# rather than the generic "Power Level").@dataclass(frozen=True)- class _SubstateSpec:+ class _StateSpec:suffix : strentity_state_type : EntityStateTypeis_controllable : boolvalue_range : Optional[Dict] = Nonelabel : Optional[str] = Noneunits : Optional[str] = None+ # Refined EntityStateRole; ``None`` falls back to the+ # EntityStateType's default role at creation time. Set when+ # the spec carries domain semantics beyond the bare type+ # (e.g., distinguishing current vs. target temperature on a+ # thermostat where both are EntityStateType.TEMPERATURE).+ role : Optional[EntityStateRole] = None@propertydef display_label(self) -> str:@@ -1111,8 +1120,8 @@ class HassConverter:}@classmethod- def _substate_specs_for_hass_state(- cls, hass_state: HassState ) -> List[ '_SubstateSpec' ]:+ def _state_specs_for_hass_state(+ cls, hass_state: HassState ) -> List[ '_StateSpec' ]:"""Return the substate specs for a HA state that decomposesinto multiple HI EntityStates, or an empty list when thestate maps to a single bare-key EntityState. Each domain@@ -1122,16 +1131,16 @@ class HassConverter:``hass_state`` actually reports."""if hass_state.domain == HassApi.LIGHT_DOMAIN:- return cls._light_substate_specs( hass_state )+ return cls._light_state_specs( hass_state )if hass_state.domain == HassApi.FAN_DOMAIN:- return cls._fan_substate_specs( hass_state )+ return cls._fan_state_specs( hass_state )if hass_state.domain == HassApi.CLIMATE_DOMAIN:- return cls._climate_substate_specs( hass_state )+ return cls._climate_state_specs( hass_state )return []@classmethod- def _light_substate_specs(- cls, hass_state: HassState ) -> List[ '_SubstateSpec' ]:+ def _light_state_specs(+ cls, hass_state: HassState ) -> List[ '_StateSpec' ]:"""Color-related substates implied by a HA ``light.x`` state's``supported_color_modes`` declaration. A bulb supporting HS(or RGB / XY, alternate representations of HS chromaticity)@@ -1151,24 +1160,27 @@ class HassConverter:specs = []if chromatic_present or color_temp_present:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.BRIGHTNESS_ATTR,entity_state_type = EntityStateType.LIGHT_DIMMER,is_controllable = True,value_range = { 'min': 0, 'max': 100 },+ role = EntityStateRole.LIGHT_BRIGHTNESS,))if chromatic_present:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = 'hue',entity_state_type = EntityStateType.HUE,is_controllable = True,value_range = { 'min': 0, 'max': 360 },+ role = EntityStateRole.LIGHT_HUE,))- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = 'saturation',entity_state_type = EntityStateType.SATURATION,is_controllable = True,value_range = { 'min': 0, 'max': 100 },+ role = EntityStateRole.LIGHT_SATURATION,))if color_temp_present:# Real bulbs have device-specific Kelvin ranges (e.g.,@@ -1183,26 +1195,28 @@ class HassConverter:max_k = hass_state.attributes.get(HassApi.MAX_COLOR_TEMP_KELVIN_ATTR, 6500,)- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.COLOR_MODE_COLOR_TEMP,entity_state_type = EntityStateType.COLOR_TEMPERATURE,is_controllable = True,value_range = { 'min': min_k, 'max': max_k },+ role = EntityStateRole.LIGHT_COLOR_TEMPERATURE,))# COLOR_MODE only adds information when there's actual# mode-switching to track. A bulb with a single supported# mode has a constant value; skip it.if len( supported ) > 1:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.COLOR_MODE_ATTR,entity_state_type = EntityStateType.COLOR_MODE,is_controllable = False,+ role = EntityStateRole.LIGHT_COLOR_MODE,))return specs@classmethod- def _fan_substate_specs(- cls, hass_state: HassState ) -> List[ '_SubstateSpec' ]:+ def _fan_state_specs(+ cls, hass_state: HassState ) -> List[ '_StateSpec' ]:"""Substates implied by a HA ``fan.x`` state when it reportsany of the multi-axis features (oscillating / direction /preset_modes). Speed becomes a peer ``~speed`` POWER_LEVEL@@ -1214,22 +1228,24 @@ class HassConverter:attrs = hass_state.attributesspecs = []if cls._has_percentage_capability( hass_state ):- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = 'speed',entity_state_type = EntityStateType.POWER_LEVEL,is_controllable = True,value_range = { 'min': 0, 'max': 100 },label = 'Speed',+ role = EntityStateRole.FAN_SPEED,))if HassApi.OSCILLATING_ATTR in attrs:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.OSCILLATING_ATTR,entity_state_type = EntityStateType.ON_OFF,is_controllable = True,label = 'Oscillation',+ role = EntityStateRole.FAN_OSCILLATION,))if HassApi.DIRECTION_ATTR in attrs:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.DIRECTION_ATTR,entity_state_type = EntityStateType.DISCRETE,is_controllable = True,@@ -1238,15 +1254,17 @@ class HassConverter:HassApi.FAN_DIRECTION_REVERSE: 'Reverse',},label = 'Direction',+ role = EntityStateRole.FAN_DIRECTION,))preset_modes = attrs.get( HassApi.PRESET_MODES_ATTR )if isinstance( preset_modes, list ) and preset_modes:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.PRESET_MODE_ATTR,entity_state_type = EntityStateType.DISCRETE,is_controllable = True,value_range = { mode: mode for mode in preset_modes },label = 'Preset',+ role = EntityStateRole.FAN_PRESET_MODE,))return specs@@ -1267,8 +1285,8 @@ class HassConverter:}@classmethod- def _climate_substate_specs(- cls, hass_state: HassState ) -> List[ '_SubstateSpec' ]:+ def _climate_state_specs(+ cls, hass_state: HassState ) -> List[ '_StateSpec' ]:"""Substates implied by a HA ``climate.x`` state. A climateentity that declares ``hvac_modes`` always decomposes:current_temperature (sensor), hvac_mode (controller from@@ -1286,26 +1304,29 @@ class HassConverter:canonical_unit = CANONICAL_TEMPERATURE_UNITspecs = [- cls._SubstateSpec(+ cls._StateSpec(suffix = HassApi.CURRENT_TEMPERATURE_ATTR,entity_state_type = EntityStateType.TEMPERATURE,is_controllable = False,label = 'Current Temperature',units = canonical_unit,+ role = EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,),- cls._SubstateSpec(+ cls._StateSpec(suffix = HassApi.HVAC_MODE_ATTR,entity_state_type = EntityStateType.DISCRETE,is_controllable = True,value_range = { mode: mode for mode in hvac_modes },label = 'HVAC Mode',+ role = EntityStateRole.HVAC_MODE,),- cls._SubstateSpec(+ cls._StateSpec(suffix = HassApi.HVAC_ACTION_ATTR,entity_state_type = EntityStateType.DISCRETE,is_controllable = False,value_range = dict( cls._HVAC_ACTION_CHOICES ),label = 'HVAC Action',+ role = EntityStateRole.HVAC_ACTION,),]@@ -1321,30 +1342,33 @@ class HassConverter:has_single_mode = any( m != HassApi.HVAC_MODE_HEAT_COOL for m in hvac_modes )has_dual_mode = HassApi.HVAC_MODE_HEAT_COOL in hvac_modesif has_single_mode:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = 'target_temperature',entity_state_type = EntityStateType.TEMPERATURE,is_controllable = True,value_range = setpoint_range,label = 'Setpoint',units = canonical_unit,+ role = EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,))if has_dual_mode:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.TARGET_TEMP_LOW_ATTR,entity_state_type = EntityStateType.TEMPERATURE,is_controllable = True,value_range = setpoint_range,label = 'Setpoint Low',units = canonical_unit,+ role = EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW,))- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.TARGET_TEMP_HIGH_ATTR,entity_state_type = EntityStateType.TEMPERATURE,is_controllable = True,value_range = setpoint_range,label = 'Setpoint High',units = canonical_unit,+ role = EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_HIGH,))# Optional axes that real thermostats commonly expose.@@ -1353,24 +1377,26 @@ class HassConverter:# that doesn't have one.fan_modes = attrs.get( HassApi.FAN_MODES_ATTR )if isinstance( fan_modes, list ) and fan_modes:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.FAN_MODE_ATTR,entity_state_type = EntityStateType.DISCRETE,is_controllable = True,value_range = { mode: mode for mode in fan_modes },label = 'Fan Mode',+ role = EntityStateRole.FAN_MODE,))preset_modes = attrs.get( HassApi.PRESET_MODES_ATTR )if isinstance( preset_modes, list ) and preset_modes:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.PRESET_MODE_ATTR,entity_state_type = EntityStateType.DISCRETE,is_controllable = True,value_range = { mode: mode for mode in preset_modes },label = 'Preset',+ role = EntityStateRole.PRESET_MODE,))if HassApi.CURRENT_HUMIDITY_ATTR in attrs:- specs.append( cls._SubstateSpec(+ specs.append( cls._StateSpec(suffix = HassApi.CURRENT_HUMIDITY_ATTR,entity_state_type = EntityStateType.HUMIDITY,is_controllable = False,@@ -1394,7 +1420,7 @@ class HassConverter:def _extract_substate_value(cls,hass_state : HassState,- spec : '_SubstateSpec',+ spec : '_StateSpec',) -> Optional[ str ]:"""Pull the value for a single substate out of a HA state,dispatching per-domain. Returns ``None`` when the relevant@@ -1483,7 +1509,7 @@ class HassConverter:@classmethoddef _climate_substate_value(- cls, hass_state : HassState, spec : '_SubstateSpec' ) -> Optional[ str ]:+ cls, hass_state : HassState, spec : '_StateSpec' ) -> Optional[ str ]:"""Climate-domain substate values. Temperature substates emitfloats as strings, converted from HA's reported``temperature_unit`` to the EntityState's stored unit (looked@@ -2272,13 +2298,13 @@ class HassConverter:lights brightness is itself a peer substate (suffixedkey); for single-state lights it goes at the bare key."""result : Dict[ IntegrationKey, str ] = {}- substate_specs = cls._substate_specs_for_hass_state( hass_state )- if not substate_specs:+ state_specs = cls._state_specs_for_hass_state( hass_state )+ if not state_specs:brightness_value = cls._dimmer_brightness_value( hass_state )if brightness_value:result[ cls.hass_state_to_integration_key( hass_state ) ] = brightness_valuereturn result- for spec in substate_specs:+ for spec in state_specs:value = cls._extract_substate_value( hass_state, spec )if value is None:continue@@ -2426,10 +2452,10 @@ class HassConverter:fans get a single bare-key POWER_LEVEL value with thenumeric percentage. Fans without percentage stay ON_OFFand pass HA's discrete ``'on'``/``'off'`` state through."""- substate_specs = cls._substate_specs_for_hass_state( hass_state )- if substate_specs:+ state_specs = cls._state_specs_for_hass_state( hass_state )+ if state_specs:result : Dict[ IntegrationKey, str ] = {}- for spec in substate_specs:+ for spec in state_specs:value = cls._extract_substate_value( hass_state, spec )if value is None:continue@@ -2458,11 +2484,11 @@ class HassConverter:lands at its suffix-keyed integration_key. Climateentities lacking ``hvac_modes`` (rare but allowed byHA's contract) fall through to passthrough behavior."""- substate_specs = cls._substate_specs_for_hass_state( hass_state )- if not substate_specs:+ state_specs = cls._state_specs_for_hass_state( hass_state )+ if not state_specs:return cls._passthrough_to_sensor_value_map( hass_state )result : Dict[ IntegrationKey, str ] = {}- for spec in substate_specs:+ for spec in state_specs:value = cls._extract_substate_value( hass_state, spec )if value is None:continuediff --git a/src/hi/services/hass/tests/test_hass_converter_climate.py b/src/hi/services/hass/tests/test_hass_converter_climate.pyindex 78f2fe1d..dd613696 100644--- a/src/hi/services/hass/tests/test_hass_converter_climate.py+++ b/src/hi/services/hass/tests/test_hass_converter_climate.py@@ -4,7 +4,7 @@ from unittest.mock import patchfrom django.test import TestCasefrom hi.apps.control.models import Controller-from hi.apps.entity.enums import EntityStateType, EntityType+from hi.apps.entity.enums import EntityStateRole, EntityStateType, EntityTypefrom hi.apps.entity.models import EntityStatefrom hi.services.hass.hass_converter import HassConverterfrom hi.services.hass.hass_models import HassApi, HassDevice, HassServiceCall@@ -86,7 +86,7 @@ class TestClimateSubstateSpecs(TestCase):# Minimal climate without hvac_modes falls through to# legacy single-state TEMPERATURE handling.hass_state = _make_climate_hass_state( current_temperature=70 )- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )self.assertEqual( specs, [] )def test_full_feature_thermostat_has_all_axes(self):@@ -99,7 +99,7 @@ class TestClimateSubstateSpecs(TestCase):current_humidity = 42,temperature_unit = '°F',)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )suffixes = [ s.suffix for s in specs ]self.assertEqual( suffixes, ['current_temperature',@@ -112,6 +112,38 @@ class TestClimateSubstateSpecs(TestCase):'current_humidity',])+ def test_thermostat_temperature_substates_carry_distinct_roles(self):+ # The motivating multi-of-same-type case: a thermostat with+ # heat_cool + heat creates four EntityStateType.TEMPERATURE+ # substates. Roles disambiguate them; without per-substate+ # roles, downstream consumers (modal ordering, icon status+ # selection) couldn't tell current from setpoint-low from+ # setpoint-high from single-mode setpoint.+ hass_state = _make_climate_hass_state(+ hvac_modes = [ 'heat', 'cool', 'heat_cool', 'off' ],+ current_temperature = 70,+ target_temp_low = 68, target_temp_high = 75,+ )+ specs = HassConverter._state_specs_for_hass_state( hass_state )+ roles_by_suffix = { s.suffix: s.role for s in specs }+ self.assertEqual(+ roles_by_suffix['current_temperature'],+ EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+ )+ self.assertEqual(+ roles_by_suffix['target_temperature'],+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,+ )+ self.assertEqual(+ roles_by_suffix['target_temp_low'],+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW,+ )+ self.assertEqual(+ roles_by_suffix['target_temp_high'],+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_HIGH,+ )+ return+def test_heat_only_thermostat_omits_dual_setpoints(self):hass_state = _make_climate_hass_state(hvac_modes = [ 'heat', 'off' ],@@ -119,7 +151,7 @@ class TestClimateSubstateSpecs(TestCase):temperature = 22,temperature_unit = '°C',)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )suffixes = [ s.suffix for s in specs ]self.assertIn( 'target_temperature', suffixes )self.assertNotIn( 'target_temp_low', suffixes )@@ -132,7 +164,7 @@ class TestClimateSubstateSpecs(TestCase):current_temperature = 70,target_temp_low = 68, target_temp_high = 75,)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )suffixes = [ s.suffix for s in specs ]self.assertIn( 'target_temp_low', suffixes )self.assertIn( 'target_temp_high', suffixes )@@ -149,7 +181,7 @@ class TestClimateSubstateSpecs(TestCase):hvac_modes = [ 'heat', 'off' ],temperature_unit = ha_unit,)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )setpoint = next( s for s in specs if s.suffix == 'target_temperature' )self.assertEqual(setpoint.value_range,@@ -169,7 +201,7 @@ class TestClimateSubstateSpecs(TestCase):target_temp_low = 68, target_temp_high = 75,temperature_unit = '°F',)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )temperature_suffixes = {'current_temperature', 'target_temperature','target_temp_low', 'target_temp_high',@@ -186,7 +218,7 @@ class TestClimateSubstateSpecs(TestCase):hass_state = _make_climate_hass_state(hvac_modes = [ 'heat', 'auto', 'off' ],)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )hvac_mode = next( s for s in specs if s.suffix == 'hvac_mode' )self.assertEqual(hvac_mode.value_range,@@ -198,7 +230,7 @@ class TestClimateSubstateSpecs(TestCase):hvac_modes = [ 'heat', 'off' ],fan_modes = [ 'auto', 'low', 'medium', 'high' ],)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )fan_mode = next( s for s in specs if s.suffix == 'fan_mode' )self.assertEqual(fan_mode.value_range,@@ -209,7 +241,7 @@ class TestClimateSubstateSpecs(TestCase):hass_state = _make_climate_hass_state(hvac_modes = [ 'heat', 'off' ],)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )suffixes = [ s.suffix for s in specs ]self.assertNotIn( 'fan_mode', suffixes )diff --git a/src/hi/services/hass/tests/test_hass_converter_fan.py b/src/hi/services/hass/tests/test_hass_converter_fan.pyindex e0739338..d04ff0ac 100644--- a/src/hi/services/hass/tests/test_hass_converter_fan.py+++ b/src/hi/services/hass/tests/test_hass_converter_fan.py@@ -111,7 +111,7 @@ class TestFanSubstateSpecs(TestCase):def test_single_state_fan_has_no_substates(self):# Speed-only fan stays single-state at the bare key.hass_state = _make_fan_hass_state( percentage=50 )- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )self.assertEqual( specs, [] )def test_full_multi_feature_fan_has_four_substates(self):@@ -119,7 +119,7 @@ class TestFanSubstateSpecs(TestCase):percentage=50, oscillating=True,direction='forward', preset_modes=[ 'auto', 'sleep' ],)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )suffixes = [ s.suffix for s in specs ]self.assertEqual( suffixes, [ 'speed', 'oscillating', 'direction', 'preset_mode' ] )@@ -127,7 +127,7 @@ class TestFanSubstateSpecs(TestCase):# Fan declares oscillating but no percentage — only# oscillating substate (no speed peer to add).hass_state = _make_fan_hass_state( oscillating=False )- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )suffixes = [ s.suffix for s in specs ]self.assertEqual( suffixes, [ 'oscillating' ] )@@ -135,7 +135,7 @@ class TestFanSubstateSpecs(TestCase):hass_state = _make_fan_hass_state(percentage=50, oscillating=True,)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )speed = next( s for s in specs if s.suffix == 'speed' )self.assertEqual( speed.entity_state_type, EntityStateType.POWER_LEVEL )self.assertEqual( speed.display_label, 'Speed' )@@ -145,7 +145,7 @@ class TestFanSubstateSpecs(TestCase):hass_state = _make_fan_hass_state(preset_modes=[ 'auto', 'sleep', 'eco' ],)- specs = HassConverter._substate_specs_for_hass_state( hass_state )+ specs = HassConverter._state_specs_for_hass_state( hass_state )preset = next( s for s in specs if s.suffix == 'preset_mode' )self.assertEqual(preset.value_range,