1
mirror of https://github.com/home-assistant/core synced 2024-09-12 15:16:21 +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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.anthemav/ https://home-assistant.io/components/media_player.anthemav/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -35,9 +34,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up our socket to the AVR.""" """Set up our socket to the AVR."""
import anthemav import anthemav
@ -53,7 +51,7 @@ def async_setup_platform(hass, config, async_add_entities,
_LOGGER.info("Received update callback from AVR: %s", message) _LOGGER.info("Received update callback from AVR: %s", message)
hass.async_add_job(device.async_update_ha_state()) 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, host=host, port=port, loop=hass.loop,
update_callback=async_anthemav_update_callback) update_callback=async_anthemav_update_callback)
@ -136,28 +134,23 @@ class AnthemAVR(MediaPlayerDevice):
"""Return all active, configured inputs.""" """Return all active, configured inputs."""
return self._lookup('input_list', ["Unknown"]) return self._lookup('input_list', ["Unknown"])
@asyncio.coroutine async def async_select_source(self, source):
def async_select_source(self, source):
"""Change AVR to the designated source (by name).""" """Change AVR to the designated source (by name)."""
self._update_avr('input_name', source) self._update_avr('input_name', source)
@asyncio.coroutine async def async_turn_off(self):
def async_turn_off(self):
"""Turn AVR power off.""" """Turn AVR power off."""
self._update_avr('power', False) self._update_avr('power', False)
@asyncio.coroutine async def async_turn_on(self):
def async_turn_on(self):
"""Turn AVR power on.""" """Turn AVR power on."""
self._update_avr('power', True) self._update_avr('power', True)
@asyncio.coroutine async def async_set_volume_level(self, volume):
def async_set_volume_level(self, volume):
"""Set AVR volume (0 to 1).""" """Set AVR volume (0 to 1)."""
self._update_avr('volume_as_percentage', volume) self._update_avr('volume_as_percentage', volume)
@asyncio.coroutine async def async_mute_volume(self, mute):
def async_mute_volume(self, mute):
"""Engage AVR mute.""" """Engage AVR mute."""
self._update_avr('mute', 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.apple_tv/ https://home-assistant.io/components/media_player.apple_tv/
""" """
import asyncio
import logging import logging
from homeassistant.components.apple_tv import ( 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 SUPPORT_STOP | SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK
@asyncio.coroutine async def async_setup_platform(
def async_setup_platform(
hass, config, async_add_entities, discovery_info=None): hass, config, async_add_entities, discovery_info=None):
"""Set up the Apple TV platform.""" """Set up the Apple TV platform."""
if not discovery_info: if not discovery_info:
@ -71,8 +69,7 @@ class AppleTvDevice(MediaPlayerDevice):
self._power.listeners.append(self) self._power.listeners.append(self)
self.atv.push_updater.listener = self self.atv.push_updater.listener = self
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Handle when an entity is about to be added to Home Assistant.""" """Handle when an entity is about to be added to Home Assistant."""
self._power.init() self._power.init()
@ -164,10 +161,9 @@ class AppleTvDevice(MediaPlayerDevice):
if state in (STATE_PLAYING, STATE_PAUSED): if state in (STATE_PLAYING, STATE_PAUSED):
return dt_util.utcnow() return dt_util.utcnow()
@asyncio.coroutine async def async_play_media(self, media_type, media_id, **kwargs):
def async_play_media(self, media_type, media_id, **kwargs):
"""Send the play_media command to the media player.""" """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 @property
def media_image_hash(self): def media_image_hash(self):
@ -176,12 +172,11 @@ class AppleTvDevice(MediaPlayerDevice):
if self._playing and state not in [STATE_OFF, STATE_IDLE]: if self._playing and state not in [STATE_OFF, STATE_IDLE]:
return self._playing.hash return self._playing.hash
@asyncio.coroutine async def async_get_media_image(self):
def async_get_media_image(self):
"""Fetch media image of current playing image.""" """Fetch media image of current playing image."""
state = self.state state = self.state
if self._playing and state not in [STATE_OFF, STATE_IDLE]: 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 return None, None
@ -201,13 +196,11 @@ class AppleTvDevice(MediaPlayerDevice):
"""Flag media player features that are supported.""" """Flag media player features that are supported."""
return SUPPORT_APPLE_TV return SUPPORT_APPLE_TV
@asyncio.coroutine async def async_turn_on(self):
def async_turn_on(self):
"""Turn the media player on.""" """Turn the media player on."""
self._power.set_power_on(True) self._power.set_power_on(True)
@asyncio.coroutine async def async_turn_off(self):
def async_turn_off(self):
"""Turn the media player off.""" """Turn the media player off."""
self._playing = None self._playing = None
self._power.set_power_on(False) 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.clementine/ https://home-assistant.io/components/media_player.clementine/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
import time import time
@ -169,8 +168,7 @@ class ClementineDevice(MediaPlayerDevice):
return None return None
@asyncio.coroutine async def async_get_media_image(self):
def async_get_media_image(self):
"""Fetch media image of current playing image.""" """Fetch media image of current playing image."""
if self._client.current_track: if self._client.current_track:
image = bytes(self._client.current_track['art']) 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.emby/ https://home-assistant.io/components/media_player.emby/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -50,9 +49,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the Emby platform.""" """Set up the Emby platform."""
from pyemby import EmbyServer from pyemby import EmbyServer
@ -113,10 +111,9 @@ def async_setup_platform(hass, config, async_add_entities,
"""Start Emby connection.""" """Start Emby connection."""
emby.start() emby.start()
@asyncio.coroutine async def stop_emby(event):
def stop_emby(event):
"""Stop Emby connection.""" """Stop Emby connection."""
yield from emby.stop() await emby.stop()
emby.add_new_devices_callback(device_update_callback) emby.add_new_devices_callback(device_update_callback)
emby.add_stale_devices_callback(device_removal_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_last_position = None
self.media_status_received = None self.media_status_received = None
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callback.""" """Register callback."""
self.emby.add_update_callback( self.emby.add_update_callback(
self.async_update_callback, self.device_id) 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.frontier_silicon/ https://home-assistant.io/components/media_player.frontier_silicon/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -41,8 +40,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(
def async_setup_platform(
hass, config, async_add_entities, discovery_info=None): hass, config, async_add_entities, discovery_info=None):
"""Set up the Frontier Silicon platform.""" """Set up the Frontier Silicon platform."""
import requests import requests
@ -157,18 +155,17 @@ class AFSAPIDevice(MediaPlayerDevice):
"""Image url of current playing media.""" """Image url of current playing media."""
return self._media_image_url return self._media_image_url
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Get the latest date and update device state.""" """Get the latest date and update device state."""
fs_device = self.fs_device fs_device = self.fs_device
if not self._name: 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: 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 = { self._state = {
'playing': STATE_PLAYING, 'playing': STATE_PLAYING,
'paused': STATE_PAUSED, 'paused': STATE_PAUSED,
@ -178,16 +175,16 @@ class AFSAPIDevice(MediaPlayerDevice):
}.get(status, STATE_UNKNOWN) }.get(status, STATE_UNKNOWN)
if self._state != STATE_OFF: if self._state != STATE_OFF:
info_name = yield from fs_device.get_play_name() info_name = await fs_device.get_play_name()
info_text = yield from fs_device.get_play_text() info_text = await fs_device.get_play_text()
self._title = ' - '.join(filter(None, [info_name, info_text])) self._title = ' - '.join(filter(None, [info_name, info_text]))
self._artist = yield from fs_device.get_play_artist() self._artist = await fs_device.get_play_artist()
self._album_name = yield from fs_device.get_play_album() self._album_name = await fs_device.get_play_album()
self._source = yield from fs_device.get_mode() self._source = await fs_device.get_mode()
self._mute = yield from fs_device.get_mute() self._mute = await fs_device.get_mute()
self._media_image_url = yield from fs_device.get_play_graphic() self._media_image_url = await fs_device.get_play_graphic()
else: else:
self._title = None self._title = None
self._artist = None self._artist = None
@ -199,48 +196,40 @@ class AFSAPIDevice(MediaPlayerDevice):
# Management actions # Management actions
# power control # power control
@asyncio.coroutine async def async_turn_on(self):
def async_turn_on(self):
"""Turn on the device.""" """Turn on the device."""
yield from self.fs_device.set_power(True) await self.fs_device.set_power(True)
@asyncio.coroutine async def async_turn_off(self):
def async_turn_off(self):
"""Turn off the device.""" """Turn off the device."""
yield from self.fs_device.set_power(False) await self.fs_device.set_power(False)
@asyncio.coroutine async def async_media_play(self):
def async_media_play(self):
"""Send play command.""" """Send play command."""
yield from self.fs_device.play() await self.fs_device.play()
@asyncio.coroutine async def async_media_pause(self):
def async_media_pause(self):
"""Send pause command.""" """Send pause command."""
yield from self.fs_device.pause() await self.fs_device.pause()
@asyncio.coroutine async def async_media_play_pause(self):
def async_media_play_pause(self):
"""Send play/pause command.""" """Send play/pause command."""
if 'playing' in self._state: if 'playing' in self._state:
yield from self.fs_device.pause() await self.fs_device.pause()
else: else:
yield from self.fs_device.play() await self.fs_device.play()
@asyncio.coroutine async def async_media_stop(self):
def async_media_stop(self):
"""Send play/pause command.""" """Send play/pause command."""
yield from self.fs_device.pause() await self.fs_device.pause()
@asyncio.coroutine async def async_media_previous_track(self):
def async_media_previous_track(self):
"""Send previous track command (results in rewind).""" """Send previous track command (results in rewind)."""
yield from self.fs_device.rewind() await self.fs_device.rewind()
@asyncio.coroutine async def async_media_next_track(self):
def async_media_next_track(self):
"""Send next track command (results in fast-forward).""" """Send next track command (results in fast-forward)."""
yield from self.fs_device.forward() await self.fs_device.forward()
# mute # mute
@property @property
@ -248,30 +237,25 @@ class AFSAPIDevice(MediaPlayerDevice):
"""Boolean if volume is currently muted.""" """Boolean if volume is currently muted."""
return self._mute return self._mute
@asyncio.coroutine async def async_mute_volume(self, mute):
def async_mute_volume(self, mute):
"""Send mute command.""" """Send mute command."""
yield from self.fs_device.set_mute(mute) await self.fs_device.set_mute(mute)
# volume # volume
@asyncio.coroutine async def async_volume_up(self):
def async_volume_up(self):
"""Send volume up command.""" """Send volume up command."""
volume = yield from self.fs_device.get_volume() volume = await self.fs_device.get_volume()
yield from self.fs_device.set_volume(volume+1) await self.fs_device.set_volume(volume+1)
@asyncio.coroutine async def async_volume_down(self):
def async_volume_down(self):
"""Send volume down command.""" """Send volume down command."""
volume = yield from self.fs_device.get_volume() volume = await self.fs_device.get_volume()
yield from self.fs_device.set_volume(volume-1) await self.fs_device.set_volume(volume-1)
@asyncio.coroutine async def async_set_volume_level(self, volume):
def async_set_volume_level(self, volume):
"""Set volume command.""" """Set volume command."""
yield from self.fs_device.set_volume(volume) await self.fs_device.set_volume(volume)
@asyncio.coroutine async def async_select_source(self, source):
def async_select_source(self, source):
"""Select input 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 return turn_off_action
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the Kodi platform.""" """Set up the Kodi platform."""
if DATA_KODI not in hass.data: if DATA_KODI not in hass.data:
hass.data[DATA_KODI] = dict() 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 hass.data[DATA_KODI][ip_addr] = entity
async_add_entities([entity], update_before_add=True) async_add_entities([entity], update_before_add=True)
@asyncio.coroutine async def async_service_handler(service):
def async_service_handler(service):
"""Map services to methods on MediaPlayerDevice.""" """Map services to methods on MediaPlayerDevice."""
method = SERVICE_TO_METHOD.get(service.service) method = SERVICE_TO_METHOD.get(service.service)
if not method: if not method:
@ -230,7 +228,7 @@ def async_setup_platform(hass, config, async_add_entities,
update_tasks = [] update_tasks = []
for player in target_players: for player in target_players:
yield from getattr(player, method['method'])(**params) await getattr(player, method['method'])(**params)
for player in target_players: for player in target_players:
if player.should_poll: if player.should_poll:
@ -238,7 +236,7 @@ def async_setup_platform(hass, config, async_add_entities,
update_tasks.append(update_coro) update_tasks.append(update_coro)
if update_tasks: 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): if hass.services.has_service(DOMAIN, SERVICE_ADD_MEDIA):
return return
@ -253,12 +251,11 @@ def async_setup_platform(hass, config, async_add_entities,
def cmd(func): def cmd(func):
"""Catch command exceptions.""" """Catch command exceptions."""
@wraps(func) @wraps(func)
@asyncio.coroutine async def wrapper(obj, *args, **kwargs):
def wrapper(obj, *args, **kwargs):
"""Wrap all command methods.""" """Wrap all command methods."""
import jsonrpc_base import jsonrpc_base
try: try:
yield from func(obj, *args, **kwargs) await func(obj, *args, **kwargs)
except jsonrpc_base.jsonrpc.TransportError as exc: except jsonrpc_base.jsonrpc.TransportError as exc:
# If Kodi is off, we expect calls to fail. # If Kodi is off, we expect calls to fail.
if obj.state == STATE_OFF: if obj.state == STATE_OFF:
@ -392,12 +389,11 @@ class KodiDevice(MediaPlayerDevice):
self._app_properties = {} self._app_properties = {}
self.hass.async_add_job(self._ws_server.close()) self.hass.async_add_job(self._ws_server.close())
@asyncio.coroutine async def _get_players(self):
def _get_players(self):
"""Return the active player objects or None.""" """Return the active player objects or None."""
import jsonrpc_base import jsonrpc_base
try: try:
return (yield from self.server.Player.GetActivePlayers()) return await self.server.Player.GetActivePlayers()
except jsonrpc_base.jsonrpc.TransportError: except jsonrpc_base.jsonrpc.TransportError:
if self._players is not None: if self._players is not None:
_LOGGER.info("Unable to fetch kodi data") _LOGGER.info("Unable to fetch kodi data")
@ -423,23 +419,21 @@ class KodiDevice(MediaPlayerDevice):
return STATE_PLAYING return STATE_PLAYING
@asyncio.coroutine async def async_ws_connect(self):
def async_ws_connect(self):
"""Connect to Kodi via websocket protocol.""" """Connect to Kodi via websocket protocol."""
import jsonrpc_base import jsonrpc_base
try: 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: except jsonrpc_base.jsonrpc.TransportError:
_LOGGER.info("Unable to connect to Kodi via websocket") _LOGGER.info("Unable to connect to Kodi via websocket")
_LOGGER.debug( _LOGGER.debug(
"Unable to connect to Kodi via websocket", exc_info=True) "Unable to connect to Kodi via websocket", exc_info=True)
return return
@asyncio.coroutine async def ws_loop_wrapper():
def ws_loop_wrapper():
"""Catch exceptions from the websocket loop task.""" """Catch exceptions from the websocket loop task."""
try: try:
yield from ws_loop_future await ws_loop_future
except jsonrpc_base.TransportError: except jsonrpc_base.TransportError:
# Kodi abruptly ends ws connection when exiting. We will try # Kodi abruptly ends ws connection when exiting. We will try
# to reconnect on the next poll. # to reconnect on the next poll.
@ -451,10 +445,9 @@ class KodiDevice(MediaPlayerDevice):
# run until the websocket connection is closed. # run until the websocket connection is closed.
self.hass.loop.create_task(ws_loop_wrapper()) self.hass.loop.create_task(ws_loop_wrapper())
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Retrieve latest state.""" """Retrieve latest state."""
self._players = yield from self._get_players() self._players = await self._get_players()
if self._players is None: if self._players is None:
self._properties = {} self._properties = {}
@ -466,7 +459,7 @@ class KodiDevice(MediaPlayerDevice):
self.hass.async_add_job(self.async_ws_connect()) self.hass.async_add_job(self.async_ws_connect())
self._app_properties = \ self._app_properties = \
yield from self.server.Application.GetProperties( await self.server.Application.GetProperties(
['volume', 'muted'] ['volume', 'muted']
) )
@ -475,12 +468,12 @@ class KodiDevice(MediaPlayerDevice):
assert isinstance(player_id, int) assert isinstance(player_id, int)
self._properties = yield from self.server.Player.GetProperties( self._properties = await self.server.Player.GetProperties(
player_id, player_id,
['time', 'totaltime', 'speed', 'live'] ['time', 'totaltime', 'speed', 'live']
) )
self._item = (yield from self.server.Player.GetItem( self._item = (await self.server.Player.GetItem(
player_id, player_id,
['title', 'file', 'uniqueid', 'thumbnail', 'artist', ['title', 'file', 'uniqueid', 'thumbnail', 'artist',
'albumartist', 'showtitle', 'album', 'season', 'episode'] 'albumartist', 'showtitle', 'album', 'season', 'episode']
@ -622,38 +615,34 @@ class KodiDevice(MediaPlayerDevice):
return supported_features return supported_features
@cmd @cmd
@asyncio.coroutine async def async_turn_on(self):
def async_turn_on(self):
"""Execute turn_on_action to turn on media player.""" """Execute turn_on_action to turn on media player."""
if self._turn_on_action is not None: 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}) variables={"entity_id": self.entity_id})
else: else:
_LOGGER.warning("turn_on requested but turn_on_action is none") _LOGGER.warning("turn_on requested but turn_on_action is none")
@cmd @cmd
@asyncio.coroutine async def async_turn_off(self):
def async_turn_off(self):
"""Execute turn_off_action to turn off media player.""" """Execute turn_off_action to turn off media player."""
if self._turn_off_action is not None: 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}) variables={"entity_id": self.entity_id})
else: else:
_LOGGER.warning("turn_off requested but turn_off_action is none") _LOGGER.warning("turn_off requested but turn_off_action is none")
@cmd @cmd
@asyncio.coroutine async def async_volume_up(self):
def async_volume_up(self):
"""Volume up the media player.""" """Volume up the media player."""
assert ( assert (
yield from self.server.Input.ExecuteAction('volumeup')) == 'OK' await self.server.Input.ExecuteAction('volumeup')) == 'OK'
@cmd @cmd
@asyncio.coroutine async def async_volume_down(self):
def async_volume_down(self):
"""Volume down the media player.""" """Volume down the media player."""
assert ( assert (
yield from self.server.Input.ExecuteAction('volumedown')) == 'OK' await self.server.Input.ExecuteAction('volumedown')) == 'OK'
@cmd @cmd
def async_set_volume_level(self, volume): def async_set_volume_level(self, volume):
@ -671,13 +660,12 @@ class KodiDevice(MediaPlayerDevice):
""" """
return self.server.Application.SetMute(mute) return self.server.Application.SetMute(mute)
@asyncio.coroutine async def async_set_play_state(self, state):
def async_set_play_state(self, state):
"""Handle play/pause/toggle.""" """Handle play/pause/toggle."""
players = yield from self._get_players() players = await self._get_players()
if players is not None and players: if players is not None and players:
yield from self.server.Player.PlayPause( await self.server.Player.PlayPause(
players[0]['playerid'], state) players[0]['playerid'], state)
@cmd @cmd
@ -705,26 +693,24 @@ class KodiDevice(MediaPlayerDevice):
return self.async_set_play_state(False) return self.async_set_play_state(False)
@cmd @cmd
@asyncio.coroutine async def async_media_stop(self):
def async_media_stop(self):
"""Stop the media player.""" """Stop the media player."""
players = yield from self._get_players() players = await self._get_players()
if players: if players:
yield from self.server.Player.Stop(players[0]['playerid']) await self.server.Player.Stop(players[0]['playerid'])
@asyncio.coroutine async def _goto(self, direction):
def _goto(self, direction):
"""Handle for previous/next track.""" """Handle for previous/next track."""
players = yield from self._get_players() players = await self._get_players()
if players: if players:
if direction == 'previous': if direction == 'previous':
# First seek to position 0. Kodi goes to the beginning of the # First seek to position 0. Kodi goes to the beginning of the
# current track if the current track is not at the beginning. # 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) players[0]['playerid'], direction)
@cmd @cmd
@ -744,10 +730,9 @@ class KodiDevice(MediaPlayerDevice):
return self._goto('previous') return self._goto('previous')
@cmd @cmd
@asyncio.coroutine async def async_media_seek(self, position):
def async_media_seek(self, position):
"""Send seek command.""" """Send seek command."""
players = yield from self._get_players() players = await self._get_players()
time = {} time = {}
@ -763,7 +748,7 @@ class KodiDevice(MediaPlayerDevice):
time['hours'] = int(position) time['hours'] = int(position)
if players: if players:
yield from self.server.Player.Seek(players[0]['playerid'], time) await self.server.Player.Seek(players[0]['playerid'], time)
@cmd @cmd
def async_play_media(self, media_type, media_id, **kwargs): def async_play_media(self, media_type, media_id, **kwargs):
@ -781,22 +766,20 @@ class KodiDevice(MediaPlayerDevice):
return self.server.Player.Open( return self.server.Player.Open(
{"item": {"file": str(media_id)}}) {"item": {"file": str(media_id)}})
@asyncio.coroutine async def async_set_shuffle(self, shuffle):
def async_set_shuffle(self, shuffle):
"""Set shuffle mode, for the first player.""" """Set shuffle mode, for the first player."""
if not self._players: if not self._players:
raise RuntimeError("Error: No active player.") raise RuntimeError("Error: No active player.")
yield from self.server.Player.SetShuffle( await self.server.Player.SetShuffle(
{"playerid": self._players[0]['playerid'], "shuffle": shuffle}) {"playerid": self._players[0]['playerid'], "shuffle": shuffle})
@asyncio.coroutine async def async_call_method(self, method, **kwargs):
def async_call_method(self, method, **kwargs):
"""Run Kodi JSONRPC API method with params.""" """Run Kodi JSONRPC API method with params."""
import jsonrpc_base import jsonrpc_base
_LOGGER.debug("Run API method %s, kwargs=%s", method, kwargs) _LOGGER.debug("Run API method %s, kwargs=%s", method, kwargs)
result_ok = False result_ok = False
try: try:
result = yield from getattr(self.server, method)(**kwargs) result = await getattr(self.server, method)(**kwargs)
result_ok = True result_ok = True
except jsonrpc_base.jsonrpc.ProtocolError as exc: except jsonrpc_base.jsonrpc.ProtocolError as exc:
result = exc.args[2]['error'] result = exc.args[2]['error']
@ -817,8 +800,7 @@ class KodiDevice(MediaPlayerDevice):
event_data=event_data) event_data=event_data)
return result return result
@asyncio.coroutine async def async_add_media_to_playlist(
def async_add_media_to_playlist(
self, media_type, media_id=None, media_name='ALL', artist_name=''): self, media_type, media_id=None, media_name='ALL', artist_name=''):
"""Add a media to default playlist (i.e. playlistid=0). """Add a media to default playlist (i.e. playlistid=0).
@ -832,7 +814,7 @@ class KodiDevice(MediaPlayerDevice):
params = {"playlistid": 0} params = {"playlistid": 0}
if media_type == "SONG": if media_type == "SONG":
if media_id is None: if media_id is None:
media_id = yield from self.async_find_song( media_id = await self.async_find_song(
media_name, artist_name) media_name, artist_name)
if media_id: if media_id:
params["item"] = {"songid": int(media_id)} params["item"] = {"songid": int(media_id)}
@ -840,10 +822,10 @@ class KodiDevice(MediaPlayerDevice):
elif media_type == "ALBUM": elif media_type == "ALBUM":
if media_id is None: if media_id is None:
if media_name == "ALL": if media_name == "ALL":
yield from self.async_add_all_albums(artist_name) await self.async_add_all_albums(artist_name)
return return
media_id = yield from self.async_find_album( media_id = await self.async_find_album(
media_name, artist_name) media_name, artist_name)
if media_id: if media_id:
params["item"] = {"albumid": int(media_id)} params["item"] = {"albumid": int(media_id)}
@ -853,7 +835,7 @@ class KodiDevice(MediaPlayerDevice):
if media_id is not None: if media_id is not None:
try: try:
yield from self.server.Playlist.Add(params) await self.server.Playlist.Add(params)
except jsonrpc_base.jsonrpc.ProtocolError as exc: except jsonrpc_base.jsonrpc.ProtocolError as exc:
result = exc.args[2]['error'] result = exc.args[2]['error']
_LOGGER.error("Run API method %s.Playlist.Add(%s) error: %s", _LOGGER.error("Run API method %s.Playlist.Add(%s) error: %s",
@ -864,43 +846,38 @@ class KodiDevice(MediaPlayerDevice):
else: else:
_LOGGER.warning("No media detected for Playlist.Add") _LOGGER.warning("No media detected for Playlist.Add")
@asyncio.coroutine async def async_add_all_albums(self, artist_name):
def async_add_all_albums(self, artist_name):
"""Add all albums of an artist to default playlist (i.e. playlistid=0). """Add all albums of an artist to default playlist (i.e. playlistid=0).
The artist is specified in terms of name. 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']: for alb in albums['albums']:
yield from self.server.Playlist.Add( await self.server.Playlist.Add(
{"playlistid": 0, "item": {"albumid": int(alb['albumid'])}}) {"playlistid": 0, "item": {"albumid": int(alb['albumid'])}})
@asyncio.coroutine async def async_clear_playlist(self):
def async_clear_playlist(self):
"""Clear default playlist (i.e. playlistid=0).""" """Clear default playlist (i.e. playlistid=0)."""
return self.server.Playlist.Clear({"playlistid": 0}) return self.server.Playlist.Clear({"playlistid": 0})
@asyncio.coroutine async def async_get_artists(self):
def async_get_artists(self):
"""Get artists list.""" """Get artists list."""
return (yield from self.server.AudioLibrary.GetArtists()) return await self.server.AudioLibrary.GetArtists()
@asyncio.coroutine async def async_get_albums(self, artist_id=None):
def async_get_albums(self, artist_id=None):
"""Get albums list.""" """Get albums list."""
if artist_id is None: 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)}})) {"filter": {"artistid": int(artist_id)}}))
@asyncio.coroutine async def async_find_artist(self, artist_name):
def async_find_artist(self, artist_name):
"""Find artist by name.""" """Find artist by name."""
artists = yield from self.async_get_artists() artists = await self.async_get_artists()
try: try:
out = self._find( out = self._find(
artist_name, [a['artist'] for a in artists['artists']]) 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) _LOGGER.warning("No artists were found: %s", artist_name)
return None return None
@asyncio.coroutine async def async_get_songs(self, artist_id=None):
def async_get_songs(self, artist_id=None):
"""Get songs list.""" """Get songs list."""
if artist_id is None: 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)}})) {"filter": {"artistid": int(artist_id)}}))
@asyncio.coroutine async def async_find_song(self, song_name, artist_name=''):
def async_find_song(self, song_name, artist_name=''):
"""Find song by name and optionally artist name.""" """Find song by name and optionally artist name."""
artist_id = None artist_id = None
if artist_name != '': 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: if songs['limits']['total'] == 0:
return None return None
out = self._find(song_name, [a['label'] for a in songs['songs']]) out = self._find(song_name, [a['label'] for a in songs['songs']])
return songs['songs'][out[0][0]]['songid'] return songs['songs'][out[0][0]]['songid']
@asyncio.coroutine async def async_find_album(self, album_name, artist_name=''):
def async_find_album(self, album_name, artist_name=''):
"""Find album by name and optionally artist name.""" """Find album by name and optionally artist name."""
artist_id = None artist_id = None
if artist_name != '': 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: try:
out = self._find( out = self._find(
album_name, [a['label'] for a in albums['albums']]) 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.liveboxplaytv/ https://home-assistant.io/components/media_player.liveboxplaytv/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
@ -44,9 +43,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the Orange Livebox Play TV platform.""" """Set up the Orange Livebox Play TV platform."""
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
port = config.get(CONF_PORT) port = config.get(CONF_PORT)
@ -83,8 +81,7 @@ class LiveboxPlayTvDevice(MediaPlayerDevice):
self._media_image_url = None self._media_image_url = None
self._media_last_updated = None self._media_last_updated = None
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Retrieve the latest data.""" """Retrieve the latest data."""
import pyteleloisirs import pyteleloisirs
try: try:
@ -95,7 +92,7 @@ class LiveboxPlayTvDevice(MediaPlayerDevice):
channel = self._client.channel channel = self._client.channel
if channel is not None: if channel is not None:
self._current_channel = channel self._current_channel = channel
program = yield from \ program = await \
self._client.async_get_current_program() self._client.async_get_current_program()
if program and self._current_program != program.get('name'): if program and self._current_program != program.get('name'):
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 # Set media image to current program if a thumbnail is
# available. Otherwise we'll use the channel's image. # available. Otherwise we'll use the channel's image.
img_size = 800 img_size = 800
prg_img_url = yield from \ prg_img_url = await \
self._client.async_get_current_program_image(img_size) self._client.async_get_current_program_image(img_size)
if prg_img_url: if prg_img_url:
self._media_image_url = 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.russound_rio/ https://home-assistant.io/components/media_player.russound_rio/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -33,8 +32,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(
def async_setup_platform(
hass, config, async_add_entities, discovery_info=None): hass, config, async_add_entities, discovery_info=None):
"""Set up the Russound RIO platform.""" """Set up the Russound RIO platform."""
from russound_rio import Russound from russound_rio import Russound
@ -44,15 +42,15 @@ def async_setup_platform(
russ = Russound(hass.loop, host, port) russ = Russound(hass.loop, host, port)
yield from russ.connect() await russ.connect()
# Discover sources and zones # Discover sources and zones
sources = yield from russ.enumerate_sources() sources = await russ.enumerate_sources()
valid_zones = yield from russ.enumerate_zones() valid_zones = await russ.enumerate_zones()
devices = [] devices = []
for zone_id, name in valid_zones: 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) dev = RussoundZoneDevice(russ, zone_id, name, sources)
devices.append(dev) devices.append(dev)
@ -108,8 +106,7 @@ class RussoundZoneDevice(MediaPlayerDevice):
if source_id == current: if source_id == current:
self.schedule_update_ha_state() self.schedule_update_ha_state()
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callback handlers.""" """Register callback handlers."""
self._russ.add_zone_callback(self._zone_callback_handler) self._russ.add_zone_callback(self._zone_callback_handler)
self._russ.add_source_callback(self._source_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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.snapcast/ https://home-assistant.io/components/media_player.snapcast/
""" """
import asyncio
import logging import logging
import socket import socket
@ -46,17 +45,15 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
discovery_info=None):
"""Set up the Snapcast platform.""" """Set up the Snapcast platform."""
import snapcast.control import snapcast.control
from snapcast.control.server import CONTROL_PORT from snapcast.control.server import CONTROL_PORT
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
port = config.get(CONF_PORT, CONTROL_PORT) port = config.get(CONF_PORT, CONTROL_PORT)
@asyncio.coroutine async def _handle_service(service):
def _handle_service(service):
"""Handle services.""" """Handle services."""
entity_ids = service.data.get(ATTR_ENTITY_ID) entity_ids = service.data.get(ATTR_ENTITY_ID)
devices = [device for device in hass.data[DATA_KEY] 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: if service.service == SERVICE_SNAPSHOT:
device.snapshot() device.snapshot()
elif service.service == SERVICE_RESTORE: elif service.service == SERVICE_RESTORE:
yield from device.async_restore() await device.async_restore()
hass.services.async_register( hass.services.async_register(
DOMAIN, SERVICE_SNAPSHOT, _handle_service, schema=SERVICE_SCHEMA) 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) DOMAIN, SERVICE_RESTORE, _handle_service, schema=SERVICE_SCHEMA)
try: try:
server = yield from snapcast.control.create_server( server = await snapcast.control.create_server(
hass.loop, host, port, reconnect=True) hass.loop, host, port, reconnect=True)
except socket.gaierror: except socket.gaierror:
_LOGGER.error("Could not connect to Snapcast server at %s:%d", _LOGGER.error("Could not connect to Snapcast server at %s:%d",
@ -157,34 +154,30 @@ class SnapcastGroupDevice(MediaPlayerDevice):
"""Do not poll for state.""" """Do not poll for state."""
return False return False
@asyncio.coroutine async def async_select_source(self, source):
def async_select_source(self, source):
"""Set input source.""" """Set input source."""
streams = self._group.streams_by_name() streams = self._group.streams_by_name()
if source in streams: 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() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_mute_volume(self, mute):
def async_mute_volume(self, mute):
"""Send the mute command.""" """Send the mute command."""
yield from self._group.set_muted(mute) await self._group.set_muted(mute)
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_set_volume_level(self, volume):
def async_set_volume_level(self, volume):
"""Set the volume level.""" """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() self.async_schedule_update_ha_state()
def snapshot(self): def snapshot(self):
"""Snapshot the group state.""" """Snapshot the group state."""
self._group.snapshot() self._group.snapshot()
@asyncio.coroutine async def async_restore(self):
def async_restore(self):
"""Restore the group state.""" """Restore the group state."""
yield from self._group.restore() await self._group.restore()
class SnapcastClientDevice(MediaPlayerDevice): class SnapcastClientDevice(MediaPlayerDevice):
@ -246,23 +239,20 @@ class SnapcastClientDevice(MediaPlayerDevice):
"""Do not poll for state.""" """Do not poll for state."""
return False return False
@asyncio.coroutine async def async_mute_volume(self, mute):
def async_mute_volume(self, mute):
"""Send the mute command.""" """Send the mute command."""
yield from self._client.set_muted(mute) await self._client.set_muted(mute)
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_set_volume_level(self, volume):
def async_set_volume_level(self, volume):
"""Set the volume level.""" """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() self.async_schedule_update_ha_state()
def snapshot(self): def snapshot(self):
"""Snapshot the client state.""" """Snapshot the client state."""
self._client.snapshot() self._client.snapshot()
@asyncio.coroutine async def async_restore(self):
def async_restore(self):
"""Restore the client state.""" """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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.sonos/ https://home-assistant.io/components/media_player.sonos/
""" """
import asyncio
import datetime import datetime
import functools as ft import functools as ft
import logging import logging
@ -364,8 +363,7 @@ class SonosDevice(MediaPlayerDevice):
self._set_basic_information() self._set_basic_information()
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Subscribe sonos events.""" """Subscribe sonos events."""
self.hass.data[DATA_SONOS].devices.append(self) self.hass.data[DATA_SONOS].devices.append(self)
self.hass.async_add_job(self._subscribe_to_player_events) self.hass.async_add_job(self._subscribe_to_player_events)

View File

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

View File

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

View File

@ -49,18 +49,16 @@ NOTIFY_SERVICE_SCHEMA = vol.Schema({
}) })
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the notify services.""" """Set up the notify services."""
targets = {} targets = {}
@asyncio.coroutine async def async_setup_platform(p_type, p_config=None, discovery_info=None):
def async_setup_platform(p_type, p_config=None, discovery_info=None):
"""Set up a notify platform.""" """Set up a notify platform."""
if p_config is None: if p_config is None:
p_config = {} p_config = {}
platform = yield from async_prepare_setup_platform( platform = await async_prepare_setup_platform(
hass, config, DOMAIN, p_type) hass, config, DOMAIN, p_type)
if platform is None: if platform is None:
@ -71,10 +69,10 @@ def async_setup(hass, config):
notify_service = None notify_service = None
try: try:
if hasattr(platform, 'async_get_service'): if hasattr(platform, 'async_get_service'):
notify_service = yield from \ notify_service = await \
platform.async_get_service(hass, p_config, discovery_info) platform.async_get_service(hass, p_config, discovery_info)
elif hasattr(platform, 'get_service'): 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) platform.get_service, hass, p_config, discovery_info)
else: else:
raise HomeAssistantError("Invalid notify platform.") raise HomeAssistantError("Invalid notify platform.")
@ -97,8 +95,7 @@ def async_setup(hass, config):
if discovery_info is None: if discovery_info is None:
discovery_info = {} discovery_info = {}
@asyncio.coroutine async def async_notify_message(service):
def async_notify_message(service):
"""Handle sending notification message service calls.""" """Handle sending notification message service calls."""
kwargs = {} kwargs = {}
message = service.data[ATTR_MESSAGE] message = service.data[ATTR_MESSAGE]
@ -117,7 +114,7 @@ def async_setup(hass, config):
kwargs[ATTR_MESSAGE] = message.async_render() kwargs[ATTR_MESSAGE] = message.async_render()
kwargs[ATTR_DATA] = service.data.get(ATTR_DATA) 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'): if hasattr(notify_service, 'targets'):
platform_name = ( platform_name = (
@ -147,12 +144,11 @@ def async_setup(hass, config):
in config_per_platform(config, DOMAIN)] in config_per_platform(config, DOMAIN)]
if setup_tasks: if setup_tasks:
yield from asyncio.wait(setup_tasks, loop=hass.loop) await asyncio.wait(setup_tasks, loop=hass.loop)
@asyncio.coroutine async def async_platform_discovered(platform, info):
def async_platform_discovered(platform, info):
"""Handle for discovered platform.""" """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) 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.discord/ https://home-assistant.io/components/notify.discord/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -39,8 +38,7 @@ class DiscordNotificationService(BaseNotificationService):
self.token = token self.token = token
self.hass = hass self.hass = hass
@asyncio.coroutine async def async_send_message(self, message, **kwargs):
def async_send_message(self, message, **kwargs):
"""Login to Discord, send message to channel(s) and log out.""" """Login to Discord, send message to channel(s) and log out."""
import discord import discord
discord_bot = discord.Client(loop=self.hass.loop) discord_bot = discord.Client(loop=self.hass.loop)
@ -51,8 +49,7 @@ class DiscordNotificationService(BaseNotificationService):
# pylint: disable=unused-variable # pylint: disable=unused-variable
@discord_bot.event @discord_bot.event
@asyncio.coroutine async def on_ready():
def on_ready():
"""Send the messages when the bot is ready.""" """Send the messages when the bot is ready."""
try: try:
data = kwargs.get(ATTR_DATA) data = kwargs.get(ATTR_DATA)
@ -60,14 +57,14 @@ class DiscordNotificationService(BaseNotificationService):
images = data.get(ATTR_IMAGES) images = data.get(ATTR_IMAGES)
for channelid in kwargs[ATTR_TARGET]: for channelid in kwargs[ATTR_TARGET]:
channel = discord.Object(id=channelid) channel = discord.Object(id=channelid)
yield from discord_bot.send_message(channel, message) await discord_bot.send_message(channel, message)
if images: if images:
for anum, f_name in enumerate(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, except (discord.errors.HTTPException,
discord.errors.NotFound) as error: discord.errors.NotFound) as error:
_LOGGER.warning("Communication error: %s", error) _LOGGER.warning("Communication error: %s", error)
yield from discord_bot.logout() await discord_bot.logout()
yield from discord_bot.close() 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 return input_dict
@asyncio.coroutine async def async_get_service(hass, config, discovery_info=None):
def async_get_service(hass, config, discovery_info=None):
"""Get the Group notification service.""" """Get the Group notification service."""
return GroupNotifyPlatform(hass, config.get(CONF_SERVICES)) return GroupNotifyPlatform(hass, config.get(CONF_SERVICES))
@ -55,8 +54,7 @@ class GroupNotifyPlatform(BaseNotificationService):
self.hass = hass self.hass = hass
self.entities = entities self.entities = entities
@asyncio.coroutine async def async_send_message(self, message="", **kwargs):
def async_send_message(self, message="", **kwargs):
"""Send message to all entities in the group.""" """Send message to all entities in the group."""
payload = {ATTR_MESSAGE: message} payload = {ATTR_MESSAGE: message}
payload.update({key: val for key, val in kwargs.items() if val}) 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)) DOMAIN, entity.get(ATTR_SERVICE), sending_payload))
if tasks: 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.kodi/ https://home-assistant.io/components/notify.kodi/
""" """
import asyncio
import logging import logging
import aiohttp import aiohttp
@ -38,8 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
ATTR_DISPLAYTIME = 'displaytime' ATTR_DISPLAYTIME = 'displaytime'
@asyncio.coroutine async def async_get_service(hass, config, discovery_info=None):
def async_get_service(hass, config, discovery_info=None):
"""Return the notify service.""" """Return the notify service."""
url = '{}:{}'.format(config.get(CONF_HOST), config.get(CONF_PORT)) 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) self._server = jsonrpc_async.Server(self._url, **kwargs)
@asyncio.coroutine async def async_send_message(self, message="", **kwargs):
def async_send_message(self, message="", **kwargs):
"""Send a message to Kodi.""" """Send a message to Kodi."""
import jsonrpc_async import jsonrpc_async
try: try:
@ -96,7 +93,7 @@ class KodiNotificationService(BaseNotificationService):
displaytime = data.get(ATTR_DISPLAYTIME, 10000) displaytime = data.get(ATTR_DISPLAYTIME, 10000)
icon = data.get(ATTR_ICON, "info") icon = data.get(ATTR_ICON, "info")
title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT) title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
yield from self._server.GUI.ShowNotification( await self._server.GUI.ShowNotification(
title, message, icon, displaytime) title, message, icon, displaytime)
except jsonrpc_async.TransportError: except jsonrpc_async.TransportError:

View File

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