Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions custom_components/hilo/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions custom_components/hilo/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,15 @@
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
from yaml.scanner import ScannerError

from . import Hilo, HiloConfigEntry
from .const import (
CLIMATE_CLASSES,
CONF_ENERGY_METER_PERIOD,
CONF_GENERATE_ENERGY_METERS,
CONF_UNTARIFICATED_DEVICES,
Expand Down Expand Up @@ -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"):
Expand Down Expand Up @@ -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."""

Expand Down
7 changes: 7 additions & 0 deletions custom_components/hilo/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,12 @@
}
}
}
},
"entity": {
"sensor": {
"humidity": {
"name": "Humidity"
}
}
}
}
7 changes: 7 additions & 0 deletions custom_components/hilo/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,12 @@
}
}
}
},
"entity": {
"sensor": {
"humidity": {
"name": "Humidité"
}
}
}
}
22 changes: 18 additions & 4 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,34 @@ 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),
patch(
"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,
Expand Down
19 changes: 19 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
Expand Down
47 changes: 47 additions & 0 deletions tests/fixtures/graphql_location.json
Original file line number Diff line number Diff line change
@@ -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": []
}
]
}
}
54 changes: 54 additions & 0 deletions tests/snapshots/test_sensor.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -446,3 +446,57 @@
'unit_of_measurement': <UnitOfEnergy.KILO_WATT_HOUR: 'kWh'>,
})
# ---
# name: test_humidity_sensor[45][entry]
EntityRegistryEntrySnapshot({
'aliases': list([
]),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': None,
'entity_id': 'sensor.thermostat_1_humidity',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Humidity',
'options': dict({
}),
'original_device_class': <SensorDeviceClass.HUMIDITY: 'humidity'>,
'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': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': '%',
}),
'context': <ANY>,
'entity_id': 'sensor.thermostat_1_humidity',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '45',
})
# ---
70 changes: 70 additions & 0 deletions tests/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Loading