Skip to content

Commit

Permalink
Async syntax 7, switch & tts & vacuum (#17021)
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p authored and balloob committed Oct 1, 2018
1 parent 9aaf11d commit 121dba6
Show file tree
Hide file tree
Showing 20 changed files with 163 additions and 253 deletions.
4 changes: 1 addition & 3 deletions homeassistant/components/switch/ads.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
For more details about this platform, please refer to the documentation.
https://home-assistant.io/components/switch.ads/
"""
import asyncio
import logging

import voluptuous as vol
Expand Down Expand Up @@ -47,8 +46,7 @@ def __init__(self, ads_hub, name, ads_var):
self._name = name
self.ads_var = ads_var

@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register device notification."""
def update(name, value):
"""Handle device notification."""
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/switch/amcrest.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.amcrest/
"""
import asyncio
import logging

from homeassistant.components.amcrest import DATA_AMCREST, SWITCHES
Expand All @@ -17,9 +16,8 @@
DEPENDENCIES = ['amcrest']


@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the IP Amcrest camera switch platform."""
if discovery_info is None:
return
Expand Down
31 changes: 13 additions & 18 deletions homeassistant/components/switch/android_ip_webcam.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.android_ip_webcam/
"""
import asyncio

from homeassistant.components.switch import SwitchDevice
from homeassistant.components.android_ip_webcam import (
Expand All @@ -14,9 +13,8 @@
DEPENDENCIES = ['android_ip_webcam']


@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the IP Webcam switch platform."""
if discovery_info is None:
return
Expand Down Expand Up @@ -51,8 +49,7 @@ def name(self):
"""Return the name of the node."""
return self._name

@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Get the updated status of the switch."""
self._state = bool(self._ipcam.current_settings.get(self._setting))

Expand All @@ -61,31 +58,29 @@ def is_on(self):
"""Return the boolean response if the node is on."""
return self._state

@asyncio.coroutine
def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs):
"""Turn device on."""
if self._setting == 'torch':
yield from self._ipcam.torch(activate=True)
await self._ipcam.torch(activate=True)
elif self._setting == 'focus':
yield from self._ipcam.focus(activate=True)
await self._ipcam.focus(activate=True)
elif self._setting == 'video_recording':
yield from self._ipcam.record(record=True)
await self._ipcam.record(record=True)
else:
yield from self._ipcam.change_setting(self._setting, True)
await self._ipcam.change_setting(self._setting, True)
self._state = True
self.async_schedule_update_ha_state()

@asyncio.coroutine
def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Turn device off."""
if self._setting == 'torch':
yield from self._ipcam.torch(activate=False)
await self._ipcam.torch(activate=False)
elif self._setting == 'focus':
yield from self._ipcam.focus(activate=False)
await self._ipcam.focus(activate=False)
elif self._setting == 'video_recording':
yield from self._ipcam.record(record=False)
await self._ipcam.record(record=False)
else:
yield from self._ipcam.change_setting(self._setting, False)
await self._ipcam.change_setting(self._setting, False)
self._state = False
self.async_schedule_update_ha_state()

Expand Down
18 changes: 8 additions & 10 deletions homeassistant/components/switch/broadlink.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,24 +80,23 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
config.get(CONF_MAC).encode().replace(b':', b''))
switch_type = config.get(CONF_TYPE)

@asyncio.coroutine
def _learn_command(call):
async def _learn_command(call):
"""Handle a learn command."""
try:
auth = yield from hass.async_add_job(broadlink_device.auth)
auth = await hass.async_add_job(broadlink_device.auth)
except socket.timeout:
_LOGGER.error("Failed to connect to device, timeout")
return
if not auth:
_LOGGER.error("Failed to connect to device")
return

yield from hass.async_add_job(broadlink_device.enter_learning)
await hass.async_add_job(broadlink_device.enter_learning)

_LOGGER.info("Press the key you want Home Assistant to learn")
start_time = utcnow()
while (utcnow() - start_time) < timedelta(seconds=20):
packet = yield from hass.async_add_job(
packet = await hass.async_add_job(
broadlink_device.check_data)
if packet:
log_msg = "Received packet is: {}".\
Expand All @@ -106,13 +105,12 @@ def _learn_command(call):
hass.components.persistent_notification.async_create(
log_msg, title='Broadlink switch')
return
yield from asyncio.sleep(1, loop=hass.loop)
await asyncio.sleep(1, loop=hass.loop)
_LOGGER.error("Did not received any signal")
hass.components.persistent_notification.async_create(
"Did not received any signal", title='Broadlink switch')

@asyncio.coroutine
def _send_packet(call):
async def _send_packet(call):
"""Send a packet."""
packets = call.data.get('packet', [])
for packet in packets:
Expand All @@ -122,12 +120,12 @@ def _send_packet(call):
if extra > 0:
packet = packet + ('=' * (4 - extra))
payload = b64decode(packet)
yield from hass.async_add_job(
await hass.async_add_job(
broadlink_device.send_data, payload)
break
except (socket.timeout, ValueError):
try:
yield from hass.async_add_job(
await hass.async_add_job(
broadlink_device.auth)
except socket.timeout:
if retry == DEFAULT_RETRY-1:
Expand Down
30 changes: 13 additions & 17 deletions homeassistant/components/switch/hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@
})


@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up Hook by getting the access token and list of actions."""
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
Expand All @@ -43,14 +42,14 @@ def async_setup_platform(hass, config, async_add_entities,
if username is not None and password is not None:
try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = yield from websession.post(
response = await websession.post(
'{}{}'.format(HOOK_ENDPOINT, 'user/login'),
data={
'username': username,
'password': password})
# The Hook API returns JSON but calls it 'text/html'. Setting
# content_type=None disables aiohttp's content-type validation.
data = yield from response.json(content_type=None)
data = await response.json(content_type=None)
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed authentication API call: %s", error)
return False
Expand All @@ -63,10 +62,10 @@ def async_setup_platform(hass, config, async_add_entities,

try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = yield from websession.get(
response = await websession.get(
'{}{}'.format(HOOK_ENDPOINT, 'device'),
params={"token": token})
data = yield from response.json(content_type=None)
data = await response.json(content_type=None)
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed getting devices: %s", error)
return False
Expand Down Expand Up @@ -104,16 +103,15 @@ def is_on(self):
"""Return true if device is on."""
return self._state

@asyncio.coroutine
def _send(self, url):
async def _send(self, url):
"""Send the url to the Hook API."""
try:
_LOGGER.debug("Sending: %s", url)
websession = async_get_clientsession(self.hass)
with async_timeout.timeout(TIMEOUT, loop=self.hass.loop):
response = yield from websession.get(
response = await websession.get(
url, params={"token": self._token})
data = yield from response.json(content_type=None)
data = await response.json(content_type=None)

except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed setting state: %s", error)
Expand All @@ -122,21 +120,19 @@ def _send(self, url):
_LOGGER.debug("Got: %s", data)
return data['return_value'] == '1'

@asyncio.coroutine
def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs):
"""Turn the device on asynchronously."""
_LOGGER.debug("Turning on: %s", self._name)
url = '{}{}{}{}'.format(
HOOK_ENDPOINT, 'device/trigger/', self._id, '/On')
success = yield from self._send(url)
success = await self._send(url)
self._state = success

@asyncio.coroutine
def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Turn the device off asynchronously."""
_LOGGER.debug("Turning off: %s", self._name)
url = '{}{}{}{}'.format(
HOOK_ENDPOINT, 'device/trigger/', self._id, '/Off')
success = yield from self._send(url)
success = await self._send(url)
# If it wasn't successful, keep state as true
self._state = not success
18 changes: 6 additions & 12 deletions homeassistant/components/switch/insteon.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/switch.insteon/
"""
import asyncio
import logging

from homeassistant.components.insteon import InsteonEntity
Expand All @@ -15,9 +14,8 @@
_LOGGER = logging.getLogger(__name__)


@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the INSTEON device class for the hass platform."""
insteon_modem = hass.data['insteon'].get('modem')

Expand Down Expand Up @@ -48,13 +46,11 @@ def is_on(self):
"""Return the boolean response if the node is on."""
return bool(self._insteon_device_state.value)

@asyncio.coroutine
def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs):
"""Turn device on."""
self._insteon_device_state.on()

@asyncio.coroutine
def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Turn device off."""
self._insteon_device_state.off()

Expand All @@ -67,12 +63,10 @@ def is_on(self):
"""Return the boolean response if the node is on."""
return bool(self._insteon_device_state.value)

@asyncio.coroutine
def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs):
"""Turn device on."""
self._insteon_device_state.open()

@asyncio.coroutine
def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Turn device off."""
self._insteon_device_state.close()
15 changes: 5 additions & 10 deletions homeassistant/components/switch/lutron_caseta.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sitch.lutron_caseta/
"""
import asyncio
import logging

from homeassistant.components.lutron_caseta import (
Expand All @@ -16,9 +15,8 @@
DEPENDENCIES = ['lutron_caseta']


@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up Lutron switch."""
devs = []
bridge = hass.data[LUTRON_CASETA_SMARTBRIDGE]
Expand All @@ -35,13 +33,11 @@ def async_setup_platform(hass, config, async_add_entities,
class LutronCasetaLight(LutronCasetaDevice, SwitchDevice):
"""Representation of a Lutron Caseta switch."""

@asyncio.coroutine
def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs):
"""Turn the switch on."""
self._smartbridge.turn_on(self._device_id)

@asyncio.coroutine
def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Turn the switch off."""
self._smartbridge.turn_off(self._device_id)

Expand All @@ -50,8 +46,7 @@ def is_on(self):
"""Return true if device is on."""
return self._state["current_state"] > 0

@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Update when forcing a refresh of the device."""
self._state = self._smartbridge.get_device_by_id(self._device_id)
_LOGGER.debug(self._state)
6 changes: 2 additions & 4 deletions homeassistant/components/switch/pilight.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.pilight/
"""
import asyncio
import logging

import voluptuous as vol
Expand Down Expand Up @@ -122,10 +121,9 @@ def __init__(self, hass, name, code_on, code_off, code_on_receive,
if any(self._code_on_receive) or any(self._code_off_receive):
hass.bus.listen(pilight.EVENT, self._handle_code)

@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Call when entity about to be added to hass."""
state = yield from async_get_last_state(self._hass, self.entity_id)
state = await async_get_last_state(self._hass, self.entity_id)
if state:
self._state = state.state == STATE_ON

Expand Down
Loading

0 comments on commit 121dba6

Please sign in to comment.