Refactor Freebox : add config flow + temperature sensor + signal dispatch (#30334)
* Add config flow to Freebox * Add manufacturer in device_tracker info * Add device_info to sensor + switch * Add device_info: connections * Add config_flow test + update .coveragerc * Typing * Add device_type icon * Remove one error log * Fix pylint * Add myself as CODEOWNER * Handle sync in one place * Separate the Freebox[Router/Device/Sensor] from __init__.py * Add link step to config flow * Make temperature sensors auto-discovered * Use device activity instead of reachablility for device_tracker * Store token file in .storage Depending on host if list of Freebox integration on the future without breaking change * Remove IP sensors + add Freebox router as a device with attrs : IPs, conection type, uptime, version & serial * Add sensor should_poll=False * Test typing * Handle devices with no name * None is the default for data * Fix comment * Use config_entry.unique_id * Add async_unload_entry with asyncio * Add and use bunch of data size and rate related constants (#31781) * Review * Remove useless "already_configured" error string * Review : merge 2 device & 2 sensor classes * Entities from platforms * Fix unload + add device after setup + clean loggers * async_add_entities True * Review * Use pathlib + refactor get_api * device_tracker set + tests with CoroutineMock() * Removing active & reachable from tracker attrs * Review * Fix pipeline * typing * typing * typing * Raise ConfigEntryNotReady when HttpRequestError at setup * Review * Multiple Freebox s * Review: store sensors in router * Freebox: a sensor story
This commit is contained in:
1 parent
180bcad477
commit
19be4a5d6d
17 files changed
+917
-165
No files matched your search
@@ -1,65 +1,148 @@
|
||||
"""Support for Freebox devices (Freebox v6 and Freebox mini 4K)."""
|
||||
from collections import namedtuple
|
||||
from datetime import datetime
|
||||
import logging
|
||||
from typing import Dict
|
||||
|
||||
from homeassistant.components.device_tracker import DeviceScanner
|
||||
from homeassistant.components.device_tracker import SOURCE_TYPE_ROUTER
|
||||
from homeassistant.components.device_tracker.config_entry import ScannerEntity
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
from homeassistant.helpers.typing import HomeAssistantType
|
||||
|
||||
from . import DATA_FREEBOX
|
||||
from .const import DEFAULT_DEVICE_NAME, DEVICE_ICONS, DOMAIN
|
||||
from .router import FreeboxRouter
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_get_scanner(hass, config):
|
||||
"""Validate the configuration and return a Freebox scanner."""
|
||||
scanner = FreeboxDeviceScanner(hass.data[DATA_FREEBOX])
|
||||
await scanner.async_connect()
|
||||
return scanner if scanner.success_init else None
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
|
||||
) -> None:
|
||||
"""Set up device tracker for Freebox component."""
|
||||
router = hass.data[DOMAIN][entry.unique_id]
|
||||
tracked = set()
|
||||
|
||||
@callback
|
||||
def update_router():
|
||||
"""Update the values of the router."""
|
||||
add_entities(router, async_add_entities, tracked)
|
||||
|
||||
Device = namedtuple("Device", ["id", "name", "ip"])
|
||||
|
||||
|
||||
def _build_device(device_dict):
|
||||
return Device(
|
||||
device_dict["l2ident"]["id"],
|
||||
device_dict["primary_name"],
|
||||
device_dict["l3connectivities"][0]["addr"],
|
||||
router.listeners.append(
|
||||
async_dispatcher_connect(hass, router.signal_device_new, update_router)
|
||||
)
|
||||
|
||||
update_router()
|
||||
|
||||
class FreeboxDeviceScanner(DeviceScanner):
|
||||
"""Queries the Freebox device."""
|
||||
|
||||
def __init__(self, fbx):
|
||||
"""Initialize the scanner."""
|
||||
self.last_results = {}
|
||||
self.success_init = False
|
||||
self.connection = fbx
|
||||
@callback
|
||||
def add_entities(router, async_add_entities, tracked):
|
||||
"""Add new tracker entities from the router."""
|
||||
new_tracked = []
|
||||
|
||||
async def async_connect(self):
|
||||
"""Initialize connection to the router."""
|
||||
# Test the router is accessible.
|
||||
data = await self.connection.lan.get_hosts_list()
|
||||
self.success_init = data is not None
|
||||
for mac, device in router.devices.items():
|
||||
if mac in tracked:
|
||||
continue
|
||||
|
||||
async def async_scan_devices(self):
|
||||
"""Scan for new devices and return a list with found device IDs."""
|
||||
await self.async_update_info()
|
||||
return [device.id for device in self.last_results]
|
||||
new_tracked.append(FreeboxDevice(router, device))
|
||||
tracked.add(mac)
|
||||
|
||||
async def get_device_name(self, device):
|
||||
"""Return the name of the given device or None if we don't know."""
|
||||
name = next(
|
||||
(result.name for result in self.last_results if result.id == device), None
|
||||
if new_tracked:
|
||||
async_add_entities(new_tracked, True)
|
||||
|
||||
|
||||
class FreeboxDevice(ScannerEntity):
|
||||
"""Representation of a Freebox device."""
|
||||
|
||||
def __init__(self, router: FreeboxRouter, device: Dict[str, any]) -> None:
|
||||
"""Initialize a Freebox device."""
|
||||
self._router = router
|
||||
self._name = device["primary_name"].strip() or DEFAULT_DEVICE_NAME
|
||||
self._mac = device["l2ident"]["id"]
|
||||
self._manufacturer = device["vendor_name"]
|
||||
self._icon = icon_for_freebox_device(device)
|
||||
self._active = False
|
||||
self._attrs = {}
|
||||
|
||||
self._unsub_dispatcher = None
|
||||
|
||||
def update(self) -> None:
|
||||
"""Update the Freebox device."""
|
||||
device = self._router.devices[self._mac]
|
||||
self._active = device["active"]
|
||||
if device.get("attrs") is None:
|
||||
# device
|
||||
self._attrs = {
|
||||
"last_time_reachable": datetime.fromtimestamp(
|
||||
device["last_time_reachable"]
|
||||
),
|
||||
"last_time_activity": datetime.fromtimestamp(device["last_activity"]),
|
||||
}
|
||||
else:
|
||||
# router
|
||||
self._attrs = device["attrs"]
|
||||
|
||||
@property
|
||||
def unique_id(self) -> str:
|
||||
"""Return a unique ID."""
|
||||
return self._mac
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""Return the name."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def is_connected(self):
|
||||
"""Return true if the device is connected to the network."""
|
||||
return self._active
|
||||
|
||||
@property
|
||||
def source_type(self) -> str:
|
||||
"""Return the source type."""
|
||||
return SOURCE_TYPE_ROUTER
|
||||
|
||||
@property
|
||||
def icon(self) -> str:
|
||||
"""Return the icon."""
|
||||
return self._icon
|
||||
|
||||
@property
|
||||
def device_state_attributes(self) -> Dict[str, any]:
|
||||
"""Return the attributes."""
|
||||
return self._attrs
|
||||
|
||||
@property
|
||||
def device_info(self) -> Dict[str, any]:
|
||||
"""Return the device information."""
|
||||
return {
|
||||
"connections": {(CONNECTION_NETWORK_MAC, self._mac)},
|
||||
"identifiers": {(DOMAIN, self.unique_id)},
|
||||
"name": self.name,
|
||||
"manufacturer": self._manufacturer,
|
||||
}
|
||||
|
||||
@property
|
||||
def should_poll(self) -> bool:
|
||||
"""No polling needed."""
|
||||
return False
|
||||
|
||||
async def async_on_demand_update(self):
|
||||
"""Update state."""
|
||||
self.async_schedule_update_ha_state(True)
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Register state update callback."""
|
||||
self._unsub_dispatcher = async_dispatcher_connect(
|
||||
self.hass, self._router.signal_device_update, self.async_on_demand_update
|
||||
)
|
||||
return name
|
||||
|
||||
async def async_update_info(self):
|
||||
"""Ensure the information from the Freebox router is up to date."""
|
||||
_LOGGER.debug("Checking Devices")
|
||||
async def async_will_remove_from_hass(self):
|
||||
"""Clean up after entity before removal."""
|
||||
self._unsub_dispatcher()
|
||||
|
||||
hosts = await self.connection.lan.get_hosts_list()
|
||||
|
||||
last_results = [_build_device(device) for device in hosts if device["active"]]
|
||||
|
||||
self.last_results = last_results
|
||||
def icon_for_freebox_device(device) -> str:
|
||||
"""Return a host icon from his type."""
|
||||
return DEVICE_ICONS.get(device["host_type"], "mdi:help-network")
|
||||
Reference in new issue
Block a user