Home Information - Your home, your data, organized.
Python
Issue #298: HA fan support (speed-only and multi-feature) with POWER_LEVEL EntityStateType and substate decomposition (#307)
Tony C5c0896b72621
diff --git a/src/hi/apps/control/templates/control/panes/controller_power_level.html b/src/hi/apps/control/templates/control/panes/controller_power_level.htmlnew file mode 100644index 00000000..3fe80705--- /dev/null+++ b/src/hi/apps/control/templates/control/panes/controller_power_level.html@@ -0,0 +1 @@+{% include "control/panes/continuous_slider.html" with slider_min=0 slider_max=100 slider_default=0 display_unit="%" slider_class="power-level-slider" %}diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex 975b5ffa..262b358d 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -304,6 +304,11 @@ class EntityStateType(LabeledEnum):OPEN_CLOSE_POSITION = ( 'Open/Close Position','Continuous open/close position as a percentage (0=closed, 100=open)',[] )+ POWER_LEVEL = ( 'Power Level',+ 'Generic continuous power/intensity/speed (0-100). Per-context label '+ '(e.g., "Speed" for fans, "Aperture" for dampers) is set on the '+ 'EntityState.',+ [] )PRESENCE = ( 'Presence' , '',[ EntityStateValue.ACTIVE,EntityStateValue.IDLE ] )diff --git a/src/hi/apps/location/enums.py b/src/hi/apps/location/enums.pyindex c237d01c..a68f661a 100644--- a/src/hi/apps/location/enums.py+++ b/src/hi/apps/location/enums.py@@ -56,6 +56,7 @@ class LocationViewType(LabeledEnum):EntityStateType.OPEN_CLOSE_POSITION,EntityStateType.ON_OFF,EntityStateType.LIGHT_DIMMER,+ EntityStateType.POWER_LEVEL,EntityStateType.LIGHT_LEVEL,EntityStateType.CONNECTIVITY,EntityStateType.HIGH_LOW,diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.pyindex f5a77c41..eb8334a9 100644--- a/src/hi/apps/model_helper.py+++ b/src/hi/apps/model_helper.py@@ -278,6 +278,27 @@ class HiModelHelper:value_range_str = json.dumps( value_range ),)+ @classmethod+ def create_power_level_controller(+ cls,+ entity : Entity,+ integration_key : IntegrationKey = None,+ name : str = None,+ is_sensed : bool = True ) -> Controller:+ if not name:+ name = f'{entity.name} Level'+ # Generic continuous power/intensity/speed 0-100. Per-context+ # label (e.g., "Speed" for fans) is set by the caller via name.+ value_range = { 'min': 0, 'max': 100 }+ return cls.create_controller(+ entity = entity,+ entity_state_type = EntityStateType.POWER_LEVEL,+ name = name,+ is_sensed = is_sensed,+ integration_key = integration_key,+ value_range_str = json.dumps( value_range ),+ )+@classmethoddef create_discrete_controller( cls,entity : Entity,diff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/status_display_data.pyindex 78700b34..8be70292 100644--- a/src/hi/apps/monitor/status_display_data.py+++ b/src/hi/apps/monitor/status_display_data.py@@ -127,6 +127,9 @@ class StatusDisplayData:if self.entity_state.entity_state_type == EntityStateType.OPEN_CLOSE_POSITION:return self._get_open_close_position_status_style()++ if self.entity_state.entity_state_type == EntityStateType.POWER_LEVEL:+ return StatusStyle.light_dimmer( self.latest_sensor_value )if self.entity_state.entity_state_type == EntityStateType.CONNECTIVITY:return self._get_connectivity_status_style()diff --git a/src/hi/apps/monitor/tests/test_status_display_data.py b/src/hi/apps/monitor/tests/test_status_display_data.pyindex 28e3652b..4110d666 100644--- a/src/hi/apps/monitor/tests/test_status_display_data.py+++ b/src/hi/apps/monitor/tests/test_status_display_data.py@@ -356,6 +356,75 @@ class TestStatusDisplayData(BaseTestCase):self.assertEqual( display_data.svg_status_style, StatusStyle.Closed )+ # POWER_LEVEL State Type Tests (continuous-percentage controller)+ # Reuses StatusStyle.light_dimmer for bucketing: <15 off,+ # 15-84 dim, >=85 on. Verify the bucket boundaries and the+ # graceful path for malformed values.++ def test_power_level_zero_returns_off_bucket(self):+ sensor_response = self._create_mock_sensor_response( '0' )+ status_data = self._create_entity_state_status_data(+ 'POWER_LEVEL', [ sensor_response ],+ )++ display_data = StatusDisplayData( status_data )++ self.assertEqual( display_data.svg_status_style.status_value, 'off' )++ def test_power_level_low_returns_dim_bucket_at_threshold(self):+ # 15 is the off→dim boundary.+ sensor_response = self._create_mock_sensor_response( '15' )+ status_data = self._create_entity_state_status_data(+ 'POWER_LEVEL', [ sensor_response ],+ )++ display_data = StatusDisplayData( status_data )++ self.assertEqual( display_data.svg_status_style.status_value, 'dim' )++ def test_power_level_mid_returns_dim_bucket(self):+ sensor_response = self._create_mock_sensor_response( '50' )+ status_data = self._create_entity_state_status_data(+ 'POWER_LEVEL', [ sensor_response ],+ )++ display_data = StatusDisplayData( status_data )++ self.assertEqual( display_data.svg_status_style.status_value, 'dim' )++ def test_power_level_high_returns_on_bucket_at_threshold(self):+ # 85 is the dim→on boundary.+ sensor_response = self._create_mock_sensor_response( '85' )+ status_data = self._create_entity_state_status_data(+ 'POWER_LEVEL', [ sensor_response ],+ )++ display_data = StatusDisplayData( status_data )++ self.assertEqual( display_data.svg_status_style.status_value, 'on' )++ def test_power_level_full_returns_on_bucket(self):+ sensor_response = self._create_mock_sensor_response( '100' )+ status_data = self._create_entity_state_status_data(+ 'POWER_LEVEL', [ sensor_response ],+ )++ display_data = StatusDisplayData( status_data )++ self.assertEqual( display_data.svg_status_style.status_value, 'on' )++ def test_power_level_non_numeric_falls_to_off_bucket(self):+ # Defensive: a malformed value shouldn't crash the+ # display path; treat as off (value=0).+ sensor_response = self._create_mock_sensor_response( 'garbage' )+ status_data = self._create_entity_state_status_data(+ 'POWER_LEVEL', [ sensor_response ],+ )++ display_data = StatusDisplayData( status_data )++ self.assertEqual( display_data.svg_status_style.status_value, 'off' )+# Edge Cases and Default Behavior Testsdef test_no_sensor_data_returns_default_style(self):diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.pyindex fb39eed0..7da4b417 100644--- a/src/hi/services/hass/hass_converter.py+++ b/src/hi/services/hass/hass_converter.py@@ -309,6 +309,14 @@ class HassConverter:'percentage': 'percentage', # 0-100},},+ (HassApi.FAN_DOMAIN, EntityStateType.POWER_LEVEL): {+ 'on_service': HassApi.TURN_ON_SERVICE,+ 'off_service': HassApi.TURN_OFF_SERVICE,+ 'set_service': HassApi.SET_PERCENTAGE_SERVICE,+ 'parameters': {+ 'percentage': 'percentage', # 0-100+ },+ },# Climate Domain Services(HassApi.CLIMATE_DOMAIN, EntityStateType.TEMPERATURE): {@@ -616,10 +624,10 @@ class HassConverter:# controller payloads so payload-shape changes# propagate to existing records.any_existing_substate = False- for substate_type in cls._substate_types_for_hass_state( hass_state ):+ for substate_spec in cls._substate_specs_for_hass_state( hass_state ):sub_key = cls._substate_integration_key(hass_state = hass_state,- entity_state_type = substate_type,+ suffix = substate_spec.suffix,)seen_state_integration_keys.add( sub_key )sub_controller = entiity_controllers.get( sub_key )@@ -629,7 +637,7 @@ class HassConverter:if sub_controller:sub_payload = cls._substate_integration_payload(hass_state = hass_state,- substate_type = substate_type,+ spec = substate_spec,)changed_fields = sub_controller.update_integration_payload( sub_payload )if changed_fields:@@ -752,10 +760,10 @@ class HassConverter:and ( hass_state.domain in ignore_light_state_prefixes )):continue- substate_types = cls._substate_types_for_hass_state( hass_state )- if EntityStateType.LIGHT_DIMMER in substate_types:- # Multi-substate light: ALL EntityStates are- # created as peer substates (no asymmetric+ substate_specs = cls._substate_specs_for_hass_state( hass_state )+ if substate_specs:+ # Multi-substate decomposition: ALL EntityStates+ # are created as peer substates (no asymmetric# bare-key parent). The Entity itself is still# identified by the bare HA entity_id; only the# EntityStates use suffixed integration_keys.@@ -772,10 +780,6 @@ class HassConverter:add_alarm_events = add_alarm_events,)prefix_to_entity_state[hass_state.domain] = entity_state- cls._create_substate_models(- entity = entity,- hass_state = hass_state,- )continuereturn@@ -788,14 +792,13 @@ class HassConverter:existing_sensors : Optional[ Dict ] = None,) -> List:"""Idempotent: creates a Controller (for controllable- substates) or a Sensor (for read-only ones) per- ``_SUBSTATE_SPECS`` for each substate implied by- ``hass_state`` that doesn't already exist. Pass the- entity's existing ``Controller``/``Sensor`` maps so- re-sync avoids re-creation. Returns the list of- newly-created models."""- substate_types = cls._substate_types_for_hass_state( hass_state )- if not substate_types:+ substates) or a Sensor (for read-only ones) for each+ substate implied by ``hass_state`` that doesn't already+ exist. Pass the entity's existing+ ``Controller``/``Sensor`` maps so re-sync avoids+ re-creation. Returns the list of newly-created models."""+ specs = cls._substate_specs_for_hass_state( hass_state )+ if not specs:return []if existing_controllers is None:existing_controllers = {}@@ -803,39 +806,38 @@ class HassConverter:existing_sensors = {}base_name = hass_state.friendly_name or entity.namecreated = []- for substate_type in substate_types:- spec = cls._SUBSTATE_SPECS[ substate_type ]+ for spec in specs:substate_integration_key = cls._substate_integration_key(hass_state = hass_state,- entity_state_type = substate_type,+ suffix = spec.suffix,)existing_for_kind = (existing_controllers if spec.is_controllable else existing_sensors)if substate_integration_key in existing_for_kind:continue- record_name = f'{base_name} {substate_type.label}'+ record_name = f'{base_name} {spec.display_label}'value_range_str = (json.dumps( spec.value_range ) if spec.value_range else '')if spec.is_controllable:controller = HiModelHelper.create_controller(entity = entity,- entity_state_type = substate_type,+ entity_state_type = spec.entity_state_type,name = record_name,integration_key = substate_integration_key,value_range_str = value_range_str,)controller.integration_payload = cls._substate_integration_payload(hass_state = hass_state,- substate_type = substate_type,+ spec = spec,)controller.save()created.append( controller )else:sensor = HiModelHelper.create_sensor(entity = entity,- entity_state_type = substate_type,+ entity_state_type = spec.entity_state_type,name = record_name,integration_key = substate_integration_key,value_range_str = value_range_str,@@ -847,10 +849,9 @@ class HassConverter:@classmethoddef _substate_integration_payload(cls,- hass_state : HassState,- substate_type : EntityStateType,+ hass_state : HassState,+ spec : '_SubstateSpec',) -> dict:- spec = cls._SUBSTATE_SPECS[ substate_type ]return {'domain': hass_state.domain,'is_controllable': spec.is_controllable,@@ -956,6 +957,15 @@ class HassConverter:if domain == HassApi.COVER_DOMAIN and cls._has_position_capability( hass_state ):return EntityStateType.OPEN_CLOSE_POSITION+ # Speed-aware override for fans: a fan that reports+ # ``percentage`` (and only ``percentage`` — not the+ # multi-feature attributes that trigger substate+ # decomposition) is a single continuous slider.+ if ( domain == HassApi.FAN_DOMAIN+ and cls._has_percentage_capability( hass_state )+ and not cls._fan_has_multi_features( hass_state ) ):+ return EntityStateType.POWER_LEVEL+# Try exact match firstmapping_key = (domain, device_class, has_brightness)if mapping_key in cls.HASS_STATE_TO_ENTITY_STATE_TYPE_MAPPING:@@ -1015,39 +1025,28 @@ class HassConverter:# Per-substate metadata. The suffix is appended to the parent# HA entity_id to form the substate's integration_key (parent# keeps the bare entity_id; each substate gets its own- # suffix). ``is_controllable`` selects Sensor-only vs+ # suffix). ``entity_state_type`` selects the HI controller+ # affordance. ``is_controllable`` selects Sensor-only vs# Sensor+Controller creation. ``value_range`` is stored on# the EntityState's value_range_str so client widgets and# any server-side validation share one source of truth;# ``None`` for substates whose value space comes from their# EntityStateType's enum choices instead (e.g., COLOR_MODE).+ # ``label`` overrides ``entity_state_type.label`` when the+ # generic type label is too generic for the per-domain+ # context (e.g., "Speed" for a fan POWER_LEVEL substate+ # rather than the generic "Power Level").@dataclass(frozen=True)class _SubstateSpec:- suffix : str- is_controllable : bool- value_range : Optional[Dict] = None-- _SUBSTATE_SPECS = {- EntityStateType.LIGHT_DIMMER: _SubstateSpec(- suffix='brightness', is_controllable=True,- value_range={ 'min': 0, 'max': 100 },- ),- EntityStateType.HUE: _SubstateSpec(- suffix='hue', is_controllable=True,- value_range={ 'min': 0, 'max': 360 },- ),- EntityStateType.SATURATION: _SubstateSpec(- suffix='saturation', is_controllable=True,- value_range={ 'min': 0, 'max': 100 },- ),- EntityStateType.COLOR_TEMPERATURE: _SubstateSpec(- suffix='color_temp', is_controllable=True,- value_range={ 'min': 2000, 'max': 6500 },- ),- EntityStateType.COLOR_MODE: _SubstateSpec(- suffix='color_mode', is_controllable=False,- ),- }+ suffix : str+ entity_state_type : EntityStateType+ is_controllable : bool+ value_range : Optional[Dict] = None+ label : Optional[str] = None++ @property+ def display_label(self) -> str:+ return self.label if self.label else self.entity_state_type.label# Translation of HA's color_mode attribute values to HI's# COLOR_MODE EntityStateValues. HA's ``null`` and explicit@@ -1069,22 +1068,35 @@ class HassConverter:}@classmethod- def _substate_types_for_hass_state(- cls, hass_state: HassState ) -> List[ EntityStateType ]:- """Return the color-related EntityStateTypes that a single- HA ``light.x`` state implies via its ``supported_color_modes``- declaration. A color bulb that supports HS (or RGB / XY,- which are alternate representations of HS chromaticity)- contributes ``HUE`` and ``SATURATION``; one that supports- ``color_temp`` contributes ``COLOR_TEMPERATURE``. Both- sets of sub-states can be present simultaneously when- the bulb supports both modes — HA's ``color_mode``- attribute then selects which is currently authoritative,- but HI presents both controls and lets the operator drive- whichever they want.+ def _substate_specs_for_hass_state(+ cls, hass_state: HassState ) -> List[ '_SubstateSpec' ]:+ """Return the substate specs for a HA state that decomposes+ into multiple HI EntityStates, or an empty list when the+ state maps to a single bare-key EntityState. Each domain+ owns its own decomposition rules — what substates exist,+ which are controllable, what their value ranges are — and+ composes specs per-instance based on what the live+ ``hass_state`` actually reports."""- if hass_state.domain != HassApi.LIGHT_DOMAIN:- return []+ if hass_state.domain == HassApi.LIGHT_DOMAIN:+ return cls._light_substate_specs( hass_state )+ if hass_state.domain == HassApi.FAN_DOMAIN:+ return cls._fan_substate_specs( hass_state )+ return []++ @classmethod+ def _light_substate_specs(+ cls, hass_state: HassState ) -> List[ '_SubstateSpec' ]:+ """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)+ contributes hue and saturation; one supporting ``color_temp``+ contributes color temperature. Both can be present+ simultaneously when the bulb supports both modes — HA's+ ``color_mode`` attribute selects which is currently+ authoritative, but HI presents both controls. When any color+ axis is present, brightness becomes a peer substate too;+ brightness-only bulbs keep the bare-key single-state model."""supported = hass_state.attributes.get( 'supported_color_modes' )if not isinstance( supported, list ):return []@@ -1092,47 +1104,121 @@ class HassConverter:chromatic_present = any( m in cls._CHROMATIC_COLOR_MODES for m in supported )color_temp_present = 'color_temp' in supported- substate_types = []- # When any color substate is present, brightness becomes- # a peer substate too (no asymmetric "primary state").- # Brightness-only bulbs keep the bare-key model: single- # state, no decomposition needed.+ specs = []if chromatic_present or color_temp_present:- substate_types.append( EntityStateType.LIGHT_DIMMER )+ specs.append( cls._SubstateSpec(+ suffix = 'brightness',+ entity_state_type = EntityStateType.LIGHT_DIMMER,+ is_controllable = True,+ value_range = { 'min': 0, 'max': 100 },+ ))if chromatic_present:- substate_types.append( EntityStateType.HUE )- substate_types.append( EntityStateType.SATURATION )+ specs.append( cls._SubstateSpec(+ suffix = 'hue',+ entity_state_type = EntityStateType.HUE,+ is_controllable = True,+ value_range = { 'min': 0, 'max': 360 },+ ))+ specs.append( cls._SubstateSpec(+ suffix = 'saturation',+ entity_state_type = EntityStateType.SATURATION,+ is_controllable = True,+ value_range = { 'min': 0, 'max': 100 },+ ))if color_temp_present:- substate_types.append( EntityStateType.COLOR_TEMPERATURE )+ specs.append( cls._SubstateSpec(+ suffix = 'color_temp',+ entity_state_type = EntityStateType.COLOR_TEMPERATURE,+ is_controllable = True,+ value_range = { 'min': 2000, 'max': 6500 },+ ))# COLOR_MODE only adds information when there's actual# mode-switching to track. A bulb with a single supported- # mode (e.g., ``['brightness']``) has a constant value;- # skip it.+ # mode has a constant value; skip it.if len( supported ) > 1:- substate_types.append( EntityStateType.COLOR_MODE )- return substate_types+ specs.append( cls._SubstateSpec(+ suffix = 'color_mode',+ entity_state_type = EntityStateType.COLOR_MODE,+ is_controllable = False,+ ))+ return specs++ @classmethod+ def _fan_substate_specs(+ cls, hass_state: HassState ) -> List[ '_SubstateSpec' ]:+ """Substates implied by a HA ``fan.x`` state when it reports+ any of the multi-axis features (oscillating / direction /+ preset_modes). Speed becomes a peer ``~speed`` POWER_LEVEL+ substate alongside the others; speed-only fans keep the+ bare-key single-state model. Per-fan ``preset_modes`` list+ becomes the value range of the preset substate."""+ if not cls._fan_has_multi_features( hass_state ):+ return []+ attrs = hass_state.attributes+ specs = []+ if cls._has_percentage_capability( hass_state ):+ specs.append( cls._SubstateSpec(+ suffix = 'speed',+ entity_state_type = EntityStateType.POWER_LEVEL,+ is_controllable = True,+ value_range = { 'min': 0, 'max': 100 },+ label = 'Speed',+ ))+ if 'oscillating' in attrs:+ specs.append( cls._SubstateSpec(+ suffix = 'oscillating',+ entity_state_type = EntityStateType.ON_OFF,+ is_controllable = True,+ label = 'Oscillation',+ ))+ if 'direction' in attrs:+ specs.append( cls._SubstateSpec(+ suffix = 'direction',+ entity_state_type = EntityStateType.DISCRETE,+ is_controllable = True,+ value_range = { 'forward': 'Forward', 'reverse': 'Reverse' },+ label = 'Direction',+ ))+ preset_modes = attrs.get( 'preset_modes' )+ if isinstance( preset_modes, list ) and preset_modes:+ specs.append( cls._SubstateSpec(+ suffix = 'preset',+ entity_state_type = EntityStateType.DISCRETE,+ is_controllable = True,+ value_range = { mode: mode for mode in preset_modes },+ label = 'Preset',+ ))+ return specs@classmethoddef _extract_substate_value(cls,- hass_state : HassState,- entity_state_type : EntityStateType,+ hass_state : HassState,+ suffix : str,) -> Optional[ str ]:- """Pull the value for a single substate out of a HA- light's state. Returns whatever HA reports — we don't- filter by ``color_mode``. HA may continue to report- ``hs_color`` while in color_temp mode (or vice versa);- that value is still the bulb's last-known chromaticity and- relaying it as the HUE/SATURATION HI state is correct.- Returns ``None`` only when the attribute is absent (e.g.,- HA omits color attributes when the light is off); callers- skip ``None``-valued sub-states from the response map."""- attrs = hass_state.attributes+ """Pull the value for a single substate out of a HA state,+ dispatching per-domain. Returns ``None`` when the relevant+ attribute is absent — callers skip ``None``-valued substates+ from the response map."""+ if hass_state.domain == HassApi.LIGHT_DOMAIN:+ return cls._light_substate_value( hass_state, suffix )+ if hass_state.domain == HassApi.FAN_DOMAIN:+ return cls._fan_substate_value( hass_state, suffix )+ return None- if entity_state_type == EntityStateType.LIGHT_DIMMER:+ @classmethod+ def _light_substate_value(+ cls, hass_state : HassState, suffix : str ) -> Optional[ str ]:+ """Light-domain substate values. Returns whatever HA+ reports; we don't filter by ``color_mode``. HA may+ continue to report ``hs_color`` while in color_temp mode+ (or vice versa); that value is still the bulb's+ last-known chromaticity and relaying it as the+ hue/saturation HI state is correct."""+ attrs = hass_state.attributes+ if suffix == 'brightness':return cls._dimmer_brightness_value( hass_state )-- if entity_state_type == EntityStateType.HUE:+ if suffix == 'hue':hs = attrs.get( 'hs_color' )if isinstance( hs, list ) and len( hs ) >= 1:try:@@ -1140,8 +1226,7 @@ class HassConverter:except ( TypeError, ValueError ):return Nonereturn None-- if entity_state_type == EntityStateType.SATURATION:+ if suffix == 'saturation':hs = attrs.get( 'hs_color' )if isinstance( hs, list ) and len( hs ) >= 2:try:@@ -1149,8 +1234,7 @@ class HassConverter:except ( TypeError, ValueError ):return Nonereturn None-- if entity_state_type == EntityStateType.COLOR_TEMPERATURE:+ if suffix == 'color_temp':kelvin = attrs.get( 'color_temp_kelvin' )if kelvin is not None:try:@@ -1158,8 +1242,7 @@ class HassConverter:except ( TypeError, ValueError ):return Nonereturn None-- if entity_state_type == EntityStateType.COLOR_MODE:+ if suffix == 'color_mode':if 'color_mode' not in attrs:return Noneha_value = attrs[ 'color_mode' ]@@ -1167,22 +1250,45 @@ class HassConverter:ha_value, EntityStateValue.COLOR_MODE_UNKNOWN,)return str( hi_value )+ return None+ @classmethod+ def _fan_substate_value(+ cls, hass_state : HassState, suffix : str ) -> Optional[ str ]:+ """Fan-domain substate values."""+ attrs = hass_state.attributes+ if suffix == 'speed':+ raw = attrs.get( 'percentage' )+ if raw is None:+ return None+ try:+ return str( int( float( raw ) ) )+ except ( TypeError, ValueError ):+ return None+ if suffix == 'oscillating':+ osc = attrs.get( 'oscillating' )+ if osc is None:+ return None+ return str( EntityStateValue.ON ) if osc else str( EntityStateValue.OFF )+ if suffix == 'direction':+ return attrs.get( 'direction' )+ if suffix == 'preset':+ return attrs.get( 'preset_mode' )return None@classmethoddef _substate_integration_key(cls,- hass_state : HassState,- entity_state_type : EntityStateType,+ hass_state : HassState,+ suffix : str,) -> IntegrationKey:- """Build the suffix-extended IntegrationKey for a color- sub-state. The suffix lets the controller dispatch (and- sensor-update routing) tell which dimension a given key- targets without parsing supported_color_modes again."""+ """Build the suffix-extended IntegrationKey for a substate.+ The suffix lets the controller dispatch (and sensor-update+ routing) tell which dimension a given key targets without+ re-parsing the parent state's capability declaration."""return cls._substate_integration_key_for_suffix(parent_entity_id = hass_state.entity_id,- suffix = cls._SUBSTATE_SPECS[ entity_state_type ].suffix,+ suffix = suffix,)@classmethod@@ -1229,6 +1335,26 @@ class HassConverter:door)."""return hass_state.attributes.get( 'current_position' ) is not None+ @classmethod+ def _has_percentage_capability( cls, hass_state: HassState ) -> bool:+ """True when an HA fan state reports ``percentage``, meaning+ the fan exposes a continuous speed dimension."""+ return hass_state.attributes.get( 'percentage' ) is not None++ @classmethod+ def _fan_has_multi_features( cls, hass_state: HassState ) -> bool:+ """True when an HA fan state reports any of the multi-axis+ capabilities that trigger substate decomposition+ (oscillating, direction, preset_modes). Detection is by+ attribute presence; HA reports these only when the fan+ actually supports them."""+ attrs = hass_state.attributes+ return (+ 'oscillating' in attrs+ or 'direction' in attrs+ or 'preset_modes' in attrs+ )+@classmethoddef _is_controllable_domain_and_type( cls, domain: str, entity_state_type: EntityStateType ) -> bool:"""Check if this domain+type combination is controllable"""@@ -1268,6 +1394,14 @@ class HassConverter:integration_key = integration_key,name = name,)+ elif entity_state_type == EntityStateType.POWER_LEVEL:+ # Caller decides per-domain label by passing ``name``;+ # for a fan, it lands as e.g. "Zoo Fan Speed".+ controller = HiModelHelper.create_power_level_controller(+ entity = entity,+ integration_key = integration_key,+ name = name,+ )else:# Fallback - shouldn't happen for controllable typeslogger.warning( f'Unknown controllable EntityStateType: {entity_state_type}' )@@ -1677,6 +1811,8 @@ class HassConverter:return cls._lock_to_sensor_value_map( hass_state )if domain == HassApi.COVER_DOMAIN:return cls._cover_to_sensor_value_map( hass_state )+ if domain == HassApi.FAN_DOMAIN:+ return cls._fan_to_sensor_value_map( hass_state )return cls._passthrough_to_sensor_value_map( hass_state )@classmethod@@ -1696,18 +1832,19 @@ 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_types = cls._substate_types_for_hass_state( hass_state )- if EntityStateType.LIGHT_DIMMER not in substate_types:+ substate_specs = cls._substate_specs_for_hass_state( hass_state )+ if not substate_specs:brightness_value = cls._dimmer_brightness_value( hass_state )if brightness_value:result[ cls.hass_state_to_integration_key( hass_state ) ] = brightness_value- for substate_type in substate_types:- value = cls._extract_substate_value( hass_state, substate_type )+ return result+ for spec in substate_specs:+ value = cls._extract_substate_value( hass_state, spec.suffix )if value is None:continuesubstate_key = cls._substate_integration_key(hass_state = hass_state,- entity_state_type = substate_type,+ suffix = spec.suffix,)result[ substate_key ] = valuecontinue@@ -1823,6 +1960,38 @@ class HassConverter:return { cls.hass_state_to_integration_key( hass_state ) : str( position ) }return cls._passthrough_to_sensor_value_map( hass_state )+ @classmethod+ def _fan_to_sensor_value_map(+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:+ """Fan domain: multi-feature fans decompose into substates+ (speed/oscillating/direction/preset) — each substate's+ value lands at its suffix-keyed integration_key. Speed-only+ fans get a single bare-key POWER_LEVEL value with the+ numeric percentage. Fans without percentage stay ON_OFF+ and pass HA's discrete ``'on'``/``'off'`` state through."""+ substate_specs = cls._substate_specs_for_hass_state( hass_state )+ if substate_specs:+ result : Dict[ IntegrationKey, str ] = {}+ for spec in substate_specs:+ value = cls._extract_substate_value( hass_state, spec.suffix )+ if value is None:+ continue+ substate_key = cls._substate_integration_key(+ hass_state = hass_state,+ suffix = spec.suffix,+ )+ result[ substate_key ] = value+ continue+ return result+ raw_percentage = hass_state.attributes.get( 'percentage' )+ if raw_percentage is None:+ return cls._passthrough_to_sensor_value_map( hass_state )+ try:+ percentage = int( float( raw_percentage ) )+ except ( TypeError, ValueError ):+ return {}+ return { cls.hass_state_to_integration_key( hass_state ) : str( percentage ) }+@classmethoddef _passthrough_to_sensor_value_map(cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:@@ -1996,6 +2165,41 @@ class HassConverter:saturation = sat,)+ if substate == 'speed':+ try:+ numeric_value = cls.to_ha_numeric_parameter_value( hi_control_value )+ except ( ValueError, TypeError ):+ raise ValueError(+ f'Invalid fan speed value: {hi_control_value}'+ )+ return HassServiceComposer.for_percentage(+ domain = domain,+ hass_substate_id = parent_entity_id,+ percentage = numeric_value,+ domain_payload = { 'set_service': HassApi.SET_PERCENTAGE_SERVICE },+ )++ if substate == 'oscillating':+ return HassServiceComposer.for_oscillating(+ domain = domain,+ hass_substate_id = parent_entity_id,+ oscillating = cls.to_ha_on_off_intent( hi_control_value ) == ControlIntent.ON,+ )++ if substate == 'direction':+ return HassServiceComposer.for_direction(+ domain = domain,+ hass_substate_id = parent_entity_id,+ direction = hi_control_value,+ )++ if substate == 'preset':+ return HassServiceComposer.for_preset_mode(+ domain = domain,+ hass_substate_id = parent_entity_id,+ preset_mode = hi_control_value,+ )+raise ValueError( f'Unknown substate: {substate}' )@classmethoddiff --git a/src/hi/services/hass/hass_models.py b/src/hi/services/hass/hass_models.pyindex 210e64cb..66b8cb99 100644--- a/src/hi/services/hass/hass_models.py+++ b/src/hi/services/hass/hass_models.py@@ -46,6 +46,9 @@ class HassApi:MEDIA_STOP_SERVICE = 'media_stop'VOLUME_SET_SERVICE = 'volume_set'SET_PERCENTAGE_SERVICE = 'set_percentage'+ OSCILLATE_SERVICE = 'oscillate'+ SET_DIRECTION_SERVICE = 'set_direction'+ SET_PRESET_MODE_SERVICE = 'set_preset_mode'# Legacy aliases for backward compatibility (remove after migration)AUTOMATION_ID_PREFIX = AUTOMATION_DOMAINdiff --git a/src/hi/services/hass/hass_service_composer.py b/src/hi/services/hass/hass_service_composer.pyindex aac8eaaa..c723b78d 100644--- a/src/hi/services/hass/hass_service_composer.py+++ b/src/hi/services/hass/hass_service_composer.py@@ -182,6 +182,13 @@ class HassServiceComposer:position = numeric_value,domain_payload = domain_payload,)+ if 'percentage' in parameters:+ return cls.for_percentage(+ domain = domain,+ hass_substate_id = hass_substate_id,+ percentage = numeric_value,+ domain_payload = domain_payload,+ )if domain_payload.get( 'set_service' ):service = domain_payload[ 'set_service' ]return HassServiceCall(@@ -275,6 +282,75 @@ class HassServiceComposer:service_data = { 'position': position_pct },)+ @classmethod+ def for_percentage(+ cls,+ domain : str,+ hass_substate_id : str,+ percentage : float,+ domain_payload : dict,+ ) -> HassServiceCall:+ percentage_int = int( percentage )+ if not ( 0 <= percentage_int <= 100 ):+ raise ValueError(+ f'Invalid percentage value: {percentage} (must be 0-100)'+ )+ service = domain_payload.get( 'set_service', HassApi.SET_PERCENTAGE_SERVICE )+ return HassServiceCall(+ domain = domain,+ service = service,+ hass_entity_id = hass_substate_id,+ service_data = { 'percentage': percentage_int },+ )++ @classmethod+ def for_oscillating(+ cls,+ domain : str,+ hass_substate_id : str,+ oscillating : bool,+ ) -> HassServiceCall:+ return HassServiceCall(+ domain = domain,+ service = HassApi.OSCILLATE_SERVICE,+ hass_entity_id = hass_substate_id,+ service_data = { 'oscillating': bool( oscillating ) },+ )++ @classmethod+ def for_direction(+ cls,+ domain : str,+ hass_substate_id : str,+ direction : str,+ ) -> HassServiceCall:+ if direction not in ( 'forward', 'reverse' ):+ raise ValueError(+ f'Invalid fan direction: {direction} (must be forward/reverse)'+ )+ return HassServiceCall(+ domain = domain,+ service = HassApi.SET_DIRECTION_SERVICE,+ hass_entity_id = hass_substate_id,+ service_data = { 'direction': direction },+ )++ @classmethod+ def for_preset_mode(+ cls,+ domain : str,+ hass_substate_id : str,+ preset_mode : str,+ ) -> HassServiceCall:+ if not preset_mode:+ raise ValueError( 'preset_mode must be a non-empty string' )+ return HassServiceCall(+ domain = domain,+ service = HassApi.SET_PRESET_MODE_SERVICE,+ hass_entity_id = hass_substate_id,+ service_data = { 'preset_mode': preset_mode },+ )+@classmethoddef for_color_temp(cls,diff --git a/src/hi/services/hass/tests/test_hass_converter_fan.py b/src/hi/services/hass/tests/test_hass_converter_fan.pynew file mode 100644index 00000000..75691e02--- /dev/null+++ b/src/hi/services/hass/tests/test_hass_converter_fan.py@@ -0,0 +1,391 @@+import logging++from django.test import TestCase++from hi.apps.control.models import Controller+from hi.apps.entity.enums import EntityStateType, EntityStateValue, EntityType+from hi.apps.entity.models import EntityState+from hi.services.hass.hass_converter import HassConverter+from hi.services.hass.hass_models import HassApi, HassDevice, HassServiceCall++logging.disable(logging.CRITICAL)+++def _make_fan_api_dict(+ entity_id = 'fan.example',+ state = 'on',+ percentage = None,+ percentage_step = None,+ oscillating = None,+ direction = None,+ preset_mode = None,+ preset_modes = None,+ friendly_name = None ):+ attributes = {}+ if friendly_name:+ attributes[ 'friendly_name' ] = friendly_name+ if percentage is not None:+ attributes[ 'percentage' ] = percentage+ if percentage_step is not None:+ attributes[ 'percentage_step' ] = percentage_step+ if oscillating is not None:+ attributes[ 'oscillating' ] = oscillating+ if direction is not None:+ attributes[ 'direction' ] = direction+ if preset_mode is not None:+ attributes[ 'preset_mode' ] = preset_mode+ if preset_modes is not None:+ attributes[ 'preset_modes' ] = preset_modes+ return {+ 'entity_id': entity_id,+ 'state': state,+ 'attributes': attributes,+ 'last_changed': '2026-01-01T00:00:00+00:00',+ 'last_reported': '2026-01-01T00:00:00+00:00',+ 'last_updated': '2026-01-01T00:00:00+00:00',+ 'context': { 'id': 'ctx', 'parent_id': None, 'user_id': None },+ }+++def _make_fan_hass_state( **kwargs ):+ return HassConverter.create_hass_state( _make_fan_api_dict( **kwargs ) )+++def _build_fan_device( device_id, **kwargs ):+ api_dict = _make_fan_api_dict( entity_id=f'fan.{device_id}', **kwargs )+ hass_state = HassConverter.create_hass_state( api_dict )+ device = HassDevice( device_id=device_id )+ device.add_state( hass_state )+ return device+++class TestFanEntityStateTypeMapping(TestCase):+ """The fan domain has three EntityStateType destinations+ depending on what the live state reports: ON_OFF (no+ percentage), POWER_LEVEL (percentage-only single state), or+ substate decomposition (percentage + any of oscillating /+ direction / preset_modes)."""++ def test_no_percentage_routes_to_on_off(self):+ hass_state = _make_fan_hass_state()+ result = HassConverter._determine_entity_state_type_from_mapping( hass_state )+ self.assertEqual( result, EntityStateType.ON_OFF )++ def test_percentage_only_routes_to_power_level(self):+ hass_state = _make_fan_hass_state( percentage=50, percentage_step=25 )+ result = HassConverter._determine_entity_state_type_from_mapping( hass_state )+ self.assertEqual( result, EntityStateType.POWER_LEVEL )++ def test_oscillating_attribute_disables_power_level(self):+ # Multi-feature fans go through substate decomposition,+ # not the single-state POWER_LEVEL path. The mapping+ # function returns ON_OFF (the table fallback); the+ # substate-creation flow takes over before that mapping+ # gets used as a primary state type.+ hass_state = _make_fan_hass_state(+ percentage=50, oscillating=False,+ )+ result = HassConverter._determine_entity_state_type_from_mapping( hass_state )+ self.assertEqual( result, EntityStateType.ON_OFF )++ def test_direction_attribute_disables_power_level(self):+ hass_state = _make_fan_hass_state(+ percentage=50, direction='forward',+ )+ result = HassConverter._determine_entity_state_type_from_mapping( hass_state )+ self.assertEqual( result, EntityStateType.ON_OFF )++ def test_preset_modes_attribute_disables_power_level(self):+ hass_state = _make_fan_hass_state(+ percentage=50, preset_modes=[ 'auto', 'sleep' ],+ )+ result = HassConverter._determine_entity_state_type_from_mapping( hass_state )+ self.assertEqual( result, EntityStateType.ON_OFF )+++class TestFanSubstateSpecs(TestCase):+ """Multi-feature fans decompose into peer substates. The+ spec list reflects what the live state reports — a fan+ without ``direction`` doesn't get a direction substate."""++ 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 )+ self.assertEqual( specs, [] )++ def test_full_multi_feature_fan_has_four_substates(self):+ hass_state = _make_fan_hass_state(+ percentage=50, oscillating=True,+ direction='forward', preset_modes=[ 'auto', 'sleep' ],+ )+ specs = HassConverter._substate_specs_for_hass_state( hass_state )+ suffixes = [ s.suffix for s in specs ]+ self.assertEqual( suffixes, [ 'speed', 'oscillating', 'direction', 'preset' ] )++ def test_oscillating_only_fan_has_oscillating_substate_no_speed(self):+ # 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 )+ suffixes = [ s.suffix for s in specs ]+ self.assertEqual( suffixes, [ 'oscillating' ] )++ def test_speed_substate_has_power_level_type_and_speed_label(self):+ hass_state = _make_fan_hass_state(+ percentage=50, oscillating=True,+ )+ specs = HassConverter._substate_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' )+ self.assertTrue( speed.is_controllable )++ def test_preset_substate_value_range_from_preset_modes(self):+ hass_state = _make_fan_hass_state(+ preset_modes=[ 'auto', 'sleep', 'eco' ],+ )+ specs = HassConverter._substate_specs_for_hass_state( hass_state )+ preset = next( s for s in specs if s.suffix == 'preset' )+ self.assertEqual(+ preset.value_range,+ { 'auto': 'auto', 'sleep': 'sleep', 'eco': 'eco' },+ )+++class TestFanInboundStateTranslation(TestCase):++ def test_speed_only_fan_emits_numeric_percentage_at_bare_key(self):+ hass_state = _make_fan_hass_state( percentage=42 )+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )+ self.assertEqual( len( value_map ), 1 )+ key, value = next( iter( value_map.items() ) )+ self.assertEqual( key.integration_name, hass_state.entity_id )+ self.assertEqual( value, '42' )++ def test_no_percentage_fan_passes_state_through(self):+ hass_state = _make_fan_hass_state( state='on' )+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )+ self.assertEqual( list( value_map.values() )[ 0 ], 'on' )++ def test_multi_feature_fan_decomposes_into_suffixed_keys(self):+ hass_state = _make_fan_hass_state(+ entity_id='fan.living_room',+ percentage=60, oscillating=True,+ direction='reverse', preset_modes=[ 'auto', 'sleep', 'eco' ],+ preset_mode='sleep',+ )+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )+ names_to_values = {+ key.integration_name: value for key, value in value_map.items()+ }+ self.assertEqual( names_to_values, {+ 'fan.living_room~speed': '60',+ 'fan.living_room~oscillating': str( EntityStateValue.ON ),+ 'fan.living_room~direction': 'reverse',+ 'fan.living_room~preset': 'sleep',+ } )++ def test_oscillating_false_emits_canonical_off(self):+ hass_state = _make_fan_hass_state(+ percentage=50, oscillating=False,+ )+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )+ names_to_values = {+ key.integration_name: value for key, value in value_map.items()+ }+ self.assertEqual(+ names_to_values[ 'fan.example~oscillating' ],+ str( EntityStateValue.OFF ),+ )++ def test_non_numeric_percentage_returns_empty(self):+ hass_state = _make_fan_hass_state( percentage='garbage' )+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )+ self.assertEqual( value_map, {} )+++class TestFanImport(TestCase):+ """End-to-end import of fan devices: the right+ EntityStateType(s), controller(s), and outbound payloads+ land on the imported models."""++ def test_speed_only_fan_imports_with_single_power_level_state(self):+ device = _build_fan_device(+ 'speedy', percentage=40, percentage_step=25,+ )+ entity = HassConverter.create_models_for_hass_device(+ hass_device=device,+ add_alarm_events=False,+ )+ self.assertEqual( entity.entity_type, EntityType.CEILING_FAN )++ states = list( EntityState.objects.filter( entity=entity ) )+ self.assertEqual( len( states ), 1 )+ self.assertEqual( states[ 0 ].entity_state_type, EntityStateType.POWER_LEVEL )++ controllers = list( Controller.objects.filter( entity_state=states[ 0 ] ) )+ self.assertEqual( len( controllers ), 1 )+ self.assertEqual(+ controllers[ 0 ].integration_payload.get( 'set_service' ),+ HassApi.SET_PERCENTAGE_SERVICE,+ )++ def test_multi_feature_fan_imports_with_four_substates(self):+ device = _build_fan_device(+ 'smart_fan',+ percentage=60, oscillating=True,+ direction='forward',+ preset_modes=[ 'auto', 'sleep', 'eco' ],+ preset_mode='auto',+ )+ entity = HassConverter.create_models_for_hass_device(+ hass_device=device,+ add_alarm_events=False,+ )+ self.assertEqual( entity.entity_type, EntityType.CEILING_FAN )++ states = list( EntityState.objects.filter( entity=entity ) )+ self.assertEqual( len( states ), 4 )++ controllers_by_suffix = {}+ for ctrl in Controller.objects.filter( entity_state__entity=entity ):+ payload = ctrl.integration_payload+ controllers_by_suffix[ payload.get( 'substate' ) ] = ctrl++ self.assertEqual(+ set( controllers_by_suffix.keys() ),+ { 'speed', 'oscillating', 'direction', 'preset' },+ )+ # Each substate's payload carries domain + parent_entity_id+ # so the outbound dispatcher can compose the right service call.+ for suffix, ctrl in controllers_by_suffix.items():+ payload = ctrl.integration_payload+ self.assertEqual( payload.get( 'domain' ), HassApi.FAN_DOMAIN )+ self.assertEqual( payload.get( 'parent_entity_id' ), 'fan.smart_fan' )++ def test_multi_feature_fan_substate_state_types(self):+ device = _build_fan_device(+ 'fan_b', percentage=50, oscillating=True,+ direction='reverse',+ preset_modes=[ 'auto' ],+ )+ entity = HassConverter.create_models_for_hass_device(+ hass_device=device,+ add_alarm_events=False,+ )+ # Index by the integration-payload's substate suffix (the+ # stable contract) rather than by parsing the EntityState's+ # display label, which is presentational and could change.+ types_by_suffix = {+ ctrl.integration_payload.get( 'substate' ): ctrl.entity_state.entity_state_type+ for ctrl in Controller.objects.filter( entity_state__entity=entity )+ }+ self.assertEqual( types_by_suffix[ 'speed' ], EntityStateType.POWER_LEVEL )+ self.assertEqual( types_by_suffix[ 'oscillating' ], EntityStateType.ON_OFF )+ self.assertEqual( types_by_suffix[ 'direction' ], EntityStateType.DISCRETE )+ self.assertEqual( types_by_suffix[ 'preset' ], EntityStateType.DISCRETE )+++class TestFanOutboundDispatchSpeedOnly(TestCase):+ """Single-state speed-only fans take a different outbound+ path than multi-feature fans: their domain_payload has no+ ``substate`` field, so dispatch flows through+ ``_payload_driven_service_call`` to the+ ``HassServiceComposer.for_numeric_parameter`` percentage+ branch. This is distinct from the substate-dispatch path+ exercised by ``TestFanOutboundDispatch``."""++ def test_numeric_routes_to_set_percentage(self):+ payload = {+ 'domain': HassApi.FAN_DOMAIN,+ 'is_controllable': True,+ 'on_service': HassApi.TURN_ON_SERVICE,+ 'off_service': HassApi.TURN_OFF_SERVICE,+ 'set_service': HassApi.SET_PERCENTAGE_SERVICE,+ 'parameters': { 'percentage': 'percentage' },+ }+ call = HassConverter.hi_value_to_hass_service_call(+ hass_substate_id='fan.zoo_fan',+ hi_control_value='42',+ domain_payload=payload,+ )+ self.assertEqual( call, HassServiceCall(+ domain=HassApi.FAN_DOMAIN,+ service=HassApi.SET_PERCENTAGE_SERVICE,+ hass_entity_id='fan.zoo_fan',+ service_data={ 'percentage': 42 },+ ))+++class TestFanOutboundDispatch(TestCase):+ """Each fan substate routes to the matching HA service via+ ``hi_value_to_hass_service_call``."""++ def _substate_payload( self, suffix ):+ return {+ 'domain': HassApi.FAN_DOMAIN,+ 'is_controllable': True,+ 'substate': suffix,+ 'parent_entity_id': 'fan.smart_fan',+ }++ def test_speed_routes_to_set_percentage(self):+ call = HassConverter.hi_value_to_hass_service_call(+ hass_substate_id='fan.smart_fan~speed',+ hi_control_value='75',+ domain_payload=self._substate_payload( 'speed' ),+ )+ self.assertEqual( call, HassServiceCall(+ domain=HassApi.FAN_DOMAIN,+ service=HassApi.SET_PERCENTAGE_SERVICE,+ hass_entity_id='fan.smart_fan',+ service_data={ 'percentage': 75 },+ ))++ def test_oscillating_on_routes_to_oscillate_true(self):+ call = HassConverter.hi_value_to_hass_service_call(+ hass_substate_id='fan.smart_fan~oscillating',+ hi_control_value='on',+ domain_payload=self._substate_payload( 'oscillating' ),+ )+ self.assertEqual( call, HassServiceCall(+ domain=HassApi.FAN_DOMAIN,+ service=HassApi.OSCILLATE_SERVICE,+ hass_entity_id='fan.smart_fan',+ service_data={ 'oscillating': True },+ ))++ def test_oscillating_off_routes_to_oscillate_false(self):+ call = HassConverter.hi_value_to_hass_service_call(+ hass_substate_id='fan.smart_fan~oscillating',+ hi_control_value='off',+ domain_payload=self._substate_payload( 'oscillating' ),+ )+ self.assertEqual( call.service_data, { 'oscillating': False } )++ def test_direction_routes_to_set_direction(self):+ call = HassConverter.hi_value_to_hass_service_call(+ hass_substate_id='fan.smart_fan~direction',+ hi_control_value='reverse',+ domain_payload=self._substate_payload( 'direction' ),+ )+ self.assertEqual( call, HassServiceCall(+ domain=HassApi.FAN_DOMAIN,+ service=HassApi.SET_DIRECTION_SERVICE,+ hass_entity_id='fan.smart_fan',+ service_data={ 'direction': 'reverse' },+ ))++ def test_preset_routes_to_set_preset_mode(self):+ call = HassConverter.hi_value_to_hass_service_call(+ hass_substate_id='fan.smart_fan~preset',+ hi_control_value='sleep',+ domain_payload=self._substate_payload( 'preset' ),+ )+ self.assertEqual( call, HassServiceCall(+ domain=HassApi.FAN_DOMAIN,+ service=HassApi.SET_PRESET_MODE_SERVICE,+ hass_entity_id='fan.smart_fan',+ service_data={ 'preset_mode': 'sleep' },+ ))diff --git a/src/hi/services/hass/tests/test_hass_service_composer.py b/src/hi/services/hass/tests/test_hass_service_composer.pyindex 3260504b..177708ae 100644--- a/src/hi/services/hass/tests/test_hass_service_composer.py+++ b/src/hi/services/hass/tests/test_hass_service_composer.py@@ -317,3 +317,60 @@ class TestForColor(TestCase):self.assertEqual(result.service_data, {'hs_color': [180.0, 75.0]})self.assertEqual(result.service, 'turn_on')self.assertEqual(result.hass_entity_id, 'light.x')+++class TestFanAxisComposers(TestCase):++ def test_for_percentage_valid(self):+ result = HassServiceComposer.for_percentage(+ domain='fan', hass_substate_id='fan.x',+ percentage=42, domain_payload={'set_service': 'set_percentage'},+ )+ self.assertEqual(result.service, 'set_percentage')+ self.assertEqual(result.service_data, {'percentage': 42})++ def test_for_percentage_out_of_range_raises(self):+ with self.assertRaises(ValueError):+ HassServiceComposer.for_percentage(+ domain='fan', hass_substate_id='fan.x',+ percentage=120, domain_payload={'set_service': 'set_percentage'},+ )++ def test_for_oscillating_true(self):+ result = HassServiceComposer.for_oscillating(+ domain='fan', hass_substate_id='fan.x', oscillating=True,+ )+ self.assertEqual(result.service, 'oscillate')+ self.assertEqual(result.service_data, {'oscillating': True})++ def test_for_oscillating_false(self):+ result = HassServiceComposer.for_oscillating(+ domain='fan', hass_substate_id='fan.x', oscillating=False,+ )+ self.assertEqual(result.service_data, {'oscillating': False})++ def test_for_direction_valid(self):+ result = HassServiceComposer.for_direction(+ domain='fan', hass_substate_id='fan.x', direction='reverse',+ )+ self.assertEqual(result.service, 'set_direction')+ self.assertEqual(result.service_data, {'direction': 'reverse'})++ def test_for_direction_invalid_raises(self):+ with self.assertRaises(ValueError):+ HassServiceComposer.for_direction(+ domain='fan', hass_substate_id='fan.x', direction='upward',+ )++ def test_for_preset_mode_valid(self):+ result = HassServiceComposer.for_preset_mode(+ domain='fan', hass_substate_id='fan.x', preset_mode='sleep',+ )+ self.assertEqual(result.service, 'set_preset_mode')+ self.assertEqual(result.service_data, {'preset_mode': 'sleep'})++ def test_for_preset_mode_empty_raises(self):+ with self.assertRaises(ValueError):+ HassServiceComposer.for_preset_mode(+ domain='fan', hass_substate_id='fan.x', preset_mode='',+ )diff --git a/src/hi/simulator/enums.py b/src/hi/simulator/enums.pyindex 009c5fb7..802068e7 100644--- a/src/hi/simulator/enums.py+++ b/src/hi/simulator/enums.py@@ -70,6 +70,7 @@ class SimEntityType(LabeledEnum):AUTOMOBILE = ( 'Automobile', '' )BAROMETER = ( 'Barometer', '' )CAMERA = ( 'Camera', '' )+ CEILING_FAN = ( 'Ceiling Fan', '' )COMPUTER = ( 'Computer', '' )CONSUMABLE = ( 'Consumable', '' )CONTROL_WIRE = ( 'Control Wire', '' )diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.pyindex 809d0551..7c30c0db 100644--- a/src/hi/simulator/management/commands/seed_sim_profiles.py+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py@@ -75,6 +75,7 @@ from hi.simulator.enums import SimEntityTypefrom hi.simulator.models import DbSimEntity, SimProfilefrom hi.simulator.services.hass.sim_models import (HassColorSmartBulbFields,+ HassFanFields,HassGarageCoverFields,HassGenericCoverFields,HassInsteonDimmerLightSwitchFields,@@ -84,6 +85,7 @@ from hi.simulator.services.hass.sim_models import (HassInsteonOpenCloseSensorFields,HassInsteonOutletFields,HassLockFields,+ HassMultiFeatureFanFields,HassSmartBulbFields,HassWindowBlindCoverFields,)@@ -353,6 +355,8 @@ class Command(BaseCommand):self._add_hass_garage_cover( profile, 'Zoo Garage' )self._add_hass_window_blind_cover( profile, 'Zoo Blind' )self._add_hass_generic_cover( profile, 'Zoo Cover' )+ self._add_hass_ceiling_fan( profile, 'Zoo Fan' )+ self._add_hass_multi_feature_fan( profile, 'Zoo Smart Fan' )return profile.db_sim_entities.count()def _build_volume(self, profile: SimProfile) -> int:@@ -520,6 +524,24 @@ class Command(BaseCommand):fields_kwargs = {'name': name},)+ def _add_hass_ceiling_fan(self, profile, name):+ self._create_db_entity(+ profile = profile,+ simulator_id = 'hass',+ fields_class = HassFanFields,+ sim_entity_type = SimEntityType.CEILING_FAN,+ fields_kwargs = {'name': name},+ )++ def _add_hass_multi_feature_fan(self, profile, name):+ self._create_db_entity(+ profile = profile,+ simulator_id = 'hass',+ fields_class = HassMultiFeatureFanFields,+ sim_entity_type = SimEntityType.CEILING_FAN,+ fields_kwargs = {'name': name},+ )+def _add_homebox_item(self, profile, name, **fields_kwargs):kwargs = {'name': name}kwargs.update(fields_kwargs)diff --git a/src/hi/simulator/services/hass/api_composers.py b/src/hi/simulator/services/hass/api_composers.pyindex 0b703521..f8b0cadd 100644--- a/src/hi/simulator/services/hass/api_composers.py+++ b/src/hi/simulator/services/hass/api_composers.py@@ -28,6 +28,8 @@ from .sim_models import (HassColorSmartBulbBrightnessState,HassColorSmartBulbColorModeState,HassColorSmartBulbFields,+ HassMultiFeatureFanFields,+ HassMultiFeatureFanPercentageState,)@@ -104,10 +106,33 @@ class HassApiComposer:primary_dict[ 'attributes' ] = merged_attrsreturn [ primary_dict ]+ @staticmethod+ def _multi_feature_fan( sim_states : List[ SimState ] ) -> List[ Dict ]:+ """Compose a multi-feature fan's percentage / oscillating /+ direction / preset SimStates into ONE HA ``fan.x`` entity.+ Percentage is the primary state (drives the entity's+ ``state`` field on/off); the others contribute attributes+ only."""+ primary_dict = None+ merged_attrs : Dict = {}+ for state in sim_states:+ api_dict = state.to_api_dict()+ if isinstance( state, HassMultiFeatureFanPercentageState ):+ primary_dict = dict( api_dict )+ merged_attrs.update( api_dict.get( 'attributes', {} ) )+ continue++ if primary_dict is None:+ return HassApiComposer._default( sim_states )++ primary_dict[ 'attributes' ] = merged_attrs+ return [ primary_dict ]+# Registry built after the class is defined so the classmethod# objects exist as references. Keyed off SimEntityFields class so# the dispatch is per-device-type.HassApiComposer._REGISTRY = {HassColorSmartBulbFields: HassApiComposer._color_smart_bulb,+ HassMultiFeatureFanFields: HassApiComposer._multi_feature_fan,}diff --git a/src/hi/simulator/services/hass/service_dispatchers.py b/src/hi/simulator/services/hass/service_dispatchers.pyindex 948dd544..36b346d3 100644--- a/src/hi/simulator/services/hass/service_dispatchers.py+++ b/src/hi/simulator/services/hass/service_dispatchers.py@@ -30,9 +30,11 @@ from hi.simulator.enums import SimStateTypefrom .sim_models import (HassColorSmartBulbFields,+ HassFanFields,HassGarageCoverFields,HassGenericCoverFields,HassLockFields,+ HassMultiFeatureFanFields,HassWindowBlindCoverFields,)@@ -219,6 +221,88 @@ class HassServiceDispatcher:return [ ( 'position', str( position_int ) ) ]return []+ @staticmethod+ def _fan( sim_entity,+ domain : str,+ service : str,+ payload : Dict[ str, Any ],+ ) -> List[ Tuple[ str, str ] ]:+ """Speed-only fan: ``turn_on`` / ``turn_off`` /+ ``set_percentage`` all act on the percentage SimState.+ ``turn_on`` with no payload defaults to max speed so+ the operator sees an effect; with a ``percentage`` /+ ``percentage_step`` payload, that value is used."""+ if domain != 'fan':+ return []+ if service == 'turn_off':+ return [ ( 'percentage', '0' ) ]+ if service == 'turn_on':+ value_str = HassServiceDispatcher._extract_percentage_value_str( payload )+ if value_str is None:+ value_str = '100'+ return [ ( 'percentage', value_str ) ]+ if service == 'set_percentage':+ value_str = HassServiceDispatcher._extract_percentage_value_str( payload )+ if value_str is None:+ return []+ return [ ( 'percentage', value_str ) ]+ return []++ @staticmethod+ def _multi_feature_fan( sim_entity,+ domain : str,+ service : str,+ payload : Dict[ str, Any ],+ ) -> List[ Tuple[ str, str ] ]:+ """Multi-feature fan: routes each axis-specific HA service+ to the matching SimState. ``turn_on`` / ``turn_off`` /+ ``set_percentage`` act on the percentage SimState (same+ as the speed-only fan); ``oscillate`` writes the+ oscillating SimState; ``set_direction`` and+ ``set_preset_mode`` write theirs."""+ if domain != 'fan':+ return []+ if service == 'turn_off':+ return [ ( 'percentage', '0' ) ]+ if service == 'turn_on':+ value_str = HassServiceDispatcher._extract_percentage_value_str( payload )+ if value_str is None:+ value_str = '100'+ return [ ( 'percentage', value_str ) ]+ if service == 'set_percentage':+ value_str = HassServiceDispatcher._extract_percentage_value_str( payload )+ if value_str is None:+ return []+ return [ ( 'percentage', value_str ) ]+ if service == 'oscillate':+ osc = payload.get( 'oscillating' )+ if osc is None:+ return []+ return [ ( 'oscillating', 'on' if bool( osc ) else 'off' ) ]+ if service == 'set_direction':+ direction = payload.get( 'direction' )+ if direction not in ( 'forward', 'reverse' ):+ return []+ return [ ( 'direction', direction ) ]+ if service == 'set_preset_mode':+ preset_mode = payload.get( 'preset_mode' )+ if not preset_mode:+ return []+ return [ ( 'preset', str( preset_mode ) ) ]+ return []++ @staticmethod+ def _extract_percentage_value_str( payload : Dict[ str, Any ] ) -> Optional[ str ]:+ """Read fan ``percentage`` from an HA service-call+ payload as a 0-100 integer string. Returns None when the+ payload doesn't carry one."""+ if 'percentage' not in payload:+ return None+ try:+ return str( int( float( payload[ 'percentage' ] ) ) )+ except ( TypeError, ValueError ):+ return None+@staticmethoddef _extract_brightness_value_str( payload : Dict[ str, Any ] ) -> Optional[ str ]:"""Read brightness from an HA service-call payload as a@@ -245,8 +329,10 @@ class HassServiceDispatcher:# objects exist as references. Keyed off SimEntityFields class.HassServiceDispatcher._REGISTRY = {HassColorSmartBulbFields: HassServiceDispatcher._color_smart_bulb,+ HassFanFields: HassServiceDispatcher._fan,HassGarageCoverFields: HassServiceDispatcher._discrete_cover,HassGenericCoverFields: HassServiceDispatcher._discrete_cover,HassLockFields: HassServiceDispatcher._lock,+ HassMultiFeatureFanFields: HassServiceDispatcher._multi_feature_fan,HassWindowBlindCoverFields: HassServiceDispatcher._window_blind_cover,}diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.pyindex 66d81434..4387b2a0 100644--- a/src/hi/simulator/services/hass/sim_models.py+++ b/src/hi/simulator/services/hass/sim_models.py@@ -873,6 +873,241 @@ class HassWindowBlindCoverState( HassState ):}+@dataclass( frozen = True )+class HassFanFields( SimEntityFields ):+ """Speed-only fan. Single CONTINUOUS SimState (0-100+ percentage). The ``state`` property derives ``'on'`` /+ ``'off'`` from the percentage; ``percentage`` and+ ``percentage_step`` attributes carry the numeric value and+ granularity."""+ pass+++def _fan_entity_id( name : str ) -> str:+ suffix = name.lower().replace( ' ', '_' )+ return f'fan.{suffix}'+++@dataclass+class HassFanState( HassState ):+ sim_entity_fields : HassFanFields+ sim_state_type : SimStateType = SimStateType.CONTINUOUS+ sim_state_id : str = 'percentage'+ value : str = '0'++ @property+ def min_value(self):+ return 0++ @property+ def max_value(self):+ return 100++ @property+ def name(self):+ return f'{self.entity_name} Speed'++ @property+ def entity_id(self):+ return _fan_entity_id( self.entity_name )++ @property+ def state(self):+ try:+ percentage = int( float( self.value ) )+ except ( TypeError, ValueError ):+ percentage = 0+ return 'on' if percentage > 0 else 'off'++ @property+ def attributes(self) -> Dict[ str, str ]:+ try:+ percentage = int( float( self.value ) )+ except ( TypeError, ValueError ):+ percentage = 0+ # 25%-step granularity (low/medium/high/max). Real fans+ # vary; this is a representative middle-of-the-road shape.+ return {+ 'friendly_name': self.entity_name,+ 'percentage': percentage,+ 'percentage_step': 25,+ }+++@dataclass( frozen = True )+class HassMultiFeatureFanFields( SimEntityFields ):+ """A multi-feature ceiling fan: speed plus oscillating,+ direction, and preset_mode axes. Composed of multiple+ SimStates collapsed into one HA ``fan.x`` entity at emit+ time by ``api_composers``. HI imports this as four peer+ substate EntityStates (~speed, ~oscillating, ~direction,+ ~preset)."""+ pass+++def _multi_feature_fan_entity_id( name : str ) -> str:+ suffix = name.lower().replace( ' ', '_' )+ return f'fan.{suffix}'+++@dataclass+class HassMultiFeatureFanPercentageState( HassState ):+ """Speed component (CONTINUOUS, 0-100). Primary state of the+ composed entity (drives the entity's ``state`` field)."""++ sim_entity_fields : HassMultiFeatureFanFields+ sim_state_type : SimStateType = SimStateType.CONTINUOUS+ sim_state_id : str = 'percentage'+ value : str = '0'++ @property+ def min_value(self):+ return 0++ @property+ def max_value(self):+ return 100++ @property+ def name(self):+ return f'{self.entity_name} Speed'++ @property+ def entity_id(self):+ return _multi_feature_fan_entity_id( self.entity_name )++ @property+ def state(self):+ try:+ percentage = int( float( self.value ) )+ except ( TypeError, ValueError ):+ percentage = 0+ return 'on' if percentage > 0 else 'off'++ @property+ def attributes(self) -> Dict[ str, str ]:+ try:+ percentage = int( float( self.value ) )+ except ( TypeError, ValueError ):+ percentage = 0+ return {+ 'friendly_name': self.entity_name,+ 'percentage': percentage,+ 'percentage_step': 25,+ }+++@dataclass+class HassMultiFeatureFanOscillatingState( HassState ):+ """Oscillation component (ON_OFF). Composed into the entity's+ ``oscillating`` attribute as a real Python bool (HA expects+ bool, not the simulator's internal ``'on'``/``'off'``+ string)."""++ sim_entity_fields : HassMultiFeatureFanFields+ sim_state_type : SimStateType = SimStateType.ON_OFF+ sim_state_id : str = 'oscillating'+ value : str = 'off'++ @property+ def name(self):+ return f'{self.entity_name} Oscillation'++ @property+ def entity_id(self):+ return _multi_feature_fan_entity_id( self.entity_name )++ @property+ def state(self):+ # Composer ignores; primary state drives entity-level state.+ return 'on'++ @property+ def attributes(self) -> Dict[ str, str ]:+ return { 'oscillating': str_to_bool( self.value ) }+++@dataclass+class HassMultiFeatureFanDirectionState( HassState ):+ """Direction component (DISCRETE). Two-value enum;+ contributes the entity's ``direction`` attribute."""++ DIRECTION_CHOICES : ClassVar[ List[ Tuple[ str, str ] ] ] = [+ ( 'forward', 'Forward' ),+ ( 'reverse', 'Reverse' ),+ ]++ sim_entity_fields : HassMultiFeatureFanFields+ sim_state_type : SimStateType = SimStateType.DISCRETE+ sim_state_id : str = 'direction'+ value : str = 'forward'++ @property+ def name(self):+ return f'{self.entity_name} Direction'++ @property+ def entity_id(self):+ return _multi_feature_fan_entity_id( self.entity_name )++ @property+ def state(self):+ return 'on'++ @property+ def choices(self) -> List[ Tuple[ str, str ] ]:+ return self.DIRECTION_CHOICES++ @property+ def attributes(self) -> Dict[ str, str ]:+ return { 'direction': self.value }+++@dataclass+class HassMultiFeatureFanPresetState( HassState ):+ """Preset component (DISCRETE). Three representative HA+ presets — actual fan vendors expose varying lists; the+ simulator picks a small standard set so HI's import path+ sees the per-fan ``preset_modes`` declaration without+ overreaching into vendor-specific ones. Contributes the+ entity's ``preset_mode`` (current selection) and+ ``preset_modes`` (available list) attributes."""++ PRESET_CHOICES : ClassVar[ List[ Tuple[ str, str ] ] ] = [+ ( 'auto', 'Auto' ),+ ( 'sleep', 'Sleep' ),+ ( 'eco', 'Eco' ),+ ]++ sim_entity_fields : HassMultiFeatureFanFields+ sim_state_type : SimStateType = SimStateType.DISCRETE+ sim_state_id : str = 'preset'+ value : str = 'auto'++ @property+ def name(self):+ return f'{self.entity_name} Preset'++ @property+ def entity_id(self):+ return _multi_feature_fan_entity_id( self.entity_name )++ @property+ def state(self):+ return 'on'++ @property+ def choices(self) -> List[ Tuple[ str, str ] ]:+ return self.PRESET_CHOICES++ @property+ def attributes(self) -> Dict[ str, str ]:+ return {+ 'preset_mode': self.value,+ 'preset_modes': [ choice for choice, _label in self.PRESET_CHOICES ],+ }++HASS_SIM_ENTITY_DEFINITION_LIST = [SimEntityDefinition(class_label = 'Insteon Switch',@@ -986,4 +1221,23 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [HassGenericCoverState,],),+ SimEntityDefinition(+ class_label = 'Fan (speed-only)',+ sim_entity_type = SimEntityType.CEILING_FAN,+ sim_entity_fields_class = HassFanFields,+ sim_state_class_list = [+ HassFanState,+ ],+ ),+ SimEntityDefinition(+ class_label = 'Fan (multi-feature)',+ sim_entity_type = SimEntityType.CEILING_FAN,+ sim_entity_fields_class = HassMultiFeatureFanFields,+ sim_state_class_list = [+ HassMultiFeatureFanPercentageState,+ HassMultiFeatureFanOscillatingState,+ HassMultiFeatureFanDirectionState,+ HassMultiFeatureFanPresetState,+ ],+ ),]diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex 9496d225..d7fd5b6c 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -724,9 +724,6 @@ g[status="past"] {filter: drop-shadow(0 0 5px var(--status-past-color));}-g[status="off"] {- filter: drop-shadow(0 0 5px var(--status-on-color));-}g[status="off"] path.hi-state-bg {fill: var(--status-off-color);}