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
1 change: 1 addition & 0 deletions .strict-typing
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ homeassistant.components.water_heater.*
homeassistant.components.watttime.*
homeassistant.components.weather.*
homeassistant.components.websocket_api.*
homeassistant.components.wemo.*
homeassistant.components.zodiac.*
homeassistant.components.zeroconf.*
homeassistant.components.zone.*
Expand Down
63 changes: 31 additions & 32 deletions homeassistant/components/wemo/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Support for WeMo device discovery."""
from __future__ import annotations

from collections.abc import Sequence
import logging
from typing import Any, Optional, Tuple

import pywemo
import voluptuous as vol
Expand All @@ -14,10 +16,11 @@
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DISCOVERY, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant, callback
from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_call_later
from homeassistant.helpers.typing import ConfigType
from homeassistant.util.async_ import gather_with_concurrency

from .const import DOMAIN
Expand All @@ -44,21 +47,20 @@

_LOGGER = logging.getLogger(__name__)

HostPortTuple = Tuple[str, Optional[int]]

def coerce_host_port(value):

def coerce_host_port(value: str) -> HostPortTuple:
"""Validate that provided value is either just host or host:port.

Returns (host, None) or (host, port) respectively.
"""
host, _, port = value.partition(":")
host, _, port_str = value.partition(":")

if not host:
raise vol.Invalid("host cannot be empty")

if port:
port = cv.port(port)
else:
port = None
port = cv.port(port_str) if port_str else None

return host, port

Expand All @@ -82,7 +84,7 @@ def coerce_host_port(value):
)


async def async_setup(hass, config):
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up for WeMo devices."""
hass.data[DOMAIN] = {
"config": config.get(DOMAIN, {}),
Expand Down Expand Up @@ -112,11 +114,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
discovery_responder = pywemo.ssdp.DiscoveryResponder(registry.port)
await hass.async_add_executor_job(discovery_responder.start)

static_conf = config.get(CONF_STATIC, [])
static_conf: Sequence[HostPortTuple] = config.get(CONF_STATIC, [])
wemo_dispatcher = WemoDispatcher(entry)
wemo_discovery = WemoDiscovery(hass, wemo_dispatcher, static_conf)

async def async_stop_wemo(event):
async def async_stop_wemo(event: Event) -> None:
"""Shutdown Wemo subscriptions and subscription thread on exit."""
_LOGGER.debug("Shutting down WeMo event subscriptions")
await hass.async_add_executor_job(registry.stop)
Expand All @@ -142,8 +144,8 @@ class WemoDispatcher:
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize the WemoDispatcher."""
self._config_entry = config_entry
self._added_serial_numbers = set()
self._loaded_components = set()
self._added_serial_numbers: set[str] = set()
self._loaded_components: set[str] = set()

async def async_add_unique_device(
self, hass: HomeAssistant, wemo: pywemo.WeMoDevice
Expand Down Expand Up @@ -191,16 +193,16 @@ def __init__(
self,
hass: HomeAssistant,
wemo_dispatcher: WemoDispatcher,
static_config: list[tuple[[str, str | None]]],
static_config: Sequence[HostPortTuple],
) -> None:
"""Initialize the WemoDiscovery."""
self._hass = hass
self._wemo_dispatcher = wemo_dispatcher
self._stop = None
self._stop: CALLBACK_TYPE | None = None
self._scan_delay = 0
self._static_config = static_config

async def async_discover_and_schedule(self, *_) -> None:
async def async_discover_and_schedule(self, *_: tuple[Any]) -> None:
"""Periodically scan the network looking for WeMo devices."""
_LOGGER.debug("Scanning network for WeMo devices")
try:
Expand Down Expand Up @@ -229,26 +231,23 @@ def async_stop_discovery(self) -> None:
self._stop()
self._stop = None

async def discover_statics(self):
async def discover_statics(self) -> None:
"""Initialize or Re-Initialize connections to statically configured devices."""
if self._static_config:
_LOGGER.debug("Adding statically configured WeMo devices")
for device in await gather_with_concurrency(
MAX_CONCURRENCY,
*(
self._hass.async_add_executor_job(
validate_static_config, host, port
)
for host, port in self._static_config
),
):
if device:
await self._wemo_dispatcher.async_add_unique_device(
self._hass, device
)
if not self._static_config:
return
_LOGGER.debug("Adding statically configured WeMo devices")
for device in await gather_with_concurrency(
MAX_CONCURRENCY,
*(
self._hass.async_add_executor_job(validate_static_config, host, port)
for host, port in self._static_config
),
):
if device:
await self._wemo_dispatcher.async_add_unique_device(self._hass, device)


def validate_static_config(host, port):
def validate_static_config(host: str, port: int | None) -> pywemo.WeMoDevice | None:
"""Handle a static config."""
url = pywemo.setup_url_for_address(host, port)

Expand Down
16 changes: 12 additions & 4 deletions homeassistant/components/wemo/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,24 @@
from pywemo import Insight, Maker

from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN as WEMO_DOMAIN
from .entity import WemoEntity
from .wemo_device import DeviceCoordinator


async def async_setup_entry(hass, config_entry, async_add_entities):
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up WeMo binary sensors."""

async def _discovered_wemo(coordinator):
async def _discovered_wemo(coordinator: DeviceCoordinator) -> None:
"""Handle a discovered Wemo device."""
if isinstance(coordinator.wemo, Insight):
async_add_entities([InsightBinarySensor(coordinator)])
Expand All @@ -38,7 +46,7 @@ class WemoBinarySensor(WemoEntity, BinarySensorEntity):
@property
def is_on(self) -> bool:
"""Return true if the state is on. Standby is on."""
return self.wemo.get_state()
return bool(self.wemo.get_state())


class MakerBinarySensor(WemoEntity, BinarySensorEntity):
Expand All @@ -49,7 +57,7 @@ class MakerBinarySensor(WemoEntity, BinarySensorEntity):
@property
def is_on(self) -> bool:
"""Return true if the Maker's sensor is pulled low."""
return self.wemo.has_sensor and self.wemo.sensor_state == 0
return bool(self.wemo.has_sensor) and self.wemo.sensor_state == 0


class InsightBinarySensor(WemoBinarySensor):
Expand Down
3 changes: 2 additions & 1 deletion homeassistant/components/wemo/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

import pywemo

from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_flow

from . import DOMAIN


async def _async_has_devices(hass):
async def _async_has_devices(hass: HomeAssistant) -> bool:
"""Return if there are devices that can be discovered."""
return bool(await hass.async_add_executor_job(pywemo.discover_devices))

Expand Down
21 changes: 19 additions & 2 deletions homeassistant/components/wemo/device_trigger.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
"""Triggers for WeMo devices."""
from __future__ import annotations

from typing import Any

from pywemo.subscribe import EVENT_TYPE_LONG_PRESS
import voluptuous as vol

from homeassistant.components.automation import (
AutomationActionType,
AutomationTriggerInfo,
)
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.components.homeassistant.triggers import event as event_trigger
from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers.typing import ConfigType

from .const import DOMAIN as WEMO_DOMAIN, WEMO_SUBSCRIPTION_EVENT
from .wemo_device import async_get_coordinator
Expand All @@ -18,7 +28,9 @@
)


async def async_get_triggers(hass, device_id):
async def async_get_triggers(
hass: HomeAssistant, device_id: str
) -> list[dict[str, Any]]:
"""Return a list of triggers."""

wemo_trigger = {
Expand All @@ -44,7 +56,12 @@ async def async_get_triggers(hass, device_id):
return triggers


async def async_attach_trigger(hass, config, action, automation_info):
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: AutomationTriggerInfo,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
event_config = event_trigger.TRIGGER_SCHEMA(
{
Expand Down
10 changes: 5 additions & 5 deletions homeassistant/components/wemo/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def __init__(self, coordinator: DeviceCoordinator) -> None:
self._available = True

@property
def name_suffix(self):
def name_suffix(self) -> str | None:
"""Suffix to append to the WeMo device name."""
return self._name_suffix

Expand All @@ -42,26 +42,26 @@ def name(self) -> str:
"""Return the name of the device if any."""
if suffix := self.name_suffix:
return f"{self.wemo.name} {suffix}"
return self.wemo.name
return str(self.wemo.name)

@property
def available(self) -> bool:
"""Return true if the device is available."""
return super().available and self._available

@property
def unique_id_suffix(self):
def unique_id_suffix(self) -> str | None:
"""Suffix to append to the WeMo device's unique ID."""
if self._unique_id_suffix is None and self.name_suffix is not None:
return self._name_suffix.lower()
return self.name_suffix.lower()
return self._unique_id_suffix

@property
def unique_id(self) -> str:
"""Return the id of this WeMo device."""
if suffix := self.unique_id_suffix:
return f"{self.wemo.serialnumber}_{suffix}"
return self.wemo.serialnumber
return str(self.wemo.serialnumber)

@property
def device_info(self) -> DeviceInfo:
Expand Down
Loading