Skip to content

Home Information - Your home, your data, organized.

Python

Issue #295: HA smart bulb support (brightness + color) (#303)

Tony Ca74b6a8b41e7
diff --git a/docs/dev/integrations/home-assistant.md b/docs/dev/integrations/home-assistant.md
index fa8300ec..77c9cb78 100644
--- a/docs/dev/integrations/home-assistant.md
+++ b/docs/dev/integrations/home-assistant.md
@@ -65,6 +65,26 @@ Upstream API reference: <https://developers.home-assistant.io/docs/api/rest/>.
- **Allowlist filtering.** Only HA domains and device classes named
in the `IMPORT_ALLOWLIST` integration attribute are imported. The
default list is set in `enums.py` (`HassAttributeType`).
+- **HA state vs HA substate.** A "HA state" is the bundle HA returns
+ for one entity_id (top-level `state` field plus `attributes` dict);
+ a "HA substate" is each meaningful atom inside that bundle that HI
+ represents as one HI EntityState. Simple entities have one substate
+ per HA state; a color bulb decomposes into four (brightness, hue,
+ saturation, color temperature). Substate integration_keys use a
+ `~suffix` convention (`light.x` for the parent, `light.x~hue` etc.
+ for the rest) — see `_HASS_SUBSTATE_SUFFIXES` in `hass_converter.py`.
+ Inbound: `hass_state_to_sensor_value_map` decomposes one HA state
+ into its substate value entries. Outbound: `hi_value_to_hass_service_call`
+ routes substate-targeted control values to a single HA service call,
+ reading partner substate values via the framework's
+ `IntegrationConverterHelper` to compose paired payloads (e.g.,
+ `hs_color: [hue, saturation]`).
+- **HassConverter vs HassServiceComposer.** The converter owns
+ HI<->HA bridging (parsing HI control values, choosing the right
+ outbound path); the composer (`hass_service_composer.py`) owns
+ pure HA-side service-call shaping. Bridge methods cross the
+ namespace via `to_ha_*` helpers and hand HA-shaped values to the
+ composer.
## Testing approach
diff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.md
index 8e404a1c..35bebd49 100644
--- a/docs/dev/integrations/integration-guidelines.md
+++ b/docs/dev/integrations/integration-guidelines.md
@@ -9,6 +9,13 @@ Each integration is a Django app in `hi/services/` directory. The `hi.integratio
- **integration_key**: Associates entities/sensors with external systems
- **detail_attrs**: Opaque data blob - only the integration uses this data
+### One-to-many state composition
+A single upstream state may decompose into multiple HI EntityStates when the upstream protocol packs several independently-controllable values into one entity (e.g., a color light's brightness + hue + saturation + color temperature). The framework supports this via:
+
+- **integration_key suffix convention**: each derived EntityState gets its own integration_key (e.g., `light.x` for the parent, `light.x~hue` / `light.x~saturation` for the substates). The integration controls the suffix scheme.
+- **`IntegrationConverterHelper`** (`hi/integrations/integration_converter_helper.py`): a classmethod helper used by converters that need to compose outbound calls from multiple HI EntityState values. Exposes `get_latest_state_values(integration_keys)` for the runtime cache lookup. Inbound decomposition writes each substate value through `SensorResponse`; outbound recomposition reads it back via this helper.
+- The integration's converter decides which upstream attributes become substates and how they map back to outbound calls. See the HA integration's substate handling for a worked example.
+
### Responsibility Boundaries
Integrations 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.
diff --git a/src/hi/apps/api/views.py b/src/hi/apps/api/views.py
index b0f0d4fe..359296c1 100644
--- a/src/hi/apps/api/views.py
+++ b/src/hi/apps/api/views.py
@@ -34,6 +34,7 @@ class StatusView( View,
LastServerTimestampAttr = 'lastTimestamp'
AlertStatusDataAttr = 'alertData'
CssClassUpdateMapAttr = 'cssClassUpdateMap'
+ CssControllerValueMapAttr = 'cssControllerValueMap'
IdReplaceUpdateMapAttr = 'idReplaceUpdateMap'
IdReplaceHashMapAttr = 'idReplaceHashMap'
ConsoleLockedAttr = 'consoleLocked'
@@ -72,6 +73,8 @@ class StatusView( View,
css_class_update_map = dict()
css_class_update_map.update( StatusDisplayManager().get_status_css_class_update_map() )
+ css_controller_value_map = StatusDisplayManager().get_status_controller_value_map()
+
# Hash provided for client to prevent unneeded DOM updates since
# they can interfer with user interactions.
#
@@ -91,6 +94,7 @@ class StatusView( View,
self.ServerTimestampAttr: server_datetime.isoformat(),
self.AlertStatusDataAttr: alert_status_data.to_dict( request = request ),
self.CssClassUpdateMapAttr: css_class_update_map,
+ self.CssControllerValueMapAttr: css_controller_value_map,
self.IdReplaceUpdateMapAttr: id_replace_map,
self.IdReplaceHashMapAttr: id_replace_hash_map,
self.ConsoleLockedAttr: request.session.get(
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.html
index a6ae0bba..d114222e 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
@@ -12,8 +12,11 @@
<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" %}
+{% elif entity_state_status_data.has_sensor %}
+<div class="alert alert-info">{{ entity_state_status_data.entity_state.name }}: awaiting sensor reading.</div>
+
{% else %}
-<div class="alert alert-info">No sensors or controllers defined.</div>
+<div class="alert alert-info">{{ entity_state_status_data.entity_state.name }}: no sensors or controllers defined.</div>
{% endif %}
{% endwith %}
diff --git a/src/hi/apps/control/controller_manager.py b/src/hi/apps/control/controller_manager.py
index f9132f37..12e77d66 100644
--- a/src/hi/apps/control/controller_manager.py
+++ b/src/hi/apps/control/controller_manager.py
@@ -37,7 +37,7 @@ class ControllerManager( Singleton ):
control_result = integration_controller.do_control(
integration_details = controller.get_integration_details(),
- control_value = control_value,
+ hi_control_value = control_value,
)
if not control_result.has_errors:
ControllerHistoryManager().add_to_controller_history(
diff --git a/src/hi/apps/control/templates/control/panes/continuous_slider.html b/src/hi/apps/control/templates/control/panes/continuous_slider.html
new file mode 100644
index 00000000..e85c18db
--- /dev/null
+++ b/src/hi/apps/control/templates/control/panes/continuous_slider.html
@@ -0,0 +1,52 @@
+{% comment %}
+Continuous slider widget (range input + value display + optional
+min/max preset buttons). Per-slider templates {% include %} this
+partial with their own parameters.
+
+Parameters:
+- slider_min, slider_max : required range bounds (numeric).
+- slider_step : optional step (default: omitted).
+- slider_default : value to display when no latest
+ sensor response is cached.
+- display_unit : suffix for the displayed value
+ ('%', '°', 'K', or '').
+- slider_class : per-slider CSS class for gradient
+ track styling (e.g., 'hue-slider').
+- show_presets : True to render two preset buttons
+ that snap the slider to its min and
+ max values (default: False).
+- min_preset_label : button label for the min preset
+ (default: 'Min').
+- max_preset_label : button label for the max preset
+ (default: 'Max').
+{% endcomment %}
+<div class="{{ DIVID.CONTROLLER_SLIDER_CONTROL_CLASS }}">
+ <input type="range"
+ name="value"
+ min="{{ slider_min }}"
+ max="{{ slider_max }}"
+ {% if slider_step %}step="{{ slider_step }}"{% endif %}
+ value="{{ controller_data.latest_sensor_response.value|default_if_none:slider_default }}"
+ class="{{ controller_data.css_class }} {{ DIVID.CONTROLLER_SLIDER_CLASS }} {{ slider_class }}"
+ {{ DIVID.CONTROLLER_DISPLAY_TARGET_ATTR }}=".hi-continuous-slider-value"
+ {{ DIVID.CONTROLLER_DISPLAY_FORMAT_ATTR }}="{n}{{ display_unit }}"
+ onchange-async="true"
+ data-controller-id="{{ controller_data.controller.id }}">
+ <div class="hi-continuous-slider-display">
+ <span class="hi-continuous-slider-value">{{ controller_data.latest_sensor_response.value|default_if_none:slider_default }}{{ display_unit }}</span>
+ {% if show_presets %}
+ <div class="hi-continuous-slider-presets">
+ <button type="button"
+ class="btn btn-sm btn-secondary {{ DIVID.CONTROLLER_PRESET_BTN_CLASS }}"
+ {{ DIVID.DATA_VALUE_ATTR }}="{{ slider_min }}">
+ {{ min_preset_label|default:"Min" }}
+ </button>
+ <button type="button"
+ class="btn btn-sm btn-primary {{ DIVID.CONTROLLER_PRESET_BTN_CLASS }}"
+ {{ DIVID.DATA_VALUE_ATTR }}="{{ slider_max }}">
+ {{ max_preset_label|default:"Max" }}
+ </button>
+ </div>
+ {% endif %}
+ </div>
+</div>
diff --git a/src/hi/apps/control/templates/control/panes/controller_color_temperature.html b/src/hi/apps/control/templates/control/panes/controller_color_temperature.html
new file mode 100644
index 00000000..f1c13c4e
--- /dev/null
+++ b/src/hi/apps/control/templates/control/panes/controller_color_temperature.html
@@ -0,0 +1 @@
+{% include "control/panes/continuous_slider.html" with slider_min=2000 slider_max=6500 slider_step=100 slider_default=4000 display_unit="K" slider_class="color-temperature-slider" %}
diff --git a/src/hi/apps/control/templates/control/panes/controller_hue.html b/src/hi/apps/control/templates/control/panes/controller_hue.html
new file mode 100644
index 00000000..91e115e4
--- /dev/null
+++ b/src/hi/apps/control/templates/control/panes/controller_hue.html
@@ -0,0 +1 @@
+{% include "control/panes/continuous_slider.html" with slider_min=0 slider_max=360 slider_default=0 display_unit="°" slider_class="hue-slider" %}
diff --git a/src/hi/apps/control/templates/control/panes/controller_light_dimmer.html b/src/hi/apps/control/templates/control/panes/controller_light_dimmer.html
index 007ad742..8845a83b 100644
--- a/src/hi/apps/control/templates/control/panes/controller_light_dimmer.html
+++ b/src/hi/apps/control/templates/control/panes/controller_light_dimmer.html
@@ -1,17 +1 @@
-<div class="brightness-control">
- <input type="range"
- name="value"
- min="0"
- max="100"
- value="{{ controller_data.latest_sensor_response.value|default:0 }}"
- class="{{ controller_data.css_class }} brightness-slider"
- onchange-async="true"
- data-controller-id="{{ controller_data.controller.id }}">
- <div class="brightness-display">
- <span class="brightness-value">{{ controller_data.latest_sensor_response.value|default:0 }}%</span>
- <div class="brightness-buttons">
- <button type="button" class="btn btn-sm btn-secondary brightness-btn off-btn" data-value="0">Off</button>
- <button type="button" class="btn btn-sm btn-primary brightness-btn full-btn" data-value="100">Full</button>
- </div>
- </div>
-</div>
\ No newline at end of file
+{% include "control/panes/continuous_slider.html" with slider_min=0 slider_max=100 slider_default=0 display_unit="%" slider_class="brightness-slider" show_presets=True min_preset_label="Off" max_preset_label="Full" %}
diff --git a/src/hi/apps/control/templates/control/panes/controller_saturation.html b/src/hi/apps/control/templates/control/panes/controller_saturation.html
new file mode 100644
index 00000000..bc7f2e10
--- /dev/null
+++ b/src/hi/apps/control/templates/control/panes/controller_saturation.html
@@ -0,0 +1 @@
+{% include "control/panes/continuous_slider.html" with slider_min=0 slider_max=100 slider_default=0 display_unit="%" slider_class="saturation-slider" %}
diff --git a/src/hi/apps/control/tests/test_controller_manager.py b/src/hi/apps/control/tests/test_controller_manager.py
index d7b8f349..e747b2f2 100644
--- a/src/hi/apps/control/tests/test_controller_manager.py
+++ b/src/hi/apps/control/tests/test_controller_manager.py
@@ -89,7 +89,7 @@ class TestControllerManager(BaseTestCase):
# Verify integration details passed correctly
call_args = mock_integration_controller.do_control.call_args
- self.assertEqual(call_args.kwargs['control_value'], 'on')
+ self.assertEqual(call_args.kwargs['hi_control_value'], 'on')
integration_details = call_args.kwargs['integration_details']
self.assertEqual(integration_details.key, controller.integration_key)
self.assertEqual(integration_details.payload, controller.integration_payload)
@@ -205,5 +205,5 @@ class TestControllerManager(BaseTestCase):
# Verify both called integration with same parameters
self.assertEqual(mock_integration_controller.do_control.call_count, 2)
for call in mock_integration_controller.do_control.call_args_list:
- self.assertEqual(call.kwargs['control_value'], '75')
+ self.assertEqual(call.kwargs['hi_control_value'], '75')
return
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index 4200b308..4bf9cab5 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -202,8 +202,23 @@ class EntityStateValue(LabeledEnum):
HIGH = ( 'High', '' )
LOW = ( 'Low', '' )
-
-
+
+ # COLOR_MODE values — modes a smart bulb can be in. UNKNOWN
+ # covers integrations that don't report a mode and cases where
+ # the bulb hasn't yet declared one. Names follow HA's modes;
+ # see EntityStateType.COLOR_MODE for the integration mapping.
+ COLOR_MODE_UNKNOWN = ( 'Unknown', '' )
+ COLOR_MODE_ONOFF = ( 'Basic On/Off', '' )
+ COLOR_MODE_BRIGHTNESS = ( 'Brightness', '' )
+ COLOR_MODE_COLOR_TEMP = ( 'White Temperature', '' )
+ COLOR_MODE_HS = ( 'HS Color', '' )
+ COLOR_MODE_RGB = ( 'RGB Color', '' )
+ COLOR_MODE_RGBW = ( 'RGBW Color', '' )
+ COLOR_MODE_RGBWW = ( 'RGBWW Color', '' )
+ COLOR_MODE_XY = ( 'XY Color', '' )
+ COLOR_MODE_WHITE = ( 'White', '' )
+
+
class EntityStateType(LabeledEnum):
# General types
@@ -226,16 +241,48 @@ class EntityStateType(LabeledEnum):
[] )
BANDWIDTH_USAGE = ( 'Bandwidth Usage' , '',
[] )
+ # COLOR_MODE reports which lighting mode a smart bulb is
+ # currently in (e.g., HS color, white temperature, basic
+ # on/off). Read-only sensor; HA derives the value from
+ # whichever attribute was most recently written. The value
+ # set is the ``COLOR_MODE_*`` family of EntityStateValues.
+ COLOR_MODE = ( 'Color Mode' , 'Active lighting color mode',
+ [ EntityStateValue.COLOR_MODE_UNKNOWN,
+ EntityStateValue.COLOR_MODE_ONOFF,
+ EntityStateValue.COLOR_MODE_BRIGHTNESS,
+ EntityStateValue.COLOR_MODE_COLOR_TEMP,
+ EntityStateValue.COLOR_MODE_HS,
+ EntityStateValue.COLOR_MODE_RGB,
+ EntityStateValue.COLOR_MODE_RGBW,
+ EntityStateValue.COLOR_MODE_RGBWW,
+ EntityStateValue.COLOR_MODE_XY,
+ EntityStateValue.COLOR_MODE_WHITE ] )
+ # COLOR_TEMPERATURE is the white-light Kelvin scale
+ # (warm 2000K to cool 6500K); distinct from a chromatic
+ # color (HUE+SATURATION) since the underlying physics and
+ # the natural UI affordance are different — a 1-D Kelvin
+ # slider, not a 2-D color picker.
+ COLOR_TEMPERATURE = ( 'Color Temperature', 'White-light temperature in Kelvin',
+ [] )
CONNECTIVITY = ( 'Connectivity' , '',
[ EntityStateValue.CONNECTED,
- EntityStateValue.DISCONNECTED ] )
+ EntityStateValue.DISCONNECTED ] )
DATETIME = ( 'Date/Time' , '',
[] )
ELECTRIC_USAGE = ( 'Electric Usage' , '',
[] )
HIGH_LOW = ( 'High/Low' , '',
[ EntityStateValue.HIGH,
- EntityStateValue.LOW ] )
+ EntityStateValue.LOW ] )
+ # HUE and SATURATION are paired in HA's ``hs_color`` 2-tuple
+ # but modeled as separate 1-D EntityStates here so each gets
+ # its own slider; the controller dispatch composes the pair
+ # at the HA service-call boundary. HUE is in degrees (0-360);
+ # SATURATION is a percentage (0-100). Brightness is a third,
+ # independent dimension (LIGHT_DIMMER) — see hi_styles.py
+ # for the chromaticity-vs-intensity rationale.
+ HUE = ( 'Hue' , 'Color hue in degrees (0-360)',
+ [] )
HUMIDITY = ( 'Humidity' , '',
[] )
LIGHT_DIMMER = ( 'Light Dimmer' , 'Controllable light brightness (0-100)',
@@ -256,6 +303,8 @@ class EntityStateType(LabeledEnum):
PRESENCE = ( 'Presence' , '',
[ EntityStateValue.ACTIVE,
EntityStateValue.IDLE ] )
+ SATURATION = ( 'Saturation' , 'Color saturation as a percentage (0-100)',
+ [] )
SOUND_LEVEL = ( 'Sound Level' , '',
[] )
TEMPERATURE = ( 'Temperature' , '',
diff --git a/src/hi/apps/entity/templates/entity/panes/entity_state_status_row.html b/src/hi/apps/entity/templates/entity/panes/entity_state_status_row.html
index 6ee5d3f4..f26947da 100644
--- a/src/hi/apps/entity/templates/entity/panes/entity_state_status_row.html
+++ b/src/hi/apps/entity/templates/entity/panes/entity_state_status_row.html
@@ -10,8 +10,11 @@
{% elif entity_state_status_data.sensor_response_list %}
{% include "sense/panes/sensor_response_status_row.html" with sensor_response=entity_state_status_data.latest_sensor_response %}
+ {% elif entity_state_status_data.has_sensor %}
+ <div class="alert alert-info">{{ entity_state_status_data.entity_state.name }}: awaiting sensor reading.</div>
+
{% else %}
- <div class="alert alert-info">No sensors or controllers defined.</div>
+ <div class="alert alert-info">{{ entity_state_status_data.entity_state.name }}: no sensors or controllers defined.</div>
{% endif %}
</div>
diff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/status_display_data.py
index 2286f730..4487ab57 100644
--- a/src/hi/apps/monitor/status_display_data.py
+++ b/src/hi/apps/monitor/status_display_data.py
@@ -21,6 +21,7 @@ class StatusDisplayData:
self._controller_data_list = entity_state_status_data.controller_data_list
self._svg_status_style = self._get_svg_status_style()
+ self._controller_data_value = self._get_controller_data_value()
return
@property
@@ -52,6 +53,23 @@ class StatusDisplayData:
if self._svg_status_style:
return self._svg_status_style.to_dict()
return dict()
+
+ @property
+ def controller_data_value(self):
+ """The value to push to controller widgets (slider, checkbox,
+ select, color picker) for this state via the polling
+ controller-value map. None means this state has no
+ controller (read-only sensor) and should be skipped.
+
+ Distinct from the visual ``svg_status_style`` (CSS-driven
+ bucketed status): the controller value is whatever the
+ widget needs to faithfully reflect the latest state — a
+ precise numeric for a slider, ``'on'``/``'off'`` for a
+ checkbox, the discrete value for a select, a structured
+ dict for a future color picker. Per-state-type reshaping
+ can be added in ``_get_controller_data_value`` when a
+ widget needs something other than the raw sensor value."""
+ return self._controller_data_value
@property
def latest_sensor_value(self):
@@ -71,6 +89,25 @@ class StatusDisplayData:
return self.sensor_response_list[1].timestamp
return None
+ def _get_controller_data_value(self):
+ """Compute the controller-shaped value for this state.
+
+ Returns None when the state has no controller (purely
+ read-only sensors like motion or open/close binary
+ sensors), so the polling map skips them. Default for
+ controllable states is the raw latest sensor value, which
+ is what the existing widget templates already render
+ on initial load (slider ``value=...``, checkbox
+ ``checked=...``, select option ``selected=...``).
+
+ Per-state-type overrides go here when a widget needs a
+ reshape — e.g., a future COLOR state would return a dict
+ like ``{"hs": [60, 100]}`` for the color picker to consume.
+ """
+ if not self._controller_data_list:
+ return None
+ return self.latest_sensor_value
+
def _get_svg_status_style(self):
if self.entity_state.entity_state_type == EntityStateType.MOVEMENT:
diff --git a/src/hi/apps/monitor/status_display_manager.py b/src/hi/apps/monitor/status_display_manager.py
index 516dbefd..8289f924 100644
--- a/src/hi/apps/monitor/status_display_manager.py
+++ b/src/hi/apps/monitor/status_display_manager.py
@@ -39,6 +39,28 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
continue
return css_class_update_map
+
+ def get_status_controller_value_map( self ) -> Dict[ str, object ]:
+ """Build the class-to-controller-value map consumed by the
+ polling response's ``cssControllerValueMap`` key. Parallel
+ to ``get_status_css_class_update_map`` but for value-bearing
+ controller widgets (slider, checkbox, select, future color
+ picker) rather than CSS-driven visual styling. States with
+ no controller (read-only sensors) are skipped — see
+ ``StatusDisplayData.controller_data_value``."""
+
+ entity_state_status_data_list = self.get_all_entity_state_status_data_list()
+ status_display_data_list = [ StatusDisplayData(x) for x in entity_state_status_data_list ]
+
+ controller_value_map = dict()
+ for status_display_data in status_display_data_list:
+ controller_value = status_display_data.controller_data_value
+ if controller_value is None:
+ continue
+ controller_value_map[ status_display_data.css_class ] = controller_value
+ continue
+
+ return controller_value_map
def get_all_entity_state_status_data_list( self ) -> List[ EntityStateStatusData ]:
"""
@@ -86,6 +108,11 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
entity_state = entity_state,
sensor_response_list = sensor_response_list,
controller_data_list = controller_data_list,
+ # This branch only sees EntityStates that produced
+ # responses, so a sensor must exist; controllers
+ # are explicitly known via the list above.
+ has_sensor = True,
+ has_controller = bool( controller_data_list ),
)
entity_state_status_data_list.append( entity_state_status_data )
continue
@@ -260,6 +287,8 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
entity_state = entity_state,
sensor_response_list = entity_state_sensor_response_list,
controller_data_list = controller_data_list,
+ has_sensor = bool( entity_state_to_sensor_list.get( entity_state ) ),
+ has_controller = bool( controller_data_list ),
)
entity_state_to_entity_state_status_data_map[entity_state] = entity_state_status_data
continue
diff --git a/src/hi/apps/monitor/transient_models.py b/src/hi/apps/monitor/transient_models.py
index 88180eb5..6fca0da4 100644
--- a/src/hi/apps/monitor/transient_models.py
+++ b/src/hi/apps/monitor/transient_models.py
@@ -14,6 +14,14 @@ class EntityStateStatusData:
entity_state : EntityState
sensor_response_list : List[ SensorResponse ] # Not grouped by sensor, but ordered by response time
controller_data_list : List[ ControllerData ]
+ # Whether the EntityState has any Sensor / Controller defined,
+ # distinct from whether the response/data lists are populated.
+ # A sensor-only state whose Sensor has no cached response yet
+ # has ``has_sensor=True`` but an empty ``sensor_response_list``;
+ # the display layer uses these to distinguish "awaiting first
+ # reading" from "nothing defined."
+ has_sensor : bool = False
+ has_controller : bool = False
@property
def latest_sensor_response(self) -> SensorResponse:
diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.py
index e7c2e2d5..e280a5a1 100644
--- a/src/hi/apps/sense/sensor_response_manager.py
+++ b/src/hi/apps/sense/sensor_response_manager.py
@@ -2,7 +2,7 @@ from asgiref.sync import sync_to_async
import asyncio
from cachetools import TTLCache
import logging
-from typing import Dict, List
+from typing import Dict, List, Optional
from hi.apps.common.redis_client import get_redis_client
from hi.apps.common.singleton import Singleton
@@ -169,6 +169,25 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
return sensor_response_list_map
+ def get_latest_sensor_response_map(
+ self, integration_keys : List[ IntegrationKey ],
+ ) -> Dict[ IntegrationKey, Optional[ SensorResponse ] ]:
+ if not integration_keys:
+ return {}
+ list_cache_keys = [ self.to_sensor_response_list_cache_key( k ) for k in integration_keys ]
+ pipeline = self._redis_client.pipeline()
+ for list_cache_key in list_cache_keys:
+ pipeline.lindex( list_cache_key, 0 )
+ continue
+ cached_values = pipeline.execute()
+ result : Dict[ IntegrationKey, Optional[ SensorResponse ] ] = {}
+ for integration_key, cached_value in zip( integration_keys, cached_values ):
+ result[ integration_key ] = (
+ SensorResponse.from_string( cached_value ) if cached_value else None
+ )
+ continue
+ return result
+
def get_latest_sensor_responses( self,
sensor_list : List[ Sensor ] ) -> Dict[ Sensor, List[ SensorResponse ] ]:
diff --git a/src/hi/apps/sense/tests/test_sensor_response_manager.py b/src/hi/apps/sense/tests/test_sensor_response_manager.py
index 0de4dc82..b581d9f9 100644
--- a/src/hi/apps/sense/tests/test_sensor_response_manager.py
+++ b/src/hi/apps/sense/tests/test_sensor_response_manager.py
@@ -226,6 +226,72 @@ class AsyncSensorResponseManagerTestCase(AsyncTaskTestCase):
self.assertEqual(deserialized.detail_attrs, original_response.detail_attrs)
self.assertEqual(deserialized.source_image_url, original_response.source_image_url)
+ def test_get_latest_sensor_response_map_empty_list_short_circuits(self):
+ """Empty integration_keys returns empty dict without touching Redis."""
+ with patch.object(self.manager, '_redis_client') as mock_redis:
+ result = self.manager.get_latest_sensor_response_map(integration_keys=[])
+ self.assertEqual(result, {})
+ mock_redis.pipeline.assert_not_called()
+
+ def test_get_latest_sensor_response_map_returns_none_for_uncached(self):
+ """Keys with no cached entry map to None."""
+ # Reset fakeredis state for this test.
+ self.manager._redis_client.flushdb()
+
+ result = self.manager.get_latest_sensor_response_map(
+ integration_keys=[self.integration_key],
+ )
+ self.assertEqual(result, {self.integration_key: None})
+
+ def test_get_latest_sensor_response_map_returns_latest_for_cached(self):
+ """Keys with cached entries return the most recent SensorResponse."""
+ self.manager._redis_client.flushdb()
+
+ cache_key = self.manager.to_sensor_response_list_cache_key(self.integration_key)
+ older = SensorResponse(
+ integration_key=self.integration_key,
+ value='old_value',
+ timestamp=timezone.now(),
+ )
+ newer = SensorResponse(
+ integration_key=self.integration_key,
+ value='new_value',
+ timestamp=timezone.now(),
+ )
+ # LPUSH order matches the production write path (newer at index 0).
+ self.manager._redis_client.lpush(cache_key, str(older))
+ self.manager._redis_client.lpush(cache_key, str(newer))
+
+ result = self.manager.get_latest_sensor_response_map(
+ integration_keys=[self.integration_key],
+ )
+ self.assertEqual(len(result), 1)
+ self.assertEqual(result[self.integration_key].value, 'new_value')
+
+ def test_get_latest_sensor_response_map_handles_mixed_cached_and_uncached(self):
+ """Multiple keys: some cached, some not — order preserved, None for misses."""
+ self.manager._redis_client.flushdb()
+
+ key_a = IntegrationKey(integration_id='a', integration_name='one')
+ key_b = IntegrationKey(integration_id='b', integration_name='two')
+ key_c = IntegrationKey(integration_id='c', integration_name='three')
+
+ # Cache only key_a and key_c.
+ for key, value in [(key_a, 'val_a'), (key_c, 'val_c')]:
+ cache_key = self.manager.to_sensor_response_list_cache_key(key)
+ response = SensorResponse(
+ integration_key=key, value=value, timestamp=timezone.now(),
+ )
+ self.manager._redis_client.lpush(cache_key, str(response))
+
+ result = self.manager.get_latest_sensor_response_map(
+ integration_keys=[key_a, key_b, key_c],
+ )
+ self.assertEqual(set(result.keys()), {key_a, key_b, key_c})
+ self.assertEqual(result[key_a].value, 'val_a')
+ self.assertIsNone(result[key_b])
+ self.assertEqual(result[key_c].value, 'val_c')
+
def test_get_latest_sensor_responses_for_specific_sensors(self):
"""Test retrieval of responses for specific sensor list."""
# Create additional test data
diff --git a/src/hi/constants.py b/src/hi/constants.py
index 298dea86..80a104b1 100644
--- a/src/hi/constants.py
+++ b/src/hi/constants.py
@@ -131,6 +131,16 @@ DIVID = {
'ATTR_V2_SHOW_LESS_TEXT_CLASS': 'show-less-text',
'ATTR_V2_DELETE_FILE_ATTR': 'delete_file_attribute',
+ # Controller widgets - Class names and data attributes shared
+ # between controller templates (server-emitted) and
+ # controllers.js (client-side display sync, preset buttons).
+ 'CONTROLLER_DISPLAY_TARGET_ATTR': 'data-display-target',
+ 'CONTROLLER_DISPLAY_FORMAT_ATTR': 'data-display-format',
+ 'CONTROLLER_SLIDER_CLASS': 'hi-continuous-slider',
+ 'CONTROLLER_SLIDER_CONTROL_CLASS': 'hi-continuous-slider-control',
+ 'CONTROLLER_PRESET_BTN_CLASS': 'hi-continuous-slider-preset-btn',
+ 'DATA_VALUE_ATTR': 'data-value',
+
# Entity Picker - JavaScript dependencies only
'ENTITY_PICKER_FILTERABLE_ITEM_CLASS': 'filterable-item',
'ENTITY_PICKER_GROUP_SECTION_CLASS': 'entity-group-section',
diff --git a/src/hi/integrations/integration_controller.py b/src/hi/integrations/integration_controller.py
index 5c3336b5..6a4b1bf4 100644
--- a/src/hi/integrations/integration_controller.py
+++ b/src/hi/integrations/integration_controller.py
@@ -6,5 +6,5 @@ class IntegrationController:
def do_control( self,
integration_details : IntegrationDetails,
- control_value : str ) -> IntegrationControlResult:
+ hi_control_value : str ) -> IntegrationControlResult:
raise NotImplementedError('Subclasses must override this method')
diff --git a/src/hi/integrations/integration_converter_helper.py b/src/hi/integrations/integration_converter_helper.py
new file mode 100644
index 00000000..76f17f60
--- /dev/null
+++ b/src/hi/integrations/integration_converter_helper.py
@@ -0,0 +1,43 @@
+from typing import Dict, List, Optional
+
+from hi.apps.sense.sensor_response_manager import SensorResponseMixin
+
+from .transient_models import IntegrationKey
+
+
+class IntegrationConverterHelper:
+ """Shared classmethod helpers for integration converters
+ (which are stateless containers of related methods).
+
+ The cached ``_Internal`` instance bridges this classmethod
+ facade to the project's instance-method ``SensorResponseMixin``
+ pattern so manager access still goes through the mixin's
+ coordination path. The proper fix is to make converters
+ Singleton instances and inherit ``SensorResponseMixin``
+ directly; deferred because the converter call surface is
+ pervasively classmethod-based and that conversion is a much
+ larger change.
+ """
+
+ class _Internal( SensorResponseMixin ):
+ pass
+
+ _internal_instance = None
+
+ @classmethod
+ def _sensor_response_manager(cls):
+ if cls._internal_instance is None:
+ cls._internal_instance = cls._Internal()
+ return cls._internal_instance.sensor_response_manager()
+
+ @classmethod
+ def get_latest_state_values(
+ cls, integration_keys : List[IntegrationKey],
+ ) -> Dict[IntegrationKey, Optional[str]]:
+ response_map = cls._sensor_response_manager().get_latest_sensor_response_map(
+ integration_keys = integration_keys,
+ )
+ return {
+ integration_key: ( response.value if response else None )
+ for integration_key, response in response_map.items()
+ }
diff --git a/src/hi/integrations/models.py b/src/hi/integrations/models.py
index 3f36ce37..aa919061 100644
--- a/src/hi/integrations/models.py
+++ b/src/hi/integrations/models.py
@@ -189,21 +189,21 @@ class IntegrationDetailsModel( models.Model ):
def update_integration_payload(self, new_payload: dict) -> list:
"""
Update integration payload and return list of changed fields.
- Only reports changes to existing fields (ignores new fields).
- Returns list of strings describing changes, empty if no existing values changed.
+ Reports modifications to existing fields by name; returns an
+ empty list when nothing changed (no DB write performed).
"""
old_payload = self.integration_payload or {}
+ if old_payload == new_payload:
+ return []
+
changed_fields = []
-
- # Check for changes to existing fields only
for key, new_value in new_payload.items():
if key in old_payload and old_payload[key] != new_value:
changed_fields.append(f'{key}: {old_payload[key]} -> {new_value}')
-
- # Always update payload (even if no existing fields changed)
+
self.integration_payload = new_payload
self.save()
-
+
return changed_fields
diff --git a/src/hi/integrations/tests/test_models.py b/src/hi/integrations/tests/test_models.py
index 474a4183..0fba1716 100644
--- a/src/hi/integrations/tests/test_models.py
+++ b/src/hi/integrations/tests/test_models.py
@@ -520,17 +520,14 @@ class IntegrationDetailsModelTestCase(TestCase):
def update_integration_payload(self, new_payload):
old_payload = self.integration_payload or {}
+ if old_payload == new_payload:
+ return []
changed_fields = []
-
- # Check for changes to existing fields only
for key, new_value in new_payload.items():
if key in old_payload and old_payload[key] != new_value:
changed_fields.append(f'{key}: {old_payload[key]} -> {new_value}')
-
- # Always update payload (even if no existing fields changed)
self.integration_payload = new_payload
self.save()
-
return changed_fields
# Test with empty initial payload
diff --git a/src/hi/services/hass/hass_client.py b/src/hi/services/hass/hass_client.py
index 15f7103e..827e18f6 100644
--- a/src/hi/services/hass/hass_client.py
+++ b/src/hi/services/hass/hass_client.py
@@ -117,22 +117,22 @@ class HassClient:
)
return response.json()
- def call_service( self, domain: str, service: str, hass_state_id: str, service_data: dict = None ):
+ def call_service( self, domain: str, service: str, hass_entity_id: str, service_data: dict = None ):
"""
- Call a Home Assistant service for a specific HassState.
-
+ Call a Home Assistant service for a specific HA entity.
+
Args:
domain: The domain (e.g., 'light', 'switch')
service: The service name (e.g., 'turn_on', 'turn_off')
- hass_state_id: The HassState identifier (e.g., 'light.switch_name')
+ hass_entity_id: The HA entity_id (e.g., 'light.switch_name')
service_data: Additional service data (optional)
-
+
Returns:
Response object
"""
url = f'{self._api_base_url}/api/services/{domain}/{service}'
data = {
- 'entity_id': hass_state_id,
+ 'entity_id': hass_entity_id,
}
if service_data:
data.update(service_data)
@@ -153,7 +153,7 @@ class HassClient:
f'Ensure the URL points at the HASS API root.'
)
- logger.debug( f'HAss call_service: {domain}.{service} for {hass_state_id}, response={response.status_code}' )
+ logger.debug( f'HAss call_service: {domain}.{service} for {hass_entity_id}, response={response.status_code}' )
return response
diff --git a/src/hi/services/hass/hass_controller.py b/src/hi/services/hass/hass_controller.py
index c8e723bd..79d298c1 100644
--- a/src/hi/services/hass/hass_controller.py
+++ b/src/hi/services/hass/hass_controller.py
@@ -14,24 +14,27 @@ class HassController( IntegrationController, HassMixin ):
def do_control( self,
integration_details : IntegrationDetails,
- control_value : str ) -> IntegrationControlResult:
+ hi_control_value : str ) -> IntegrationControlResult:
logger.debug( f'HAss do_control ENTRY: integration_details={integration_details},'
- f' control_value={control_value}' )
+ f' hi_control_value={hi_control_value}' )
try:
- entity_id = integration_details.key.integration_name
+ hass_substate_id = integration_details.key.integration_name
domain_payload = integration_details.payload or {}
- logger.debug( f'HAss do_control entity_id: {entity_id}, payload: {domain_payload}' )
-
- hass_state_value = HassConverter.hass_entity_id_to_state_value_str(
- hass_entity_id = entity_id,
- hi_value = control_value,
+ service_call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id = hass_substate_id,
+ hi_control_value = hi_control_value,
+ domain_payload = domain_payload,
+ )
+ self.hass_manager().hass_client.call_service(
+ domain = service_call.domain,
+ service = service_call.service,
+ hass_entity_id = service_call.hass_entity_id,
+ service_data = service_call.service_data,
+ )
+ return IntegrationControlResult(
+ new_value = hi_control_value,
+ error_list = [],
)
- logger.debug( f'HAss do_control converted value: {hass_state_value}' )
-
- return self._do_control_with_services( entity_id,
- control_value,
- hass_state_value,
- domain_payload )
except Exception as e:
logger.warning( f'Exception in HAss do_control: {e}' )
return IntegrationControlResult(
@@ -40,532 +43,25 @@ class HassController( IntegrationController, HassMixin ):
)
def _do_control_with_set_state( self,
- hass_state_id : str,
- control_value : str,
- hass_state_value : str ) -> IntegrationControlResult:
+ hass_entity_id : str,
+ hi_control_value : str,
+ hass_substate_value : str ) -> IntegrationControlResult:
"""
- Legacy method using Home Assistant set_state API.
-
- Note: This method updates HA's internal state but may not actually
- control physical devices. Kept for debugging and special use cases.
+ Legacy method using Home Assistant set_state API. Retained for
+ debugging and special use cases; not invoked by the live
+ ``do_control`` path which uses HA service calls instead.
"""
- logger.debug( f'HAss attempting set state: {hass_state_id}={hass_state_value}' )
-
+ logger.debug( f'HAss attempting set state: {hass_entity_id}={hass_substate_value}' )
+
response_data = self.hass_manager().hass_client.set_state(
- entity_id = hass_state_id,
- state = hass_state_value,
+ entity_id = hass_entity_id,
+ state = hass_substate_value,
)
- # If we get here, the HTTP call succeeded (set_state raises exception on failure)
error_list = list()
- logger.debug( f'HAss set state SUCCESS: {hass_state_id}={hass_state_value},'
+ logger.debug( f'HAss set state SUCCESS: {hass_entity_id}={hass_substate_value},'
f' response_data={response_data}' )
return IntegrationControlResult(
- new_value = control_value,
+ new_value = hi_control_value,
error_list = error_list,
)
-
- def _do_control_with_services( self,
- hass_state_id : str,
- control_value : str,
- hass_state_value : str,
- domain_payload : dict ) -> IntegrationControlResult:
- """Use Home Assistant service calls for device control (recommended approach)"""
-
- # Extract domain from payload (more reliable than parsing entity_id)
- domain = domain_payload.get('domain')
- if not domain:
- # Fallback to parsing from entity_id if payload missing
- if '.' not in hass_state_id:
- logger.warning( f'Invalid hass_state_id format and no domain payload:'
- f' {hass_state_id}' )
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Invalid entity_id format: {hass_state_id}'],
- )
- domain = hass_state_id.split('.', 1)[0]
- logger.warning( f'Missing domain payload for {hass_state_id},'
- f' using parsed domain: {domain}' )
-
- # Use payload-based service routing if available, otherwise best-effort
- if domain_payload:
- return self._control_device_with_payload( domain,
- hass_state_id,
- control_value,
- hass_state_value,
- domain_payload )
- else:
- return self._control_device_best_effort( domain,
- hass_state_id,
- control_value,
- hass_state_value )
-
- def _control_on_off_device( self,
- domain: str,
- hass_state_id: str,
- control_value: str,
- hass_state_value: str ) -> IntegrationControlResult:
- """Handle on/off control for lights, switches, and similar devices"""
- logger.debug( f'HAss attempting service call for {domain}:'
- f' {hass_state_id}={control_value}' )
-
- # Determine service based on control value
- if control_value.lower() in ['on', 'true', '1']:
- service = 'turn_on'
- elif control_value.lower() in ['off', 'false', '0']:
- service = 'turn_off'
- else:
- logger.warning( f'Unknown {domain} control value "{control_value}"' )
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Unknown control value: {control_value}'],
- )
-
- # Call the Home Assistant service
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = service,
- hass_state_id = hass_state_id,
- )
-
- error_list = list()
- logger.debug( f'HAss service call SUCCESS: {domain}.{service} for {hass_state_id}' )
- return IntegrationControlResult(
- new_value = control_value,
- error_list = error_list,
- )
-
- def _control_device_best_effort( self,
- domain : str,
- hass_state_id : str,
- control_value : str,
- hass_state_value : str ) -> IntegrationControlResult:
- """
- Best-effort device control when payload is missing.
- Uses standard Home Assistant service patterns based on domain and control value.
- """
- logger.debug( f'HAss best-effort control: {domain} {hass_state_id}={control_value}' )
-
- try:
- # Handle numeric controls for known domains
- if self._is_numeric_value( control_value ):
- return self._control_numeric_best_effort( domain, hass_state_id, control_value )
-
- # Handle on/off/open/close controls
- return self._control_on_off_best_effort( domain, hass_state_id, control_value )
-
- except Exception as e:
- logger.warning( f'Best-effort control failed for {hass_state_id}: {e}' )
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Best-effort control failed: {str(e)}'],
- )
-
- def _is_numeric_value( self, control_value: str ) -> bool:
- """Check if control value is numeric"""
- try:
- float(control_value)
- return True
- except (ValueError, TypeError):
- return False
-
- def _control_on_off_best_effort( self,
- domain : str,
- hass_state_id : str,
- control_value : str ) -> IntegrationControlResult:
- """Best-effort on/off/open/close control based on standard HA patterns"""
- logger.debug( f'HAss best-effort on/off control: {domain} {hass_state_id}={control_value}' )
-
- # Determine service based on control value and domain
- control_lower = control_value.lower()
-
- if control_lower in ['on', 'true', '1']:
- service = 'turn_on'
- elif control_lower in ['off', 'false', '0']:
- service = 'turn_off'
- elif control_lower in ['open']:
- if domain == 'cover':
- service = 'open_cover'
- elif domain == 'lock':
- service = 'unlock'
- else:
- service = 'turn_on' # Fallback
- elif control_lower in ['close']:
- if domain == 'cover':
- service = 'close_cover'
- elif domain == 'lock':
- service = 'lock'
- else:
- service = 'turn_off' # Fallback
- else:
- logger.warning( f'Unknown control value "{control_value}"'
- f' for best-effort control of {hass_state_id}' )
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Unknown control value: {control_value}'],
- )
-
- # Call the Home Assistant service
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = service,
- hass_state_id = hass_state_id,
- )
-
- logger.debug( f'HAss best-effort service call SUCCESS: {domain}.{service}'
- f' for {hass_state_id}' )
- return IntegrationControlResult(
- new_value = control_value,
- error_list = [],
- )
-
- def _control_numeric_best_effort( self,
- domain : str,
- hass_state_id : str,
- control_value : str ) -> IntegrationControlResult:
- """Best-effort numeric control based on common HA patterns"""
- logger.debug( f'HAss best-effort numeric control: {domain}'
- f' {hass_state_id}={control_value}' )
-
- try:
- numeric_value = float(control_value)
-
- # Light brightness (0-100%)
- if domain == 'light':
- brightness_pct = int(numeric_value)
- if not (0 <= brightness_pct <= 100):
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Invalid brightness value: {brightness_pct} (must be 0-100)'],
- )
-
- if brightness_pct == 0:
- service = 'turn_off'
- service_data = None
- else:
- service = 'turn_on'
- service_data = {'brightness_pct': brightness_pct}
-
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = service,
- hass_state_id = hass_state_id,
- service_data = service_data,
- )
-
- logger.debug( f'HAss best-effort light control SUCCESS: {domain}.{service} for {hass_state_id}' )
- return IntegrationControlResult(
- new_value = str(brightness_pct),
- error_list = [],
- )
-
- # Climate temperature
- elif domain == 'climate':
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = 'set_temperature',
- hass_state_id = hass_state_id,
- service_data = {'temperature': numeric_value},
- )
-
- logger.debug( f'HAss best-effort climate control SUCCESS: climate.set_temperature for {hass_state_id}' )
- return IntegrationControlResult(
- new_value = str(numeric_value),
- error_list = [],
- )
-
- # Cover position (0-100%)
- elif domain == 'cover':
- position_pct = int(numeric_value)
- if not (0 <= position_pct <= 100):
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Invalid position value: {position_pct} (must be 0-100)'],
- )
-
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = 'set_cover_position',
- hass_state_id = hass_state_id,
- service_data = {'position': position_pct},
- )
-
- logger.debug( f'HAss best-effort cover control SUCCESS: cover.set_cover_position for {hass_state_id}' )
- return IntegrationControlResult(
- new_value = str(position_pct),
- error_list = [],
- )
-
- # Media player volume (0.0-1.0)
- elif domain == 'media_player':
- if not (0.0 <= numeric_value <= 1.0):
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Invalid volume value: {numeric_value} (must be 0.0-1.0)'],
- )
-
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = 'volume_set',
- hass_state_id = hass_state_id,
- service_data = {'volume_level': numeric_value},
- )
-
- logger.debug( f'HAss best-effort media_player control SUCCESS: media_player.volume_set for {hass_state_id}' )
- return IntegrationControlResult(
- new_value = str(numeric_value),
- error_list = [],
- )
-
- # Other domains - try generic approach
- else:
- logger.warning( f'No best-effort numeric control pattern for domain {domain}, entity {hass_state_id}' )
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'No numeric control pattern for domain: {domain}'],
- )
-
- except ValueError:
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Invalid numeric value: {control_value}'],
- )
-
- def _control_device_with_payload( self, domain: str, hass_state_id: str, control_value: str, hass_state_value: str, domain_payload: dict ) -> IntegrationControlResult:
- """Use stored payload to control device directly"""
- logger.debug( f'HAss payload-based control: {domain} {hass_state_id}={control_value}, payload={domain_payload}' )
-
- # Check if device is controllable
- if not domain_payload.get('is_controllable', False):
- logger.warning( f'Device {hass_state_id} is not controllable, attempting best-effort control' )
- return self._control_device_best_effort( domain, hass_state_id, control_value, hass_state_value )
-
- # Handle complex numeric controls (brightness, temperature, volume, etc.)
- if self._is_numeric_control( control_value, domain_payload ):
- return self._control_numeric_parameter_device( domain, hass_state_id, control_value, domain_payload )
-
- # Handle on/off control
- if control_value.lower() in ['on', 'true', '1']:
- service = domain_payload.get('on_service')
- if not service:
- logger.warning( f'No on_service defined in payload for {hass_state_id}, using best-effort control' )
- return self._control_device_best_effort( domain, hass_state_id, control_value, hass_state_value )
- elif control_value.lower() in ['off', 'false', '0']:
- service = domain_payload.get('off_service')
- if not service:
- logger.warning( f'No off_service defined in payload for {hass_state_id}, using best-effort control' )
- return self._control_device_best_effort( domain, hass_state_id, control_value, hass_state_value )
- elif control_value.lower() in ['open']:
- service = domain_payload.get('open_service')
- if not service:
- logger.warning( f'No open_service defined in payload for {hass_state_id}, using best-effort control' )
- return self._control_device_best_effort( domain, hass_state_id, control_value, hass_state_value )
- elif control_value.lower() in ['close']:
- service = domain_payload.get('close_service')
- if not service:
- logger.warning( f'No close_service defined in payload for {hass_state_id}, using best-effort control' )
- return self._control_device_best_effort( domain, hass_state_id, control_value, hass_state_value )
- else:
- logger.warning( f'Unknown control value "{control_value}" for {hass_state_id}' )
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Unknown control value: {control_value}'],
- )
-
- # Call the Home Assistant service
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = service,
- hass_state_id = hass_state_id,
- )
-
- logger.debug( f'HAss service call SUCCESS: {domain}.{service} for {hass_state_id}' )
- return IntegrationControlResult(
- new_value = control_value,
- error_list = [],
- )
-
- def _is_numeric_control( self, control_value: str, domain_payload: dict ) -> bool:
- """Check if control value should be handled as numeric parameter"""
- try:
- # Must be a valid numeric value
- float(control_value)
-
- # Must have either brightness support or set_service for numeric parameters
- return ( domain_payload.get('supports_brightness', False)
- or domain_payload.get('set_service') is not None )
- except (ValueError, TypeError):
- return False
-
- def _control_numeric_parameter_device( self,
- domain : str,
- hass_state_id : str,
- control_value : str,
- domain_payload : dict ) -> IntegrationControlResult:
- """Handle numeric parameter controls (brightness, temperature, volume, position, etc.)"""
- try:
- numeric_value = float(control_value)
-
- # Handle brightness control (0-100%)
- if domain_payload.get('supports_brightness', False):
- return self._control_brightness_value( domain, hass_state_id, numeric_value, domain_payload )
-
- # Handle temperature control
- elif 'temperature' in domain_payload.get('parameters', {}):
- return self._control_temperature_value( domain, hass_state_id, numeric_value, domain_payload )
-
- # Handle volume control
- elif 'volume_level' in domain_payload.get('parameters', {}):
- return self._control_volume_value( domain, hass_state_id, numeric_value, domain_payload )
-
- # Handle position control (covers, etc.)
- elif 'position' in domain_payload.get('parameters', {}):
- return self._control_position_value( domain, hass_state_id, numeric_value, domain_payload )
-
- # Generic set_service fallback
- elif domain_payload.get('set_service'):
- service = domain_payload.get('set_service')
- # Use the numeric value directly - service will determine parameter name
- service_data = {domain.rstrip('s'): numeric_value} # e.g., climate -> temperature
-
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = service,
- hass_state_id = hass_state_id,
- service_data = service_data,
- )
-
- logger.debug( f'HAss numeric control SUCCESS: {domain}.{service} for {hass_state_id} value={numeric_value}' )
- return IntegrationControlResult(
- new_value = control_value,
- error_list = [],
- )
-
- else:
- logger.warning( f'No numeric parameter handling defined for {hass_state_id}' )
- return IntegrationControlResult(
- new_value = None,
- error_list = ['No numeric parameter handling defined'],
- )
-
- except ValueError:
- logger.warning( f'Invalid numeric control value: {control_value}' )
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Invalid numeric value: {control_value}'],
- )
-
- def _control_brightness_value( self, domain: str, hass_state_id: str, brightness: float, domain_payload: dict ) -> IntegrationControlResult:
- """Handle brightness/dimmer control (0-100%)"""
- brightness_pct = int(brightness)
- if not (0 <= brightness_pct <= 100):
- logger.warning( f'Invalid brightness value {brightness} for {hass_state_id}' )
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Invalid brightness value: {brightness}'],
- )
-
- if brightness_pct == 0:
- # Turn off for 0% brightness
- service = domain_payload.get('off_service')
- service_data = None
- else:
- # Turn on with brightness
- service = domain_payload.get('on_service')
- service_data = {'brightness_pct': brightness_pct}
-
- if not service:
- logger.warning( f'No appropriate service defined in payload for brightness control of {hass_state_id}' )
- return IntegrationControlResult(
- new_value = None,
- error_list = ['No service defined for brightness control'],
- )
-
- # Call the Home Assistant service
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = service,
- hass_state_id = hass_state_id,
- service_data = service_data,
- )
-
- logger.debug( f'HAss brightness control SUCCESS: {domain}.{service} for {hass_state_id} brightness={brightness_pct}%' )
- return IntegrationControlResult(
- new_value = str(brightness_pct),
- error_list = [],
- )
-
- def _control_temperature_value( self, domain: str, hass_state_id: str, temperature: float, domain_payload: dict ) -> IntegrationControlResult:
- """Handle temperature control for thermostats"""
- service = domain_payload.get('set_service')
- if not service:
- logger.warning( f'No set_service defined for temperature control of {hass_state_id}' )
- return IntegrationControlResult(
- new_value = None,
- error_list = ['No temperature service defined'],
- )
-
- # Call the Home Assistant service
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = service,
- hass_state_id = hass_state_id,
- service_data = {'temperature': temperature},
- )
-
- logger.debug( f'HAss temperature control SUCCESS: {domain}.{service} for {hass_state_id} temperature={temperature}' )
- return IntegrationControlResult(
- new_value = str(temperature),
- error_list = [],
- )
-
- def _control_volume_value( self, domain: str, hass_state_id: str, volume: float, domain_payload: dict ) -> IntegrationControlResult:
- """Handle volume control for media players (0.0-1.0)"""
- if not (0.0 <= volume <= 1.0):
- logger.warning( f'Invalid volume value {volume} for {hass_state_id} (must be 0.0-1.0)' )
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Invalid volume value: {volume} (must be 0.0-1.0)'],
- )
-
- service = domain_payload.get('set_service', 'volume_set')
-
- # Call the Home Assistant service
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = service,
- hass_state_id = hass_state_id,
- service_data = {'volume_level': volume},
- )
-
- logger.debug( f'HAss volume control SUCCESS: {domain}.{service} for {hass_state_id} volume={volume}' )
- return IntegrationControlResult(
- new_value = str(volume),
- error_list = [],
- )
-
- def _control_position_value( self, domain: str, hass_state_id: str, position: float, domain_payload: dict ) -> IntegrationControlResult:
- """Handle position control for covers (0-100%)"""
- position_pct = int(position)
- if not (0 <= position_pct <= 100):
- logger.warning( f'Invalid position value {position} for {hass_state_id} (must be 0-100)' )
- return IntegrationControlResult(
- new_value = None,
- error_list = [f'Invalid position value: {position} (must be 0-100)'],
- )
-
- service = domain_payload.get('set_service', 'set_cover_position')
-
- # Call the Home Assistant service
- self.hass_manager().hass_client.call_service(
- domain = domain,
- service = service,
- hass_state_id = hass_state_id,
- service_data = {'position': position_pct},
- )
-
- logger.debug( f'HAss position control SUCCESS: {domain}.{service} for {hass_state_id} position={position_pct}%' )
- return IntegrationControlResult(
- new_value = str(position_pct),
- error_list = [],
- )
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index 373bc07c..562a0829 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -1,5 +1,7 @@
+import json
import logging
import re
+from dataclasses import dataclass
from typing import Dict, List, Optional, Set, Tuple
from django.db import transaction
@@ -18,67 +20,59 @@ from hi.apps.entity.enums import (
from hi.apps.entity.models import Entity, EntityAttribute, EntityState
from hi.apps.model_helper import HiModelHelper
+from hi.integrations.integration_converter_helper import IntegrationConverterHelper
from hi.integrations.transient_models import IntegrationKey
from .enums import HassStateValue
from .hass_metadata import HassMetaData
-from .hass_models import HassApi, HassState, HassDevice
+from .hass_models import HassApi, HassServiceCall, HassState, HassDevice
+from .hass_service_composer import ControlIntent, HassServiceComposer
logger = logging.getLogger(__name__)
class HassConverter:
"""
- Converts Home Assistant API states into HI devices with comprehensive service call support.
-
- OVERVIEW:
- - Converts HA API states into HI devices (Entity models)
- - HA devices may consist of multiple states (e.g., light.kitchen + switch.kitchen = one device)
- - Determines which HA devices are imported into HI
- - HA API response doesn't make state-to-device relationships explicit, so we use heuristics
-
- ARCHITECTURE:
-
- 1. DEVICE AGGREGATION (heuristic grouping of HassStates into HassDevices):
- - device_group_id: States with same Insteon address are grouped together
- - full_name matching: States with same name but different domains are grouped
- - suffix-based logic: Removes known suffixes (_temperature, _battery) to find base device
- - switch/light deduplication: Avoids creating duplicate entities for dual-domain devices
-
- 2. ENTITY-STATE MAPPING (structured mapping from HA domains/device_classes to EntityStateTypes):
- - Uses HASS_STATE_TO_ENTITY_STATE_TYPE_MAPPING table for consistent, predictable mapping
- - Key: (domain, device_class, has_brightness) → EntityStateType
- - Handles special cases: dimmer lights, door sensors, temperature sensors, etc.
- - Replaces old heuristic if/else chains with maintainable lookup tables
-
- 3. CONTROLLABILITY DETERMINATION:
- - ON_OFF_CONTROLLABLE_DOMAINS: light, switch (simple on/off control)
- - COMPLEX_CONTROLLABLE_DOMAINS: cover, fan, climate, etc. (multiple services)
- - SENSOR_ONLY_DOMAINS: binary_sensor, sensor, camera (read-only)
- - Uses _is_controllable_domain_and_type() for precise control determination
-
- 4. SERVICE CALL PAYLOAD (storage of service routing info for device control):
- - CONTROL_SERVICE_MAPPING: (domain, EntityStateType) → service names and parameters
- - Payload data stored during import contains: domain, on_service, off_service, capabilities
- - Controller uses payload data directly without runtime lookups or EntityStateType awareness
- - Enables proper HA service calls (turn_on/turn_off) instead of unreliable set_state API
-
- 5. CONTROLLER + SENSOR CREATION:
- - Controllable devices: Create Controller (which auto-creates associated Sensor)
- - Sensor-only devices: Create Sensor only
- - All models store integration payload data for service call routing
- - Maintains 1:1 HassState ↔ EntityState mapping with proper separation of concerns
-
- RATIONALE:
- - Centralizes all HA integration complexity in converter (import-time)
- - Controller becomes simple payload consumer (runtime)
- - Service calls work reliably vs set_state which only updates HA internal state
- - Structured mappings are maintainable vs scattered heuristic logic
- - Backward compatible with existing device grouping and alarm event creation
-
- FLOW:
- HA API → HassStates → Device Grouping → EntityState Mapping → Service Payload →
- Controller/Sensor Creation → Payload Storage → Runtime Service Calls
+ Bidirectional bridge between HI's data model and Home
+ Assistant's API.
+
+ Terminology:
+ - domain : HA top-level category (``light``, ``switch``,
+ ``binary_sensor``, ``sensor``, ``cover``, ...).
+ The prefix of an entity_id (``light.x`` →
+ domain ``light``).
+ - device_class : Subtype within a domain (``motion``,
+ ``temperature``, ``door``, ...). Reported in
+ the HA state's attributes.
+ - entity, state : A single HA entity (one entity_id) and the
+ bundle HA returns for it from
+ ``/api/states/{entity_id}`` (top-level
+ ``state`` field + ``attributes`` dict).
+ ``HassState`` wraps one HA state.
+ - substate : One meaningful atom inside a HA state that
+ maps to one HI EntityState. Simple entities
+ have one substate; color bulbs have several
+ (brightness, hue, saturation, color_temp).
+ - device : An aggregate of HA entities believed to
+ belong to one physical thing. Heuristic
+ grouping (Insteon address, name suffixes)
+ since HA's API doesn't make the relationship
+ explicit.
+
+ Three jobs:
+ 1. Import-time: HA API → HI Entity + Sensor + Controller
+ models. Aggregates entities into devices, maps each substate
+ to an EntityStateType, decides controller-vs-sensor, attaches
+ an integration_payload carrying service-routing info for
+ outbound calls.
+ 2. Inbound runtime (``hass_state_to_sensor_value_map``): one HA
+ state → ``Dict[IntegrationKey, value]``, one entry per
+ substate.
+ 3. Outbound runtime (``hi_value_to_hass_service_call``): one HI
+ control value + integration_payload → ``HassServiceCall``.
+ Bridge methods parse HI values via ``to_ha_*`` boundary
+ helpers and delegate pure HA-side composition to
+ ``HassServiceComposer``.
"""
@staticmethod
@@ -600,30 +594,72 @@ class HassConverter:
new_hass_state_list = list()
seen_state_integration_keys = set()
for hass_state in hass_device.hass_state_list:
-
+
state_integration_key = cls.hass_state_to_integration_key( hass_state = hass_state )
seen_state_integration_keys.add( state_integration_key )
-
+
+ # Substates are derived EntityStates of the same
+ # HA state; register their keys so the cleanup
+ # loop below spares them, and refresh their
+ # 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 ):
+ sub_key = cls._substate_integration_key(
+ hass_state = hass_state,
+ entity_state_type = substate_type,
+ )
+ seen_state_integration_keys.add( sub_key )
+ sub_controller = entiity_controllers.get( sub_key )
+ sub_sensor = entiity_sensors.get( sub_key )
+ if sub_controller or sub_sensor:
+ any_existing_substate = True
+ if sub_controller:
+ sub_payload = cls._substate_integration_payload(
+ hass_state = hass_state,
+ substate_type = substate_type,
+ )
+ changed_fields = sub_controller.update_integration_payload( sub_payload )
+ if changed_fields:
+ messages.append(
+ f'Updated payload for substate controller {sub_controller}:'
+ f' {", ".join(changed_fields)}'
+ )
+ continue
+
sensor = entiity_sensors.get( state_integration_key )
controller = entiity_controllers.get( state_integration_key )
- # Update integration payload for existing sensors and controllers
- # Every HassState should have at least a sensor, potentially also a controller
- if sensor or controller:
- # Use sensor or controller to determine EntityStateType (they should be the same)
- model_with_entity_state = controller if controller else sensor
- existing_entity_state_type = model_with_entity_state.entity_state.entity_state_type
- is_controllable = cls._is_controllable_domain_and_type(hass_state.domain, existing_entity_state_type)
-
- # Generate new payload using existing logic
- new_payload = cls._create_service_payload(hass_state, existing_entity_state_type, is_controllable)
-
- # Update payload for both sensor and controller if they exist
- for model, model_type in [(sensor, 'sensor'), (controller, 'controller')]:
- if model:
- changed_fields = model.update_integration_payload(new_payload)
- if changed_fields:
- messages.append(f'Updated payload for {model_type} {model}: {", ".join(changed_fields)}')
+ # For multi-substate lights, no model lives at
+ # the bare key — match on existing substates so
+ # we don't fall through to the "missing" branch
+ # and re-create what's already there.
+ if sensor or controller or any_existing_substate:
+ if sensor or controller:
+ # Refresh the parent (bare-key) payload —
+ # only relevant for single-state HA entities;
+ # multi-substate lights have no parent model.
+ model_with_entity_state = controller if controller else sensor
+ existing_entity_state_type = model_with_entity_state.entity_state.entity_state_type
+ is_controllable = cls._is_controllable_domain_and_type(hass_state.domain, existing_entity_state_type)
+ new_payload = cls._create_service_payload(hass_state, existing_entity_state_type, is_controllable)
+ for model, model_type in [(sensor, 'sensor'), (controller, 'controller')]:
+ if model:
+ changed_fields = model.update_integration_payload(new_payload)
+ if changed_fields:
+ messages.append(f'Updated payload for {model_type} {model}: {", ".join(changed_fields)}')
+
+ # Create any newly-implied substate models
+ # (e.g., a bulb that gained color modes since
+ # it was first imported).
+ created = cls._create_substate_models(
+ entity = entity,
+ hass_state = hass_state,
+ existing_controllers = entiity_controllers,
+ existing_sensors = entiity_sensors,
+ )
+ for new_model in created:
+ messages.append( f'Added substate model {new_model}' )
else:
messages.append( f'Missing sensors/controllers for {entity}. Adding {hass_state}' )
new_hass_state_list.append( hass_state )
@@ -704,17 +740,112 @@ class HassConverter:
and ( hass_state.domain in ignore_light_state_prefixes )):
continue
- entity_state = cls._create_hass_state_sensor_or_controller(
- hass_device = hass_device,
+ 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
+ # bare-key parent). The Entity itself is still
+ # identified by the bare HA entity_id; only the
+ # EntityStates use suffixed integration_keys.
+ cls._create_substate_models(
+ entity = entity,
+ hass_state = hass_state,
+ )
+ else:
+ entity_state = cls._create_hass_state_sensor_or_controller(
+ hass_device = hass_device,
+ hass_state = hass_state,
+ entity = entity,
+ integration_key = state_integration_key,
+ 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,
+ )
+ continue
+ return
+
+ @classmethod
+ def _create_substate_models(
+ cls,
+ entity : Entity,
+ hass_state : HassState,
+ existing_controllers : Optional[ Dict ] = None,
+ 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:
+ return []
+ if existing_controllers is None:
+ existing_controllers = {}
+ if existing_sensors is None:
+ existing_sensors = {}
+ base_name = hass_state.friendly_name or entity.name
+ created = []
+ for substate_type in substate_types:
+ spec = cls._SUBSTATE_SPECS[ substate_type ]
+ substate_integration_key = cls._substate_integration_key(
hass_state = hass_state,
- entity = entity,
- integration_key = state_integration_key,
- add_alarm_events = add_alarm_events,
+ entity_state_type = substate_type,
+ )
+ existing_for_kind = (
+ existing_controllers if spec.is_controllable else existing_sensors
)
- prefix_to_entity_state[hass_state.domain] = entity_state
+ if substate_integration_key in existing_for_kind:
+ continue
+ record_name = f'{base_name} {substate_type.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,
+ 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,
+ )
+ controller.save()
+ created.append( controller )
+ else:
+ sensor = HiModelHelper.create_sensor(
+ entity = entity,
+ entity_state_type = substate_type,
+ name = record_name,
+ integration_key = substate_integration_key,
+ value_range_str = value_range_str,
+ )
+ created.append( sensor )
continue
- return
-
+ return created
+
+ @classmethod
+ def _substate_integration_payload(
+ cls,
+ hass_state : HassState,
+ substate_type : EntityStateType,
+ ) -> dict:
+ spec = cls._SUBSTATE_SPECS[ substate_type ]
+ return {
+ 'domain': hass_state.domain,
+ 'is_controllable': spec.is_controllable,
+ 'substate': spec.suffix,
+ 'parent_entity_id': hass_state.entity_id,
+ }
+
@classmethod
def _create_hass_state_sensor_or_controller( cls,
hass_device : HassDevice,
@@ -829,15 +960,246 @@ class HassConverter:
logger.warning( f'No mapping found for domain {domain}, device_class {device_class}. Using BLOB.' )
return EntityStateType.BLOB
+ # HA color/light modes that imply the light supports a
+ # variable brightness level. Used by ``_has_brightness_capability``
+ # to recognize a dimmer-capable light from its declared
+ # ``supported_color_modes`` even when the live ``brightness``
+ # attribute is absent — which HA does when the light is off.
+ # Without this, a known dimmer that's currently off would
+ # collapse into the on/off path and lose its dimmer state
+ # type on every off→on transition.
+ _BRIGHTNESS_SUPPORTING_COLOR_MODES = {
+ 'brightness',
+ 'color_temp',
+ 'hs',
+ 'rgb',
+ 'rgbw',
+ 'rgbww',
+ 'white',
+ 'xy',
+ }
+
+ # Modes whose presence in ``supported_color_modes`` means the
+ # light can produce chromatic color (hue/saturation pair, with
+ # rgb/xy as alternate representations of the same chromaticity).
+ # ``color_temp`` is excluded — it's white-light Kelvin, a
+ # separate axis with its own EntityStateType.
+ _CHROMATIC_COLOR_MODES = {
+ 'hs',
+ 'rgb',
+ 'rgbw',
+ 'rgbww',
+ 'xy',
+ }
+
+ # 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
+ # 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).
+ @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,
+ ),
+ }
+
+ # Translation of HA's color_mode attribute values to HI's
+ # COLOR_MODE EntityStateValues. HA's ``null`` and explicit
+ # ``'unknown'`` both map to UNKNOWN — HA's docs distinguish
+ # them but don't ascribe different semantics, and off-state
+ # behavior varies per-integration.
+ _HASS_COLOR_MODE_TO_HI_VALUE = {
+ None: EntityStateValue.COLOR_MODE_UNKNOWN,
+ 'unknown': EntityStateValue.COLOR_MODE_UNKNOWN,
+ 'onoff': EntityStateValue.COLOR_MODE_ONOFF,
+ 'brightness': EntityStateValue.COLOR_MODE_BRIGHTNESS,
+ 'color_temp': EntityStateValue.COLOR_MODE_COLOR_TEMP,
+ 'hs': EntityStateValue.COLOR_MODE_HS,
+ 'rgb': EntityStateValue.COLOR_MODE_RGB,
+ 'rgbw': EntityStateValue.COLOR_MODE_RGBW,
+ 'rgbww': EntityStateValue.COLOR_MODE_RGBWW,
+ 'xy': EntityStateValue.COLOR_MODE_XY,
+ 'white': EntityStateValue.COLOR_MODE_WHITE,
+ }
+
+ @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.
+ """
+ if hass_state.domain != HassApi.LIGHT_DOMAIN:
+ return []
+ supported = hass_state.attributes.get( 'supported_color_modes' )
+ if not isinstance( supported, list ):
+ return []
+
+ 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.
+ if chromatic_present or color_temp_present:
+ substate_types.append( EntityStateType.LIGHT_DIMMER )
+ if chromatic_present:
+ substate_types.append( EntityStateType.HUE )
+ substate_types.append( EntityStateType.SATURATION )
+ if color_temp_present:
+ substate_types.append( EntityStateType.COLOR_TEMPERATURE )
+ # 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.
+ if len( supported ) > 1:
+ substate_types.append( EntityStateType.COLOR_MODE )
+ return substate_types
+
+ @classmethod
+ def _extract_substate_value(
+ cls,
+ hass_state : HassState,
+ entity_state_type : EntityStateType,
+ ) -> 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
+
+ if entity_state_type == EntityStateType.LIGHT_DIMMER:
+ return cls._dimmer_brightness_value( hass_state )
+
+ if entity_state_type == EntityStateType.HUE:
+ hs = attrs.get( 'hs_color' )
+ if isinstance( hs, list ) and len( hs ) >= 1:
+ try:
+ return str( round( float( hs[ 0 ] ) ) )
+ except ( TypeError, ValueError ):
+ return None
+ return None
+
+ if entity_state_type == EntityStateType.SATURATION:
+ hs = attrs.get( 'hs_color' )
+ if isinstance( hs, list ) and len( hs ) >= 2:
+ try:
+ return str( round( float( hs[ 1 ] ) ) )
+ except ( TypeError, ValueError ):
+ return None
+ return None
+
+ if entity_state_type == EntityStateType.COLOR_TEMPERATURE:
+ kelvin = attrs.get( 'color_temp_kelvin' )
+ if kelvin is not None:
+ try:
+ return str( int( float( kelvin ) ) )
+ except ( TypeError, ValueError ):
+ return None
+ return None
+
+ if entity_state_type == EntityStateType.COLOR_MODE:
+ if 'color_mode' not in attrs:
+ return None
+ ha_value = attrs[ 'color_mode' ]
+ hi_value = cls._HASS_COLOR_MODE_TO_HI_VALUE.get(
+ ha_value, EntityStateValue.COLOR_MODE_UNKNOWN,
+ )
+ return str( hi_value )
+
+ return None
+
+ @classmethod
+ def _substate_integration_key(
+ cls,
+ hass_state : HassState,
+ entity_state_type : EntityStateType,
+ ) -> 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."""
+ return cls._substate_integration_key_for_suffix(
+ parent_entity_id = hass_state.entity_id,
+ suffix = cls._SUBSTATE_SPECS[ entity_state_type ].suffix,
+ )
+
+ @classmethod
+ def _substate_integration_key_for_suffix(
+ cls,
+ parent_entity_id : str,
+ suffix : str,
+ ) -> IntegrationKey:
+ # ``~`` separator chosen over ``:`` because the latter has
+ # special meaning in CSS selectors (pseudo-classes) and
+ # in URLs; ``~`` is web-safe in every position and never
+ # appears in real HA entity_ids (they're ``[a-z0-9_]+``).
+ return IntegrationKey(
+ integration_id = HassMetaData.integration_id,
+ integration_name = f'{parent_entity_id}~{suffix}',
+ )
+
@classmethod
def _has_brightness_capability( cls, hass_state: HassState ) -> bool:
- """Check if a light has brightness/dimming capability"""
+ """Check if a light has brightness/dimming capability."""
if hass_state.domain != HassApi.LIGHT_DOMAIN:
return False
-
- # Check if brightness is in the state attributes
+
attributes = hass_state.attributes
- return 'brightness' in attributes or 'brightness_pct' in attributes
+ if 'brightness' in attributes or 'brightness_pct' in attributes:
+ return True
+
+ # The brightness attribute is omitted in HA's off-state
+ # output even for known-dimmable lights; consult the
+ # capability declaration in ``supported_color_modes`` so
+ # the dimmer path keeps firing across on/off transitions.
+ supported_color_modes = attributes.get('supported_color_modes')
+ if isinstance(supported_color_modes, list):
+ for mode in supported_color_modes:
+ if mode in cls._BRIGHTNESS_SUPPORTING_COLOR_MODES:
+ return True
+ return False
@classmethod
def _is_controllable_domain_and_type( cls, domain: str, entity_state_type: EntityStateType ) -> bool:
@@ -1250,101 +1612,370 @@ class HassConverter:
integration_id = HassMetaData.integration_id,
integration_name = hass_state.entity_id,
)
-
- @classmethod
- def hass_state_to_sensor_value_str( cls, hass_state : HassState ) -> str:
- if hass_state.domain == HassApi.SUN_DOMAIN:
- return hass_state.state_value
-
- elif hass_state.domain == HassApi.WEATHER_DOMAIN:
- return hass_state.state_value
-
- elif hass_state.domain == HassApi.LIGHT_DOMAIN:
- # Handle light domain - could be LIGHT_DIMMER or ON_OFF
- if cls._has_brightness_capability(hass_state):
- # This is a dimmer light - normalize to 0-100 numeric values
- if hass_state.state_value.lower() == HassStateValue.OFF:
- return "0"
- elif hass_state.state_value.lower() == HassStateValue.ON:
- # Extract brightness from attributes (HA uses 1-255, we use 0-100)
- brightness = hass_state.attributes.get('brightness')
- if brightness is not None:
- try:
- # Convert HA brightness (1-255) to percentage (0-100) with rounding
- brightness_pct = round((float(brightness) / 255.0) * 100)
- return str(brightness_pct)
- except (ValueError, TypeError):
- # Invalid brightness value, assume full brightness
- return "100"
- else:
- # No brightness info available, assume full brightness
- return "100"
- else:
- # Unknown state, return as-is
- return hass_state.state_value
- else:
- # Regular on/off light - convert to EntityStateValue strings
- if hass_state.state_value.lower() == HassStateValue.ON:
- return str(EntityStateValue.ON)
- elif hass_state.state_value.lower() == HassStateValue.OFF:
- return str(EntityStateValue.OFF)
- else:
- return hass_state.state_value
-
- elif hass_state.domain == HassApi.BINARY_SENSOR_DOMAIN:
-
- if hass_state.state_value.lower() == HassStateValue.ON:
- if hass_state.device_class in HassApi.MOTION_DEVICE_CLASS:
- return str(EntityStateValue.ACTIVE)
- elif hass_state.device_class in HassApi.BATTERY_DEVICE_CLASS:
- return str(EntityStateValue.LOW)
- elif hass_state.device_class in HassApi.OPEN_CLOSE_DEVICE_CLASS_SET:
- return str(EntityStateValue.OPEN)
- elif hass_state.device_class in HassApi.CONNECTIVITY_DEVICE_CLASS:
- return str(EntityStateValue.CONNECTED)
- else:
- return str(EntityStateValue.ON)
-
- elif hass_state.state_value.lower() == HassStateValue.OFF:
- if hass_state.device_class in HassApi.MOTION_DEVICE_CLASS:
- return str(EntityStateValue.IDLE)
- elif hass_state.device_class in HassApi.BATTERY_DEVICE_CLASS:
- return str(EntityStateValue.HIGH)
- elif hass_state.device_class in HassApi.OPEN_CLOSE_DEVICE_CLASS_SET:
- return str(EntityStateValue.CLOSED)
- elif hass_state.device_class in HassApi.CONNECTIVITY_DEVICE_CLASS:
- return str(EntityStateValue.DISCONNECTED)
- else:
- return str(EntityStateValue.OFF)
- else:
- logger.warning( f'Unknown HAss binary state value "{hass_state.state_value}".' )
- return None
-
- elif hass_state.device_class == HassApi.TEMPERATURE_DEVICE_CLASS:
- return hass_state.state_value
-
- elif hass_state.device_class == HassApi.HUMIDITY_DEVICE_CLASS:
- return hass_state.state_value
+ @classmethod
+ def hass_state_to_sensor_value_map(
+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
+ """All HI sensor values produced by a single HA state,
+ keyed by the integration_key of the HI EntityState the
+ value targets. A simple HA state contributes a single
+ entry; a color-capable light decomposes into brightness
+ plus hue, saturation, and color temperature entries.
+ Domain-specific value extraction lives in the per-domain
+ helpers this method dispatches to."""
+ domain = hass_state.domain
+ if domain == HassApi.LIGHT_DOMAIN:
+ return cls._light_to_sensor_value_map( hass_state )
+ if domain == HassApi.BINARY_SENSOR_DOMAIN:
+ return cls._binary_sensor_to_sensor_value_map( hass_state )
+ return cls._passthrough_to_sensor_value_map( hass_state )
- elif hass_state.device_class == HassApi.TIMESTAMP_DEVICE_CLASS:
- return hass_state.state_value
+ @classmethod
+ def _light_to_sensor_value_map(
+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
+ if cls._has_brightness_capability( hass_state ):
+ return cls._dimmer_light_to_sensor_value_map( hass_state )
+ return cls._on_off_light_to_sensor_value_map( hass_state )
- elif hass_state.device_class == HassApi.ENUM_DEVICE_CLASS:
- return hass_state.state_value
+ @classmethod
+ def _dimmer_light_to_sensor_value_map(
+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
+ """Brightness percentage plus any color sub-state values
+ (hue, saturation, color temperature, color mode) implied
+ by the HA light's ``supported_color_modes``. Each value
+ targets a distinct HI EntityState. For multi-substate
+ lights brightness is itself a peer substate (suffixed
+ key); 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:
+ 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 )
+ if value is None:
+ continue
+ substate_key = cls._substate_integration_key(
+ hass_state = hass_state,
+ entity_state_type = substate_type,
+ )
+ result[ substate_key ] = value
+ continue
+ return result
+ @classmethod
+ def _dimmer_brightness_value( cls, hass_state : HassState ) -> Optional[ str ]:
+ """0-100 percentage for the LIGHT_DIMMER state. HA reports
+ ``brightness`` as 1-255 when on, and omits the attribute
+ when the light is off (state='off' carries the level)."""
+ sv = hass_state.state_value.lower()
+ if sv == HassStateValue.OFF:
+ return "0"
+ if sv == HassStateValue.ON:
+ brightness = hass_state.attributes.get( 'brightness' )
+ if brightness is None:
+ return "100"
+ try:
+ return str( round( ( float( brightness ) / 255.0 ) * 100 ) )
+ except ( ValueError, TypeError ):
+ return "100"
return hass_state.state_value
+ @classmethod
+ def _on_off_light_to_sensor_value_map(
+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
+ sv = hass_state.state_value.lower()
+ if sv == HassStateValue.ON:
+ value = str( EntityStateValue.ON )
+ elif sv == HassStateValue.OFF:
+ value = str( EntityStateValue.OFF )
+ else:
+ value = hass_state.state_value
+ if not value:
+ return {}
+ return { cls.hass_state_to_integration_key( hass_state ) : value }
+
+ @classmethod
+ def _binary_sensor_to_sensor_value_map(
+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
+ value = cls._binary_sensor_value( hass_state )
+ if value is None:
+ return {}
+ return { cls.hass_state_to_integration_key( hass_state ) : value }
+
+ @classmethod
+ def _binary_sensor_value( cls, hass_state : HassState ) -> Optional[ str ]:
+ """Translate HA binary state (on/off) plus device_class to
+ the matching HI EntityStateValue: ACTIVE/IDLE for motion,
+ OPEN/CLOSED for doors and peers, CONNECTED/DISCONNECTED
+ for connectivity, LOW/HIGH for battery."""
+ sv = hass_state.state_value.lower()
+ dc = hass_state.device_class
+ if sv == HassStateValue.ON:
+ if dc == HassApi.MOTION_DEVICE_CLASS:
+ return str( EntityStateValue.ACTIVE )
+ if dc == HassApi.BATTERY_DEVICE_CLASS:
+ return str( EntityStateValue.LOW )
+ if dc in HassApi.OPEN_CLOSE_DEVICE_CLASS_SET:
+ return str( EntityStateValue.OPEN )
+ if dc == HassApi.CONNECTIVITY_DEVICE_CLASS:
+ return str( EntityStateValue.CONNECTED )
+ return str( EntityStateValue.ON )
+ if sv == HassStateValue.OFF:
+ if dc == HassApi.MOTION_DEVICE_CLASS:
+ return str( EntityStateValue.IDLE )
+ if dc == HassApi.BATTERY_DEVICE_CLASS:
+ return str( EntityStateValue.HIGH )
+ if dc in HassApi.OPEN_CLOSE_DEVICE_CLASS_SET:
+ return str( EntityStateValue.CLOSED )
+ if dc == HassApi.CONNECTIVITY_DEVICE_CLASS:
+ return str( EntityStateValue.DISCONNECTED )
+ return str( EntityStateValue.OFF )
+ logger.warning( f'Unknown HAss binary state value "{hass_state.state_value}".' )
+ return None
+
+ @classmethod
+ def _passthrough_to_sensor_value_map(
+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
+ """Domains and device classes whose HA state value passes
+ through unchanged: sun, weather, sensor temperature /
+ humidity / timestamp / enum, and any unrecognized HA
+ state shape."""
+ value = hass_state.state_value
+ if value is None:
+ return {}
+ return { cls.hass_state_to_integration_key( hass_state ) : value }
+
@classmethod
def hass_entity_id_to_state_value_str( cls,
hass_entity_id : str,
- hi_value : str) -> str:
- if hi_value is None:
+ hi_control_value : str) -> str:
+ if hi_control_value is None:
return HassStateValue.OFF
- if hi_value.lower() in [ str(EntityStateValue.OPEN), str(EntityStateValue.ON) ]:
+ if hi_control_value.lower() in [ str(EntityStateValue.OPEN), str(EntityStateValue.ON) ]:
return HassStateValue.ON
- if hi_value.lower() in [ str(EntityStateValue.CLOSED), str(EntityStateValue.OFF) ]:
+ if hi_control_value.lower() in [ str(EntityStateValue.CLOSED), str(EntityStateValue.OFF) ]:
return HassStateValue.OFF
- return hi_value
-
-
+ return hi_control_value
+
+ # ------------------------------------------------------------------
+ # HI control value -> HA service call composition
+ #
+ # Inverse direction of ``hass_state_to_sensor_value_map``: given a
+ # HI control value targeting one HA substate, produce the HA
+ # service call to invoke. Bridge methods here parse HI values
+ # and orchestrate; pure HA-side composition lives in
+ # ``HassServiceComposer``.
+ # ------------------------------------------------------------------
+
+ @classmethod
+ def to_ha_numeric_parameter_value( cls, hi_control_value : str ) -> float:
+ """Identity-valued boundary marker: parses an HI numeric
+ control value into the float HA expects. Today the value
+ passes through unchanged; the named conversion documents
+ the namespace transition and gives a single point to
+ introduce real conversion if HI's units later diverge from
+ HA's."""
+ return float( hi_control_value )
+
+ @classmethod
+ def to_ha_on_off_intent( cls, hi_control_value : str ) -> str:
+ """Normalize an HI on/off-style control value to a
+ canonical ``ControlIntent``. ``HassServiceComposer`` maps
+ the intent + domain to the right HA service name."""
+ lower = hi_control_value.lower()
+ if lower == str( EntityStateValue.ON ) or lower in ( 'true', '1' ):
+ return ControlIntent.ON
+ if lower == str( EntityStateValue.OFF ) or lower in ( 'false', '0' ):
+ return ControlIntent.OFF
+ if lower == str( EntityStateValue.OPEN ):
+ return ControlIntent.OPEN
+ if lower == str( EntityStateValue.CLOSED ) or lower == 'close':
+ return ControlIntent.CLOSE
+ raise ValueError( f'Unknown control value: {hi_control_value}' )
+
+ @classmethod
+ def hi_value_to_hass_service_call(
+ cls,
+ hass_substate_id : str,
+ hi_control_value : str,
+ domain_payload : dict,
+ ) -> HassServiceCall:
+ """Compose the HA service call for a HI control value
+ targeting one HA substate. Raises ValueError when the
+ inputs cannot be resolved to a valid call."""
+ if domain_payload and domain_payload.get( 'substate' ):
+ return cls._substate_service_call(
+ hi_control_value = hi_control_value,
+ domain_payload = domain_payload,
+ )
+
+ domain = domain_payload.get( 'domain' ) if domain_payload else None
+ if not domain:
+ if '.' not in hass_substate_id:
+ raise ValueError( f'Invalid entity_id format: {hass_substate_id}' )
+ domain = hass_substate_id.split( '.', 1 )[ 0 ]
+ logger.warning( f'Missing domain payload for {hass_substate_id},'
+ f' using parsed domain: {domain}' )
+
+ if domain_payload:
+ return cls._payload_driven_service_call(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ hi_control_value = hi_control_value,
+ domain_payload = domain_payload,
+ )
+ return cls._best_effort_service_call(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ hi_control_value = hi_control_value,
+ )
+
+ @classmethod
+ def _substate_service_call(
+ cls,
+ hi_control_value : str,
+ domain_payload : dict,
+ ) -> HassServiceCall:
+ substate = domain_payload[ 'substate' ]
+ parent_entity_id = domain_payload[ 'parent_entity_id' ]
+ domain = domain_payload[ 'domain' ]
+
+ if substate == 'brightness':
+ try:
+ numeric_value = cls.to_ha_numeric_parameter_value( hi_control_value )
+ except ( ValueError, TypeError ):
+ raise ValueError(
+ f'Invalid brightness value: {hi_control_value}'
+ )
+ return HassServiceComposer.for_numeric_best_effort(
+ domain = domain,
+ hass_substate_id = parent_entity_id,
+ numeric_value = numeric_value,
+ )
+
+ if substate == 'color_temp':
+ try:
+ kelvin = int( round( cls.to_ha_numeric_parameter_value( hi_control_value ) ) )
+ except ( ValueError, TypeError ):
+ raise ValueError(
+ f'Invalid color_temp value: {hi_control_value}'
+ )
+ return HassServiceComposer.for_color_temp(
+ domain = domain,
+ parent_entity_id = parent_entity_id,
+ kelvin = kelvin,
+ )
+
+ if substate in ( 'hue', 'saturation' ):
+ try:
+ changed_value = cls.to_ha_numeric_parameter_value( hi_control_value )
+ except ( ValueError, TypeError ):
+ raise ValueError(
+ f'Invalid {substate} value: {hi_control_value}'
+ )
+ partner_substate = 'saturation' if substate == 'hue' else 'hue'
+ partner_int_key = cls._substate_integration_key_for_suffix(
+ parent_entity_id = parent_entity_id,
+ suffix = partner_substate,
+ )
+ partner_value_str = IntegrationConverterHelper.get_latest_state_values(
+ integration_keys = [ partner_int_key ],
+ ).get( partner_int_key )
+ try:
+ partner_value = (
+ float( partner_value_str ) if partner_value_str is not None else None
+ )
+ except ( ValueError, TypeError ):
+ partner_value = None
+ # Defaults when the partner has no cached value yet (e.g.,
+ # before the first poll cycle): saturation=100 keeps the
+ # color visible while hue is being chosen; hue=0 is an
+ # arbitrary fallback whose effect is irrelevant when
+ # saturation=0 and small when saturation is being set
+ # for the first time.
+ if substate == 'hue':
+ hue = changed_value
+ sat = partner_value if partner_value is not None else 100.0
+ else:
+ hue = partner_value if partner_value is not None else 0.0
+ sat = changed_value
+ return HassServiceComposer.for_hs_color(
+ domain = domain,
+ parent_entity_id = parent_entity_id,
+ hue = hue,
+ saturation = sat,
+ )
+
+ raise ValueError( f'Unknown substate: {substate}' )
+
+ @classmethod
+ def _payload_driven_service_call(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ hi_control_value : str,
+ domain_payload : dict,
+ ) -> HassServiceCall:
+ if not domain_payload.get( 'is_controllable', False ):
+ return cls._best_effort_service_call(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ hi_control_value = hi_control_value,
+ )
+
+ if cls._payload_supports_numeric_control( domain_payload ):
+ try:
+ numeric_value = cls.to_ha_numeric_parameter_value( hi_control_value )
+ except ( ValueError, TypeError ):
+ numeric_value = None
+ if numeric_value is not None:
+ return HassServiceComposer.for_numeric_parameter(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ numeric_value = numeric_value,
+ domain_payload = domain_payload,
+ )
+
+ intent = cls.to_ha_on_off_intent( hi_control_value )
+ result = HassServiceComposer.for_payload_intent(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ intent = intent,
+ domain_payload = domain_payload,
+ )
+ if result is None:
+ return cls._best_effort_service_call(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ hi_control_value = hi_control_value,
+ )
+ return result
+
+ @classmethod
+ def _best_effort_service_call(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ hi_control_value : str,
+ ) -> HassServiceCall:
+ try:
+ numeric_value = cls.to_ha_numeric_parameter_value( hi_control_value )
+ except ( ValueError, TypeError ):
+ intent = cls.to_ha_on_off_intent( hi_control_value )
+ return HassServiceComposer.for_on_off_best_effort(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ intent = intent,
+ )
+ return HassServiceComposer.for_numeric_best_effort(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ numeric_value = numeric_value,
+ )
+
+ @classmethod
+ def _payload_supports_numeric_control( cls, domain_payload : dict ) -> bool:
+ return ( domain_payload.get( 'supports_brightness', False )
+ or domain_payload.get( 'set_service' ) is not None )
diff --git a/src/hi/services/hass/hass_models.py b/src/hi/services/hass/hass_models.py
index 01904a65..419ab01a 100644
--- a/src/hi/services/hass/hass_models.py
+++ b/src/hi/services/hass/hass_models.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass
-from typing import Dict
+from typing import Dict, Optional
class HassApi:
@@ -169,7 +169,17 @@ class HassState:
return f'insteon:{self.insteon_address}'
return None
-
+
+@dataclass
+class HassServiceCall:
+ """Outbound HA service call composed from a HI control value."""
+
+ domain : str
+ service : str
+ hass_entity_id : str
+ service_data : Optional[Dict] = None
+
+
class HassDevice:
""" An aggregate of one or more HassStates associated with a single device. """
diff --git a/src/hi/services/hass/hass_service_composer.py b/src/hi/services/hass/hass_service_composer.py
new file mode 100644
index 00000000..aac8eaaa
--- /dev/null
+++ b/src/hi/services/hass/hass_service_composer.py
@@ -0,0 +1,305 @@
+from typing import Optional
+
+from .hass_models import HassApi, HassServiceCall
+
+
+class ControlIntent:
+ """Canonical operator intents flowing across the HI->HA
+ bridge. ``HassConverter.to_ha_on_off_intent`` produces these
+ from HI control values; ``HassServiceComposer`` dispatches
+ on them to pick the right HA service name."""
+
+ ON = 'on'
+ OFF = 'off'
+ OPEN = 'open'
+ CLOSE = 'close'
+
+
+class HassServiceComposer:
+ """Pure HA-side service-call composition. Methods take
+ HA-namespace inputs (already-converted values, payload flags,
+ canonical intents) and produce ``HassServiceCall``. They do
+ not interpret HI control values directly — when an HI value
+ is needed, callers convert via ``HassConverter.to_ha_*``
+ boundary methods first."""
+
+ _PAYLOAD_INTENT_SERVICE_KEYS = {
+ ControlIntent.ON: 'on_service',
+ ControlIntent.OFF: 'off_service',
+ ControlIntent.OPEN: 'open_service',
+ ControlIntent.CLOSE: 'close_service',
+ }
+
+ @classmethod
+ def for_payload_intent(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ intent : str,
+ domain_payload : dict,
+ ) -> Optional[HassServiceCall]:
+ """Compose a service call from the matching ``*_service``
+ field on the payload. Returns None when the payload does
+ not define a service for this intent (caller falls back
+ to best-effort)."""
+ service_key = cls._PAYLOAD_INTENT_SERVICE_KEYS.get( intent )
+ if not service_key:
+ raise ValueError( f'Unknown control intent: {intent}' )
+ service = domain_payload.get( service_key )
+ if not service:
+ return None
+ return HassServiceCall(
+ domain = domain,
+ service = service,
+ hass_entity_id = hass_substate_id,
+ )
+
+ @classmethod
+ def for_on_off_best_effort(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ intent : str,
+ ) -> HassServiceCall:
+ if intent == ControlIntent.ON:
+ service = HassApi.TURN_ON_SERVICE
+ elif intent == ControlIntent.OFF:
+ service = HassApi.TURN_OFF_SERVICE
+ elif intent == ControlIntent.OPEN:
+ if domain == HassApi.COVER_DOMAIN:
+ service = HassApi.OPEN_COVER_SERVICE
+ elif domain == HassApi.LOCK_DOMAIN:
+ service = HassApi.UNLOCK_SERVICE
+ else:
+ service = HassApi.TURN_ON_SERVICE
+ elif intent == ControlIntent.CLOSE:
+ if domain == HassApi.COVER_DOMAIN:
+ service = HassApi.CLOSE_COVER_SERVICE
+ elif domain == HassApi.LOCK_DOMAIN:
+ service = HassApi.LOCK_SERVICE
+ else:
+ service = HassApi.TURN_OFF_SERVICE
+ else:
+ raise ValueError( f'Unknown control intent: {intent}' )
+ return HassServiceCall(
+ domain = domain,
+ service = service,
+ hass_entity_id = hass_substate_id,
+ )
+
+ @classmethod
+ def for_numeric_best_effort(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ numeric_value : float,
+ ) -> HassServiceCall:
+ if domain == HassApi.LIGHT_DOMAIN:
+ brightness_pct = int( numeric_value )
+ if not ( 0 <= brightness_pct <= 100 ):
+ raise ValueError(
+ f'Invalid brightness value: {brightness_pct} (must be 0-100)'
+ )
+ if brightness_pct == 0:
+ return HassServiceCall(
+ domain = domain,
+ service = HassApi.TURN_OFF_SERVICE,
+ hass_entity_id = hass_substate_id,
+ service_data = None,
+ )
+ return HassServiceCall(
+ domain = domain,
+ service = HassApi.TURN_ON_SERVICE,
+ hass_entity_id = hass_substate_id,
+ service_data = { 'brightness_pct': brightness_pct },
+ )
+ if domain == HassApi.CLIMATE_DOMAIN:
+ return HassServiceCall(
+ domain = domain,
+ service = HassApi.SET_TEMPERATURE_SERVICE,
+ hass_entity_id = hass_substate_id,
+ service_data = { 'temperature': numeric_value },
+ )
+ if domain == HassApi.COVER_DOMAIN:
+ position_pct = int( numeric_value )
+ if not ( 0 <= position_pct <= 100 ):
+ raise ValueError(
+ f'Invalid position value: {position_pct} (must be 0-100)'
+ )
+ return HassServiceCall(
+ domain = domain,
+ service = HassApi.SET_COVER_POSITION_SERVICE,
+ hass_entity_id = hass_substate_id,
+ service_data = { 'position': position_pct },
+ )
+ if domain == HassApi.MEDIA_PLAYER_DOMAIN:
+ if not ( 0.0 <= numeric_value <= 1.0 ):
+ raise ValueError(
+ f'Invalid volume value: {numeric_value} (must be 0.0-1.0)'
+ )
+ return HassServiceCall(
+ domain = domain,
+ service = HassApi.VOLUME_SET_SERVICE,
+ hass_entity_id = hass_substate_id,
+ service_data = { 'volume_level': numeric_value },
+ )
+ raise ValueError( f'No numeric control pattern for domain: {domain}' )
+
+ @classmethod
+ def for_numeric_parameter(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ numeric_value : float,
+ domain_payload : dict,
+ ) -> HassServiceCall:
+ if domain_payload.get( 'supports_brightness', False ):
+ return cls.for_brightness(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ brightness = numeric_value,
+ domain_payload = domain_payload,
+ )
+ parameters = domain_payload.get( 'parameters', {} )
+ if 'temperature' in parameters:
+ return cls.for_temperature(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ temperature = numeric_value,
+ domain_payload = domain_payload,
+ )
+ if 'volume_level' in parameters:
+ return cls.for_volume(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ volume = numeric_value,
+ domain_payload = domain_payload,
+ )
+ if 'position' in parameters:
+ return cls.for_position(
+ domain = domain,
+ hass_substate_id = hass_substate_id,
+ position = numeric_value,
+ domain_payload = domain_payload,
+ )
+ if domain_payload.get( 'set_service' ):
+ service = domain_payload[ 'set_service' ]
+ return HassServiceCall(
+ domain = domain,
+ service = service,
+ hass_entity_id = hass_substate_id,
+ service_data = { domain.rstrip( 's' ): numeric_value },
+ )
+ raise ValueError( 'No numeric parameter handling defined' )
+
+ @classmethod
+ def for_brightness(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ brightness : float,
+ domain_payload : dict,
+ ) -> HassServiceCall:
+ brightness_pct = int( brightness )
+ if not ( 0 <= brightness_pct <= 100 ):
+ raise ValueError( f'Invalid brightness value: {brightness}' )
+ if brightness_pct == 0:
+ service = domain_payload.get( 'off_service' )
+ service_data = None
+ else:
+ service = domain_payload.get( 'on_service' )
+ service_data = { 'brightness_pct': brightness_pct }
+ if not service:
+ raise ValueError( 'No service defined for brightness control' )
+ return HassServiceCall(
+ domain = domain,
+ service = service,
+ hass_entity_id = hass_substate_id,
+ service_data = service_data,
+ )
+
+ @classmethod
+ def for_temperature(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ temperature : float,
+ domain_payload : dict,
+ ) -> HassServiceCall:
+ service = domain_payload.get( 'set_service' )
+ if not service:
+ raise ValueError( 'No temperature service defined' )
+ return HassServiceCall(
+ domain = domain,
+ service = service,
+ hass_entity_id = hass_substate_id,
+ service_data = { 'temperature': temperature },
+ )
+
+ @classmethod
+ def for_volume(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ volume : float,
+ domain_payload : dict,
+ ) -> HassServiceCall:
+ if not ( 0.0 <= volume <= 1.0 ):
+ raise ValueError( f'Invalid volume value: {volume} (must be 0.0-1.0)' )
+ service = domain_payload.get( 'set_service', HassApi.VOLUME_SET_SERVICE )
+ return HassServiceCall(
+ domain = domain,
+ service = service,
+ hass_entity_id = hass_substate_id,
+ service_data = { 'volume_level': volume },
+ )
+
+ @classmethod
+ def for_position(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ position : float,
+ domain_payload : dict,
+ ) -> HassServiceCall:
+ position_pct = int( position )
+ if not ( 0 <= position_pct <= 100 ):
+ raise ValueError(
+ f'Invalid position value: {position} (must be 0-100)'
+ )
+ service = domain_payload.get( 'set_service', HassApi.SET_COVER_POSITION_SERVICE )
+ return HassServiceCall(
+ domain = domain,
+ service = service,
+ hass_entity_id = hass_substate_id,
+ service_data = { 'position': position_pct },
+ )
+
+ @classmethod
+ def for_color_temp(
+ cls,
+ domain : str,
+ parent_entity_id : str,
+ kelvin : int,
+ ) -> HassServiceCall:
+ return HassServiceCall(
+ domain = domain,
+ service = HassApi.TURN_ON_SERVICE,
+ hass_entity_id = parent_entity_id,
+ service_data = { 'color_temp_kelvin': kelvin },
+ )
+
+ @classmethod
+ def for_hs_color(
+ cls,
+ domain : str,
+ parent_entity_id : str,
+ hue : float,
+ saturation : float,
+ ) -> HassServiceCall:
+ return HassServiceCall(
+ domain = domain,
+ service = HassApi.TURN_ON_SERVICE,
+ hass_entity_id = parent_entity_id,
+ service_data = { 'hs_color': [ hue, saturation ] },
+ )
diff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.py
index 37672b59..8259bf23 100644
--- a/src/hi/services/hass/monitors.py
+++ b/src/hi/services/hass/monitors.py
@@ -93,16 +93,17 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):
sensor_response_latest_map = dict()
for hass_state in id_to_hass_state_map.values():
- integration_key = HassConverter.hass_state_to_integration_key( hass_state = hass_state )
- sensor_value_str = HassConverter.hass_state_to_sensor_value_str( hass_state )
- if not sensor_value_str:
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ for integration_key, sensor_value_str in value_map.items():
+ if not sensor_value_str:
+ continue
+ sensor_response = SensorResponse(
+ integration_key = integration_key,
+ value = sensor_value_str,
+ timestamp = current_datetime,
+ )
+ sensor_response_latest_map[integration_key] = sensor_response
continue
- sensor_response = SensorResponse(
- integration_key = integration_key,
- value = sensor_value_str,
- timestamp = current_datetime,
- )
- sensor_response_latest_map[integration_key] = sensor_response
continue
await self.sensor_response_manager().update_with_latest_sensor_responses(
diff --git a/src/hi/services/hass/tests/test_dimmer_state_conversion.py b/src/hi/services/hass/tests/test_dimmer_state_conversion.py
index eb8d274d..840ac488 100644
--- a/src/hi/services/hass/tests/test_dimmer_state_conversion.py
+++ b/src/hi/services/hass/tests/test_dimmer_state_conversion.py
@@ -8,7 +8,16 @@ logging.disable(logging.CRITICAL)
class TestDimmerStateConversion(TestCase):
- """Test the dimmer state conversion logic in hass_state_to_sensor_value_str"""
+ """Verify HA light states decompose to the right HI sensor
+ value(s) via ``hass_state_to_sensor_value_map``. The brightness
+ (or on/off) value lives under the bare integration_key; color
+ sub-states live under suffixed keys (covered separately)."""
+
+ @staticmethod
+ def _brightness_value( hass_state ):
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ key = HassConverter.hass_state_to_integration_key( hass_state )
+ return value_map.get( key )
def test_dimmer_light_off_returns_zero(self):
"""Test that dimmer light in 'off' state returns '0'"""
@@ -28,20 +37,19 @@ class TestDimmerStateConversion(TestCase):
entity_name_sans_prefix='dimmer_switch',
entity_name_sans_suffix='dimmer_switch'
)
-
- result = HassConverter.hass_state_to_sensor_value_str(hass_state)
- self.assertEqual(result, "0")
+
+ self.assertEqual( self._brightness_value( hass_state ), "0" )
def test_dimmer_light_on_with_brightness_converts_correctly(self):
"""Test that dimmer light converts HA brightness (1-255) to percentage (0-100)"""
test_cases = [
(255, "100"), # Full brightness
(128, "50"), # Half brightness (rounded)
- (127, "50"), # Half brightness (rounded down)
+ (127, "50"), # Half brightness (rounded down)
(25, "10"), # Low brightness (rounded)
(1, "0"), # Minimum HA brightness maps to 0%
]
-
+
for ha_brightness, expected_pct in test_cases:
with self.subTest(brightness=ha_brightness):
api_dict = {
@@ -60,9 +68,8 @@ class TestDimmerStateConversion(TestCase):
entity_name_sans_prefix='dimmer_switch',
entity_name_sans_suffix='dimmer_switch'
)
-
- result = HassConverter.hass_state_to_sensor_value_str(hass_state)
- self.assertEqual(result, expected_pct)
+
+ self.assertEqual( self._brightness_value( hass_state ), expected_pct )
def test_dimmer_light_on_without_brightness_defaults_to_full(self):
"""Test that dimmer light 'on' with brightness attribute but None value defaults to 100"""
@@ -82,9 +89,8 @@ class TestDimmerStateConversion(TestCase):
entity_name_sans_prefix='dimmer_switch',
entity_name_sans_suffix='dimmer_switch'
)
-
- result = HassConverter.hass_state_to_sensor_value_str(hass_state)
- self.assertEqual(result, "100")
+
+ self.assertEqual( self._brightness_value( hass_state ), "100" )
def test_regular_light_on_off_returns_entity_state_values(self):
"""Test that regular (non-dimmer) lights return EntityStateValue strings"""
@@ -104,10 +110,9 @@ class TestDimmerStateConversion(TestCase):
entity_name_sans_prefix='regular_switch',
entity_name_sans_suffix='regular_switch'
)
-
- result_on = HassConverter.hass_state_to_sensor_value_str(hass_state_on)
- self.assertEqual(result_on, "on") # EntityStateValue.ON (lowercase string representation)
-
+
+ self.assertEqual( self._brightness_value( hass_state_on ), "on" )
+
# Test OFF state (no brightness attribute = not a dimmer)
api_dict_off = {
'entity_id': 'light.regular_switch',
@@ -124,9 +129,8 @@ class TestDimmerStateConversion(TestCase):
entity_name_sans_prefix='regular_switch',
entity_name_sans_suffix='regular_switch'
)
-
- result_off = HassConverter.hass_state_to_sensor_value_str(hass_state_off)
- self.assertEqual(result_off, "off") # EntityStateValue.OFF (lowercase string representation)
+
+ self.assertEqual( self._brightness_value( hass_state_off ), "off" )
def test_invalid_brightness_defaults_to_full(self):
"""Test that invalid brightness values default to full brightness"""
@@ -146,7 +150,5 @@ class TestDimmerStateConversion(TestCase):
entity_name_sans_prefix='dimmer_switch',
entity_name_sans_suffix='dimmer_switch'
)
-
- result = HassConverter.hass_state_to_sensor_value_str(hass_state)
- self.assertEqual(result, "100")
-
+
+ self.assertEqual( self._brightness_value( hass_state ), "100" )
diff --git a/src/hi/services/hass/tests/test_hass_controller.py b/src/hi/services/hass/tests/test_hass_controller.py
index 514c84d8..d69a3ad0 100644
--- a/src/hi/services/hass/tests/test_hass_controller.py
+++ b/src/hi/services/hass/tests/test_hass_controller.py
@@ -52,7 +52,7 @@ class TestHassControllerBehaviorVerification(TestCase):
# Verify the service call was made correctly (system boundary)
self.mock_client.call_service.assert_called_once_with(
- domain='light', service='turn_on', hass_state_id='light.living_room'
+ domain='light', service='turn_on', hass_entity_id='light.living_room', service_data=None
)
def test_do_control_brightness_numeric_conversion_and_service_call(self):
@@ -82,7 +82,7 @@ class TestHassControllerBehaviorVerification(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='light',
service='turn_on',
- hass_state_id='light.dining_room',
+ hass_entity_id='light.dining_room',
service_data={'brightness_pct': 75}
)
@@ -112,7 +112,7 @@ class TestHassControllerBehaviorVerification(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='light',
service='turn_off',
- hass_state_id='light.bedroom',
+ hass_entity_id='light.bedroom',
service_data=None
)
@@ -140,7 +140,7 @@ class TestHassControllerBehaviorVerification(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='media_player',
service='volume_set',
- hass_state_id='media_player.living_room',
+ hass_entity_id='media_player.living_room',
service_data={'volume_level': 0.7}
)
@@ -185,7 +185,7 @@ class TestHassControllerErrorHandlingBehavior(TestCase):
integration_details = IntegrationDetails(key=integration_key)
# Patch the converter to raise an exception
- with patch('hi.services.hass.hass_controller.HassConverter.hass_entity_id_to_state_value_str') as mock_converter:
+ with patch('hi.services.hass.hass_controller.HassConverter.hi_value_to_hass_service_call') as mock_converter:
mock_converter.side_effect = ValueError("Invalid entity format")
result = self.controller.do_control(integration_details, 'on')
@@ -249,7 +249,7 @@ class TestHassControllerDomainRoutingBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='cover',
service='open_cover',
- hass_state_id='cover.garage_door'
+ hass_entity_id='cover.garage_door', service_data=None
)
def test_best_effort_routing_without_payload(self):
@@ -269,7 +269,7 @@ class TestHassControllerDomainRoutingBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='switch',
service='turn_off',
- hass_state_id='switch.outlet'
+ hass_entity_id='switch.outlet', service_data=None
)
def test_payload_domain_overrides_entity_id_domain(self):
@@ -296,7 +296,7 @@ class TestHassControllerDomainRoutingBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='switch', # From payload, not entity_id
service='turn_on',
- hass_state_id='light.misleading_name'
+ hass_entity_id='light.misleading_name', service_data=None
)
def test_climate_temperature_control_with_best_effort(self):
@@ -316,7 +316,7 @@ class TestHassControllerDomainRoutingBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='climate',
service='set_temperature',
- hass_state_id='climate.thermostat',
+ hass_entity_id='climate.thermostat',
service_data={'temperature': 72.5}
)
@@ -367,7 +367,7 @@ class TestHassControllerValueTransformationBehavior(TestCase):
self.assertEqual(result.error_list, [])
self.mock_client.call_service.assert_called_once_with(
- domain='light', service='turn_on', hass_state_id='light.test'
+ domain='light', service='turn_on', hass_entity_id='light.test', service_data=None
)
def test_numeric_one_treated_as_brightness_not_boolean(self):
@@ -387,7 +387,7 @@ class TestHassControllerValueTransformationBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='light',
service='turn_on',
- hass_state_id='light.test',
+ hass_entity_id='light.test',
service_data={'brightness_pct': 1}
)
@@ -412,7 +412,7 @@ class TestHassControllerValueTransformationBehavior(TestCase):
self.assertEqual(result.error_list, [])
self.mock_client.call_service.assert_called_once_with(
- domain='switch', service='turn_off', hass_state_id='switch.test'
+ domain='switch', service='turn_off', hass_entity_id='switch.test', service_data=None
)
def test_numeric_zero_on_switch_returns_error(self):
@@ -455,7 +455,7 @@ class TestHassControllerValueTransformationBehavior(TestCase):
self.assertEqual(result_open.error_list, [])
self.mock_client.call_service.assert_called_with(
- domain='cover', service='open_cover', hass_state_id='cover.garage'
+ domain='cover', service='open_cover', hass_entity_id='cover.garage', service_data=None
)
# Reset and test 'close' maps to close_cover
@@ -466,7 +466,7 @@ class TestHassControllerValueTransformationBehavior(TestCase):
self.assertEqual(result_close.error_list, [])
self.mock_client.call_service.assert_called_with(
- domain='cover', service='close_cover', hass_state_id='cover.garage'
+ domain='cover', service='close_cover', hass_entity_id='cover.garage', service_data=None
)
@@ -481,20 +481,18 @@ class TestHassControllerHttpExceptionHandling(TestCase):
self.controller._hass_manager = self.mock_manager
def test_http_service_call_exception_not_caught_in_best_effort(self):
- """Test that HTTP exceptions in best-effort control are caught and returned as errors"""
+ """Test that HTTP exceptions during do_control are caught and returned as errors"""
integration_key = IntegrationKey(integration_id='hass', integration_name='light.test')
integration_details = IntegrationDetails(key=integration_key) # No payload - triggers best-effort
-
+
# Simulate HTTP failure
self.mock_client.call_service.side_effect = Exception("HTTP 503 Service Unavailable")
-
- # In best-effort mode, exceptions are caught and returned as errors
+
result = self.controller.do_control(integration_details, 'on')
-
+
# Should return error result, not propagate exception
self.assertIsNone(result.new_value)
self.assertTrue(len(result.error_list) > 0)
- self.assertIn('Best-effort control failed', result.error_list[0])
self.assertIn('HTTP 503 Service Unavailable', result.error_list[0])
def test_set_state_http_exception_propagates(self):
@@ -544,7 +542,7 @@ class TestHassControllerNumericValidationBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='light',
service='turn_off',
- hass_state_id='light.dimmer',
+ hass_entity_id='light.dimmer',
service_data=None
)
@@ -559,7 +557,7 @@ class TestHassControllerNumericValidationBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='light',
service='turn_on',
- hass_state_id='light.dimmer',
+ hass_entity_id='light.dimmer',
service_data={'brightness_pct': 100}
)
@@ -629,7 +627,7 @@ class TestHassControllerNumericValidationBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='media_player',
service='volume_set',
- hass_state_id='media_player.speaker',
+ hass_entity_id='media_player.speaker',
service_data={'volume_level': float(volume)}
)
@@ -685,7 +683,7 @@ class TestHassControllerCoverPositionBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='cover',
service='set_cover_position',
- hass_state_id='cover.blinds',
+ hass_entity_id='cover.blinds',
service_data={'position': 50}
)
@@ -749,7 +747,7 @@ class TestHassControllerRealWorldEntityBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='script',
service='turn_on',
- hass_state_id=script_entity
+ hass_entity_id=script_entity, service_data=None
)
def test_sensor_entities_return_error_for_control_attempts(self):
@@ -864,8 +862,8 @@ class TestHassControllerIntegrationBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='light',
service=expected_service,
- hass_state_id='light.living_room',
- **(dict(service_data=expected_data) if expected_data else {})
+ hass_entity_id='light.living_room',
+ service_data=expected_data,
)
def test_lock_domain_uses_lock_unlock_services(self):
@@ -884,7 +882,7 @@ class TestHassControllerIntegrationBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='lock',
service='unlock', # 'open' -> 'unlock' for locks
- hass_state_id='lock.front_door'
+ hass_entity_id='lock.front_door', service_data=None
)
# Test 'close' maps to 'lock' for locks
@@ -898,7 +896,7 @@ class TestHassControllerIntegrationBehavior(TestCase):
self.mock_client.call_service.assert_called_once_with(
domain='lock',
service='lock', # 'close' -> 'lock' for locks
- hass_state_id='lock.front_door'
+ hass_entity_id='lock.front_door', service_data=None
)
@patch('hi.services.hass.hass_mixins.HassManager')
diff --git a/src/hi/services/hass/tests/test_hass_converter_substate.py b/src/hi/services/hass/tests/test_hass_converter_substate.py
new file mode 100644
index 00000000..aae3e76e
--- /dev/null
+++ b/src/hi/services/hass/tests/test_hass_converter_substate.py
@@ -0,0 +1,484 @@
+import logging
+from unittest.mock import patch
+
+from django.test import TestCase
+
+from hi.apps.control.models import Controller
+from hi.apps.entity.enums import EntityStateValue
+from hi.apps.sense.models import Sensor
+from hi.integrations.integration_converter_helper import IntegrationConverterHelper
+from hi.services.hass.hass_converter import HassConverter
+from hi.services.hass.hass_models import HassDevice, HassState
+
+logging.disable(logging.CRITICAL)
+
+
+def _build_color_light_device(
+ device_id='color_bulb', supported_color_modes=None,
+ state='on', brightness=255,
+):
+ supported_color_modes = supported_color_modes or ['hs', 'color_temp']
+ api_dict = {
+ 'entity_id': f'light.{device_id}',
+ 'state': state,
+ 'attributes': {
+ 'friendly_name': device_id.replace('_', ' ').title(),
+ 'supported_color_modes': supported_color_modes,
+ 'color_mode': supported_color_modes[0],
+ 'brightness': brightness,
+ },
+ '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},
+ }
+ hass_state = HassConverter.create_hass_state(api_dict)
+ device = HassDevice(device_id=device_id)
+ device.add_state(hass_state)
+ return device
+
+
+def _make_light_hass_state(api_dict, entity_id='light.x'):
+ return HassState(
+ api_dict=api_dict,
+ entity_id=entity_id,
+ domain='light',
+ entity_name_sans_prefix=entity_id.split('.', 1)[1],
+ entity_name_sans_suffix=entity_id.split('.', 1)[1],
+ )
+
+
+class TestSubstateInboundDecomposition(TestCase):
+ """Verify ``hass_state_to_sensor_value_map`` decomposes one
+ HA light state into the right set of HI integration_keys."""
+
+ def test_dimmer_without_color_modes_returns_only_brightness(self):
+ hass_state = _make_light_hass_state({
+ 'entity_id': 'light.bedroom',
+ 'state': 'on',
+ 'attributes': {
+ 'brightness': 128,
+ 'supported_color_modes': ['brightness'],
+ },
+ }, entity_id='light.bedroom')
+ value_map = HassConverter.hass_state_to_sensor_value_map(hass_state)
+ keys = [k.integration_name for k in value_map.keys()]
+ self.assertEqual(keys, ['light.bedroom'])
+ self.assertEqual(list(value_map.values())[0], '50') # 128/255 ≈ 50%
+
+ def test_color_bulb_with_hs_returns_brightness_plus_hue_saturation(self):
+ hass_state = _make_light_hass_state({
+ 'entity_id': 'light.c',
+ 'state': 'on',
+ 'attributes': {
+ 'brightness': 255,
+ 'hs_color': [180, 75],
+ 'supported_color_modes': ['hs'],
+ },
+ }, entity_id='light.c')
+ value_map = HassConverter.hass_state_to_sensor_value_map(hass_state)
+ keys = sorted(k.integration_name for k in value_map.keys())
+ self.assertEqual(
+ keys,
+ ['light.c~brightness', 'light.c~hue', 'light.c~saturation'],
+ )
+
+ def test_color_bulb_with_color_temp_returns_brightness_plus_kelvin(self):
+ hass_state = _make_light_hass_state({
+ 'entity_id': 'light.c',
+ 'state': 'on',
+ 'attributes': {
+ 'brightness': 200,
+ 'color_temp_kelvin': 4500,
+ 'supported_color_modes': ['color_temp'],
+ },
+ }, entity_id='light.c')
+ value_map = HassConverter.hass_state_to_sensor_value_map(hass_state)
+ keys = sorted(k.integration_name for k in value_map.keys())
+ self.assertEqual(keys, ['light.c~brightness', 'light.c~color_temp'])
+
+ def test_color_bulb_with_both_modes_returns_all_substates(self):
+ hass_state = _make_light_hass_state({
+ 'entity_id': 'light.c',
+ 'state': 'on',
+ 'attributes': {
+ 'brightness': 200,
+ 'hs_color': [240, 60],
+ 'color_temp_kelvin': 4500,
+ 'supported_color_modes': ['hs', 'color_temp'],
+ },
+ }, entity_id='light.c')
+ value_map = HassConverter.hass_state_to_sensor_value_map(hass_state)
+ keys = sorted(k.integration_name for k in value_map.keys())
+ self.assertEqual(
+ keys,
+ [
+ 'light.c~brightness',
+ 'light.c~color_temp',
+ 'light.c~hue',
+ 'light.c~saturation',
+ ],
+ )
+
+ def test_off_state_color_bulb_returns_brightness_zero_and_skips_color(self):
+ # HA omits color attributes when the light is off; substates
+ # whose attribute is absent return None and are skipped from
+ # the value map. Brightness reports 0 at its substate key.
+ hass_state = _make_light_hass_state({
+ 'entity_id': 'light.c',
+ 'state': 'off',
+ 'attributes': {
+ 'supported_color_modes': ['hs', 'color_temp'],
+ },
+ }, entity_id='light.c')
+ value_map = HassConverter.hass_state_to_sensor_value_map(hass_state)
+ keys = [k.integration_name for k in value_map.keys()]
+ self.assertEqual(keys, ['light.c~brightness'])
+ self.assertEqual(list(value_map.values())[0], '0')
+
+
+class TestSubstateOutboundDispatch(TestCase):
+ """Verify ``hi_value_to_hass_service_call`` routes substate
+ payloads to the right HA service call."""
+
+ def test_color_temp_substate_composes_color_temp_kelvin_call(self):
+ service_call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='light.c~color_temp',
+ hi_control_value='4500',
+ domain_payload={
+ 'domain': 'light',
+ 'is_controllable': True,
+ 'substate': 'color_temp',
+ 'parent_entity_id': 'light.c',
+ },
+ )
+ self.assertEqual(service_call.domain, 'light')
+ self.assertEqual(service_call.service, 'turn_on')
+ self.assertEqual(service_call.hass_entity_id, 'light.c')
+ self.assertEqual(service_call.service_data, {'color_temp_kelvin': 4500})
+
+ def test_hue_with_cached_saturation_uses_partner_value(self):
+ with patch.object(
+ IntegrationConverterHelper, 'get_latest_state_values',
+ ) as mock_lookup:
+ # Build a real return value keyed by whatever key
+ # HassConverter constructs internally.
+ captured = {}
+
+ def side_effect(integration_keys):
+ captured['keys'] = integration_keys
+ return {integration_keys[0]: '60'}
+ mock_lookup.side_effect = side_effect
+
+ service_call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='light.c~hue',
+ hi_control_value='180',
+ domain_payload={
+ 'domain': 'light',
+ 'is_controllable': True,
+ 'substate': 'hue',
+ 'parent_entity_id': 'light.c',
+ },
+ )
+
+ partner_key = captured['keys'][0]
+ self.assertEqual(partner_key.integration_name, 'light.c~saturation')
+ self.assertEqual(service_call.service_data, {'hs_color': [180.0, 60.0]})
+
+ def test_saturation_with_cached_hue_uses_partner_value(self):
+ with patch.object(IntegrationConverterHelper, "get_latest_state_values") as mock_lookup:
+ def side_effect(integration_keys):
+ return {integration_keys[0]: '210'}
+ mock_lookup.side_effect = side_effect
+
+ service_call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='light.c~saturation',
+ hi_control_value='75',
+ domain_payload={
+ 'domain': 'light',
+ 'is_controllable': True,
+ 'substate': 'saturation',
+ 'parent_entity_id': 'light.c',
+ },
+ )
+
+ self.assertEqual(service_call.service_data, {'hs_color': [210.0, 75.0]})
+
+ def test_hue_without_cached_partner_defaults_saturation_to_full(self):
+ with patch.object(
+ IntegrationConverterHelper, 'get_latest_state_values',
+ ) as mock_lookup:
+ mock_lookup.side_effect = lambda integration_keys: {integration_keys[0]: None}
+ service_call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='light.c~hue',
+ hi_control_value='90',
+ domain_payload={
+ 'domain': 'light',
+ 'is_controllable': True,
+ 'substate': 'hue',
+ 'parent_entity_id': 'light.c',
+ },
+ )
+ self.assertEqual(service_call.service_data, {'hs_color': [90.0, 100.0]})
+
+ def test_saturation_without_cached_partner_defaults_hue_to_zero(self):
+ with patch.object(IntegrationConverterHelper, "get_latest_state_values") as mock_lookup:
+ mock_lookup.side_effect = lambda integration_keys: {integration_keys[0]: None}
+ service_call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='light.c~saturation',
+ hi_control_value='80',
+ domain_payload={
+ 'domain': 'light',
+ 'is_controllable': True,
+ 'substate': 'saturation',
+ 'parent_entity_id': 'light.c',
+ },
+ )
+ self.assertEqual(service_call.service_data, {'hs_color': [0.0, 80.0]})
+
+ def test_invalid_color_temp_value_raises(self):
+ with self.assertRaises(ValueError):
+ HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='light.c~color_temp',
+ hi_control_value='not-a-number',
+ domain_payload={
+ 'domain': 'light',
+ 'is_controllable': True,
+ 'substate': 'color_temp',
+ 'parent_entity_id': 'light.c',
+ },
+ )
+
+ def test_unknown_substate_kind_raises(self):
+ with self.assertRaises(ValueError):
+ HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='light.c~unknown',
+ hi_control_value='42',
+ domain_payload={
+ 'domain': 'light',
+ 'is_controllable': True,
+ 'substate': 'mystery',
+ 'parent_entity_id': 'light.c',
+ },
+ )
+
+
+class TestBoundaryHelpers(TestCase):
+ """Verify the namespace-marker helpers used by the bridge methods."""
+
+ def test_to_ha_numeric_parameter_value_parses_string(self):
+ self.assertEqual(HassConverter.to_ha_numeric_parameter_value('50'), 50.0)
+ self.assertEqual(HassConverter.to_ha_numeric_parameter_value('0.7'), 0.7)
+
+ def test_to_ha_numeric_parameter_value_rejects_non_numeric(self):
+ with self.assertRaises(ValueError):
+ HassConverter.to_ha_numeric_parameter_value('abc')
+
+ def test_to_ha_on_off_intent_canonicalizes_on_variants(self):
+ for value in ['on', 'ON', 'true', 'TRUE', '1']:
+ self.assertEqual(HassConverter.to_ha_on_off_intent(value), 'on')
+
+ def test_to_ha_on_off_intent_canonicalizes_off_variants(self):
+ for value in ['off', 'OFF', 'false', 'FALSE', '0']:
+ self.assertEqual(HassConverter.to_ha_on_off_intent(value), 'off')
+
+ def test_to_ha_on_off_intent_passes_through_open_close(self):
+ self.assertEqual(HassConverter.to_ha_on_off_intent('open'), 'open')
+ self.assertEqual(HassConverter.to_ha_on_off_intent('close'), 'close')
+
+ def test_to_ha_on_off_intent_rejects_unknown(self):
+ with self.assertRaises(ValueError):
+ HassConverter.to_ha_on_off_intent('maybe')
+
+
+class TestSubstateControllerCreationIdempotency(TestCase):
+ """Verify ``_create_substate_controllers`` is idempotent and
+ that ``update_models_for_hass_device`` symmetrically adds
+ newly-implied substate controllers without duplicating
+ existing ones."""
+
+ def _count_substate_controllers(self, entity):
+ return Controller.objects.filter(
+ entity_state__entity=entity,
+ ).exclude(
+ integration_name=f'light.{entity.integration_name}',
+ ).filter(
+ integration_name__contains='~',
+ ).count()
+
+ def test_initial_create_produces_four_substate_controllers(self):
+ device = _build_color_light_device(
+ device_id='c1',
+ supported_color_modes=['hs', 'color_temp'],
+ )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device,
+ add_alarm_events=False,
+ )
+ substate_controllers = Controller.objects.filter(
+ entity_state__entity=entity,
+ integration_name__contains='~',
+ )
+ suffixes = sorted(
+ c.integration_name.split('~', 1)[1] for c in substate_controllers
+ )
+ self.assertEqual(suffixes, ['brightness', 'color_temp', 'hue', 'saturation'])
+
+ def test_resync_does_not_duplicate_existing_substate_controllers(self):
+ device = _build_color_light_device(
+ device_id='c2',
+ supported_color_modes=['hs', 'color_temp'],
+ )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device, add_alarm_events=False,
+ )
+ before = Controller.objects.filter(
+ entity_state__entity=entity,
+ integration_name__contains='~',
+ ).count()
+ self.assertEqual(before, 4)
+
+ # Re-sync the same device shape — should be a no-op for
+ # substate controller creation.
+ HassConverter.update_models_for_hass_device(
+ entity=entity, hass_device=device,
+ )
+ after = Controller.objects.filter(
+ entity_state__entity=entity,
+ integration_name__contains='~',
+ ).count()
+ self.assertEqual(after, 4)
+
+ def test_resync_creates_newly_implied_substate_controllers(self):
+ # Initial import: brightness-only bulb (no color substates,
+ # brightness at the bare integration_key).
+ device = _build_color_light_device(
+ device_id='c3',
+ supported_color_modes=['brightness'],
+ )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device, add_alarm_events=False,
+ )
+ self.assertEqual(
+ Controller.objects.filter(
+ entity_state__entity=entity,
+ integration_name__contains='~',
+ ).count(),
+ 0,
+ )
+
+ # Bulb gains color modes (firmware update, etc.); re-sync.
+ # Brightness is now a peer substate alongside the new color
+ # ones; the bare-key controller is cleaned up by the
+ # re-sync's seen-keys logic.
+ upgraded_device = _build_color_light_device(
+ device_id='c3',
+ supported_color_modes=['hs', 'color_temp'],
+ )
+ HassConverter.update_models_for_hass_device(
+ entity=entity, hass_device=upgraded_device,
+ )
+ suffixes = sorted(
+ c.integration_name.split('~', 1)[1]
+ for c in Controller.objects.filter(
+ entity_state__entity=entity,
+ integration_name__contains='~',
+ )
+ )
+ self.assertEqual(suffixes, ['brightness', 'color_temp', 'hue', 'saturation'])
+
+
+class TestColorModeSubstate(TestCase):
+ """Behavior specific to the COLOR_MODE substate (sensor-only,
+ discrete-valued, mapped from HA's ``color_mode`` attribute)."""
+
+ def test_color_mode_value_translation(self):
+ """HA's color_mode strings translate to HI EntityStateValue
+ members; null and 'unknown' both map to UNKNOWN."""
+ cases = [
+ ('hs', EntityStateValue.COLOR_MODE_HS),
+ ('color_temp', EntityStateValue.COLOR_MODE_COLOR_TEMP),
+ ('rgb', EntityStateValue.COLOR_MODE_RGB),
+ ('onoff', EntityStateValue.COLOR_MODE_ONOFF),
+ ('brightness', EntityStateValue.COLOR_MODE_BRIGHTNESS),
+ ('white', EntityStateValue.COLOR_MODE_WHITE),
+ (None, EntityStateValue.COLOR_MODE_UNKNOWN),
+ ('unknown', EntityStateValue.COLOR_MODE_UNKNOWN),
+ ]
+ for ha_value, expected_hi_value in cases:
+ with self.subTest(ha_value=ha_value):
+ hass_state = _build_color_light_device(
+ device_id='cm',
+ supported_color_modes=['hs', 'color_temp'],
+ ).hass_state_list[0]
+ hass_state.api_dict['attributes']['color_mode'] = ha_value
+ value_map = HassConverter.hass_state_to_sensor_value_map(hass_state)
+ color_mode_key = next(
+ k for k in value_map if k.integration_name.endswith('~color_mode')
+ )
+ self.assertEqual(value_map[color_mode_key], str(expected_hi_value))
+
+ def test_color_mode_attribute_absent_skipped_from_value_map(self):
+ """When HA omits the ``color_mode`` attribute key entirely,
+ the substate is skipped from the value map (last-known
+ retained), consistent with hue/saturation behavior."""
+ hass_state = _build_color_light_device(
+ device_id='cm2',
+ supported_color_modes=['hs', 'color_temp'],
+ ).hass_state_list[0]
+ # Strip color_mode; the fixture builder sets it by default.
+ del hass_state.api_dict['attributes']['color_mode']
+ value_map = HassConverter.hass_state_to_sensor_value_map(hass_state)
+ color_mode_keys = [
+ k for k in value_map if k.integration_name.endswith('~color_mode')
+ ]
+ self.assertEqual(color_mode_keys, [])
+
+ def test_color_mode_substate_creates_sensor_not_controller(self):
+ """COLOR_MODE is sensor-only — operator can't directly set
+ the mode (HA derives it from whichever attribute was
+ most-recently written)."""
+ device = _build_color_light_device(
+ device_id='cm3',
+ supported_color_modes=['hs', 'color_temp'],
+ )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device, add_alarm_events=False,
+ )
+ # COLOR_MODE substate should exist as a Sensor.
+ self.assertTrue(
+ Sensor.objects.filter(
+ entity_state__entity=entity,
+ integration_name__endswith='~color_mode',
+ ).exists()
+ )
+ # COLOR_MODE substate should NOT exist as a Controller.
+ self.assertFalse(
+ Controller.objects.filter(
+ entity_state__entity=entity,
+ integration_name__endswith='~color_mode',
+ ).exists()
+ )
+
+ def test_resync_does_not_duplicate_color_mode_sensor(self):
+ device = _build_color_light_device(
+ device_id='cm4',
+ supported_color_modes=['hs', 'color_temp'],
+ )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device, add_alarm_events=False,
+ )
+ before = Sensor.objects.filter(
+ entity_state__entity=entity,
+ integration_name__endswith='~color_mode',
+ ).count()
+ self.assertEqual(before, 1)
+
+ HassConverter.update_models_for_hass_device(
+ entity=entity, hass_device=device,
+ )
+ after = Sensor.objects.filter(
+ entity_state__entity=entity,
+ integration_name__endswith='~color_mode',
+ ).count()
+ self.assertEqual(after, 1)
diff --git a/src/hi/services/hass/tests/test_hass_service_composer.py b/src/hi/services/hass/tests/test_hass_service_composer.py
new file mode 100644
index 00000000..3260504b
--- /dev/null
+++ b/src/hi/services/hass/tests/test_hass_service_composer.py
@@ -0,0 +1,319 @@
+import logging
+
+from django.test import TestCase
+
+from hi.services.hass.hass_models import HassServiceCall
+from hi.services.hass.hass_service_composer import HassServiceComposer
+
+logging.disable(logging.CRITICAL)
+
+
+class TestForOnOffBestEffort(TestCase):
+
+ def test_on_intent_maps_to_turn_on(self):
+ result = HassServiceComposer.for_on_off_best_effort(
+ domain='switch', hass_substate_id='switch.x', intent='on',
+ )
+ self.assertEqual(result, HassServiceCall(
+ domain='switch', service='turn_on', hass_entity_id='switch.x',
+ ))
+
+ def test_off_intent_maps_to_turn_off(self):
+ result = HassServiceComposer.for_on_off_best_effort(
+ domain='light', hass_substate_id='light.x', intent='off',
+ )
+ self.assertEqual(result.service, 'turn_off')
+
+ def test_open_on_cover_maps_to_open_cover(self):
+ result = HassServiceComposer.for_on_off_best_effort(
+ domain='cover', hass_substate_id='cover.x', intent='open',
+ )
+ self.assertEqual(result.service, 'open_cover')
+
+ def test_close_on_cover_maps_to_close_cover(self):
+ result = HassServiceComposer.for_on_off_best_effort(
+ domain='cover', hass_substate_id='cover.x', intent='close',
+ )
+ self.assertEqual(result.service, 'close_cover')
+
+ def test_open_on_lock_maps_to_unlock(self):
+ result = HassServiceComposer.for_on_off_best_effort(
+ domain='lock', hass_substate_id='lock.x', intent='open',
+ )
+ self.assertEqual(result.service, 'unlock')
+
+ def test_close_on_lock_maps_to_lock(self):
+ result = HassServiceComposer.for_on_off_best_effort(
+ domain='lock', hass_substate_id='lock.x', intent='close',
+ )
+ self.assertEqual(result.service, 'lock')
+
+ def test_open_on_other_domain_falls_back_to_turn_on(self):
+ result = HassServiceComposer.for_on_off_best_effort(
+ domain='light', hass_substate_id='light.x', intent='open',
+ )
+ self.assertEqual(result.service, 'turn_on')
+
+ def test_close_on_other_domain_falls_back_to_turn_off(self):
+ result = HassServiceComposer.for_on_off_best_effort(
+ domain='light', hass_substate_id='light.x', intent='close',
+ )
+ self.assertEqual(result.service, 'turn_off')
+
+ def test_unknown_intent_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_on_off_best_effort(
+ domain='light', hass_substate_id='light.x', intent='maybe',
+ )
+
+
+class TestForNumericBestEffort(TestCase):
+
+ def test_light_zero_brightness_turns_off(self):
+ result = HassServiceComposer.for_numeric_best_effort(
+ domain='light', hass_substate_id='light.x', numeric_value=0,
+ )
+ self.assertEqual(result.service, 'turn_off')
+ self.assertIsNone(result.service_data)
+
+ def test_light_partial_brightness_turns_on_with_pct(self):
+ result = HassServiceComposer.for_numeric_best_effort(
+ domain='light', hass_substate_id='light.x', numeric_value=50,
+ )
+ self.assertEqual(result.service, 'turn_on')
+ self.assertEqual(result.service_data, {'brightness_pct': 50})
+
+ def test_light_full_brightness_turns_on_with_pct(self):
+ result = HassServiceComposer.for_numeric_best_effort(
+ domain='light', hass_substate_id='light.x', numeric_value=100,
+ )
+ self.assertEqual(result.service_data, {'brightness_pct': 100})
+
+ def test_light_invalid_brightness_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_numeric_best_effort(
+ domain='light', hass_substate_id='light.x', numeric_value=150,
+ )
+
+ def test_climate_temperature_call(self):
+ result = HassServiceComposer.for_numeric_best_effort(
+ domain='climate', hass_substate_id='climate.x', numeric_value=72.5,
+ )
+ self.assertEqual(result.service, 'set_temperature')
+ self.assertEqual(result.service_data, {'temperature': 72.5})
+
+ def test_cover_valid_position(self):
+ result = HassServiceComposer.for_numeric_best_effort(
+ domain='cover', hass_substate_id='cover.x', numeric_value=50,
+ )
+ self.assertEqual(result.service, 'set_cover_position')
+ self.assertEqual(result.service_data, {'position': 50})
+
+ def test_cover_invalid_position_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_numeric_best_effort(
+ domain='cover', hass_substate_id='cover.x', numeric_value=120,
+ )
+
+ def test_media_player_valid_volume(self):
+ result = HassServiceComposer.for_numeric_best_effort(
+ domain='media_player', hass_substate_id='mp.x', numeric_value=0.5,
+ )
+ self.assertEqual(result.service, 'volume_set')
+ self.assertEqual(result.service_data, {'volume_level': 0.5})
+
+ def test_media_player_invalid_volume_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_numeric_best_effort(
+ domain='media_player', hass_substate_id='mp.x', numeric_value=1.5,
+ )
+
+ def test_unknown_domain_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_numeric_best_effort(
+ domain='switch', hass_substate_id='switch.x', numeric_value=42,
+ )
+
+
+class TestForBrightness(TestCase):
+
+ def test_zero_uses_off_service(self):
+ result = HassServiceComposer.for_brightness(
+ domain='light', hass_substate_id='light.x', brightness=0,
+ domain_payload={'on_service': 'turn_on', 'off_service': 'turn_off'},
+ )
+ self.assertEqual(result.service, 'turn_off')
+ self.assertIsNone(result.service_data)
+
+ def test_partial_uses_on_service_with_pct(self):
+ result = HassServiceComposer.for_brightness(
+ domain='light', hass_substate_id='light.x', brightness=75,
+ domain_payload={'on_service': 'turn_on', 'off_service': 'turn_off'},
+ )
+ self.assertEqual(result.service, 'turn_on')
+ self.assertEqual(result.service_data, {'brightness_pct': 75})
+
+ def test_missing_on_service_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_brightness(
+ domain='light', hass_substate_id='light.x', brightness=50,
+ domain_payload={'off_service': 'turn_off'},
+ )
+
+ def test_invalid_range_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_brightness(
+ domain='light', hass_substate_id='light.x', brightness=150,
+ domain_payload={'on_service': 'turn_on'},
+ )
+
+
+class TestForTemperatureVolumePosition(TestCase):
+
+ def test_temperature_uses_set_service(self):
+ result = HassServiceComposer.for_temperature(
+ domain='climate', hass_substate_id='climate.x', temperature=68.0,
+ domain_payload={'set_service': 'set_temperature'},
+ )
+ self.assertEqual(result.service, 'set_temperature')
+ self.assertEqual(result.service_data, {'temperature': 68.0})
+
+ def test_temperature_missing_set_service_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_temperature(
+ domain='climate', hass_substate_id='climate.x', temperature=68.0,
+ domain_payload={},
+ )
+
+ def test_volume_default_service_is_volume_set(self):
+ result = HassServiceComposer.for_volume(
+ domain='media_player', hass_substate_id='mp.x', volume=0.6,
+ domain_payload={},
+ )
+ self.assertEqual(result.service, 'volume_set')
+ self.assertEqual(result.service_data, {'volume_level': 0.6})
+
+ def test_volume_out_of_range_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_volume(
+ domain='media_player', hass_substate_id='mp.x', volume=2.0,
+ domain_payload={},
+ )
+
+ def test_position_default_service_is_set_cover_position(self):
+ result = HassServiceComposer.for_position(
+ domain='cover', hass_substate_id='cover.x', position=42,
+ domain_payload={},
+ )
+ self.assertEqual(result.service, 'set_cover_position')
+ self.assertEqual(result.service_data, {'position': 42})
+
+ def test_position_out_of_range_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_position(
+ domain='cover', hass_substate_id='cover.x', position=200,
+ domain_payload={},
+ )
+
+
+class TestForNumericParameter(TestCase):
+
+ def test_supports_brightness_flag_routes_to_brightness(self):
+ result = HassServiceComposer.for_numeric_parameter(
+ domain='light', hass_substate_id='light.x', numeric_value=50,
+ domain_payload={
+ 'supports_brightness': True,
+ 'on_service': 'turn_on', 'off_service': 'turn_off',
+ },
+ )
+ self.assertEqual(result.service_data, {'brightness_pct': 50})
+
+ def test_temperature_parameter_routes_to_temperature(self):
+ result = HassServiceComposer.for_numeric_parameter(
+ domain='climate', hass_substate_id='climate.x', numeric_value=70,
+ domain_payload={
+ 'parameters': {'temperature': True},
+ 'set_service': 'set_temperature',
+ },
+ )
+ self.assertEqual(result.service, 'set_temperature')
+ self.assertEqual(result.service_data, {'temperature': 70})
+
+ def test_volume_level_parameter_routes_to_volume(self):
+ result = HassServiceComposer.for_numeric_parameter(
+ domain='media_player', hass_substate_id='mp.x', numeric_value=0.4,
+ domain_payload={'parameters': {'volume_level': True}},
+ )
+ self.assertEqual(result.service_data, {'volume_level': 0.4})
+
+ def test_position_parameter_routes_to_position(self):
+ result = HassServiceComposer.for_numeric_parameter(
+ domain='cover', hass_substate_id='cover.x', numeric_value=30,
+ domain_payload={'parameters': {'position': True}},
+ )
+ self.assertEqual(result.service_data, {'position': 30})
+
+ def test_set_service_only_falls_back_to_generic_call(self):
+ result = HassServiceComposer.for_numeric_parameter(
+ domain='climate', hass_substate_id='climate.x', numeric_value=21,
+ domain_payload={'set_service': 'set_value'},
+ )
+ self.assertEqual(result.service, 'set_value')
+ # Generic fallback uses domain.rstrip('s') as key
+ self.assertEqual(result.service_data, {'climate': 21})
+
+ def test_empty_payload_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_numeric_parameter(
+ domain='light', hass_substate_id='light.x', numeric_value=50,
+ domain_payload={},
+ )
+
+
+class TestForPayloadIntent(TestCase):
+
+ def test_intent_with_matching_service_returns_call(self):
+ result = HassServiceComposer.for_payload_intent(
+ domain='light', hass_substate_id='light.x', intent='on',
+ domain_payload={'on_service': 'turn_on'},
+ )
+ self.assertEqual(result, HassServiceCall(
+ domain='light', service='turn_on', hass_entity_id='light.x',
+ ))
+
+ def test_intent_without_matching_service_returns_none(self):
+ result = HassServiceComposer.for_payload_intent(
+ domain='light', hass_substate_id='light.x', intent='on',
+ domain_payload={'off_service': 'turn_off'}, # only off
+ )
+ self.assertIsNone(result)
+
+ def test_unknown_intent_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_payload_intent(
+ domain='light', hass_substate_id='light.x', intent='maybe',
+ domain_payload={'on_service': 'turn_on'},
+ )
+
+
+class TestForColor(TestCase):
+
+ def test_for_color_temp_composes_kelvin_call(self):
+ result = HassServiceComposer.for_color_temp(
+ domain='light', parent_entity_id='light.x', kelvin=4000,
+ )
+ self.assertEqual(result, HassServiceCall(
+ domain='light',
+ service='turn_on',
+ hass_entity_id='light.x',
+ service_data={'color_temp_kelvin': 4000},
+ ))
+
+ def test_for_hs_color_composes_hs_color_list(self):
+ result = HassServiceComposer.for_hs_color(
+ domain='light', parent_entity_id='light.x',
+ hue=180.0, saturation=75.0,
+ )
+ 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')
diff --git a/src/hi/services/homebox/hb_controller.py b/src/hi/services/homebox/hb_controller.py
index 80c60b5a..81ff0eea 100644
--- a/src/hi/services/homebox/hb_controller.py
+++ b/src/hi/services/homebox/hb_controller.py
@@ -14,11 +14,11 @@ class HomeBoxController( IntegrationController, HomeBoxMixin ):
def do_control(
self,
integration_details: IntegrationDetails,
- control_value: str,
+ hi_control_value: str,
) -> IntegrationControlResult:
logger.debug(
f'HomeBox do_control unsupported. details={integration_details},'
- f' value={control_value}'
+ f' value={hi_control_value}'
)
return IntegrationControlResult(
new_value = None,
diff --git a/src/hi/services/zoneminder/zm_controller.py b/src/hi/services/zoneminder/zm_controller.py
index a5843eef..d97421ac 100644
--- a/src/hi/services/zoneminder/zm_controller.py
+++ b/src/hi/services/zoneminder/zm_controller.py
@@ -14,22 +14,22 @@ class ZoneMinderController( IntegrationController, ZoneMinderMixin ):
def do_control( self,
integration_details : IntegrationDetails,
- control_value : str ) -> IntegrationControlResult:
+ hi_control_value : str ) -> IntegrationControlResult:
zm_manager = self.zm_manager()
integration_key = integration_details.key
try:
if integration_key.integration_name == zm_manager.ZM_RUN_STATE_SENSOR_INTEGRATION_NAME:
- return self.set_run_state( run_state_value = control_value )
+ return self.set_run_state( run_state_value = hi_control_value )
if integration_key.integration_name.startswith( zm_manager.MONITOR_FUNCTION_SENSOR_PREFIX ):
m = re.match( r'.+\D(\d+)', integration_key.integration_name )
if m:
return self.set_monitor_function(
monitor_id = m.group(1),
- function_value = control_value,
+ function_value = hi_control_value,
)
- logger.warning( f'ZM action undefined. key={integration_key}, value={control_value}' )
+ logger.warning( f'ZM action undefined. key={integration_key}, value={hi_control_value}' )
raise ValueError( 'Unknown ZM control action.' )
except Exception as e:
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index 23a64660..671f1239 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -265,6 +265,7 @@ PIPELINE = {
'js/antinode.js',
'js/autosize.min.js',
'js/main.js',
+ 'js/controllers.js',
),
'output_filename': 'js/js_before_content.js',
},
diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.py
index 68759a96..fba49b64 100644
--- a/src/hi/simulator/management/commands/seed_sim_profiles.py
+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py
@@ -74,12 +74,14 @@ from django.db import transaction
from hi.simulator.enums import SimEntityType
from hi.simulator.models import DbSimEntity, SimProfile
from hi.simulator.services.hass.sim_models import (
+ HassColorSmartBulbFields,
HassInsteonDimmerLightSwitchFields,
HassInsteonDualBandLightSwitchFields,
HassInsteonLightSwitchFields,
HassInsteonMotionDetectorFields,
HassInsteonOpenCloseSensorFields,
HassInsteonOutletFields,
+ HassSmartBulbFields,
)
from hi.simulator.services.homebox.attachment_catalog import AttachmentTemplate
from hi.simulator.services.homebox.sim_models import (
@@ -335,12 +337,14 @@ class Command(BaseCommand):
def _build_hass_zoo(self, profile: SimProfile) -> int:
# One of every HASS sim entity definition type.
- self._add_hass_light_switch( profile, 'Zoo Light Switch' , '01.BB.01' )
- self._add_hass_dimmer( profile, 'Zoo Dimmer' , '01.BB.02' )
- self._add_hass_dual_band( profile, 'Zoo Dual Band Switch' , '01.BB.03' )
- self._add_hass_motion( profile, 'Zoo Motion' , '01.BB.04' )
- self._add_hass_open_close( profile, 'Zoo Open/Close' , '01.BB.05' )
- self._add_hass_outlet( profile, 'Zoo Outlet' , '01.BB.06' )
+ self._add_hass_light_switch( profile, 'Zoo Light Switch' , '01.BB.01' )
+ self._add_hass_dimmer( profile, 'Zoo Dimmer' , '01.BB.02' )
+ self._add_hass_dual_band( profile, 'Zoo Dual Band Switch' , '01.BB.03' )
+ self._add_hass_motion( profile, 'Zoo Motion' , '01.BB.04' )
+ self._add_hass_open_close( profile, 'Zoo Open/Close' , '01.BB.05' )
+ self._add_hass_outlet( profile, 'Zoo Outlet' , '01.BB.06' )
+ self._add_hass_smart_bulb( profile, 'Zoo Smart Bulb' )
+ self._add_hass_color_smart_bulb( profile, 'Zoo Color Bulb' )
return profile.db_sim_entities.count()
def _build_volume(self, profile: SimProfile) -> int:
@@ -454,6 +458,24 @@ class Command(BaseCommand):
fields_kwargs = {'name': name, 'insteon_address': addr},
)
+ def _add_hass_smart_bulb(self, profile, name):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassSmartBulbFields,
+ sim_entity_type = SimEntityType.LIGHT,
+ fields_kwargs = {'name': name},
+ )
+
+ def _add_hass_color_smart_bulb(self, profile, name):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassColorSmartBulbFields,
+ sim_entity_type = SimEntityType.LIGHT,
+ 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/views.py b/src/hi/simulator/services/hass/api/views.py
index 71d90644..997bd5df 100644
--- a/src/hi/simulator/services/hass/api/views.py
+++ b/src/hi/simulator/services/hass/api/views.py
@@ -7,25 +7,13 @@ from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
+from hi.simulator.services.hass.api_composers import HassApiComposer
+from hi.simulator.services.hass.service_dispatchers import HassServiceDispatcher
from hi.simulator.services.hass.simulator import HassSimulator
logger = logging.getLogger(__name__)
-# Service-call mapping for the limited set of entity types the simulator
-# supports (switches, outlets, dimmer light switches). Keys are
-# (domain, service) tuples; values are the target state value the
-# simulator should set on the addressed entity.
-#
-# Sensors (motion, open/close) are read-only and accept no service calls.
-_SUPPORTED_SERVICES = {
- ( 'switch', 'turn_on' ): 'on',
- ( 'switch', 'turn_off' ): 'off',
- ( 'light', 'turn_on' ): 'on',
- ( 'light', 'turn_off' ): 'off',
-}
-
-
class PingView( View ):
"""
Mirrors the real Home Assistant API root endpoint, which returns a
@@ -44,8 +32,17 @@ class AllStatesView( View ):
def get(self, request, *args, **kwargs):
try:
hass_simulator = HassSimulator()
- hass_sim_state_list = hass_simulator.get_hass_sim_state_list()
- return JsonResponse( [ x.to_api_dict() for x in hass_sim_state_list ], safe = False )
+ # Compose per-entity rather than per-state so devices
+ # whose HA shape is "one entity with attributes from
+ # multiple SimStates" (color smart bulbs, future
+ # climate entities) get collapsed correctly. Devices
+ # without a registered composer use the default
+ # one-state-per-HA-entity behavior, preserving the
+ # existing motion-detector / switch / sensor shapes.
+ api_dicts = []
+ for sim_entity in hass_simulator.sim_entities:
+ api_dicts.extend( HassApiComposer.compose( sim_entity ) )
+ return JsonResponse( api_dicts, safe = False )
except Exception:
logger.exception( 'Problem processing HAss states API request' )
@@ -89,10 +86,10 @@ class ServiceCallView( View ):
The response is a JSON list of state objects for the entities that
were changed.
- Only the services emitted by Home Information's HAss controller for
- the hard-coded simulator entity types (switch/light turn_on/turn_off)
- are supported. Brightness data on light.turn_on is accepted but not
- modeled — the simulator's dimmer states are ON_OFF only.
+ Service-call → SimState translation is delegated to
+ ``HassServiceDispatcher`` so per-device-type behavior (single-state
+ on/off, dimmer brightness, color-bulb hs/temp routing) lives in
+ one place rather than as a hard-coded mapping table here.
"""
def post(self, request, *args, **kwargs):
@@ -105,14 +102,6 @@ class ServiceCallView( View ):
except json.JSONDecodeError as jde:
raise BadRequest( f'Request body is not JSON: {jde}' )
- target_state = _SUPPORTED_SERVICES.get( (domain, service) )
- if target_state is None:
- logger.warning( f'Unsupported HAss service: {domain}.{service}' )
- return JsonResponse(
- { 'message': f'Service {domain}.{service} not supported by simulator' },
- status = 400,
- )
-
entity_id_field = data.get('entity_id')
if not entity_id_field:
raise BadRequest( '"entity_id" is required in service call body.' )
@@ -124,21 +113,40 @@ class ServiceCallView( View ):
hass_simulator = HassSimulator()
changed_states = list()
for hass_entity_id in entity_id_list:
- try:
- sim_state = hass_simulator.set_sim_state_by_hass_entity_id(
- hass_entity_id = hass_entity_id,
- value_str = target_state,
+ sim_entity = hass_simulator.find_sim_entity_by_hass_entity_id(
+ hass_entity_id = hass_entity_id,
+ )
+ if sim_entity is None:
+ # Real HA silently no-ops on unknown entity_ids
+ # in service calls; mirror that behavior.
+ logger.warning( f'HAss entity not found: {hass_entity_id}' )
+ continue
+
+ updates = HassServiceDispatcher.dispatch(
+ sim_entity = sim_entity,
+ domain = domain,
+ service = service,
+ payload = data,
+ )
+ if not updates:
+ logger.warning(
+ f'Unsupported HAss service for {hass_entity_id}: '
+ f'{domain}.{service}'
+ )
+ continue
+
+ for sim_state_id, value_str in updates:
+ sim_state = sim_entity.set_sim_state(
+ sim_state_id = sim_state_id,
+ value_str = value_str,
)
changed_states.append( sim_state.to_api_dict() )
- except KeyError:
- # Real HA silently no-ops on unknown entity_ids in
- # service calls; mirror that behavior.
- logger.warning( f'HAss entity not found: {hass_entity_id}' )
+ continue
continue
logger.debug(
f'HAss service call: {domain}.{service} on {entity_id_list} '
- f'-> {target_state} ({len(changed_states)} changed)'
+ f'({len(changed_states)} state(s) changed)'
)
return JsonResponse( changed_states, safe = False )
diff --git a/src/hi/simulator/services/hass/api_composers.py b/src/hi/simulator/services/hass/api_composers.py
new file mode 100644
index 00000000..0b703521
--- /dev/null
+++ b/src/hi/simulator/services/hass/api_composers.py
@@ -0,0 +1,113 @@
+"""
+HA API entity composition for the simulator.
+
+The simulator's data model is HI-centric: each runtime-mutable
+value HI sees as its own EntityState gets its own SimState (own
+min/max range, own slider in the simulator UI). Real HA, however,
+emits some devices (color smart bulbs, climate entities) as ONE
+HA entity with multiple attributes — not multiple entities. This
+module reconciles the two: a per-device-type composer collapses an
+entity's SimStates into the HA-shape dict(s) emitted by
+``/api/states``.
+
+The default composer keeps the existing one-state-per-HA-entity
+behavior so devices already aligned with HA's shape (motion
+detectors, switches, sensors) are unaffected. Devices whose HA
+shape is "one entity with attributes from N states" register a
+custom composer keyed off their ``SimEntityFields`` class.
+
+The dispatch entrypoint is
+``HassApiComposer.compose(sim_entity)``; ``AllStatesView`` calls
+it per SimEntity and concatenates the results.
+"""
+from typing import Dict, List
+
+from hi.simulator.base_models import SimState
+
+from .sim_models import (
+ HassColorSmartBulbBrightnessState,
+ HassColorSmartBulbColorModeState,
+ HassColorSmartBulbFields,
+)
+
+
+class HassApiComposer:
+ """Namespace for the HA API entity composers and their
+ dispatch. Composers are classmethods so they can reference
+ each other and the registry stays close to the implementations.
+ """
+
+ @classmethod
+ def compose( cls, sim_entity ) -> List[ Dict ]:
+ """Public dispatch. Look up the composer registered for
+ the sim_entity's fields class; fall back to the default
+ (one-state-per-HA-entity) when no specific composer is
+ registered. Returns the list of HA-shape api dicts the
+ ``/api/states`` endpoint should emit for this entity."""
+ fields_class = type( sim_entity.sim_entity_fields )
+ composer_fn = cls._REGISTRY.get( fields_class, cls._default )
+ return composer_fn( sim_entity.sim_state_list )
+
+ @staticmethod
+ def _default( sim_states : List[ SimState ] ) -> List[ Dict ]:
+ """Default emission: each SimState becomes its own HA
+ entity. Used by the motion detector, switches, sensors —
+ anything where the existing one-state-per-entity model
+ already matches real HA's shape."""
+ return [ s.to_api_dict() for s in sim_states ]
+
+ @staticmethod
+ def _color_smart_bulb( sim_states : List[ SimState ] ) -> List[ Dict ]:
+ """Compose a color smart bulb's brightness/hue/saturation/
+ color-temperature SimStates into ONE HA ``light.x`` entity
+ matching real HA's shape. Brightness is the primary state
+ (drives the entity's ``state`` field); others contribute
+ attributes only. Hue+saturation are combined into the
+ standard ``hs_color: [h, s]`` two-element list."""
+ primary_dict = None
+ merged_attrs : Dict = {}
+ color_mode_value = None
+ for state in sim_states:
+ api_dict = state.to_api_dict()
+ if isinstance( state, HassColorSmartBulbBrightnessState ):
+ # Primary — clone its api_dict shape (entity_id,
+ # state, context, last_changed, etc.), then merge
+ # attributes from the other states into its
+ # attributes dict.
+ primary_dict = dict( api_dict )
+ elif isinstance( state, HassColorSmartBulbColorModeState ):
+ color_mode_value = state.value
+ merged_attrs.update( api_dict.get( 'attributes', {} ) )
+ continue
+
+ # Combine the partial hs_hue/hs_saturation contributions
+ # into the standard hs_color two-element list.
+ hue = merged_attrs.pop( '_partial_hs_hue', None )
+ sat = merged_attrs.pop( '_partial_hs_saturation', None )
+ if hue is not None and sat is not None:
+ merged_attrs[ 'hs_color' ] = [ hue, sat ]
+
+ # ``color_mode`` reflects the dedicated SimState — the
+ # service dispatcher writes it when HI sends hs_color or
+ # color_temp_kelvin, and the operator can override it
+ # directly via the simulator UI for edge-case testing.
+ if color_mode_value is not None:
+ merged_attrs[ 'color_mode' ] = color_mode_value
+
+ if primary_dict is None:
+ # No brightness state in the entity — should not
+ # happen in practice with the registered SimEntity
+ # shape, but fall back to default behavior so we
+ # don't drop the device entirely.
+ 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,
+}
diff --git a/src/hi/simulator/services/hass/service_dispatchers.py b/src/hi/simulator/services/hass/service_dispatchers.py
new file mode 100644
index 00000000..86048d47
--- /dev/null
+++ b/src/hi/simulator/services/hass/service_dispatchers.py
@@ -0,0 +1,178 @@
+"""
+HA service-call dispatch for the simulator.
+
+Inverse direction of ``api_composers``: when HA's REST service-call
+endpoint receives ``light.turn_on`` (etc.) the simulator must
+translate the call into one or more SimState updates on the target
+entity. For simple devices (an Insteon switch with one ON_OFF
+SimState) this is a 1-to-1 mapping. For composite devices (color
+smart bulb with brightness/hue/saturation/color-temp SimStates,
+future climate entities with multiple setpoint states) one HA
+service call can carry attributes that route to different
+SimStates within the same entity.
+
+The dispatcher's job is to read the (domain, service, payload)
+shape and emit a list of (sim_state_id, value_str) pairs for the
+caller to apply. Per-device-type registry keyed off
+``SimEntityFields`` class; the default handler covers the simple
+single-state cases (switch on/off, light on/off with optional
+brightness payload), so most device types get correct round-trip
+behavior without registering a custom handler.
+
+Naming: ``brightness`` here refers to HA's 1-255 attribute (or
+``brightness_pct`` 0-100, which the dispatcher converts).
+``hs_color`` is HA's standard ``[hue, saturation]`` two-element
+list. ``color_temp_kelvin`` is degrees Kelvin.
+"""
+from typing import Any, Dict, List, Optional, Tuple
+
+from hi.simulator.enums import SimStateType
+
+from .sim_models import HassColorSmartBulbFields
+
+
+class HassServiceDispatcher:
+ """Namespace for the per-device-type service-call handlers and
+ their dispatch."""
+
+ @classmethod
+ def dispatch( cls,
+ sim_entity,
+ domain : str,
+ service : str,
+ payload : Dict[ str, Any ],
+ ) -> List[ Tuple[ str, str ] ]:
+ """Public dispatch entrypoint. Returns a list of
+ ``(sim_state_id, value_str)`` pairs the caller should apply
+ via ``sim_entity.set_sim_state(...)``. An empty list means
+ the service is unsupported for this entity (caller logs
+ and falls through). Unknown sim_state_ids in the returned
+ list are caller-visible bugs in the handler."""
+ fields_class = type( sim_entity.sim_entity_fields )
+ handler = cls._REGISTRY.get( fields_class, cls._default )
+ return handler( sim_entity, domain, service, payload )
+
+ @staticmethod
+ def _default( sim_entity,
+ domain : str,
+ service : str,
+ payload : Dict[ str, Any ],
+ ) -> List[ Tuple[ str, str ] ]:
+ """Default dispatch for single-state devices.
+
+ Switch / outlet domains: literal ``on``/``off`` value
+ strings on the primary SimState — works for ON_OFF state
+ types whose ``state`` property uses ``str_to_bool``.
+
+ Light domain: brightness-aware. ``turn_on`` with a
+ ``brightness`` or ``brightness_pct`` payload writes the
+ numeric to the primary SimState. ``turn_on`` without a
+ brightness payload turns on at the SimState's max value
+ for CONTINUOUS states (so dimmers light up fully) or the
+ literal ``on`` for ON_OFF states. ``turn_off`` writes 0
+ for CONTINUOUS, ``off`` for ON_OFF — without this, the
+ old hard-coded ``off`` literal would have polluted a
+ CONTINUOUS state's value with a non-numeric string."""
+ if not sim_entity.sim_state_list:
+ return []
+ primary = sim_entity.sim_state_list[ 0 ]
+
+ if ( domain, service ) == ( 'switch', 'turn_on' ):
+ return [ ( primary.sim_state_id, 'on' ) ]
+ if ( domain, service ) == ( 'switch', 'turn_off' ):
+ return [ ( primary.sim_state_id, 'off' ) ]
+
+ if domain == 'light':
+ if service == 'turn_on':
+ value_str = HassServiceDispatcher._extract_brightness_value_str( payload )
+ if value_str is None:
+ if primary.sim_state_type == SimStateType.CONTINUOUS:
+ value_str = str( primary.max_value )
+ else:
+ value_str = 'on'
+ return [ ( primary.sim_state_id, value_str ) ]
+ if service == 'turn_off':
+ if primary.sim_state_type == SimStateType.CONTINUOUS:
+ return [ ( primary.sim_state_id, '0' ) ]
+ return [ ( primary.sim_state_id, 'off' ) ]
+
+ return []
+
+ @staticmethod
+ def _color_smart_bulb( sim_entity,
+ domain : str,
+ service : str,
+ payload : Dict[ str, Any ],
+ ) -> List[ Tuple[ str, str ] ]:
+ """Color smart bulb's ``light.turn_on`` can carry any of
+ ``brightness`` / ``brightness_pct`` / ``hs_color`` /
+ ``color_temp_kelvin`` / ``rgb_color`` — each routes to a
+ different SimState within the bulb. ``turn_off`` sets the
+ brightness state to 0 (the bulb's ``state`` field derives
+ from brightness). With no payload at all, ``turn_on``
+ defaults to full brightness so the bulb actually lights
+ up rather than no-opping."""
+ if domain != 'light':
+ return []
+ if service == 'turn_off':
+ return [ ( 'brightness', '0' ) ]
+ if service != 'turn_on':
+ return []
+
+ updates : List[ Tuple[ str, str ] ] = []
+
+ brightness_value = HassServiceDispatcher._extract_brightness_value_str( payload )
+ if brightness_value is not None:
+ updates.append( ( 'brightness', brightness_value ) )
+
+ hs_color = payload.get( 'hs_color' )
+ if isinstance( hs_color, list ) and len( hs_color ) == 2:
+ updates.append( ( 'hue', str( hs_color[ 0 ] ) ) )
+ updates.append( ( 'saturation', str( hs_color[ 1 ] ) ) )
+ # Mirrors HA's behavior: writing hs_color makes hs the
+ # active color_mode.
+ updates.append( ( 'color_mode', 'hs' ) )
+
+ color_temp = payload.get( 'color_temp_kelvin' )
+ if color_temp is not None:
+ updates.append( ( 'color_temp', str( int( color_temp ) ) ) )
+ updates.append( ( 'color_mode', 'color_temp' ) )
+
+ # ``rgb_color`` is accepted on the wire but not modeled —
+ # the bulb's color is driven by hs_color/color_temp in this
+ # simulator. HI's color picker (Phase 3) chooses one mode
+ # at a time, so leaving rgb out keeps the surface bounded.
+
+ if not updates:
+ # Bare turn_on without payload: light up at full
+ # brightness so the operator sees an effect.
+ updates.append( ( 'brightness', '255' ) )
+ return updates
+
+ @staticmethod
+ def _extract_brightness_value_str( payload : Dict[ str, Any ] ) -> Optional[ str ]:
+ """Read brightness from an HA service-call payload as a
+ string suitable for a CONTINUOUS sim state (HA 0-255).
+ HA accepts either ``brightness`` (1-255 absolute) or
+ ``brightness_pct`` (0-100 percentage); convert pct to
+ the absolute scale so the SimState always holds the
+ absolute value."""
+ if 'brightness' in payload:
+ try:
+ return str( int( payload[ 'brightness' ] ) )
+ except ( TypeError, ValueError ):
+ return None
+ if 'brightness_pct' in payload:
+ try:
+ pct = float( payload[ 'brightness_pct' ] )
+ except ( TypeError, ValueError ):
+ return None
+ return str( round( pct * 255 / 100 ) )
+ return None
+
+
+# Registry built after the class is defined so the staticmethod
+# objects exist as references. Keyed off SimEntityFields class.
+HassServiceDispatcher._REGISTRY = {
+ HassColorSmartBulbFields: HassServiceDispatcher._color_smart_bulb,
+}
diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.py
index 690f3c39..815d3482 100644
--- a/src/hi/simulator/services/hass/sim_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -2,7 +2,7 @@ import base64
from dataclasses import dataclass
import os
import time
-from typing import Dict, List, Tuple
+from typing import ClassVar, Dict, List, Tuple
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.common.utils import str_to_bool
@@ -66,6 +66,40 @@ class HassState( SimState ):
}
+class HassBrightnessHelper:
+ """Conversions between the simulator's stored brightness value
+ (HA's 0-255 numeric string) and the two HA-shape outputs that
+ light states emit: the entity-level ``state`` field
+ (``'on'``/``'off'``) and the ``brightness`` attribute integer.
+ Shared across HASS light state classes (Insteon dimmer, smart
+ bulb, color smart bulb's brightness component)."""
+
+ @staticmethod
+ def value_to_state( value : str ) -> str:
+ """Map a brightness value to the HA ``state`` field. HA
+ reports ``state='on'`` whenever the light is producing any
+ light, ``state='off'`` only when fully off."""
+ try:
+ numeric = int( float( value ) ) if value is not None else 0
+ except ( TypeError, ValueError ):
+ numeric = 0
+ return 'on' if numeric > 0 else 'off'
+
+ @staticmethod
+ def value_to_attr( value : str ) -> int:
+ """Map a brightness value to the integer ``brightness``
+ attribute (1-255). Returns None when the bulb is off so
+ callers can omit the attribute, matching HA's typical
+ off-state shape."""
+ try:
+ numeric = int( float( value ) ) if value is not None else 0
+ except ( TypeError, ValueError ):
+ numeric = 0
+ if numeric <= 0:
+ return None
+ return min( numeric, 255 )
+
+
@dataclass( frozen = True )
class HassInsteonSimEntityFields( SimEntityFields ):
""" Base class for all HAss Insteon devices """
@@ -134,25 +168,52 @@ class HassInsteonDimmerLightSwitchFields( HassInsteonSimEntityFields ):
class HassInsteonDimmerLightLightState( HassInsteonState ):
sim_entity_fields : HassInsteonDimmerLightSwitchFields
- sim_state_type : SimStateType = SimStateType.ON_OFF
+ # CONTINUOUS so the operator can set arbitrary brightness via
+ # the simulator's range slider. Value is a string-encoded int
+ # in HA's 1-255 brightness range; 0 means off. Without this
+ # change HI's _has_brightness_capability check failed (no
+ # ``brightness`` in attributes) and the entity imported as
+ # ON_OFF rather than LIGHT_DIMMER, leaving the existing
+ # ``controller_light_dimmer.html`` slider unreachable for
+ # HASS-imported dimmers.
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
sim_state_id : str = 'light'
+ value : str = '255'
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 255
@property
def name(self):
return f'{self.entity_name} Light'
-
+
@property
def entity_id(self):
return 'light.switchlinc_dimmer_%s' % self.insteon_address_id_suffix
-
+
+ @property
+ def state(self):
+ return HassBrightnessHelper.value_to_state( self.value )
+
@property
def attributes(self) -> Dict[ str, str ]:
- return {
+ attrs = {
'friendly_name': self.entity_name,
"icon": "mdi:lightbulb",
"insteon_address": self.insteon_address,
"insteon_group": 1,
+ "supported_color_modes": [ "brightness" ],
}
+ brightness = HassBrightnessHelper.value_to_attr( self.value )
+ if brightness is not None:
+ attrs[ "brightness" ] = brightness
+ attrs[ "color_mode" ] = "brightness"
+ return attrs
@dataclass( frozen = True )
@@ -326,6 +387,313 @@ class HassInsteonOutletState( HassInsteonState ):
}
+# --------------------------------------------------------------------------
+# Non-Insteon HASS device variants
+# --------------------------------------------------------------------------
+#
+# Smart bulbs (Hue-, Lifx-, Wyze-style) are dedicated lighting
+# products HA exposes via the ``light`` domain with brightness and
+# (for color bulbs) color attributes. They are not switches wired
+# to fixtures, so they do NOT inherit from ``HassInsteonState`` —
+# bulbs carry no Insteon address / group, and inheriting would
+# leak those Insteon-flavored attributes into the API output and
+# mask issues in HI's vendor-neutral attribute path.
+#
+# The simulator's data model is HI-centric: each runtime-mutable
+# value HI sees as its own EntityState gets its own SimState here,
+# with its own min/max range and slider in the simulator UI. Real
+# HA, however, models a color bulb as ONE entity with multiple
+# attributes — see ``api_composers.py`` for the per-device-type
+# composer that collapses the multi-state HI shape to HA's flat-
+# attribute shape on emit.
+
+
+@dataclass( frozen = True )
+class HassSmartBulbFields( SimEntityFields ):
+ """A brightness-only smart bulb. No color attributes — that
+ variant is ``HassColorSmartBulbFields`` below. One SimState
+ per device, so this device uses the default API composer
+ (one-state-per-HA-entity)."""
+ pass
+
+
+@dataclass
+class HassSmartBulbState( HassState ):
+ """Single CONTINUOUS brightness state in HA's 0-255 range.
+ ``state`` is derived (``on`` when brightness > 0, else
+ ``off``); ``brightness`` is omitted from attributes when off,
+ matching HA's typical off-state shape."""
+
+ sim_entity_fields : HassSmartBulbFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'light'
+ value : str = '255'
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 255
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Brightness'
+
+ @property
+ def entity_id(self):
+ suffix = self.entity_name.lower().replace( ' ', '_' )
+ return f'light.smart_bulb_{suffix}'
+
+ @property
+ def state(self):
+ return HassBrightnessHelper.value_to_state( self.value )
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ attrs = {
+ 'friendly_name': self.entity_name,
+ 'icon': 'mdi:lightbulb',
+ 'supported_color_modes': [ 'brightness' ],
+ }
+ brightness = HassBrightnessHelper.value_to_attr( self.value )
+ if brightness is not None:
+ attrs[ 'brightness' ] = brightness
+ attrs[ 'color_mode' ] = 'brightness'
+ return attrs
+
+
+@dataclass( frozen = True )
+class HassColorSmartBulbFields( SimEntityFields ):
+ """A color smart bulb. Composed of multiple SimStates
+ (brightness, hue, saturation, color temperature) collapsed
+ into one HA entity at emit time by ``api_composers``."""
+ pass
+
+
+def _color_bulb_entity_id( name : str ) -> str:
+ suffix = name.lower().replace( ' ', '_' )
+ return f'light.color_bulb_{suffix}'
+
+
+@dataclass
+class HassColorSmartBulbBrightnessState( HassState ):
+ """Brightness component of a color smart bulb (CONTINUOUS,
+ 0-255). Drives the HA entity's ``state`` (on/off) and the
+ ``brightness`` attribute. Designated as the primary state in
+ the color-bulb composer (its ``state`` field becomes the
+ composed entity's ``state`` field)."""
+
+ sim_entity_fields : HassColorSmartBulbFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'brightness'
+ value : str = '255'
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 255
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Brightness'
+
+ @property
+ def entity_id(self):
+ return _color_bulb_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return HassBrightnessHelper.value_to_state( self.value )
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ # The composer combines this state's contributions with
+ # those of the other color-bulb states; we return only
+ # this state's piece of the attribute dict.
+ attrs = {
+ 'friendly_name': self.entity_name,
+ 'icon': 'mdi:lightbulb',
+ 'supported_color_modes': [ 'hs', 'color_temp', 'rgb' ],
+ }
+ brightness = HassBrightnessHelper.value_to_attr( self.value )
+ if brightness is not None:
+ attrs[ 'brightness' ] = brightness
+ return attrs
+
+
+@dataclass
+class HassColorSmartBulbHueState( HassState ):
+ """Hue component (CONTINUOUS, 0-360 degrees). Combined with
+ the saturation state into ``hs_color: [hue, saturation]`` by
+ the color-bulb composer."""
+
+ sim_entity_fields : HassColorSmartBulbFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'hue'
+ value : str = '60'
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 360
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Hue'
+
+ @property
+ def entity_id(self):
+ return _color_bulb_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ # Composer ignores this state's ``state`` field; only the
+ # primary (brightness) state's value drives the entity's
+ # state. Returning a placeholder keeps the HassState
+ # contract satisfied for any direct callers.
+ return 'on'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ # Hue and saturation must compose into ``hs_color: [h, s]``;
+ # neither alone has the full pair. Return the hue under a
+ # private key the composer combines with the saturation
+ # state's contribution into a single ``hs_color`` attribute.
+ return { '_partial_hs_hue': float( self.value ) }
+
+
+@dataclass
+class HassColorSmartBulbSaturationState( HassState ):
+ """Saturation component (CONTINUOUS, 0-100 percent). Pairs
+ with the hue state to compose ``hs_color``."""
+
+ sim_entity_fields : HassColorSmartBulbFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'saturation'
+ value : str = '100'
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 100
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Saturation'
+
+ @property
+ def entity_id(self):
+ return _color_bulb_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'on'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return { '_partial_hs_saturation': float( self.value ) }
+
+
+@dataclass
+class HassColorSmartBulbColorTempState( HassState ):
+ """Color temperature component (CONTINUOUS, 2000-6500 Kelvin
+ — HA's typical light range, warm to cool white). Emits
+ ``color_temp_kelvin`` directly; no composition needed."""
+
+ sim_entity_fields : HassColorSmartBulbFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'color_temp'
+ value : str = '4000'
+
+ @property
+ def min_value(self):
+ return 2000
+
+ @property
+ def max_value(self):
+ return 6500
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Color Temp'
+
+ @property
+ def entity_id(self):
+ return _color_bulb_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'on'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return { 'color_temp_kelvin': int( float( self.value ) ) }
+
+
+@dataclass
+class HassColorSmartBulbColorModeState( HassState ):
+ """Active color mode (DISCRETE). HA reports this as the
+ ``color_mode`` attribute and derives it from whichever color
+ attribute was most recently written; the simulator's service
+ dispatcher mirrors that by writing this state when it sees
+ ``hs_color`` or ``color_temp_kelvin`` on a service call. The
+ simulator also exposes the dropdown directly so a tester can
+ reach edge values (e.g., ``unknown``, ``rgbww``) without
+ having to drive every mode through HI's controllers."""
+
+ COLOR_MODE_CHOICES : ClassVar[ List[ Tuple[ str, str ] ] ] = [
+ ( 'unknown', 'Unknown' ),
+ ( 'onoff', 'On/Off' ),
+ ( 'brightness', 'Brightness' ),
+ ( 'color_temp', 'Color Temperature' ),
+ ( 'hs', 'HS Color' ),
+ ( 'rgb', 'RGB Color' ),
+ ( 'rgbw', 'RGBW Color' ),
+ ( 'rgbww', 'RGBWW Color' ),
+ ( 'xy', 'XY Color' ),
+ ( 'white', 'White' ),
+ ]
+
+ sim_entity_fields : HassColorSmartBulbFields
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ sim_state_id : str = 'color_mode'
+ value : str = 'hs'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Color Mode'
+
+ @property
+ def entity_id(self):
+ return _color_bulb_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'on'
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ] ]:
+ return self.COLOR_MODE_CHOICES
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ # Composer reads this state's value as the entity-level
+ # ``color_mode`` attribute; emit nothing per-state to
+ # avoid duplicate keys when the composer merges.
+ return {}
+
+
HASS_SIM_ENTITY_DEFINITION_LIST = [
SimEntityDefinition(
class_label = 'Insteon Switch',
@@ -383,4 +751,28 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [
HassInsteonOutletState,
],
),
+ SimEntityDefinition(
+ class_label = 'Smart Bulb (brightness)',
+ sim_entity_type = SimEntityType.LIGHT,
+ sim_entity_fields_class = HassSmartBulbFields,
+ sim_state_class_list = [
+ HassSmartBulbState,
+ ],
+ ),
+ SimEntityDefinition(
+ class_label = 'Smart Bulb (color)',
+ sim_entity_type = SimEntityType.LIGHT,
+ sim_entity_fields_class = HassColorSmartBulbFields,
+ sim_state_class_list = [
+ # Order matters: ``api_composers`` treats the first
+ # state (brightness) as the primary, taking its
+ # ``state`` field for the composed HA entity. The
+ # other states only contribute attributes.
+ HassColorSmartBulbBrightnessState,
+ HassColorSmartBulbHueState,
+ HassColorSmartBulbSaturationState,
+ HassColorSmartBulbColorTempState,
+ HassColorSmartBulbColorModeState,
+ ],
+ ),
]
diff --git a/src/hi/simulator/services/hass/simulator.py b/src/hi/simulator/services/hass/simulator.py
index 6038cc6e..87073dd0 100644
--- a/src/hi/simulator/services/hass/simulator.py
+++ b/src/hi/simulator/services/hass/simulator.py
@@ -38,6 +38,20 @@ class HassSimulator( Simulator ):
continue
continue
raise KeyError( f'HAss entity {hass_entity_id} does not exist.' )
+
+ def find_sim_entity_by_hass_entity_id( self, hass_entity_id : str ) -> SimEntity:
+ """Locate the SimEntity that owns a SimState with the given
+ HA entity_id, or return None if no match. Used by the
+ service-call dispatcher to map an incoming HA service call
+ to the right per-device-type handler — the handler then
+ decides which of the entity's SimStates to update and how."""
+ for sim_entity in self._sim_entity_map.values():
+ for sim_state in sim_entity.sim_state_list:
+ if sim_state.entity_id == hass_entity_id:
+ return sim_entity
+ continue
+ continue
+ return None
@property
def sim_entity_definition_list(self) -> List[ SimEntityDefinition ]:
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_continuous.html b/src/hi/simulator/templates/simulator/panes/sim_control_continuous.html
new file mode 100644
index 00000000..ea6995c7
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/sim_control_continuous.html
@@ -0,0 +1,12 @@
+<div class="continuous-control d-flex align-items-center">
+ <span class="mr-2">{{ sim_state.min_value }}</span>
+ <input type="range"
+ name="value"
+ min="{{ sim_state.min_value }}"
+ max="{{ sim_state.max_value }}"
+ value="{{ sim_state.value }}"
+ oninput="this.nextElementSibling.value=this.value"
+ onchange-async="true">
+ <output class="ml-2" style="min-width: 3em; text-align: right;">{{ sim_state.value }}</output>
+ <span class="ml-2">{{ sim_state.max_value }}</span>
+</div>
diff --git a/src/hi/static/css/control.css b/src/hi/static/css/control.css
index 7d337897..f88e33e7 100644
--- a/src/hi/static/css/control.css
+++ b/src/hi/static/css/control.css
@@ -3,7 +3,7 @@
/* Common Control Container Styles */
.on-off-control,
.discrete-control,
-.brightness-control {
+.hi-continuous-slider-control {
display: flex;
flex-direction: column;
align-items: center;
@@ -126,16 +126,11 @@
color: var(--text-color, #333);
}
-/* Light Dimmer Controller Styles */
-.brightness-control {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 0.5rem;
- padding: 0.5rem;
-}
-
-.brightness-slider {
+/* Continuous-slider widget shared base. Used by brightness,
+ hue, saturation, and color temperature sliders. Per-slider
+ classes contribute the track gradient that gives the operator
+ a visual reference for what the numeric value means. */
+.hi-continuous-slider {
width: 200px;
height: 6px;
border-radius: 3px;
@@ -145,7 +140,7 @@
cursor: pointer;
}
-.brightness-slider::-webkit-slider-thumb {
+.hi-continuous-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
@@ -157,7 +152,7 @@
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
-.brightness-slider::-moz-range-thumb {
+.hi-continuous-slider::-moz-range-thumb {
width: 20px;
height: 20px;
border-radius: 50%;
@@ -167,51 +162,72 @@
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
-.brightness-slider::-webkit-slider-track {
+.hi-continuous-slider::-moz-range-track {
height: 6px;
border-radius: 3px;
- background: #ccc;
+ background: inherit;
+ border: none;
}
-.brightness-slider::-moz-range-track {
- height: 6px;
- border-radius: 3px;
- background: #ccc;
- border: none;
+.hi-continuous-slider:focus {
+ box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
+}
+
+.hi-continuous-slider:hover::-webkit-slider-thumb {
+ transform: scale(1.1);
+}
+
+.hi-continuous-slider:hover::-moz-range-thumb {
+ transform: scale(1.1);
}
-.brightness-display {
+.hi-continuous-slider-display {
display: flex;
align-items: center;
gap: 1rem;
}
-.brightness-value {
+.hi-continuous-slider-value {
font-weight: bold;
min-width: 3rem;
text-align: center;
font-size: 0.9rem;
}
-.brightness-buttons {
+.hi-continuous-slider-presets {
display: flex;
gap: 0.5rem;
}
-.brightness-btn {
+.hi-continuous-slider-preset-btn {
min-width: 3rem;
font-size: 0.8rem;
}
-/* Focus and active states */
-.brightness-slider:focus {
- box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
+/* Per-slider track gradients. These give a visual reference
+ for the numeric scale without claiming to depict the bulb's
+ current rendered color (the bulb may be in color_temp mode
+ while the operator is dragging the hue slider). */
+
+.hue-slider {
+ background: linear-gradient(to right,
+ hsl(0, 100%, 50%),
+ hsl(60, 100%, 50%),
+ hsl(120, 100%, 50%),
+ hsl(180, 100%, 50%),
+ hsl(240, 100%, 50%),
+ hsl(300, 100%, 50%),
+ hsl(360, 100%, 50%));
}
-.brightness-slider:hover::-webkit-slider-thumb {
- transform: scale(1.1);
+.saturation-slider {
+ background: linear-gradient(to right, #999999, #cc4040);
}
-.brightness-slider:hover::-moz-range-thumb {
- transform: scale(1.1);
+.color-temperature-slider {
+ background: linear-gradient(to right,
+ #ff9d4d 0%,
+ #ffd9b3 33%,
+ #ffffff 66%,
+ #cce0ff 100%);
}
\ No newline at end of file
diff --git a/src/hi/static/js/controllers.js b/src/hi/static/js/controllers.js
new file mode 100644
index 00000000..ac03cc17
--- /dev/null
+++ b/src/hi/static/js/controllers.js
@@ -0,0 +1,153 @@
+/*
+ * Home Information - Controller widget interaction
+ *
+ * Two responsibilities:
+ *
+ * 1. Wire UI affordances on controller templates that need
+ * behavior beyond what antinode's onchange-async handler
+ * provides (e.g., the dimmer's Off / Full convenience
+ * buttons that drive the brightness slider).
+ *
+ * 2. Apply server-pushed controller values to widgets via
+ * ``Hi.controllers.applyValueMap`` — called by the polling
+ * layer with the ``cssControllerValueMap`` from the status
+ * response. Each map entry is a class-name → value pair;
+ * every element matching the class gets its widget property
+ * updated (slider ``.value``, checkbox ``.checked``,
+ * ``<select>`` ``.value``, etc.).
+ *
+ * The controller-value path is parallel to the existing CSS-class
+ * status path (status drives icon styling via attributes; values
+ * drive interactive widget state via DOM properties). Replaces
+ * the older checkbox+select special-cases that were inlined in
+ * status.js's CSS-class-update handler.
+ */
+(function() {
+ 'use strict';
+
+ window.Hi = window.Hi || {};
+ Hi.controllers = Hi.controllers || {};
+
+ /**
+ * Apply a class-name → controller-value map by finding each
+ * matching element and updating the appropriate widget
+ * property. Only applies updates when the new value differs
+ * from the widget's current state — avoids interfering with
+ * an in-progress user interaction (e.g., a slider mid-drag
+ * whose optimistic update already matches the polled value).
+ *
+ * @param {Object} controllerValueMap - { className: value }
+ */
+ Hi.controllers.applyValueMap = function( controllerValueMap ) {
+ if ( !controllerValueMap ) return;
+ Object.entries( controllerValueMap ).forEach( function( [ cssClass, value ] ) {
+ const $elements = $( '.' + cssClass );
+ $elements.each( function() {
+ _applyValueToElement( this, value );
+ });
+ });
+ };
+
+ function _applyValueToElement( element, value ) {
+ const tag = element.tagName;
+ if ( tag === 'INPUT' ) {
+ const type = element.type;
+ if ( type === 'range' || type === 'number' || type === 'text' ) {
+ _setIfDifferent( element, 'value', String( value ) );
+ _syncSliderDisplay( element );
+ return;
+ }
+ if ( type === 'checkbox' ) {
+ const checked = _coerceCheckboxValue( value );
+ if ( element.checked !== checked ) {
+ element.checked = checked;
+ }
+ return;
+ }
+ }
+ if ( tag === 'SELECT' ) {
+ _setIfDifferent( element, 'value', String( value ) );
+ return;
+ }
+ // Other shapes (color picker, etc.) get their own branches
+ // here as widgets are added. Silently no-op so unrelated
+ // class-targeted elements (e.g., the wrapper div sharing
+ // the same class for CSS purposes) are unaffected.
+ }
+
+ function _syncSliderDisplay( slider ) {
+ // Mirror a slider's current value into a paired display
+ // element. Sliders opt in by declaring two data
+ // attributes on the ``<input type=range>``:
+ //
+ // Hi.CONTROLLER_DISPLAY_TARGET_ATTR CSS selector for
+ // the display element, looked up within the
+ // enclosing form.
+ // Hi.CONTROLLER_DISPLAY_FORMAT_ATTR Format string with
+ // ``{n}`` as the value placeholder, e.g. ``{n}%``,
+ // ``{n}°``, ``{n}K``. Optional; defaults to ``{n}``.
+ //
+ // Attribute names are defined in DIVID (server) and
+ // mirrored in main.js (client) — templates emit them via
+ // the DIVID entries and this code reads them via Hi.
+ //
+ // Called whenever the slider's value changes (drag,
+ // button click, controller-value polling) so the
+ // displayed value stays in lock-step with the thumb.
+ const selector = slider.getAttribute( Hi.CONTROLLER_DISPLAY_TARGET_ATTR );
+ if ( ! selector ) return;
+ const $display = $( slider ).closest( 'form' ).find( selector );
+ if ( ! $display.length ) return;
+ const format = slider.getAttribute( Hi.CONTROLLER_DISPLAY_FORMAT_ATTR ) || '{n}';
+ $display.text( format.replace( '{n}', slider.value ) );
+ }
+
+ function _setIfDifferent( element, prop, newValue ) {
+ if ( element[ prop ] !== newValue ) {
+ element[ prop ] = newValue;
+ }
+ }
+
+ function _coerceCheckboxValue( value ) {
+ if ( typeof value === 'boolean' ) return value;
+ if ( typeof value === 'number' ) return value !== 0;
+ if ( typeof value === 'string' ) {
+ const lowered = value.toLowerCase();
+ return lowered === 'on' || lowered === 'true' || lowered === '1';
+ }
+ return Boolean( value );
+ }
+
+ jQuery(function($) {
+ // Continuous-slider preset buttons (e.g., the dimmer's
+ // Off/Full). The button's ``data-value`` is written to
+ // the sibling slider and ``change`` is triggered so
+ // antinode's ``onchange-async`` handler submits the form
+ // — identical round-trip to dragging the slider.
+ $('body').on(
+ 'click',
+ `.${Hi.CONTROLLER_PRESET_BTN_CLASS}`,
+ function() {
+ const $btn = $(this);
+ const $slider = $btn.closest( `.${Hi.CONTROLLER_SLIDER_CONTROL_CLASS}` )
+ .find( `.${Hi.CONTROLLER_SLIDER_CLASS}` );
+ $slider.val( $btn.attr( Hi.DATA_VALUE_ATTR ) ).trigger( 'change' );
+ _syncSliderDisplay( $slider[ 0 ] );
+ }
+ );
+
+ // Mirror the value into the display element as the
+ // operator drags any slider that opted in. ``input``
+ // fires continuously during a drag; ``change`` only
+ // fires on release, which would let the displayed value
+ // lag behind the thumb position.
+ $('body').on(
+ 'input',
+ `input[type=range][${Hi.CONTROLLER_DISPLAY_TARGET_ATTR}]`,
+ function() {
+ _syncSliderDisplay( this );
+ }
+ );
+ });
+
+})();
diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.js
index 1b4fbd69..27fe507d 100644
--- a/src/hi/static/js/main.js
+++ b/src/hi/static/js/main.js
@@ -127,6 +127,17 @@
DATA_ORIGINAL_VALUE_ATTR: 'data-original-value',
ATTR_V2_DELETE_FILE_ATTR: 'delete_file_attribute',
+ // Controller widgets - Class names and data attributes
+ // shared between controller templates (server-emitted)
+ // and controllers.js (client-side display sync, preset
+ // buttons). Mirror of DIVID entries in src/hi/constants.py.
+ CONTROLLER_DISPLAY_TARGET_ATTR: 'data-display-target',
+ CONTROLLER_DISPLAY_FORMAT_ATTR: 'data-display-format',
+ CONTROLLER_SLIDER_CLASS: 'hi-continuous-slider',
+ CONTROLLER_SLIDER_CONTROL_CLASS: 'hi-continuous-slider-control',
+ CONTROLLER_PRESET_BTN_CLASS: 'hi-continuous-slider-preset-btn',
+ DATA_VALUE_ATTR: 'data-value',
+
// Entity Picker - selectors for JavaScript dependencies
ENTITY_PICKER_FILTERABLE_ITEM_SELECTOR: '.filterable-item',
ENTITY_PICKER_GROUP_SECTION_SELECTOR: '.entity-group-section',
diff --git a/src/hi/static/js/status.js b/src/hi/static/js/status.js
index b8de0d6e..f4aa5087 100644
--- a/src/hi/static/js/status.js
+++ b/src/hi/static/js/status.js
@@ -31,6 +31,7 @@
const ServerTimestampAttr = 'timestamp';
const LastServerTimestampAttr = 'lastTimestamp';
const CssClassUpdateMapAttr = 'cssClassUpdateMap';
+ const CssControllerValueMapAttr = 'cssControllerValueMap';
const IdReplaceUpdateMapAttr = 'idReplaceUpdateMap';
const IdReplaceHashMapAttr = 'idReplaceHashMap';
const ConsoleLockedAttr = 'consoleLocked';
@@ -148,6 +149,9 @@
if ( CssClassUpdateMapAttr in respObj ) {
handleCssClassUpdates( respObj[CssClassUpdateMapAttr] );
}
+ if ( CssControllerValueMapAttr in respObj ) {
+ Hi.controllers.applyValueMap( respObj[CssControllerValueMapAttr] );
+ }
if ( TransientViewSuggestionAttr in respObj ) {
handleTransientViewSuggestion( respObj[TransientViewSuggestionAttr] );
}
@@ -238,11 +242,18 @@
}
function handleCssClassUpdates( updateMap ) {
-
+ // Apply attribute updates (the bucketed status string and
+ // peers) for CSS-driven visual styling. Widget-state
+ // updates (slider position, checkbox checked, select value)
+ // come through the parallel controller-value path; see
+ // ``Hi.controllers.applyValueMap`` in controllers.js.
+ // The descendent ``div[status]`` text-update branch is
+ // preserved here because its purpose is visual (showing
+ // the bucketed status as text), not widget control.
for ( let cssClass in updateMap ) {
let elements = getElementsByCssClass( cssClass );
let attrMap = updateMap[cssClass];
- for ( let attrName in attrMap ) {
+ for ( let attrName in attrMap ) {
let attrValue = attrMap[attrName];
elements.each( function() {
if (this.hasAttribute(attrName)) {
@@ -250,28 +261,11 @@
if ( attrValue != null && ( currentValue !== String(attrValue) )) {
$(this).attr( attrName, attrValue );
}
- } else {
- // Special cases:
- // - descendent SELECT tag - assume select value is sensor value
- // - descendent checkbox - assumes status value 'on' when checked
- // - descendent DIV tag with status attr - assume attr and text needs updating
- //
- if ( attrName == 'status' ) {
- $(this).find('select').val( attrValue );
-
- $(this).find('input[type="checkbox"]').each( function(index, element) {
- if ( attrValue == 'on' ) {
- $(element).attr( 'checked', 'true' );
- } else {
- $(element).removeAttr( 'checked' );
- }
- });
-
- $(this).find('div[status]').each( function(index, element) {
- $(element).attr( attrName, attrValue );
- $(element).text( attrValue );
- });
- }
+ } else if ( attrName == 'status' ) {
+ $(this).find('div[status]').each( function(index, element) {
+ $(element).attr( attrName, attrValue );
+ $(element).text( attrValue );
+ });
}
});
}