diff --git a/custom_components/hilo/entity.py b/custom_components/hilo/entity.py index 28183440..ab025a6f 100644 --- a/custom_components/hilo/entity.py +++ b/custom_components/hilo/entity.py @@ -49,9 +49,9 @@ def __init__( pass with contextlib.suppress(AttributeError): self._attr_device_info["sw_version"] = device.sw_version - if not name: - name = device.name - self._attr_name = name + # _attr_name would take precedence over a translation_key name. + if not self.has_entity_name: + self._attr_name = name or device.name self._device = device self._hilo = hilo self._device._entity = self diff --git a/custom_components/hilo/sensor.py b/custom_components/hilo/sensor.py index 006ce2eb..2bfaeb8e 100755 --- a/custom_components/hilo/sensor.py +++ b/custom_components/hilo/sensor.py @@ -47,6 +47,7 @@ import homeassistant.util.dt as dt_util from pyhilo.const import UNMONITORED_DEVICES from pyhilo.device import HiloDevice +from pyhilo.device.climate import Climate from pyhilo.event import Event from pyhilo.util import from_utc_timestamp import yaml @@ -54,6 +55,7 @@ from . import Hilo, HiloConfigEntry from .const import ( + CLIMATE_CLASSES, CONF_ENERGY_METER_PERIOD, CONF_GENERATE_ENERGY_METERS, CONF_UNTARIFICATED_DEVICES, @@ -125,6 +127,10 @@ def generate_entities_from_device(device, hilo, scan_interval): entities.append(Co2Sensor(hilo, device)) if device.has_attribute("current_temperature"): entities.append(TemperatureSensor(hilo, device)) + # The device list advertises Humidity even on models without a sensor + # (HT402), so only the GraphQL reading tells them apart. + if device.type in CLIMATE_CLASSES and device.current_humidity is not None: + entities.append(HumiditySensor(hilo, device)) if device.type in HILO_SENSOR_CLASSES: entities.append(DeviceSensor(hilo, device)) if device.has_attribute("noise"): @@ -429,6 +435,27 @@ async def async_added_to_hass(self) -> None: ) +class HumiditySensor(HiloEntity, SensorEntity): + """Define a Hilo thermostat humidity sensor entity.""" + + _attr_device_class = SensorDeviceClass.HUMIDITY + _attr_has_entity_name = True + _attr_native_unit_of_measurement = PERCENTAGE + _attr_state_class = SensorStateClass.MEASUREMENT + _attr_translation_key = "humidity" + + def __init__(self, hilo: Hilo, device: Climate) -> None: + """Hilo Humidity sensor initialization.""" + super().__init__(hilo, device=device) + self._attr_unique_id = f"{device.identifier.lower()}-humidity" + LOG.debug("Setting up HumiditySensor entity: %s", device.name) + + @property + def native_value(self) -> int | None: + """Return the current humidity.""" + return self._device.current_humidity + + class NoiseSensor(HiloEntity, SensorEntity): """Define a Netatmo noise sensor entity.""" diff --git a/custom_components/hilo/translations/en.json b/custom_components/hilo/translations/en.json index 929df0b4..1eef939e 100755 --- a/custom_components/hilo/translations/en.json +++ b/custom_components/hilo/translations/en.json @@ -45,5 +45,12 @@ } } } + }, + "entity": { + "sensor": { + "humidity": { + "name": "Humidity" + } + } } } \ No newline at end of file diff --git a/custom_components/hilo/translations/fr.json b/custom_components/hilo/translations/fr.json index ee8b907d..dfd2c03f 100755 --- a/custom_components/hilo/translations/fr.json +++ b/custom_components/hilo/translations/fr.json @@ -46,5 +46,12 @@ } } } + }, + "entity": { + "sensor": { + "humidity": { + "name": "Humidité" + } + } } } \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py index 451d42a0..1840ddfd 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -14,10 +14,26 @@ async def setup_with_selected_platforms( entry: MockConfigEntry, platforms: list[Platform], mock_api: MagicMock, + graphql_location: dict[str, dict[str, list[dict[str, object]]]] | None = None, ) -> None: - """Set up the Hilo integration with the selected platforms.""" + """Set up the Hilo integration with the selected platforms. + + When given, graphql_location is handled as the getLocation query result, + which is where python-hilo loads device readings such as humidity. + """ if not hass.config_entries.async_get_entry(entry.entry_id): entry.add_to_hass(hass) + graphql_init = ( + patch( + "custom_components.hilo.GraphQlHelper.async_init", + autospec=True, + side_effect=lambda helper: helper._handle_query_result(graphql_location), + ) + if graphql_location is not None + else patch( + "custom_components.hilo.GraphQlHelper.async_init", new_callable=AsyncMock + ) + ) with ( patch("custom_components.hilo.PLATFORMS", platforms), patch("custom_components.hilo.API.async_create", return_value=mock_api), @@ -25,9 +41,7 @@ async def setup_with_selected_platforms( "custom_components.hilo.Hilo.should_signalr_reconnect", new_callable=PropertyMock, ) as mock_should_signalr_reconnect, - patch( - "custom_components.hilo.GraphQlHelper.async_init", new_callable=AsyncMock - ), + graphql_init, patch( "custom_components.hilo.GraphQlHelper.subscribe_to_device_updated", new_callable=AsyncMock, diff --git a/tests/conftest.py b/tests/conftest.py index 8a23bf2b..ed5246ca 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -120,6 +120,25 @@ def device_fixture() -> str: return "all_devices.json" +@pytest.fixture +def ambient_humidity() -> int: + """Return the GraphQL ambientHumidity reported for Thermostat 1. + + 0 is what thermostats without a humidity sensor, such as the HT402, report. + """ + return 0 + + +@pytest.fixture +def graphql_location( + ambient_humidity: int, +) -> dict[str, dict[str, list[dict[str, object]]]]: + """Return a GraphQL getLocation result for Thermostat 1.""" + location = json.loads(load_fixture("graphql_location.json")) + location["getLocation"]["devices"][0]["ambientHumidity"] = ambient_humidity + return location + + @pytest.fixture def mock_api(device_fixture: str) -> Generator[MagicMock]: """Return a mocked Hilo API""" diff --git a/tests/fixtures/graphql_location.json b/tests/fixtures/graphql_location.json new file mode 100644 index 00000000..f1f8cc82 --- /dev/null +++ b/tests/fixtures/graphql_location.json @@ -0,0 +1,47 @@ +{ + "getLocation": { + "devices": [ + { + "deviceType": "Tstat", + "hiloId": "urn:hilo:philo:1a2b3c4d5e6f:0", + "physicalAddress": "1A2B3C4D5E6F", + "connectionStatus": "CONNECTED", + "ambientHumidity": 0, + "gDState": "EXCLUDED", + "version": "21", + "zigbeeVersion": "22", + "ambientTemperature": { + "value": 18, + "kind": "DEGREE_CELSIUS" + }, + "ambientTempSetpoint": { + "value": 15, + "kind": "DEGREE_CELSIUS" + }, + "maxAmbientTempSetpoint": { + "value": 30, + "kind": "DEGREE_CELSIUS" + }, + "minAmbientTempSetpoint": { + "value": 5, + "kind": "DEGREE_CELSIUS" + }, + "maxAmbientTempSetpointLimit": { + "value": 30, + "kind": "DEGREE_CELSIUS" + }, + "minAmbientTempSetpointLimit": { + "value": 5, + "kind": "DEGREE_CELSIUS" + }, + "heatDemand": 0, + "power": { + "value": null, + "kind": "WATT" + }, + "mode": "UNKNOWN", + "allowedModes": [] + } + ] + } +} diff --git a/tests/snapshots/test_sensor.ambr b/tests/snapshots/test_sensor.ambr index ef0fac96..c0611171 100644 --- a/tests/snapshots/test_sensor.ambr +++ b/tests/snapshots/test_sensor.ambr @@ -446,3 +446,57 @@ 'unit_of_measurement': , }) # --- +# name: test_humidity_sensor[45][entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + ]), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.thermostat_1_humidity', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Humidity', + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Humidity', + 'platform': 'hilo', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'humidity', + 'unique_id': '1a2b3c4d5e6f-humidity', + 'unit_of_measurement': '%', + }) +# --- +# name: test_humidity_sensor[45][state] + StateSnapshot({ + 'attributes': dict({ + 'device_class': 'humidity', + 'friendly_name': 'Thermostat 1 Humidity', + 'state_class': , + 'unit_of_measurement': '%', + }), + 'context': , + 'entity_id': 'sensor.thermostat_1_humidity', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '45', + }) +# --- diff --git a/tests/test_sensor.py b/tests/test_sensor.py index 998c3e0b..7adaf553 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -44,6 +44,8 @@ "sensor.water_heater_controller_hilo_energy", "sensor.calypso_water_heater_hilo_energy", ) +HUMIDITY_ENTITY_ID = "sensor.thermostat_1_humidity" +HUMIDITY_UNIQUE_ID = "1a2b3c4d5e6f-humidity" @pytest.fixture(autouse=True) @@ -359,3 +361,71 @@ async def test_energy_sensor_unavailable_or_invalid_power( assert device._energy_entity.native_value == Decimal("0.00") device.update(Disconnected={"value": False}, Power={"value": 0}) + + +@pytest.mark.parametrize("ambient_humidity", [45]) +async def test_humidity_sensor( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, + mock_api: MagicMock, + graphql_location: dict[str, dict[str, list[dict[str, object]]]], +) -> None: + """A thermostat with a GraphQL humidity reading gets a humidity sensor.""" + await setup_with_selected_platforms( + hass, mock_config_entry, [Platform.SENSOR], mock_api, graphql_location + ) + + assert entity_registry.async_get(HUMIDITY_ENTITY_ID) == snapshot(name="entry") + assert hass.states.get(HUMIDITY_ENTITY_ID) == snapshot(name="state") + + +async def test_no_humidity_sensor_without_reading( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, + mock_api: MagicMock, + graphql_location: dict[str, dict[str, list[dict[str, object]]]], +) -> None: + """A thermostat reporting 0 humidity (no sensor, e.g. HT402) gets no sensor.""" + await setup_with_selected_platforms( + hass, mock_config_entry, [Platform.SENSOR], mock_api, graphql_location + ) + + assert ( + entity_registry.async_get_entity_id(Platform.SENSOR, DOMAIN, HUMIDITY_UNIQUE_ID) + is None + ) + + +@pytest.mark.parametrize("ambient_humidity", [45]) +async def test_humidity_sensor_unknown_when_reading_missing( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_api: MagicMock, + graphql_location: dict[str, dict[str, list[dict[str, object]]]], +) -> None: + """A humidity sensor whose reading later goes missing reports unknown.""" + await setup_with_selected_platforms( + hass, mock_config_entry, [Platform.SENSOR], mock_api, graphql_location + ) + hilo = mock_config_entry.runtime_data + + hilo.devices.parse_values_received( + [ + { + "deviceId": 111000, + "locationId": 123, + "timeStampUTC": "2026-11-01T12:00:00Z", + "attribute": "Humidity", + "valueType": "Percentage", + "value": None, + } + ] + ) + await hilo.coordinator.async_refresh() + + state = hass.states.get(HUMIDITY_ENTITY_ID) + assert state is not None + assert state.state == STATE_UNKNOWN