Skip to content

Commit

Permalink
Use global imports for ESPHome (home-assistant#24158)
Browse files Browse the repository at this point in the history
* Use global import for ESPHome

* Add aioesphomeapi to test requirements

aioesphomeapi is also shipped as a pure-python wheel, so this should not impact test install time
  • Loading branch information
OttoWinter authored and pvizeli committed May 29, 2019
1 parent d9c78b7 commit 015c881
Show file tree
Hide file tree
Showing 11 changed files with 69 additions and 118 deletions.
37 changes: 13 additions & 24 deletions homeassistant/components/esphome/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,35 @@
import asyncio
import logging
import math
from typing import Any, Dict, List, Optional, TYPE_CHECKING, Callable, Tuple
from typing import Any, Callable, Dict, List, Optional, Tuple

from aioesphomeapi import (
COMPONENT_TYPE_TO_INFO, APIClient, APIConnectionError, DeviceInfo,
EntityInfo, EntityState, ServiceCall, UserService, UserServiceArgType)
import attr
import voluptuous as vol

from homeassistant import const
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, \
EVENT_HOMEASSISTANT_STOP
from homeassistant.core import callback, Event, State
import homeassistant.helpers.device_registry as dr
from homeassistant.const import (
CONF_HOST, CONF_PASSWORD, CONF_PORT, EVENT_HOMEASSISTANT_STOP)
from homeassistant.core import Event, State, callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import template
from homeassistant.helpers.dispatcher import async_dispatcher_connect, \
async_dispatcher_send
import homeassistant.helpers.config_validation as cv
import homeassistant.helpers.device_registry as dr
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect, async_dispatcher_send)
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers.template import Template
from homeassistant.helpers.json import JSONEncoder
from homeassistant.helpers.storage import Store
from homeassistant.helpers.typing import HomeAssistantType, ConfigType
from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import ConfigType, HomeAssistantType

# Import config flow so that it's added to the registry
from .config_flow import EsphomeFlowHandler # noqa

if TYPE_CHECKING:
from aioesphomeapi import APIClient, EntityInfo, EntityState, DeviceInfo, \
ServiceCall, UserService

DOMAIN = 'esphome'
_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -110,10 +109,6 @@ def async_update_device_state(self, hass: HomeAssistantType) -> None:
async def async_load_from_store(self) -> Tuple[List['EntityInfo'],
List['UserService']]:
"""Load the retained data from store and return de-serialized data."""
# pylint: disable= redefined-outer-name
from aioesphomeapi import COMPONENT_TYPE_TO_INFO, DeviceInfo, \
UserService

restored = await self.store.async_load()
if restored is None:
return [], []
Expand Down Expand Up @@ -164,9 +159,6 @@ async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
async def async_setup_entry(hass: HomeAssistantType,
entry: ConfigEntry) -> bool:
"""Set up the esphome component."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import APIClient, APIConnectionError

hass.data.setdefault(DOMAIN, {})

host = entry.data[CONF_HOST]
Expand Down Expand Up @@ -306,8 +298,6 @@ async def _setup_auto_reconnect_logic(hass: HomeAssistantType,
cli: 'APIClient',
entry: ConfigEntry, host: str, on_login):
"""Set up the re-connect logic for the API client."""
from aioesphomeapi import APIConnectionError

async def try_connect(tries: int = 0, is_disconnect: bool = True) -> None:
"""Try connecting to the API client. Will retry if not successful."""
if entry.entry_id not in hass.data[DOMAIN]:
Expand Down Expand Up @@ -382,7 +372,6 @@ async def _async_setup_device_registry(hass: HomeAssistantType,
async def _register_service(hass: HomeAssistantType,
entry_data: RuntimeEntryData,
service: 'UserService'):
from aioesphomeapi import UserServiceArgType
service_name = '{}_{}'.format(entry_data.device_info.name, service.name)
schema = {}
for arg in service.args:
Expand Down
15 changes: 5 additions & 10 deletions homeassistant/components/esphome/binary_sensor.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
"""Support for ESPHome binary sensors."""
import logging
from typing import TYPE_CHECKING, Optional
from typing import Optional

from aioesphomeapi import BinarySensorInfo, BinarySensorState

from homeassistant.components.binary_sensor import BinarySensorDevice

from . import EsphomeEntity, platform_async_setup_entry

if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass, entry, async_add_entities):
"""Set up ESPHome binary sensors based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa

await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='binary_sensor',
Expand All @@ -30,11 +25,11 @@ class EsphomeBinarySensor(EsphomeEntity, BinarySensorDevice):
"""A binary sensor implementation for ESPHome."""

@property
def _static_info(self) -> 'BinarySensorInfo':
def _static_info(self) -> BinarySensorInfo:
return super()._static_info

@property
def _state(self) -> Optional['BinarySensorState']:
def _state(self) -> Optional[BinarySensorState]:
return super()._state

@property
Expand Down
16 changes: 6 additions & 10 deletions homeassistant/components/esphome/camera.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,23 @@
"""Support for ESPHome cameras."""
import asyncio
import logging
from typing import Optional, TYPE_CHECKING
from typing import Optional

from aioesphomeapi import CameraInfo, CameraState

from homeassistant.components import camera
from homeassistant.components.camera import Camera
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType
from . import EsphomeEntity, platform_async_setup_entry

if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import CameraInfo, CameraState # noqa
from . import EsphomeEntity, platform_async_setup_entry

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass: HomeAssistantType,
entry: ConfigEntry, async_add_entities) -> None:
"""Set up esphome cameras based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import CameraInfo, CameraState # noqa

await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='camera',
Expand All @@ -40,11 +36,11 @@ def __init__(self, entry_id: str, component_key: str, key: int):
self._image_cond = asyncio.Condition()

@property
def _static_info(self) -> 'CameraInfo':
def _static_info(self) -> CameraInfo:
return super()._static_info

@property
def _state(self) -> Optional['CameraState']:
def _state(self) -> Optional[CameraState]:
return super()._state

async def _on_update(self) -> None:
Expand Down
22 changes: 8 additions & 14 deletions homeassistant/components/esphome/climate.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Support for ESPHome climate devices."""
import logging
from typing import TYPE_CHECKING, List, Optional
from typing import List, Optional

from aioesphomeapi import ClimateInfo, ClimateMode, ClimateState

from homeassistant.components.climate import ClimateDevice
from homeassistant.components.climate.const import (
Expand All @@ -12,21 +14,15 @@
ATTR_TEMPERATURE, PRECISION_HALVES, PRECISION_TENTHS, PRECISION_WHOLE,
STATE_OFF, TEMP_CELSIUS)

from . import EsphomeEntity, platform_async_setup_entry, \
esphome_state_property, esphome_map_enum

if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import ClimateInfo, ClimateState, ClimateMode # noqa
from . import (
EsphomeEntity, esphome_map_enum, esphome_state_property,
platform_async_setup_entry)

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass, entry, async_add_entities):
"""Set up ESPHome climate devices based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import ClimateInfo, ClimateState # noqa

await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='climate',
Expand All @@ -37,8 +33,6 @@ async def async_setup_entry(hass, entry, async_add_entities):

@esphome_map_enum
def _climate_modes():
# pylint: disable=redefined-outer-name
from aioesphomeapi import ClimateMode # noqa
return {
ClimateMode.OFF: STATE_OFF,
ClimateMode.AUTO: STATE_AUTO,
Expand All @@ -51,11 +45,11 @@ class EsphomeClimateDevice(EsphomeEntity, ClimateDevice):
"""A climate implementation for ESPHome."""

@property
def _static_info(self) -> 'ClimateInfo':
def _static_info(self) -> ClimateInfo:
return super()._static_info

@property
def _state(self) -> Optional['ClimateState']:
def _state(self) -> Optional[ClimateState]:
return super()._state

@property
Expand Down
17 changes: 6 additions & 11 deletions homeassistant/components/esphome/cover.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Support for ESPHome covers."""
import logging
from typing import TYPE_CHECKING, Optional
from typing import Optional

from aioesphomeapi import CoverInfo, CoverState

from homeassistant.components.cover import (
ATTR_POSITION, ATTR_TILT_POSITION, SUPPORT_CLOSE, SUPPORT_CLOSE_TILT,
Expand All @@ -9,21 +11,14 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType

from . import EsphomeEntity, platform_async_setup_entry, esphome_state_property

if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import CoverInfo, CoverState # noqa
from . import EsphomeEntity, esphome_state_property, platform_async_setup_entry

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass: HomeAssistantType,
entry: ConfigEntry, async_add_entities) -> None:
"""Set up ESPHome covers based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import CoverInfo, CoverState # noqa

await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='cover',
Expand All @@ -36,7 +31,7 @@ class EsphomeCover(EsphomeEntity, CoverDevice):
"""A cover implementation for ESPHome."""

@property
def _static_info(self) -> 'CoverInfo':
def _static_info(self) -> CoverInfo:
return super()._static_info

@property
Expand All @@ -61,7 +56,7 @@ def assumed_state(self) -> bool:
return self._static_info.assumed_state

@property
def _state(self) -> Optional['CoverState']:
def _state(self) -> Optional[CoverState]:
return super()._state

@esphome_state_property
Expand Down
22 changes: 8 additions & 14 deletions homeassistant/components/esphome/fan.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,25 @@
"""Support for ESPHome fans."""
import logging
from typing import TYPE_CHECKING, List, Optional
from typing import List, Optional

from aioesphomeapi import FanInfo, FanSpeed, FanState

from homeassistant.components.fan import (
SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM, SPEED_OFF, SUPPORT_OSCILLATE,
SUPPORT_SET_SPEED, FanEntity)
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType

from . import EsphomeEntity, platform_async_setup_entry, \
esphome_state_property, esphome_map_enum

if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import FanInfo, FanState, FanSpeed # noqa
from . import (
EsphomeEntity, esphome_map_enum, esphome_state_property,
platform_async_setup_entry)

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass: HomeAssistantType,
entry: ConfigEntry, async_add_entities) -> None:
"""Set up ESPHome fans based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import FanInfo, FanState # noqa

await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='fan',
Expand All @@ -34,8 +30,6 @@ async def async_setup_entry(hass: HomeAssistantType,

@esphome_map_enum
def _fan_speeds():
# pylint: disable=redefined-outer-name
from aioesphomeapi import FanSpeed # noqa
return {
FanSpeed.LOW: SPEED_LOW,
FanSpeed.MEDIUM: SPEED_MEDIUM,
Expand All @@ -47,11 +41,11 @@ class EsphomeFan(EsphomeEntity, FanEntity):
"""A fan implementation for ESPHome."""

@property
def _static_info(self) -> 'FanInfo':
def _static_info(self) -> FanInfo:
return super()._static_info

@property
def _state(self) -> Optional['FanState']:
def _state(self) -> Optional[FanState]:
return super()._state

async def async_set_speed(self, speed: str) -> None:
Expand Down
17 changes: 6 additions & 11 deletions homeassistant/components/esphome/light.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Support for ESPHome lights."""
import logging
from typing import TYPE_CHECKING, List, Optional, Tuple
from typing import List, Optional, Tuple

from aioesphomeapi import LightInfo, LightState

from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_HS_COLOR,
Expand All @@ -11,11 +13,7 @@
from homeassistant.helpers.typing import HomeAssistantType
import homeassistant.util.color as color_util

from . import EsphomeEntity, platform_async_setup_entry, esphome_state_property

if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import LightInfo, LightState # noqa
from . import EsphomeEntity, esphome_state_property, platform_async_setup_entry

_LOGGER = logging.getLogger(__name__)

Expand All @@ -29,9 +27,6 @@
async def async_setup_entry(hass: HomeAssistantType,
entry: ConfigEntry, async_add_entities) -> None:
"""Set up ESPHome lights based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import LightInfo, LightState # noqa

await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='light',
Expand All @@ -44,11 +39,11 @@ class EsphomeLight(EsphomeEntity, Light):
"""A switch implementation for ESPHome."""

@property
def _static_info(self) -> 'LightInfo':
def _static_info(self) -> LightInfo:
return super()._static_info

@property
def _state(self) -> Optional['LightState']:
def _state(self) -> Optional[LightState]:
return super()._state

@esphome_state_property
Expand Down
Loading

0 comments on commit 015c881

Please sign in to comment.