Async syntax 6, sensor (#17020)

This commit is contained in:
cdce8p 2018-10-01 08:55:43 +02:00 committed by Paulus Schoutsen
parent 121dba659c
commit 9e4c8f45d6
45 changed files with 195 additions and 319 deletions

View file

@ -4,7 +4,6 @@ Support for ADS sensors.
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/sensor.ads/ https://home-assistant.io/components/sensor.ads/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -62,8 +61,7 @@ class AdsSensor(Entity):
self.ads_type = ads_type self.ads_type = ads_type
self.factor = factor self.factor = factor
@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 notifications.""" """Handle device notifications."""

View file

@ -4,7 +4,6 @@ Support for AlarmDecoder Sensors (Shows Panel Display).
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/sensor.alarmdecoder/ https://home-assistant.io/components/sensor.alarmdecoder/
""" """
import asyncio
import logging import logging
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
@ -34,8 +33,7 @@ class AlarmDecoderSensor(Entity):
self._icon = 'mdi:alarm-check' self._icon = 'mdi:alarm-check'
self._name = 'Alarm Panel Display' self._name = 'Alarm Panel Display'
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect( self.hass.helpers.dispatcher.async_dispatcher_connect(
SIGNAL_PANEL_MESSAGE, self._message_callback) SIGNAL_PANEL_MESSAGE, self._message_callback)

View file

@ -4,7 +4,6 @@ This component provides HA sensor support for Amcrest IP cameras.
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/sensor.amcrest/ https://home-assistant.io/components/sensor.amcrest/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
@ -19,8 +18,7 @@ _LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=10) SCAN_INTERVAL = timedelta(seconds=10)
@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 a sensor for an Amcrest IP Camera.""" """Set up a sensor for an Amcrest IP Camera."""
if discovery_info is None: if discovery_info is None:

View file

@ -4,7 +4,6 @@ Support for IP Webcam sensors.
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/sensor.android_ip_webcam/ https://home-assistant.io/components/sensor.android_ip_webcam/
""" """
import asyncio
from homeassistant.components.android_ip_webcam import ( from homeassistant.components.android_ip_webcam import (
KEY_MAP, ICON_MAP, DATA_IP_WEBCAM, AndroidIPCamEntity, CONF_HOST, KEY_MAP, ICON_MAP, DATA_IP_WEBCAM, AndroidIPCamEntity, CONF_HOST,
@ -14,8 +13,7 @@ from homeassistant.helpers.icon import icon_for_battery_level
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 Sensor.""" """Set up the IP Webcam Sensor."""
if discovery_info is None: if discovery_info is None:
@ -62,8 +60,7 @@ class IPWebcamSensor(AndroidIPCamEntity):
"""Return the state of the sensor.""" """Return the state of the sensor."""
return self._state return self._state
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Retrieve latest state.""" """Retrieve latest state."""
if self._sensor in ('audio_connections', 'video_connections'): if self._sensor in ('audio_connections', 'video_connections'):
if not self._ipcam.status_data: if not self._ipcam.status_data:

View file

@ -4,7 +4,6 @@ Entity to track connections to stream API.
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/sensor.api_stream/ https://home-assistant.io/components/sensor.api_stream/
""" """
import asyncio
import logging import logging
from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.const import EVENT_HOMEASSISTANT_STOP
@ -48,8 +47,7 @@ class StreamHandler(logging.Handler):
self.entity.schedule_update_ha_state() self.entity.schedule_update_ha_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 API stream platform.""" """Set up the API stream platform."""
entity = APICount() entity = APICount()

View file

@ -4,7 +4,6 @@ Support for collecting data from the ARWN project.
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/sensor.arwn/ https://home-assistant.io/components/sensor.arwn/
""" """
import asyncio
import json import json
import logging import logging
@ -58,8 +57,7 @@ def _slug(name):
return 'sensor.arwn_{}'.format(slugify(name)) return 'sensor.arwn_{}'.format(slugify(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 ARWN platform.""" """Set up the ARWN platform."""
@callback @callback
@ -102,7 +100,7 @@ def async_setup_platform(hass, config, async_add_entities,
else: else:
store[sensor.name].set_event(event) store[sensor.name].set_event(event)
yield from mqtt.async_subscribe( await mqtt.async_subscribe(
hass, TOPIC, async_sensor_event_received, 0) hass, TOPIC, async_sensor_event_received, 0)
return True return True

View file

@ -4,7 +4,6 @@ Support for BH1750 light sensor.
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/sensor.bh1750/ https://home-assistant.io/components/sensor.bh1750/
""" """
import asyncio
from functools import partial from functools import partial
import logging import logging
@ -66,8 +65,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=import-error # pylint: disable=import-error
@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 BH1750 sensor.""" """Set up the BH1750 sensor."""
import smbus import smbus
@ -80,7 +78,7 @@ def async_setup_platform(hass, config, async_add_entities,
bus = smbus.SMBus(bus_number) bus = smbus.SMBus(bus_number)
sensor = yield from hass.async_add_job( sensor = await hass.async_add_job(
partial(BH1750, bus, i2c_address, partial(BH1750, bus, i2c_address,
operation_mode=operation_mode, operation_mode=operation_mode,
measurement_delay=config.get(CONF_DELAY), measurement_delay=config.get(CONF_DELAY),
@ -133,10 +131,9 @@ class BH1750Sensor(Entity):
"""Return the class of this device, from component DEVICE_CLASSES.""" """Return the class of this device, from component DEVICE_CLASSES."""
return DEVICE_CLASS_ILLUMINANCE return DEVICE_CLASS_ILLUMINANCE
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data from the BH1750 and update the states.""" """Get the latest data from the BH1750 and update the states."""
yield from self.hass.async_add_job(self.bh1750_sensor.update) await self.hass.async_add_job(self.bh1750_sensor.update)
if self.bh1750_sensor.sample_ok \ if self.bh1750_sensor.sample_ok \
and self.bh1750_sensor.light_level >= 0: and self.bh1750_sensor.light_level >= 0:
self._state = int(round(self.bh1750_sensor.light_level self._state = int(round(self.bh1750_sensor.light_level

View file

@ -4,7 +4,6 @@ Support for BME280 temperature, humidity and pressure sensor.
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/sensor.bme280/ https://home-assistant.io/components/sensor.bme280/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
from functools import partial from functools import partial
import logging import logging
@ -81,8 +80,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=import-error # pylint: disable=import-error
@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 BME280 sensor.""" """Set up the BME280 sensor."""
import smbus import smbus
@ -93,7 +91,7 @@ def async_setup_platform(hass, config, async_add_entities,
i2c_address = config.get(CONF_I2C_ADDRESS) i2c_address = config.get(CONF_I2C_ADDRESS)
bus = smbus.SMBus(config.get(CONF_I2C_BUS)) bus = smbus.SMBus(config.get(CONF_I2C_BUS))
sensor = yield from hass.async_add_job( sensor = await hass.async_add_job(
partial(BME280, bus, i2c_address, partial(BME280, bus, i2c_address,
osrs_t=config.get(CONF_OVERSAMPLING_TEMP), osrs_t=config.get(CONF_OVERSAMPLING_TEMP),
osrs_p=config.get(CONF_OVERSAMPLING_PRES), osrs_p=config.get(CONF_OVERSAMPLING_PRES),
@ -108,7 +106,7 @@ def async_setup_platform(hass, config, async_add_entities,
_LOGGER.error("BME280 sensor not detected at %s", i2c_address) _LOGGER.error("BME280 sensor not detected at %s", i2c_address)
return False return False
sensor_handler = yield from hass.async_add_job(BME280Handler, sensor) sensor_handler = await hass.async_add_job(BME280Handler, sensor)
dev = [] dev = []
try: try:
@ -163,10 +161,9 @@ class BME280Sensor(Entity):
"""Return the unit of measurement of the sensor.""" """Return the unit of measurement of the sensor."""
return self._unit_of_measurement return self._unit_of_measurement
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data from the BME280 and update the states.""" """Get the latest data from the BME280 and update the states."""
yield from self.hass.async_add_job(self.bme280_client.update) await self.hass.async_add_job(self.bme280_client.update)
if self.bme280_client.sensor.sample_ok: if self.bme280_client.sensor.sample_ok:
if self.type == SENSOR_TEMP: if self.type == SENSOR_TEMP:
temperature = round(self.bme280_client.sensor.temperature, 1) temperature = round(self.bme280_client.sensor.temperature, 1)

View file

@ -7,7 +7,6 @@ Air Quality calculation based on humidity and volatile gas.
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/sensor.bme680/ https://home-assistant.io/components/sensor.bme680/
""" """
import asyncio
import logging import logging
from time import time, sleep from time import time, sleep
@ -97,14 +96,13 @@ 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 BME680 sensor.""" """Set up the BME680 sensor."""
SENSOR_TYPES[SENSOR_TEMP][1] = hass.config.units.temperature_unit SENSOR_TYPES[SENSOR_TEMP][1] = hass.config.units.temperature_unit
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
sensor_handler = yield from hass.async_add_job(_setup_bme680, config) sensor_handler = await hass.async_add_job(_setup_bme680, config)
if sensor_handler is None: if sensor_handler is None:
return return
@ -351,10 +349,9 @@ class BME680Sensor(Entity):
"""Return the unit of measurement of the sensor.""" """Return the unit of measurement of the sensor."""
return self._unit_of_measurement return self._unit_of_measurement
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data from the BME680 and update the states.""" """Get the latest data from the BME680 and update the states."""
yield from self.hass.async_add_job(self.bme680_client.update) await self.hass.async_add_job(self.bme680_client.update)
if self.type == SENSOR_TEMP: if self.type == SENSOR_TEMP:
temperature = round(self.bme680_client.sensor_data.temperature, 1) temperature = round(self.bme680_client.sensor_data.temperature, 1)
if self.temp_unit == TEMP_FAHRENHEIT: if self.temp_unit == TEMP_FAHRENHEIT:

View file

@ -4,7 +4,6 @@ Reads vehicle status from BMW connected drive portal.
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/sensor.bmw_connected_drive/ https://home-assistant.io/components/sensor.bmw_connected_drive/
""" """
import asyncio
import logging import logging
from homeassistant.components.bmw_connected_drive import DOMAIN as BMW_DOMAIN from homeassistant.components.bmw_connected_drive import DOMAIN as BMW_DOMAIN
@ -124,8 +123,7 @@ class BMWConnectedDriveSensor(Entity):
"""Schedule a state update.""" """Schedule a state update."""
self.schedule_update_ha_state(True) self.schedule_update_ha_state(True)
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Add callback after being added to hass. """Add callback after being added to hass.
Show latest data after startup. Show latest data after startup.

View file

@ -140,8 +140,7 @@ 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):
"""Create the buienradar sensor.""" """Create the buienradar sensor."""
from homeassistant.components.weather.buienradar import DEFAULT_TIMEFRAME from homeassistant.components.weather.buienradar import DEFAULT_TIMEFRAME
@ -168,7 +167,7 @@ def async_setup_platform(hass, config, async_add_entities,
data = BrData(hass, coordinates, timeframe, dev) data = BrData(hass, coordinates, timeframe, dev)
# schedule the first update in 1 minute from now: # schedule the first update in 1 minute from now:
yield from data.schedule_update(1) await data.schedule_update(1)
class BrSensor(Entity): class BrSensor(Entity):
@ -386,8 +385,7 @@ class BrData:
self.coordinates = coordinates self.coordinates = coordinates
self.timeframe = timeframe self.timeframe = timeframe
@asyncio.coroutine async def update_devices(self):
def update_devices(self):
"""Update all devices/sensors.""" """Update all devices/sensors."""
if self.devices: if self.devices:
tasks = [] tasks = []
@ -397,18 +395,16 @@ class BrData:
tasks.append(dev.async_update_ha_state()) tasks.append(dev.async_update_ha_state())
if tasks: if tasks:
yield from asyncio.wait(tasks, loop=self.hass.loop) await asyncio.wait(tasks, loop=self.hass.loop)
@asyncio.coroutine async def schedule_update(self, minute=1):
def schedule_update(self, minute=1):
"""Schedule an update after minute minutes.""" """Schedule an update after minute minutes."""
_LOGGER.debug("Scheduling next update in %s minutes.", minute) _LOGGER.debug("Scheduling next update in %s minutes.", minute)
nxt = dt_util.utcnow() + timedelta(minutes=minute) nxt = dt_util.utcnow() + timedelta(minutes=minute)
async_track_point_in_utc_time(self.hass, self.async_update, async_track_point_in_utc_time(self.hass, self.async_update,
nxt) nxt)
@asyncio.coroutine async def get_data(self, url):
def get_data(self, url):
"""Load data from specified url.""" """Load data from specified url."""
from buienradar.buienradar import (CONTENT, from buienradar.buienradar import (CONTENT,
MESSAGE, STATUS_CODE, SUCCESS) MESSAGE, STATUS_CODE, SUCCESS)
@ -419,10 +415,10 @@ class BrData:
try: try:
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10, loop=self.hass.loop):
resp = yield from websession.get(url) resp = await websession.get(url)
result[STATUS_CODE] = resp.status result[STATUS_CODE] = resp.status
result[CONTENT] = yield from resp.text() result[CONTENT] = await resp.text()
if resp.status == 200: if resp.status == 200:
result[SUCCESS] = True result[SUCCESS] = True
else: else:
@ -434,17 +430,16 @@ class BrData:
return result return result
finally: finally:
if resp is not None: if resp is not None:
yield from resp.release() await resp.release()
@asyncio.coroutine async def async_update(self, *_):
def async_update(self, *_):
"""Update the data from buienradar.""" """Update the data from buienradar."""
from buienradar.buienradar import (parse_data, CONTENT, from buienradar.buienradar import (parse_data, CONTENT,
DATA, MESSAGE, STATUS_CODE, SUCCESS) DATA, MESSAGE, STATUS_CODE, SUCCESS)
content = yield from self.get_data('http://xml.buienradar.nl') content = await self.get_data('http://xml.buienradar.nl')
if not content.get(SUCCESS, False): if not content.get(SUCCESS, False):
content = yield from self.get_data('http://api.buienradar.nl') content = await self.get_data('http://api.buienradar.nl')
if content.get(SUCCESS) is not True: if content.get(SUCCESS) is not True:
# unable to get the data # unable to get the data
@ -453,7 +448,7 @@ class BrData:
content.get(MESSAGE), content.get(MESSAGE),
content.get(STATUS_CODE),) content.get(STATUS_CODE),)
# schedule new call # schedule new call
yield from self.schedule_update(SCHEDULE_NOK) await self.schedule_update(SCHEDULE_NOK)
return return
# rounding coordinates prevents unnecessary redirects/calls # rounding coordinates prevents unnecessary redirects/calls
@ -462,7 +457,7 @@ class BrData:
round(self.coordinates[CONF_LATITUDE], 2), round(self.coordinates[CONF_LATITUDE], 2),
round(self.coordinates[CONF_LONGITUDE], 2) round(self.coordinates[CONF_LONGITUDE], 2)
) )
raincontent = yield from self.get_data(rainurl) raincontent = await self.get_data(rainurl)
if raincontent.get(SUCCESS) is not True: if raincontent.get(SUCCESS) is not True:
# unable to get the data # unable to get the data
@ -471,7 +466,7 @@ class BrData:
raincontent.get(MESSAGE), raincontent.get(MESSAGE),
raincontent.get(STATUS_CODE),) raincontent.get(STATUS_CODE),)
# schedule new call # schedule new call
yield from self.schedule_update(SCHEDULE_NOK) await self.schedule_update(SCHEDULE_NOK)
return return
result = parse_data(content.get(CONTENT), result = parse_data(content.get(CONTENT),
@ -486,12 +481,12 @@ class BrData:
_LOGGER.warning("Unable to parse data from Buienradar." _LOGGER.warning("Unable to parse data from Buienradar."
"(Msg: %s)", "(Msg: %s)",
result.get(MESSAGE),) result.get(MESSAGE),)
yield from self.schedule_update(SCHEDULE_NOK) await self.schedule_update(SCHEDULE_NOK)
return return
self.data = result.get(DATA) self.data = result.get(DATA)
yield from self.update_devices() await self.update_devices()
yield from self.schedule_update(SCHEDULE_OK) await self.schedule_update(SCHEDULE_OK)
@property @property
def attribution(self): def attribution(self):

View file

@ -104,16 +104,15 @@ class CityBikesRequestError(Exception):
pass pass
@asyncio.coroutine async def async_citybikes_request(hass, uri, schema):
def async_citybikes_request(hass, uri, schema):
"""Perform a request to CityBikes API endpoint, and parse the response.""" """Perform a request to CityBikes API endpoint, and parse the response."""
try: try:
session = async_get_clientsession(hass) session = async_get_clientsession(hass)
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
req = yield from session.get(DEFAULT_ENDPOINT.format(uri=uri)) req = await session.get(DEFAULT_ENDPOINT.format(uri=uri))
json_response = yield from req.json() json_response = await req.json()
return schema(json_response) return schema(json_response)
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Could not connect to CityBikes API endpoint") _LOGGER.error("Could not connect to CityBikes API endpoint")
@ -125,8 +124,7 @@ def async_citybikes_request(hass, uri, schema):
raise CityBikesRequestError raise CityBikesRequestError
@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 CityBikes platform.""" """Set up the CityBikes platform."""
if PLATFORM not in hass.data: if PLATFORM not in hass.data:
@ -142,7 +140,7 @@ def async_setup_platform(hass, config, async_add_entities,
radius = distance.convert(radius, LENGTH_FEET, LENGTH_METERS) radius = distance.convert(radius, LENGTH_FEET, LENGTH_METERS)
if not network_id: if not network_id:
network_id = yield from CityBikesNetwork.get_closest_network_id( network_id = await CityBikesNetwork.get_closest_network_id(
hass, latitude, longitude) hass, latitude, longitude)
if network_id not in hass.data[PLATFORM][MONITORED_NETWORKS]: if network_id not in hass.data[PLATFORM][MONITORED_NETWORKS]:
@ -153,7 +151,7 @@ def async_setup_platform(hass, config, async_add_entities,
else: else:
network = hass.data[PLATFORM][MONITORED_NETWORKS][network_id] network = hass.data[PLATFORM][MONITORED_NETWORKS][network_id]
yield from network.ready.wait() await network.ready.wait()
devices = [] devices = []
for station in network.stations: for station in network.stations:
@ -177,13 +175,12 @@ class CityBikesNetwork:
NETWORKS_LIST_LOADING = asyncio.Condition() NETWORKS_LIST_LOADING = asyncio.Condition()
@classmethod @classmethod
@asyncio.coroutine async def get_closest_network_id(cls, hass, latitude, longitude):
def get_closest_network_id(cls, hass, latitude, longitude):
"""Return the id of the network closest to provided location.""" """Return the id of the network closest to provided location."""
try: try:
yield from cls.NETWORKS_LIST_LOADING.acquire() await cls.NETWORKS_LIST_LOADING.acquire()
if cls.NETWORKS_LIST is None: if cls.NETWORKS_LIST is None:
networks = yield from async_citybikes_request( networks = await async_citybikes_request(
hass, NETWORKS_URI, NETWORKS_RESPONSE_SCHEMA) hass, NETWORKS_URI, NETWORKS_RESPONSE_SCHEMA)
cls.NETWORKS_LIST = networks[ATTR_NETWORKS_LIST] cls.NETWORKS_LIST = networks[ATTR_NETWORKS_LIST]
result = None result = None
@ -210,11 +207,10 @@ class CityBikesNetwork:
self.stations = [] self.stations = []
self.ready = asyncio.Event() self.ready = asyncio.Event()
@asyncio.coroutine async def async_refresh(self, now=None):
def async_refresh(self, now=None):
"""Refresh the state of the network.""" """Refresh the state of the network."""
try: try:
network = yield from async_citybikes_request( network = await async_citybikes_request(
self.hass, STATIONS_URI.format(uid=self.network_id), self.hass, STATIONS_URI.format(uid=self.network_id),
STATIONS_RESPONSE_SCHEMA) STATIONS_RESPONSE_SCHEMA)
self.stations = network[ATTR_NETWORK][ATTR_STATIONS_LIST] self.stations = network[ATTR_NETWORK][ATTR_STATIONS_LIST]
@ -253,8 +249,7 @@ class CityBikesStation(Entity):
return self._station_data[ATTR_NAME] return self._station_data[ATTR_NAME]
return None return None
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Update station state.""" """Update station state."""
if self._network.ready.is_set(): if self._network.ready.is_set():
for station in self._network.stations: for station in self._network.stations:

View file

@ -49,8 +49,7 @@ 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 ComEd Hourly Pricing sensor.""" """Set up the ComEd Hourly Pricing sensor."""
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
@ -101,8 +100,7 @@ class ComedHourlyPricingSensor(Entity):
attrs = {ATTR_ATTRIBUTION: CONF_ATTRIBUTION} attrs = {ATTR_ATTRIBUTION: CONF_ATTRIBUTION}
return attrs return attrs
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the ComEd Hourly Pricing data from the web service.""" """Get the ComEd Hourly Pricing data from the web service."""
try: try:
if self.type == CONF_FIVE_MINUTE or \ if self.type == CONF_FIVE_MINUTE or \
@ -114,9 +112,9 @@ class ComedHourlyPricingSensor(Entity):
url_string += '?type=currenthouraverage' url_string += '?type=currenthouraverage'
with async_timeout.timeout(60, loop=self.loop): with async_timeout.timeout(60, loop=self.loop):
response = yield from self.websession.get(url_string) response = await self.websession.get(url_string)
# The API responds with MIME type 'text/html' # The API responds with MIME type 'text/html'
text = yield from response.text() text = await response.text()
data = json.loads(text) data = json.loads(text)
self._state = round( self._state = round(
float(data[0]['price']) + self.offset, 2) float(data[0]['price']) + self.offset, 2)

View file

@ -4,7 +4,6 @@ Show the amount of records in a user's Discogs collection.
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/sensor.discogs/ https://home-assistant.io/components/sensor.discogs/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
@ -36,8 +35,7 @@ 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 Discogs sensor.""" """Set up the Discogs sensor."""
import discogs_client import discogs_client
@ -92,7 +90,6 @@ class DiscogsSensor(Entity):
ATTR_IDENTITY: self._identity.name, ATTR_IDENTITY: self._identity.name,
} }
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Set state to the amount of records in user's collection.""" """Set state to the amount of records in user's collection."""
self._state = self._identity.num_collection self._state = self._identity.num_collection

View file

@ -4,7 +4,6 @@ Get your own public IP address or that of any host.
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/sensor.dnsip/ https://home-assistant.io/components/sensor.dnsip/
""" """
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -42,8 +41,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_devices,
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): discovery_info=None):
"""Set up the DNS IP sensor.""" """Set up the DNS IP sensor."""
hostname = config.get(CONF_HOSTNAME) hostname = config.get(CONF_HOSTNAME)
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
@ -86,10 +85,9 @@ class WanIpSensor(Entity):
"""Return the current DNS IP address for hostname.""" """Return the current DNS IP address for hostname."""
return self._state return self._state
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the current DNS IP address for hostname.""" """Get the current DNS IP address for hostname."""
response = yield from self.resolver.query(self.hostname, response = await self.resolver.query(self.hostname,
self.querytype) self.querytype)
if response: if response:
self._state = response[0].host self._state = response[0].host

View file

@ -48,8 +48,7 @@ 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 DSMR sensor.""" """Set up the DSMR sensor."""
# Suppress logging # Suppress logging
@ -182,13 +181,12 @@ def async_setup_platform(hass, config, async_add_entities,
create_dsmr_reader, config[CONF_PORT], config[CONF_DSMR_VERSION], create_dsmr_reader, config[CONF_PORT], config[CONF_DSMR_VERSION],
update_entities_telegram, loop=hass.loop) update_entities_telegram, loop=hass.loop)
@asyncio.coroutine async def connect_and_reconnect():
def connect_and_reconnect():
"""Connect to DSMR and keep reconnecting until Home Assistant stops.""" """Connect to DSMR and keep reconnecting until Home Assistant stops."""
while hass.state != CoreState.stopping: while hass.state != CoreState.stopping:
# Start DSMR asyncio.Protocol reader # Start DSMR asyncio.Protocol reader
try: try:
transport, protocol = yield from hass.loop.create_task( transport, protocol = await hass.loop.create_task(
reader_factory()) reader_factory())
except (serial.serialutil.SerialException, ConnectionRefusedError, except (serial.serialutil.SerialException, ConnectionRefusedError,
TimeoutError): TimeoutError):
@ -203,7 +201,7 @@ def async_setup_platform(hass, config, async_add_entities,
EVENT_HOMEASSISTANT_STOP, transport.close) EVENT_HOMEASSISTANT_STOP, transport.close)
# Wait for reader to close # Wait for reader to close
yield from protocol.wait_closed() await protocol.wait_closed()
if hass.state != CoreState.stopping: if hass.state != CoreState.stopping:
# Unexpected disconnect # Unexpected disconnect
@ -216,7 +214,7 @@ def async_setup_platform(hass, config, async_add_entities,
update_entities_telegram({}) update_entities_telegram({})
# throttle reconnect attempts # throttle reconnect attempts
yield from asyncio.sleep(config[CONF_RECONNECT_INTERVAL], await asyncio.sleep(config[CONF_RECONNECT_INTERVAL],
loop=hass.loop) loop=hass.loop)
# Can't be hass.async_add_job because job runs forever # Can't be hass.async_add_job because job runs forever
@ -309,8 +307,7 @@ class DerivativeDSMREntity(DSMREntity):
"""Return the calculated current hourly rate.""" """Return the calculated current hourly rate."""
return self._state return self._state
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Recalculate hourly rate if timestamp has changed. """Recalculate hourly rate if timestamp has changed.
DSMR updates gas meter reading every hour. Along with the new DSMR updates gas meter reading every hour. Along with the new

View file

@ -4,7 +4,6 @@ Support for Dyson Pure Cool Link Sensors.
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/sensor.dyson/ https://home-assistant.io/components/sensor.dyson/
""" """
import asyncio
import logging import logging
from homeassistant.components.dyson import DYSON_DEVICES from homeassistant.components.dyson import DYSON_DEVICES
@ -58,8 +57,7 @@ class DysonSensor(Entity):
self._name = None self._name = None
self._sensor_type = sensor_type self._sensor_type = sensor_type
@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 Envisalink sensors (shows panel info).
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/sensor.envisalink/ https://home-assistant.io/components/sensor.envisalink/
""" """
import asyncio
import logging import logging
from homeassistant.core import callback from homeassistant.core import callback
@ -19,8 +18,7 @@ _LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['envisalink'] DEPENDENCIES = ['envisalink']
@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):
"""Perform the setup for Envisalink sensor devices.""" """Perform the setup for Envisalink sensor devices."""
configured_partitions = discovery_info['partitions'] configured_partitions = discovery_info['partitions']
@ -51,8 +49,7 @@ class EnvisalinkSensor(EnvisalinkDevice, Entity):
_LOGGER.debug("Setting up sensor for partition: %s", partition_name) _LOGGER.debug("Setting up sensor for partition: %s", partition_name)
super().__init__(partition_name + ' Keypad', info, controller) super().__init__(partition_name + ' Keypad', info, controller)
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
async_dispatcher_connect( async_dispatcher_connect(
self.hass, SIGNAL_KEYPAD_UPDATE, self._update_callback) self.hass, SIGNAL_KEYPAD_UPDATE, self._update_callback)

View file

@ -5,7 +5,6 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.fail2ban/ https://home-assistant.io/components/sensor.fail2ban/
""" """
import os import os
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -39,8 +38,7 @@ 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 fail2ban sensor.""" """Set up the fail2ban sensor."""
name = config.get(CONF_NAME) name = config.get(CONF_NAME)

View file

@ -4,7 +4,6 @@ Support for Fast.com internet speed testing sensor.
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/sensor.fastdotcom/ https://home-assistant.io/components/sensor.fastdotcom/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -88,10 +87,9 @@ class SpeedtestSensor(Entity):
self._state = data['download'] self._state = data['download']
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Handle entity which will be added.""" """Handle entity which will be added."""
state = yield from async_get_last_state(self.hass, self.entity_id) state = await async_get_last_state(self.hass, self.entity_id)
if not state: if not state:
return return
self._state = state.state self._state = state.state

View file

@ -7,7 +7,6 @@ https://www.fido.ca/pages/#/my-account/wireless
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/sensor.fido/ https://home-assistant.io/components/sensor.fido/
""" """
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -70,8 +69,7 @@ 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 Fido sensor.""" """Set up the Fido sensor."""
username = config.get(CONF_USERNAME) username = config.get(CONF_USERNAME)
@ -79,7 +77,7 @@ def async_setup_platform(hass, config, async_add_entities,
httpsession = hass.helpers.aiohttp_client.async_get_clientsession() httpsession = hass.helpers.aiohttp_client.async_get_clientsession()
fido_data = FidoData(username, password, httpsession) fido_data = FidoData(username, password, httpsession)
ret = yield from fido_data.async_update() ret = await fido_data.async_update()
if ret is False: if ret is False:
return return
@ -134,10 +132,9 @@ class FidoSensor(Entity):
'number': self._number, 'number': self._number,
} }
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data from Fido and update the state.""" """Get the latest data from Fido and update the state."""
yield from self.fido_data.async_update() await self.fido_data.async_update()
if self.type == 'balance': if self.type == 'balance':
if self.fido_data.data.get(self.type) is not None: if self.fido_data.data.get(self.type) is not None:
self._state = round(self.fido_data.data[self.type], 2) self._state = round(self.fido_data.data[self.type], 2)

View file

@ -5,7 +5,6 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.file/ https://home-assistant.io/components/sensor.file/
""" """
import os import os
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -32,8 +31,7 @@ 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 file sensor.""" """Set up the file sensor."""
file_path = config.get(CONF_FILE_PATH) file_path = config.get(CONF_FILE_PATH)

View file

@ -4,7 +4,6 @@ Support for HTU21D temperature and humidity sensor.
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/sensor.htu21d/ https://home-assistant.io/components/sensor.htu21d/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
from functools import partial from functools import partial
import logging import logging
@ -40,8 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=import-error # pylint: disable=import-error
@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 HTU21D sensor.""" """Set up the HTU21D sensor."""
import smbus import smbus
@ -52,14 +50,14 @@ def async_setup_platform(hass, config, async_add_entities,
temp_unit = hass.config.units.temperature_unit temp_unit = hass.config.units.temperature_unit
bus = smbus.SMBus(config.get(CONF_I2C_BUS)) bus = smbus.SMBus(config.get(CONF_I2C_BUS))
sensor = yield from hass.async_add_job( sensor = await hass.async_add_job(
partial(HTU21D, bus, logger=_LOGGER) partial(HTU21D, bus, logger=_LOGGER)
) )
if not sensor.sample_ok: if not sensor.sample_ok:
_LOGGER.error("HTU21D sensor not detected in bus %s", bus_number) _LOGGER.error("HTU21D sensor not detected in bus %s", bus_number)
return False return False
sensor_handler = yield from hass.async_add_job(HTU21DHandler, sensor) sensor_handler = await hass.async_add_job(HTU21DHandler, sensor)
dev = [HTU21DSensor(sensor_handler, name, SENSOR_TEMPERATURE, temp_unit), dev = [HTU21DSensor(sensor_handler, name, SENSOR_TEMPERATURE, temp_unit),
HTU21DSensor(sensor_handler, name, SENSOR_HUMIDITY, '%')] HTU21DSensor(sensor_handler, name, SENSOR_HUMIDITY, '%')]
@ -107,10 +105,9 @@ class HTU21DSensor(Entity):
"""Return the unit of measurement of the sensor.""" """Return the unit of measurement of the sensor."""
return self._unit_of_measurement return self._unit_of_measurement
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data from the HTU21D sensor and update the state.""" """Get the latest data from the HTU21D sensor and update the state."""
yield from self.hass.async_add_job(self._client.update) await self.hass.async_add_job(self._client.update)
if self._client.sensor.sample_ok: if self._client.sensor.sample_ok:
if self._variable == SENSOR_TEMPERATURE: if self._variable == SENSOR_TEMPERATURE:
value = round(self._client.sensor.temperature, 1) value = round(self._client.sensor.temperature, 1)

View file

@ -7,7 +7,6 @@ https://www.hydroquebec.com/portail/en/group/clientele/portrait-de-consommation
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/sensor.hydroquebec/ https://home-assistant.io/components/sensor.hydroquebec/
""" """
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -93,8 +92,7 @@ DAILY_MAP = (('yesterday_total_consumption', 'consoTotalQuot'),
('yesterday_higher_price_consumption', 'consoHautQuot')) ('yesterday_higher_price_consumption', 'consoHautQuot'))
@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 HydroQuebec sensor.""" """Set up the HydroQuebec sensor."""
# Create a data fetcher to support all of the configured sensors. Then make # Create a data fetcher to support all of the configured sensors. Then make
@ -107,7 +105,7 @@ def async_setup_platform(hass, config, async_add_entities,
httpsession = hass.helpers.aiohttp_client.async_get_clientsession() httpsession = hass.helpers.aiohttp_client.async_get_clientsession()
hydroquebec_data = HydroquebecData(username, password, httpsession, hydroquebec_data = HydroquebecData(username, password, httpsession,
contract) contract)
contracts = yield from hydroquebec_data.get_contract_list() contracts = await hydroquebec_data.get_contract_list()
if not contracts: if not contracts:
return return
_LOGGER.info("Contract list: %s", _LOGGER.info("Contract list: %s",
@ -155,10 +153,9 @@ class HydroQuebecSensor(Entity):
"""Icon to use in the frontend, if any.""" """Icon to use in the frontend, if any."""
return self._icon return self._icon
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data from Hydroquebec and update the state.""" """Get the latest data from Hydroquebec and update the state."""
yield from self.hydroquebec_data.async_update() await self.hydroquebec_data.async_update()
if self.hydroquebec_data.data.get(self.type) is not None: if self.hydroquebec_data.data.get(self.type) is not None:
self._state = round(self.hydroquebec_data.data[self.type], 2) self._state = round(self.hydroquebec_data.data[self.type], 2)
@ -174,11 +171,10 @@ class HydroquebecData:
self._contract = contract self._contract = contract
self.data = {} self.data = {}
@asyncio.coroutine async def get_contract_list(self):
def get_contract_list(self):
"""Return the contract list.""" """Return the contract list."""
# Fetch data # Fetch data
ret = yield from self._fetch_data() ret = await self._fetch_data()
if ret: if ret:
return self.client.get_contracts() return self.client.get_contracts()
return [] return []
@ -194,8 +190,7 @@ class HydroquebecData:
return False return False
return True return True
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Return the latest collected data from HydroQuebec.""" """Return the latest collected data from HydroQuebec."""
yield from self._fetch_data() await self._fetch_data()
self.data = self.client.get_data(self._contract)[self._contract] self.data = self.client.get_data(self._contract)[self._contract]

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/sensor.insteon/ https://home-assistant.io/components/sensor.insteon/
""" """
import asyncio
import logging import logging
from homeassistant.components.insteon import InsteonEntity from homeassistant.components.insteon import InsteonEntity
@ -15,8 +14,7 @@ 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')

View file

@ -4,7 +4,6 @@ Support for displaying the minimal and the maximal value.
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/sensor.min_max/ https://home-assistant.io/components/sensor.min_max/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -54,8 +53,7 @@ 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 min/max/mean sensor.""" """Set up the min/max/mean sensor."""
entity_ids = config.get(CONF_ENTITY_IDS) entity_ids = config.get(CONF_ENTITY_IDS)
@ -194,8 +192,7 @@ class MinMaxSensor(Entity):
"""Return the icon to use in the frontend, if any.""" """Return the icon to use in the frontend, if any."""
return ICON return ICON
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data and updates the states.""" """Get the latest data and updates the states."""
sensor_values = [self.states[k] for k in self._entity_ids sensor_values = [self.states[k] for k in self._entity_ids
if k in self.states] if k in self.states]

View file

@ -4,7 +4,6 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.mychevy/ https://home-assistant.io/components/sensor.mychevy/
""" """
import asyncio
import logging import logging
from homeassistant.components.mychevy import ( from homeassistant.components.mychevy import (
@ -55,8 +54,7 @@ class MyChevyStatus(Entity):
"""Initialize sensor with car connection.""" """Initialize sensor with car connection."""
self._state = None self._state = None
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect( self.hass.helpers.dispatcher.async_dispatcher_connect(
UPDATE_TOPIC, self.success) UPDATE_TOPIC, self.success)
@ -129,8 +127,7 @@ class EVSensor(Entity):
slugify(self._car.name), slugify(self._car.name),
slugify(self._name))) slugify(self._name)))
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect( self.hass.helpers.dispatcher.async_dispatcher_connect(
UPDATE_TOPIC, self.async_update_callback) UPDATE_TOPIC, self.async_update_callback)

View file

@ -5,7 +5,6 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.otp/ https://home-assistant.io/components/sensor.otp/
""" """
import time import time
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -32,8 +31,7 @@ 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 OTP sensor.""" """Set up the OTP sensor."""
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
@ -55,8 +53,7 @@ class TOTPSensor(Entity):
self._state = None self._state = None
self._next_expiration = None self._next_expiration = None
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Handle when an entity is about to be added to Home Assistant.""" """Handle when an entity is about to be added to Home Assistant."""
self._call_loop() self._call_loop()

View file

@ -4,7 +4,6 @@ Support for Rflink sensors.
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/light.rflink/ https://home-assistant.io/components/light.rflink/
""" """
import asyncio
from functools import partial from functools import partial
import logging import logging
@ -74,14 +73,12 @@ 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))
@asyncio.coroutine async def add_new_device(event):
def add_new_device(event):
"""Check if device is known, otherwise create device entity.""" """Check if device is known, otherwise create device entity."""
device_id = event[EVENT_KEY_ID] device_id = event[EVENT_KEY_ID]

View file

@ -4,7 +4,6 @@ Support for reading data from a serial port.
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/sensor.serial/ https://home-assistant.io/components/sensor.serial/
""" """
import asyncio
import logging import logging
import json import json
@ -35,8 +34,7 @@ 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 Serial sensor platform.""" """Set up the Serial sensor platform."""
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
@ -67,20 +65,18 @@ class SerialSensor(Entity):
self._template = value_template self._template = value_template
self._attributes = [] self._attributes = []
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Handle when an entity is about to be added to Home Assistant.""" """Handle when an entity is about to be added to Home Assistant."""
self._serial_loop_task = self.hass.loop.create_task( self._serial_loop_task = self.hass.loop.create_task(
self.serial_read(self._port, self._baudrate)) self.serial_read(self._port, self._baudrate))
@asyncio.coroutine async def serial_read(self, device, rate, **kwargs):
def serial_read(self, device, rate, **kwargs):
"""Read the data from the port.""" """Read the data from the port."""
import serial_asyncio import serial_asyncio
reader, _ = yield from serial_asyncio.open_serial_connection( reader, _ = await serial_asyncio.open_serial_connection(
url=device, baudrate=rate, **kwargs) url=device, baudrate=rate, **kwargs)
while True: while True:
line = yield from reader.readline() line = await reader.readline()
line = line.decode('utf-8').strip() line = line.decode('utf-8').strip()
try: try:
@ -98,8 +94,7 @@ class SerialSensor(Entity):
self._state = line self._state = line
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def stop_serial_read(self):
def stop_serial_read(self):
"""Close resources.""" """Close resources."""
if self._serial_loop_task: if self._serial_loop_task:
self._serial_loop_task.cancel() self._serial_loop_task.cancel()

View file

@ -63,8 +63,7 @@ PLATFORM_SCHEMA = vol.All(PLATFORM_SCHEMA.extend({
}, extra=vol.PREVENT_EXTRA), _check_sensor_schema) }, extra=vol.PREVENT_EXTRA), _check_sensor_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 SMA WebConnect sensor.""" """Set up SMA WebConnect sensor."""
import pysma import pysma
@ -107,10 +106,9 @@ def async_setup_platform(hass, config, async_add_entities,
sma = pysma.SMA(session, url, config[CONF_PASSWORD], group=grp) sma = pysma.SMA(session, url, config[CONF_PASSWORD], group=grp)
# Ensure we logout on shutdown # Ensure we logout on shutdown
@asyncio.coroutine async def async_close_session(event):
def async_close_session(event):
"""Close the session.""" """Close the session."""
yield from sma.close_session() await sma.close_session()
hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, async_close_session) hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, async_close_session)
@ -120,15 +118,14 @@ def async_setup_platform(hass, config, async_add_entities,
backoff = 0 backoff = 0
@asyncio.coroutine async def async_sma(event):
def async_sma(event):
"""Update all the SMA sensors.""" """Update all the SMA sensors."""
nonlocal backoff nonlocal backoff
if backoff > 1: if backoff > 1:
backoff -= 1 backoff -= 1
return return
values = yield from sma.read(keys_to_query) values = await sma.read(keys_to_query)
if values is None: if values is None:
backoff = 3 backoff = 3
return return
@ -142,7 +139,7 @@ def async_setup_platform(hass, config, async_add_entities,
if task: if task:
tasks.append(task) tasks.append(task)
if tasks: if tasks:
yield from asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks, loop=hass.loop)
interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=5) interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=5)
async_track_time_interval(hass, async_sma, interval) async_track_time_interval(hass, async_sma, interval)

View file

@ -4,7 +4,6 @@ Support for watching multiple cryptocurrencies.
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/sensor.sochain/ https://home-assistant.io/components/sensor.sochain/
""" """
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -35,8 +34,7 @@ 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 sochain sensors.""" """Set up the sochain sensors."""
from pysochain import ChainSo from pysochain import ChainSo
@ -82,7 +80,6 @@ class SochainSensor(Entity):
ATTR_ATTRIBUTION: CONF_ATTRIBUTION, ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
} }
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest state of the sensor.""" """Get the latest state of the sensor."""
yield from self.chainso.async_get_data() await self.chainso.async_get_data()

View file

@ -4,7 +4,6 @@ Support for Speedtest.net.
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/sensor.speedtest/ https://home-assistant.io/components/sensor.speedtest/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -139,10 +138,9 @@ class SpeedtestSensor(Entity):
elif self.type == 'upload': elif self.type == 'upload':
self._state = round(self._data['upload'] / 10**6, 2) self._state = round(self._data['upload'] / 10**6, 2)
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Handle all entity which are about to be added.""" """Handle all entity which are about to be added."""
state = yield from async_get_last_state(self.hass, self.entity_id) state = await async_get_last_state(self.hass, self.entity_id)
if not state: if not state:
return return
self._state = state.state self._state = state.state

View file

@ -7,7 +7,6 @@ https://home-assistant.io/components/sensor.startca/
from datetime import timedelta from datetime import timedelta
from xml.parsers.expat import ExpatError from xml.parsers.expat import ExpatError
import logging import logging
import asyncio
import async_timeout import async_timeout
import voluptuous as vol import voluptuous as vol
@ -57,8 +56,7 @@ 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 sensor platform.""" """Set up the sensor platform."""
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
@ -66,7 +64,7 @@ def async_setup_platform(hass, config, async_add_entities,
bandwidthcap = config.get(CONF_TOTAL_BANDWIDTH) bandwidthcap = config.get(CONF_TOTAL_BANDWIDTH)
ts_data = StartcaData(hass.loop, websession, apikey, bandwidthcap) ts_data = StartcaData(hass.loop, websession, apikey, bandwidthcap)
ret = yield from ts_data.async_update() ret = await ts_data.async_update()
if ret is False: if ret is False:
_LOGGER.error("Invalid Start.ca API key: %s", apikey) _LOGGER.error("Invalid Start.ca API key: %s", apikey)
return return
@ -111,10 +109,9 @@ class StartcaSensor(Entity):
"""Icon to use in the frontend, if any.""" """Icon to use in the frontend, if any."""
return self._icon return self._icon
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data from Start.ca and update the state.""" """Get the latest data from Start.ca and update the state."""
yield from self.startcadata.async_update() await self.startcadata.async_update()
if self.type in self.startcadata.data: if self.type in self.startcadata.data:
self._state = round(self.startcadata.data[self.type], 2) self._state = round(self.startcadata.data[self.type], 2)

View file

@ -4,7 +4,6 @@ Support for statistics for sensor values.
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/sensor.statistics/ https://home-assistant.io/components/sensor.statistics/
""" """
import asyncio
import logging import logging
import statistics import statistics
from collections import deque from collections import deque
@ -58,8 +57,7 @@ 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 Statistics sensor.""" """Set up the Statistics sensor."""
entity_id = config.get(CONF_ENTITY_ID) entity_id = config.get(CONF_ENTITY_ID)
@ -179,8 +177,7 @@ class StatisticsSensor(Entity):
self.ages.popleft() self.ages.popleft()
self.states.popleft() self.states.popleft()
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data and updates the states.""" """Get the latest data and updates the states."""
if self._max_age is not None: if self._max_age is not None:
self._purge_old() self._purge_old()
@ -236,8 +233,7 @@ class StatisticsSensor(Entity):
self.change = self.average_change = STATE_UNKNOWN self.change = self.average_change = STATE_UNKNOWN
self.change_rate = STATE_UNKNOWN self.change_rate = STATE_UNKNOWN
@asyncio.coroutine async def _initialize_from_database(self):
def _initialize_from_database(self):
"""Initialize the list of states from the database. """Initialize the list of states from the database.
The query will get the list of states in DESCENDING order so that we The query will get the list of states in DESCENDING order so that we

View file

@ -6,7 +6,6 @@ https://home-assistant.io/components/sensor.teksavvy/
""" """
from datetime import timedelta from datetime import timedelta
import logging import logging
import asyncio
import async_timeout import async_timeout
import voluptuous as vol import voluptuous as vol
@ -58,8 +57,7 @@ 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 sensor platform.""" """Set up the sensor platform."""
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
@ -67,7 +65,7 @@ def async_setup_platform(hass, config, async_add_entities,
bandwidthcap = config.get(CONF_TOTAL_BANDWIDTH) bandwidthcap = config.get(CONF_TOTAL_BANDWIDTH)
ts_data = TekSavvyData(hass.loop, websession, apikey, bandwidthcap) ts_data = TekSavvyData(hass.loop, websession, apikey, bandwidthcap)
ret = yield from ts_data.async_update() ret = await ts_data.async_update()
if ret is False: if ret is False:
_LOGGER.error("Invalid Teksavvy API key: %s", apikey) _LOGGER.error("Invalid Teksavvy API key: %s", apikey)
return return
@ -112,10 +110,9 @@ class TekSavvySensor(Entity):
"""Icon to use in the frontend, if any.""" """Icon to use in the frontend, if any."""
return self._icon return self._icon
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data from TekSavvy and update the state.""" """Get the latest data from TekSavvy and update the state."""
yield from self.teksavvydata.async_update() await self.teksavvydata.async_update()
if self.type in self.teksavvydata.data: if self.type in self.teksavvydata.data:
self._state = round(self.teksavvydata.data[self.type], 2) self._state = round(self.teksavvydata.data[self.type], 2)

View file

@ -4,7 +4,6 @@ Allows the creation of a sensor that breaks out state_attributes.
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/sensor.template/ https://home-assistant.io/components/sensor.template/
""" """
import asyncio
import logging import logging
from typing import Optional from typing import Optional
@ -41,8 +40,7 @@ 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 sensors.""" """Set up the template sensors."""
sensors = [] sensors = []
@ -123,8 +121,7 @@ class SensorTemplate(Entity):
self._entities = entity_ids self._entities = entity_ids
self._device_class = device_class self._device_class = device_class
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
@callback @callback
def template_sensor_state_listener(entity, old_state, new_state): def template_sensor_state_listener(entity, old_state, new_state):
@ -177,8 +174,7 @@ class SensorTemplate(Entity):
"""No polling needed.""" """No polling needed."""
return False return False
@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:
self._state = self._template.async_render() self._state = self._template.async_render()

View file

@ -38,8 +38,7 @@ 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 Things Network Data storage sensors.""" """Set up The Things Network Data storage sensors."""
ttn = hass.data.get(DATA_TTN) ttn = hass.data.get(DATA_TTN)
@ -50,7 +49,7 @@ def async_setup_platform(hass, config, async_add_entities,
ttn_data_storage = TtnDataStorage( ttn_data_storage = TtnDataStorage(
hass, app_id, device_id, access_key, values) hass, app_id, device_id, access_key, values)
success = yield from ttn_data_storage.async_update() success = await ttn_data_storage.async_update()
if not success: if not success:
return False return False
@ -104,10 +103,9 @@ class TtnDataSensor(Entity):
ATTR_TIME: self._state['time'], ATTR_TIME: self._state['time'],
} }
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the current state.""" """Get the current state."""
yield from self._ttn_data_storage.async_update() await self._ttn_data_storage.async_update()
self._state = self._ttn_data_storage.data self._state = self._ttn_data_storage.data
@ -128,13 +126,12 @@ class TtnDataStorage:
AUTHORIZATION: 'key {}'.format(access_key), AUTHORIZATION: 'key {}'.format(access_key),
} }
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the current state from The Things Network Data Storage.""" """Get the current state from The Things Network Data Storage."""
try: try:
session = async_get_clientsession(self._hass) session = async_get_clientsession(self._hass)
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._hass.loop): with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._hass.loop):
req = yield from session.get(self._url, headers=self._headers) req = await session.get(self._url, headers=self._headers)
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Error while accessing: %s", self._url) _LOGGER.error("Error while accessing: %s", self._url)
@ -155,7 +152,7 @@ class TtnDataStorage:
_LOGGER.error("Application ID is not available: %s", self._app_id) _LOGGER.error("Application ID is not available: %s", self._app_id)
return False return False
data = yield from req.json() data = await req.json()
self.data = data[0] self.data = data[0]
for value in self._values.items(): for value in self._values.items():

View file

@ -5,7 +5,6 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.time_date/ https://home-assistant.io/components/sensor.time_date/
""" """
from datetime import timedelta from datetime import timedelta
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -37,8 +36,7 @@ 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 Time and Date sensor.""" """Set up the Time and Date sensor."""
if hass.config.time_zone is None: if hass.config.time_zone is None:

View file

@ -56,8 +56,7 @@ 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 ViaggiaTreno platform.""" """Set up the ViaggiaTreno platform."""
train_id = config.get(CONF_TRAIN_ID) train_id = config.get(CONF_TRAIN_ID)
@ -68,16 +67,15 @@ def async_setup_platform(hass, config, async_add_entities,
async_add_entities([ViaggiaTrenoSensor(train_id, station_id, name)]) async_add_entities([ViaggiaTrenoSensor(train_id, station_id, name)])
@asyncio.coroutine async def async_http_request(hass, uri):
def async_http_request(hass, uri):
"""Perform actual request.""" """Perform actual request."""
try: try:
session = hass.helpers.aiohttp_client.async_get_clientsession(hass) session = hass.helpers.aiohttp_client.async_get_clientsession(hass)
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
req = yield from session.get(uri) req = await session.get(uri)
if req.status != 200: if req.status != 200:
return {'error': req.status} return {'error': req.status}
json_response = yield from req.json() json_response = await req.json()
return json_response return json_response
except (asyncio.TimeoutError, aiohttp.ClientError) as exc: except (asyncio.TimeoutError, aiohttp.ClientError) as exc:
_LOGGER.error("Cannot connect to ViaggiaTreno API endpoint: %s", exc) _LOGGER.error("Cannot connect to ViaggiaTreno API endpoint: %s", exc)
@ -152,11 +150,10 @@ class ViaggiaTrenoSensor(Entity):
return True return True
return False return False
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Update state.""" """Update state."""
uri = self.uri uri = self.uri
res = yield from async_http_request(self.hass, uri) res = await async_http_request(self.hass, uri)
if res.get('error', ''): if res.get('error', ''):
if res['error'] == 204: if res['error'] == 204:
self._state = NO_INFORMATION_STRING self._state = NO_INFORMATION_STRING

View file

@ -59,8 +59,7 @@ 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 requested World Air Quality Index locations.""" """Set up the requested World Air Quality Index locations."""
import waqiasync import waqiasync
@ -74,7 +73,7 @@ def async_setup_platform(hass, config, async_add_entities,
dev = [] dev = []
try: try:
for location_name in locations: for location_name in locations:
stations = yield from client.search(location_name) stations = await client.search(location_name)
_LOGGER.debug("The following stations were returned: %s", stations) _LOGGER.debug("The following stations were returned: %s", stations)
for station in stations: for station in stations:
waqi_sensor = WaqiSensor(client, station) waqi_sensor = WaqiSensor(client, station)
@ -161,13 +160,12 @@ class WaqiSensor(Entity):
except (IndexError, KeyError): except (IndexError, KeyError):
return {ATTR_ATTRIBUTION: ATTRIBUTION} return {ATTR_ATTRIBUTION: ATTRIBUTION}
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest data and updates the states.""" """Get the latest data and updates the states."""
if self.uid: if self.uid:
result = yield from self._client.get_station_by_number(self.uid) result = await self._client.get_station_by_number(self.uid)
elif self.url: elif self.url:
result = yield from self._client.get_station_by_name(self.url) result = await self._client.get_station_by_name(self.url)
else: else:
result = None result = None
self._data = result self._data = result

View file

@ -4,7 +4,6 @@ Support for Waterfurnace.
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/sensor.waterfurnace/ https://home-assistant.io/components/sensor.waterfurnace/
""" """
import asyncio
from homeassistant.components.sensor import ENTITY_ID_FORMAT from homeassistant.components.sensor import ENTITY_ID_FORMAT
from homeassistant.components.waterfurnace import ( from homeassistant.components.waterfurnace import (
@ -100,8 +99,7 @@ class WaterFurnaceSensor(Entity):
"""Return the polling state.""" """Return the polling state."""
return False return False
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect( self.hass.helpers.dispatcher.async_dispatcher_connect(
UPDATE_TOPIC, self.async_update_callback) UPDATE_TOPIC, self.async_update_callback)

View file

@ -4,7 +4,6 @@ Support for Wink sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
at https://home-assistant.io/components/sensor.wink/ at https://home-assistant.io/components/sensor.wink/
""" """
import asyncio
import logging import logging
from homeassistant.components.wink import DOMAIN, WinkDevice from homeassistant.components.wink import DOMAIN, WinkDevice
@ -60,8 +59,7 @@ class WinkSensorDevice(WinkDevice, Entity):
else: else:
self._unit_of_measurement = self.wink.unit() self._unit_of_measurement = self.wink.unit()
@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']['sensor'].append(self) self.hass.data[DOMAIN]['entities']['sensor'].append(self)

View file

@ -50,8 +50,7 @@ ERROR_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 Worx Landroid sensors.""" """Set up the Worx Landroid sensors."""
for typ in ('battery', 'state'): for typ in ('battery', 'state'):
@ -88,8 +87,7 @@ class WorxLandroidSensor(Entity):
return '%' return '%'
return None return None
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Update the sensor data from the mower.""" """Update the sensor data from the mower."""
connection_error = False connection_error = False
@ -97,7 +95,7 @@ class WorxLandroidSensor(Entity):
session = async_get_clientsession(self.hass) session = 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):
auth = aiohttp.helpers.BasicAuth('admin', self.pin) auth = aiohttp.helpers.BasicAuth('admin', self.pin)
mower_response = yield from session.get(self.url, auth=auth) mower_response = await session.get(self.url, auth=auth)
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
if self.allow_unreachable is False: if self.allow_unreachable is False:
_LOGGER.error("Error connecting to mower at %s", self.url) _LOGGER.error("Error connecting to mower at %s", self.url)
@ -115,7 +113,7 @@ class WorxLandroidSensor(Entity):
elif connection_error is False: elif connection_error is False:
# set the expected content type to be text/html # set the expected content type to be text/html
# since the mover incorrectly returns it... # since the mover incorrectly returns it...
data = yield from mower_response.json(content_type='text/html') data = await mower_response.json(content_type='text/html')
# sensor battery # sensor battery
if self.sensor == 'battery': if self.sensor == 'battery':

View file

@ -741,10 +741,9 @@ class WUndergroundSensor(Entity):
"""Return the units of measurement.""" """Return the units of measurement."""
return self._unit_of_measurement return self._unit_of_measurement
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Update current conditions.""" """Update current conditions."""
yield from self.rest.async_update() await self.rest.async_update()
if not self.rest.data: if not self.rest.data:
# no data, return # no data, return