Async syntax 7, switch & tts & vacuum (#17021)

This commit is contained in:
cdce8p 2018-10-01 08:55:00 +02:00 committed by Paulus Schoutsen
parent 9aaf11de8c
commit 121dba659c
20 changed files with 163 additions and 253 deletions

View File

@ -4,7 +4,6 @@ Support for ADS switch platform.
For more details about this platform, please refer to the documentation. For more details about this platform, please refer to the documentation.
https://home-assistant.io/components/switch.ads/ https://home-assistant.io/components/switch.ads/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -47,8 +46,7 @@ class AdsSwitch(ToggleEntity):
self._name = name self._name = name
self.ads_var = ads_var self.ads_var = ads_var
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register device notification.""" """Register device notification."""
def update(name, value): def update(name, value):
"""Handle device notification.""" """Handle device notification."""

View File

@ -4,7 +4,6 @@ Support for toggling Amcrest IP camera settings.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.amcrest/ https://home-assistant.io/components/switch.amcrest/
""" """
import asyncio
import logging import logging
from homeassistant.components.amcrest import DATA_AMCREST, SWITCHES from homeassistant.components.amcrest import DATA_AMCREST, SWITCHES
@ -17,9 +16,8 @@ _LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['amcrest'] DEPENDENCIES = ['amcrest']
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the IP Amcrest camera switch platform.""" """Set up the IP Amcrest camera switch platform."""
if discovery_info is None: if discovery_info is None:
return return

View File

@ -4,7 +4,6 @@ Support for IP Webcam settings.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.android_ip_webcam/ https://home-assistant.io/components/switch.android_ip_webcam/
""" """
import asyncio
from homeassistant.components.switch import SwitchDevice from homeassistant.components.switch import SwitchDevice
from homeassistant.components.android_ip_webcam import ( from homeassistant.components.android_ip_webcam import (
@ -14,9 +13,8 @@ from homeassistant.components.android_ip_webcam import (
DEPENDENCIES = ['android_ip_webcam'] DEPENDENCIES = ['android_ip_webcam']
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the IP Webcam switch platform.""" """Set up the IP Webcam switch platform."""
if discovery_info is None: if discovery_info is None:
return return
@ -51,8 +49,7 @@ class IPWebcamSettingsSwitch(AndroidIPCamEntity, SwitchDevice):
"""Return the name of the node.""" """Return the name of the node."""
return self._name return self._name
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the updated status of the switch.""" """Get the updated status of the switch."""
self._state = bool(self._ipcam.current_settings.get(self._setting)) self._state = bool(self._ipcam.current_settings.get(self._setting))
@ -61,31 +58,29 @@ class IPWebcamSettingsSwitch(AndroidIPCamEntity, SwitchDevice):
"""Return the boolean response if the node is on.""" """Return the boolean response if the node is on."""
return self._state return self._state
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn device on.""" """Turn device on."""
if self._setting == 'torch': if self._setting == 'torch':
yield from self._ipcam.torch(activate=True) await self._ipcam.torch(activate=True)
elif self._setting == 'focus': elif self._setting == 'focus':
yield from self._ipcam.focus(activate=True) await self._ipcam.focus(activate=True)
elif self._setting == 'video_recording': elif self._setting == 'video_recording':
yield from self._ipcam.record(record=True) await self._ipcam.record(record=True)
else: else:
yield from self._ipcam.change_setting(self._setting, True) await self._ipcam.change_setting(self._setting, True)
self._state = True self._state = True
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn device off.""" """Turn device off."""
if self._setting == 'torch': if self._setting == 'torch':
yield from self._ipcam.torch(activate=False) await self._ipcam.torch(activate=False)
elif self._setting == 'focus': elif self._setting == 'focus':
yield from self._ipcam.focus(activate=False) await self._ipcam.focus(activate=False)
elif self._setting == 'video_recording': elif self._setting == 'video_recording':
yield from self._ipcam.record(record=False) await self._ipcam.record(record=False)
else: else:
yield from self._ipcam.change_setting(self._setting, False) await self._ipcam.change_setting(self._setting, False)
self._state = False self._state = False
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()

View File

@ -80,11 +80,10 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
config.get(CONF_MAC).encode().replace(b':', b'')) config.get(CONF_MAC).encode().replace(b':', b''))
switch_type = config.get(CONF_TYPE) switch_type = config.get(CONF_TYPE)
@asyncio.coroutine async def _learn_command(call):
def _learn_command(call):
"""Handle a learn command.""" """Handle a learn command."""
try: try:
auth = yield from hass.async_add_job(broadlink_device.auth) auth = await hass.async_add_job(broadlink_device.auth)
except socket.timeout: except socket.timeout:
_LOGGER.error("Failed to connect to device, timeout") _LOGGER.error("Failed to connect to device, timeout")
return return
@ -92,12 +91,12 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
_LOGGER.error("Failed to connect to device") _LOGGER.error("Failed to connect to device")
return 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") _LOGGER.info("Press the key you want Home Assistant to learn")
start_time = utcnow() start_time = utcnow()
while (utcnow() - start_time) < timedelta(seconds=20): while (utcnow() - start_time) < timedelta(seconds=20):
packet = yield from hass.async_add_job( packet = await hass.async_add_job(
broadlink_device.check_data) broadlink_device.check_data)
if packet: if packet:
log_msg = "Received packet is: {}".\ log_msg = "Received packet is: {}".\
@ -106,13 +105,12 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
hass.components.persistent_notification.async_create( hass.components.persistent_notification.async_create(
log_msg, title='Broadlink switch') log_msg, title='Broadlink switch')
return return
yield from asyncio.sleep(1, loop=hass.loop) await asyncio.sleep(1, loop=hass.loop)
_LOGGER.error("Did not received any signal") _LOGGER.error("Did not received any signal")
hass.components.persistent_notification.async_create( hass.components.persistent_notification.async_create(
"Did not received any signal", title='Broadlink switch') "Did not received any signal", title='Broadlink switch')
@asyncio.coroutine async def _send_packet(call):
def _send_packet(call):
"""Send a packet.""" """Send a packet."""
packets = call.data.get('packet', []) packets = call.data.get('packet', [])
for packet in packets: for packet in packets:
@ -122,12 +120,12 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
if extra > 0: if extra > 0:
packet = packet + ('=' * (4 - extra)) packet = packet + ('=' * (4 - extra))
payload = b64decode(packet) payload = b64decode(packet)
yield from hass.async_add_job( await hass.async_add_job(
broadlink_device.send_data, payload) broadlink_device.send_data, payload)
break break
except (socket.timeout, ValueError): except (socket.timeout, ValueError):
try: try:
yield from hass.async_add_job( await hass.async_add_job(
broadlink_device.auth) broadlink_device.auth)
except socket.timeout: except socket.timeout:
if retry == DEFAULT_RETRY-1: if retry == DEFAULT_RETRY-1:

View File

@ -31,9 +31,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up Hook by getting the access token and list of actions.""" """Set up Hook by getting the access token and list of actions."""
username = config.get(CONF_USERNAME) username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD) password = config.get(CONF_PASSWORD)
@ -43,14 +42,14 @@ def async_setup_platform(hass, config, async_add_entities,
if username is not None and password is not None: if username is not None and password is not None:
try: try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop): with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = yield from websession.post( response = await websession.post(
'{}{}'.format(HOOK_ENDPOINT, 'user/login'), '{}{}'.format(HOOK_ENDPOINT, 'user/login'),
data={ data={
'username': username, 'username': username,
'password': password}) 'password': password})
# The Hook API returns JSON but calls it 'text/html'. Setting # The Hook API returns JSON but calls it 'text/html'. Setting
# content_type=None disables aiohttp's content-type validation. # 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: except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed authentication API call: %s", error) _LOGGER.error("Failed authentication API call: %s", error)
return False return False
@ -63,10 +62,10 @@ def async_setup_platform(hass, config, async_add_entities,
try: try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop): with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = yield from websession.get( response = await websession.get(
'{}{}'.format(HOOK_ENDPOINT, 'device'), '{}{}'.format(HOOK_ENDPOINT, 'device'),
params={"token": token}) 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: except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed getting devices: %s", error) _LOGGER.error("Failed getting devices: %s", error)
return False return False
@ -104,16 +103,15 @@ class HookSmartHome(SwitchDevice):
"""Return true if device is on.""" """Return true if device is on."""
return self._state return self._state
@asyncio.coroutine async def _send(self, url):
def _send(self, url):
"""Send the url to the Hook API.""" """Send the url to the Hook API."""
try: try:
_LOGGER.debug("Sending: %s", url) _LOGGER.debug("Sending: %s", url)
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
with async_timeout.timeout(TIMEOUT, loop=self.hass.loop): with async_timeout.timeout(TIMEOUT, loop=self.hass.loop):
response = yield from websession.get( response = await websession.get(
url, params={"token": self._token}) 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: except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed setting state: %s", error) _LOGGER.error("Failed setting state: %s", error)
@ -122,21 +120,19 @@ class HookSmartHome(SwitchDevice):
_LOGGER.debug("Got: %s", data) _LOGGER.debug("Got: %s", data)
return data['return_value'] == '1' return data['return_value'] == '1'
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the device on asynchronously.""" """Turn the device on asynchronously."""
_LOGGER.debug("Turning on: %s", self._name) _LOGGER.debug("Turning on: %s", self._name)
url = '{}{}{}{}'.format( url = '{}{}{}{}'.format(
HOOK_ENDPOINT, 'device/trigger/', self._id, '/On') HOOK_ENDPOINT, 'device/trigger/', self._id, '/On')
success = yield from self._send(url) success = await self._send(url)
self._state = success self._state = success
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn the device off asynchronously.""" """Turn the device off asynchronously."""
_LOGGER.debug("Turning off: %s", self._name) _LOGGER.debug("Turning off: %s", self._name)
url = '{}{}{}{}'.format( url = '{}{}{}{}'.format(
HOOK_ENDPOINT, 'device/trigger/', self._id, '/Off') 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 # If it wasn't successful, keep state as true
self._state = not success self._state = not success

View File

@ -4,7 +4,6 @@ Support for INSTEON dimmers via PowerLinc Modem.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/switch.insteon/ https://home-assistant.io/components/switch.insteon/
""" """
import asyncio
import logging import logging
from homeassistant.components.insteon import InsteonEntity from homeassistant.components.insteon import InsteonEntity
@ -15,9 +14,8 @@ DEPENDENCIES = ['insteon']
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the INSTEON device class for the hass platform.""" """Set up the INSTEON device class for the hass platform."""
insteon_modem = hass.data['insteon'].get('modem') insteon_modem = hass.data['insteon'].get('modem')
@ -48,13 +46,11 @@ class InsteonSwitchDevice(InsteonEntity, SwitchDevice):
"""Return the boolean response if the node is on.""" """Return the boolean response if the node is on."""
return bool(self._insteon_device_state.value) return bool(self._insteon_device_state.value)
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn device on.""" """Turn device on."""
self._insteon_device_state.on() self._insteon_device_state.on()
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn device off.""" """Turn device off."""
self._insteon_device_state.off() self._insteon_device_state.off()
@ -67,12 +63,10 @@ class InsteonOpenClosedDevice(InsteonEntity, SwitchDevice):
"""Return the boolean response if the node is on.""" """Return the boolean response if the node is on."""
return bool(self._insteon_device_state.value) return bool(self._insteon_device_state.value)
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn device on.""" """Turn device on."""
self._insteon_device_state.open() self._insteon_device_state.open()
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn device off.""" """Turn device off."""
self._insteon_device_state.close() self._insteon_device_state.close()

View File

@ -4,7 +4,6 @@ Support for Lutron Caseta switches.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sitch.lutron_caseta/ https://home-assistant.io/components/sitch.lutron_caseta/
""" """
import asyncio
import logging import logging
from homeassistant.components.lutron_caseta import ( from homeassistant.components.lutron_caseta import (
@ -16,9 +15,8 @@ _LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['lutron_caseta'] DEPENDENCIES = ['lutron_caseta']
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up Lutron switch.""" """Set up Lutron switch."""
devs = [] devs = []
bridge = hass.data[LUTRON_CASETA_SMARTBRIDGE] bridge = hass.data[LUTRON_CASETA_SMARTBRIDGE]
@ -35,13 +33,11 @@ def async_setup_platform(hass, config, async_add_entities,
class LutronCasetaLight(LutronCasetaDevice, SwitchDevice): class LutronCasetaLight(LutronCasetaDevice, SwitchDevice):
"""Representation of a Lutron Caseta switch.""" """Representation of a Lutron Caseta switch."""
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the switch on.""" """Turn the switch on."""
self._smartbridge.turn_on(self._device_id) self._smartbridge.turn_on(self._device_id)
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn the switch off.""" """Turn the switch off."""
self._smartbridge.turn_off(self._device_id) self._smartbridge.turn_off(self._device_id)
@ -50,8 +46,7 @@ class LutronCasetaLight(LutronCasetaDevice, SwitchDevice):
"""Return true if device is on.""" """Return true if device is on."""
return self._state["current_state"] > 0 return self._state["current_state"] > 0
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Update when forcing a refresh of the device.""" """Update when forcing a refresh of the device."""
self._state = self._smartbridge.get_device_by_id(self._device_id) self._state = self._smartbridge.get_device_by_id(self._device_id)
_LOGGER.debug(self._state) _LOGGER.debug(self._state)

View File

@ -4,7 +4,6 @@ Support for switching devices via Pilight to on and off.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.pilight/ https://home-assistant.io/components/switch.pilight/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -122,10 +121,9 @@ class PilightSwitch(SwitchDevice):
if any(self._code_on_receive) or any(self._code_off_receive): if any(self._code_on_receive) or any(self._code_off_receive):
hass.bus.listen(pilight.EVENT, self._handle_code) hass.bus.listen(pilight.EVENT, self._handle_code)
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Call when entity about to be added to hass.""" """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: if state:
self._state = state.state == STATE_ON self._state = state.state == STATE_ON

View File

@ -47,9 +47,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the RESTful switch.""" """Set up the RESTful switch."""
body_off = config.get(CONF_BODY_OFF) body_off = config.get(CONF_BODY_OFF)
body_on = config.get(CONF_BODY_ON) body_on = config.get(CONF_BODY_ON)
@ -77,7 +76,7 @@ def async_setup_platform(hass, config, async_add_entities,
switch = RestSwitch(name, resource, method, headers, auth, body_on, switch = RestSwitch(name, resource, method, headers, auth, body_on,
body_off, is_on_template, timeout) body_off, is_on_template, timeout)
req = yield from switch.get_device_state(hass) req = await switch.get_device_state(hass)
if req.status >= 400: if req.status >= 400:
_LOGGER.error("Got non-ok response from resource: %s", req.status) _LOGGER.error("Got non-ok response from resource: %s", req.status)
else: else:
@ -116,13 +115,12 @@ class RestSwitch(SwitchDevice):
"""Return true if device is on.""" """Return true if device is on."""
return self._state return self._state
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the device on.""" """Turn the device on."""
body_on_t = self._body_on.async_render() body_on_t = self._body_on.async_render()
try: try:
req = yield from self.set_device_state(body_on_t) req = await self.set_device_state(body_on_t)
if req.status == 200: if req.status == 200:
self._state = True self._state = True
@ -133,13 +131,12 @@ class RestSwitch(SwitchDevice):
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Error while turn on %s", self._resource) _LOGGER.error("Error while turn on %s", self._resource)
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn the device off.""" """Turn the device off."""
body_off_t = self._body_off.async_render() body_off_t = self._body_off.async_render()
try: try:
req = yield from self.set_device_state(body_off_t) req = await self.set_device_state(body_off_t)
if req.status == 200: if req.status == 200:
self._state = False self._state = False
else: else:
@ -149,33 +146,30 @@ class RestSwitch(SwitchDevice):
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Error while turn off %s", self._resource) _LOGGER.error("Error while turn off %s", self._resource)
@asyncio.coroutine async def set_device_state(self, body):
def set_device_state(self, body):
"""Send a state update to the device.""" """Send a state update to the device."""
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
with async_timeout.timeout(self._timeout, loop=self.hass.loop): with async_timeout.timeout(self._timeout, loop=self.hass.loop):
req = yield from getattr(websession, self._method)( req = await getattr(websession, self._method)(
self._resource, auth=self._auth, data=bytes(body, 'utf-8'), self._resource, auth=self._auth, data=bytes(body, 'utf-8'),
headers=self._headers) headers=self._headers)
return req return req
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the current state, catching errors.""" """Get the current state, catching errors."""
try: try:
yield from self.get_device_state(self.hass) await self.get_device_state(self.hass)
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.exception("Error while fetch data.") _LOGGER.exception("Error while fetch data.")
@asyncio.coroutine async def get_device_state(self, hass):
def get_device_state(self, hass):
"""Get the latest data from REST API and update the state.""" """Get the latest data from REST API and update the state."""
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
with async_timeout.timeout(self._timeout, loop=hass.loop): with async_timeout.timeout(self._timeout, loop=hass.loop):
req = yield from websession.get(self._resource, auth=self._auth) req = await websession.get(self._resource, auth=self._auth)
text = yield from req.text() text = await req.text()
if self._is_on_template is not None: if self._is_on_template is not None:
text = self._is_on_template.async_render_with_possible_json_value( text = self._is_on_template.async_render_with_possible_json_value(

View File

@ -4,7 +4,6 @@ Support for Rflink switches.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.rflink/ https://home-assistant.io/components/switch.rflink/
""" """
import asyncio
import logging import logging
from homeassistant.components.rflink import ( from homeassistant.components.rflink import (
@ -85,9 +84,8 @@ def devices_from_config(domain_config, hass=None):
return devices return devices
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the Rflink platform.""" """Set up the Rflink platform."""
async_add_entities(devices_from_config(config, hass)) async_add_entities(devices_from_config(config, hass))

View File

@ -4,7 +4,6 @@ Support for switches which integrates with other components.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.template/ https://home-assistant.io/components/switch.template/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -43,9 +42,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the Template switch.""" """Set up the Template switch."""
switches = [] switches = []
@ -103,8 +101,7 @@ class SwitchTemplate(SwitchDevice):
self._entity_picture = None self._entity_picture = None
self._entities = entity_ids self._entities = entity_ids
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
@callback @callback
def template_switch_state_listener(entity, old_state, new_state): def template_switch_state_listener(entity, old_state, new_state):
@ -152,18 +149,15 @@ class SwitchTemplate(SwitchDevice):
"""Return the entity_picture to use in the frontend, if any.""" """Return the entity_picture to use in the frontend, if any."""
return self._entity_picture return self._entity_picture
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Fire the on action.""" """Fire the on action."""
yield from self._on_script.async_run() await self._on_script.async_run()
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Fire the off action.""" """Fire the off action."""
yield from self._off_script.async_run() await self._off_script.async_run()
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Update the state from the template.""" """Update the state from the template."""
try: try:
state = self._template.async_render().lower() state = self._template.async_render().lower()

View File

@ -4,7 +4,6 @@ Support for Wink switches.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.wink/ https://home-assistant.io/components/switch.wink/
""" """
import asyncio
import logging import logging
from homeassistant.components.wink import DOMAIN, WinkDevice from homeassistant.components.wink import DOMAIN, WinkDevice
@ -40,8 +39,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
class WinkToggleDevice(WinkDevice, ToggleEntity): class WinkToggleDevice(WinkDevice, ToggleEntity):
"""Representation of a Wink toggle device.""" """Representation of a Wink toggle device."""
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Call when entity is added to hass.""" """Call when entity is added to hass."""
self.hass.data[DOMAIN]['entities']['switch'].append(self) self.hass.data[DOMAIN]['entities']['switch'].append(self)

View File

@ -45,8 +45,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_get_engine(hass, config):
def async_get_engine(hass, config):
"""Set up MaryTTS speech component.""" """Set up MaryTTS speech component."""
return MaryTTSProvider(hass, config) return MaryTTSProvider(hass, config)
@ -74,8 +73,7 @@ class MaryTTSProvider(Provider):
"""Return list of supported languages.""" """Return list of supported languages."""
return SUPPORT_LANGUAGES return SUPPORT_LANGUAGES
@asyncio.coroutine async def async_get_tts_audio(self, message, language, options=None):
def async_get_tts_audio(self, message, language, options=None):
"""Load TTS from MaryTTS.""" """Load TTS from MaryTTS."""
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
@ -98,13 +96,13 @@ class MaryTTSProvider(Provider):
'LOCALE': actual_language 'LOCALE': actual_language
} }
request = yield from websession.get(url, params=url_param) request = await websession.get(url, params=url_param)
if request.status != 200: if request.status != 200:
_LOGGER.error("Error %d on load url %s", _LOGGER.error("Error %d on load url %s",
request.status, request.url) request.status, request.url)
return (None, None) return (None, None)
data = yield from request.read() data = await request.read()
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout for MaryTTS API") _LOGGER.error("Timeout for MaryTTS API")

View File

@ -80,8 +80,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_get_engine(hass, config):
def async_get_engine(hass, config):
"""Set up VoiceRSS TTS component.""" """Set up VoiceRSS TTS component."""
return VoiceRSSProvider(hass, config) return VoiceRSSProvider(hass, config)
@ -113,8 +112,7 @@ class VoiceRSSProvider(Provider):
"""Return list of supported languages.""" """Return list of supported languages."""
return SUPPORT_LANGUAGES return SUPPORT_LANGUAGES
@asyncio.coroutine async def async_get_tts_audio(self, message, language, options=None):
def async_get_tts_audio(self, message, language, options=None):
"""Load TTS from VoiceRSS.""" """Load TTS from VoiceRSS."""
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
form_data = self._form_data.copy() form_data = self._form_data.copy()
@ -124,7 +122,7 @@ class VoiceRSSProvider(Provider):
try: try:
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10, loop=self.hass.loop):
request = yield from websession.post( request = await websession.post(
VOICERSS_API_URL, data=form_data VOICERSS_API_URL, data=form_data
) )
@ -132,7 +130,7 @@ class VoiceRSSProvider(Provider):
_LOGGER.error("Error %d on load url %s.", _LOGGER.error("Error %d on load url %s.",
request.status, request.url) request.status, request.url)
return (None, None) return (None, None)
data = yield from request.read() data = await request.read()
if data in ERROR_MSG: if data in ERROR_MSG:
_LOGGER.error( _LOGGER.error(

View File

@ -71,8 +71,7 @@ SUPPORTED_OPTIONS = [
] ]
@asyncio.coroutine async def async_get_engine(hass, config):
def async_get_engine(hass, config):
"""Set up VoiceRSS speech component.""" """Set up VoiceRSS speech component."""
return YandexSpeechKitProvider(hass, config) return YandexSpeechKitProvider(hass, config)
@ -106,8 +105,7 @@ class YandexSpeechKitProvider(Provider):
"""Return list of supported options.""" """Return list of supported options."""
return SUPPORTED_OPTIONS return SUPPORTED_OPTIONS
@asyncio.coroutine async def async_get_tts_audio(self, message, language, options=None):
def async_get_tts_audio(self, message, language, options=None):
"""Load TTS from yandex.""" """Load TTS from yandex."""
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
actual_language = language actual_language = language
@ -125,14 +123,14 @@ class YandexSpeechKitProvider(Provider):
'speed': options.get(CONF_SPEED, self._speed) 'speed': options.get(CONF_SPEED, self._speed)
} }
request = yield from websession.get( request = await websession.get(
YANDEX_API_URL, params=url_param) YANDEX_API_URL, params=url_param)
if request.status != 200: if request.status != 200:
_LOGGER.error("Error %d on load URL %s", _LOGGER.error("Error %d on load URL %s",
request.status, request.url) request.status, request.url)
return (None, None) return (None, None)
data = yield from request.read() data = await request.read()
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout for yandex speech kit API") _LOGGER.error("Timeout for yandex speech kit API")

View File

@ -4,7 +4,6 @@ Support for vacuum cleaner robots (botvacs).
For more details about this platform, please refer to the documentation For more details about this platform, please refer to the documentation
https://home-assistant.io/components/vacuum/ https://home-assistant.io/components/vacuum/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
from functools import partial from functools import partial
import logging import logging
@ -94,13 +93,12 @@ def is_on(hass, entity_id=None):
return hass.states.is_state(entity_id, STATE_ON) return hass.states.is_state(entity_id, STATE_ON)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the vacuum component.""" """Set up the vacuum component."""
component = EntityComponent( component = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_VACUUMS) _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_VACUUMS)
yield from component.async_setup(config) await component.async_setup(config)
component.async_register_entity_service( component.async_register_entity_service(
SERVICE_TURN_ON, VACUUM_SERVICE_SCHEMA, SERVICE_TURN_ON, VACUUM_SERVICE_SCHEMA,

View File

@ -4,7 +4,6 @@ Support for the Dyson 360 eye vacuum cleaner robot.
For more details about this platform, please refer to the documentation For more details about this platform, please refer to the documentation
https://home-assistant.io/components/vacuum.dyson/ https://home-assistant.io/components/vacuum.dyson/
""" """
import asyncio
import logging import logging
from homeassistant.components.dyson import DYSON_DEVICES from homeassistant.components.dyson import DYSON_DEVICES
@ -55,8 +54,7 @@ class Dyson360EyeDevice(VacuumDevice):
_LOGGER.debug("Creating device %s", device.name) _LOGGER.debug("Creating device %s", device.name)
self._device = device self._device = device
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Call when entity is added to hass.""" """Call when entity is added to hass."""
self.hass.async_add_job( self.hass.async_add_job(
self._device.add_message_listener, self.on_message) self._device.add_message_listener, self.on_message)

View File

@ -4,7 +4,6 @@ Support for a generic MQTT vacuum.
For more details about this platform, please refer to the documentation For more details about this platform, please refer to the documentation
https://home-assistant.io/components/vacuum.mqtt/ https://home-assistant.io/components/vacuum.mqtt/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -139,9 +138,8 @@ PLATFORM_SCHEMA = mqtt.MQTT_BASE_PLATFORM_SCHEMA.extend({
}).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema) }).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema)
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the vacuum.""" """Set up the vacuum."""
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
supported_feature_strings = config.get(CONF_SUPPORTED_FEATURES) supported_feature_strings = config.get(CONF_SUPPORTED_FEATURES)
@ -265,10 +263,9 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._battery_level = 0 self._battery_level = 0
self._fan_speed = 'unknown' self._fan_speed = 'unknown'
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Subscribe MQTT events.""" """Subscribe MQTT events."""
yield from super().async_added_to_hass() await super().async_added_to_hass()
@callback @callback
def message_received(topic, payload, qos): def message_received(topic, payload, qos):
@ -332,7 +329,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._docked_topic, self._docked_topic,
self._fan_speed_topic) if topic] self._fan_speed_topic) if topic]
for topic in set(topics_list): for topic in set(topics_list):
yield from self.hass.components.mqtt.async_subscribe( await self.hass.components.mqtt.async_subscribe(
topic, message_received, self._qos) topic, message_received, self._qos)
@property @property
@ -395,8 +392,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
"""Flag supported features.""" """Flag supported features."""
return self._supported_features return self._supported_features
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the vacuum on.""" """Turn the vacuum on."""
if self.supported_features & SUPPORT_TURN_ON == 0: if self.supported_features & SUPPORT_TURN_ON == 0:
return return
@ -406,8 +402,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = 'Cleaning' self._status = 'Cleaning'
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn the vacuum off.""" """Turn the vacuum off."""
if self.supported_features & SUPPORT_TURN_OFF == 0: if self.supported_features & SUPPORT_TURN_OFF == 0:
return return
@ -417,8 +412,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = 'Turning Off' self._status = 'Turning Off'
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_stop(self, **kwargs):
def async_stop(self, **kwargs):
"""Stop the vacuum.""" """Stop the vacuum."""
if self.supported_features & SUPPORT_STOP == 0: if self.supported_features & SUPPORT_STOP == 0:
return return
@ -428,8 +422,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = 'Stopping the current task' self._status = 'Stopping the current task'
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_clean_spot(self, **kwargs):
def async_clean_spot(self, **kwargs):
"""Perform a spot clean-up.""" """Perform a spot clean-up."""
if self.supported_features & SUPPORT_CLEAN_SPOT == 0: if self.supported_features & SUPPORT_CLEAN_SPOT == 0:
return return
@ -439,8 +432,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = "Cleaning spot" self._status = "Cleaning spot"
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_locate(self, **kwargs):
def async_locate(self, **kwargs):
"""Locate the vacuum (usually by playing a song).""" """Locate the vacuum (usually by playing a song)."""
if self.supported_features & SUPPORT_LOCATE == 0: if self.supported_features & SUPPORT_LOCATE == 0:
return return
@ -450,8 +442,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = "Hi, I'm over here!" self._status = "Hi, I'm over here!"
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_start_pause(self, **kwargs):
def async_start_pause(self, **kwargs):
"""Start, pause or resume the cleaning task.""" """Start, pause or resume the cleaning task."""
if self.supported_features & SUPPORT_PAUSE == 0: if self.supported_features & SUPPORT_PAUSE == 0:
return return
@ -461,8 +452,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = 'Pausing/Resuming cleaning...' self._status = 'Pausing/Resuming cleaning...'
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_return_to_base(self, **kwargs):
def async_return_to_base(self, **kwargs):
"""Tell the vacuum to return to its dock.""" """Tell the vacuum to return to its dock."""
if self.supported_features & SUPPORT_RETURN_HOME == 0: if self.supported_features & SUPPORT_RETURN_HOME == 0:
return return
@ -473,8 +463,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = 'Returning home...' self._status = 'Returning home...'
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_set_fan_speed(self, fan_speed, **kwargs):
def async_set_fan_speed(self, fan_speed, **kwargs):
"""Set fan speed.""" """Set fan speed."""
if self.supported_features & SUPPORT_FAN_SPEED == 0: if self.supported_features & SUPPORT_FAN_SPEED == 0:
return return
@ -487,8 +476,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = "Setting fan to {}...".format(fan_speed) self._status = "Setting fan to {}...".format(fan_speed)
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_send_command(self, command, params=None, **kwargs):
def async_send_command(self, command, params=None, **kwargs):
"""Send a command to a vacuum cleaner.""" """Send a command to a vacuum cleaner."""
if self.supported_features & SUPPORT_SEND_COMMAND == 0: if self.supported_features & SUPPORT_SEND_COMMAND == 0:
return return

View File

@ -68,9 +68,8 @@ SUPPORT_ROOMBA = SUPPORT_BATTERY | SUPPORT_PAUSE | SUPPORT_RETURN_HOME | \
SUPPORT_ROOMBA_CARPET_BOOST = SUPPORT_ROOMBA | SUPPORT_FAN_SPEED SUPPORT_ROOMBA_CARPET_BOOST = SUPPORT_ROOMBA | SUPPORT_FAN_SPEED
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the iRobot Roomba vacuum cleaner platform.""" """Set up the iRobot Roomba vacuum cleaner platform."""
from roomba import Roomba from roomba import Roomba
if PLATFORM not in hass.data: if PLATFORM not in hass.data:
@ -96,7 +95,7 @@ def async_setup_platform(hass, config, async_add_entities,
try: try:
with async_timeout.timeout(9): with async_timeout.timeout(9):
yield from hass.async_add_job(roomba.connect) await hass.async_add_job(roomba.connect)
except asyncio.TimeoutError: except asyncio.TimeoutError:
raise PlatformNotReady raise PlatformNotReady
@ -170,54 +169,46 @@ class RoombaVacuum(VacuumDevice):
"""Return the state attributes of the device.""" """Return the state attributes of the device."""
return self._state_attrs return self._state_attrs
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the vacuum on.""" """Turn the vacuum on."""
yield from self.hass.async_add_job(self.vacuum.send_command, 'start') await self.hass.async_add_job(self.vacuum.send_command, 'start')
self._is_on = True self._is_on = True
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn the vacuum off and return to home.""" """Turn the vacuum off and return to home."""
yield from self.async_stop() await self.async_stop()
yield from self.async_return_to_base() await self.async_return_to_base()
@asyncio.coroutine async def async_stop(self, **kwargs):
def async_stop(self, **kwargs):
"""Stop the vacuum cleaner.""" """Stop the vacuum cleaner."""
yield from self.hass.async_add_job(self.vacuum.send_command, 'stop') await self.hass.async_add_job(self.vacuum.send_command, 'stop')
self._is_on = False self._is_on = False
@asyncio.coroutine async def async_resume(self, **kwargs):
def async_resume(self, **kwargs):
"""Resume the cleaning cycle.""" """Resume the cleaning cycle."""
yield from self.hass.async_add_job(self.vacuum.send_command, 'resume') await self.hass.async_add_job(self.vacuum.send_command, 'resume')
self._is_on = True self._is_on = True
@asyncio.coroutine async def async_pause(self, **kwargs):
def async_pause(self, **kwargs):
"""Pause the cleaning cycle.""" """Pause the cleaning cycle."""
yield from self.hass.async_add_job(self.vacuum.send_command, 'pause') await self.hass.async_add_job(self.vacuum.send_command, 'pause')
self._is_on = False self._is_on = False
@asyncio.coroutine async def async_start_pause(self, **kwargs):
def async_start_pause(self, **kwargs):
"""Pause the cleaning task or resume it.""" """Pause the cleaning task or resume it."""
if self.vacuum_state and self.is_on: # vacuum is running if self.vacuum_state and self.is_on: # vacuum is running
yield from self.async_pause() await self.async_pause()
elif self._status == 'Stopped': # vacuum is stopped elif self._status == 'Stopped': # vacuum is stopped
yield from self.async_resume() await self.async_resume()
else: # vacuum is off else: # vacuum is off
yield from self.async_turn_on() await self.async_turn_on()
@asyncio.coroutine async def async_return_to_base(self, **kwargs):
def async_return_to_base(self, **kwargs):
"""Set the vacuum cleaner to return to the dock.""" """Set the vacuum cleaner to return to the dock."""
yield from self.hass.async_add_job(self.vacuum.send_command, 'dock') await self.hass.async_add_job(self.vacuum.send_command, 'dock')
self._is_on = False self._is_on = False
@asyncio.coroutine async def async_set_fan_speed(self, fan_speed, **kwargs):
def async_set_fan_speed(self, fan_speed, **kwargs):
"""Set fan speed.""" """Set fan speed."""
if fan_speed.capitalize() in FAN_SPEEDS: if fan_speed.capitalize() in FAN_SPEEDS:
fan_speed = fan_speed.capitalize() fan_speed = fan_speed.capitalize()
@ -240,22 +231,20 @@ class RoombaVacuum(VacuumDevice):
_LOGGER.error("No such fan speed available: %s", fan_speed) _LOGGER.error("No such fan speed available: %s", fan_speed)
return return
# The set_preference method does only accept string values # The set_preference method does only accept string values
yield from self.hass.async_add_job( await self.hass.async_add_job(
self.vacuum.set_preference, 'carpetBoost', str(carpet_boost)) self.vacuum.set_preference, 'carpetBoost', str(carpet_boost))
yield from self.hass.async_add_job( await self.hass.async_add_job(
self.vacuum.set_preference, 'vacHigh', str(high_perf)) self.vacuum.set_preference, 'vacHigh', str(high_perf))
@asyncio.coroutine async def async_send_command(self, command, params=None, **kwargs):
def async_send_command(self, command, params=None, **kwargs):
"""Send raw command.""" """Send raw command."""
_LOGGER.debug("async_send_command %s (%s), %s", _LOGGER.debug("async_send_command %s (%s), %s",
command, params, kwargs) command, params, kwargs)
yield from self.hass.async_add_job( await self.hass.async_add_job(
self.vacuum.send_command, command, params) self.vacuum.send_command, command, params)
return True return True
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Fetch state from the device.""" """Fetch state from the device."""
# No data, no update # No data, no update
if not self.vacuum.master_state: if not self.vacuum.master_state:

View File

@ -103,9 +103,8 @@ STATE_CODE_TO_STATE = {
} }
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the Xiaomi vacuum cleaner robot platform.""" """Set up the Xiaomi vacuum cleaner robot platform."""
from miio import Vacuum from miio import Vacuum
if DATA_KEY not in hass.data: if DATA_KEY not in hass.data:
@ -124,8 +123,7 @@ def async_setup_platform(hass, config, async_add_entities,
async_add_entities([mirobo], update_before_add=True) async_add_entities([mirobo], update_before_add=True)
@asyncio.coroutine async def async_service_handler(service):
def async_service_handler(service):
"""Map services to methods on MiroboVacuum.""" """Map services to methods on MiroboVacuum."""
method = SERVICE_TO_METHOD.get(service.service) method = SERVICE_TO_METHOD.get(service.service)
params = {key: value for key, value in service.data.items() params = {key: value for key, value in service.data.items()
@ -139,14 +137,14 @@ def async_setup_platform(hass, config, async_add_entities,
update_tasks = [] update_tasks = []
for vacuum in target_vacuums: for vacuum in target_vacuums:
yield from getattr(vacuum, method['method'])(**params) await getattr(vacuum, method['method'])(**params)
for vacuum in target_vacuums: for vacuum in target_vacuums:
update_coro = vacuum.async_update_ha_state(True) update_coro = vacuum.async_update_ha_state(True)
update_tasks.append(update_coro) update_tasks.append(update_coro)
if update_tasks: if update_tasks:
yield from asyncio.wait(update_tasks, loop=hass.loop) await asyncio.wait(update_tasks, loop=hass.loop)
for vacuum_service in SERVICE_TO_METHOD: for vacuum_service in SERVICE_TO_METHOD:
schema = SERVICE_TO_METHOD[vacuum_service].get( schema = SERVICE_TO_METHOD[vacuum_service].get(
@ -259,12 +257,11 @@ class MiroboVacuum(StateVacuumDevice):
"""Flag vacuum cleaner robot features that are supported.""" """Flag vacuum cleaner robot features that are supported."""
return SUPPORT_XIAOMI return SUPPORT_XIAOMI
@asyncio.coroutine async def _try_command(self, mask_error, func, *args, **kwargs):
def _try_command(self, mask_error, func, *args, **kwargs):
"""Call a vacuum command handling error messages.""" """Call a vacuum command handling error messages."""
from miio import DeviceException from miio import DeviceException
try: try:
yield from self.hass.async_add_job(partial(func, *args, **kwargs)) await self.hass.async_add_job(partial(func, *args, **kwargs))
return True return True
except DeviceException as exc: except DeviceException as exc:
_LOGGER.error(mask_error, exc) _LOGGER.error(mask_error, exc)
@ -281,14 +278,12 @@ class MiroboVacuum(StateVacuumDevice):
await self._try_command( await self._try_command(
"Unable to set start/pause: %s", self._vacuum.pause) "Unable to set start/pause: %s", self._vacuum.pause)
@asyncio.coroutine async def async_stop(self, **kwargs):
def async_stop(self, **kwargs):
"""Stop the vacuum cleaner.""" """Stop the vacuum cleaner."""
yield from self._try_command( await self._try_command(
"Unable to stop: %s", self._vacuum.stop) "Unable to stop: %s", self._vacuum.stop)
@asyncio.coroutine async def async_set_fan_speed(self, fan_speed, **kwargs):
def async_set_fan_speed(self, fan_speed, **kwargs):
"""Set fan speed.""" """Set fan speed."""
if fan_speed.capitalize() in FAN_SPEEDS: if fan_speed.capitalize() in FAN_SPEEDS:
fan_speed = FAN_SPEEDS[fan_speed.capitalize()] fan_speed = FAN_SPEEDS[fan_speed.capitalize()]
@ -300,68 +295,60 @@ class MiroboVacuum(StateVacuumDevice):
"Valid speeds are: %s", exc, "Valid speeds are: %s", exc,
self.fan_speed_list) self.fan_speed_list)
return return
yield from self._try_command( await self._try_command(
"Unable to set fan speed: %s", "Unable to set fan speed: %s",
self._vacuum.set_fan_speed, fan_speed) self._vacuum.set_fan_speed, fan_speed)
@asyncio.coroutine async def async_return_to_base(self, **kwargs):
def async_return_to_base(self, **kwargs):
"""Set the vacuum cleaner to return to the dock.""" """Set the vacuum cleaner to return to the dock."""
yield from self._try_command( await self._try_command(
"Unable to return home: %s", self._vacuum.home) "Unable to return home: %s", self._vacuum.home)
@asyncio.coroutine async def async_clean_spot(self, **kwargs):
def async_clean_spot(self, **kwargs):
"""Perform a spot clean-up.""" """Perform a spot clean-up."""
yield from self._try_command( await self._try_command(
"Unable to start the vacuum for a spot clean-up: %s", "Unable to start the vacuum for a spot clean-up: %s",
self._vacuum.spot) self._vacuum.spot)
@asyncio.coroutine async def async_locate(self, **kwargs):
def async_locate(self, **kwargs):
"""Locate the vacuum cleaner.""" """Locate the vacuum cleaner."""
yield from self._try_command( await self._try_command(
"Unable to locate the botvac: %s", self._vacuum.find) "Unable to locate the botvac: %s", self._vacuum.find)
@asyncio.coroutine async def async_send_command(self, command, params=None, **kwargs):
def async_send_command(self, command, params=None, **kwargs):
"""Send raw command.""" """Send raw command."""
yield from self._try_command( await self._try_command(
"Unable to send command to the vacuum: %s", "Unable to send command to the vacuum: %s",
self._vacuum.raw_command, command, params) self._vacuum.raw_command, command, params)
@asyncio.coroutine async def async_remote_control_start(self):
def async_remote_control_start(self):
"""Start remote control mode.""" """Start remote control mode."""
yield from self._try_command( await self._try_command(
"Unable to start remote control the vacuum: %s", "Unable to start remote control the vacuum: %s",
self._vacuum.manual_start) self._vacuum.manual_start)
@asyncio.coroutine async def async_remote_control_stop(self):
def async_remote_control_stop(self):
"""Stop remote control mode.""" """Stop remote control mode."""
yield from self._try_command( await self._try_command(
"Unable to stop remote control the vacuum: %s", "Unable to stop remote control the vacuum: %s",
self._vacuum.manual_stop) self._vacuum.manual_stop)
@asyncio.coroutine async def async_remote_control_move(self,
def async_remote_control_move(self, rotation: int = 0,
rotation: int = 0, velocity: float = 0.3,
velocity: float = 0.3, duration: int = 1500):
duration: int = 1500):
"""Move vacuum with remote control mode.""" """Move vacuum with remote control mode."""
yield from self._try_command( await self._try_command(
"Unable to move with remote control the vacuum: %s", "Unable to move with remote control the vacuum: %s",
self._vacuum.manual_control, self._vacuum.manual_control,
velocity=velocity, rotation=rotation, duration=duration) velocity=velocity, rotation=rotation, duration=duration)
@asyncio.coroutine async def async_remote_control_move_step(self,
def async_remote_control_move_step(self, rotation: int = 0,
rotation: int = 0, velocity: float = 0.2,
velocity: float = 0.2, duration: int = 1500):
duration: int = 1500):
"""Move vacuum one step with remote control mode.""" """Move vacuum one step with remote control mode."""
yield from self._try_command( await self._try_command(
"Unable to remote control the vacuum: %s", "Unable to remote control the vacuum: %s",
self._vacuum.manual_control_once, self._vacuum.manual_control_once,
velocity=velocity, rotation=rotation, duration=duration) velocity=velocity, rotation=rotation, duration=duration)