Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
30 changes: 18 additions & 12 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 MutableSet, Sequence

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MutableSet unused now?

@esev esev Dec 19, 2021

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. You're quick! I didn't get e92b075 pushed fast enough. :)

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,12 +47,15 @@

_LOGGER = logging.getLogger(__name__)

HostPortTuple = Tuple[str, Optional[str]]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the port really a string?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No it is not. Nice catch, thank you! I missed the cv.port() call. Fixed.


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.
"""
port: str | None = None
host, _, port = value.partition(":")

if not host:
Expand Down Expand Up @@ -82,7 +88,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 +118,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 +148,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: MutableSet[str] = set()
self._loaded_components: MutableSet[str] = set()
Comment thread
esev marked this conversation as resolved.
Outdated

async def async_add_unique_device(
self, hass: HomeAssistant, wemo: pywemo.WeMoDevice
Expand Down Expand Up @@ -191,16 +197,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,7 +235,7 @@ 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:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you reverse this condition and return, you can outdent below

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. 96d9573

_LOGGER.debug("Adding statically configured WeMo devices")
Expand All @@ -248,7 +254,7 @@ async def discover_statics(self):
)


def validate_static_config(host, port):
def validate_static_config(host: str, port: str | 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
36 changes: 23 additions & 13 deletions homeassistant/components/wemo/fan.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
"""Support for WeMo humidifier."""
from __future__ import annotations

import asyncio
from datetime import timedelta
import math
from typing import Any

import voluptuous as vol

from homeassistant.components.fan import SUPPORT_SET_SPEED, FanEntity
from homeassistant.core import callback
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_platform
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util.percentage import (
int_states_in_range,
percentage_to_ranged_value,
Expand All @@ -21,6 +26,7 @@
SERVICE_SET_HUMIDITY,
)
from .entity import WemoEntity
from .wemo_device import DeviceCoordinator

SCAN_INTERVAL = timedelta(seconds=10)
PARALLEL_UPDATES = 0
Expand Down Expand Up @@ -63,10 +69,14 @@
}


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."""
async_add_entities([WemoHumidifier(coordinator)])

Expand Down Expand Up @@ -95,7 +105,7 @@ async def _discovered_wemo(coordinator):
class WemoHumidifier(WemoEntity, FanEntity):
"""Representation of a WeMo humidifier."""

def __init__(self, coordinator):
def __init__(self, coordinator: DeviceCoordinator) -> None:
"""Initialize the WeMo switch."""
super().__init__(coordinator)
if self.wemo.fan_mode != WEMO_FAN_OFF:
Expand All @@ -104,12 +114,12 @@ def __init__(self, coordinator):
self._last_fan_on_mode = WEMO_FAN_MEDIUM

@property
def icon(self):
def icon(self) -> str:
"""Return the icon of device based on its type."""
return "mdi:water-percent"

@property
def extra_state_attributes(self):
def extra_state_attributes(self) -> dict[str, Any]:
"""Return device specific state attributes."""
return {
ATTR_CURRENT_HUMIDITY: self.wemo.current_humidity_percent,
Expand Down Expand Up @@ -145,26 +155,26 @@ def _handle_coordinator_update(self) -> None:
@property
def is_on(self) -> bool:
"""Return true if the state is on."""
return self.wemo.get_state()
return bool(self.wemo.get_state())

def turn_on(
self,
speed: str = None,
percentage: int = None,
preset_mode: str = None,
**kwargs,
speed: str | None = None,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Turn the fan on."""
self.set_percentage(percentage)

def turn_off(self, **kwargs) -> None:
def turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off."""
with self._wemo_exception_handler("turn off"):
self.wemo.set_state(WEMO_FAN_OFF)

self.schedule_update_ha_state()

def set_percentage(self, percentage: int) -> None:
def set_percentage(self, percentage: int | None) -> None:
"""Set the fan_mode of the Humidifier."""
if percentage is None:
named_speed = self._last_fan_on_mode
Expand Down
Loading