1
mirror of https://github.com/home-assistant/core synced 2024-08-31 05:57:13 +02:00

Async syntax 4/8 (#17018)

* Async syntax 4, media_player & notify

* Pylint fixes
This commit is contained in:
cdce8p 2018-10-01 08:58:21 +02:00 committed by Paulus Schoutsen
parent 3b5e5cbcd6
commit 134eeecd65
17 changed files with 212 additions and 314 deletions

View File

@ -4,7 +4,6 @@ Support for Anthem Network Receivers and Processors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.anthemav/
"""
import asyncio
import logging
import voluptuous as vol
@ -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 our socket to the AVR."""
import anthemav
@ -53,7 +51,7 @@ def async_setup_platform(hass, config, async_add_entities,
_LOGGER.info("Received update callback from AVR: %s", message)
hass.async_add_job(device.async_update_ha_state())
avr = yield from anthemav.Connection.create(
avr = await anthemav.Connection.create(
host=host, port=port, loop=hass.loop,
update_callback=async_anthemav_update_callback)
@ -136,28 +134,23 @@ class AnthemAVR(MediaPlayerDevice):
"""Return all active, configured inputs."""
return self._lookup('input_list', ["Unknown"])
@asyncio.coroutine
def async_select_source(self, source):
async def async_select_source(self, source):
"""Change AVR to the designated source (by name)."""
self._update_avr('input_name', source)
@asyncio.coroutine
def async_turn_off(self):
async def async_turn_off(self):
"""Turn AVR power off."""
self._update_avr('power', False)
@asyncio.coroutine
def async_turn_on(self):
async def async_turn_on(self):
"""Turn AVR power on."""
self._update_avr('power', True)
@asyncio.coroutine
def async_set_volume_level(self, volume):
async def async_set_volume_level(self, volume):
"""Set AVR volume (0 to 1)."""
self._update_avr('volume_as_percentage', volume)
@asyncio.coroutine
def async_mute_volume(self, mute):
async def async_mute_volume(self, mute):
"""Engage AVR mute."""
self._update_avr('mute', mute)

View File

@ -4,7 +4,6 @@ Support for Apple TV.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.apple_tv/
"""
import asyncio
import logging
from homeassistant.components.apple_tv import (
@ -29,8 +28,7 @@ SUPPORT_APPLE_TV = SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PLAY_MEDIA | \
SUPPORT_STOP | SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK
@asyncio.coroutine
def async_setup_platform(
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the Apple TV platform."""
if not discovery_info:
@ -71,8 +69,7 @@ class AppleTvDevice(MediaPlayerDevice):
self._power.listeners.append(self)
self.atv.push_updater.listener = self
@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._power.init()
@ -164,10 +161,9 @@ class AppleTvDevice(MediaPlayerDevice):
if state in (STATE_PLAYING, STATE_PAUSED):
return dt_util.utcnow()
@asyncio.coroutine
def async_play_media(self, media_type, media_id, **kwargs):
async def async_play_media(self, media_type, media_id, **kwargs):
"""Send the play_media command to the media player."""
yield from self.atv.airplay.play_url(media_id)
await self.atv.airplay.play_url(media_id)
@property
def media_image_hash(self):
@ -176,12 +172,11 @@ class AppleTvDevice(MediaPlayerDevice):
if self._playing and state not in [STATE_OFF, STATE_IDLE]:
return self._playing.hash
@asyncio.coroutine
def async_get_media_image(self):
async def async_get_media_image(self):
"""Fetch media image of current playing image."""
state = self.state
if self._playing and state not in [STATE_OFF, STATE_IDLE]:
return (yield from self.atv.metadata.artwork()), 'image/png'
return (await self.atv.metadata.artwork()), 'image/png'
return None, None
@ -201,13 +196,11 @@ class AppleTvDevice(MediaPlayerDevice):
"""Flag media player features that are supported."""
return SUPPORT_APPLE_TV
@asyncio.coroutine
def async_turn_on(self):
async def async_turn_on(self):
"""Turn the media player on."""
self._power.set_power_on(True)
@asyncio.coroutine
def async_turn_off(self):
async def async_turn_off(self):
"""Turn the media player off."""
self._playing = None
self._power.set_power_on(False)

View File

@ -4,7 +4,6 @@ Support for Clementine Music Player as media player.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.clementine/
"""
import asyncio
from datetime import timedelta
import logging
import time
@ -169,8 +168,7 @@ class ClementineDevice(MediaPlayerDevice):
return None
@asyncio.coroutine
def async_get_media_image(self):
async def async_get_media_image(self):
"""Fetch media image of current playing image."""
if self._client.current_track:
image = bytes(self._client.current_track['art'])

View File

@ -4,7 +4,6 @@ Support to interface with the Emby API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.emby/
"""
import asyncio
import logging
import voluptuous as vol
@ -50,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 Emby platform."""
from pyemby import EmbyServer
@ -113,10 +111,9 @@ def async_setup_platform(hass, config, async_add_entities,
"""Start Emby connection."""
emby.start()
@asyncio.coroutine
def stop_emby(event):
async def stop_emby(event):
"""Stop Emby connection."""
yield from emby.stop()
await emby.stop()
emby.add_new_devices_callback(device_update_callback)
emby.add_stale_devices_callback(device_removal_callback)
@ -141,8 +138,7 @@ class EmbyDevice(MediaPlayerDevice):
self.media_status_last_position = None
self.media_status_received = None
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callback."""
self.emby.add_update_callback(
self.async_update_callback, self.device_id)

View File

@ -4,7 +4,6 @@ Support for Frontier Silicon Devices (Medion, Hama, Auna,...).
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.frontier_silicon/
"""
import asyncio
import logging
import voluptuous as vol
@ -41,8 +40,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
@asyncio.coroutine
def async_setup_platform(
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the Frontier Silicon platform."""
import requests
@ -157,18 +155,17 @@ class AFSAPIDevice(MediaPlayerDevice):
"""Image url of current playing media."""
return self._media_image_url
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Get the latest date and update device state."""
fs_device = self.fs_device
if not self._name:
self._name = yield from fs_device.get_friendly_name()
self._name = await fs_device.get_friendly_name()
if not self._source_list:
self._source_list = yield from fs_device.get_mode_list()
self._source_list = await fs_device.get_mode_list()
status = yield from fs_device.get_play_status()
status = await fs_device.get_play_status()
self._state = {
'playing': STATE_PLAYING,
'paused': STATE_PAUSED,
@ -178,16 +175,16 @@ class AFSAPIDevice(MediaPlayerDevice):
}.get(status, STATE_UNKNOWN)
if self._state != STATE_OFF:
info_name = yield from fs_device.get_play_name()
info_text = yield from fs_device.get_play_text()
info_name = await fs_device.get_play_name()
info_text = await fs_device.get_play_text()
self._title = ' - '.join(filter(None, [info_name, info_text]))
self._artist = yield from fs_device.get_play_artist()
self._album_name = yield from fs_device.get_play_album()
self._artist = await fs_device.get_play_artist()
self._album_name = await fs_device.get_play_album()
self._source = yield from fs_device.get_mode()
self._mute = yield from fs_device.get_mute()
self._media_image_url = yield from fs_device.get_play_graphic()
self._source = await fs_device.get_mode()
self._mute = await fs_device.get_mute()
self._media_image_url = await fs_device.get_play_graphic()
else:
self._title = None
self._artist = None
@ -199,48 +196,40 @@ class AFSAPIDevice(MediaPlayerDevice):
# Management actions
# power control
@asyncio.coroutine
def async_turn_on(self):
async def async_turn_on(self):
"""Turn on the device."""
yield from self.fs_device.set_power(True)
await self.fs_device.set_power(True)
@asyncio.coroutine
def async_turn_off(self):
async def async_turn_off(self):
"""Turn off the device."""
yield from self.fs_device.set_power(False)
await self.fs_device.set_power(False)
@asyncio.coroutine
def async_media_play(self):
async def async_media_play(self):
"""Send play command."""
yield from self.fs_device.play()
await self.fs_device.play()
@asyncio.coroutine
def async_media_pause(self):
async def async_media_pause(self):
"""Send pause command."""
yield from self.fs_device.pause()
await self.fs_device.pause()
@asyncio.coroutine
def async_media_play_pause(self):
async def async_media_play_pause(self):
"""Send play/pause command."""
if 'playing' in self._state:
yield from self.fs_device.pause()
await self.fs_device.pause()
else:
yield from self.fs_device.play()
await self.fs_device.play()
@asyncio.coroutine
def async_media_stop(self):
async def async_media_stop(self):
"""Send play/pause command."""
yield from self.fs_device.pause()
await self.fs_device.pause()
@asyncio.coroutine
def async_media_previous_track(self):
async def async_media_previous_track(self):
"""Send previous track command (results in rewind)."""
yield from self.fs_device.rewind()
await self.fs_device.rewind()
@asyncio.coroutine
def async_media_next_track(self):
async def async_media_next_track(self):
"""Send next track command (results in fast-forward)."""
yield from self.fs_device.forward()
await self.fs_device.forward()
# mute
@property
@ -248,30 +237,25 @@ class AFSAPIDevice(MediaPlayerDevice):
"""Boolean if volume is currently muted."""
return self._mute
@asyncio.coroutine
def async_mute_volume(self, mute):
async def async_mute_volume(self, mute):
"""Send mute command."""
yield from self.fs_device.set_mute(mute)
await self.fs_device.set_mute(mute)
# volume
@asyncio.coroutine
def async_volume_up(self):
async def async_volume_up(self):
"""Send volume up command."""
volume = yield from self.fs_device.get_volume()
yield from self.fs_device.set_volume(volume+1)
volume = await self.fs_device.get_volume()
await self.fs_device.set_volume(volume+1)
@asyncio.coroutine
def async_volume_down(self):
async def async_volume_down(self):
"""Send volume down command."""
volume = yield from self.fs_device.get_volume()
yield from self.fs_device.set_volume(volume-1)
volume = await self.fs_device.get_volume()
await self.fs_device.set_volume(volume-1)
@asyncio.coroutine
def async_set_volume_level(self, volume):
async def async_set_volume_level(self, volume):
"""Set volume command."""
yield from self.fs_device.set_volume(volume)
await self.fs_device.set_volume(volume)
@asyncio.coroutine
def async_select_source(self, source):
async def async_select_source(self, source):
"""Select input source."""
yield from self.fs_device.set_mode(source)
await self.fs_device.set_mode(source)

View File

@ -156,9 +156,8 @@ def _check_deprecated_turn_off(hass, turn_off_action):
return turn_off_action
@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 Kodi platform."""
if DATA_KODI not in hass.data:
hass.data[DATA_KODI] = dict()
@ -211,8 +210,7 @@ def async_setup_platform(hass, config, async_add_entities,
hass.data[DATA_KODI][ip_addr] = entity
async_add_entities([entity], update_before_add=True)
@asyncio.coroutine
def async_service_handler(service):
async def async_service_handler(service):
"""Map services to methods on MediaPlayerDevice."""
method = SERVICE_TO_METHOD.get(service.service)
if not method:
@ -230,7 +228,7 @@ def async_setup_platform(hass, config, async_add_entities,
update_tasks = []
for player in target_players:
yield from getattr(player, method['method'])(**params)
await getattr(player, method['method'])(**params)
for player in target_players:
if player.should_poll:
@ -238,7 +236,7 @@ def async_setup_platform(hass, config, async_add_entities,
update_tasks.append(update_coro)
if update_tasks:
yield from asyncio.wait(update_tasks, loop=hass.loop)
await asyncio.wait(update_tasks, loop=hass.loop)
if hass.services.has_service(DOMAIN, SERVICE_ADD_MEDIA):
return
@ -253,12 +251,11 @@ def async_setup_platform(hass, config, async_add_entities,
def cmd(func):
"""Catch command exceptions."""
@wraps(func)
@asyncio.coroutine
def wrapper(obj, *args, **kwargs):
async def wrapper(obj, *args, **kwargs):
"""Wrap all command methods."""
import jsonrpc_base
try:
yield from func(obj, *args, **kwargs)
await func(obj, *args, **kwargs)
except jsonrpc_base.jsonrpc.TransportError as exc:
# If Kodi is off, we expect calls to fail.
if obj.state == STATE_OFF:
@ -392,12 +389,11 @@ class KodiDevice(MediaPlayerDevice):
self._app_properties = {}
self.hass.async_add_job(self._ws_server.close())
@asyncio.coroutine
def _get_players(self):
async def _get_players(self):
"""Return the active player objects or None."""
import jsonrpc_base
try:
return (yield from self.server.Player.GetActivePlayers())
return await self.server.Player.GetActivePlayers()
except jsonrpc_base.jsonrpc.TransportError:
if self._players is not None:
_LOGGER.info("Unable to fetch kodi data")
@ -423,23 +419,21 @@ class KodiDevice(MediaPlayerDevice):
return STATE_PLAYING
@asyncio.coroutine
def async_ws_connect(self):
async def async_ws_connect(self):
"""Connect to Kodi via websocket protocol."""
import jsonrpc_base
try:
ws_loop_future = yield from self._ws_server.ws_connect()
ws_loop_future = await self._ws_server.ws_connect()
except jsonrpc_base.jsonrpc.TransportError:
_LOGGER.info("Unable to connect to Kodi via websocket")
_LOGGER.debug(
"Unable to connect to Kodi via websocket", exc_info=True)
return
@asyncio.coroutine
def ws_loop_wrapper():
async def ws_loop_wrapper():
"""Catch exceptions from the websocket loop task."""
try:
yield from ws_loop_future
await ws_loop_future
except jsonrpc_base.TransportError:
# Kodi abruptly ends ws connection when exiting. We will try
# to reconnect on the next poll.
@ -451,10 +445,9 @@ class KodiDevice(MediaPlayerDevice):
# run until the websocket connection is closed.
self.hass.loop.create_task(ws_loop_wrapper())
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Retrieve latest state."""
self._players = yield from self._get_players()
self._players = await self._get_players()
if self._players is None:
self._properties = {}
@ -466,7 +459,7 @@ class KodiDevice(MediaPlayerDevice):
self.hass.async_add_job(self.async_ws_connect())
self._app_properties = \
yield from self.server.Application.GetProperties(
await self.server.Application.GetProperties(
['volume', 'muted']
)
@ -475,12 +468,12 @@ class KodiDevice(MediaPlayerDevice):
assert isinstance(player_id, int)
self._properties = yield from self.server.Player.GetProperties(
self._properties = await self.server.Player.GetProperties(
player_id,
['time', 'totaltime', 'speed', 'live']
)
self._item = (yield from self.server.Player.GetItem(
self._item = (await self.server.Player.GetItem(
player_id,
['title', 'file', 'uniqueid', 'thumbnail', 'artist',
'albumartist', 'showtitle', 'album', 'season', 'episode']
@ -622,38 +615,34 @@ class KodiDevice(MediaPlayerDevice):
return supported_features
@cmd
@asyncio.coroutine
def async_turn_on(self):
async def async_turn_on(self):
"""Execute turn_on_action to turn on media player."""
if self._turn_on_action is not None:
yield from self._turn_on_action.async_run(
await self._turn_on_action.async_run(
variables={"entity_id": self.entity_id})
else:
_LOGGER.warning("turn_on requested but turn_on_action is none")
@cmd
@asyncio.coroutine
def async_turn_off(self):
async def async_turn_off(self):
"""Execute turn_off_action to turn off media player."""
if self._turn_off_action is not None:
yield from self._turn_off_action.async_run(
await self._turn_off_action.async_run(
variables={"entity_id": self.entity_id})
else:
_LOGGER.warning("turn_off requested but turn_off_action is none")
@cmd
@asyncio.coroutine
def async_volume_up(self):
async def async_volume_up(self):
"""Volume up the media player."""
assert (
yield from self.server.Input.ExecuteAction('volumeup')) == 'OK'
await self.server.Input.ExecuteAction('volumeup')) == 'OK'
@cmd
@asyncio.coroutine
def async_volume_down(self):
async def async_volume_down(self):
"""Volume down the media player."""
assert (
yield from self.server.Input.ExecuteAction('volumedown')) == 'OK'
await self.server.Input.ExecuteAction('volumedown')) == 'OK'
@cmd
def async_set_volume_level(self, volume):
@ -671,13 +660,12 @@ class KodiDevice(MediaPlayerDevice):
"""
return self.server.Application.SetMute(mute)
@asyncio.coroutine
def async_set_play_state(self, state):
async def async_set_play_state(self, state):
"""Handle play/pause/toggle."""
players = yield from self._get_players()
players = await self._get_players()
if players is not None and players:
yield from self.server.Player.PlayPause(
await self.server.Player.PlayPause(
players[0]['playerid'], state)
@cmd
@ -705,26 +693,24 @@ class KodiDevice(MediaPlayerDevice):
return self.async_set_play_state(False)
@cmd
@asyncio.coroutine
def async_media_stop(self):
async def async_media_stop(self):
"""Stop the media player."""
players = yield from self._get_players()
players = await self._get_players()
if players:
yield from self.server.Player.Stop(players[0]['playerid'])
await self.server.Player.Stop(players[0]['playerid'])
@asyncio.coroutine
def _goto(self, direction):
async def _goto(self, direction):
"""Handle for previous/next track."""
players = yield from self._get_players()
players = await self._get_players()
if players:
if direction == 'previous':
# First seek to position 0. Kodi goes to the beginning of the
# current track if the current track is not at the beginning.
yield from self.server.Player.Seek(players[0]['playerid'], 0)
await self.server.Player.Seek(players[0]['playerid'], 0)
yield from self.server.Player.GoTo(
await self.server.Player.GoTo(
players[0]['playerid'], direction)
@cmd
@ -744,10 +730,9 @@ class KodiDevice(MediaPlayerDevice):
return self._goto('previous')
@cmd
@asyncio.coroutine
def async_media_seek(self, position):
async def async_media_seek(self, position):
"""Send seek command."""
players = yield from self._get_players()
players = await self._get_players()
time = {}
@ -763,7 +748,7 @@ class KodiDevice(MediaPlayerDevice):
time['hours'] = int(position)
if players:
yield from self.server.Player.Seek(players[0]['playerid'], time)
await self.server.Player.Seek(players[0]['playerid'], time)
@cmd
def async_play_media(self, media_type, media_id, **kwargs):
@ -781,22 +766,20 @@ class KodiDevice(MediaPlayerDevice):
return self.server.Player.Open(
{"item": {"file": str(media_id)}})
@asyncio.coroutine
def async_set_shuffle(self, shuffle):
async def async_set_shuffle(self, shuffle):
"""Set shuffle mode, for the first player."""
if not self._players:
raise RuntimeError("Error: No active player.")
yield from self.server.Player.SetShuffle(
await self.server.Player.SetShuffle(
{"playerid": self._players[0]['playerid'], "shuffle": shuffle})
@asyncio.coroutine
def async_call_method(self, method, **kwargs):
async def async_call_method(self, method, **kwargs):
"""Run Kodi JSONRPC API method with params."""
import jsonrpc_base
_LOGGER.debug("Run API method %s, kwargs=%s", method, kwargs)
result_ok = False
try:
result = yield from getattr(self.server, method)(**kwargs)
result = await getattr(self.server, method)(**kwargs)
result_ok = True
except jsonrpc_base.jsonrpc.ProtocolError as exc:
result = exc.args[2]['error']
@ -817,8 +800,7 @@ class KodiDevice(MediaPlayerDevice):
event_data=event_data)
return result
@asyncio.coroutine
def async_add_media_to_playlist(
async def async_add_media_to_playlist(
self, media_type, media_id=None, media_name='ALL', artist_name=''):
"""Add a media to default playlist (i.e. playlistid=0).
@ -832,7 +814,7 @@ class KodiDevice(MediaPlayerDevice):
params = {"playlistid": 0}
if media_type == "SONG":
if media_id is None:
media_id = yield from self.async_find_song(
media_id = await self.async_find_song(
media_name, artist_name)
if media_id:
params["item"] = {"songid": int(media_id)}
@ -840,10 +822,10 @@ class KodiDevice(MediaPlayerDevice):
elif media_type == "ALBUM":
if media_id is None:
if media_name == "ALL":
yield from self.async_add_all_albums(artist_name)
await self.async_add_all_albums(artist_name)
return
media_id = yield from self.async_find_album(
media_id = await self.async_find_album(
media_name, artist_name)
if media_id:
params["item"] = {"albumid": int(media_id)}
@ -853,7 +835,7 @@ class KodiDevice(MediaPlayerDevice):
if media_id is not None:
try:
yield from self.server.Playlist.Add(params)
await self.server.Playlist.Add(params)
except jsonrpc_base.jsonrpc.ProtocolError as exc:
result = exc.args[2]['error']
_LOGGER.error("Run API method %s.Playlist.Add(%s) error: %s",
@ -864,43 +846,38 @@ class KodiDevice(MediaPlayerDevice):
else:
_LOGGER.warning("No media detected for Playlist.Add")
@asyncio.coroutine
def async_add_all_albums(self, artist_name):
async def async_add_all_albums(self, artist_name):
"""Add all albums of an artist to default playlist (i.e. playlistid=0).
The artist is specified in terms of name.
"""
artist_id = yield from self.async_find_artist(artist_name)
artist_id = await self.async_find_artist(artist_name)
albums = yield from self.async_get_albums(artist_id)
albums = await self.async_get_albums(artist_id)
for alb in albums['albums']:
yield from self.server.Playlist.Add(
await self.server.Playlist.Add(
{"playlistid": 0, "item": {"albumid": int(alb['albumid'])}})
@asyncio.coroutine
def async_clear_playlist(self):
async def async_clear_playlist(self):
"""Clear default playlist (i.e. playlistid=0)."""
return self.server.Playlist.Clear({"playlistid": 0})
@asyncio.coroutine
def async_get_artists(self):
async def async_get_artists(self):
"""Get artists list."""
return (yield from self.server.AudioLibrary.GetArtists())
return await self.server.AudioLibrary.GetArtists()
@asyncio.coroutine
def async_get_albums(self, artist_id=None):
async def async_get_albums(self, artist_id=None):
"""Get albums list."""
if artist_id is None:
return (yield from self.server.AudioLibrary.GetAlbums())
return await self.server.AudioLibrary.GetAlbums()
return (yield from self.server.AudioLibrary.GetAlbums(
return (await self.server.AudioLibrary.GetAlbums(
{"filter": {"artistid": int(artist_id)}}))
@asyncio.coroutine
def async_find_artist(self, artist_name):
async def async_find_artist(self, artist_name):
"""Find artist by name."""
artists = yield from self.async_get_artists()
artists = await self.async_get_artists()
try:
out = self._find(
artist_name, [a['artist'] for a in artists['artists']])
@ -909,37 +886,34 @@ class KodiDevice(MediaPlayerDevice):
_LOGGER.warning("No artists were found: %s", artist_name)
return None
@asyncio.coroutine
def async_get_songs(self, artist_id=None):
async def async_get_songs(self, artist_id=None):
"""Get songs list."""
if artist_id is None:
return (yield from self.server.AudioLibrary.GetSongs())
return await self.server.AudioLibrary.GetSongs()
return (yield from self.server.AudioLibrary.GetSongs(
return (await self.server.AudioLibrary.GetSongs(
{"filter": {"artistid": int(artist_id)}}))
@asyncio.coroutine
def async_find_song(self, song_name, artist_name=''):
async def async_find_song(self, song_name, artist_name=''):
"""Find song by name and optionally artist name."""
artist_id = None
if artist_name != '':
artist_id = yield from self.async_find_artist(artist_name)
artist_id = await self.async_find_artist(artist_name)
songs = yield from self.async_get_songs(artist_id)
songs = await self.async_get_songs(artist_id)
if songs['limits']['total'] == 0:
return None
out = self._find(song_name, [a['label'] for a in songs['songs']])
return songs['songs'][out[0][0]]['songid']
@asyncio.coroutine
def async_find_album(self, album_name, artist_name=''):
async def async_find_album(self, album_name, artist_name=''):
"""Find album by name and optionally artist name."""
artist_id = None
if artist_name != '':
artist_id = yield from self.async_find_artist(artist_name)
artist_id = await self.async_find_artist(artist_name)
albums = yield from self.async_get_albums(artist_id)
albums = await self.async_get_albums(artist_id)
try:
out = self._find(
album_name, [a['label'] for a in albums['albums']])

View File

@ -4,7 +4,6 @@ Support for interface with an Orange Livebox Play TV appliance.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.liveboxplaytv/
"""
import asyncio
from datetime import timedelta
import logging
@ -44,9 +43,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 Orange Livebox Play TV platform."""
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
@ -83,8 +81,7 @@ class LiveboxPlayTvDevice(MediaPlayerDevice):
self._media_image_url = None
self._media_last_updated = None
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Retrieve the latest data."""
import pyteleloisirs
try:
@ -95,7 +92,7 @@ class LiveboxPlayTvDevice(MediaPlayerDevice):
channel = self._client.channel
if channel is not None:
self._current_channel = channel
program = yield from \
program = await \
self._client.async_get_current_program()
if program and self._current_program != program.get('name'):
self._current_program = program.get('name')
@ -109,7 +106,7 @@ class LiveboxPlayTvDevice(MediaPlayerDevice):
# Set media image to current program if a thumbnail is
# available. Otherwise we'll use the channel's image.
img_size = 800
prg_img_url = yield from \
prg_img_url = await \
self._client.async_get_current_program_image(img_size)
if prg_img_url:
self._media_image_url = prg_img_url

View File

@ -4,7 +4,6 @@ Support for Russound multizone controllers using RIO Protocol.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.russound_rio/
"""
import asyncio
import logging
import voluptuous as vol
@ -33,8 +32,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
@asyncio.coroutine
def async_setup_platform(
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the Russound RIO platform."""
from russound_rio import Russound
@ -44,15 +42,15 @@ def async_setup_platform(
russ = Russound(hass.loop, host, port)
yield from russ.connect()
await russ.connect()
# Discover sources and zones
sources = yield from russ.enumerate_sources()
valid_zones = yield from russ.enumerate_zones()
sources = await russ.enumerate_sources()
valid_zones = await russ.enumerate_zones()
devices = []
for zone_id, name in valid_zones:
yield from russ.watch_zone(zone_id)
await russ.watch_zone(zone_id)
dev = RussoundZoneDevice(russ, zone_id, name, sources)
devices.append(dev)
@ -108,8 +106,7 @@ class RussoundZoneDevice(MediaPlayerDevice):
if source_id == current:
self.schedule_update_ha_state()
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callback handlers."""
self._russ.add_zone_callback(self._zone_callback_handler)
self._russ.add_source_callback(self._source_callback_handler)

View File

@ -4,7 +4,6 @@ Support for interacting with Snapcast clients.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.snapcast/
"""
import asyncio
import logging
import socket
@ -46,17 +45,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 Snapcast platform."""
import snapcast.control
from snapcast.control.server import CONTROL_PORT
host = config.get(CONF_HOST)
port = config.get(CONF_PORT, CONTROL_PORT)
@asyncio.coroutine
def _handle_service(service):
async def _handle_service(service):
"""Handle services."""
entity_ids = service.data.get(ATTR_ENTITY_ID)
devices = [device for device in hass.data[DATA_KEY]
@ -65,7 +62,7 @@ def async_setup_platform(hass, config, async_add_entities,
if service.service == SERVICE_SNAPSHOT:
device.snapshot()
elif service.service == SERVICE_RESTORE:
yield from device.async_restore()
await device.async_restore()
hass.services.async_register(
DOMAIN, SERVICE_SNAPSHOT, _handle_service, schema=SERVICE_SCHEMA)
@ -73,7 +70,7 @@ def async_setup_platform(hass, config, async_add_entities,
DOMAIN, SERVICE_RESTORE, _handle_service, schema=SERVICE_SCHEMA)
try:
server = yield from snapcast.control.create_server(
server = await snapcast.control.create_server(
hass.loop, host, port, reconnect=True)
except socket.gaierror:
_LOGGER.error("Could not connect to Snapcast server at %s:%d",
@ -157,34 +154,30 @@ class SnapcastGroupDevice(MediaPlayerDevice):
"""Do not poll for state."""
return False
@asyncio.coroutine
def async_select_source(self, source):
async def async_select_source(self, source):
"""Set input source."""
streams = self._group.streams_by_name()
if source in streams:
yield from self._group.set_stream(streams[source].identifier)
await self._group.set_stream(streams[source].identifier)
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_mute_volume(self, mute):
async def async_mute_volume(self, mute):
"""Send the mute command."""
yield from self._group.set_muted(mute)
await self._group.set_muted(mute)
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_set_volume_level(self, volume):
async def async_set_volume_level(self, volume):
"""Set the volume level."""
yield from self._group.set_volume(round(volume * 100))
await self._group.set_volume(round(volume * 100))
self.async_schedule_update_ha_state()
def snapshot(self):
"""Snapshot the group state."""
self._group.snapshot()
@asyncio.coroutine
def async_restore(self):
async def async_restore(self):
"""Restore the group state."""
yield from self._group.restore()
await self._group.restore()
class SnapcastClientDevice(MediaPlayerDevice):
@ -246,23 +239,20 @@ class SnapcastClientDevice(MediaPlayerDevice):
"""Do not poll for state."""
return False
@asyncio.coroutine
def async_mute_volume(self, mute):
async def async_mute_volume(self, mute):
"""Send the mute command."""
yield from self._client.set_muted(mute)
await self._client.set_muted(mute)
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_set_volume_level(self, volume):
async def async_set_volume_level(self, volume):
"""Set the volume level."""
yield from self._client.set_volume(round(volume * 100))
await self._client.set_volume(round(volume * 100))
self.async_schedule_update_ha_state()
def snapshot(self):
"""Snapshot the client state."""
self._client.snapshot()
@asyncio.coroutine
def async_restore(self):
async def async_restore(self):
"""Restore the client state."""
yield from self._client.restore()
await self._client.restore()

View File

@ -4,7 +4,6 @@ Support to interface with Sonos players.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.sonos/
"""
import asyncio
import datetime
import functools as ft
import logging
@ -364,8 +363,7 @@ class SonosDevice(MediaPlayerDevice):
self._set_basic_information()
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Subscribe sonos events."""
self.hass.data[DATA_SONOS].devices.append(self)
self.hass.async_add_job(self._subscribe_to_player_events)

View File

@ -64,9 +64,8 @@ SERVICE_TO_METHOD = {
}
@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 squeezebox platform."""
import socket
@ -106,13 +105,12 @@ def async_setup_platform(hass, config, async_add_entities,
_LOGGER.debug("Creating LMS object for %s", ipaddr)
lms = LogitechMediaServer(hass, host, port, username, password)
players = yield from lms.create_players()
players = await lms.create_players()
hass.data[DATA_SQUEEZEBOX].extend(players)
async_add_entities(players)
@asyncio.coroutine
def async_service_handler(service):
async def async_service_handler(service):
"""Map services to methods on MediaPlayerDevice."""
method = SERVICE_TO_METHOD.get(service.service)
if not method:
@ -129,11 +127,11 @@ def async_setup_platform(hass, config, async_add_entities,
update_tasks = []
for player in target_players:
yield from getattr(player, method['method'])(**params)
await getattr(player, method['method'])(**params)
update_tasks.append(player.async_update_ha_state(True))
if update_tasks:
yield from asyncio.wait(update_tasks, loop=hass.loop)
await asyncio.wait(update_tasks, loop=hass.loop)
for service in SERVICE_TO_METHOD:
schema = SERVICE_TO_METHOD[service]['schema']
@ -155,22 +153,20 @@ class LogitechMediaServer:
self._username = username
self._password = password
@asyncio.coroutine
def create_players(self):
async def create_players(self):
"""Create a list of devices connected to LMS."""
result = []
data = yield from self.async_query('players', 'status')
data = await self.async_query('players', 'status')
if data is False:
return result
for players in data.get('players_loop', []):
player = SqueezeBoxDevice(
self, players['playerid'], players['name'])
yield from player.async_update()
await player.async_update()
result.append(player)
return result
@asyncio.coroutine
def async_query(self, *command, player=""):
async def async_query(self, *command, player=""):
"""Abstract out the JSON-RPC connection."""
auth = None if self._username is None else aiohttp.BasicAuth(
self._username, self._password)
@ -187,7 +183,7 @@ class LogitechMediaServer:
try:
websession = async_get_clientsession(self.hass)
with async_timeout.timeout(TIMEOUT, loop=self.hass.loop):
response = yield from websession.post(
response = await websession.post(
url,
data=data,
auth=auth)
@ -198,7 +194,7 @@ class LogitechMediaServer:
response.status, response)
return False
data = yield from response.json()
data = await response.json()
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed communicating with LMS: %s", type(error))
@ -256,11 +252,10 @@ class SqueezeBoxDevice(MediaPlayerDevice):
return self._lms.async_query(
*parameters, player=self._id)
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Retrieve the current state of the player."""
tags = 'adKl'
response = yield from self.async_query(
response = await self.async_query(
"status", "-", "1", "tags:{tags}"
.format(tags=tags))

View File

@ -51,9 +51,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 Volumio platform."""
if DATA_VOLUMIO not in hass.data:
hass.data[DATA_VOLUMIO] = dict()
@ -96,8 +95,7 @@ class Volumio(MediaPlayerDevice):
self._playlists = []
self._currentplaylist = None
@asyncio.coroutine
def send_volumio_msg(self, method, params=None):
async def send_volumio_msg(self, method, params=None):
"""Send message."""
url = "http://{}:{}/api/v1/{}/".format(self.host, self.port, method)
@ -105,9 +103,9 @@ class Volumio(MediaPlayerDevice):
try:
websession = async_get_clientsession(self.hass)
response = yield from websession.get(url, params=params)
response = await websession.get(url, params=params)
if response.status == 200:
data = yield from response.json()
data = await response.json()
else:
_LOGGER.error(
"Query failed, response code: %s Full message: %s",
@ -124,11 +122,10 @@ class Volumio(MediaPlayerDevice):
_LOGGER.error("Received invalid response: %s", data)
return False
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Update state."""
resp = yield from self.send_volumio_msg('getState')
yield from self._async_update_playlists()
resp = await self.send_volumio_msg('getState')
await self._async_update_playlists()
if resp is False:
return
self._state = resp.copy()

View File

@ -49,18 +49,16 @@ NOTIFY_SERVICE_SCHEMA = vol.Schema({
})
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the notify services."""
targets = {}
@asyncio.coroutine
def async_setup_platform(p_type, p_config=None, discovery_info=None):
async def async_setup_platform(p_type, p_config=None, discovery_info=None):
"""Set up a notify platform."""
if p_config is None:
p_config = {}
platform = yield from async_prepare_setup_platform(
platform = await async_prepare_setup_platform(
hass, config, DOMAIN, p_type)
if platform is None:
@ -71,10 +69,10 @@ def async_setup(hass, config):
notify_service = None
try:
if hasattr(platform, 'async_get_service'):
notify_service = yield from \
notify_service = await \
platform.async_get_service(hass, p_config, discovery_info)
elif hasattr(platform, 'get_service'):
notify_service = yield from hass.async_add_job(
notify_service = await hass.async_add_job(
platform.get_service, hass, p_config, discovery_info)
else:
raise HomeAssistantError("Invalid notify platform.")
@ -97,8 +95,7 @@ def async_setup(hass, config):
if discovery_info is None:
discovery_info = {}
@asyncio.coroutine
def async_notify_message(service):
async def async_notify_message(service):
"""Handle sending notification message service calls."""
kwargs = {}
message = service.data[ATTR_MESSAGE]
@ -117,7 +114,7 @@ def async_setup(hass, config):
kwargs[ATTR_MESSAGE] = message.async_render()
kwargs[ATTR_DATA] = service.data.get(ATTR_DATA)
yield from notify_service.async_send_message(**kwargs)
await notify_service.async_send_message(**kwargs)
if hasattr(notify_service, 'targets'):
platform_name = (
@ -147,12 +144,11 @@ def async_setup(hass, config):
in config_per_platform(config, DOMAIN)]
if setup_tasks:
yield from asyncio.wait(setup_tasks, loop=hass.loop)
await asyncio.wait(setup_tasks, loop=hass.loop)
@asyncio.coroutine
def async_platform_discovered(platform, info):
async def async_platform_discovered(platform, info):
"""Handle for discovered platform."""
yield from async_setup_platform(platform, discovery_info=info)
await async_setup_platform(platform, discovery_info=info)
discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered)

View File

@ -4,7 +4,6 @@ Discord platform for notify component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.discord/
"""
import asyncio
import logging
import voluptuous as vol
@ -39,8 +38,7 @@ class DiscordNotificationService(BaseNotificationService):
self.token = token
self.hass = hass
@asyncio.coroutine
def async_send_message(self, message, **kwargs):
async def async_send_message(self, message, **kwargs):
"""Login to Discord, send message to channel(s) and log out."""
import discord
discord_bot = discord.Client(loop=self.hass.loop)
@ -51,8 +49,7 @@ class DiscordNotificationService(BaseNotificationService):
# pylint: disable=unused-variable
@discord_bot.event
@asyncio.coroutine
def on_ready():
async def on_ready():
"""Send the messages when the bot is ready."""
try:
data = kwargs.get(ATTR_DATA)
@ -60,14 +57,14 @@ class DiscordNotificationService(BaseNotificationService):
images = data.get(ATTR_IMAGES)
for channelid in kwargs[ATTR_TARGET]:
channel = discord.Object(id=channelid)
yield from discord_bot.send_message(channel, message)
await discord_bot.send_message(channel, message)
if images:
for anum, f_name in enumerate(images):
yield from discord_bot.send_file(channel, f_name)
await discord_bot.send_file(channel, f_name)
except (discord.errors.HTTPException,
discord.errors.NotFound) as error:
_LOGGER.warning("Communication error: %s", error)
yield from discord_bot.logout()
yield from discord_bot.close()
await discord_bot.logout()
await discord_bot.close()
yield from discord_bot.start(self.token)
await discord_bot.start(self.token)

View File

@ -41,8 +41,7 @@ def update(input_dict, update_source):
return input_dict
@asyncio.coroutine
def async_get_service(hass, config, discovery_info=None):
async def async_get_service(hass, config, discovery_info=None):
"""Get the Group notification service."""
return GroupNotifyPlatform(hass, config.get(CONF_SERVICES))
@ -55,8 +54,7 @@ class GroupNotifyPlatform(BaseNotificationService):
self.hass = hass
self.entities = entities
@asyncio.coroutine
def async_send_message(self, message="", **kwargs):
async def async_send_message(self, message="", **kwargs):
"""Send message to all entities in the group."""
payload = {ATTR_MESSAGE: message}
payload.update({key: val for key, val in kwargs.items() if val})
@ -70,4 +68,4 @@ class GroupNotifyPlatform(BaseNotificationService):
DOMAIN, entity.get(ATTR_SERVICE), sending_payload))
if tasks:
yield from asyncio.wait(tasks, loop=self.hass.loop)
await asyncio.wait(tasks, loop=self.hass.loop)

View File

@ -4,7 +4,6 @@ Kodi notification service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.kodi/
"""
import asyncio
import logging
import aiohttp
@ -38,8 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
ATTR_DISPLAYTIME = 'displaytime'
@asyncio.coroutine
def async_get_service(hass, config, discovery_info=None):
async def async_get_service(hass, config, discovery_info=None):
"""Return the notify service."""
url = '{}:{}'.format(config.get(CONF_HOST), config.get(CONF_PORT))
@ -86,8 +84,7 @@ class KodiNotificationService(BaseNotificationService):
self._server = jsonrpc_async.Server(self._url, **kwargs)
@asyncio.coroutine
def async_send_message(self, message="", **kwargs):
async def async_send_message(self, message="", **kwargs):
"""Send a message to Kodi."""
import jsonrpc_async
try:
@ -96,7 +93,7 @@ class KodiNotificationService(BaseNotificationService):
displaytime = data.get(ATTR_DISPLAYTIME, 10000)
icon = data.get(ATTR_ICON, "info")
title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
yield from self._server.GUI.ShowNotification(
await self._server.GUI.ShowNotification(
title, message, icon, displaytime)
except jsonrpc_async.TransportError:

View File

@ -25,8 +25,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
@asyncio.coroutine
def async_get_service(hass, config, discovery_info=None):
async def async_get_service(hass, config, discovery_info=None):
"""Get the Prowl notification service."""
return ProwlNotificationService(hass, config[CONF_API_KEY])
@ -39,8 +38,7 @@ class ProwlNotificationService(BaseNotificationService):
self._hass = hass
self._api_key = api_key
@asyncio.coroutine
def async_send_message(self, message, **kwargs):
async def async_send_message(self, message, **kwargs):
"""Send the message to the user."""
response = None
session = None
@ -59,8 +57,8 @@ class ProwlNotificationService(BaseNotificationService):
try:
with async_timeout.timeout(10, loop=self._hass.loop):
response = yield from session.post(url, data=payload)
result = yield from response.text()
response = await session.post(url, data=payload)
result = await response.text()
if response.status != 200 or 'error' in result:
_LOGGER.error("Prowl service returned http "