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.
https://home-assistant.io/components/switch.ads/
"""
import asyncio
import logging
import voluptuous as vol
@ -47,8 +46,7 @@ class AdsSwitch(ToggleEntity):
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."""

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
https://home-assistant.io/components/switch.amcrest/
"""
import asyncio
import logging
from homeassistant.components.amcrest import DATA_AMCREST, SWITCHES
@ -17,9 +16,8 @@ _LOGGER = logging.getLogger(__name__)
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

View file

@ -4,7 +4,6 @@ Support for IP Webcam settings.
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 (
@ -14,9 +13,8 @@ from homeassistant.components.android_ip_webcam import (
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
@ -51,8 +49,7 @@ class IPWebcamSettingsSwitch(AndroidIPCamEntity, SwitchDevice):
"""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))
@ -61,31 +58,29 @@ class IPWebcamSettingsSwitch(AndroidIPCamEntity, SwitchDevice):
"""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()

View file

@ -80,11 +80,10 @@ 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
@ -92,12 +91,12 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
_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: {}".\
@ -106,13 +105,12 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
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:
@ -122,12 +120,12 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
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:

View file

@ -31,9 +31,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
@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)
@ -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
@ -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
@ -104,16 +103,15 @@ class HookSmartHome(SwitchDevice):
"""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)
@ -122,21 +120,19 @@ class HookSmartHome(SwitchDevice):
_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

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
https://home-assistant.io/components/switch.insteon/
"""
import asyncio
import logging
from homeassistant.components.insteon import InsteonEntity
@ -15,9 +14,8 @@ DEPENDENCIES = ['insteon']
_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')
@ -48,13 +46,11 @@ class InsteonSwitchDevice(InsteonEntity, SwitchDevice):
"""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()
@ -67,12 +63,10 @@ class InsteonOpenClosedDevice(InsteonEntity, SwitchDevice):
"""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()

View file

@ -4,7 +4,6 @@ Support for Lutron Caseta switches.
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 (
@ -16,9 +15,8 @@ _LOGGER = logging.getLogger(__name__)
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]
@ -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)
@ -50,8 +46,7 @@ class LutronCasetaLight(LutronCasetaDevice, SwitchDevice):
"""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)

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
https://home-assistant.io/components/switch.pilight/
"""
import asyncio
import logging
import voluptuous as vol
@ -122,10 +121,9 @@ class PilightSwitch(SwitchDevice):
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

View file

@ -47,9 +47,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
@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 RESTful switch."""
body_off = config.get(CONF_BODY_OFF)
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,
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:
_LOGGER.error("Got non-ok response from resource: %s", req.status)
else:
@ -116,13 +115,12 @@ class RestSwitch(SwitchDevice):
"""Return true if device is on."""
return self._state
@asyncio.coroutine
def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs):
"""Turn the device on."""
body_on_t = self._body_on.async_render()
try:
req = yield from self.set_device_state(body_on_t)
req = await self.set_device_state(body_on_t)
if req.status == 200:
self._state = True
@ -133,13 +131,12 @@ class RestSwitch(SwitchDevice):
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Error while turn on %s", self._resource)
@asyncio.coroutine
def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Turn the device off."""
body_off_t = self._body_off.async_render()
try:
req = yield from self.set_device_state(body_off_t)
req = await self.set_device_state(body_off_t)
if req.status == 200:
self._state = False
else:
@ -149,33 +146,30 @@ class RestSwitch(SwitchDevice):
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Error while turn off %s", self._resource)
@asyncio.coroutine
def set_device_state(self, body):
async def set_device_state(self, body):
"""Send a state update to the device."""
websession = async_get_clientsession(self.hass)
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'),
headers=self._headers)
return req
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Get the current state, catching errors."""
try:
yield from self.get_device_state(self.hass)
await self.get_device_state(self.hass)
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.exception("Error while fetch data.")
@asyncio.coroutine
def get_device_state(self, hass):
async def get_device_state(self, hass):
"""Get the latest data from REST API and update the state."""
websession = async_get_clientsession(hass)
with async_timeout.timeout(self._timeout, loop=hass.loop):
req = yield from websession.get(self._resource, auth=self._auth)
text = yield from req.text()
req = await websession.get(self._resource, auth=self._auth)
text = await req.text()
if self._is_on_template is not None:
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
https://home-assistant.io/components/switch.rflink/
"""
import asyncio
import logging
from homeassistant.components.rflink import (
@ -85,9 +84,8 @@ def devices_from_config(domain_config, hass=None):
return devices
@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 Rflink platform."""
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
https://home-assistant.io/components/switch.template/
"""
import asyncio
import logging
import voluptuous as vol
@ -43,9 +42,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
@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 Template switch."""
switches = []
@ -103,8 +101,7 @@ class SwitchTemplate(SwitchDevice):
self._entity_picture = None
self._entities = entity_ids
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
@callback
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 self._entity_picture
@asyncio.coroutine
def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
yield from self._on_script.async_run()
await self._on_script.async_run()
@asyncio.coroutine
def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
yield from self._off_script.async_run()
await self._off_script.async_run()
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Update the state from the template."""
try:
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
https://home-assistant.io/components/switch.wink/
"""
import asyncio
import logging
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):
"""Representation of a Wink toggle device."""
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self.hass.data[DOMAIN]['entities']['switch'].append(self)

View file

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

View file

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

View file

@ -71,8 +71,7 @@ SUPPORTED_OPTIONS = [
]
@asyncio.coroutine
def async_get_engine(hass, config):
async def async_get_engine(hass, config):
"""Set up VoiceRSS speech component."""
return YandexSpeechKitProvider(hass, config)
@ -106,8 +105,7 @@ class YandexSpeechKitProvider(Provider):
"""Return list of supported options."""
return SUPPORTED_OPTIONS
@asyncio.coroutine
def async_get_tts_audio(self, message, language, options=None):
async def async_get_tts_audio(self, message, language, options=None):
"""Load TTS from yandex."""
websession = async_get_clientsession(self.hass)
actual_language = language
@ -125,14 +123,14 @@ class YandexSpeechKitProvider(Provider):
'speed': options.get(CONF_SPEED, self._speed)
}
request = yield from websession.get(
request = await websession.get(
YANDEX_API_URL, params=url_param)
if request.status != 200:
_LOGGER.error("Error %d on load URL %s",
request.status, request.url)
return (None, None)
data = yield from request.read()
data = await request.read()
except (asyncio.TimeoutError, aiohttp.ClientError):
_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
https://home-assistant.io/components/vacuum/
"""
import asyncio
from datetime import timedelta
from functools import partial
import logging
@ -94,13 +93,12 @@ def is_on(hass, entity_id=None):
return hass.states.is_state(entity_id, STATE_ON)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the vacuum component."""
component = EntityComponent(
_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(
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
https://home-assistant.io/components/vacuum.dyson/
"""
import asyncio
import logging
from homeassistant.components.dyson import DYSON_DEVICES
@ -55,8 +54,7 @@ class Dyson360EyeDevice(VacuumDevice):
_LOGGER.debug("Creating device %s", device.name)
self._device = device
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self.hass.async_add_job(
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
https://home-assistant.io/components/vacuum.mqtt/
"""
import asyncio
import logging
import voluptuous as vol
@ -139,9 +138,8 @@ PLATFORM_SCHEMA = mqtt.MQTT_BASE_PLATFORM_SCHEMA.extend({
}).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema)
@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 vacuum."""
name = config.get(CONF_NAME)
supported_feature_strings = config.get(CONF_SUPPORTED_FEATURES)
@ -265,10 +263,9 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._battery_level = 0
self._fan_speed = 'unknown'
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Subscribe MQTT events."""
yield from super().async_added_to_hass()
await super().async_added_to_hass()
@callback
def message_received(topic, payload, qos):
@ -332,7 +329,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._docked_topic,
self._fan_speed_topic) if topic]
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)
@property
@ -395,8 +392,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
"""Flag supported features."""
return self._supported_features
@asyncio.coroutine
def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs):
"""Turn the vacuum on."""
if self.supported_features & SUPPORT_TURN_ON == 0:
return
@ -406,8 +402,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = 'Cleaning'
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Turn the vacuum off."""
if self.supported_features & SUPPORT_TURN_OFF == 0:
return
@ -417,8 +412,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = 'Turning Off'
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_stop(self, **kwargs):
async def async_stop(self, **kwargs):
"""Stop the vacuum."""
if self.supported_features & SUPPORT_STOP == 0:
return
@ -428,8 +422,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = 'Stopping the current task'
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_clean_spot(self, **kwargs):
async def async_clean_spot(self, **kwargs):
"""Perform a spot clean-up."""
if self.supported_features & SUPPORT_CLEAN_SPOT == 0:
return
@ -439,8 +432,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = "Cleaning spot"
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_locate(self, **kwargs):
async def async_locate(self, **kwargs):
"""Locate the vacuum (usually by playing a song)."""
if self.supported_features & SUPPORT_LOCATE == 0:
return
@ -450,8 +442,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = "Hi, I'm over here!"
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_start_pause(self, **kwargs):
async def async_start_pause(self, **kwargs):
"""Start, pause or resume the cleaning task."""
if self.supported_features & SUPPORT_PAUSE == 0:
return
@ -461,8 +452,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = 'Pausing/Resuming cleaning...'
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_return_to_base(self, **kwargs):
async def async_return_to_base(self, **kwargs):
"""Tell the vacuum to return to its dock."""
if self.supported_features & SUPPORT_RETURN_HOME == 0:
return
@ -473,8 +463,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = 'Returning home...'
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_set_fan_speed(self, fan_speed, **kwargs):
async def async_set_fan_speed(self, fan_speed, **kwargs):
"""Set fan speed."""
if self.supported_features & SUPPORT_FAN_SPEED == 0:
return
@ -487,8 +476,7 @@ class MqttVacuum(MqttAvailability, VacuumDevice):
self._status = "Setting fan to {}...".format(fan_speed)
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_send_command(self, command, params=None, **kwargs):
async def async_send_command(self, command, params=None, **kwargs):
"""Send a command to a vacuum cleaner."""
if self.supported_features & SUPPORT_SEND_COMMAND == 0:
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
@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 iRobot Roomba vacuum cleaner platform."""
from roomba import Roomba
if PLATFORM not in hass.data:
@ -96,7 +95,7 @@ def async_setup_platform(hass, config, async_add_entities,
try:
with async_timeout.timeout(9):
yield from hass.async_add_job(roomba.connect)
await hass.async_add_job(roomba.connect)
except asyncio.TimeoutError:
raise PlatformNotReady
@ -170,54 +169,46 @@ class RoombaVacuum(VacuumDevice):
"""Return the state attributes of the device."""
return self._state_attrs
@asyncio.coroutine
def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs):
"""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
@asyncio.coroutine
def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Turn the vacuum off and return to home."""
yield from self.async_stop()
yield from self.async_return_to_base()
await self.async_stop()
await self.async_return_to_base()
@asyncio.coroutine
def async_stop(self, **kwargs):
async def async_stop(self, **kwargs):
"""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
@asyncio.coroutine
def async_resume(self, **kwargs):
async def async_resume(self, **kwargs):
"""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
@asyncio.coroutine
def async_pause(self, **kwargs):
async def async_pause(self, **kwargs):
"""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
@asyncio.coroutine
def async_start_pause(self, **kwargs):
async def async_start_pause(self, **kwargs):
"""Pause the cleaning task or resume it."""
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
yield from self.async_resume()
await self.async_resume()
else: # vacuum is off
yield from self.async_turn_on()
await self.async_turn_on()
@asyncio.coroutine
def async_return_to_base(self, **kwargs):
async def async_return_to_base(self, **kwargs):
"""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
@asyncio.coroutine
def async_set_fan_speed(self, fan_speed, **kwargs):
async def async_set_fan_speed(self, fan_speed, **kwargs):
"""Set fan speed."""
if fan_speed.capitalize() in FAN_SPEEDS:
fan_speed = fan_speed.capitalize()
@ -240,22 +231,20 @@ class RoombaVacuum(VacuumDevice):
_LOGGER.error("No such fan speed available: %s", fan_speed)
return
# 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))
yield from self.hass.async_add_job(
await self.hass.async_add_job(
self.vacuum.set_preference, 'vacHigh', str(high_perf))
@asyncio.coroutine
def async_send_command(self, command, params=None, **kwargs):
async def async_send_command(self, command, params=None, **kwargs):
"""Send raw command."""
_LOGGER.debug("async_send_command %s (%s), %s",
command, params, kwargs)
yield from self.hass.async_add_job(
await self.hass.async_add_job(
self.vacuum.send_command, command, params)
return True
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Fetch state from the device."""
# No data, no update
if not self.vacuum.master_state:

View file

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