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

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

No files matched your search

+1 -3
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."""
+2 -4
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
@@ -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()
+8 -10
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:
+13 -17
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
+6 -12
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()
@@ -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)
+2 -4
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
+14 -20
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(
+2 -4
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))
+8 -14
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()
+1 -3
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)