Skip to content

Home Information - Your home, your data, organized.

Python

HA thermostat support + temperature unit handling (#299 / #308) (#309)

Tony C900f85394c76
diff --git a/docs/dev/frontend/frontend-guidelines.md b/docs/dev/frontend/frontend-guidelines.md
index 8cd50e86..cbabca3e 100644
--- a/docs/dev/frontend/frontend-guidelines.md
+++ b/docs/dev/frontend/frontend-guidelines.md
@@ -82,6 +82,25 @@ return {
In this way, there is at most two places these ids are used as strings, and both client and server can referenced more safely.
+## Unit-Bearing Values: Server ↔ UI Translation
+
+Server-side EntityState values are stored in a canonical unit per state type (e.g., temperatures are °C internally regardless of whether the source integration reports °F or °C). The UI displays them in the user's configured display unit (IMPERIAL / METRIC) — translation happens at the server/UI boundary in **both directions**:
+
+- **Outbound (server → UI):** convert the EntityState's stored value to the user's display unit before rendering. Used for initial template renders AND polling-driven UI refreshes; both paths share one helper so the displayed value is consistent.
+- **Inbound (UI → server):** convert form/slider submissions from the user's display unit back to the EntityState's stored unit before caching/dispatching.
+
+The helpers:
+
+- **`ConsoleConverterHelper.from_entity_state_value(value, entity_state)`** returns a `DisplayValue` dataclass with `magnitude` / `unit_symbol` fields plus a combined `__str__`. Use `magnitude` when a numeric attribute is needed (slider `value=`); use the dataclass directly when combined text is wanted (status label, modal value).
+- **`ConsoleConverterHelper.to_entity_state_value(display_value, entity_state)`** for the inbound direction. `ControlViewMixin.to_entity_state_value` is a thin pass-through for control views.
+- **`{{ value|as_display_value:entity_state }}`** template filter (in `hi/apps/config/templatetags/units.py`) wraps the outbound helper; outputs `DisplayValue.__str__` (combined text) by default, or use `.magnitude` / `.unit_symbol` for separate access.
+
+Both pass through unchanged when the EntityState has no units, so the helpers are safe to call uniformly without per-state-type branching.
+
+The polling-update path lives in `StatusDisplayData` (sensor refresh) and `_get_controller_data_value` (controller widget refresh). They go through the same `ConsoleConverterHelper.from_entity_state_value` helper so async UI refreshes match initial template renders — if they don't, the bug is almost certainly that some new render path is reading raw values instead of going through the helper.
+
+The integration ↔ server boundary has a parallel pair (`IntegrationConverterHelper.to_/from_entity_state_value`) for converters; see [Integration Guidelines](../integrations/integration-guidelines.md).
+
## JavaScript Standards
**Minimize Javascript**: We should strive for the minimal amount of new Javascript. There are many special-purpose needs in the app that require Javascript, but we should never do in Javascfript what we can achieve on the backend.
diff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.md
index 35bebd49..89080846 100644
--- a/docs/dev/integrations/integration-guidelines.md
+++ b/docs/dev/integrations/integration-guidelines.md
@@ -16,6 +16,16 @@ A single upstream state may decompose into multiple HI EntityStates when the ups
- **`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.
+### Unit conversion at the integration boundary
+Integrations whose external system reports values with a unit (HA's `temperature_unit`, sensor `unit_of_measurement`, etc.) MUST normalize at the boundary: convert inbound values to a canonical unit before storing, and convert outbound values from canonical to the external system's required unit. The canonical unit is declared once where the EntityState is created (e.g., HA's climate substate specs declare °C as canonical for temperatures). Downstream code reads `EntityState.units` rather than re-asserting the canonical, so changing the choice propagates through the spec → EntityState chain without code edits at every conversion site.
+
+- **`IntegrationMetadataCache`** (`hi/integrations/integration_metadata_cache.py`) caches `EntityState.units` per `IntegrationKey` so polling-loop unit lookups don't multiply DB queries. Process-wide, lazy-warmed; provides parallel sync and async APIs (use the async variant from monitor coroutines so DB access goes through `sync_to_async`).
+- **`IntegrationConverterHelper.to_entity_state_value` / `from_entity_state_value`** (both with `_async` variants) are the boundary helpers backed by the cache. Inbound (`to_`) takes an external value + external unit and returns the value in the EntityState's stored unit. Outbound (`from_`) takes an EntityState-unit value + target external unit. Both pass through unchanged when units are absent or already match — safe to call uniformly without per-state-type branching.
+
+See `hi/services/hass/hass_converter.py` (climate substate inbound + setpoint outbound dispatch) for a worked example.
+
+The symmetric server ↔ UI boundary uses `ConsoleConverterHelper`; see [Frontend Guidelines](../frontend/frontend-guidelines.md#unit-bearing-values-server--ui-translation).
+
### 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/attribute/edit_context.py b/src/hi/apps/attribute/edit_context.py
index 785df364..be3bd7a4 100644
--- a/src/hi/apps/attribute/edit_context.py
+++ b/src/hi/apps/attribute/edit_context.py
@@ -132,7 +132,38 @@ class AttributePageEditContext:
@property
def update_button_label(self) -> str:
return 'UPDATE'
-
+
+ @property
+ def allow_edits(self) -> bool:
+ """Whether existing attribute values may be edited and saved on
+ this surface. Drives UPDATE-button visibility (and the dirty/status
+ message stack tied to the submission flow). Independent of
+ ``can_add_custom_attributes``: a surface may permit editing
+ existing values while disallowing new attributes (e.g., config
+ settings)."""
+ return True
+
+ @property
+ def can_add_custom_attributes(self) -> bool:
+ """Whether the surface allows adding new custom attributes
+ (Add File / Add Info). Independent of ``allow_edits``."""
+ return True
+
+ @property
+ def add_attribute_disabled_message(self) -> str:
+ return ''
+
+ @property
+ def externally_managed_message(self) -> str:
+ """Operator-facing notice rendered in the action bar's
+ UPDATE-button slot when the surface has no UPDATE action
+ (i.e., ``allow_edits`` is False). Returns an empty string by
+ default; owner contexts override to enable the notice. The
+ template only renders the notice when UPDATE is hidden, so an
+ owner can return a non-empty value here without worrying about
+ duplication on the normal editable surface."""
+ return ''
+
def to_template_context(self) -> Dict[str, Any]:
return {
"attr_page_context": self,
@@ -255,26 +286,6 @@ class AttributeItemEditContext( AttributePageEditContext ):
def add_attribute_button_html_id(self) -> str:
return f"{DIVID['ATTR_V2_ADD_ATTRIBUTE_BTN_ID']}{self.id_suffix}"
- @property
- def can_add_custom_attributes(self) -> bool:
- return True
-
- @property
- def add_attribute_disabled_message(self) -> str:
- return ''
-
- @property
- def externally_managed_message(self) -> str:
- """Operator-facing notice rendered in the action bar's
- UPDATE-button slot when the surface has no UPDATE action
- (i.e., ``can_add_custom_attributes`` is False on the owner).
- Returns an empty string by default; owner contexts override
- to enable the notice. The template only renders the notice
- when UPDATE is hidden, so an owner can return a non-empty
- value here without worrying about duplication on the normal
- editable surface."""
- return ''
-
def to_template_context(self) -> Dict[str, Any]:
template_context = super().to_template_context()
template_context.update({
diff --git a/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html b/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
index eb8a9d7b..56b63ff5 100644
--- a/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
+++ b/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
@@ -39,7 +39,7 @@ Compact history display that loads into attribute cards
</div>
<div>
{% if record.value != attribute.value %}
- {% if attr_item_context.can_add_custom_attributes %}
+ {% if attr_item_context.allow_edits and attribute.is_editable %}
<a href="{% attr_restore_url attr_item_context attribute.id record.pk %}"
class="btn btn-xs btn-outline-primary {{ DIVID.ATTR_V2_RESTORE_LINK_CLASS }}"
title="Restore this value">
@@ -50,7 +50,7 @@ Compact history display that loads into attribute cards
class="btn btn-xs btn-outline-primary {{ DIVID.ATTR_V2_RESTORE_LINK_CLASS }}"
disabled
aria-disabled="true"
- title="{{ attr_item_context.add_attribute_disabled_message }}">
+ title="This value cannot be edited.">
Restore
</button>
{% endif %}
diff --git a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
index 47836ab9..1b5175f6 100644
--- a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
+++ b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
@@ -45,7 +45,7 @@ by using the AttributeItemEditContext pattern.
<div class="{{ DIVID.ATTR_V2_ACTION_BAR_CONTENT_CLASS }}">
<!-- Left Side: UPDATE button and vertically stacked message areas -->
<div class="attr-v2-action-bar-left">
- {% if attr_item_context.can_add_custom_attributes %}
+ {% if attr_page_context.allow_edits %}
<button id="{{ attr_page_context.update_button_html_id }}"
type="submit"
class="btn btn-outline-primary d-inline-flex align-items-center {{ DIVID.ATTR_V2_UPDATE_BTN_CLASS }}"
@@ -54,10 +54,10 @@ by using the AttributeItemEditContext pattern.
{% icon "save" size="sm" css_class="hi-icon-left" %}
{{ attr_page_context.update_button_label }}
</button>
- {% elif attr_item_context.externally_managed_message %}
+ {% elif attr_page_context.externally_managed_message %}
<div class="attr-v2-externally-managed text-muted small d-inline-flex align-items-center">
{% icon "info-circle" size="sm" css_class="hi-icon-left" %}
- {{ attr_item_context.externally_managed_message }}
+ {{ attr_page_context.externally_managed_message }}
</div>
{% endif %}
{% block additional_buttons %}
@@ -69,7 +69,7 @@ by using the AttributeItemEditContext pattern.
free of empty placeholders that the script layer would
otherwise target.
{% endcomment %}
- {% if attr_item_context.can_add_custom_attributes %}
+ {% if attr_page_context.allow_edits %}
<!-- Vertically stacked message areas -->
<div class="attr-v2-message-stack">
<div id="{{ attr_page_context.dirty_msg_html_id }}"
@@ -90,7 +90,7 @@ by using the AttributeItemEditContext pattern.
<div class="{{ DIVID.ATTR_V2_ACTION_BUTTONS_CLASS }}">
{% block additional_actions %}
{% endblock %}
- {% if attr_item_context.can_add_custom_attributes %}
+ {% if attr_page_context.can_add_custom_attributes %}
{% block file_upload_button %}
<button type="button"
class="btn btn-sm btn-outline-primary mb-0"
diff --git a/src/hi/apps/config/subsystem_attribute_edit_context.py b/src/hi/apps/config/subsystem_attribute_edit_context.py
index d8ec7ccd..32842daf 100644
--- a/src/hi/apps/config/subsystem_attribute_edit_context.py
+++ b/src/hi/apps/config/subsystem_attribute_edit_context.py
@@ -22,7 +22,13 @@ class SubsystemAttributePageEditContext(AttributePageEditContext):
super().__init__( owner_type = 'subsystem' )
self.selected_subsystem_id = selected_subsystem_id
return
-
+
+ @property
+ def can_add_custom_attributes(self) -> bool:
+ # Config settings expose system-defined attributes only;
+ # values are editable but no new attributes may be added.
+ return False
+
@property
def can_restore_default(self):
return True
@@ -51,7 +57,12 @@ class SubsystemAttributeItemEditContext(AttributeItemEditContext):
def subsystem(self) -> Subsystem:
"""Get the Subsystem instance (typed accessor)."""
return self.owner
-
+
+ @property
+ def can_add_custom_attributes(self) -> bool:
+ # Mirrors SubsystemAttributePageEditContext — see comment there.
+ return False
+
@property
def can_restore_default(self):
return True
diff --git a/src/hi/apps/config/templatetags/units.py b/src/hi/apps/config/templatetags/units.py
index b4e366bd..1d290b31 100644
--- a/src/hi/apps/config/templatetags/units.py
+++ b/src/hi/apps/config/templatetags/units.py
@@ -1,5 +1,8 @@
from django import template
+from hi.apps.console.console_converter_helper import (
+ ConsoleConverterHelper,
+)
from hi.apps.console.console_helper import ConsoleSettingsHelper
from hi.units import UnitQuantity, get_display_quantity
@@ -7,6 +10,19 @@ from hi.units import UnitQuantity, get_display_quantity
register = template.Library()
+def as_display_value( value, entity_state ):
+ """Boundary translation for templates: take a value in the
+ EntityState's stored unit and return a ``DisplayValue`` (with
+ ``magnitude`` / ``unit_symbol`` / combined ``__str__``) ready
+ for display in the user's preferred unit. Pass-through when
+ the EntityState has no units."""
+ return ConsoleConverterHelper.from_entity_state_value(
+ entity_state_value = value,
+ entity_state = entity_state,
+ )
+
+
@register.filter
def format_quantity( quantity : UnitQuantity, fmt = "~H" ):
"""
diff --git a/src/hi/apps/console/console_converter_helper.py b/src/hi/apps/console/console_converter_helper.py
new file mode 100644
index 00000000..df49d629
--- /dev/null
+++ b/src/hi/apps/console/console_converter_helper.py
@@ -0,0 +1,124 @@
+"""Console/UI boundary value translation.
+
+Symmetric to ``IntegrationConverterHelper`` (which handles the
+integration ↔ HI boundary): this helper handles the HI ↔ UI
+boundary. The integration boundary keys conversions on
+``IntegrationKey`` and consults the ``IntegrationMetadataCache``;
+the UI boundary keys on ``EntityState`` and reads ``.units``
+directly.
+
+Direction conventions match the integration helper:
+- ``to_entity_state_value(display_value, entity_state)``: inbound
+ from the UI (a slider submission, a form field) — translate the
+ user's display-unit value back to the EntityState's stored unit
+ for caching and downstream dispatch.
+- ``from_entity_state_value(value, entity_state)``: outbound to
+ the UI — translate the EntityState's stored value to the user's
+ preferred display unit, returning a structured ``DisplayValue``
+ so callers can format magnitude / unit / combined text per
+ their need.
+
+Pass-through when the EntityState has no units (hue, percent,
+on/off, etc.) so this helper is safe to call uniformly without
+per-state-type branching at the call sites.
+"""
+import logging
+from dataclasses import dataclass
+
+from hi.apps.console.console_helper import ConsoleSettingsHelper
+from hi.apps.entity.models import EntityState
+from hi.units import UnitQuantity, get_display_quantity
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class DisplayValue:
+ """A value formatted for UI display: separated magnitude and
+ unit-symbol fields so callers can render each independently
+ (e.g., a slider's numeric ``value=`` attribute uses just the
+ magnitude; a status text element uses the combined string).
+
+ ``__str__`` produces the combined form (``"69.8°F"``) for the
+ common case of dropping it directly into a template."""
+
+ magnitude : str = ''
+ unit_symbol : str = ''
+
+ def __str__(self):
+ return f'{self.magnitude}{self.unit_symbol}'
+
+
+class ConsoleConverterHelper:
+
+ @classmethod
+ def to_entity_state_value(
+ cls,
+ display_value : str,
+ entity_state : EntityState,
+ ) -> str:
+ """Inbound boundary: translate a value submitted from the
+ UI (form post, slider) — which is in the user's display
+ unit — back to the EntityState's stored unit for caching
+ and downstream dispatch. No-op when the EntityState has no
+ units or when the display unit equals the stored unit.
+ Non-numeric submissions are logged and passed through so
+ downstream validation owns the rejection."""
+ entity_state_unit_str = entity_state.units
+ if not entity_state_unit_str:
+ return display_value
+ display_units = ConsoleSettingsHelper().get_display_units()
+ entity_state_quantity = UnitQuantity( 0, entity_state_unit_str )
+ display_unit = get_display_quantity(
+ entity_state_quantity, display_units,
+ ).units
+ if display_unit == entity_state_quantity.units:
+ return display_value
+ try:
+ display_value_float = float( display_value )
+ except ( ValueError, TypeError ):
+ logger.warning(
+ f'Non-numeric value {display_value!r} submitted for'
+ f' unit-bearing entity_state {entity_state.id};'
+ f' skipping unit translation.'
+ )
+ return display_value
+ display_quantity = UnitQuantity( display_value_float, display_unit )
+ return str(
+ display_quantity.to( entity_state_unit_str ).magnitude
+ )
+
+ @classmethod
+ def from_entity_state_value(
+ cls,
+ entity_state_value,
+ entity_state : EntityState,
+ ) -> DisplayValue:
+ """Outbound boundary: translate a value in the EntityState's
+ stored unit to the user's preferred display unit, returning
+ a ``DisplayValue`` (magnitude + unit_symbol). Pass-through
+ when the EntityState has no units or the value can't be
+ coerced — the magnitude is the input value as a string and
+ the unit_symbol is empty, so the call is safe to make
+ uniformly across all EntityState types."""
+ if entity_state_value is None:
+ return DisplayValue()
+ raw_str = str( entity_state_value )
+ units = getattr( entity_state, 'units', None )
+ if not units:
+ return DisplayValue( magnitude = raw_str )
+ try:
+ quantity = UnitQuantity( float( entity_state_value ), units )
+ except Exception:
+ return DisplayValue( magnitude = raw_str )
+ display_units = ConsoleSettingsHelper().get_display_units()
+ display_quantity = get_display_quantity( quantity, display_units )
+ try:
+ magnitude = str( round( display_quantity.magnitude, 1 ) )
+ except Exception:
+ magnitude = raw_str
+ try:
+ unit_symbol = f'{display_quantity.units:~P}'
+ except Exception:
+ unit_symbol = ''
+ return DisplayValue( magnitude = magnitude, unit_symbol = unit_symbol )
diff --git a/src/hi/apps/console/tests/test_console_converter_helper.py b/src/hi/apps/console/tests/test_console_converter_helper.py
new file mode 100644
index 00000000..ba32bdcf
--- /dev/null
+++ b/src/hi/apps/console/tests/test_console_converter_helper.py
@@ -0,0 +1,166 @@
+import logging
+from unittest.mock import MagicMock, patch
+
+from hi.apps.console.console_converter_helper import (
+ ConsoleConverterHelper,
+ DisplayValue,
+)
+from hi.apps.console.enums import DisplayUnits
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestDisplayValue(BaseTestCase):
+
+ def test_str_combines_magnitude_and_unit(self):
+ # ``DisplayValue.__str__`` is the contract that templates
+ # rely on for ``{{ value|as_display_value:entity_state }}`` to
+ # produce combined text directly.
+ self.assertEqual(
+ str( DisplayValue( magnitude = '69.8', unit_symbol = '°F' ) ),
+ '69.8°F',
+ )
+
+ def test_str_with_empty_unit_is_just_magnitude(self):
+ self.assertEqual(
+ str( DisplayValue( magnitude = '50' ) ), '50',
+ )
+
+ def test_default_construction_is_empty(self):
+ # Used as the no-value sentinel from ``from_entity_state_value``.
+ self.assertEqual( str( DisplayValue() ), '' )
+
+
+def _entity_state_with_units( units ):
+ """Build a minimal EntityState-shaped object — the helper only
+ reads ``.units`` and ``.id``, so a MagicMock is sufficient and
+ avoids per-test DB setup."""
+ state = MagicMock()
+ state.units = units
+ state.id = 1
+ return state
+
+
+def _patch_user_display_units( display_units ):
+ return patch(
+ 'hi.apps.console.console_converter_helper.ConsoleSettingsHelper',
+ return_value = MagicMock( get_display_units = MagicMock(
+ return_value = display_units,
+ )),
+ )
+
+
+class TestToEntityStateValue(BaseTestCase):
+ """Inbound: HTML/JS form value (in user's display unit) →
+ EntityState's stored unit."""
+
+ def test_converts_imperial_user_input_to_celsius_state(self):
+ # User submitted "70" in their °F display preference; the
+ # entity stores °C — helper converts.
+ state = _entity_state_with_units( '°C' )
+ with _patch_user_display_units( DisplayUnits.IMPERIAL ):
+ result = ConsoleConverterHelper.to_entity_state_value(
+ display_value = '70',
+ entity_state = state,
+ )
+ self.assertAlmostEqual( float( result ), 21.111, places = 2 )
+
+ def test_passthrough_when_user_unit_matches_state_unit(self):
+ # Metric user, °C entity — no conversion needed; original
+ # string returned unchanged so downstream string handling
+ # is preserved.
+ state = _entity_state_with_units( '°C' )
+ with _patch_user_display_units( DisplayUnits.METRIC ):
+ result = ConsoleConverterHelper.to_entity_state_value(
+ display_value = '22',
+ entity_state = state,
+ )
+ self.assertEqual( result, '22' )
+
+ def test_passthrough_when_state_has_no_units(self):
+ # Hue / saturation / on-off / etc. — original string
+ # returned unchanged, no Pint hop attempted.
+ state = _entity_state_with_units( None )
+ with _patch_user_display_units( DisplayUnits.IMPERIAL ):
+ result = ConsoleConverterHelper.to_entity_state_value(
+ display_value = '180',
+ entity_state = state,
+ )
+ self.assertEqual( result, '180' )
+
+ def test_non_numeric_input_passes_through(self):
+ # User submission of a non-numeric value for a unit-bearing
+ # state must not raise — downstream validation owns the
+ # rejection. The value passes through unchanged so callers
+ # see the original string they can validate.
+ state = _entity_state_with_units( '°C' )
+ with _patch_user_display_units( DisplayUnits.IMPERIAL ):
+ result = ConsoleConverterHelper.to_entity_state_value(
+ display_value = 'not-a-number',
+ entity_state = state,
+ )
+ self.assertEqual( result, 'not-a-number' )
+
+
+class TestFromEntityStateValue(BaseTestCase):
+ """Outbound: EntityState's stored unit → user's display unit.
+ Returns DisplayValue (magnitude + unit_symbol)."""
+
+ def test_imperial_user_sees_celsius_state_in_fahrenheit(self):
+ state = _entity_state_with_units( '°C' )
+ with _patch_user_display_units( DisplayUnits.IMPERIAL ):
+ display = ConsoleConverterHelper.from_entity_state_value(
+ entity_state_value = 22.0,
+ entity_state = state,
+ )
+ self.assertEqual( display.unit_symbol, '°F' )
+ self.assertAlmostEqual( float( display.magnitude ), 71.6, places = 1 )
+
+ def test_metric_user_sees_celsius_state_unchanged(self):
+ state = _entity_state_with_units( '°C' )
+ with _patch_user_display_units( DisplayUnits.METRIC ):
+ display = ConsoleConverterHelper.from_entity_state_value(
+ entity_state_value = 22.5,
+ entity_state = state,
+ )
+ self.assertEqual( display.unit_symbol, '°C' )
+ self.assertAlmostEqual( float( display.magnitude ), 22.5 )
+
+ def test_no_units_returns_passthrough_display_value(self):
+ # Unit-less states (hue, percent) return DisplayValue with
+ # the value as magnitude and empty unit_symbol — preserves
+ # the safe-to-call-uniformly contract.
+ state = _entity_state_with_units( None )
+ with _patch_user_display_units( DisplayUnits.IMPERIAL ):
+ display = ConsoleConverterHelper.from_entity_state_value(
+ entity_state_value = 50,
+ entity_state = state,
+ )
+ self.assertEqual( display.unit_symbol, '' )
+ self.assertEqual( display.magnitude, '50' )
+
+ def test_none_value_returns_empty_display_value(self):
+ state = _entity_state_with_units( '°C' )
+ with _patch_user_display_units( DisplayUnits.METRIC ):
+ display = ConsoleConverterHelper.from_entity_state_value(
+ entity_state_value = None,
+ entity_state = state,
+ )
+ self.assertEqual( str( display ), '' )
+
+ def test_round_trip_with_to_entity_state_value(self):
+ # User submits 70°F → stored canonical °C → rendered back
+ # as 70°F. Within float precision after two Pint hops.
+ state = _entity_state_with_units( '°C' )
+ with _patch_user_display_units( DisplayUnits.IMPERIAL ):
+ stored = ConsoleConverterHelper.to_entity_state_value(
+ display_value = '70',
+ entity_state = state,
+ )
+ display = ConsoleConverterHelper.from_entity_state_value(
+ entity_state_value = float( stored ),
+ entity_state = state,
+ )
+ self.assertEqual( display.unit_symbol, '°F' )
+ self.assertAlmostEqual( float( display.magnitude ), 70.0, places = 1 )
diff --git a/src/hi/apps/control/templates/control/panes/continuous_slider_with_units.html b/src/hi/apps/control/templates/control/panes/continuous_slider_with_units.html
new file mode 100644
index 00000000..d65e3561
--- /dev/null
+++ b/src/hi/apps/control/templates/control/panes/continuous_slider_with_units.html
@@ -0,0 +1,64 @@
+{% load units %}
+{% comment %}
+Continuous slider widget for controllers whose value is in
+``EntityState.units`` and must be translated to the user's preferred
+display unit at the render boundary. Translation goes through the
+``to_display`` filter (backed by ``ConsoleConverterHelper``); the
+HTML/JS layer never sees the canonical value.
+
+For unit-agnostic / fixed-suffix sliders (hue, saturation, percent,
+etc.), use ``continuous_slider.html`` instead.
+
+Required parameters:
+- controller_data : the controller data transient.
+- entity_state : the EntityState whose ``units`` drives
+ translation.
+- slider_min,
+ slider_max : range bounds in EntityState.units (will be
+ converted to display units for rendering).
+- slider_default : default value in EntityState.units, used when
+ no cached sensor response is present.
+
+Optional (forwarded to slider chrome):
+- slider_step : step in DISPLAY units.
+- slider_class, min_label, max_label, show_presets,
+ min_preset_label, max_preset_label
+{% endcomment %}
+{% with effective_canonical_value=controller_data.latest_sensor_response.value|default_if_none:slider_default %}
+{% with display_min=slider_min|as_display_value:entity_state display_max=slider_max|as_display_value:entity_state display_value=effective_canonical_value|as_display_value:entity_state %}
+<div class="{{ DIVID.CONTROLLER_SLIDER_CONTROL_CLASS }}">
+ <div class="hi-continuous-slider-row">
+ {% if min_label %}<span class="hi-continuous-slider-extreme">{{ min_label }}</span>{% endif %}
+ <input type="range"
+ name="value"
+ min="{{ display_min.magnitude }}"
+ max="{{ display_max.magnitude }}"
+ {% if slider_step %}step="{{ slider_step }}"{% endif %}
+ value="{{ display_value.magnitude }}"
+ 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_value.unit_symbol }}"
+ onchange-async="true"
+ data-controller-id="{{ controller_data.controller.id }}">
+ {% if max_label %}<span class="hi-continuous-slider-extreme">{{ max_label }}</span>{% endif %}
+ </div>
+ <div class="hi-continuous-slider-display">
+ <span class="hi-continuous-slider-value">{{ display_value }}</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 }}="{{ display_min.magnitude }}">
+ {{ min_preset_label|default:"Min" }}
+ </button>
+ <button type="button"
+ class="btn btn-sm btn-primary {{ DIVID.CONTROLLER_PRESET_BTN_CLASS }}"
+ {{ DIVID.DATA_VALUE_ATTR }}="{{ display_max.magnitude }}">
+ {{ max_preset_label|default:"Max" }}
+ </button>
+ </div>
+ {% endif %}
+ </div>
+</div>
+{% endwith %}
+{% endwith %}
diff --git a/src/hi/apps/control/templates/control/panes/controller_temperature.html b/src/hi/apps/control/templates/control/panes/controller_temperature.html
new file mode 100644
index 00000000..d84516dd
--- /dev/null
+++ b/src/hi/apps/control/templates/control/panes/controller_temperature.html
@@ -0,0 +1,5 @@
+{% with entity_state=controller_data.controller.entity_state %}
+{% with value_range=entity_state.value_range_dict %}
+{% include "control/panes/continuous_slider_with_units.html" with entity_state=entity_state slider_min=value_range.min slider_max=value_range.max slider_default=value_range.min slider_step="0.1" slider_class="temperature-slider" %}
+{% endwith %}
+{% endwith %}
diff --git a/src/hi/apps/control/view_mixins.py b/src/hi/apps/control/view_mixins.py
index 4fdb5782..ba955ba5 100644
--- a/src/hi/apps/control/view_mixins.py
+++ b/src/hi/apps/control/view_mixins.py
@@ -1,14 +1,19 @@
+import logging
from typing import List
from django.core.exceptions import BadRequest
from django.http import Http404, HttpRequest, HttpResponse
from django.shortcuts import render
+from hi.apps.console.console_converter_helper import ConsoleConverterHelper
from hi.apps.control.models import Controller
+from hi.apps.entity.models import EntityState
from hi.apps.monitor.status_display_manager import StatusDisplayManager
from .transient_models import ControllerData
+logger = logging.getLogger(__name__)
+
class ControlViewMixin:
@@ -23,6 +28,20 @@ class ControlViewMixin:
except Controller.DoesNotExist:
raise Http404( request )
+ def to_entity_state_value(
+ self,
+ display_value : str,
+ entity_state : EntityState,
+ ) -> str:
+ """Convenience for control views: thin pass-through to
+ ``ConsoleConverterHelper.to_entity_state_value`` so the call
+ site reads naturally alongside ``get_controller`` /
+ ``controller_data_response``."""
+ return ConsoleConverterHelper.to_entity_state_value(
+ display_value = display_value,
+ entity_state = entity_state,
+ )
+
def controller_data_response( self,
request : HttpRequest,
controller : Controller,
diff --git a/src/hi/apps/control/views.py b/src/hi/apps/control/views.py
index a9571643..f9e11ea7 100644
--- a/src/hi/apps/control/views.py
+++ b/src/hi/apps/control/views.py
@@ -29,13 +29,20 @@ class ControllerView( View, ControlViewMixin, ControllerMixin ):
def post( self, request, *args, **kwargs ):
controller = self.get_controller( request, *args, **kwargs )
- control_value = request.POST.get( 'value' )
+ display_control_value = request.POST.get( 'value' )
# Checkbox case results in no value, so we need to normalize those
# binary states based on EntityStateType.
#
- if control_value is None:
- control_value = self._get_value_for_missing_input( controller = controller )
+ if display_control_value is None:
+ display_control_value = self._get_value_for_missing_input(
+ controller = controller,
+ )
+
+ control_value = self.to_entity_state_value(
+ display_value = display_control_value,
+ entity_state = controller.entity_state,
+ )
controller_outcome = self.controller_manager().do_control(
controller = controller,
diff --git a/src/hi/apps/entity/entity_attribute_edit_context.py b/src/hi/apps/entity/entity_attribute_edit_context.py
index cd098316..c6c73385 100644
--- a/src/hi/apps/entity/entity_attribute_edit_context.py
+++ b/src/hi/apps/entity/entity_attribute_edit_context.py
@@ -83,6 +83,12 @@ class EntityAttributeItemEditContext(AttributeItemEditContext):
def can_add_custom_attributes(self) -> bool:
return self.entity.can_add_custom_attributes
+ @property
+ def allow_edits(self) -> bool:
+ # Externally managed entities (e.g., HomeBox-imported) are
+ # fully read-only on this surface — same gate as adding.
+ return self.entity.can_add_custom_attributes
+
@property
def add_attribute_disabled_message(self) -> str:
if self.can_add_custom_attributes:
diff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/status_display_data.py
index 8be70292..03f63a4e 100644
--- a/src/hi/apps/monitor/status_display_data.py
+++ b/src/hi/apps/monitor/status_display_data.py
@@ -1,5 +1,9 @@
import hi.apps.common.datetimeproxy as datetimeproxy
+from hi.apps.console.console_converter_helper import (
+ ConsoleConverterHelper,
+ DisplayValue,
+)
from hi.apps.entity.enums import EntityStateType, EntityStateValue
from hi.hi_styles import StatusStyle
@@ -77,6 +81,20 @@ class StatusDisplayData:
return self.sensor_response_list[0].value
return None
+ @property
+ def latest_display_value(self) -> DisplayValue:
+ """Latest sensor value translated to the user's preferred
+ display unit (when the EntityState has unit-bearing data) —
+ the polling-update analogue of the template-render boundary
+ translation. Returns a ``DisplayValue`` with separated
+ magnitude and unit_symbol so consumers can format per
+ their need (slider's numeric ``value=`` uses ``.magnitude``;
+ status text uses ``str(...)`` which combines both)."""
+ return ConsoleConverterHelper.from_entity_state_value(
+ entity_state_value = self.latest_sensor_value,
+ entity_state = self._entity_state,
+ )
+
@property
def penultimate_sensor_value(self):
if len(self.sensor_response_list) > 1:
@@ -95,10 +113,14 @@ class StatusDisplayData:
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=...``).
+ controllable states is the latest sensor value translated
+ to the user's display unit when the EntityState has units —
+ widgets rendered by ``continuous_slider_with_units.html``
+ operate in display-unit space, so the polling refresh has
+ to push values in that same unit. Unit-less states pass
+ through unchanged so existing widget contracts (slider
+ ``value=...``, checkbox ``checked=...``, select option
+ ``selected=...``) are preserved.
Per-state-type overrides go here when a widget needs a
reshape — e.g., a future COLOR state would return a dict
@@ -106,7 +128,10 @@ class StatusDisplayData:
"""
if not self._controller_data_list:
return None
- return self.latest_sensor_value
+ # Slider widget's numeric ``value=`` attribute needs just
+ # the magnitude — combined-string would break the range
+ # input's parsing.
+ return self.latest_display_value.magnitude
def _get_svg_status_style(self):
@@ -150,7 +175,11 @@ class StatusDisplayData:
# EntityStateType.WATER_FLOW
# EntityStateType.WIND_SPEED
- status_value = self.latest_sensor_value
+ # Use the display-unit text so the polling refresh of the
+ # status display matches what the initial server-side
+ # template render produced (combined magnitude + unit
+ # suffix for unit-bearing values, raw value otherwise).
+ status_value = str( self.latest_display_value )
if not status_value:
status_value = StatusStyle.DEFAULT_STATUS_VALUE
diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html
new file mode 100644
index 00000000..aa559447
--- /dev/null
+++ b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html
@@ -0,0 +1,11 @@
+{% load units %}
+{% comment %}
+Temperature sensor value rendering. Server-side
+``sensor_response.value`` is in the EntityState's stored unit;
+the ``as_display_value`` filter goes through ``ConsoleConverterHelper``
+to produce a ``DisplayValue`` whose ``__str__`` combines the
+user-display magnitude and unit symbol.
+{% endcomment %}
+<div class="text-center px-2" status="{{ sensor_response.value }}">
+ {{ sensor_response.value|as_display_value:sensor_response.sensor.entity_state }}
+</div>
diff --git a/src/hi/integrations/integration_converter_helper.py b/src/hi/integrations/integration_converter_helper.py
index 76f17f60..f60d4a8c 100644
--- a/src/hi/integrations/integration_converter_helper.py
+++ b/src/hi/integrations/integration_converter_helper.py
@@ -1,7 +1,9 @@
-from typing import Dict, List, Optional
+from typing import Any, Dict, List, Optional
from hi.apps.sense.sensor_response_manager import SensorResponseMixin
+from hi.units import UnitQuantity
+from .integration_metadata_cache import IntegrationMetadataCache
from .transient_models import IntegrationKey
@@ -41,3 +43,115 @@ class IntegrationConverterHelper:
integration_key: ( response.value if response else None )
for integration_key, response in response_map.items()
}
+
+ @classmethod
+ def get_cache_entry(
+ cls, integration_key : IntegrationKey,
+ ) -> Dict[str, Any]:
+ """Return cached EntityState metadata used by integration
+ value translation. The dict has a ``units`` key holding the
+ EntityState.units string (or None when no translation is
+ needed). Backed by ``IntegrationMetadataCache`` (process-wide,
+ lazy-warmed)."""
+ return IntegrationMetadataCache().get_entry( integration_key )
+
+ @classmethod
+ async def get_cache_entry_async(
+ cls, integration_key : IntegrationKey,
+ ) -> Dict[str, Any]:
+ """Async variant of ``get_cache_entry`` for use from async
+ monitor / converter paths."""
+ return await IntegrationMetadataCache().get_entry_async( integration_key )
+
+ @classmethod
+ def to_entity_state_value(
+ cls,
+ external_value : float,
+ external_unit : str,
+ integration_key : IntegrationKey,
+ ) -> float:
+ """Inbound boundary: translate a numeric value from the
+ integration's external unit (e.g., HA's reported
+ ``unit_of_measurement``) to the EntityState's stored unit.
+ The target unit is read from the IntegrationMetadataCache.
+ Pass-through when the EntityState has no units or the units
+ already match."""
+ target_unit = cls.get_cache_entry(
+ integration_key,
+ ).get( 'units' )
+ return cls._convert_between_units(
+ value = external_value,
+ from_unit = external_unit,
+ to_unit = target_unit,
+ )
+
+ @classmethod
+ async def to_entity_state_value_async(
+ cls,
+ external_value : float,
+ external_unit : str,
+ integration_key : IntegrationKey,
+ ) -> float:
+ """Async variant of ``to_entity_state_value`` for use from
+ async monitor paths. Cache lookup goes through
+ sync_to_async; conversion arithmetic is pure-Python."""
+ entry = await cls.get_cache_entry_async( integration_key )
+ return cls._convert_between_units(
+ value = external_value,
+ from_unit = external_unit,
+ to_unit = entry.get( 'units' ),
+ )
+
+ @classmethod
+ def from_entity_state_value(
+ cls,
+ entity_state_value : float,
+ external_unit : str,
+ integration_key : IntegrationKey,
+ ) -> float:
+ """Outbound boundary: translate a numeric value in the
+ EntityState's stored unit to the integration's external
+ unit (e.g., HA's currently-reported native unit). The
+ source unit is read from the IntegrationMetadataCache.
+ Pass-through when the EntityState has no units or the units
+ already match."""
+ source_unit = cls.get_cache_entry(
+ integration_key,
+ ).get( 'units' )
+ return cls._convert_between_units(
+ value = entity_state_value,
+ from_unit = source_unit,
+ to_unit = external_unit,
+ )
+
+ @classmethod
+ async def from_entity_state_value_async(
+ cls,
+ entity_state_value : float,
+ external_unit : str,
+ integration_key : IntegrationKey,
+ ) -> float:
+ """Async variant of ``from_entity_state_value``."""
+ entry = await cls.get_cache_entry_async( integration_key )
+ return cls._convert_between_units(
+ value = entity_state_value,
+ from_unit = entry.get( 'units' ),
+ to_unit = external_unit,
+ )
+
+ @staticmethod
+ def _convert_between_units(
+ value : float,
+ from_unit : Optional[str],
+ to_unit : Optional[str],
+ ) -> float:
+ """Pure-Python Pint conversion between unit strings.
+ Pass-through when either side is missing or the units
+ already match. Defensive on parse failures so a malformed
+ unit string never raises into the converter call sites."""
+ if not from_unit or not to_unit or from_unit == to_unit:
+ return value
+ try:
+ return UnitQuantity( value, from_unit ).to( to_unit ).magnitude
+ except Exception:
+ return value
diff --git a/src/hi/integrations/integration_metadata_cache.py b/src/hi/integrations/integration_metadata_cache.py
new file mode 100644
index 00000000..966508f5
--- /dev/null
+++ b/src/hi/integrations/integration_metadata_cache.py
@@ -0,0 +1,149 @@
+import logging
+import threading
+from typing import Any, Dict, Optional
+
+from asgiref.sync import sync_to_async
+
+from hi.apps.common.singleton import Singleton
+from hi.apps.control.models import Controller
+from hi.apps.entity.models import EntityState
+from hi.apps.sense.models import Sensor
+
+from .transient_models import IntegrationKey
+
+logger = logging.getLogger(__name__)
+
+
+class IntegrationMetadataCache( Singleton ):
+ """Process-wide, lazily-warmed cache of EntityState metadata
+ that integration converters need at value-translation time.
+
+ Polling loops are hot paths and the inbound and outbound
+ converters need per-entity metadata (today: stored units;
+ potentially more in the future) on every call. Caching avoids
+ per-call DB queries; the underlying fields are set at creation
+ and rarely change in practice, so a process-lifetime cache
+ with no active invalidation is the right trade-off (the
+ workaround for the rare edit is a process restart).
+
+ Keyed by ``IntegrationKey``. Each entry is a small dict so
+ additional metadata can be added later without changing the
+ API surface. Today the only entry key is ``units`` (the
+ EntityState.units string, or None when the EntityState has
+ no units).
+
+ Concurrency: bulk-warmup and lazy single-row fills take the
+ write lock; reads of an already-populated entry are unlocked
+ (CPython dict reads are atomic for our access pattern).
+ """
+
+ def __init_singleton__(self):
+ self._cache : Dict[ IntegrationKey, Dict[str, Any] ] = {}
+ self._lock = threading.Lock()
+ self._warmed = False
+ return
+
+ def get_entry(
+ self, integration_key : IntegrationKey,
+ ) -> Dict[str, Any]:
+ """Return the cached metadata dict for the given
+ ``integration_key``. Triggers a single bulk warmup on the
+ first call across the process; entities created after
+ warmup are filled lazily on miss. Sync API; use
+ ``get_entry_async`` from async contexts to avoid Django's
+ SynchronousOnlyOperation guard during DB-touching paths."""
+ if not self._warmed:
+ self._warmup()
+ entry = self._cache.get( integration_key )
+ if entry is not None:
+ return entry
+ return self._lazy_fill( integration_key )
+
+ async def get_entry_async(
+ self, integration_key : IntegrationKey,
+ ) -> Dict[str, Any]:
+ """Async variant of ``get_entry``. After the cache is
+ warmed, reads are pure-Python dict accesses and the
+ sync_to_async hop is essentially free; before warm and on
+ lazy-fill misses, the DB lookup happens in a thread pool
+ so it's safe to call from async monitor contexts."""
+ if self._warmed and integration_key in self._cache:
+ return self._cache[ integration_key ]
+ return await sync_to_async(
+ self.get_entry, thread_sensitive=True,
+ )( integration_key )
+
+ def _warmup(self):
+ """One-shot bulk load of every known integration_key.
+
+ Assumes any Sensor/Controller pair sharing an
+ ``integration_key`` references the same EntityState (enforced
+ by ``HiModelHelper``; ``integration_id`` namespacing prevents
+ cross-integration collisions). Sensor entries win on overlap;
+ a warning fires if the Controller's entry would have
+ disagreed — canary for invariant violations."""
+ with self._lock:
+ if self._warmed:
+ return
+ for sensor in Sensor.objects.select_related( 'entity_state' ).all():
+ key = sensor.integration_key
+ if key is None:
+ continue
+ self._cache[ key ] = self._build_entry( sensor.entity_state )
+ for controller in Controller.objects.select_related( 'entity_state' ).all():
+ key = controller.integration_key
+ if key is None:
+ continue
+ controller_entry = self._build_entry( controller.entity_state )
+ existing = self._cache.get( key )
+ if existing is None:
+ self._cache[ key ] = controller_entry
+ continue
+ if existing != controller_entry:
+ logger.warning(
+ f'IntegrationMetadataCache invariant violated for '
+ f'{key}: divergent Sensor/Controller metadata '
+ f'({existing} vs {controller_entry}). See class docs.'
+ )
+ self._warmed = True
+
+ def _lazy_fill(
+ self, integration_key : IntegrationKey,
+ ) -> Dict[str, Any]:
+ """Single-row fill on a post-warmup miss (entity created
+ after warmup). Falls back to an empty entry when the key
+ resolves to nothing so subsequent misses don't re-query."""
+ entity_state = self._lookup_entity_state( integration_key )
+ entry = (
+ self._build_entry( entity_state )
+ if entity_state is not None
+ else { 'units': None }
+ )
+ with self._lock:
+ self._cache.setdefault( integration_key, entry )
+ return self._cache[ integration_key ]
+
+ @staticmethod
+ def _lookup_entity_state(
+ integration_key : IntegrationKey,
+ ) -> Optional[ EntityState ]:
+ try:
+ return Sensor.objects.select_related( 'entity_state' ).get(
+ integration_id = integration_key.integration_id,
+ integration_name = integration_key.integration_name,
+ ).entity_state
+ except Sensor.DoesNotExist:
+ pass
+ try:
+ return Controller.objects.select_related( 'entity_state' ).get(
+ integration_id = integration_key.integration_id,
+ integration_name = integration_key.integration_name,
+ ).entity_state
+ except Controller.DoesNotExist:
+ return None
+
+ @staticmethod
+ def _build_entry( entity_state : EntityState ) -> Dict[str, Any]:
+ return {
+ 'units': entity_state.units or None,
+ }
diff --git a/src/hi/integrations/tests/test_integration_converter_helper.py b/src/hi/integrations/tests/test_integration_converter_helper.py
new file mode 100644
index 00000000..75c9d43d
--- /dev/null
+++ b/src/hi/integrations/tests/test_integration_converter_helper.py
@@ -0,0 +1,194 @@
+import logging
+
+from django.test import TestCase
+
+from hi.integrations.integration_converter_helper import IntegrationConverterHelper
+from hi.integrations.integration_metadata_cache import IntegrationMetadataCache
+from hi.integrations.transient_models import IntegrationKey
+from hi.testing.async_task_utils import AsyncTaskTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+def _seed_cache_entry( integration_key, units ):
+ """Pre-populate the metadata cache so the converter helpers
+ don't need real Sensor/Controller rows for unit-translation
+ tests that only exercise the helper's conversion math."""
+ cache = IntegrationMetadataCache()
+ cache._warmed = True
+ cache._cache[ integration_key ] = { 'units': units }
+
+
+def _reset_cache():
+ cache = IntegrationMetadataCache()
+ cache._cache.clear()
+ cache._warmed = False
+
+
+class TestToEntityStateValue(TestCase):
+ """Inbound boundary: integration's external value (e.g., HA's
+ reported °F) → EntityState's stored unit (canonical °C). Cache
+ holds the target unit; helper applies Pint conversion."""
+
+ def setUp(self):
+ _reset_cache()
+
+ def tearDown(self):
+ _reset_cache()
+
+ def _key(self, name='test'):
+ return IntegrationKey( integration_id = 'hass', integration_name = name )
+
+ def test_converts_fahrenheit_to_canonical_celsius(self):
+ key = self._key( 'climate.zoo~current_temperature' )
+ _seed_cache_entry( key, units = '°C' )
+
+ result = IntegrationConverterHelper.to_entity_state_value(
+ external_value = 70.0,
+ external_unit = '°F',
+ integration_key = key,
+ )
+
+ self.assertAlmostEqual( result, 21.111, places = 2 )
+
+ def test_passthrough_when_units_match(self):
+ key = self._key( 'climate.zoo~current_temperature' )
+ _seed_cache_entry( key, units = '°C' )
+
+ result = IntegrationConverterHelper.to_entity_state_value(
+ external_value = 22.0,
+ external_unit = '°C',
+ integration_key = key,
+ )
+
+ self.assertEqual( result, 22.0 )
+
+ def test_passthrough_when_no_target_unit(self):
+ # Cache says no units (e.g., ON/OFF state) — converter must
+ # not try to translate.
+ key = self._key( 'switch.outlet' )
+ _seed_cache_entry( key, units = None )
+
+ result = IntegrationConverterHelper.to_entity_state_value(
+ external_value = 50.0,
+ external_unit = '%',
+ integration_key = key,
+ )
+
+ self.assertEqual( result, 50.0 )
+
+
+class TestFromEntityStateValue(TestCase):
+ """Outbound boundary: HI's stored value (canonical °C) →
+ integration's required external unit (e.g., HA's °F)."""
+
+ def setUp(self):
+ _reset_cache()
+
+ def tearDown(self):
+ _reset_cache()
+
+ def _key(self, name='test'):
+ return IntegrationKey( integration_id = 'hass', integration_name = name )
+
+ def test_converts_canonical_celsius_to_fahrenheit(self):
+ key = self._key( 'climate.zoo~target_temperature' )
+ _seed_cache_entry( key, units = '°C' )
+
+ result = IntegrationConverterHelper.from_entity_state_value(
+ entity_state_value = 22.0,
+ external_unit = '°F',
+ integration_key = key,
+ )
+
+ self.assertAlmostEqual( result, 71.6, places = 2 )
+
+ def test_passthrough_when_units_match(self):
+ key = self._key( 'climate.zoo~target_temperature' )
+ _seed_cache_entry( key, units = '°C' )
+
+ result = IntegrationConverterHelper.from_entity_state_value(
+ entity_state_value = 22.0,
+ external_unit = '°C',
+ integration_key = key,
+ )
+
+ self.assertEqual( result, 22.0 )
+
+ def test_passthrough_when_no_source_unit(self):
+ # An EntityState without units (e.g., a discrete enum
+ # state) must not be translated even if the dispatch
+ # specifies an external_unit.
+ key = self._key( 'switch.lamp' )
+ _seed_cache_entry( key, units = None )
+
+ result = IntegrationConverterHelper.from_entity_state_value(
+ entity_state_value = 1.0,
+ external_unit = '°F',
+ integration_key = key,
+ )
+
+ self.assertEqual( result, 1.0 )
+
+ def test_round_trip_to_then_from_preserves_value(self):
+ # to_entity_state_value followed by from_entity_state_value
+ # with the same external_unit must round-trip with at most
+ # one Pint hop's worth of float imprecision.
+ key = self._key( 'climate.zoo~target_temperature' )
+ _seed_cache_entry( key, units = '°C' )
+
+ canonical = IntegrationConverterHelper.to_entity_state_value(
+ external_value = 75.0, external_unit = '°F', integration_key = key,
+ )
+ external = IntegrationConverterHelper.from_entity_state_value(
+ entity_state_value = canonical,
+ external_unit = '°F',
+ integration_key = key,
+ )
+
+ self.assertAlmostEqual( external, 75.0, places = 6 )
+
+
+class TestAsyncConverterHelpers(AsyncTaskTestCase):
+ """Async variants delegate to the cache's async API, which uses
+ sync_to_async for DB safety. AsyncTaskTestCase manages the
+ event-loop lifecycle so these don't deadlock on DB locks."""
+
+ def setUp(self):
+ _reset_cache()
+
+ def tearDown(self):
+ _reset_cache()
+
+ def _key(self, name='test'):
+ return IntegrationKey( integration_id = 'hass', integration_name = name )
+
+ def test_to_entity_state_value_async_matches_sync(self):
+ key = self._key( 'climate.zoo~current_temperature' )
+ _seed_cache_entry( key, units = '°C' )
+
+ sync_result = IntegrationConverterHelper.to_entity_state_value(
+ external_value = 70.0, external_unit = '°F', integration_key = key,
+ )
+ async_result = self.run_async(
+ IntegrationConverterHelper.to_entity_state_value_async(
+ external_value = 70.0, external_unit = '°F', integration_key = key,
+ )
+ )
+
+ self.assertEqual( sync_result, async_result )
+
+ def test_from_entity_state_value_async_matches_sync(self):
+ key = self._key( 'climate.zoo~target_temperature' )
+ _seed_cache_entry( key, units = '°C' )
+
+ sync_result = IntegrationConverterHelper.from_entity_state_value(
+ entity_state_value = 22.0, external_unit = '°F', integration_key = key,
+ )
+ async_result = self.run_async(
+ IntegrationConverterHelper.from_entity_state_value_async(
+ entity_state_value = 22.0, external_unit = '°F', integration_key = key,
+ )
+ )
+
+ self.assertEqual( sync_result, async_result )
diff --git a/src/hi/integrations/tests/test_integration_metadata_cache.py b/src/hi/integrations/tests/test_integration_metadata_cache.py
new file mode 100644
index 00000000..9a071316
--- /dev/null
+++ b/src/hi/integrations/tests/test_integration_metadata_cache.py
@@ -0,0 +1,203 @@
+import logging
+from unittest.mock import patch
+
+from django.test import TestCase
+
+from hi.apps.entity.enums import EntityStateType, EntityType
+from hi.apps.entity.models import Entity, EntityState
+from hi.apps.sense.models import Sensor
+from hi.apps.control.models import Controller
+from hi.integrations.integration_metadata_cache import IntegrationMetadataCache
+from hi.integrations.transient_models import IntegrationKey
+from hi.testing.async_task_utils import AsyncTaskTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+def _make_entity_with_sensor( integration_key, units = None ):
+ entity = Entity.objects.create(
+ name = f'Test {integration_key.integration_name}',
+ integration_id = integration_key.integration_id,
+ integration_name = integration_key.integration_name,
+ entity_type_str = str( EntityType.LIGHT ),
+ )
+ state = EntityState.objects.create(
+ entity = entity,
+ entity_state_type_str = str( EntityStateType.TEMPERATURE ),
+ name = f'{entity.name} state',
+ units = units,
+ )
+ sensor = Sensor( entity_state = state, name = entity.name )
+ sensor.integration_key = integration_key
+ sensor.save()
+ return entity, state, sensor
+
+
+def _reset_cache():
+ IntegrationMetadataCache()._cache.clear()
+ IntegrationMetadataCache()._warmed = False
+
+
+class TestIntegrationMetadataCache(TestCase):
+ """Cache exists to amortize per-call EntityState.units lookups
+ inside the HA monitor's polling loop. The tests cover the
+ contracts that path depends on: warmup populates from the DB
+ one-shot, lazy fill handles entities created post-warmup,
+ misses for unknown keys are cached so they don't re-hit the
+ DB, and the invariant-violation warning fires when a
+ Sensor/Controller pair disagree (the canary protection)."""
+
+ def setUp(self):
+ _reset_cache()
+
+ def tearDown(self):
+ _reset_cache()
+
+ def test_warmup_loads_units_from_sensor_entity_states(self):
+ key = IntegrationKey(
+ integration_id = 'hass',
+ integration_name = 'climate.thermostat~current_temperature',
+ )
+ _make_entity_with_sensor( key, units = '°C' )
+
+ entry = IntegrationMetadataCache().get_entry( key )
+
+ self.assertEqual( entry, { 'units': '°C' } )
+ self.assertTrue( IntegrationMetadataCache()._warmed )
+
+ def test_warmup_dedupes_sensor_and_controller_sharing_key(self):
+ # HiModelHelper.create_controller(is_sensed=True) creates both
+ # a Sensor and Controller pointing at the same EntityState.
+ # The cache records one entry without duplication; the
+ # Sensor pass populates first, the Controller pass's
+ # ``setdefault`` is a no-op for a matching pair.
+ key = IntegrationKey(
+ integration_id = 'hass',
+ integration_name = 'switch.lamp',
+ )
+ entity, state, sensor = _make_entity_with_sensor( key, units = '°C' )
+ controller = Controller( entity_state = state, name = entity.name )
+ controller.integration_key = key
+ controller.save()
+
+ entry = IntegrationMetadataCache().get_entry( key )
+
+ self.assertEqual( entry, { 'units': '°C' } )
+
+ def test_lazy_fill_loads_entity_created_after_warmup(self):
+ # Warmup with no entities present — cache marks itself
+ # warmed but is empty.
+ IntegrationMetadataCache().get_entry( IntegrationKey(
+ integration_id = 'hass', integration_name = 'absent',
+ ))
+ self.assertTrue( IntegrationMetadataCache()._warmed )
+ # New entity created after warmup; lazy_fill should query
+ # the DB for the specific key and populate.
+ late_key = IntegrationKey(
+ integration_id = 'hass', integration_name = 'late.entity',
+ )
+ _make_entity_with_sensor( late_key, units = '°F' )
+
+ entry = IntegrationMetadataCache().get_entry( late_key )
+
+ self.assertEqual( entry, { 'units': '°F' } )
+
+ def test_unknown_key_caches_a_no_units_entry(self):
+ # Misses must be remembered so the cache doesn't re-query
+ # the DB for the same unknown key on every poll.
+ key = IntegrationKey(
+ integration_id = 'hass', integration_name = 'never.imported',
+ )
+
+ first = IntegrationMetadataCache().get_entry( key )
+ with patch(
+ 'hi.integrations.integration_metadata_cache.Sensor.objects',
+ ) as mock_sensor_objects:
+ second = IntegrationMetadataCache().get_entry( key )
+
+ self.assertEqual( first, { 'units': None } )
+ self.assertEqual( second, { 'units': None } )
+ # Second call must not have re-queried Sensor.objects.
+ mock_sensor_objects.select_related.assert_not_called()
+
+ def test_divergent_sensor_controller_keeps_sensor_entry(self):
+ # Sensor and Controller with the same integration_key but
+ # pointing to different EntityStates with different units
+ # is a programming error (HiModelHelper enforces
+ # co-location); the cache resolves the conflict by keeping
+ # the Sensor pass's entry — that's the documented design,
+ # and the cache logs a warning canary which we don't
+ # exercise here (tests disable logging).
+ key = IntegrationKey(
+ integration_id = 'hass',
+ integration_name = 'oddly.divergent',
+ )
+ sensor_entity, sensor_state, _ = _make_entity_with_sensor(
+ key, units = '°C',
+ )
+ # Manually create a separate EntityState with a different
+ # units value, and a Controller pointing to it under the
+ # same integration_key — bypassing HiModelHelper.
+ other_state = EntityState.objects.create(
+ entity = sensor_entity,
+ entity_state_type_str = str( EntityStateType.TEMPERATURE ),
+ name = 'Divergent state',
+ units = '°F',
+ )
+ controller = Controller(
+ entity_state = other_state, name = sensor_entity.name,
+ )
+ controller.integration_key = key
+ controller.save()
+
+ entry = IntegrationMetadataCache().get_entry( key )
+
+ # Sensor pass wins, per the documented design.
+ self.assertEqual( entry, { 'units': '°C' } )
+
+
+class TestIntegrationMetadataCacheAsync(AsyncTaskTestCase):
+ """Async paths use ``sync_to_async`` to safely call the
+ DB-touching methods from async contexts. Inherits from
+ AsyncTaskTestCase so the event-loop lifecycle is managed
+ correctly and the tests don't deadlock on DB locks."""
+
+ def setUp(self):
+ _reset_cache()
+
+ def tearDown(self):
+ _reset_cache()
+
+ def test_async_variant_returns_same_as_sync(self):
+ key = IntegrationKey(
+ integration_id = 'hass', integration_name = 'async.entity',
+ )
+ _make_entity_with_sensor( key, units = '°C' )
+
+ # Cold cache — async hits sync_to_async wrapper for warmup.
+ entry = self.run_async(
+ IntegrationMetadataCache().get_entry_async( key )
+ )
+
+ self.assertEqual( entry, { 'units': '°C' } )
+
+ def test_warm_cache_async_avoids_sync_to_async_hop(self):
+ # Performance contract: once warmed and the entry is
+ # present, async path should short-circuit to a pure
+ # dict read without dispatching to a thread.
+ key = IntegrationKey(
+ integration_id = 'hass', integration_name = 'warm.entity',
+ )
+ _make_entity_with_sensor( key, units = '°C' )
+ # Prime the cache.
+ IntegrationMetadataCache().get_entry( key )
+
+ with patch(
+ 'hi.integrations.integration_metadata_cache.sync_to_async',
+ ) as mock_sync_to_async:
+ entry = self.run_async(
+ IntegrationMetadataCache().get_entry_async( key )
+ )
+
+ self.assertEqual( entry, { 'units': '°C' } )
+ mock_sync_to_async.assert_not_called()
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index 7da4b417..32ef6095 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -15,13 +15,13 @@ from hi.apps.entity.enums import (
EntityType,
EntityStateValue,
HumidityUnit,
- TemperatureUnit,
)
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 hi.units import CANONICAL_TEMPERATURE_UNIT
from .enums import HassStateValue
from .hass_metadata import HassMetaData
@@ -827,6 +827,7 @@ class HassConverter:
name = record_name,
integration_key = substate_integration_key,
value_range_str = value_range_str,
+ units = spec.units,
)
controller.integration_payload = cls._substate_integration_payload(
hass_state = hass_state,
@@ -841,6 +842,7 @@ class HassConverter:
name = record_name,
integration_key = substate_integration_key,
value_range_str = value_range_str,
+ units = spec.units,
)
created.append( sensor )
continue
@@ -852,12 +854,26 @@ class HassConverter:
hass_state : HassState,
spec : '_SubstateSpec',
) -> dict:
- return {
+ payload = {
'domain': hass_state.domain,
'is_controllable': spec.is_controllable,
'substate': spec.suffix,
'parent_entity_id': hass_state.entity_id,
}
+ # Climate temperature substates carry HA's currently reported
+ # native unit so dispatch can convert from the EntityState's
+ # stored unit without fetching the live HA state on every
+ # service call. The HI-side unit is read from the
+ # IntegrationMetadataCache (keyed by IntegrationKey) instead of
+ # being duplicated in the payload.
+ if (
+ hass_state.domain == HassApi.CLIMATE_DOMAIN
+ and spec.entity_state_type == EntityStateType.TEMPERATURE
+ ):
+ payload[ 'native_temperature_unit' ] = (
+ hass_state.attributes.get( 'temperature_unit' )
+ )
+ return payload
@classmethod
def _create_hass_state_sensor_or_controller( cls,
@@ -1043,11 +1059,21 @@ class HassConverter:
is_controllable : bool
value_range : Optional[Dict] = None
label : Optional[str] = None
+ units : Optional[str] = None
@property
def display_label(self) -> str:
return self.label if self.label else self.entity_state_type.label
+ # Setpoint slider bounds for thermostat substates, expressed in
+ # ``hi.units.CANONICAL_TEMPERATURE_UNIT``. Climate-specific UX
+ # choices (slightly wider than typical HVAC comfort ranges so
+ # the operator can push edge cases). If the HI-wide canonical
+ # changes, these bounds must also be updated to the equivalent
+ # values in the new unit.
+ _SETPOINT_MIN_CANONICAL = 5
+ _SETPOINT_MAX_CANONICAL = 35
+
# 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
@@ -1082,6 +1108,8 @@ class HassConverter:
return cls._light_substate_specs( hass_state )
if hass_state.domain == HassApi.FAN_DOMAIN:
return cls._fan_substate_specs( hass_state )
+ if hass_state.domain == HassApi.CLIMATE_DOMAIN:
+ return cls._climate_substate_specs( hass_state )
return []
@classmethod
@@ -1190,20 +1218,155 @@ class HassConverter:
))
return specs
+ # HA's well-known set of HVAC action values (what the system
+ # is currently doing). Used as the value range of the
+ # ``hvac_action`` substate so the controller widget displays
+ # human-friendly labels even though the substate is
+ # sensor-only (read from HA, not operator-set).
+ _HVAC_ACTION_CHOICES = {
+ 'heating' : 'Heating',
+ 'cooling' : 'Cooling',
+ 'drying' : 'Drying',
+ 'fan' : 'Fan',
+ 'idle' : 'Idle',
+ 'off' : 'Off',
+ 'preheating' : 'Preheating',
+ 'defrosting' : 'Defrosting',
+ }
+
+ @classmethod
+ def _climate_substate_specs(
+ cls, hass_state: HassState ) -> List[ '_SubstateSpec' ]:
+ """Substates implied by a HA ``climate.x`` state. A climate
+ entity that declares ``hvac_modes`` always decomposes:
+ current_temperature (sensor), hvac_mode (controller from
+ the declared modes list), hvac_action (sensor), plus a
+ setpoint substate set chosen from the supported modes —
+ single ``target_temperature`` for any single-mode
+ operation (heat/cool/off/etc.), low+high pair for
+ ``heat_cool`` mode. Climate entities lacking
+ ``hvac_modes`` fall through to the bare-key TEMPERATURE
+ mapping for backward compatibility."""
+ attrs = hass_state.attributes
+ hvac_modes = attrs.get( 'hvac_modes' )
+ if not isinstance( hvac_modes, list ) or not hvac_modes:
+ return []
+
+ canonical_unit = CANONICAL_TEMPERATURE_UNIT
+ specs = [
+ cls._SubstateSpec(
+ suffix = 'current_temperature',
+ entity_state_type = EntityStateType.TEMPERATURE,
+ is_controllable = False,
+ label = 'Current Temperature',
+ units = canonical_unit,
+ ),
+ cls._SubstateSpec(
+ suffix = 'hvac_mode',
+ entity_state_type = EntityStateType.DISCRETE,
+ is_controllable = True,
+ value_range = { mode: mode for mode in hvac_modes },
+ label = 'HVAC Mode',
+ ),
+ cls._SubstateSpec(
+ suffix = 'hvac_action',
+ entity_state_type = EntityStateType.DISCRETE,
+ is_controllable = False,
+ value_range = dict( cls._HVAC_ACTION_CHOICES ),
+ label = 'HVAC Action',
+ ),
+ ]
+
+ # Setpoint substates: any non-heat_cool mode (heat / cool /
+ # off / dry / fan_only / auto) implies single-setpoint
+ # operation; ``heat_cool`` implies a low/high pair. A
+ # thermostat that supports both creates all three —
+ # which one carries a value at runtime depends on the
+ # active hvac_mode. Bounds are in HI's canonical unit;
+ # display-layer unit conversion happens at render time
+ # against the user's preferred unit.
+ setpoint_range = cls._setpoint_value_range()
+ has_single_mode = any( m != 'heat_cool' for m in hvac_modes )
+ has_dual_mode = 'heat_cool' in hvac_modes
+ if has_single_mode:
+ specs.append( cls._SubstateSpec(
+ suffix = 'target_temperature',
+ entity_state_type = EntityStateType.TEMPERATURE,
+ is_controllable = True,
+ value_range = setpoint_range,
+ label = 'Setpoint',
+ units = canonical_unit,
+ ))
+ if has_dual_mode:
+ specs.append( cls._SubstateSpec(
+ suffix = 'target_temp_low',
+ entity_state_type = EntityStateType.TEMPERATURE,
+ is_controllable = True,
+ value_range = setpoint_range,
+ label = 'Setpoint Low',
+ units = canonical_unit,
+ ))
+ specs.append( cls._SubstateSpec(
+ suffix = 'target_temp_high',
+ entity_state_type = EntityStateType.TEMPERATURE,
+ is_controllable = True,
+ value_range = setpoint_range,
+ label = 'Setpoint High',
+ units = canonical_unit,
+ ))
+
+ # Optional axes that real thermostats commonly expose.
+ # Surfaced only when the live state declares them so HI
+ # doesn't display a "Fan Mode" control on a thermostat
+ # that doesn't have one.
+ fan_modes = attrs.get( 'fan_modes' )
+ if isinstance( fan_modes, list ) and fan_modes:
+ specs.append( cls._SubstateSpec(
+ suffix = 'fan_mode',
+ entity_state_type = EntityStateType.DISCRETE,
+ is_controllable = True,
+ value_range = { mode: mode for mode in fan_modes },
+ label = 'Fan Mode',
+ ))
+ if 'current_humidity' in attrs:
+ specs.append( cls._SubstateSpec(
+ suffix = 'current_humidity',
+ entity_state_type = EntityStateType.HUMIDITY,
+ is_controllable = False,
+ label = 'Current Humidity',
+ ))
+ return specs
+
+ @classmethod
+ def _setpoint_value_range( cls ) -> Dict[ str, float ]:
+ """Slider bounds for thermostat setpoints, in HI's canonical
+ temperature unit. Slightly wider than typical HVAC comfort
+ ranges so the operator can push edge cases. Display layer
+ converts to the user's preferred unit."""
+ return {
+ 'min': cls._SETPOINT_MIN_CANONICAL,
+ 'max': cls._SETPOINT_MAX_CANONICAL,
+ }
+
@classmethod
def _extract_substate_value(
cls,
hass_state : HassState,
- suffix : str,
+ spec : '_SubstateSpec',
) -> Optional[ str ]:
"""Pull the value for a single substate out of a HA state,
dispatching per-domain. Returns ``None`` when the relevant
attribute is absent — callers skip ``None``-valued substates
- from the response map."""
+ from the response map. The full ``spec`` is passed (rather
+ than just the suffix) so per-domain handlers can read
+ metadata such as the spec's canonical ``units`` when
+ normalizing values at the boundary."""
if hass_state.domain == HassApi.LIGHT_DOMAIN:
- return cls._light_substate_value( hass_state, suffix )
+ return cls._light_substate_value( hass_state, spec.suffix )
if hass_state.domain == HassApi.FAN_DOMAIN:
- return cls._fan_substate_value( hass_state, suffix )
+ return cls._fan_substate_value( hass_state, spec.suffix )
+ if hass_state.domain == HassApi.CLIMATE_DOMAIN:
+ return cls._climate_substate_value( hass_state, spec )
return None
@classmethod
@@ -1276,6 +1439,71 @@ class HassConverter:
return attrs.get( 'preset_mode' )
return None
+ @classmethod
+ def _climate_substate_value(
+ cls, hass_state : HassState, spec : '_SubstateSpec' ) -> Optional[ str ]:
+ """Climate-domain substate values. Temperature substates emit
+ floats as strings, converted from HA's reported
+ ``temperature_unit`` to the EntityState's stored unit (looked
+ up via the IntegrationMetadataCache) so cached values stay
+ unit-coherent with the EntityState. Mode/action substates
+ emit HA's wire enum strings unchanged. The hvac_mode's value
+ lives on the entity-level ``state`` field (not in attributes),
+ per HA's climate platform contract. Setpoint substates only
+ emit a value when the matching attribute is present in the
+ live state — HA's setpoint shape varies by mode (single
+ ``temperature`` vs ``target_temp_low`` + ``target_temp_high``)
+ and unused setpoints simply aren't reported."""
+ attrs = hass_state.attributes
+ suffix = spec.suffix
+ if suffix == 'hvac_mode':
+ return hass_state.state_value
+ if suffix == 'hvac_action':
+ return attrs.get( 'hvac_action' )
+ if suffix == 'fan_mode':
+ return attrs.get( 'fan_mode' )
+ if suffix == 'current_humidity':
+ return cls._numeric_attr_as_str( attrs, 'current_humidity' )
+ # Temperature-bearing substates: convert from HA's reported
+ # unit to the EntityState's stored unit at the boundary.
+ attr_key_for_suffix = {
+ 'current_temperature' : 'current_temperature',
+ 'target_temperature' : 'temperature',
+ 'target_temp_low' : 'target_temp_low',
+ 'target_temp_high' : 'target_temp_high',
+ }
+ attr_key = attr_key_for_suffix.get( suffix )
+ if attr_key is None:
+ return None
+ raw = attrs.get( attr_key )
+ if raw is None:
+ return None
+ try:
+ external_value = float( raw )
+ except ( TypeError, ValueError ):
+ return None
+ substate_integration_key = cls._substate_integration_key(
+ hass_state = hass_state,
+ suffix = suffix,
+ )
+ entity_state_value = IntegrationConverterHelper.to_entity_state_value(
+ external_value = external_value,
+ external_unit = attrs.get( 'temperature_unit' ),
+ integration_key = substate_integration_key,
+ )
+ return str( entity_state_value )
+
+ @staticmethod
+ def _numeric_attr_as_str(
+ attrs : Dict, key : str ) -> Optional[ str ]:
+ raw = attrs.get( key )
+ if raw is None:
+ return None
+ try:
+ return str( float( raw ) )
+ except ( TypeError, ValueError ):
+ return None
+
@classmethod
def _substate_integration_key(
cls,
@@ -1492,19 +1720,23 @@ class HassConverter:
"""Create appropriate sensor with legacy parameter handling"""
if entity_state_type == EntityStateType.TEMPERATURE:
- # Handle temperature units from HA data
- unit_str = hass_state.unit_of_measurement or ''
- if 'c' in unit_str.lower():
- temperature_unit = TemperatureUnit.CELSIUS
- else:
- temperature_unit = TemperatureUnit.FAHRENHEIT
-
- sensor = HiModelHelper.create_temperature_sensor(
+ # HA → HI boundary: HI stores temperatures in the canonical
+ # unit; the inbound state translator converts HA's reported
+ # value at every poll. The EntityState.units is the source
+ # of truth (consulted via IntegrationMetadataCache); HA's
+ # native unit lives in the integration_payload for
+ # outbound dispatch convenience.
+ sensor = HiModelHelper.create_sensor(
entity = entity,
- integration_key = integration_key,
+ entity_state_type = EntityStateType.TEMPERATURE,
name = name,
- temperature_unit = temperature_unit,
+ integration_key = integration_key,
+ units = CANONICAL_TEMPERATURE_UNIT,
)
+ domain_payload = {
+ **( domain_payload or {} ),
+ 'native_temperature_unit': hass_state.unit_of_measurement,
+ }
elif entity_state_type == EntityStateType.HUMIDITY:
# Handle humidity units from HA data
unit_str = hass_state.unit_of_measurement or ''
@@ -1813,8 +2045,34 @@ class HassConverter:
return cls._cover_to_sensor_value_map( hass_state )
if domain == HassApi.FAN_DOMAIN:
return cls._fan_to_sensor_value_map( hass_state )
+ if domain == HassApi.CLIMATE_DOMAIN:
+ return cls._climate_to_sensor_value_map( hass_state )
+ if domain == HassApi.SENSOR_DOMAIN:
+ return cls._sensor_domain_to_sensor_value_map( hass_state )
return cls._passthrough_to_sensor_value_map( hass_state )
+ @classmethod
+ def _sensor_domain_to_sensor_value_map(
+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
+ """HA ``sensor.x`` entities. Temperature-class sensors are
+ normalized at this boundary into the EntityState's stored
+ unit (looked up via IntegrationMetadataCache) so cached values
+ stay coherent with the EntityState's units field. Other
+ sensor device classes pass through unchanged."""
+ if hass_state.device_class != HassApi.TEMPERATURE_DEVICE_CLASS:
+ return cls._passthrough_to_sensor_value_map( hass_state )
+ try:
+ external_value = float( hass_state.state_value )
+ except ( TypeError, ValueError ):
+ return {}
+ integration_key = cls.hass_state_to_integration_key( hass_state )
+ entity_state_value = IntegrationConverterHelper.to_entity_state_value(
+ external_value = external_value,
+ external_unit = hass_state.unit_of_measurement,
+ integration_key = integration_key,
+ )
+ return { integration_key : str( entity_state_value ) }
+
@classmethod
def _light_to_sensor_value_map(
cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
@@ -1839,7 +2097,7 @@ class HassConverter:
result[ cls.hass_state_to_integration_key( hass_state ) ] = brightness_value
return result
for spec in substate_specs:
- value = cls._extract_substate_value( hass_state, spec.suffix )
+ value = cls._extract_substate_value( hass_state, spec )
if value is None:
continue
substate_key = cls._substate_integration_key(
@@ -1973,7 +2231,7 @@ class HassConverter:
if substate_specs:
result : Dict[ IntegrationKey, str ] = {}
for spec in substate_specs:
- value = cls._extract_substate_value( hass_state, spec.suffix )
+ value = cls._extract_substate_value( hass_state, spec )
if value is None:
continue
substate_key = cls._substate_integration_key(
@@ -1992,6 +2250,31 @@ class HassConverter:
return {}
return { cls.hass_state_to_integration_key( hass_state ) : str( percentage ) }
+ @classmethod
+ def _climate_to_sensor_value_map(
+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
+ """Climate domain: a thermostat that declares
+ ``hvac_modes`` decomposes into substates (current
+ temperature, mode, action, setpoint(s)) — each value
+ lands at its suffix-keyed integration_key. Climate
+ entities lacking ``hvac_modes`` (rare but allowed by
+ HA's contract) fall through to passthrough behavior."""
+ substate_specs = cls._substate_specs_for_hass_state( hass_state )
+ if not substate_specs:
+ return cls._passthrough_to_sensor_value_map( hass_state )
+ result : Dict[ IntegrationKey, str ] = {}
+ for spec in substate_specs:
+ value = cls._extract_substate_value( hass_state, spec )
+ if value is None:
+ continue
+ substate_key = cls._substate_integration_key(
+ hass_state = hass_state,
+ suffix = spec.suffix,
+ )
+ result[ substate_key ] = value
+ continue
+ return result
+
@classmethod
def _passthrough_to_sensor_value_map(
cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
@@ -2200,6 +2483,111 @@ class HassConverter:
preset_mode = hi_control_value,
)
+ if substate == 'target_temperature':
+ try:
+ entity_state_temperature = cls.to_ha_numeric_parameter_value(
+ hi_control_value,
+ )
+ except ( ValueError, TypeError ):
+ raise ValueError(
+ f'Invalid temperature value: {hi_control_value}'
+ )
+ substate_integration_key = cls._substate_integration_key_for_suffix(
+ parent_entity_id = parent_entity_id,
+ suffix = substate,
+ )
+ temperature = IntegrationConverterHelper.from_entity_state_value(
+ entity_state_value = entity_state_temperature,
+ external_unit = domain_payload.get( 'native_temperature_unit' ),
+ integration_key = substate_integration_key,
+ )
+ return HassServiceComposer.for_temperature(
+ domain = domain,
+ hass_substate_id = parent_entity_id,
+ temperature = temperature,
+ domain_payload = { 'set_service': HassApi.SET_TEMPERATURE_SERVICE },
+ )
+
+ if substate in ( 'target_temp_low', 'target_temp_high' ):
+ 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 = (
+ 'target_temp_high' if substate == 'target_temp_low'
+ else 'target_temp_low'
+ )
+ 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): pick a sensible
+ # ordering around the changed value so HA's call doesn't
+ # reject low > high. Both values are in HI's stored unit
+ # (cached values came through the same boundary-converted
+ # translation path); we convert both to external together.
+ if substate == 'target_temp_low':
+ entity_state_low = changed_value
+ entity_state_high = (
+ partner_value
+ if partner_value is not None and partner_value >= entity_state_low
+ else entity_state_low
+ )
+ else:
+ entity_state_high = changed_value
+ entity_state_low = (
+ partner_value
+ if partner_value is not None and partner_value <= entity_state_high
+ else entity_state_high
+ )
+ external_unit = domain_payload.get( 'native_temperature_unit' )
+ substate_integration_key = cls._substate_integration_key_for_suffix(
+ parent_entity_id = parent_entity_id,
+ suffix = substate,
+ )
+ low = IntegrationConverterHelper.from_entity_state_value(
+ entity_state_value = entity_state_low,
+ external_unit = external_unit,
+ integration_key = substate_integration_key,
+ )
+ high = IntegrationConverterHelper.from_entity_state_value(
+ entity_state_value = entity_state_high,
+ external_unit = external_unit,
+ integration_key = substate_integration_key,
+ )
+ return HassServiceComposer.for_temperature_range(
+ domain = domain,
+ hass_substate_id = parent_entity_id,
+ low = low,
+ high = high,
+ )
+
+ if substate == 'hvac_mode':
+ return HassServiceComposer.for_hvac_mode(
+ domain = domain,
+ hass_substate_id = parent_entity_id,
+ hvac_mode = hi_control_value,
+ )
+
+ if substate == 'fan_mode':
+ return HassServiceComposer.for_fan_mode(
+ domain = domain,
+ hass_substate_id = parent_entity_id,
+ fan_mode = hi_control_value,
+ )
+
raise ValueError( f'Unknown substate: {substate}' )
@classmethod
diff --git a/src/hi/services/hass/hass_models.py b/src/hi/services/hass/hass_models.py
index 66b8cb99..abbf88d8 100644
--- a/src/hi/services/hass/hass_models.py
+++ b/src/hi/services/hass/hass_models.py
@@ -49,6 +49,7 @@ class HassApi:
OSCILLATE_SERVICE = 'oscillate'
SET_DIRECTION_SERVICE = 'set_direction'
SET_PRESET_MODE_SERVICE = 'set_preset_mode'
+ SET_FAN_MODE_SERVICE = 'set_fan_mode'
# Legacy aliases for backward compatibility (remove after migration)
AUTOMATION_ID_PREFIX = AUTOMATION_DOMAIN
diff --git a/src/hi/services/hass/hass_service_composer.py b/src/hi/services/hass/hass_service_composer.py
index c723b78d..3158b698 100644
--- a/src/hi/services/hass/hass_service_composer.py
+++ b/src/hi/services/hass/hass_service_composer.py
@@ -243,6 +243,64 @@ class HassServiceComposer:
service_data = { 'temperature': temperature },
)
+ @classmethod
+ def for_temperature_range(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ low : float,
+ high : float,
+ ) -> HassServiceCall:
+ """``climate.set_temperature`` with the dual-setpoint
+ shape used in ``heat_cool`` mode. HA expects both bounds
+ in the same call; the caller is responsible for
+ composing the unchanged partner from cached state."""
+ if low > high:
+ raise ValueError(
+ f'Invalid temperature range: low={low} > high={high}'
+ )
+ return HassServiceCall(
+ domain = domain,
+ service = HassApi.SET_TEMPERATURE_SERVICE,
+ hass_entity_id = hass_substate_id,
+ service_data = {
+ 'target_temp_low': low,
+ 'target_temp_high': high,
+ },
+ )
+
+ @classmethod
+ def for_hvac_mode(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ hvac_mode : str,
+ ) -> HassServiceCall:
+ if not hvac_mode:
+ raise ValueError( 'hvac_mode must be a non-empty string' )
+ return HassServiceCall(
+ domain = domain,
+ service = HassApi.SET_HVAC_MODE_SERVICE,
+ hass_entity_id = hass_substate_id,
+ service_data = { 'hvac_mode': hvac_mode },
+ )
+
+ @classmethod
+ def for_fan_mode(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ fan_mode : str,
+ ) -> HassServiceCall:
+ if not fan_mode:
+ raise ValueError( 'fan_mode must be a non-empty string' )
+ return HassServiceCall(
+ domain = domain,
+ service = HassApi.SET_FAN_MODE_SERVICE,
+ hass_entity_id = hass_substate_id,
+ service_data = { 'fan_mode': fan_mode },
+ )
+
@classmethod
def for_volume(
cls,
diff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.py
index 90abb850..9be8bf2e 100644
--- a/src/hi/services/hass/monitors.py
+++ b/src/hi/services/hass/monitors.py
@@ -1,5 +1,6 @@
import logging
+from asgiref.sync import sync_to_async
from django.conf import settings
import hi.apps.common.datetimeproxy as datetimeproxy
@@ -95,8 +96,17 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):
current_datetime = datetimeproxy.now()
sensor_response_latest_map = dict()
+ # The converter chain is sync; the IntegrationMetadataCache it
+ # consults may trigger DB queries on cold-cache or new-entity
+ # paths. Wrap each per-state translation through sync_to_async
+ # so any DB work happens in a thread pool rather than raising
+ # SynchronousOnlyOperation in this async monitor context.
+ translate = sync_to_async(
+ HassConverter.hass_state_to_sensor_value_map,
+ thread_sensitive = True,
+ )
for hass_state in id_to_hass_state_map.values():
- value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ value_map = await translate( hass_state )
if settings.DEBUG and settings.DEBUG_TRACE_STATE:
DevOverrideManager.trace_state(
'hi.ha_poll.in',
diff --git a/src/hi/services/hass/tests/test_hass_converter_climate.py b/src/hi/services/hass/tests/test_hass_converter_climate.py
new file mode 100644
index 00000000..443f7b5f
--- /dev/null
+++ b/src/hi/services/hass/tests/test_hass_converter_climate.py
@@ -0,0 +1,667 @@
+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 EntityStateType, EntityType
+from hi.apps.entity.models import EntityState
+from hi.services.hass.hass_converter import HassConverter
+from hi.services.hass.hass_models import HassApi, HassDevice, HassServiceCall
+from hi.integrations.integration_converter_helper import IntegrationConverterHelper
+from hi.integrations.integration_metadata_cache import IntegrationMetadataCache
+from hi.units import CANONICAL_TEMPERATURE_UNIT
+
+logging.disable(logging.CRITICAL)
+
+
+def _make_climate_api_dict(
+ entity_id = 'climate.example',
+ state = 'heat',
+ hvac_modes = None,
+ hvac_action = None,
+ current_temperature = None,
+ temperature = None,
+ target_temp_low = None,
+ target_temp_high = None,
+ fan_modes = None,
+ fan_mode = None,
+ current_humidity = None,
+ temperature_unit = None,
+ friendly_name = None ):
+ attributes = {}
+ if friendly_name:
+ attributes[ 'friendly_name' ] = friendly_name
+ if hvac_modes is not None:
+ attributes[ 'hvac_modes' ] = hvac_modes
+ if hvac_action is not None:
+ attributes[ 'hvac_action' ] = hvac_action
+ if current_temperature is not None:
+ attributes[ 'current_temperature' ] = current_temperature
+ if temperature is not None:
+ attributes[ 'temperature' ] = temperature
+ if target_temp_low is not None:
+ attributes[ 'target_temp_low' ] = target_temp_low
+ if target_temp_high is not None:
+ attributes[ 'target_temp_high' ] = target_temp_high
+ if fan_modes is not None:
+ attributes[ 'fan_modes' ] = fan_modes
+ if fan_mode is not None:
+ attributes[ 'fan_mode' ] = fan_mode
+ if current_humidity is not None:
+ attributes[ 'current_humidity' ] = current_humidity
+ if temperature_unit is not None:
+ attributes[ 'temperature_unit' ] = temperature_unit
+ return {
+ 'entity_id': entity_id,
+ 'state': state,
+ 'attributes': attributes,
+ 'last_changed': '2026-01-01T00:00:00+00:00',
+ 'last_reported': '2026-01-01T00:00:00+00:00',
+ 'last_updated': '2026-01-01T00:00:00+00:00',
+ 'context': { 'id': 'ctx', 'parent_id': None, 'user_id': None },
+ }
+
+
+def _make_climate_hass_state( **kwargs ):
+ return HassConverter.create_hass_state( _make_climate_api_dict( **kwargs ) )
+
+
+def _build_climate_device( device_id, **kwargs ):
+ api_dict = _make_climate_api_dict( entity_id=f'climate.{device_id}', **kwargs )
+ hass_state = HassConverter.create_hass_state( api_dict )
+ device = HassDevice( device_id=device_id )
+ device.add_state( hass_state )
+ return device
+
+
+class TestClimateSubstateSpecs(TestCase):
+ """Climate domain decomposes when ``hvac_modes`` is reported.
+ The spec list reflects what the live state declares — a
+ heat-only thermostat skips the dual-setpoint pair, a
+ thermostat without ``fan_modes`` skips the fan_mode axis,
+ etc."""
+
+ def test_no_hvac_modes_returns_empty_specs(self):
+ # Minimal climate without hvac_modes falls through to
+ # legacy single-state TEMPERATURE handling.
+ hass_state = _make_climate_hass_state( current_temperature=70 )
+ specs = HassConverter._substate_specs_for_hass_state( hass_state )
+ self.assertEqual( specs, [] )
+
+ def test_full_feature_thermostat_has_all_axes(self):
+ hass_state = _make_climate_hass_state(
+ hvac_modes = [ 'heat', 'cool', 'heat_cool', 'off' ],
+ hvac_action = 'idle',
+ current_temperature = 70,
+ target_temp_low = 68, target_temp_high = 75,
+ fan_modes = [ 'auto', 'low', 'high' ],
+ current_humidity = 42,
+ temperature_unit = '°F',
+ )
+ specs = HassConverter._substate_specs_for_hass_state( hass_state )
+ suffixes = [ s.suffix for s in specs ]
+ self.assertEqual( suffixes, [
+ 'current_temperature',
+ 'hvac_mode',
+ 'hvac_action',
+ 'target_temperature',
+ 'target_temp_low',
+ 'target_temp_high',
+ 'fan_mode',
+ 'current_humidity',
+ ])
+
+ def test_heat_only_thermostat_omits_dual_setpoints(self):
+ hass_state = _make_climate_hass_state(
+ hvac_modes = [ 'heat', 'off' ],
+ current_temperature = 21,
+ temperature = 22,
+ temperature_unit = '°C',
+ )
+ specs = HassConverter._substate_specs_for_hass_state( hass_state )
+ suffixes = [ s.suffix for s in specs ]
+ self.assertIn( 'target_temperature', suffixes )
+ self.assertNotIn( 'target_temp_low', suffixes )
+ self.assertNotIn( 'target_temp_high', suffixes )
+
+ def test_heat_cool_only_thermostat_omits_single_setpoint(self):
+ # Pure heat_cool with no other modes: dual setpoints only.
+ hass_state = _make_climate_hass_state(
+ hvac_modes = [ 'heat_cool' ],
+ current_temperature = 70,
+ target_temp_low = 68, target_temp_high = 75,
+ )
+ specs = HassConverter._substate_specs_for_hass_state( hass_state )
+ suffixes = [ s.suffix for s in specs ]
+ self.assertIn( 'target_temp_low', suffixes )
+ self.assertIn( 'target_temp_high', suffixes )
+ self.assertNotIn( 'target_temperature', suffixes )
+
+ def test_setpoint_value_range_is_canonical_unit(self):
+ # Setpoint bounds are always in HI's canonical temperature
+ # unit regardless of HA's reported ``temperature_unit``. The
+ # display layer is responsible for converting bounds to the
+ # user's preferred unit at render time.
+ for ha_unit in ( '°F', '°C', None ):
+ with self.subTest( ha_unit = ha_unit ):
+ hass_state = _make_climate_hass_state(
+ hvac_modes = [ 'heat', 'off' ],
+ temperature_unit = ha_unit,
+ )
+ specs = HassConverter._substate_specs_for_hass_state( hass_state )
+ setpoint = next( s for s in specs if s.suffix == 'target_temperature' )
+ self.assertEqual(
+ setpoint.value_range,
+ {
+ 'min': HassConverter._SETPOINT_MIN_CANONICAL,
+ 'max': HassConverter._SETPOINT_MAX_CANONICAL,
+ },
+ )
+
+ def test_temperature_substates_carry_canonical_units(self):
+ # The temperature-bearing climate substates declare HI's
+ # canonical unit on the spec so it propagates to
+ # EntityState.units at creation time.
+ hass_state = _make_climate_hass_state(
+ hvac_modes = [ 'heat', 'cool', 'heat_cool', 'off' ],
+ current_temperature = 70,
+ target_temp_low = 68, target_temp_high = 75,
+ temperature_unit = '°F',
+ )
+ specs = HassConverter._substate_specs_for_hass_state( hass_state )
+ temperature_suffixes = {
+ 'current_temperature', 'target_temperature',
+ 'target_temp_low', 'target_temp_high',
+ }
+ for spec in specs:
+ if spec.suffix in temperature_suffixes:
+ self.assertEqual(
+ spec.units,
+ CANONICAL_TEMPERATURE_UNIT,
+ f'{spec.suffix} should carry canonical units',
+ )
+
+ def test_hvac_mode_choices_from_hvac_modes(self):
+ hass_state = _make_climate_hass_state(
+ hvac_modes = [ 'heat', 'auto', 'off' ],
+ )
+ specs = HassConverter._substate_specs_for_hass_state( hass_state )
+ hvac_mode = next( s for s in specs if s.suffix == 'hvac_mode' )
+ self.assertEqual(
+ hvac_mode.value_range,
+ { 'heat': 'heat', 'auto': 'auto', 'off': 'off' },
+ )
+
+ def test_fan_mode_value_range_from_fan_modes(self):
+ hass_state = _make_climate_hass_state(
+ hvac_modes = [ 'heat', 'off' ],
+ fan_modes = [ 'auto', 'low', 'medium', 'high' ],
+ )
+ specs = HassConverter._substate_specs_for_hass_state( hass_state )
+ fan_mode = next( s for s in specs if s.suffix == 'fan_mode' )
+ self.assertEqual(
+ fan_mode.value_range,
+ { 'auto': 'auto', 'low': 'low', 'medium': 'medium', 'high': 'high' },
+ )
+
+ def test_fan_mode_omitted_when_fan_modes_absent(self):
+ hass_state = _make_climate_hass_state(
+ hvac_modes = [ 'heat', 'off' ],
+ )
+ specs = HassConverter._substate_specs_for_hass_state( hass_state )
+ suffixes = [ s.suffix for s in specs ]
+ self.assertNotIn( 'fan_mode', suffixes )
+
+
+def _reset_unit_cache():
+ """Singleton cache state must not leak across tests."""
+ cache = IntegrationMetadataCache()
+ cache._cache.clear()
+ cache._warmed = False
+
+
+def _seed_unit_cache_for_climate(parent_entity_id, units, suffixes):
+ """Pre-populate IntegrationMetadataCache for the given climate
+ substates so converter tests can exercise unit-translation paths
+ without first creating Sensor/Controller rows in the DB."""
+ cache = IntegrationMetadataCache()
+ cache._warmed = True
+ for suffix in suffixes:
+ key = HassConverter._substate_integration_key_for_suffix(
+ parent_entity_id = parent_entity_id, suffix = suffix,
+ )
+ cache._cache[ key ] = { 'units': units }
+
+
+class TestClimateInboundStateTranslation(TestCase):
+
+ def setUp(self):
+ _reset_unit_cache()
+
+ def tearDown(self):
+ _reset_unit_cache()
+
+ def test_full_feature_thermostat_emits_all_substates(self):
+ # Native unit matches HI's canonical so values pass through
+ # unchanged — this test exercises substate emission shape.
+ # Inbound conversion when native != canonical is covered
+ # separately below.
+ hass_state = _make_climate_hass_state(
+ entity_id = 'climate.bedroom',
+ state = 'heat_cool',
+ hvac_modes = [ 'heat', 'cool', 'heat_cool', 'off' ],
+ hvac_action = 'idle',
+ current_temperature = 21.5,
+ target_temp_low = 20, target_temp_high = 24,
+ fan_modes = [ 'auto', 'high' ],
+ fan_mode = 'auto',
+ current_humidity = 42,
+ temperature_unit = '°C',
+ )
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ names_to_values = {
+ key.integration_name: value for key, value in value_map.items()
+ }
+ self.assertEqual( names_to_values, {
+ 'climate.bedroom~current_temperature': '21.5',
+ 'climate.bedroom~hvac_mode': 'heat_cool',
+ 'climate.bedroom~hvac_action': 'idle',
+ 'climate.bedroom~target_temp_low': '20.0',
+ 'climate.bedroom~target_temp_high': '24.0',
+ 'climate.bedroom~fan_mode': 'auto',
+ 'climate.bedroom~current_humidity': '42.0',
+ })
+
+ def test_fahrenheit_native_temperatures_converted_to_canonical(self):
+ # An °F-native climate state's temperatures are converted to
+ # HI's canonical unit at the boundary so cached / persisted
+ # values are unit-coherent across the system.
+ _seed_unit_cache_for_climate(
+ parent_entity_id = 'climate.bedroom',
+ units = CANONICAL_TEMPERATURE_UNIT,
+ suffixes = (
+ 'current_temperature', 'target_temp_low', 'target_temp_high',
+ ),
+ )
+ hass_state = _make_climate_hass_state(
+ entity_id = 'climate.bedroom',
+ state = 'heat_cool',
+ hvac_modes = [ 'heat', 'cool', 'heat_cool', 'off' ],
+ hvac_action = 'idle',
+ current_temperature = 71.6,
+ target_temp_low = 68, target_temp_high = 75.2,
+ temperature_unit = '°F',
+ )
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ names_to_values = {
+ key.integration_name: value for key, value in value_map.items()
+ }
+ self.assertAlmostEqual(
+ float( names_to_values[ 'climate.bedroom~current_temperature' ] ),
+ 22.0, places = 2,
+ )
+ self.assertAlmostEqual(
+ float( names_to_values[ 'climate.bedroom~target_temp_low' ] ),
+ 20.0, places = 2,
+ )
+ self.assertAlmostEqual(
+ float( names_to_values[ 'climate.bedroom~target_temp_high' ] ),
+ 24.0, places = 2,
+ )
+
+ def test_unknown_native_unit_falls_through_unchanged(self):
+ # Defensive fallback: if HA reports a unit string we don't
+ # recognize, pass the value through rather than raising.
+ hass_state = _make_climate_hass_state(
+ entity_id = 'climate.exotic',
+ hvac_modes = [ 'heat', 'off' ],
+ current_temperature = 99.9,
+ temperature = 100.0,
+ temperature_unit = 'kelvin',
+ )
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ names_to_values = {
+ key.integration_name: value for key, value in value_map.items()
+ }
+ self.assertEqual(
+ names_to_values[ 'climate.exotic~current_temperature' ],
+ '99.9',
+ )
+
+ def test_single_mode_thermostat_emits_single_setpoint(self):
+ hass_state = _make_climate_hass_state(
+ entity_id = 'climate.heater',
+ state = 'heat',
+ hvac_modes = [ 'heat', 'off' ],
+ hvac_action = 'heating',
+ current_temperature = 21,
+ temperature = 22,
+ temperature_unit = '°C',
+ )
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ names_to_values = {
+ key.integration_name: value for key, value in value_map.items()
+ }
+ self.assertEqual( names_to_values[ 'climate.heater~target_temperature' ], '22.0' )
+ self.assertNotIn( 'climate.heater~target_temp_low', names_to_values )
+ self.assertNotIn( 'climate.heater~target_temp_high', names_to_values )
+
+ def test_missing_attribute_drops_substate_value(self):
+ # heat_cool mode but the dual-setpoint attributes aren't
+ # in the live state — substates exist but emit nothing.
+ hass_state = _make_climate_hass_state(
+ hvac_modes = [ 'heat', 'cool', 'heat_cool' ],
+ current_temperature = 70,
+ )
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ names_to_values = {
+ key.integration_name: value for key, value in value_map.items()
+ }
+ self.assertNotIn( 'climate.example~target_temperature', names_to_values )
+ self.assertNotIn( 'climate.example~target_temp_low', names_to_values )
+
+ def test_non_numeric_temperature_drops_value(self):
+ hass_state = _make_climate_hass_state(
+ hvac_modes = [ 'heat', 'off' ],
+ current_temperature = 'garbage',
+ )
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ names_to_values = {
+ key.integration_name: value for key, value in value_map.items()
+ }
+ self.assertNotIn( 'climate.example~current_temperature', names_to_values )
+
+
+class TestClimateImport(TestCase):
+
+ def setUp(self):
+ _reset_unit_cache()
+
+ def tearDown(self):
+ _reset_unit_cache()
+
+ def test_full_feature_thermostat_imports_all_substates(self):
+ device = _build_climate_device(
+ 'bedroom', state='heat_cool',
+ hvac_modes = [ 'heat', 'cool', 'heat_cool', 'off' ],
+ hvac_action = 'idle',
+ current_temperature = 70,
+ target_temp_low = 68, target_temp_high = 75,
+ fan_modes = [ 'auto', 'high' ],
+ fan_mode = 'auto',
+ current_humidity = 42,
+ temperature_unit = '°F',
+ )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device, add_alarm_events=False,
+ )
+ self.assertEqual( entity.entity_type, EntityType.THERMOSTAT )
+
+ states = list( EntityState.objects.filter( entity=entity ) )
+ self.assertEqual( len( states ), 8 )
+
+ types_by_suffix = {
+ ctrl.integration_payload.get( 'substate' ): ctrl.entity_state.entity_state_type
+ for ctrl in Controller.objects.filter( entity_state__entity=entity )
+ }
+ # Controllable substates only (sensor-only ones don't get controllers).
+ self.assertEqual( types_by_suffix[ 'hvac_mode' ], EntityStateType.DISCRETE )
+ self.assertEqual( types_by_suffix[ 'target_temp_low' ], EntityStateType.TEMPERATURE )
+ self.assertEqual( types_by_suffix[ 'target_temp_high' ], EntityStateType.TEMPERATURE )
+ self.assertEqual( types_by_suffix[ 'target_temperature' ], EntityStateType.TEMPERATURE )
+ self.assertEqual( types_by_suffix[ 'fan_mode' ], EntityStateType.DISCRETE )
+
+ def test_temperature_substates_persist_canonical_units(self):
+ device = _build_climate_device(
+ 'bedroom', state='heat',
+ hvac_modes = [ 'heat', 'off' ],
+ current_temperature = 70, temperature = 72,
+ temperature_unit = '°F',
+ )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device, add_alarm_events=False,
+ )
+ # Find temperature-bearing EntityStates and verify their
+ # units field carries HI's canonical, regardless of HA's
+ # native unit.
+ temp_states = list( EntityState.objects.filter(
+ entity = entity,
+ entity_state_type_str = str( EntityStateType.TEMPERATURE ),
+ ))
+ self.assertGreater( len( temp_states ), 0 )
+ for state in temp_states:
+ self.assertEqual(
+ state.units,
+ CANONICAL_TEMPERATURE_UNIT,
+ )
+
+ def test_setpoint_controller_payload_carries_native_unit(self):
+ # The HI-side unit lives only on EntityState.units (consulted
+ # via the IntegrationMetadataCache); the payload only needs HA's
+ # currently-reported native unit so outbound dispatch can
+ # convert without fetching live HA state.
+ device = _build_climate_device(
+ 'bedroom', state='heat',
+ hvac_modes = [ 'heat', 'off' ],
+ current_temperature = 70, temperature = 72,
+ temperature_unit = '°F',
+ )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device, add_alarm_events=False,
+ )
+ setpoint_ctrl = next(
+ ctrl for ctrl in Controller.objects.filter( entity_state__entity=entity )
+ if ctrl.integration_payload.get( 'substate' ) == 'target_temperature'
+ )
+ payload = setpoint_ctrl.integration_payload
+ self.assertEqual( payload[ 'native_temperature_unit' ], '°F' )
+ self.assertNotIn( 'hi_temperature_unit', payload )
+
+ def test_heat_only_thermostat_imports_minimal_substates(self):
+ device = _build_climate_device(
+ 'heater', state='heat',
+ hvac_modes = [ 'heat', 'off' ],
+ hvac_action = 'heating',
+ current_temperature = 21, temperature = 22,
+ temperature_unit = '°C',
+ )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device, add_alarm_events=False,
+ )
+ states = list( EntityState.objects.filter( entity=entity ) )
+ # current_temperature, hvac_mode, hvac_action, target_temperature
+ self.assertEqual( len( states ), 4 )
+
+ suffixes = {
+ ctrl.integration_payload.get( 'substate' )
+ for ctrl in Controller.objects.filter( entity_state__entity=entity )
+ }
+ self.assertIn( 'target_temperature', suffixes )
+ self.assertIn( 'hvac_mode', suffixes )
+ self.assertNotIn( 'target_temp_low', suffixes )
+ self.assertNotIn( 'fan_mode', suffixes )
+
+
+class TestClimateOutboundDispatch(TestCase):
+ """Climate substate dispatch composes ``set_temperature`` /
+ ``set_hvac_mode`` / ``set_fan_mode`` service calls. The
+ target_temp_low/high pair uses companion-substate cache
+ lookup like hue/saturation."""
+
+ def setUp(self):
+ _reset_unit_cache()
+
+ def tearDown(self):
+ _reset_unit_cache()
+
+ def _payload( self, suffix, native_temperature_unit = None ):
+ payload = {
+ 'domain': HassApi.CLIMATE_DOMAIN,
+ 'is_controllable': True,
+ 'substate': suffix,
+ 'parent_entity_id': 'climate.bedroom',
+ }
+ if native_temperature_unit is not None:
+ payload[ 'native_temperature_unit' ] = native_temperature_unit
+ return payload
+
+ def test_target_temperature_routes_to_set_temperature(self):
+ call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='climate.bedroom~target_temperature',
+ hi_control_value='73',
+ domain_payload=self._payload( 'target_temperature' ),
+ )
+ self.assertEqual( call, HassServiceCall(
+ domain = HassApi.CLIMATE_DOMAIN,
+ service = HassApi.SET_TEMPERATURE_SERVICE,
+ hass_entity_id = 'climate.bedroom',
+ service_data = { 'temperature': 73.0 },
+ ))
+
+ def test_hvac_mode_routes_to_set_hvac_mode(self):
+ call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='climate.bedroom~hvac_mode',
+ hi_control_value='cool',
+ domain_payload=self._payload( 'hvac_mode' ),
+ )
+ self.assertEqual( call, HassServiceCall(
+ domain = HassApi.CLIMATE_DOMAIN,
+ service = HassApi.SET_HVAC_MODE_SERVICE,
+ hass_entity_id = 'climate.bedroom',
+ service_data = { 'hvac_mode': 'cool' },
+ ))
+
+ def test_fan_mode_routes_to_set_fan_mode(self):
+ call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='climate.bedroom~fan_mode',
+ hi_control_value='high',
+ domain_payload=self._payload( 'fan_mode' ),
+ )
+ self.assertEqual( call, HassServiceCall(
+ domain = HassApi.CLIMATE_DOMAIN,
+ service = HassApi.SET_FAN_MODE_SERVICE,
+ hass_entity_id = 'climate.bedroom',
+ service_data = { 'fan_mode': 'high' },
+ ))
+
+ def test_target_temp_low_routes_to_range_with_cached_partner(self):
+ partner_key = HassConverter._substate_integration_key_for_suffix(
+ parent_entity_id='climate.bedroom', suffix='target_temp_high',
+ )
+ with patch.object(
+ IntegrationConverterHelper, 'get_latest_state_values',
+ return_value={ partner_key: '76' },
+ ):
+ call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='climate.bedroom~target_temp_low',
+ hi_control_value='68',
+ domain_payload=self._payload( 'target_temp_low' ),
+ )
+ self.assertEqual( call.service_data, {
+ 'target_temp_low': 68.0,
+ 'target_temp_high': 76.0,
+ })
+
+ def test_target_temp_high_routes_to_range_with_cached_partner(self):
+ partner_key = HassConverter._substate_integration_key_for_suffix(
+ parent_entity_id='climate.bedroom', suffix='target_temp_low',
+ )
+ with patch.object(
+ IntegrationConverterHelper, 'get_latest_state_values',
+ return_value={ partner_key: '67' },
+ ):
+ call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='climate.bedroom~target_temp_high',
+ hi_control_value='80',
+ domain_payload=self._payload( 'target_temp_high' ),
+ )
+ self.assertEqual( call.service_data, {
+ 'target_temp_low': 67.0,
+ 'target_temp_high': 80.0,
+ })
+
+ def test_target_temp_pair_no_cached_partner_falls_back(self):
+ # Without a cached partner value, the changed value is
+ # used for both bounds — safe ordering, no HA error.
+ with patch.object(
+ IntegrationConverterHelper, 'get_latest_state_values',
+ return_value={},
+ ):
+ call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='climate.bedroom~target_temp_low',
+ hi_control_value='70',
+ domain_payload=self._payload( 'target_temp_low' ),
+ )
+ self.assertEqual( call.service_data, {
+ 'target_temp_low': 70.0,
+ 'target_temp_high': 70.0,
+ })
+
+ def test_target_temperature_converts_canonical_to_native(self):
+ # HI's stored value is in canonical units; payload-tagged
+ # native unit drives outbound conversion at the boundary.
+ # The HI-side unit is read from the IntegrationMetadataCache.
+ _seed_unit_cache_for_climate(
+ parent_entity_id = 'climate.bedroom',
+ units = '°C',
+ suffixes = ( 'target_temperature', ),
+ )
+ call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='climate.bedroom~target_temperature',
+ hi_control_value='22',
+ domain_payload=self._payload(
+ 'target_temperature',
+ native_temperature_unit = '°F',
+ ),
+ )
+ self.assertAlmostEqual(
+ call.service_data[ 'temperature' ], 71.6, places = 2,
+ )
+
+ def test_target_temp_range_converts_canonical_to_native(self):
+ _seed_unit_cache_for_climate(
+ parent_entity_id = 'climate.bedroom',
+ units = '°C',
+ suffixes = ( 'target_temp_low', 'target_temp_high' ),
+ )
+ partner_key = HassConverter._substate_integration_key_for_suffix(
+ parent_entity_id='climate.bedroom', suffix='target_temp_high',
+ )
+ # Cached partner value is also in canonical units (it came
+ # through the same boundary-converted translation path).
+ with patch.object(
+ IntegrationConverterHelper, 'get_latest_state_values',
+ return_value={ partner_key: '24' },
+ ):
+ call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='climate.bedroom~target_temp_low',
+ hi_control_value='20',
+ domain_payload=self._payload(
+ 'target_temp_low',
+ native_temperature_unit = '°F',
+ ),
+ )
+ self.assertAlmostEqual(
+ call.service_data[ 'target_temp_low' ], 68.0, places = 2,
+ )
+ self.assertAlmostEqual(
+ call.service_data[ 'target_temp_high' ], 75.2, places = 2,
+ )
+
+ def test_target_temperature_no_conversion_when_units_match(self):
+ # When HI's unit matches HA's native, value passes through.
+ _seed_unit_cache_for_climate(
+ parent_entity_id = 'climate.bedroom',
+ units = '°C',
+ suffixes = ( 'target_temperature', ),
+ )
+ call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='climate.bedroom~target_temperature',
+ hi_control_value='22',
+ domain_payload=self._payload(
+ 'target_temperature',
+ native_temperature_unit = '°C',
+ ),
+ )
+ self.assertEqual( call.service_data, { 'temperature': 22.0 } )
diff --git a/src/hi/services/hass/tests/test_hass_service_composer.py b/src/hi/services/hass/tests/test_hass_service_composer.py
index 177708ae..046fe9d9 100644
--- a/src/hi/services/hass/tests/test_hass_service_composer.py
+++ b/src/hi/services/hass/tests/test_hass_service_composer.py
@@ -374,3 +374,49 @@ class TestFanAxisComposers(TestCase):
HassServiceComposer.for_preset_mode(
domain='fan', hass_substate_id='fan.x', preset_mode='',
)
+
+
+class TestClimateAxisComposers(TestCase):
+
+ def test_for_temperature_range_valid(self):
+ result = HassServiceComposer.for_temperature_range(
+ domain='climate', hass_substate_id='climate.x',
+ low=68, high=75,
+ )
+ self.assertEqual(result.service, 'set_temperature')
+ self.assertEqual(result.service_data, {
+ 'target_temp_low': 68, 'target_temp_high': 75,
+ })
+
+ def test_for_temperature_range_low_above_high_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_temperature_range(
+ domain='climate', hass_substate_id='climate.x',
+ low=80, high=70,
+ )
+
+ def test_for_hvac_mode_valid(self):
+ result = HassServiceComposer.for_hvac_mode(
+ domain='climate', hass_substate_id='climate.x', hvac_mode='cool',
+ )
+ self.assertEqual(result.service, 'set_hvac_mode')
+ self.assertEqual(result.service_data, {'hvac_mode': 'cool'})
+
+ def test_for_hvac_mode_empty_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_hvac_mode(
+ domain='climate', hass_substate_id='climate.x', hvac_mode='',
+ )
+
+ def test_for_fan_mode_valid(self):
+ result = HassServiceComposer.for_fan_mode(
+ domain='climate', hass_substate_id='climate.x', fan_mode='high',
+ )
+ self.assertEqual(result.service, 'set_fan_mode')
+ self.assertEqual(result.service_data, {'fan_mode': 'high'})
+
+ def test_for_fan_mode_empty_raises(self):
+ with self.assertRaises(ValueError):
+ HassServiceComposer.for_fan_mode(
+ domain='climate', hass_substate_id='climate.x', fan_mode='',
+ )
diff --git a/src/hi/simulator/base_models.py b/src/hi/simulator/base_models.py
index 378ff275..d47a4789 100644
--- a/src/hi/simulator/base_models.py
+++ b/src/hi/simulator/base_models.py
@@ -136,6 +136,14 @@ class SimState:
""" Subclasses using SimStateType.DISCRETE should override this to provide the valid values. """
return list()
+ @property
+ def display_unit(self) -> str:
+ """Optional unit suffix shown next to the value/bounds in
+ the simulator UI (e.g., ``°F`` next to a thermostat
+ temperature). Subclasses with unit-bearing values should
+ override; default is empty (no suffix)."""
+ return ''
+
def copy_value( self, other_sim_state : 'SimState' ):
if not other_sim_state:
return
diff --git a/src/hi/simulator/enums.py b/src/hi/simulator/enums.py
index 802068e7..22b2d510 100644
--- a/src/hi/simulator/enums.py
+++ b/src/hi/simulator/enums.py
@@ -60,6 +60,21 @@ class SimulatorFaultMode(LabeledEnum):
return cls.HEALTHY
+class SimTemperatureUnit(LabeledEnum):
+ """Integration-agnostic temperature unit choice for the
+ simulator's runtime override. Each integration's composer maps
+ these to its own wire format (e.g., HA uses ``°F`` / ``°C``;
+ other integrations may use ``degF`` / ``degC`` or other
+ conventions)."""
+
+ FAHRENHEIT = ( 'Fahrenheit', '' )
+ CELSIUS = ( 'Celsius', '' )
+
+ @classmethod
+ def default(cls):
+ return cls.FAHRENHEIT
+
+
class SimEntityType(LabeledEnum):
AIR_CONDITIONER = ( 'Air Conditioner', '' )
diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.py
index 7c30c0db..8bfa89cf 100644
--- a/src/hi/simulator/management/commands/seed_sim_profiles.py
+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py
@@ -87,6 +87,7 @@ from hi.simulator.services.hass.sim_models import (
HassLockFields,
HassMultiFeatureFanFields,
HassSmartBulbFields,
+ HassThermostatFields,
HassWindowBlindCoverFields,
)
from hi.simulator.services.homebox.attachment_catalog import AttachmentTemplate
@@ -357,6 +358,13 @@ class Command(BaseCommand):
self._add_hass_generic_cover( profile, 'Zoo Cover' )
self._add_hass_ceiling_fan( profile, 'Zoo Fan' )
self._add_hass_multi_feature_fan( profile, 'Zoo Smart Fan' )
+ self._add_hass_thermostat( profile, 'Zoo Thermostat' )
+ self._add_hass_thermostat(
+ profile, 'Zoo Heater',
+ hvac_modes = [ 'heat', 'off' ],
+ fan_modes = [],
+ temperature_unit = '°C',
+ )
return profile.db_sim_entities.count()
def _build_volume(self, profile: SimProfile) -> int:
@@ -542,6 +550,25 @@ class Command(BaseCommand):
fields_kwargs = {'name': name},
)
+ def _add_hass_thermostat(self, profile, name,
+ hvac_modes=None, fan_modes=None,
+ temperature_unit='°F'):
+ fields_kwargs = {
+ 'name': name,
+ 'temperature_unit': temperature_unit,
+ }
+ if hvac_modes is not None:
+ fields_kwargs[ 'hvac_modes' ] = hvac_modes
+ if fan_modes is not None:
+ fields_kwargs[ 'fan_modes' ] = fan_modes
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassThermostatFields,
+ sim_entity_type = SimEntityType.THERMOSTAT,
+ fields_kwargs = fields_kwargs,
+ )
+
def _add_homebox_item(self, profile, name, **fields_kwargs):
kwargs = {'name': name}
kwargs.update(fields_kwargs)
diff --git a/src/hi/simulator/runtime_settings.py b/src/hi/simulator/runtime_settings.py
new file mode 100644
index 00000000..5857c00a
--- /dev/null
+++ b/src/hi/simulator/runtime_settings.py
@@ -0,0 +1,44 @@
+from typing import Optional
+
+from hi.apps.common.singleton import Singleton
+
+from .enums import SimTemperatureUnit
+
+
+class SimulatorRuntimeSettings( Singleton ):
+ """Process-wide, in-memory settings that affect simulator
+ behavior at runtime without touching persistent state.
+
+ These are dev-tool toggles intended to make it easy to flex
+ the HI translation layers (e.g., flip what unit a simulated
+ integration reports temperatures in) without re-seeding
+ profiles. Resets to defaults on process restart by design —
+ nothing here is persisted.
+
+ Today the only setting is ``temperature_unit_override``: None
+ means profiles use their own per-entity unit; otherwise a
+ ``SimTemperatureUnit`` value forces every emitted temperature
+ to that unit (with magnitudes converted so the physical
+ temperature stays constant). Each integration's composer is
+ responsible for mapping the enum to its own wire format.
+
+ Add new toggles here as needed; the API is intentionally
+ integration-agnostic.
+ """
+
+ def __init_singleton__(self):
+ self._temperature_unit_override : Optional[SimTemperatureUnit] = None
+ return
+
+ @property
+ def temperature_unit_override(self) -> Optional[SimTemperatureUnit]:
+ return self._temperature_unit_override
+
+ def set_temperature_unit_override(
+ self, value : Optional[SimTemperatureUnit] ):
+ if value is not None and not isinstance( value, SimTemperatureUnit ):
+ raise ValueError(
+ f'Invalid temperature_unit_override: {value!r}'
+ )
+ self._temperature_unit_override = value
+ return
diff --git a/src/hi/simulator/services/hass/api_composers.py b/src/hi/simulator/services/hass/api_composers.py
index f8b0cadd..244fe8ad 100644
--- a/src/hi/simulator/services/hass/api_composers.py
+++ b/src/hi/simulator/services/hass/api_composers.py
@@ -30,7 +30,10 @@ from .sim_models import (
HassColorSmartBulbFields,
HassMultiFeatureFanFields,
HassMultiFeatureFanPercentageState,
+ HassThermostatFields,
+ HassThermostatHvacModeState,
)
+from .unit_translation import UnitTranslationHelper
class HassApiComposer:
@@ -128,6 +131,91 @@ class HassApiComposer:
primary_dict[ 'attributes' ] = merged_attrs
return [ primary_dict ]
+ @staticmethod
+ def _thermostat( sim_states : List[ SimState ] ) -> List[ Dict ]:
+ """Compose a thermostat's substate SimStates into ONE HA
+ ``climate.x`` entity. The HVAC-mode SimState carries the
+ primary state (HA climate's ``state`` field is the active
+ hvac_mode). Setpoint shape varies with the active mode:
+ ``heat_cool`` emits ``target_temp_low`` /
+ ``target_temp_high``, every other mode emits a single
+ ``temperature``. Real HA thermostats behave the same way."""
+ primary_dict = None
+ merged_attrs : Dict = {}
+ active_mode = None
+ partials : Dict = {}
+ temperature_unit = None
+ for state in sim_states:
+ api_dict = state.to_api_dict()
+ if isinstance( state, HassThermostatHvacModeState ):
+ primary_dict = dict( api_dict )
+ active_mode = state.value
+ merged_attrs.update( api_dict.get( 'attributes', {} ) )
+ sim_entity_fields = getattr( state, 'sim_entity_fields', None )
+ if isinstance( sim_entity_fields, HassThermostatFields ):
+ temperature_unit = sim_entity_fields.temperature_unit
+ continue
+
+ # Lift partial setpoint contributions into the active-mode
+ # shape; drop the partial markers either way so they don't
+ # leak into the emitted attributes.
+ for partial_key in (
+ '_partial_target_temperature',
+ '_partial_target_temp_low',
+ '_partial_target_temp_high',
+ ):
+ if partial_key in merged_attrs:
+ partials[ partial_key ] = merged_attrs.pop( partial_key )
+
+ if active_mode == 'heat_cool':
+ if '_partial_target_temp_low' in partials:
+ merged_attrs[ 'target_temp_low' ] = partials[ '_partial_target_temp_low' ]
+ if '_partial_target_temp_high' in partials:
+ merged_attrs[ 'target_temp_high' ] = partials[ '_partial_target_temp_high' ]
+ else:
+ if '_partial_target_temperature' in partials:
+ merged_attrs[ 'temperature' ] = partials[ '_partial_target_temperature' ]
+
+ # Apply the simulator's process-wide temperature unit
+ # override (if set). Convert all temperature attributes from
+ # the profile-defined unit to the override unit so the
+ # physical temperature stays constant; the wire-format
+ # ``temperature_unit`` flips with them.
+ emitted_unit = UnitTranslationHelper.emitted_temperature_unit(
+ profile_unit = temperature_unit,
+ )
+ if emitted_unit is not None and emitted_unit != temperature_unit:
+ for attr in (
+ 'current_temperature', 'temperature',
+ 'target_temp_low', 'target_temp_high',
+ 'min_temp', 'max_temp',
+ ):
+ if attr in merged_attrs:
+ merged_attrs[ attr ] = UnitTranslationHelper.convert_temperature_value(
+ merged_attrs[ attr ],
+ from_unit = temperature_unit,
+ to_unit = emitted_unit,
+ )
+ if emitted_unit is not None:
+ merged_attrs[ 'temperature_unit' ] = emitted_unit
+
+ # friendly_name lives at the entity level (HA's contract is
+ # one ``climate.x`` per thermostat regardless of how many
+ # internal axes the simulator decomposes it into), so set
+ # it once on the merged attributes from any state's
+ # ``entity_name`` rather than duplicating across substates.
+ for state in sim_states:
+ if isinstance( getattr( state, 'sim_entity_fields', None ),
+ HassThermostatFields ):
+ merged_attrs[ 'friendly_name' ] = state.entity_name
+ break
+
+ if primary_dict is None:
+ return HassApiComposer._default( sim_states )
+
+ primary_dict[ 'attributes' ] = merged_attrs
+ return [ primary_dict ]
+
# Registry built after the class is defined so the classmethod
# objects exist as references. Keyed off SimEntityFields class so
@@ -135,4 +223,5 @@ class HassApiComposer:
HassApiComposer._REGISTRY = {
HassColorSmartBulbFields: HassApiComposer._color_smart_bulb,
HassMultiFeatureFanFields: HassApiComposer._multi_feature_fan,
+ HassThermostatFields: HassApiComposer._thermostat,
}
diff --git a/src/hi/simulator/services/hass/service_dispatchers.py b/src/hi/simulator/services/hass/service_dispatchers.py
index 36b346d3..360aeb5c 100644
--- a/src/hi/simulator/services/hass/service_dispatchers.py
+++ b/src/hi/simulator/services/hass/service_dispatchers.py
@@ -28,6 +28,7 @@ from typing import Any, Dict, List, Optional, Tuple
from hi.simulator.enums import SimStateType
+from .unit_translation import UnitTranslationHelper
from .sim_models import (
HassColorSmartBulbFields,
HassFanFields,
@@ -35,6 +36,7 @@ from .sim_models import (
HassGenericCoverFields,
HassLockFields,
HassMultiFeatureFanFields,
+ HassThermostatFields,
HassWindowBlindCoverFields,
)
@@ -291,6 +293,65 @@ class HassServiceDispatcher:
return [ ( 'preset', str( preset_mode ) ) ]
return []
+ @staticmethod
+ def _thermostat( sim_entity,
+ domain : str,
+ service : str,
+ payload : Dict[ str, Any ],
+ ) -> List[ Tuple[ str, str ] ]:
+ """Thermostat: routes ``set_temperature`` (with ``temperature``
+ / ``target_temp_low`` / ``target_temp_high``) and
+ ``set_hvac_mode`` to the matching SimStates. HA's
+ ``set_temperature`` service accepts either a single
+ ``temperature`` or the low/high pair depending on the
+ thermostat's active mode — the dispatcher applies whatever
+ the payload carries.
+
+ Incoming temperature values are in the unit the simulator
+ was emitting at request time (profile unit by default; the
+ runtime override's unit when set). SimStates store in the
+ profile's unit, so we reverse-translate here to keep
+ internal storage unit-coherent with each profile's per-
+ entity ``temperature_unit``."""
+ if domain != 'climate':
+ return []
+ updates : List[ Tuple[ str, str ] ] = []
+ if service == 'set_temperature':
+ profile_unit = getattr(
+ sim_entity.sim_entity_fields, 'temperature_unit', None,
+ )
+ emitted_unit = UnitTranslationHelper.emitted_temperature_unit(
+ profile_unit = profile_unit,
+ )
+ for key, sim_state_id in (
+ ( 'temperature', 'target_temperature' ),
+ ( 'target_temp_low', 'target_temp_low' ),
+ ( 'target_temp_high', 'target_temp_high' ),
+ ):
+ if key in payload:
+ try:
+ numeric = float( payload[ key ] )
+ except ( TypeError, ValueError ):
+ continue
+ profile_unit_value = UnitTranslationHelper.convert_temperature_value(
+ numeric,
+ from_unit = emitted_unit,
+ to_unit = profile_unit,
+ )
+ updates.append( ( sim_state_id, str( profile_unit_value ) ) )
+ return updates
+ if service == 'set_hvac_mode':
+ mode = payload.get( 'hvac_mode' )
+ if not mode:
+ return []
+ return [ ( 'hvac_mode', str( mode ) ) ]
+ if service == 'set_fan_mode':
+ mode = payload.get( 'fan_mode' )
+ if not mode:
+ return []
+ return [ ( 'fan_mode', str( mode ) ) ]
+ return []
+
@staticmethod
def _extract_percentage_value_str( payload : Dict[ str, Any ] ) -> Optional[ str ]:
"""Read fan ``percentage`` from an HA service-call
@@ -334,5 +395,6 @@ HassServiceDispatcher._REGISTRY = {
HassGenericCoverFields: HassServiceDispatcher._discrete_cover,
HassLockFields: HassServiceDispatcher._lock,
HassMultiFeatureFanFields: HassServiceDispatcher._multi_feature_fan,
+ HassThermostatFields: HassServiceDispatcher._thermostat,
HassWindowBlindCoverFields: HassServiceDispatcher._window_blind_cover,
}
diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.py
index 4387b2a0..050a10b9 100644
--- a/src/hi/simulator/services/hass/sim_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -1,5 +1,5 @@
import base64
-from dataclasses import dataclass
+from dataclasses import dataclass, field
import os
import time
from typing import ClassVar, Dict, List, Tuple
@@ -1108,6 +1108,442 @@ class HassMultiFeatureFanPresetState( HassState ):
}
+# Per-mode display labels for the operator-facing dropdown in
+# the simulator UI. Per-instance ``hvac_modes`` (set on the
+# fields) is filtered against this map to build the choices
+# list — so each thermostat advertises only the modes its
+# fields declare.
+_THERMOSTAT_HVAC_MODE_LABELS = {
+ 'heat' : 'Heat',
+ 'cool' : 'Cool',
+ 'heat_cool' : 'Heat/Cool',
+ 'off' : 'Off',
+ 'auto' : 'Auto',
+ 'dry' : 'Dry',
+ 'fan_only' : 'Fan Only',
+}
+_THERMOSTAT_HVAC_ACTION_CHOICES = [
+ ( 'heating', 'Heating' ),
+ ( 'cooling', 'Cooling' ),
+ ( 'idle', 'Idle' ),
+ ( 'off', 'Off' ),
+]
+
+
+@dataclass( frozen = True )
+class HassThermostatFields( SimEntityFields ):
+ """A multi-axis thermostat. Composed of multiple SimStates
+ (current_temperature, target_temperature, target_temp_low,
+ target_temp_high, hvac_mode, hvac_action, fan_mode,
+ current_humidity) collapsed into one HA ``climate.x``
+ entity at emit time.
+
+ ``hvac_modes`` declares the modes this thermostat supports —
+ a heat-only thermostat omits ``heat_cool`` (and HI
+ accordingly creates only the single-setpoint substate, not
+ the low/high pair). ``fan_modes`` declares the available
+ fan settings (when empty, the thermostat doesn't expose a
+ fan-mode axis). ``temperature_unit`` controls °F vs °C
+ handling end-to-end so HI's unit passthrough can be
+ exercised for both."""
+
+ hvac_modes : list = field(
+ default_factory = lambda : [ 'heat', 'cool', 'heat_cool', 'off' ],
+ )
+ fan_modes : list = field(
+ default_factory = lambda : [ 'auto', 'low', 'medium', 'high' ],
+ )
+ temperature_unit : str = '°F'
+
+
+def _thermostat_entity_id( name : str ) -> str:
+ suffix = name.lower().replace( ' ', '_' )
+ return f'climate.{suffix}'
+
+
+class _ThermostatTemperatureDefaultMixin:
+ """Mixin for thermostat temperature SimStates that swaps the
+ Fahrenheit-style class default (e.g., ``'70'``) for a sensible
+ Celsius value when the parent entity is configured °C-native.
+
+ Without this, °C-native profiles (e.g., Zoo Heater) would
+ initialize ``current_temperature = 70`` meaning 70°C — over
+ 150°F, which makes the simulator's value confusing on first
+ load. Subclasses set ``_CELSIUS_DEFAULT_VALUE``; the mixin
+ detects the dataclass field default and swaps it in. User-
+ overridden values (set via the simulator UI) bypass the swap
+ because they no longer match the class default."""
+
+ _CELSIUS_DEFAULT_VALUE : str = ''
+
+ # Slider bounds used when temperature_unit is °F (the seed
+ # default) and °C respectively. Picked so both ranges cover
+ # roughly the same physical span (−1°C / 30°F at the low end,
+ # ~38°C / 100°F at the high end), with round numbers in each
+ # unit so the slider looks natural.
+ _FAHRENHEIT_MIN = 30
+ _FAHRENHEIT_MAX = 100
+ _CELSIUS_MIN = 0
+ _CELSIUS_MAX = 40
+
+ def _apply_celsius_default_if_native(self):
+ if not self._CELSIUS_DEFAULT_VALUE:
+ return
+ if getattr( self.sim_entity_fields, 'temperature_unit', None ) != '°C':
+ return
+ class_default = type( self ).__dataclass_fields__[ 'value' ].default
+ if self.value == class_default:
+ self.value = self._CELSIUS_DEFAULT_VALUE
+
+ def _is_celsius_native(self) -> bool:
+ return getattr(
+ self.sim_entity_fields, 'temperature_unit', None,
+ ) == '°C'
+
+ @property
+ def min_value(self):
+ return self._CELSIUS_MIN if self._is_celsius_native() else self._FAHRENHEIT_MIN
+
+ @property
+ def max_value(self):
+ return self._CELSIUS_MAX if self._is_celsius_native() else self._FAHRENHEIT_MAX
+
+ @property
+ def display_unit(self) -> str:
+ """The profile-defined temperature unit. The simulator UI
+ shows ``self.value`` directly — and the SimState always
+ stores in the profile's unit (the runtime override only
+ applies at the wire boundary in the composer/dispatcher).
+ So the slider label should be the profile unit too,
+ regardless of any active override."""
+ return getattr(
+ self.sim_entity_fields, 'temperature_unit', '',
+ ) or ''
+
+
+@dataclass
+class HassThermostatCurrentTemperatureState(
+ _ThermostatTemperatureDefaultMixin, HassState ):
+ """Current temperature reading. Sensor-only in HA terms but
+ operator-controllable in the simulator UI so a tester can
+ drive temperature changes (otherwise there's nothing to
+ test)."""
+
+ sim_entity_fields : HassThermostatFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'current_temperature'
+ value : str = '70'
+
+ _CELSIUS_DEFAULT_VALUE = '21'
+
+ def __post_init__(self):
+ super().__post_init__()
+ self._apply_celsius_default_if_native()
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Current Temperature'
+
+ @property
+ def entity_id(self):
+ return _thermostat_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ # Composer overrides; entity-level state is the hvac_mode.
+ return 'on'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ try:
+ temp = float( self.value )
+ except ( TypeError, ValueError ):
+ temp = 0.0
+ return { 'current_temperature': temp }
+
+
+@dataclass
+class HassThermostatTargetTemperatureState(
+ _ThermostatTemperatureDefaultMixin, HassState ):
+ """Single setpoint (used when hvac_mode is heat / cool / off
+ / etc., not heat_cool). Composer emits this only when the
+ active mode isn't ``heat_cool``."""
+
+ sim_entity_fields : HassThermostatFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'target_temperature'
+ value : str = '72'
+
+ _CELSIUS_DEFAULT_VALUE = '22'
+
+ def __post_init__(self):
+ super().__post_init__()
+ self._apply_celsius_default_if_native()
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Setpoint'
+
+ @property
+ def entity_id(self):
+ return _thermostat_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'on'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ try:
+ temp = float( self.value )
+ except ( TypeError, ValueError ):
+ temp = 0.0
+ # Marked partial so the composer can decide whether to
+ # emit it based on the active hvac_mode.
+ return { '_partial_target_temperature': temp }
+
+
+@dataclass
+class HassThermostatTargetTempLowState(
+ _ThermostatTemperatureDefaultMixin, HassState ):
+ """Low setpoint of the heat_cool pair. Emitted by the composer
+ only when the active mode is heat_cool."""
+
+ sim_entity_fields : HassThermostatFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'target_temp_low'
+ value : str = '68'
+
+ _CELSIUS_DEFAULT_VALUE = '20'
+
+ def __post_init__(self):
+ super().__post_init__()
+ self._apply_celsius_default_if_native()
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Setpoint Low'
+
+ @property
+ def entity_id(self):
+ return _thermostat_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'on'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ try:
+ temp = float( self.value )
+ except ( TypeError, ValueError ):
+ temp = 0.0
+ return { '_partial_target_temp_low': temp }
+
+
+@dataclass
+class HassThermostatTargetTempHighState(
+ _ThermostatTemperatureDefaultMixin, HassState ):
+ """High setpoint of the heat_cool pair. Emitted by the composer
+ only when the active mode is heat_cool."""
+
+ sim_entity_fields : HassThermostatFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'target_temp_high'
+ value : str = '75'
+
+ _CELSIUS_DEFAULT_VALUE = '24'
+
+ def __post_init__(self):
+ super().__post_init__()
+ self._apply_celsius_default_if_native()
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Setpoint High'
+
+ @property
+ def entity_id(self):
+ return _thermostat_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'on'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ try:
+ temp = float( self.value )
+ except ( TypeError, ValueError ):
+ temp = 0.0
+ return { '_partial_target_temp_high': temp }
+
+
+@dataclass
+class HassThermostatHvacModeState( HassState ):
+ """HVAC mode (DISCRETE, controllable). Active mode drives
+ the entity-level ``state`` field; the composer pulls this
+ state's value into the primary api_dict's state. The
+ available choices and the emitted ``hvac_modes`` attribute
+ both come from the per-thermostat fields, so a heat-only
+ thermostat naturally exposes only ``heat`` / ``off``."""
+
+ sim_entity_fields : HassThermostatFields
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ sim_state_id : str = 'hvac_mode'
+ value : str = 'heat'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} HVAC Mode'
+
+ @property
+ def entity_id(self):
+ return _thermostat_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ # Carries the mode for the composer to lift into the
+ # entity-level ``state`` field.
+ return self.value
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ] ]:
+ return [
+ ( mode, _THERMOSTAT_HVAC_MODE_LABELS.get( mode, mode ) )
+ for mode in self.sim_entity_fields.hvac_modes
+ ]
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ # The mode is the entity's primary state, not an
+ # attribute. Emit the supported-modes list as the
+ # entity's ``hvac_modes`` attribute so HI's converter
+ # can build the substate value range.
+ return {
+ 'hvac_modes': list( self.sim_entity_fields.hvac_modes ),
+ }
+
+
+@dataclass
+class HassThermostatFanModeState( HassState ):
+ """Fan mode (DISCRETE, controllable). Choices come from the
+ per-thermostat ``fan_modes`` field — a thermostat with
+ ``fan_modes=[]`` exposes no choices and the composer drops
+ the attribute. Common HA values: auto / low / medium / high
+ / on / off."""
+
+ sim_entity_fields : HassThermostatFields
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ sim_state_id : str = 'fan_mode'
+ value : str = 'auto'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Fan Mode'
+
+ @property
+ def entity_id(self):
+ return _thermostat_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'on'
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ] ]:
+ return [
+ ( mode, mode.title() )
+ for mode in self.sim_entity_fields.fan_modes
+ ]
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ if not self.sim_entity_fields.fan_modes:
+ return {}
+ return {
+ 'fan_mode': self.value,
+ 'fan_modes': list( self.sim_entity_fields.fan_modes ),
+ }
+
+
+@dataclass
+class HassThermostatCurrentHumidityState( HassState ):
+ """Current humidity reading (CONTINUOUS, sensor-only). The
+ simulator UI lets the operator drive it for testing."""
+
+ sim_entity_fields : HassThermostatFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'current_humidity'
+ value : str = '45'
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 100
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Current Humidity'
+
+ @property
+ def entity_id(self):
+ return _thermostat_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'on'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ try:
+ humidity = float( self.value )
+ except ( TypeError, ValueError ):
+ humidity = 0.0
+ return { 'current_humidity': humidity }
+
+
+@dataclass
+class HassThermostatHvacActionState( HassState ):
+ """What the HVAC system is currently doing (heating /
+ cooling / idle / off). Sensor-only in HA terms; the
+ simulator exposes the dropdown directly so a tester can
+ drive action transitions without simulating the underlying
+ physics."""
+
+ HVAC_ACTION_CHOICES : ClassVar[ List[ Tuple[ str, str ] ] ] = list(
+ _THERMOSTAT_HVAC_ACTION_CHOICES,
+ )
+
+ sim_entity_fields : HassThermostatFields
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ sim_state_id : str = 'hvac_action'
+ value : str = 'idle'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} HVAC Action'
+
+ @property
+ def entity_id(self):
+ return _thermostat_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'on'
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ] ]:
+ return self.HVAC_ACTION_CHOICES
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return { 'hvac_action': self.value }
+
+
HASS_SIM_ENTITY_DEFINITION_LIST = [
SimEntityDefinition(
class_label = 'Insteon Switch',
@@ -1240,4 +1676,19 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [
HassMultiFeatureFanPresetState,
],
),
+ SimEntityDefinition(
+ class_label = 'Thermostat',
+ sim_entity_type = SimEntityType.THERMOSTAT,
+ sim_entity_fields_class = HassThermostatFields,
+ sim_state_class_list = [
+ HassThermostatCurrentTemperatureState,
+ HassThermostatTargetTemperatureState,
+ HassThermostatTargetTempLowState,
+ HassThermostatTargetTempHighState,
+ HassThermostatHvacModeState,
+ HassThermostatHvacActionState,
+ HassThermostatFanModeState,
+ HassThermostatCurrentHumidityState,
+ ],
+ ),
]
diff --git a/src/hi/simulator/services/hass/tests/__init__.py b/src/hi/simulator/services/hass/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/services/hass/tests/test_unit_translation.py b/src/hi/simulator/services/hass/tests/test_unit_translation.py
new file mode 100644
index 00000000..7bf49976
--- /dev/null
+++ b/src/hi/simulator/services/hass/tests/test_unit_translation.py
@@ -0,0 +1,133 @@
+import logging
+from unittest.mock import patch
+
+from django.test import TestCase
+
+from hi.simulator.enums import SimTemperatureUnit
+from hi.simulator.services.hass.unit_translation import UnitTranslationHelper
+
+logging.disable(logging.CRITICAL)
+
+
+def _override_context():
+ """Patch the SimulatorRuntimeSettings singleton accessed by the
+ helper so tests can dictate the temperature_unit_override
+ without touching real process-wide state."""
+ return patch(
+ 'hi.simulator.services.hass.unit_translation'
+ '.SimulatorRuntimeSettings',
+ )
+
+
+class TestEmittedTemperatureUnit(TestCase):
+ """Resolves the wire-format unit the simulator should emit:
+ profile-default when no override, override-mapped to HA wire
+ symbol otherwise."""
+
+ def test_no_override_returns_profile_unit(self):
+ with _override_context() as mock_singleton:
+ mock_singleton.return_value.temperature_unit_override = None
+ self.assertEqual(
+ UnitTranslationHelper.emitted_temperature_unit( '°F' ),
+ '°F',
+ )
+
+ def test_override_celsius_returns_ha_celsius_symbol(self):
+ with _override_context() as mock_singleton:
+ mock_singleton.return_value.temperature_unit_override = (
+ SimTemperatureUnit.CELSIUS
+ )
+ self.assertEqual(
+ UnitTranslationHelper.emitted_temperature_unit( '°F' ),
+ '°C',
+ )
+
+ def test_override_fahrenheit_returns_ha_fahrenheit_symbol(self):
+ with _override_context() as mock_singleton:
+ mock_singleton.return_value.temperature_unit_override = (
+ SimTemperatureUnit.FAHRENHEIT
+ )
+ self.assertEqual(
+ UnitTranslationHelper.emitted_temperature_unit( '°C' ),
+ '°F',
+ )
+
+
+class TestConvertTemperatureValue(TestCase):
+ """F↔C conversion with defensive pass-through. The simulator
+ relies on this both at the composer (profile-unit → emitted
+ wire-unit) and at the dispatcher (incoming-wire-unit →
+ profile-unit) boundaries."""
+
+ def test_fahrenheit_to_celsius_freezing_point(self):
+ result = UnitTranslationHelper.convert_temperature_value(
+ 32, from_unit = '°F', to_unit = '°C',
+ )
+ self.assertAlmostEqual( result, 0.0, places = 6 )
+
+ def test_celsius_to_fahrenheit_boiling_point(self):
+ result = UnitTranslationHelper.convert_temperature_value(
+ 100, from_unit = '°C', to_unit = '°F',
+ )
+ self.assertAlmostEqual( result, 212.0, places = 6 )
+
+ def test_fahrenheit_to_celsius_room_temperature(self):
+ # 70°F → 21.111°C — the canonical conversion in the
+ # simulator's seed default for °F-native thermostats.
+ result = UnitTranslationHelper.convert_temperature_value(
+ 70, from_unit = '°F', to_unit = '°C',
+ )
+ self.assertAlmostEqual( result, 21.111, places = 2 )
+
+ def test_units_match_returns_value_unchanged(self):
+ # Passes through the value identically without a Pint hop.
+ result = UnitTranslationHelper.convert_temperature_value(
+ 22.5, from_unit = '°C', to_unit = '°C',
+ )
+ self.assertEqual( result, 22.5 )
+
+ def test_missing_units_passthrough(self):
+ # Defensive: if either side is unset (e.g., HA reports a
+ # state without temperature_unit), the helper must not
+ # raise — pass the value through.
+ self.assertEqual(
+ UnitTranslationHelper.convert_temperature_value(
+ 70, from_unit = None, to_unit = '°C',
+ ),
+ 70,
+ )
+ self.assertEqual(
+ UnitTranslationHelper.convert_temperature_value(
+ 70, from_unit = '°F', to_unit = None,
+ ),
+ 70,
+ )
+
+ def test_non_numeric_value_passes_through(self):
+ # Non-numeric input shouldn't break the boundary — the
+ # simulator's composer / dispatcher rely on this for
+ # graceful behavior on malformed values.
+ self.assertEqual(
+ UnitTranslationHelper.convert_temperature_value(
+ 'oops', from_unit = '°F', to_unit = '°C',
+ ),
+ 'oops',
+ )
+
+ def test_none_value_passes_through(self):
+ result = UnitTranslationHelper.convert_temperature_value(
+ None, from_unit = '°F', to_unit = '°C',
+ )
+ self.assertIsNone( result )
+
+ def test_round_trip_preserves_value_within_float_precision(self):
+ # The simulator uses the same conversion at composer (out)
+ # and dispatcher (in) — round-trip must preserve the
+ # physical temperature.
+ celsius = UnitTranslationHelper.convert_temperature_value(
+ 72.0, from_unit = '°F', to_unit = '°C',
+ )
+ fahrenheit = UnitTranslationHelper.convert_temperature_value(
+ celsius, from_unit = '°C', to_unit = '°F',
+ )
+ self.assertAlmostEqual( fahrenheit, 72.0, places = 6 )
diff --git a/src/hi/simulator/services/hass/unit_translation.py b/src/hi/simulator/services/hass/unit_translation.py
new file mode 100644
index 00000000..a38abe6d
--- /dev/null
+++ b/src/hi/simulator/services/hass/unit_translation.py
@@ -0,0 +1,63 @@
+"""Temperature unit translation for the HA simulator.
+
+Maps the integration-agnostic ``SimTemperatureUnit`` runtime
+override (set globally in ``SimulatorRuntimeSettings``) to HA's
+wire-format unit symbols (``°F`` / ``°C``), and provides a small
+F↔C conversion helper used on both the outbound (composer) and
+inbound (dispatcher) sides of the simulator's HA boundary.
+
+When the runtime override is set, the simulator emits all
+temperature values in the override unit (with magnitudes converted
+so the physical temperature stays constant) and accepts incoming
+HA service calls in that same unit. Internal SimState storage
+remains in each profile's per-entity unit; conversion happens
+purely at this boundary.
+"""
+from typing import Optional
+
+from hi.simulator.enums import SimTemperatureUnit
+from hi.simulator.runtime_settings import SimulatorRuntimeSettings
+
+
+class UnitTranslationHelper:
+ """Namespace for HA-simulator temperature-unit translation."""
+
+ SIM_TEMPERATURE_UNIT_TO_HA_WIRE = {
+ SimTemperatureUnit.FAHRENHEIT: '°F',
+ SimTemperatureUnit.CELSIUS: '°C',
+ }
+
+ @classmethod
+ def emitted_temperature_unit(
+ cls, profile_unit : Optional[str] ) -> Optional[str]:
+ """The wire-format temperature unit the simulator should
+ emit, applying the runtime override if set; otherwise the
+ profile's own unit passes through unchanged."""
+ override = SimulatorRuntimeSettings().temperature_unit_override
+ if override is None:
+ return profile_unit
+ return cls.SIM_TEMPERATURE_UNIT_TO_HA_WIRE.get(
+ override, profile_unit,
+ )
+
+ @staticmethod
+ def convert_temperature_value(
+ value,
+ from_unit : Optional[str],
+ to_unit : Optional[str],
+ ):
+ """F↔C conversion. Pass-through when units match, either
+ side is unset, or the value can't be coerced to float."""
+ if value is None or not from_unit or not to_unit:
+ return value
+ if from_unit == to_unit:
+ return value
+ try:
+ magnitude = float( value )
+ except ( TypeError, ValueError ):
+ return value
+ if from_unit == '°F' and to_unit == '°C':
+ return ( magnitude - 32.0 ) * 5.0 / 9.0
+ if from_unit == '°C' and to_unit == '°F':
+ return magnitude * 9.0 / 5.0 + 32.0
+ return value
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_continuous.html b/src/hi/simulator/templates/simulator/panes/sim_control_continuous.html
index ea6995c7..3184fea2 100644
--- a/src/hi/simulator/templates/simulator/panes/sim_control_continuous.html
+++ b/src/hi/simulator/templates/simulator/panes/sim_control_continuous.html
@@ -1,5 +1,5 @@
<div class="continuous-control d-flex align-items-center">
- <span class="mr-2">{{ sim_state.min_value }}</span>
+ <span class="mr-2">{{ sim_state.min_value|floatformat:"-1" }}{{ sim_state.display_unit }}</span>
<input type="range"
name="value"
min="{{ sim_state.min_value }}"
@@ -7,6 +7,6 @@
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>
+ <output class="ml-2" style="min-width: 3em; text-align: right;">{{ sim_state.value|floatformat:"-1" }}</output>{% if sim_state.display_unit %}<span class="ml-1">{{ sim_state.display_unit }}</span>{% endif %}
+ <span class="ml-2">{{ sim_state.max_value|floatformat:"-1" }}{{ sim_state.display_unit }}</span>
</div>
diff --git a/src/hi/simulator/templates/simulator/panes/sim_profile_header.html b/src/hi/simulator/templates/simulator/panes/sim_profile_header.html
index bcf8972b..ace2c97e 100644
--- a/src/hi/simulator/templates/simulator/panes/sim_profile_header.html
+++ b/src/hi/simulator/templates/simulator/panes/sim_profile_header.html
@@ -1,7 +1,10 @@
-<div class="d-flex justify-content-between">
+<div class="d-flex justify-content-between align-items-center">
<div class="h3">Service Simulators</div>
- <div>
- {% include "simulator/panes/sim_profile_dropdown.html" %}
+ <div class="d-flex align-items-center">
+ {% include "simulator/panes/temperature_unit_override_form.html" %}
+ <div class="ml-3">
+ {% include "simulator/panes/sim_profile_dropdown.html" %}
+ </div>
</div>
</div>
<div class="d-flex justify-content-start">
diff --git a/src/hi/simulator/templates/simulator/panes/temperature_unit_override_form.html b/src/hi/simulator/templates/simulator/panes/temperature_unit_override_form.html
new file mode 100644
index 00000000..d4234355
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/temperature_unit_override_form.html
@@ -0,0 +1,26 @@
+<div id="hi-temperature-unit-override" class="hi-temperature-unit-override-wrap">
+ <form action="{% url 'simulator_temperature_unit_override_set' %}"
+ method="POST" class="form-inline hi-temperature-unit-override-form"
+ data-async="#hi-temperature-unit-override"
+ data-mode="replace">
+ {% csrf_token %}
+ <label class="mr-2 mb-0" for="hi-temperature-unit-override-select">
+ Temperature:
+ </label>
+ <select id="hi-temperature-unit-override-select"
+ name="temperature_unit"
+ class="form-control form-control-sm"
+ onchange-async="true">
+ <option value=""
+ {% if not temperature_unit_override %}selected{% endif %}>
+ Default
+ </option>
+ {% for unit in temperature_unit_choices %}
+ <option value="{{ unit.name }}"
+ {% if temperature_unit_override == unit %}selected{% endif %}>
+ {{ unit.label }}
+ </option>
+ {% endfor %}
+ </select>
+ </form>
+</div>
diff --git a/src/hi/simulator/urls.py b/src/hi/simulator/urls.py
index 44ffb012..8056cb72 100644
--- a/src/hi/simulator/urls.py
+++ b/src/hi/simulator/urls.py
@@ -57,6 +57,10 @@ urlpatterns = [
re_path( r'^fault-mode/set/(?P<simulator_id>[\w_\-\.\:]+)$',
views.SetSimulatorFaultModeView.as_view(),
name = 'simulator_fault_mode_set' ),
+
+ re_path( r'^runtime/temperature-unit-override$',
+ views.TemperatureUnitOverrideSetView.as_view(),
+ name = 'simulator_temperature_unit_override_set' ),
]
diff --git a/src/hi/simulator/views.py b/src/hi/simulator/views.py
index a4498274..ff5a6099 100644
--- a/src/hi/simulator/views.py
+++ b/src/hi/simulator/views.py
@@ -7,10 +7,11 @@ from django.views.generic import View
import hi.apps.common.antinode as antinode
-from .enums import SimulatorFaultMode
+from .enums import SimulatorFaultMode, SimTemperatureUnit
from .exceptions import SimEntityValidationError
from . import forms
from .models import DbSimEntity, SimProfile
+from .runtime_settings import SimulatorRuntimeSettings
from .simulator_manager import SimulatorManager
from .sim_entity import SimEntity
from .view_mixins import SimulatorViewMixin
@@ -27,12 +28,15 @@ class HomeView( View, SimulatorViewMixin ):
request = request,
simulator_list = [ x.simulator for x in simulator_data_list ],
)
+ runtime_settings = SimulatorRuntimeSettings()
context = {
'sim_profile_list': sim_profile_list,
'current_sim_profile': current_sim_profile,
'simulator_data_list': simulator_data_list,
'current_simulator': current_simulator,
'fault_mode_choices': list( SimulatorFaultMode ),
+ 'temperature_unit_choices': list( SimTemperatureUnit ),
+ 'temperature_unit_override': runtime_settings.temperature_unit_override,
}
return render( request, 'simulator/pages/home.html', context )
@@ -387,4 +391,29 @@ class SimStateSetView( View, SimulatorViewMixin ):
'sim_state': sim_state,
}
return render( request, self.TEMPLATE_NAME, context )
+
+
+class TemperatureUnitOverrideSetView( View ):
+ """Operator control to flip the simulator's process-wide
+ temperature unit override (or clear it back to per-profile
+ defaults). Returns the dropdown's form fragment so antinode.js
+ can swap it in place — preserves the current integration tab
+ and avoids a full reload."""
+
+ TEMPLATE_NAME = 'simulator/panes/temperature_unit_override_form.html'
+
+ def post( self, request, *args, **kwargs ):
+ raw = ( request.POST.get( 'temperature_unit' ) or '' ).strip()
+ if raw:
+ override = SimTemperatureUnit.from_name_safe( raw )
+ if override is None:
+ raise BadRequest( f'Unknown temperature unit: {raw!r}' )
+ else:
+ override = None
+ SimulatorRuntimeSettings().set_temperature_unit_override( override )
+ context = {
+ 'temperature_unit_choices': list( SimTemperatureUnit ),
+ 'temperature_unit_override': override,
+ }
+ return render( request, self.TEMPLATE_NAME, context )
diff --git a/src/hi/static/js/controllers.js b/src/hi/static/js/controllers.js
index 606ef35c..56522dfe 100644
--- a/src/hi/static/js/controllers.js
+++ b/src/hi/static/js/controllers.js
@@ -28,6 +28,14 @@
window.Hi = window.Hi || {};
Hi.controllers = Hi.controllers || {};
+ // Sliders the user is actively dragging. Polling-driven value
+ // updates skip these elements so a server refresh mid-drag
+ // doesn't yank the thumb out from under the operator's
+ // fingers. Cleared on pointerup / change so subsequent polls
+ // resume normally — by definition the change-async submit on
+ // release will reconcile the value at that point.
+ const _activeSliders = new WeakSet();
+
/**
* Apply a class-name → controller-value map by finding each
* matching element and updating the appropriate widget
@@ -53,6 +61,9 @@
if ( tag === 'INPUT' ) {
const type = element.type;
if ( type === 'range' || type === 'number' || type === 'text' ) {
+ if ( type === 'range' && _activeSliders.has( element ) ) {
+ return;
+ }
_setIfDifferent( element, 'value', String( value ) );
_syncSliderDisplay( element );
return;
@@ -179,6 +190,31 @@
_syncSliderDisplay( this );
}
);
+
+ // Track active drag so polling-driven value updates can
+ // skip sliders the operator is currently manipulating.
+ // Set on pointer-down (mouse / touch / pen via Pointer
+ // Events). Cleared on pointer release and on ``change``
+ // (the canonical "value committed" signal — covers
+ // keyboard arrow adjustments too).
+ //
+ // Release-side handlers live on ``document``, not ``body``:
+ // a pointer release that happens off the slider element
+ // (or even outside the viewport) still bubbles to document,
+ // ensuring the flag clears so subsequent polls can resume
+ // updating. Listening on body alone would leak the flag if
+ // the user dragged the thumb past the page edge before
+ // releasing.
+ $('body').on(
+ 'mousedown touchstart pointerdown',
+ 'input[type=range]',
+ function() { _activeSliders.add( this ); }
+ );
+ $(document).on(
+ 'mouseup touchend touchcancel pointerup pointercancel change blur',
+ 'input[type=range]',
+ function() { _activeSliders.delete( this ); }
+ );
});
})();
diff --git a/src/hi/testing/dev_overrides.py b/src/hi/testing/dev_overrides.py
index e1cd69c2..74f7b1eb 100644
--- a/src/hi/testing/dev_overrides.py
+++ b/src/hi/testing/dev_overrides.py
@@ -157,10 +157,10 @@ class StateTraceManager:
# disrupting alignment; long values overflow the slot and
# disrupt only their own row, not subsequent ones.
LABEL_W = 28
- HA_ID_W = 32
+ HA_ID_W = 42
HA_VAL_W = 14
HI_ID_W = 6
- HI_VAL_W = 36
+ HI_VAL_W = 26
@classmethod
def emit( cls,
diff --git a/src/hi/units.py b/src/hi/units.py
index e48d01cb..fddf7670 100644
--- a/src/hi/units.py
+++ b/src/hi/units.py
@@ -4,6 +4,15 @@ from hi.apps.console.enums import DisplayUnits
ureg = UnitRegistry()
UnitQuantity = ureg.Quantity
+
+# HI-wide canonical unit choices. Integration converters that import
+# unit-bearing values normalize to the canonical at the boundary;
+# downstream code reads ``EntityState.units`` (set from these
+# canonicals at creation time) rather than re-asserting the canonical.
+# Adding a new canonical here makes it available cross-integration so
+# multiple integrations don't duplicate the choice.
+CANONICAL_TEMPERATURE_UNIT = '°C'
+
ureg.define('percent = 1 / 100 = % = pct')
ureg.define('true = 1 = yes = on')
ureg.define('false = 0 = no = off')