Skip to content
Open
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
1 change: 1 addition & 0 deletions .strict-typing
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,7 @@ homeassistant.components.kulersky.*
homeassistant.components.labs.*
homeassistant.components.lacrosse.*
homeassistant.components.lacrosse_view.*
homeassistant.components.laifen.*
homeassistant.components.lamarzocco.*
homeassistant.components.lametric.*
homeassistant.components.laundrify.*
Expand Down
2 changes: 2 additions & 0 deletions CODEOWNERS

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

44 changes: 44 additions & 0 deletions homeassistant/components/laifen/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""The Laifen integration."""

from laifen_ble import LaifenToothbrush

from homeassistant.const import CONF_ADDRESS, EVENT_HOMEASSISTANT_STOP, Platform
from homeassistant.core import Event, HomeAssistant
from homeassistant.helpers import device_registry as dr

from .const import DOMAIN
from .coordinator import LaifenConfigEntry, LaifenCoordinator

PLATFORMS: list[Platform] = [Platform.SENSOR]


async def async_setup_entry(hass: HomeAssistant, entry: LaifenConfigEntry) -> None:
"""Set up Laifen from a config entry."""
address: str = entry.data[CONF_ADDRESS]
device = dr.async_get(hass).async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, address)},
connections={(dr.CONNECTION_BLUETOOTH, address)},
manufacturer="Laifen",
model="Wave",
model_id="LFTB01-P",
name=entry.title,
)
toothbrush = LaifenToothbrush(address)
coordinator = LaifenCoordinator(hass, entry, toothbrush, device.id)
await coordinator.async_config_entry_first_refresh()
entry.runtime_data = coordinator

async def _async_disconnect(event: Event) -> None:
"""Disconnect from the toothbrush when Home Assistant stops."""
await toothbrush.disconnect()

entry.async_on_unload(
hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, _async_disconnect)
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)


async def async_unload_entry(hass: HomeAssistant, entry: LaifenConfigEntry) -> None:
"""Unload a config entry."""
await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS)
124 changes: 124 additions & 0 deletions homeassistant/components/laifen/config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
"""Config flow for the Laifen integration."""

from typing import TYPE_CHECKING, Any, override

from laifen_ble import (
LaifenConnectionError,
LaifenToothbrush,
UnsupportedStateError,
is_supported,
)
import probatio

from homeassistant.components.bluetooth import (
BluetoothServiceInfoBleak,
async_ble_device_from_address,
async_discovered_service_info,
)
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_ADDRESS
from homeassistant.data_entry_flow import AbortFlow

from .const import DOMAIN


class LaifenConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Laifen."""

def __init__(self) -> None:
"""Initialize the config flow."""
self._discovery_info: BluetoothServiceInfoBleak | None = None
self._discovered_devices: dict[str, BluetoothServiceInfoBleak] = {}

async def _async_can_connect(self, address: str) -> bool:
"""Return whether the toothbrush can be connected to."""
ble_device = async_ble_device_from_address(self.hass, address, connectable=True)
if ble_device is None:
return False
toothbrush = LaifenToothbrush(ble_device)
try:
await toothbrush.connect()
except UnsupportedStateError as err:
raise AbortFlow("unsupported_firmware") from err
except LaifenConnectionError:
return False
await toothbrush.disconnect()
return True

@override
async def async_step_bluetooth(
self, discovery_info: BluetoothServiceInfoBleak
) -> ConfigFlowResult:
"""Handle a discovered toothbrush."""
await self.async_set_unique_id(discovery_info.address)
self._abort_if_unique_id_configured()
self._discovery_info = discovery_info
self.context["title_placeholders"] = {"name": discovery_info.name}
return await self.async_step_bluetooth_confirm()

async def async_step_bluetooth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm the discovered toothbrush."""
discovery_info = self._discovery_info
if TYPE_CHECKING:
assert discovery_info is not None
errors: dict[str, str] = {}
if user_input is not None:
if await self._async_can_connect(discovery_info.address):
return self.async_create_entry(
title=discovery_info.name,
data={CONF_ADDRESS: discovery_info.address},
)
errors["base"] = "cannot_connect"
return self.async_show_form(
step_id="bluetooth_confirm",
description_placeholders={"name": discovery_info.name},
errors=errors,
)

@override
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Pick a discovered toothbrush."""
errors: dict[str, str] = {}
if user_input is not None:
address = user_input[CONF_ADDRESS]
await self.async_set_unique_id(address, raise_on_progress=False)
self._abort_if_unique_id_configured()
if await self._async_can_connect(address):
return self.async_create_entry(
title=self._discovered_devices[address].name,
data={CONF_ADDRESS: address},
)
errors["base"] = "cannot_connect"

current_addresses = self._async_current_ids(include_ignore=False)
for discovery_info in async_discovered_service_info(self.hass):
address = discovery_info.address
if (
address in current_addresses
or address in self._discovered_devices
or not is_supported(discovery_info.name)
):
continue
self._discovered_devices[address] = discovery_info

if not self._discovered_devices:
return self.async_abort(reason="no_devices_found")

return self.async_show_form(
step_id="user",
data_schema=probatio.Schema(
{
probatio.Required(CONF_ADDRESS): probatio.In(
{
address: f"{discovery_info.name} ({address})"
for address, discovery_info in self._discovered_devices.items()
}
)
}
),
errors=errors,
)
3 changes: 3 additions & 0 deletions homeassistant/components/laifen/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""Constants for the Laifen integration."""

DOMAIN = "laifen"
169 changes: 169 additions & 0 deletions homeassistant/components/laifen/coordinator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
"""Coordinator for the Laifen integration."""

from datetime import timedelta
import logging
from typing import override

from laifen_ble import LaifenConnectionError, LaifenToothbrush, UnsupportedStateError

from homeassistant.components.bluetooth import (
MONOTONIC_TIME,
BluetoothCallbackMatcher,
BluetoothCallbackReplay,
BluetoothChange,
BluetoothReachabilityIntent,
BluetoothScanningMode,
BluetoothServiceInfoBleak,
async_address_reachability_diagnostics,
async_clear_advertisement_history,
async_last_service_info,
async_register_callback,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

_LOGGER = logging.getLogger(__name__)

UPDATE_INTERVAL = timedelta(minutes=1)
ADVERTISEMENT_MAX_AGE = 30

type LaifenConfigEntry = ConfigEntry[LaifenCoordinator]


class LaifenCoordinator(DataUpdateCoordinator[None]):
"""Connect to a Laifen toothbrush whenever it is awake.

The toothbrush advertises the same data whenever it wakes up, so the
advertisement history is cleared at setup and after every connection to
hear the next wake-up. Its state is pushed over the connection, except for
the battery level, which is read every minute while it stays connected on
its charger.
"""

config_entry: LaifenConfigEntry

def __init__(
self,
hass: HomeAssistant,
config_entry: LaifenConfigEntry,
toothbrush: LaifenToothbrush,
device_id: str,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name=config_entry.title,
)
self.toothbrush = toothbrush
self.device_id = device_id
self._connected = False
self._firmware_version: str | None = None

@override
async def _async_setup(self) -> None:
"""Listen to the toothbrush and to its advertisements."""
self.config_entry.async_on_unload(
self.toothbrush.register_callback(self._async_handle_toothbrush_update)
)
self.config_entry.async_on_unload(
async_register_callback(
self.hass,
self._async_handle_advertisement,
BluetoothCallbackMatcher(
address=self.toothbrush.address, connectable=True
),
BluetoothScanningMode.PASSIVE,
replay=BluetoothCallbackReplay.DISABLED,
)
)
async_clear_advertisement_history(self.hass, self.toothbrush.address)

@callback
def _async_handle_advertisement(
self, service_info: BluetoothServiceInfoBleak, change: BluetoothChange
) -> None:
"""Connect when the toothbrush wakes up and advertises."""
if self.hass.is_stopping or self.toothbrush.connected:
return
self.config_entry.async_create_background_task(
self.hass, self.async_request_refresh(), "laifen connect"
)

@callback
def _async_handle_toothbrush_update(self) -> None:
"""Handle a change of the toothbrush or of its connection."""
if self.hass.is_stopping:
return
connected = self.toothbrush.connected
if connected != self._connected:
self._connected = connected
if connected:
_LOGGER.info("Connected to %s", self.toothbrush.name)
self.update_interval = UPDATE_INTERVAL
else:
_LOGGER.info("%s is asleep or out of range", self.toothbrush.name)
self.update_interval = None
async_clear_advertisement_history(self.hass, self.toothbrush.address)
self._async_update_firmware_version()
self.async_set_updated_data(None)

@callback
def _async_update_firmware_version(self) -> None:
"""Store the firmware version on the device."""
firmware_version = self.toothbrush.firmware_version
if firmware_version is None or firmware_version == self._firmware_version:
return
self._firmware_version = firmware_version
dr.async_get(self.hass).async_update_device(
self.device_id, sw_version=firmware_version
)

@override
async def _async_update_data(self) -> None:
"""Read the state of a connected toothbrush, or connect if it is awake."""
if self.hass.is_stopping:
return
if self.toothbrush.connected:
try:
await self.toothbrush.update()
except LaifenConnectionError as err:
_LOGGER.debug("Could not update %s: %s", self.toothbrush.name, err)
await self.toothbrush.disconnect()
return
service_info = async_last_service_info(
self.hass, self.toothbrush.address, connectable=True
)
if service_info is None:
return
if MONOTONIC_TIME() - service_info.time > ADVERTISEMENT_MAX_AGE:
async_clear_advertisement_history(self.hass, self.toothbrush.address)
return
self.toothbrush.set_ble_device(service_info.device)
try:
await self.toothbrush.connect()
except UnsupportedStateError as err:
_LOGGER.warning(
"%s sends a state that is not supported: %s", self.toothbrush.name, err
)
except LaifenConnectionError as err:
_LOGGER.debug(
"Could not connect to %s: %s (%s)",
self.toothbrush.name,
err,
async_address_reachability_diagnostics(
self.hass,
self.toothbrush.address,
BluetoothReachabilityIntent.CONNECTION,
),
)
async_clear_advertisement_history(self.hass, self.toothbrush.address)

@override
async def async_shutdown(self) -> None:
"""Disconnect from the toothbrush."""
await super().async_shutdown()
await self.toothbrush.disconnect()
33 changes: 33 additions & 0 deletions homeassistant/components/laifen/entity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""Base entity for the Laifen integration."""

from laifen_ble import LaifenToothbrush

from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN
from .coordinator import LaifenCoordinator


class LaifenEntity(CoordinatorEntity[LaifenCoordinator]):
"""Base class for Laifen entities."""

_attr_has_entity_name = True

def __init__(
self,
coordinator: LaifenCoordinator,
entity_description: EntityDescription,
) -> None:
"""Initialize the entity."""
super().__init__(coordinator)
self.entity_description = entity_description
address = coordinator.toothbrush.address
self._attr_unique_id = f"{address}_{entity_description.key}"
self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, address)})

@property
def toothbrush(self) -> LaifenToothbrush:
"""Return the toothbrush."""
return self.coordinator.toothbrush
Loading