mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 12:21:04 -04:00
Keep registered FRITZ!Box sensors while the device boots (#193873)
This commit is contained in:
@@ -10,6 +10,7 @@ from fritzconnection.lib.fritzstatus import FritzStatus
|
||||
from requests.exceptions import RequestException
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
DOMAIN as SENSOR_DOMAIN,
|
||||
SensorDeviceClass,
|
||||
SensorEntity,
|
||||
SensorEntityDescription,
|
||||
@@ -24,13 +25,14 @@ from homeassistant.const import (
|
||||
UnitOfTemperature,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
from homeassistant.helpers.typing import StateType
|
||||
from homeassistant.util.dt import utcnow
|
||||
|
||||
from .const import CONNECTION_TYPE_WLAN, DSL_CONNECTION, LOGGER
|
||||
from .const import CONNECTION_TYPE_WLAN, DOMAIN, DSL_CONNECTION, LOGGER
|
||||
from .coordinator import FRITZ_DATA_KEY, AvmWrapper, FritzConfigEntry, FritzData
|
||||
from .entity import (
|
||||
FritzBoxBaseCoordinatorEntity,
|
||||
@@ -63,9 +65,11 @@ def _retrieve_external_ip_state(status: FritzStatus, last_value: str) -> str:
|
||||
return status.external_ip # type: ignore[no-any-return]
|
||||
|
||||
|
||||
def _retrieve_external_ipv6_state(status: FritzStatus, last_value: str) -> str:
|
||||
def _retrieve_external_ipv6_state(
|
||||
status: FritzStatus, last_value: str | None
|
||||
) -> str | None:
|
||||
"""Return external ipv6 from device."""
|
||||
return str(status.external_ipv6)
|
||||
return str(status.external_ipv6) or None
|
||||
|
||||
|
||||
def _retrieve_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:
|
||||
@@ -141,9 +145,13 @@ def _retrieve_cpu_temperature_state(
|
||||
) -> float | None:
|
||||
"""Return the first CPU temperature value."""
|
||||
try:
|
||||
return status.get_cpu_temperatures()[0] # type: ignore[no-any-return]
|
||||
except RequestException:
|
||||
cpu_temp: float = status.get_cpu_temperatures()[0]
|
||||
except RequestException, IndexError, FritzConnectionException:
|
||||
return None
|
||||
# Reported while the device is still booting
|
||||
if cpu_temp == 0:
|
||||
return None
|
||||
return cpu_temp
|
||||
|
||||
|
||||
def _is_suitable_cpu_temperature(status: FritzStatus) -> bool:
|
||||
@@ -166,6 +174,7 @@ class FritzConnectionSensorEntityDescription(
|
||||
"""Describes Fritz connection sensor entity."""
|
||||
|
||||
is_suitable: Callable[[ConnectionInfo], bool] = lambda info: info.wan_enabled
|
||||
keep_if_registered: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
@@ -175,6 +184,7 @@ class FritzDeviceSensorEntityDescription(
|
||||
"""Describes Fritz device sensor entity."""
|
||||
|
||||
is_suitable: Callable[[FritzStatus], bool] = lambda status: True
|
||||
keep_if_registered: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
@@ -198,6 +208,7 @@ CONNECTION_SENSOR_TYPES: tuple[FritzConnectionSensorEntityDescription, ...] = (
|
||||
translation_key="external_ipv6",
|
||||
value_fn=_retrieve_external_ipv6_state,
|
||||
is_suitable=lambda info: info.ipv6_active,
|
||||
keep_if_registered=True,
|
||||
),
|
||||
FritzConnectionSensorEntityDescription(
|
||||
key="connection_uptime",
|
||||
@@ -326,6 +337,7 @@ DEVICE_SENSOR_TYPES: tuple[FritzDeviceSensorEntityDescription, ...] = (
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
value_fn=_retrieve_cpu_temperature_state,
|
||||
is_suitable=_is_suitable_cpu_temperature,
|
||||
keep_if_registered=True,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -381,25 +393,45 @@ LINK_SENSOR_TYPES: tuple[FritzLinkSensorEntityDescription, ...] = (
|
||||
)
|
||||
|
||||
|
||||
@callback
|
||||
def _async_registered_keys(avm_wrapper: AvmWrapper) -> set[str]:
|
||||
"""Return keys of sensors already registered, kept while the device boots."""
|
||||
entity_registry = er.async_get(avm_wrapper.hass)
|
||||
descriptions: tuple[
|
||||
FritzConnectionSensorEntityDescription | FritzDeviceSensorEntityDescription,
|
||||
...,
|
||||
] = (*CONNECTION_SENSOR_TYPES, *DEVICE_SENSOR_TYPES)
|
||||
return {
|
||||
description.key
|
||||
for description in descriptions
|
||||
if description.keep_if_registered
|
||||
and entity_registry.async_get_entity_id(
|
||||
SENSOR_DOMAIN, DOMAIN, f"{avm_wrapper.unique_id}-{description.key}"
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
async def _async_connection_sensors(
|
||||
avm_wrapper: AvmWrapper, device_friendly_name: str
|
||||
avm_wrapper: AvmWrapper, device_friendly_name: str, registered_keys: set[str]
|
||||
) -> list[FritzBoxSensor]:
|
||||
connection_info = await avm_wrapper.async_get_connection_info()
|
||||
return [
|
||||
FritzBoxSensor(avm_wrapper, device_friendly_name, description)
|
||||
for description in CONNECTION_SENSOR_TYPES
|
||||
if description.is_suitable(connection_info)
|
||||
if description.key in registered_keys
|
||||
or description.is_suitable(connection_info)
|
||||
]
|
||||
|
||||
|
||||
async def _async_device_sensors(
|
||||
avm_wrapper: AvmWrapper, device_friendly_name: str
|
||||
avm_wrapper: AvmWrapper, device_friendly_name: str, registered_keys: set[str]
|
||||
) -> list[FritzBoxSensor]:
|
||||
def _generate_device_sensors() -> list[FritzBoxSensor]:
|
||||
return [
|
||||
FritzBoxSensor(avm_wrapper, device_friendly_name, description)
|
||||
for description in DEVICE_SENSOR_TYPES
|
||||
if description.is_suitable(avm_wrapper.fritz_status)
|
||||
if description.key in registered_keys
|
||||
or description.is_suitable(avm_wrapper.fritz_status)
|
||||
]
|
||||
|
||||
return await avm_wrapper.hass.async_add_executor_job(_generate_device_sensors)
|
||||
@@ -443,10 +475,15 @@ async def async_all_entities_list(
|
||||
data_fritz: FritzData,
|
||||
) -> list[Entity]:
|
||||
"""Get a list of all entities."""
|
||||
registered_keys = _async_registered_keys(avm_wrapper)
|
||||
|
||||
return [
|
||||
*await _async_connection_sensors(avm_wrapper, device_friendly_name),
|
||||
*await _async_device_sensors(avm_wrapper, device_friendly_name),
|
||||
*await _async_connection_sensors(
|
||||
avm_wrapper, device_friendly_name, registered_keys
|
||||
),
|
||||
*await _async_device_sensors(
|
||||
avm_wrapper, device_friendly_name, registered_keys
|
||||
),
|
||||
*_async_link_sensors(avm_wrapper, data_fritz),
|
||||
]
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ from homeassistant.components.fritz.const import (
|
||||
SCAN_INTERVAL,
|
||||
)
|
||||
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import CONF_HOST, STATE_UNAVAILABLE, STATE_UNKNOWN, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
@@ -36,6 +37,7 @@ from .const import (
|
||||
MOCK_HOST_ATTRIBUTES_DATA,
|
||||
MOCK_HOST_PHONE,
|
||||
MOCK_MESH_DATA,
|
||||
MOCK_SERIAL_NUMBER,
|
||||
MOCK_USER_DATA,
|
||||
MOCK_WLAN_DEVICE_NODE,
|
||||
)
|
||||
@@ -259,6 +261,80 @@ async def test_sensor_cpu_temp_unknown_on_request_error(
|
||||
assert state.state == STATE_UNKNOWN
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("key", "attribute", "booting_value", "booted_value", "expected_state"),
|
||||
[
|
||||
pytest.param(
|
||||
"external_ipv6", "external_ipv6", "", "fec0::1", "fec0::1", id="ipv6"
|
||||
),
|
||||
pytest.param(
|
||||
"cpu_temperature",
|
||||
"get_cpu_temperatures",
|
||||
MagicMock(return_value=[0, 0]),
|
||||
MagicMock(return_value=[42, 38]),
|
||||
"42",
|
||||
id="cpu_temperature_zero",
|
||||
),
|
||||
pytest.param(
|
||||
"cpu_temperature",
|
||||
"get_cpu_temperatures",
|
||||
MagicMock(return_value=[]),
|
||||
MagicMock(return_value=[42, 38]),
|
||||
"42",
|
||||
id="cpu_temperature_empty",
|
||||
),
|
||||
pytest.param(
|
||||
"cpu_temperature",
|
||||
"get_cpu_temperatures",
|
||||
MagicMock(side_effect=FritzConnectionException("boom")),
|
||||
MagicMock(return_value=[42, 38]),
|
||||
"42",
|
||||
id="cpu_temperature_error",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("fc_class_mock", "fh_class_mock", "fs_class_mock")
|
||||
async def test_registered_sensor_kept_while_booting(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
key: str,
|
||||
attribute: str,
|
||||
booting_value: str | MagicMock,
|
||||
booted_value: str | MagicMock,
|
||||
expected_state: str,
|
||||
) -> None:
|
||||
"""Test a registered sensor is created while the device has no value yet."""
|
||||
entity_id = f"sensor.mock_title_{key}"
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
|
||||
entry.add_to_hass(hass)
|
||||
entity_registry.async_get_or_create(
|
||||
SENSOR_DOMAIN,
|
||||
DOMAIN,
|
||||
f"{MOCK_SERIAL_NUMBER}-{key}",
|
||||
config_entry=entry,
|
||||
suggested_object_id=f"mock_title_{key}",
|
||||
)
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.fritz.PLATFORMS", [Platform.SENSOR]),
|
||||
patch.object(FritzStatus, attribute, booting_value),
|
||||
):
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state == STATE_UNKNOWN
|
||||
|
||||
with patch.object(FritzStatus, attribute, booted_value):
|
||||
freezer.tick(SCAN_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state == expected_state
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fc_data",
|
||||
[
|
||||
@@ -295,6 +371,45 @@ async def test_sensor_addon_infos_not_supported(
|
||||
assert "Error adding entity" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fc_data",
|
||||
[
|
||||
{
|
||||
**MOCK_FB_SERVICES,
|
||||
"WANCommonIFC1": {
|
||||
**MOCK_FB_SERVICES["WANCommonIFC1"],
|
||||
"GetAddonInfos": FritzConnectionException("Not available Action"),
|
||||
},
|
||||
}
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("fc_class_mock", "fh_class_mock", "fs_class_mock")
|
||||
async def test_registered_sensor_not_kept_when_not_supported(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test a registered traffic sensor is not created when not supported."""
|
||||
entity_id = "sensor.mock_title_upload_throughput"
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
|
||||
entry.add_to_hass(hass)
|
||||
entity_registry.async_get_or_create(
|
||||
SENSOR_DOMAIN,
|
||||
DOMAIN,
|
||||
f"{MOCK_SERIAL_NUMBER}-kb_s_sent",
|
||||
config_entry=entry,
|
||||
suggested_object_id="mock_title_upload_throughput",
|
||||
)
|
||||
|
||||
with patch("homeassistant.components.fritz.PLATFORMS", [Platform.SENSOR]):
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
assert hass.states.get(entity_id) is None
|
||||
assert "Error adding entity" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.usefixtures(
|
||||
"fc_class_mock", "fh_class_mock", "fs_class_mock", "wlan_device_link"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user