Skip to content

Home Information - Your home, your data, organized.

Python

Issue #301: HA numeric sensors (temperature/humidity) coverage (#312)

Tony C279498604a02
diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html
index d142803a..13a1ba5a 100644
--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html
+++ b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html
@@ -1,2 +1,2 @@
-{% load entity_tags %}
-<div class="text-center px-2" status="{{ sensor_response.value }}">{{ sensor_response.value|value_label }}</div>
+{% load entity_tags units %}
+<div class="text-center px-2" status="{{ sensor_response.value }}">{% if sensor_response.sensor.entity_state.units %}{{ sensor_response.value|as_display_value:sensor_response.sensor.entity_state }}{% else %}{{ sensor_response.value|value_label }}{% endif %}</div>
diff --git a/src/hi/integrations/integration_metadata_cache.py b/src/hi/integrations/integration_metadata_cache.py
index 966508f5..b3d28f72 100644
--- a/src/hi/integrations/integration_metadata_cache.py
+++ b/src/hi/integrations/integration_metadata_cache.py
@@ -107,6 +107,26 @@ class IntegrationMetadataCache( Singleton ):
)
self._warmed = True
+ def invalidate(self):
+ """Drop all cached entries and reset the warmup flag.
+
+ Called by the integration framework after any operation
+ that creates, refreshes, or removes EntityStates with
+ integration_keys (sync, disable). The next ``get_entry``
+ triggers a fresh bulk warmup from the now-consistent DB
+ state.
+
+ Necessary because ``_lazy_fill`` caches ``{'units': None}``
+ on miss to keep the polling-loop hot path free of repeat
+ DB queries. Without invalidation, a poll that races an
+ in-progress import pins a bad entry for the lifetime of
+ the process — visible as raw, unconverted values for any
+ new unit-bearing EntityState (most obviously a wrong-by-
+ ~88°F temperature reading)."""
+ with self._lock:
+ self._cache.clear()
+ self._warmed = False
+
def _lazy_fill(
self, integration_key : IntegrationKey,
) -> Dict[str, Any]:
diff --git a/src/hi/integrations/tests/test_integration_converter_helper.py b/src/hi/integrations/tests/test_integration_converter_helper.py
index 75c9d43d..b000484b 100644
--- a/src/hi/integrations/tests/test_integration_converter_helper.py
+++ b/src/hi/integrations/tests/test_integration_converter_helper.py
@@ -20,9 +20,8 @@ def _seed_cache_entry( integration_key, units ):
def _reset_cache():
- cache = IntegrationMetadataCache()
- cache._cache.clear()
- cache._warmed = False
+ # Singleton cache state must not leak across tests.
+ IntegrationMetadataCache().invalidate()
class TestToEntityStateValue(TestCase):
diff --git a/src/hi/integrations/tests/test_integration_metadata_cache.py b/src/hi/integrations/tests/test_integration_metadata_cache.py
index 9a071316..11ba21cd 100644
--- a/src/hi/integrations/tests/test_integration_metadata_cache.py
+++ b/src/hi/integrations/tests/test_integration_metadata_cache.py
@@ -34,8 +34,8 @@ def _make_entity_with_sensor( integration_key, units = None ):
def _reset_cache():
- IntegrationMetadataCache()._cache.clear()
- IntegrationMetadataCache()._warmed = False
+ # Singleton cache state must not leak across tests.
+ IntegrationMetadataCache().invalidate()
class TestIntegrationMetadataCache(TestCase):
@@ -120,6 +120,42 @@ class TestIntegrationMetadataCache(TestCase):
# Second call must not have re-queried Sensor.objects.
mock_sensor_objects.select_related.assert_not_called()
+ def test_invalidate_drops_stale_negative_entry_and_re_warms(self):
+ # Reproduces the import-vs-poll race: a poll cached a
+ # ``{'units': None}`` miss for a key the DB doesn't yet
+ # have a row for; later the import commits the row with
+ # real units. Without ``invalidate``, the bad entry sticks
+ # for the process lifetime and HI shows raw (unconverted)
+ # values for the new sensor. ``invalidate`` (called from
+ # the integration sync view post-sync) flushes the cache;
+ # the next ``get_entry`` re-warms from the now-current DB.
+ racy_key = IntegrationKey(
+ integration_id = 'hass',
+ integration_name = 'sensor.zoo_thermometer',
+ )
+ # Pre-sync poll: row absent → negative entry pinned.
+ self.assertEqual(
+ IntegrationMetadataCache().get_entry( racy_key ),
+ { 'units': None },
+ )
+ # Sync commits the row with real units.
+ _make_entity_with_sensor( racy_key, units = '°C' )
+ # Without invalidate, the cached miss would shadow it.
+ self.assertEqual(
+ IntegrationMetadataCache()._cache.get( racy_key ),
+ { 'units': None },
+ )
+
+ IntegrationMetadataCache().invalidate()
+
+ self.assertFalse( IntegrationMetadataCache()._warmed )
+ self.assertEqual( IntegrationMetadataCache()._cache, {} )
+ # Next read warms from the now-consistent DB.
+ self.assertEqual(
+ IntegrationMetadataCache().get_entry( racy_key ),
+ { 'units': '°C' },
+ )
+
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
diff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.py
index a973d9cc..c6d5cc18 100644
--- a/src/hi/integrations/views.py
+++ b/src/hi/integrations/views.py
@@ -26,6 +26,7 @@ from .enums import IntegrationDisableMode
from .exceptions import IntegrationConnectionError
from .integration_attribute_edit_context import IntegrationAttributeItemEditContext
from .integration_manager import IntegrationManager
+from .integration_metadata_cache import IntegrationMetadataCache
from .models import IntegrationAttribute
from .sync_check import IntegrationSyncCheck
from .view_mixins import IntegrationPlacementViewMixin, IntegrationViewMixin
@@ -202,10 +203,21 @@ class IntegrationSyncView( HiModalView, IntegrationViewMixin ):
request.POST.get( 'preserve_user_data', 'true' ),
)
- sync_result = synchronizer.sync(
- is_initial_import = is_initial_import,
- preserve_user_data = preserve_user_data,
- )
+ try:
+ sync_result = synchronizer.sync(
+ is_initial_import = is_initial_import,
+ preserve_user_data = preserve_user_data,
+ )
+ finally:
+ # Drop any cached metadata pinned by a poll that raced
+ # this sync — most importantly, the ``{'units': None}``
+ # negative entries that ``_lazy_fill`` caches on miss.
+ # Without this, the first poll for a newly-imported
+ # unit-bearing EntityState can lock in a bad entry for
+ # the process lifetime, showing raw (unconverted) values
+ # in the UI until the server restarts. ``finally`` so a
+ # partial-commit failure during sync also flushes.
+ IntegrationMetadataCache().invalidate()
# Scope the placement to just the entities this sync created.
# Without scoping, the placement's GET endpoint queries every
@@ -555,10 +567,17 @@ class IntegrationDisableView( HiModalView, IntegrationViewMixin ):
def post(self, request, *args, **kwargs):
integration_data = self._get_validated_integration_data( kwargs )
mode = IntegrationDisableMode.from_name_safe( request.POST.get('mode', '') )
- IntegrationManager().disable_integration(
- integration_data = integration_data,
- mode = mode,
- )
+ try:
+ IntegrationManager().disable_integration(
+ integration_data = integration_data,
+ mode = mode,
+ )
+ finally:
+ # Disable removes EntityStates whose ``integration_key``s
+ # may still be cached; invalidate so subsequent reads
+ # don't return stale entries that reference deleted
+ # rows. Symmetric with the post-sync invalidation.
+ IntegrationMetadataCache().invalidate()
redirect_url = reverse( 'integrations_home' )
return self.redirect_response( request, redirect_url )
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index 124e22be..fdab7354 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -1910,8 +1910,38 @@ class HassConverter:
friendly_name = shortest_id_state.friendly_name
if friendly_name:
- return friendly_name
+ return cls._strip_state_suffix_from_friendly_name(
+ hass_state = shortest_id_state,
+ friendly_name = friendly_name,
+ )
return hass_device.device_id
+
+ @staticmethod
+ def _strip_state_suffix_from_friendly_name(
+ hass_state : HassState,
+ friendly_name : str ) -> str:
+ """For a combo-device state grouped via entity_id suffix
+ stripping (e.g., ``sensor.kitchen_humidity`` →
+ device_id ``kitchen``), the picked friendly_name often
+ still carries the title-cased suffix word
+ (``'Kitchen Humidity'``). Strip it so the HI Entity name
+ is the device-level name (``'Kitchen'``).
+ Conservative: only strips when the friendly_name's tail
+ is the direct title-case of the entity_id's removed
+ underscore suffix — a user-renamed friendly_name that
+ doesn't follow that pattern passes through unchanged."""
+ full = hass_state.entity_name_sans_prefix
+ short = hass_state.entity_name_sans_suffix
+ if full == short:
+ return friendly_name
+ suffix = full[ len(short): ]
+ suffix_words = ' '.join(
+ part.capitalize() for part in suffix.split('_') if part
+ )
+ tail = ' ' + suffix_words
+ if friendly_name.endswith( tail ):
+ return friendly_name[ : -len(tail) ]
+ return friendly_name
# Word-boundary patterns matched against the device's display
# name to upgrade a switch-domain device's EntityType at import
@@ -2012,12 +2042,17 @@ class HassConverter:
if HassApi.FAN_DOMAIN in domain_set:
return EntityType.CEILING_FAN
# Climate domain is the controllable HVAC entity; the
- # temperature device-class check below catches passive
- # temperature sensors that aren't climate entities.
+ # temperature / humidity device-class checks below catch
+ # passive sensors that aren't climate entities. Combo
+ # temp+humidity devices hit the temperature branch first
+ # and resolve to THERMOMETER, which reads naturally for
+ # the dual-quantity case.
if HassApi.CLIMATE_DOMAIN in domain_set:
return EntityType.THERMOSTAT
if HassApi.TEMPERATURE_DEVICE_CLASS in device_class_set:
- return EntityType.THERMOSTAT
+ return EntityType.THERMOMETER
+ if HassApi.HUMIDITY_DEVICE_CLASS in device_class_set:
+ return EntityType.HYGROMETER
if HassApi.CONNECTIVITY_DEVICE_CLASS in device_class_set:
return EntityType.HEALTHCHECK
diff --git a/src/hi/services/hass/tests/test_hass_converter_climate.py b/src/hi/services/hass/tests/test_hass_converter_climate.py
index 443f7b5f..78f2fe1d 100644
--- a/src/hi/services/hass/tests/test_hass_converter_climate.py
+++ b/src/hi/services/hass/tests/test_hass_converter_climate.py
@@ -216,9 +216,7 @@ class TestClimateSubstateSpecs(TestCase):
def _reset_unit_cache():
"""Singleton cache state must not leak across tests."""
- cache = IntegrationMetadataCache()
- cache._cache.clear()
- cache._warmed = False
+ IntegrationMetadataCache().invalidate()
def _seed_unit_cache_for_climate(parent_entity_id, units, suffixes):
diff --git a/src/hi/services/hass/tests/test_hass_converter_create.py b/src/hi/services/hass/tests/test_hass_converter_create.py
index 03d82a04..0a17ed9a 100644
--- a/src/hi/services/hass/tests/test_hass_converter_create.py
+++ b/src/hi/services/hass/tests/test_hass_converter_create.py
@@ -16,6 +16,7 @@ import logging
from django.test import TestCase
from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.entity.enums import EntityStateType
from hi.apps.entity.models import Entity, EntityAttribute, EntityState
from hi.apps.event.models import EventDefinition
from hi.integrations.entity_operations import EntityIntegrationOperations
@@ -77,6 +78,75 @@ class CreateModelsForHassDeviceCreateNewContractTests(TestCase):
self.assertGreaterEqual(EntityState.objects.filter(entity=entity).count(), 1)
+class CreateModelsForComboSensorDeviceTests(TestCase):
+ """A real-world combo temp+humidity sensor surfaces in HA as two
+ ``sensor.x`` entities (``sensor.<name>_temperature`` and
+ ``sensor.<name>_humidity``); HI's converter groups them via the
+ ``_temperature`` / ``_humidity`` suffix strip in
+ ``STATE_SUFFIXES`` so the parent device collapses to one HI
+ Entity with two EntityStates. Pin that end-to-end composition —
+ the suffix-strip grouping is the path that makes #301's combo
+ sensor work without an explicit HA device_group_id."""
+
+ def _build_combo_device(self, device_id='kitchen_climate'):
+ def _state(suffix, value, device_class, unit):
+ api_dict = {
+ 'entity_id': f'sensor.{device_id}_{suffix}',
+ 'state': value,
+ 'attributes': {
+ 'friendly_name':
+ f'{device_id.replace("_", " ").title()} '
+ f'{suffix.title()}',
+ 'device_class': device_class,
+ 'unit_of_measurement': unit,
+ },
+ '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},
+ }
+ return HassConverter.create_hass_state(api_dict)
+ device = HassDevice(device_id=device_id)
+ device.add_state(_state('temperature', '72', 'temperature', '°F'))
+ device.add_state(_state('humidity', '45', 'humidity', '%'))
+ return device
+
+ def test_combo_device_creates_one_entity_with_two_entity_states(self):
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=self._build_combo_device(),
+ add_alarm_events=False,
+ )
+
+ state_types = sorted(
+ s.entity_state_type_str
+ for s in EntityState.objects.filter(entity=entity)
+ )
+ self.assertEqual(
+ state_types,
+ sorted([
+ str(EntityStateType.HUMIDITY),
+ str(EntityStateType.TEMPERATURE),
+ ]),
+ )
+
+ def test_combo_device_creates_only_one_entity_row(self):
+ # Belt-and-suspenders for the grouping path — without the
+ # ``_temperature`` / ``_humidity`` suffix-strip the two
+ # wire entities would materialize as two separate HI
+ # Entities. The single-row assertion pins that they
+ # collapse.
+ HassConverter.create_models_for_hass_device(
+ hass_device=self._build_combo_device(),
+ add_alarm_events=False,
+ )
+ self.assertEqual(
+ Entity.objects.filter(
+ integration_id=HassMetaData.integration_id,
+ ).count(),
+ 1,
+ )
+
+
class CreateModelsForHassDeviceReconnectContractTests(TestCase):
"""
Pin the reconnect contract added in Issue #281 Phase 3:
diff --git a/src/hi/services/hass/tests/test_hass_converter_entity_type.py b/src/hi/services/hass/tests/test_hass_converter_entity_type.py
index d62b9913..88ce76c8 100644
--- a/src/hi/services/hass/tests/test_hass_converter_entity_type.py
+++ b/src/hi/services/hass/tests/test_hass_converter_entity_type.py
@@ -104,6 +104,64 @@ class HassDeviceToEntityTypeTests( TestCase ):
EntityType.THERMOSTAT,
)
+ def test_sensor_temperature_device_class_maps_to_thermometer( self ):
+ # Passive temperature sensor (``sensor.x`` with
+ # ``device_class=temperature`` and no climate.x companion)
+ # is a thermometer, not a thermostat. The CLIMATE_DOMAIN
+ # branch above still catches the real-thermostat case.
+ device = _make_device(
+ entity_id = 'sensor.outdoor',
+ friendly_name = 'Outdoor',
+ device_class = HassApi.TEMPERATURE_DEVICE_CLASS,
+ )
+ self.assertEqual(
+ HassConverter.hass_device_to_entity_type( device ),
+ EntityType.THERMOMETER,
+ )
+
+ def test_sensor_humidity_device_class_maps_to_hygrometer( self ):
+ # Standalone humidity sensor previously fell through to
+ # ``EntityType.OTHER``.
+ device = _make_device(
+ entity_id = 'sensor.basement',
+ friendly_name = 'Basement',
+ device_class = HassApi.HUMIDITY_DEVICE_CLASS,
+ )
+ self.assertEqual(
+ HassConverter.hass_device_to_entity_type( device ),
+ EntityType.HYGROMETER,
+ )
+
+ def test_combo_temp_and_humidity_device_maps_to_thermometer( self ):
+ # Real-world combo sensors (Aqara / BME280 / etc.) surface
+ # in HA as two ``sensor.x`` entities sharing a device
+ # group. After HassDevice grouping, the device carries
+ # both temperature and humidity in its device_class_set;
+ # the temperature branch fires first and wins, which reads
+ # naturally for the dual-quantity case.
+ device = _make_device(
+ entity_id = 'sensor.kitchen_temperature',
+ friendly_name = 'Kitchen Temperature',
+ device_class = HassApi.TEMPERATURE_DEVICE_CLASS,
+ )
+ humidity_state = HassConverter.create_hass_state( {
+ 'entity_id' : 'sensor.kitchen_humidity',
+ 'state' : '45',
+ 'attributes' : {
+ HassApi.FRIENDLY_NAME_ATTR : 'Kitchen Humidity',
+ HassApi.DEVICE_CLASS_ATTR : HassApi.HUMIDITY_DEVICE_CLASS,
+ },
+ '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 },
+ } )
+ device.add_state( humidity_state )
+ self.assertEqual(
+ HassConverter.hass_device_to_entity_type( device ),
+ EntityType.THERMOMETER,
+ )
+
def test_camera_domain_maps_to_camera( self ):
device = _make_device(
entity_id = 'camera.front_door', friendly_name = 'Front Door Cam',
@@ -299,3 +357,84 @@ class HassSwitchNameInferenceTests( TestCase ):
HassConverter.hass_device_to_entity_type( device ),
EntityType.ELECTRICAL_OUTLET,
)
+
+
+def _build_state( entity_id, friendly_name = '', device_class = None ):
+ """Construct a real HassState matching the wire shape, for use
+ in multi-state combo-device tests below."""
+ attributes = {}
+ if friendly_name:
+ attributes[ HassApi.FRIENDLY_NAME_ATTR ] = friendly_name
+ if device_class is not None:
+ attributes[ HassApi.DEVICE_CLASS_ATTR ] = device_class
+ api_dict = {
+ 'entity_id' : entity_id,
+ 'state' : '0',
+ '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 },
+ }
+ return HassConverter.create_hass_state( api_dict )
+
+
+class HassDeviceToEntityNameTests( TestCase ):
+ """``hass_device_to_entity_name`` derives the HI Entity name
+ from one of the HassDevice's grouped HassStates. For combo
+ devices (e.g., temp + humidity sensors sharing a short_name
+ after suffix stripping), the picked friendly_name often
+ still carries the per-state suffix word — the picker strips
+ it so the parent Entity gets the device-level name."""
+
+ def test_combo_temp_humidity_strips_humidity_suffix( self ):
+ # Both entities share short_name ``kitchen`` after the
+ # converter strips ``_temperature`` / ``_humidity``;
+ # ``sensor.kitchen_humidity`` is the shorter id and would
+ # otherwise force the Entity name to
+ # ``'Kitchen Humidity'``.
+ device = HassDevice( device_id = 'kitchen' )
+ device.add_state( _build_state(
+ entity_id = 'sensor.kitchen_temperature',
+ friendly_name = 'Kitchen Temperature',
+ device_class = HassApi.TEMPERATURE_DEVICE_CLASS,
+ ))
+ device.add_state( _build_state(
+ entity_id = 'sensor.kitchen_humidity',
+ friendly_name = 'Kitchen Humidity',
+ device_class = HassApi.HUMIDITY_DEVICE_CLASS,
+ ))
+ self.assertEqual(
+ HassConverter.hass_device_to_entity_name( device ),
+ 'Kitchen',
+ )
+
+ def test_standalone_temperature_sensor_name_unchanged( self ):
+ # Non-suffixed entity_id: ``sensor.outdoor`` reduces to
+ # short_name ``outdoor`` (no strip), so friendly_name
+ # passes through unchanged.
+ device = HassDevice( device_id = 'outdoor' )
+ device.add_state( _build_state(
+ entity_id = 'sensor.outdoor',
+ friendly_name = 'Outdoor',
+ device_class = HassApi.TEMPERATURE_DEVICE_CLASS,
+ ))
+ self.assertEqual(
+ HassConverter.hass_device_to_entity_name( device ),
+ 'Outdoor',
+ )
+
+ def test_user_renamed_friendly_name_passes_through( self ):
+ # If the user renamed a suffixed entity to a name that
+ # doesn't follow the ``<device> <Suffix>`` pattern, the
+ # strip must not apply — we'd mangle their chosen name.
+ device = HassDevice( device_id = 'kitchen' )
+ device.add_state( _build_state(
+ entity_id = 'sensor.kitchen_humidity',
+ friendly_name = 'My Custom Name',
+ device_class = HassApi.HUMIDITY_DEVICE_CLASS,
+ ))
+ self.assertEqual(
+ HassConverter.hass_device_to_entity_name( device ),
+ 'My Custom Name',
+ )
diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.py
index 8d4b10ab..19923827 100644
--- a/src/hi/simulator/management/commands/seed_sim_profiles.py
+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py
@@ -89,7 +89,10 @@ from hi.simulator.services.hass.sim_models import (
HassMultiFeatureFanFields,
HassSmartBulbFields,
HassSmokeDetectorFields,
+ HassTemperatureSensorFields,
+ HassTempHumiditySensorFields,
HassThermostatFields,
+ HassHumiditySensorFields,
HassWindowBlindCoverFields,
HassWindowContactSensorFields,
)
@@ -358,6 +361,12 @@ class Command(BaseCommand):
self._add_hass_door_contact( profile, 'Zoo Door Contact' )
self._add_hass_window_contact( profile, 'Zoo Window Contact' )
self._add_hass_smoke_detector( profile, 'Zoo Smoke Detector' )
+ self._add_hass_temperature_sensor( profile, 'Zoo Thermometer' )
+ self._add_hass_temperature_sensor(
+ profile, 'Zoo Thermometer Celsius', temperature_unit = '°C',
+ )
+ self._add_hass_humidity_sensor( profile, 'Zoo Hygrometer' )
+ self._add_hass_temp_humidity_sensor( profile, 'Zoo Climate Sensor' )
self._add_hass_lock( profile, 'Zoo Lock' )
self._add_hass_garage_cover( profile, 'Zoo Garage' )
self._add_hass_window_blind_cover( profile, 'Zoo Blind' )
@@ -529,6 +538,39 @@ class Command(BaseCommand):
fields_kwargs = {'name': name},
)
+ def _add_hass_temperature_sensor(self, profile, name, temperature_unit = '°F'):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassTemperatureSensorFields,
+ sim_entity_type = SimEntityType.THERMOMETER,
+ fields_kwargs = {
+ 'name': name,
+ 'temperature_unit': temperature_unit,
+ },
+ )
+
+ def _add_hass_humidity_sensor(self, profile, name):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassHumiditySensorFields,
+ sim_entity_type = SimEntityType.HYGROMETER,
+ fields_kwargs = {'name': name},
+ )
+
+ def _add_hass_temp_humidity_sensor(self, profile, name, temperature_unit = '°F'):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassTempHumiditySensorFields,
+ sim_entity_type = SimEntityType.THERMOMETER,
+ fields_kwargs = {
+ 'name': name,
+ 'temperature_unit': temperature_unit,
+ },
+ )
+
def _add_hass_lock(self, profile, name):
self._create_db_entity(
profile = profile,
diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.py
index 4fa89c57..b6c88334 100644
--- a/src/hi/simulator/services/hass/sim_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -823,6 +823,260 @@ class HassSmokeDetectorState( HassState ):
}
+# --------------------------------------------------------------------------
+# Numeric sensors (``sensor.x`` with explicit device_class)
+# --------------------------------------------------------------------------
+#
+# Read-only HA ``sensor`` entities whose ``state`` is a numeric
+# string and whose ``unit_of_measurement`` attribute drives HI's
+# units-aware display path. Three shapes are provided:
+#
+# 1. Temperature sensor (single ``sensor.x`` with
+# ``device_class=temperature``).
+# 2. Humidity sensor (single ``sensor.x`` with
+# ``device_class=humidity``).
+# 3. Combo temp+humidity sensor (two ``sensor.x`` entities
+# sharing a short_name so HI's converter groups them into one
+# HI Entity with two EntityStates — mirrors real-world combo
+# sensors like Aqara / BME280 / SHT3x).
+#
+# Each SimState is CONTINUOUS so the operator can drive the
+# value from the simulator UI. No HA-side controllability —
+# real ``sensor.x`` entities are read-only.
+
+
+_DEFAULT_FAHRENHEIT_VALUE = '70'
+_DEFAULT_CELSIUS_VALUE = '21'
+_FAHRENHEIT_MIN = 30
+_FAHRENHEIT_MAX = 100
+_CELSIUS_MIN = 0
+_CELSIUS_MAX = 40
+
+
+def _sensor_entity_id( name : str, suffix : str = '' ) -> str:
+ """``sensor.<slug>[_suffix]``. Combo states pass
+ ``_temperature`` / ``_humidity`` as the suffix so the
+ short_name (after HI strips known suffixes) is the same for
+ both states, which is what groups them into one HassDevice."""
+ slug = name.lower().replace( ' ', '_' )
+ if suffix:
+ return f'sensor.{slug}{suffix}'
+ return f'sensor.{slug}'
+
+
+@dataclass( frozen = True )
+class HassTemperatureSensorFields( SimEntityFields ):
+ """Standalone temperature sensor (``sensor.x`` with
+ ``device_class=temperature``). ``temperature_unit`` toggles
+ °F vs °C end-to-end so HI's unit pass-through can be
+ exercised in both directions."""
+ temperature_unit : str = '°F'
+
+
+@dataclass
+class HassTemperatureSensorState( HassState ):
+ sim_entity_fields : HassTemperatureSensorFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'temperature'
+ value : str = _DEFAULT_FAHRENHEIT_VALUE
+
+ def __post_init__(self):
+ super().__post_init__()
+ # Class-level default is Fahrenheit-shaped (``'70'``); on
+ # °C-configured profiles swap it for a sensible Celsius
+ # default so first-load values don't read as ``70°C``.
+ # Only swaps when ``value`` still equals the class default,
+ # so operator-set values survive.
+ if self.sim_entity_fields.temperature_unit != '°C':
+ return
+ class_default = type( self ).__dataclass_fields__[ 'value' ].default
+ if self.value == class_default:
+ self.value = _DEFAULT_CELSIUS_VALUE
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Temperature'
+
+ @property
+ def entity_id(self):
+ return _sensor_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ # For ``sensor.x`` entities the wire ``state`` IS the
+ # numeric reading — HA encodes it as a string.
+ return self.value
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return {
+ 'device_class' : 'temperature',
+ 'friendly_name' : self.entity_name,
+ 'unit_of_measurement': self.sim_entity_fields.temperature_unit,
+ }
+
+ @property
+ def min_value(self):
+ if self.sim_entity_fields.temperature_unit == '°C':
+ return _CELSIUS_MIN
+ return _FAHRENHEIT_MIN
+
+ @property
+ def max_value(self):
+ if self.sim_entity_fields.temperature_unit == '°C':
+ return _CELSIUS_MAX
+ return _FAHRENHEIT_MAX
+
+ @property
+ def display_unit(self) -> str:
+ return self.sim_entity_fields.temperature_unit
+
+
+@dataclass( frozen = True )
+class HassHumiditySensorFields( SimEntityFields ):
+ """Standalone humidity sensor (``sensor.x`` with
+ ``device_class=humidity``). Unit is always ``%`` so no
+ per-device toggle is needed."""
+ pass
+
+
+@dataclass
+class HassHumiditySensorState( HassState ):
+ sim_entity_fields : HassHumiditySensorFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'humidity'
+ value : str = '45'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Humidity'
+
+ @property
+ def entity_id(self):
+ return _sensor_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return {
+ 'device_class' : 'humidity',
+ 'friendly_name' : self.entity_name,
+ 'unit_of_measurement': '%',
+ }
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 100
+
+
+@dataclass( frozen = True )
+class HassTempHumiditySensorFields( SimEntityFields ):
+ """Combo sensor that reports both temperature and humidity
+ (e.g., Aqara / BME280 / SHT3x). HA represents this as two
+ separate ``sensor.x`` entities; HI's converter collapses
+ them back into one Entity with two EntityStates via
+ suffix-strip grouping (``sensor.<name>_temperature`` and
+ ``sensor.<name>_humidity`` share short_name ``<name>``)."""
+ temperature_unit : str = '°F'
+
+
+@dataclass
+class HassTempHumiditySensorTemperatureState( HassState ):
+ sim_entity_fields : HassTempHumiditySensorFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'temperature'
+ value : str = _DEFAULT_FAHRENHEIT_VALUE
+
+ def __post_init__(self):
+ super().__post_init__()
+ if self.sim_entity_fields.temperature_unit != '°C':
+ return
+ class_default = type( self ).__dataclass_fields__[ 'value' ].default
+ if self.value == class_default:
+ self.value = _DEFAULT_CELSIUS_VALUE
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Temperature'
+
+ @property
+ def entity_id(self):
+ # ``_temperature`` suffix is in ``STATE_SUFFIXES``, so
+ # HI strips it to the short_name for grouping.
+ return _sensor_entity_id( self.entity_name, suffix = '_temperature' )
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return {
+ 'device_class' : 'temperature',
+ 'friendly_name' : f'{self.entity_name} Temperature',
+ 'unit_of_measurement': self.sim_entity_fields.temperature_unit,
+ }
+
+ @property
+ def min_value(self):
+ if self.sim_entity_fields.temperature_unit == '°C':
+ return _CELSIUS_MIN
+ return _FAHRENHEIT_MIN
+
+ @property
+ def max_value(self):
+ if self.sim_entity_fields.temperature_unit == '°C':
+ return _CELSIUS_MAX
+ return _FAHRENHEIT_MAX
+
+ @property
+ def display_unit(self) -> str:
+ return self.sim_entity_fields.temperature_unit
+
+
+@dataclass
+class HassTempHumiditySensorHumidityState( HassState ):
+ sim_entity_fields : HassTempHumiditySensorFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'humidity'
+ value : str = '45'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Humidity'
+
+ @property
+ def entity_id(self):
+ return _sensor_entity_id( self.entity_name, suffix = '_humidity' )
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return {
+ 'device_class' : 'humidity',
+ 'friendly_name' : f'{self.entity_name} Humidity',
+ 'unit_of_measurement': '%',
+ }
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 100
+
+
@dataclass( frozen = True )
class HassLockFields( SimEntityFields ):
"""A lock device. Single ON_OFF SimState whose value drives
@@ -1829,6 +2083,31 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [
HassMultiFeatureFanPresetState,
],
),
+ SimEntityDefinition(
+ class_label = 'Temperature Sensor',
+ sim_entity_type = SimEntityType.THERMOMETER,
+ sim_entity_fields_class = HassTemperatureSensorFields,
+ sim_state_class_list = [
+ HassTemperatureSensorState,
+ ],
+ ),
+ SimEntityDefinition(
+ class_label = 'Humidity Sensor',
+ sim_entity_type = SimEntityType.HYGROMETER,
+ sim_entity_fields_class = HassHumiditySensorFields,
+ sim_state_class_list = [
+ HassHumiditySensorState,
+ ],
+ ),
+ SimEntityDefinition(
+ class_label = 'Temperature + Humidity Sensor',
+ sim_entity_type = SimEntityType.THERMOMETER,
+ sim_entity_fields_class = HassTempHumiditySensorFields,
+ sim_state_class_list = [
+ HassTempHumiditySensorTemperatureState,
+ HassTempHumiditySensorHumidityState,
+ ],
+ ),
SimEntityDefinition(
class_label = 'Thermostat',
sim_entity_type = SimEntityType.THERMOSTAT,