Expose IP addresses on Freebox device trackers (#195814)

This commit is contained in:
KroFR
2026-12-01 17:03:52 +00:00
committed by GitHub
parent d95dcbcfb7
commit 23675cae79
2 changed files with 190 additions and 2 deletions
@@ -70,6 +70,7 @@ class FreeboxDevice(ScannerEntity):
)
self._attr_icon = icon_for_freebox_device(device)
self._active = False
self._attr_ip_address: str | None = None
self._attr_extra_state_attributes: dict[str, Any] = {}
@callback
@@ -78,6 +79,7 @@ class FreeboxDevice(ScannerEntity):
device = self._router.devices[self._mac]
self._active = device["active"]
if device.get("attrs") is None:
self._attr_ip_address = ipv4_for_freebox_device(device)
# device
self._attr_extra_state_attributes = {
"last_time_reachable": datetime.fromtimestamp(
@@ -123,3 +125,22 @@ class FreeboxDevice(ScannerEntity):
def icon_for_freebox_device(device: dict[str, Any]) -> str:
"""Return a device icon from its type."""
return DEVICE_ICONS.get(device["host_type"], "mdi:help-network")
def ipv4_for_freebox_device(device: dict[str, Any]) -> str | None:
"""Return the most relevant IPv4 address for a Freebox device."""
connectivities = [
connectivity
for connectivity in device.get("l3connectivities", [])
if connectivity.get("af") == "ipv4" and connectivity.get("addr")
]
if not connectivities:
return None
return max(
connectivities,
key=lambda connectivity: (
connectivity.get("active", False),
connectivity.get("last_time_reachable", 0),
),
)["addr"]
+169 -2
View File
@@ -1,6 +1,7 @@
"""Tests for the Freebox device trackers."""
from unittest.mock import Mock
from copy import deepcopy
from unittest.mock import Mock, PropertyMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
@@ -9,9 +10,11 @@ from pytest_homeassistant.common import async_fire_time_changed
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN
from homeassistant.components.freebox import SCAN_INTERVAL
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity import Entity
from .common import setup_platform
from .const import DATA_LAN_GET_HOSTS_LIST
async def test_router_mode(
@@ -100,3 +103,167 @@ async def test_device_info(
)
assert device is not None
assert device.name == expected_name
@pytest.mark.parametrize(
("connectivities", "expected_ip"),
[
pytest.param(
[
{
"af": "ipv4",
"addr": "192.168.1.10",
"active": False,
"last_time_reachable": 200,
},
{
"af": "ipv4",
"addr": "192.168.1.20",
"active": True,
"last_time_reachable": 100,
},
],
"192.168.1.20",
id="active-ipv4-preferred",
),
pytest.param(
[
{
"af": "ipv4",
"addr": "192.168.1.10",
"active": False,
"last_time_reachable": 100,
},
{
"af": "ipv4",
"addr": "192.168.1.20",
"active": False,
"last_time_reachable": 200,
},
],
"192.168.1.20",
id="latest-inactive-ipv4",
),
pytest.param([], None, id="no-connectivity"),
pytest.param(
[
{
"af": "ipv6",
"addr": "fe80::1",
"active": True,
"last_time_reachable": 200,
}
],
None,
id="ipv6-only",
),
],
)
async def test_device_tracker_ip_state(
hass: HomeAssistant,
router: Mock,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
connectivities: list[dict],
expected_ip: str | None,
) -> None:
"""Test the IP attribute exposed by the device tracker state."""
hosts = deepcopy(DATA_LAN_GET_HOSTS_LIST)
host = next(
host for host in hosts if host["l2ident"]["id"].lower() == "8c:97:ea:00:00:00"
)
host["l3connectivities"] = connectivities
router().lan.get_hosts_list.side_effect = lambda interface: (
hosts if interface == "pub" else []
)
with patch.object(
Entity,
"entity_registry_enabled_default",
new_callable=PropertyMock,
return_value=True,
):
entry = await setup_platform(hass, DEVICE_TRACKER_DOMAIN)
device = device_registry.async_get_device_by_connection(
(dr.CONNECTION_NETWORK_MAC, "8c:97:ea:00:00:00"), entry.entry_id
)
assert device is not None
entities = er.async_entries_for_device(entity_registry, device.id)
tracker = next(
entity for entity in entities if entity.domain == DEVICE_TRACKER_DOMAIN
)
state = hass.states.get(tracker.entity_id)
assert state is not None
assert state.attributes.get("ip") == expected_ip
async def test_device_tracker_ip_updates_and_disconnects(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
router: Mock,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test that polling updates the IP and retains it after disconnection."""
hosts = deepcopy(DATA_LAN_GET_HOSTS_LIST)
host = next(
host for host in hosts if host["l2ident"]["id"].lower() == "8c:97:ea:00:00:00"
)
host["active"] = True
host["l3connectivities"] = [
{
"af": "ipv4",
"addr": "192.168.1.10",
"active": True,
"last_time_reachable": 100,
}
]
router().lan.get_hosts_list.side_effect = lambda interface: (
hosts if interface == "pub" else []
)
with patch.object(
Entity,
"entity_registry_enabled_default",
new_callable=PropertyMock,
return_value=True,
):
entry = await setup_platform(hass, DEVICE_TRACKER_DOMAIN)
device = device_registry.async_get_device_by_connection(
(dr.CONNECTION_NETWORK_MAC, "8c:97:ea:00:00:00"), entry.entry_id
)
assert device is not None
tracker = next(
entity
for entity in er.async_entries_for_device(entity_registry, device.id)
if entity.domain == DEVICE_TRACKER_DOMAIN
)
state = hass.states.get(tracker.entity_id)
assert state is not None
assert state.state == "home"
assert state.attributes["ip"] == "192.168.1.10"
host["l3connectivities"] = [
{
"af": "ipv4",
"addr": "192.168.1.20",
"active": True,
"last_time_reachable": 200,
}
]
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(tracker.entity_id)
assert state is not None
assert state.attributes["ip"] == "192.168.1.20"
host["active"] = False
host["l3connectivities"][0]["active"] = False
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(tracker.entity_id)
assert state is not None
assert state.state == "not_home"
assert state.attributes["ip"] == "192.168.1.20"