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.
https://home-assistant.io/components/sensor.ads/
"""
import asyncio
import logging
import voluptuous as vol
@ -62,8 +61,7 @@ class AdsSensor(Entity):
self.ads_type = ads_type
self.factor = factor
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register device notification."""
def update(name, value):
"""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
https://home-assistant.io/components/sensor.alarmdecoder/
"""
import asyncio
import logging
from homeassistant.helpers.entity import Entity
@ -34,8 +33,7 @@ class AlarmDecoderSensor(Entity):
self._icon = 'mdi:alarm-check'
self._name = 'Alarm Panel Display'
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect(
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
https://home-assistant.io/components/sensor.amcrest/
"""
import asyncio
from datetime import timedelta
import logging
@ -19,9 +18,8 @@ _LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=10)
@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 a sensor for an Amcrest IP Camera."""
if discovery_info is None:
return

View file

@ -4,7 +4,6 @@ Support for IP Webcam sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.android_ip_webcam/
"""
import asyncio
from homeassistant.components.android_ip_webcam import (
KEY_MAP, ICON_MAP, DATA_IP_WEBCAM, AndroidIPCamEntity, CONF_HOST,
@ -14,9 +13,8 @@ from homeassistant.helpers.icon import icon_for_battery_level
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 Sensor."""
if discovery_info is None:
return
@ -62,8 +60,7 @@ class IPWebcamSensor(AndroidIPCamEntity):
"""Return the state of the sensor."""
return self._state
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Retrieve latest state."""
if self._sensor in ('audio_connections', 'video_connections'):
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
https://home-assistant.io/components/sensor.api_stream/
"""
import asyncio
import logging
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
@ -48,9 +47,8 @@ class StreamHandler(logging.Handler):
self.entity.schedule_update_ha_state()
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the API stream platform."""
entity = APICount()
handler = StreamHandler(entity)

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
https://home-assistant.io/components/sensor.arwn/
"""
import asyncio
import json
import logging
@ -58,9 +57,8 @@ def _slug(name):
return 'sensor.arwn_{}'.format(slugify(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 ARWN platform."""
@callback
def async_sensor_event_received(topic, payload, qos):
@ -102,7 +100,7 @@ def async_setup_platform(hass, config, async_add_entities,
else:
store[sensor.name].set_event(event)
yield from mqtt.async_subscribe(
await mqtt.async_subscribe(
hass, TOPIC, async_sensor_event_received, 0)
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
https://home-assistant.io/components/sensor.bh1750/
"""
import asyncio
from functools import partial
import logging
@ -66,9 +65,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=import-error
@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 BH1750 sensor."""
import smbus
from i2csense.bh1750 import BH1750
@ -80,7 +78,7 @@ def async_setup_platform(hass, config, async_add_entities,
bus = smbus.SMBus(bus_number)
sensor = yield from hass.async_add_job(
sensor = await hass.async_add_job(
partial(BH1750, bus, i2c_address,
operation_mode=operation_mode,
measurement_delay=config.get(CONF_DELAY),
@ -133,10 +131,9 @@ class BH1750Sensor(Entity):
"""Return the class of this device, from component DEVICE_CLASSES."""
return DEVICE_CLASS_ILLUMINANCE
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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 \
and self.bh1750_sensor.light_level >= 0:
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
https://home-assistant.io/components/sensor.bme280/
"""
import asyncio
from datetime import timedelta
from functools import partial
import logging
@ -81,9 +80,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=import-error
@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 BME280 sensor."""
import smbus
from i2csense.bme280 import BME280
@ -93,7 +91,7 @@ def async_setup_platform(hass, config, async_add_entities,
i2c_address = config.get(CONF_I2C_ADDRESS)
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,
osrs_t=config.get(CONF_OVERSAMPLING_TEMP),
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)
return False
sensor_handler = yield from hass.async_add_job(BME280Handler, sensor)
sensor_handler = await hass.async_add_job(BME280Handler, sensor)
dev = []
try:
@ -163,10 +161,9 @@ class BME280Sensor(Entity):
"""Return the unit of measurement of the sensor."""
return self._unit_of_measurement
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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.type == SENSOR_TEMP:
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
https://home-assistant.io/components/sensor.bme680/
"""
import asyncio
import logging
from time import time, sleep
@ -97,14 +96,13 @@ 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 BME680 sensor."""
SENSOR_TYPES[SENSOR_TEMP][1] = hass.config.units.temperature_unit
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:
return
@ -351,10 +349,9 @@ class BME680Sensor(Entity):
"""Return the unit of measurement of the sensor."""
return self._unit_of_measurement
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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:
temperature = round(self.bme680_client.sensor_data.temperature, 1)
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
https://home-assistant.io/components/sensor.bmw_connected_drive/
"""
import asyncio
import logging
from homeassistant.components.bmw_connected_drive import DOMAIN as BMW_DOMAIN
@ -124,8 +123,7 @@ class BMWConnectedDriveSensor(Entity):
"""Schedule a state update."""
self.schedule_update_ha_state(True)
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Add callback after being added to hass.
Show latest data after startup.

View file

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

View file

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

View file

@ -49,9 +49,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 ComEd Hourly Pricing sensor."""
websession = async_get_clientsession(hass)
dev = []
@ -101,8 +100,7 @@ class ComedHourlyPricingSensor(Entity):
attrs = {ATTR_ATTRIBUTION: CONF_ATTRIBUTION}
return attrs
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Get the ComEd Hourly Pricing data from the web service."""
try:
if self.type == CONF_FIVE_MINUTE or \
@ -114,9 +112,9 @@ class ComedHourlyPricingSensor(Entity):
url_string += '?type=currenthouraverage'
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'
text = yield from response.text()
text = await response.text()
data = json.loads(text)
self._state = round(
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
https://home-assistant.io/components/sensor.discogs/
"""
import asyncio
from datetime import timedelta
import logging
@ -36,9 +35,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 Discogs sensor."""
import discogs_client
@ -92,7 +90,6 @@ class DiscogsSensor(Entity):
ATTR_IDENTITY: self._identity.name,
}
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Set state to the amount of records in user's 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
https://home-assistant.io/components/sensor.dnsip/
"""
import asyncio
import logging
from datetime import timedelta
@ -42,8 +41,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Set up the DNS IP sensor."""
hostname = config.get(CONF_HOSTNAME)
name = config.get(CONF_NAME)
@ -86,11 +85,10 @@ class WanIpSensor(Entity):
"""Return the current DNS IP address for hostname."""
return self._state
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Get the current DNS IP address for hostname."""
response = yield from self.resolver.query(self.hostname,
self.querytype)
response = await self.resolver.query(self.hostname,
self.querytype)
if response:
self._state = response[0].host
else:

View file

@ -48,9 +48,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 DSMR sensor."""
# Suppress logging
logging.getLogger('dsmr_parser').setLevel(logging.ERROR)
@ -182,13 +181,12 @@ def async_setup_platform(hass, config, async_add_entities,
create_dsmr_reader, config[CONF_PORT], config[CONF_DSMR_VERSION],
update_entities_telegram, loop=hass.loop)
@asyncio.coroutine
def connect_and_reconnect():
async def connect_and_reconnect():
"""Connect to DSMR and keep reconnecting until Home Assistant stops."""
while hass.state != CoreState.stopping:
# Start DSMR asyncio.Protocol reader
try:
transport, protocol = yield from hass.loop.create_task(
transport, protocol = await hass.loop.create_task(
reader_factory())
except (serial.serialutil.SerialException, ConnectionRefusedError,
TimeoutError):
@ -203,7 +201,7 @@ def async_setup_platform(hass, config, async_add_entities,
EVENT_HOMEASSISTANT_STOP, transport.close)
# Wait for reader to close
yield from protocol.wait_closed()
await protocol.wait_closed()
if hass.state != CoreState.stopping:
# Unexpected disconnect
@ -216,8 +214,8 @@ def async_setup_platform(hass, config, async_add_entities,
update_entities_telegram({})
# throttle reconnect attempts
yield from asyncio.sleep(config[CONF_RECONNECT_INTERVAL],
loop=hass.loop)
await asyncio.sleep(config[CONF_RECONNECT_INTERVAL],
loop=hass.loop)
# Can't be hass.async_add_job because job runs forever
hass.loop.create_task(connect_and_reconnect())
@ -309,8 +307,7 @@ class DerivativeDSMREntity(DSMREntity):
"""Return the calculated current hourly rate."""
return self._state
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Recalculate hourly rate if timestamp has changed.
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
https://home-assistant.io/components/sensor.dyson/
"""
import asyncio
import logging
from homeassistant.components.dyson import DYSON_DEVICES
@ -58,8 +57,7 @@ class DysonSensor(Entity):
self._name = None
self._sensor_type = sensor_type
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self.hass.async_add_job(
self._device.add_message_listener, self.on_message)

View file

@ -4,7 +4,6 @@ Support for Envisalink sensors (shows panel info).
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.envisalink/
"""
import asyncio
import logging
from homeassistant.core import callback
@ -19,9 +18,8 @@ _LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['envisalink']
@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):
"""Perform the setup for Envisalink sensor devices."""
configured_partitions = discovery_info['partitions']
@ -51,8 +49,7 @@ class EnvisalinkSensor(EnvisalinkDevice, Entity):
_LOGGER.debug("Setting up sensor for partition: %s", partition_name)
super().__init__(partition_name + ' Keypad', info, controller)
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
async_dispatcher_connect(
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/
"""
import os
import asyncio
import logging
from datetime import timedelta
@ -39,9 +38,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 fail2ban sensor."""
name = config.get(CONF_NAME)
jails = config.get(CONF_JAILS)

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
https://home-assistant.io/components/sensor.fastdotcom/
"""
import asyncio
import logging
import voluptuous as vol
@ -88,10 +87,9 @@ class SpeedtestSensor(Entity):
self._state = data['download']
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""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:
return
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
https://home-assistant.io/components/sensor.fido/
"""
import asyncio
import logging
from datetime import timedelta
@ -70,16 +69,15 @@ 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 Fido sensor."""
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
httpsession = hass.helpers.aiohttp_client.async_get_clientsession()
fido_data = FidoData(username, password, httpsession)
ret = yield from fido_data.async_update()
ret = await fido_data.async_update()
if ret is False:
return
@ -134,10 +132,9 @@ class FidoSensor(Entity):
'number': self._number,
}
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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.fido_data.data.get(self.type) is not None:
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/
"""
import os
import asyncio
import logging
import voluptuous as vol
@ -32,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 the file sensor."""
file_path = config.get(CONF_FILE_PATH)
name = config.get(CONF_NAME)

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
https://home-assistant.io/components/sensor.htu21d/
"""
import asyncio
from datetime import timedelta
from functools import partial
import logging
@ -40,9 +39,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=import-error
@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 HTU21D sensor."""
import smbus
from i2csense.htu21d import HTU21D
@ -52,14 +50,14 @@ def async_setup_platform(hass, config, async_add_entities,
temp_unit = hass.config.units.temperature_unit
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)
)
if not sensor.sample_ok:
_LOGGER.error("HTU21D sensor not detected in bus %s", bus_number)
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),
HTU21DSensor(sensor_handler, name, SENSOR_HUMIDITY, '%')]
@ -107,10 +105,9 @@ class HTU21DSensor(Entity):
"""Return the unit of measurement of the sensor."""
return self._unit_of_measurement
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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._variable == SENSOR_TEMPERATURE:
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
https://home-assistant.io/components/sensor.hydroquebec/
"""
import asyncio
import logging
from datetime import timedelta
@ -93,9 +92,8 @@ DAILY_MAP = (('yesterday_total_consumption', 'consoTotalQuot'),
('yesterday_higher_price_consumption', 'consoHautQuot'))
@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 HydroQuebec sensor."""
# Create a data fetcher to support all of the configured sensors. Then make
# the first call to init the data.
@ -107,7 +105,7 @@ def async_setup_platform(hass, config, async_add_entities,
httpsession = hass.helpers.aiohttp_client.async_get_clientsession()
hydroquebec_data = HydroquebecData(username, password, httpsession,
contract)
contracts = yield from hydroquebec_data.get_contract_list()
contracts = await hydroquebec_data.get_contract_list()
if not contracts:
return
_LOGGER.info("Contract list: %s",
@ -155,10 +153,9 @@ class HydroQuebecSensor(Entity):
"""Icon to use in the frontend, if any."""
return self._icon
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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:
self._state = round(self.hydroquebec_data.data[self.type], 2)
@ -174,11 +171,10 @@ class HydroquebecData:
self._contract = contract
self.data = {}
@asyncio.coroutine
def get_contract_list(self):
async def get_contract_list(self):
"""Return the contract list."""
# Fetch data
ret = yield from self._fetch_data()
ret = await self._fetch_data()
if ret:
return self.client.get_contracts()
return []
@ -194,8 +190,7 @@ class HydroquebecData:
return False
return True
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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]

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/sensor.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')

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
https://home-assistant.io/components/sensor.min_max/
"""
import asyncio
import logging
import voluptuous as vol
@ -54,9 +53,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 min/max/mean sensor."""
entity_ids = config.get(CONF_ENTITY_IDS)
name = config.get(CONF_NAME)
@ -194,8 +192,7 @@ class MinMaxSensor(Entity):
"""Return the icon to use in the frontend, if any."""
return ICON
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Get the latest data and updates the states."""
sensor_values = [self.states[k] for k in self._entity_ids
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/
"""
import asyncio
import logging
from homeassistant.components.mychevy import (
@ -55,8 +54,7 @@ class MyChevyStatus(Entity):
"""Initialize sensor with car connection."""
self._state = None
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect(
UPDATE_TOPIC, self.success)
@ -129,8 +127,7 @@ class EVSensor(Entity):
slugify(self._car.name),
slugify(self._name)))
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect(
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/
"""
import time
import asyncio
import logging
import voluptuous as vol
@ -32,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 the OTP sensor."""
name = config.get(CONF_NAME)
token = config.get(CONF_TOKEN)
@ -55,8 +53,7 @@ class TOTPSensor(Entity):
self._state = None
self._next_expiration = None
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Handle when an entity is about to be added to Home Assistant."""
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
https://home-assistant.io/components/light.rflink/
"""
import asyncio
from functools import partial
import logging
@ -74,14 +73,12 @@ 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))
@asyncio.coroutine
def add_new_device(event):
async def add_new_device(event):
"""Check if device is known, otherwise create device entity."""
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
https://home-assistant.io/components/sensor.serial/
"""
import asyncio
import logging
import json
@ -35,9 +34,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 Serial sensor platform."""
name = config.get(CONF_NAME)
port = config.get(CONF_SERIAL_PORT)
@ -67,20 +65,18 @@ class SerialSensor(Entity):
self._template = value_template
self._attributes = []
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Handle when an entity is about to be added to Home Assistant."""
self._serial_loop_task = self.hass.loop.create_task(
self.serial_read(self._port, self._baudrate))
@asyncio.coroutine
def serial_read(self, device, rate, **kwargs):
async def serial_read(self, device, rate, **kwargs):
"""Read the data from the port."""
import serial_asyncio
reader, _ = yield from serial_asyncio.open_serial_connection(
reader, _ = await serial_asyncio.open_serial_connection(
url=device, baudrate=rate, **kwargs)
while True:
line = yield from reader.readline()
line = await reader.readline()
line = line.decode('utf-8').strip()
try:
@ -98,8 +94,7 @@ class SerialSensor(Entity):
self._state = line
self.async_schedule_update_ha_state()
@asyncio.coroutine
def stop_serial_read(self):
async def stop_serial_read(self):
"""Close resources."""
if self._serial_loop_task:
self._serial_loop_task.cancel()

View file

@ -63,9 +63,8 @@ PLATFORM_SCHEMA = vol.All(PLATFORM_SCHEMA.extend({
}, extra=vol.PREVENT_EXTRA), _check_sensor_schema)
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up SMA WebConnect sensor."""
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)
# Ensure we logout on shutdown
@asyncio.coroutine
def async_close_session(event):
async def async_close_session(event):
"""Close the session."""
yield from sma.close_session()
await sma.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
@asyncio.coroutine
def async_sma(event):
async def async_sma(event):
"""Update all the SMA sensors."""
nonlocal backoff
if backoff > 1:
backoff -= 1
return
values = yield from sma.read(keys_to_query)
values = await sma.read(keys_to_query)
if values is None:
backoff = 3
return
@ -142,7 +139,7 @@ def async_setup_platform(hass, config, async_add_entities,
if task:
tasks.append(task)
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)
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
https://home-assistant.io/components/sensor.sochain/
"""
import asyncio
import logging
from datetime import timedelta
@ -35,9 +34,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 sochain sensors."""
from pysochain import ChainSo
address = config.get(CONF_ADDRESS)
@ -82,7 +80,6 @@ class SochainSensor(Entity):
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
}
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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
https://home-assistant.io/components/sensor.speedtest/
"""
import asyncio
import logging
import voluptuous as vol
@ -139,10 +138,9 @@ class SpeedtestSensor(Entity):
elif self.type == 'upload':
self._state = round(self._data['upload'] / 10**6, 2)
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""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:
return
self._state = state.state

View file

@ -7,7 +7,6 @@ https://home-assistant.io/components/sensor.startca/
from datetime import timedelta
from xml.parsers.expat import ExpatError
import logging
import asyncio
import async_timeout
import voluptuous as vol
@ -57,16 +56,15 @@ 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 sensor platform."""
websession = async_get_clientsession(hass)
apikey = config.get(CONF_API_KEY)
bandwidthcap = config.get(CONF_TOTAL_BANDWIDTH)
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:
_LOGGER.error("Invalid Start.ca API key: %s", apikey)
return
@ -111,10 +109,9 @@ class StartcaSensor(Entity):
"""Icon to use in the frontend, if any."""
return self._icon
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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:
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
https://home-assistant.io/components/sensor.statistics/
"""
import asyncio
import logging
import statistics
from collections import deque
@ -58,9 +57,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 Statistics sensor."""
entity_id = config.get(CONF_ENTITY_ID)
name = config.get(CONF_NAME)
@ -179,8 +177,7 @@ class StatisticsSensor(Entity):
self.ages.popleft()
self.states.popleft()
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Get the latest data and updates the states."""
if self._max_age is not None:
self._purge_old()
@ -236,8 +233,7 @@ class StatisticsSensor(Entity):
self.change = self.average_change = STATE_UNKNOWN
self.change_rate = STATE_UNKNOWN
@asyncio.coroutine
def _initialize_from_database(self):
async def _initialize_from_database(self):
"""Initialize the list of states from the database.
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
import logging
import asyncio
import async_timeout
import voluptuous as vol
@ -58,16 +57,15 @@ 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 sensor platform."""
websession = async_get_clientsession(hass)
apikey = config.get(CONF_API_KEY)
bandwidthcap = config.get(CONF_TOTAL_BANDWIDTH)
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:
_LOGGER.error("Invalid Teksavvy API key: %s", apikey)
return
@ -112,10 +110,9 @@ class TekSavvySensor(Entity):
"""Icon to use in the frontend, if any."""
return self._icon
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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:
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
https://home-assistant.io/components/sensor.template/
"""
import asyncio
import logging
from typing import Optional
@ -41,9 +40,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 sensors."""
sensors = []
@ -123,8 +121,7 @@ class SensorTemplate(Entity):
self._entities = entity_ids
self._device_class = device_class
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
@callback
def template_sensor_state_listener(entity, old_state, new_state):
@ -177,8 +174,7 @@ class SensorTemplate(Entity):
"""No polling needed."""
return False
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Update the state from the template."""
try:
self._state = self._template.async_render()

View file

@ -38,9 +38,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 Things Network Data storage sensors."""
ttn = hass.data.get(DATA_TTN)
device_id = config.get(CONF_DEVICE_ID)
@ -50,7 +49,7 @@ def async_setup_platform(hass, config, async_add_entities,
ttn_data_storage = TtnDataStorage(
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:
return False
@ -104,10 +103,9 @@ class TtnDataSensor(Entity):
ATTR_TIME: self._state['time'],
}
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""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
@ -128,13 +126,12 @@ class TtnDataStorage:
AUTHORIZATION: 'key {}'.format(access_key),
}
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Get the current state from The Things Network Data Storage."""
try:
session = async_get_clientsession(self._hass)
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):
_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)
return False
data = yield from req.json()
data = await req.json()
self.data = data[0]
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/
"""
from datetime import timedelta
import asyncio
import logging
import voluptuous as vol
@ -37,9 +36,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 Time and Date sensor."""
if hass.config.time_zone is None:
_LOGGER.error("Timezone is not set in Home Assistant configuration")

View file

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

View file

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

View file

@ -4,7 +4,6 @@ Support for Waterfurnace.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.waterfurnace/
"""
import asyncio
from homeassistant.components.sensor import ENTITY_ID_FORMAT
from homeassistant.components.waterfurnace import (
@ -100,8 +99,7 @@ class WaterFurnaceSensor(Entity):
"""Return the polling state."""
return False
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect(
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
at https://home-assistant.io/components/sensor.wink/
"""
import asyncio
import logging
from homeassistant.components.wink import DOMAIN, WinkDevice
@ -60,8 +59,7 @@ class WinkSensorDevice(WinkDevice, Entity):
else:
self._unit_of_measurement = self.wink.unit()
@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']['sensor'].append(self)

View file

@ -50,9 +50,8 @@ ERROR_STATE = [
]
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the Worx Landroid sensors."""
for typ in ('battery', 'state'):
async_add_entities([WorxLandroidSensor(typ, config)])
@ -88,8 +87,7 @@ class WorxLandroidSensor(Entity):
return '%'
return None
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Update the sensor data from the mower."""
connection_error = False
@ -97,7 +95,7 @@ class WorxLandroidSensor(Entity):
session = async_get_clientsession(self.hass)
with async_timeout.timeout(self.timeout, loop=self.hass.loop):
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):
if self.allow_unreachable is False:
_LOGGER.error("Error connecting to mower at %s", self.url)
@ -115,7 +113,7 @@ class WorxLandroidSensor(Entity):
elif connection_error is False:
# set the expected content type to be text/html
# 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
if self.sensor == 'battery':

View file

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