Fix PEP257 issues

This commit is contained in:
Fabian Affolter 2016-03-08 10:34:33 +01:00
parent 7f1e181c9b
commit cf7c2c492a
14 changed files with 460 additions and 473 deletions

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.media_player
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Component to interface with various media players. Component to interface with various media players.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
@ -110,8 +108,10 @@ ATTR_TO_PROPERTY = [
def is_on(hass, entity_id=None): def is_on(hass, entity_id=None):
""" Returns true if specified media player entity_id is on. """Return true if specified media player entity_id is on.
Will check all media player if no entity_id specified. """
Will check all media player if no entity_id specified.
"""
entity_ids = [entity_id] if entity_id else hass.states.entity_ids(DOMAIN) entity_ids = [entity_id] if entity_id else hass.states.entity_ids(DOMAIN)
return any(not hass.states.is_state(entity_id, STATE_OFF) return any(not hass.states.is_state(entity_id, STATE_OFF)
for entity_id in entity_ids) for entity_id in entity_ids)
@ -226,7 +226,7 @@ def setup(hass, config):
os.path.join(os.path.dirname(__file__), 'services.yaml')) os.path.join(os.path.dirname(__file__), 'services.yaml'))
def media_player_service_handler(service): def media_player_service_handler(service):
""" Maps services to methods on MediaPlayerDevice. """ """Map services to methods on MediaPlayerDevice."""
target_players = component.extract_from_service(service) target_players = component.extract_from_service(service)
method = SERVICE_TO_METHOD[service.service] method = SERVICE_TO_METHOD[service.service]
@ -296,7 +296,7 @@ def setup(hass, config):
descriptions.get(SERVICE_MEDIA_SEEK)) descriptions.get(SERVICE_MEDIA_SEEK))
def play_media_service(service): def play_media_service(service):
""" Plays specified media_id on the media player. """ """Play specified media_id on the media player."""
media_type = service.data.get('media_type') media_type = service.data.get('media_type')
media_id = service.data.get('media_id') media_id = service.data.get('media_id')
@ -320,11 +320,10 @@ def setup(hass, config):
class MediaPlayerDevice(Entity): class MediaPlayerDevice(Entity):
""" ABC for media player devices. """ """An abstract class for media player devices."""
# pylint: disable=too-many-public-methods,no-self-use # pylint: disable=too-many-public-methods,no-self-use
# Implement these for your media player # Implement these for your media player
@property @property
def state(self): def state(self):
"""State of the player.""" """State of the player."""
@ -367,37 +366,37 @@ class MediaPlayerDevice(Entity):
@property @property
def media_artist(self): def media_artist(self):
""" Artist of current playing media. (Music track only) """ """Artist of current playing media (Music track only)."""
return None return None
@property @property
def media_album_name(self): def media_album_name(self):
""" Album name of current playing media. (Music track only) """ """Album name of current playing media (Music track only)."""
return None return None
@property @property
def media_album_artist(self): def media_album_artist(self):
""" Album arist of current playing media. (Music track only) """ """Album artist of current playing media (Music track only)."""
return None return None
@property @property
def media_track(self): def media_track(self):
""" Track number of current playing media. (Music track only) """ """Track number of current playing media (Music track only)."""
return None return None
@property @property
def media_series_title(self): def media_series_title(self):
""" Series title of current playing media. (TV Show only)""" """The title of the series of current playing media (TV Show only)."""
return None return None
@property @property
def media_season(self): def media_season(self):
""" Season of current playing media. (TV Show only) """ """Season of current playing media (TV Show only)."""
return None return None
@property @property
def media_episode(self): def media_episode(self):
""" Episode of current playing media. (TV Show only) """ """Episode of current playing media (TV Show only)."""
return None return None
@property @property
@ -422,23 +421,23 @@ class MediaPlayerDevice(Entity):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return 0 return 0
def turn_on(self): def turn_on(self):
""" turn the media player on. """ """Turn the media player on."""
raise NotImplementedError() raise NotImplementedError()
def turn_off(self): def turn_off(self):
""" turn the media player off. """ """Turn the media player off."""
raise NotImplementedError() raise NotImplementedError()
def mute_volume(self, mute): def mute_volume(self, mute):
""" mute the volume. """ """Mute the volume."""
raise NotImplementedError() raise NotImplementedError()
def set_volume_level(self, volume): def set_volume_level(self, volume):
""" set volume level, range 0..1. """ """Set volume level, range 0..1."""
raise NotImplementedError() raise NotImplementedError()
def media_play(self): def media_play(self):
@ -462,7 +461,7 @@ class MediaPlayerDevice(Entity):
raise NotImplementedError() raise NotImplementedError()
def play_media(self, media_type, media_id): def play_media(self, media_type, media_id):
""" Plays a piece of media. """ """Play a piece of media."""
raise NotImplementedError() raise NotImplementedError()
# No need to overwrite these. # No need to overwrite these.
@ -502,7 +501,7 @@ class MediaPlayerDevice(Entity):
return bool(self.supported_media_commands & SUPPORT_PLAY_MEDIA) return bool(self.supported_media_commands & SUPPORT_PLAY_MEDIA)
def toggle(self): def toggle(self):
""" Toggles the power on the media player. """ """Toggle the power on the media player."""
if self.state in [STATE_OFF, STATE_IDLE]: if self.state in [STATE_OFF, STATE_IDLE]:
self.turn_on() self.turn_on()
else: else:
@ -527,7 +526,7 @@ class MediaPlayerDevice(Entity):
@property @property
def entity_picture(self): def entity_picture(self):
"""Return image of the media playing.""" """Return the image of the media playing."""
return None if self.state == STATE_OFF else self.media_image_url return None if self.state == STATE_OFF else self.media_image_url
@property @property

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.chromecast Provide functionality to interact with Cast devices on the network.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to interact with Cast devices on the network.
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.cast/ https://home-assistant.io/components/media_player.cast/
@ -31,7 +29,7 @@ DEFAULT_PORT = 8009
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the cast platform. """ """Setup the cast platform."""
import pychromecast import pychromecast
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -70,12 +68,12 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class CastDevice(MediaPlayerDevice): class CastDevice(MediaPlayerDevice):
""" Represents a Cast device on the network. """ """Representation of a Cast device on the network."""
# pylint: disable=abstract-method # pylint: disable=abstract-method
# pylint: disable=too-many-public-methods # pylint: disable=too-many-public-methods
def __init__(self, host, port): def __init__(self, host, port):
"""Initialize the Cast device."""
import pychromecast import pychromecast
self.cast = pychromecast.Chromecast(host, port) self.cast = pychromecast.Chromecast(host, port)
@ -86,22 +84,20 @@ class CastDevice(MediaPlayerDevice):
self.cast_status = self.cast.status self.cast_status = self.cast.status
self.media_status = self.cast.media_controller.status self.media_status = self.cast.media_controller.status
# Entity properties and methods
@property @property
def should_poll(self): def should_poll(self):
"""No polling needed."""
return False return False
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Return the name of the device."""
return self.cast.device.friendly_name return self.cast.device.friendly_name
# MediaPlayerDevice properties and methods # MediaPlayerDevice properties and methods
@property @property
def state(self): def state(self):
""" State of the player. """ """Return the state of the player."""
if self.media_status is None: if self.media_status is None:
return STATE_UNKNOWN return STATE_UNKNOWN
elif self.media_status.player_is_playing: elif self.media_status.player_is_playing:
@ -165,42 +161,42 @@ class CastDevice(MediaPlayerDevice):
@property @property
def media_artist(self): def media_artist(self):
""" Artist of current playing media. (Music track only) """ """Artist of current playing media (Music track only)."""
return self.media_status.artist if self.media_status else None return self.media_status.artist if self.media_status else None
@property @property
def media_album(self): def media_album(self):
""" Album of current playing media. (Music track only) """ """Album of current playing media (Music track only)."""
return self.media_status.album_name if self.media_status else None return self.media_status.album_name if self.media_status else None
@property @property
def media_album_artist(self): def media_album_artist(self):
""" Album arist of current playing media. (Music track only) """ """Album arist of current playing media (Music track only)."""
return self.media_status.album_artist if self.media_status else None return self.media_status.album_artist if self.media_status else None
@property @property
def media_track(self): def media_track(self):
""" Track number of current playing media. (Music track only) """ """Track number of current playing media (Music track only)."""
return self.media_status.track if self.media_status else None return self.media_status.track if self.media_status else None
@property @property
def media_series_title(self): def media_series_title(self):
""" Series title of current playing media. (TV Show only)""" """The title of the series of current playing media (TV Show only)."""
return self.media_status.series_title if self.media_status else None return self.media_status.series_title if self.media_status else None
@property @property
def media_season(self): def media_season(self):
""" Season of current playing media. (TV Show only) """ """Season of current playing media (TV Show only)."""
return self.media_status.season if self.media_status else None return self.media_status.season if self.media_status else None
@property @property
def media_episode(self): def media_episode(self):
""" Episode of current playing media. (TV Show only) """ """Episode of current playing media (TV Show only)."""
return self.media_status.episode if self.media_status else None return self.media_status.episode if self.media_status else None
@property @property
def app_id(self): def app_id(self):
""" ID of the current running app. """ """Return the ID of the current running app."""
return self.cast.app_id return self.cast.app_id
@property @property
@ -210,11 +206,11 @@ class CastDevice(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_CAST return SUPPORT_CAST
def turn_on(self): def turn_on(self):
""" Turns on the ChromeCast. """ """Turn on the ChromeCast."""
# The only way we can turn the Chromecast is on is by launching an app # The only way we can turn the Chromecast is on is by launching an app
if not self.cast.status or not self.cast.status.is_active_input: if not self.cast.status or not self.cast.status.is_active_input:
import pychromecast import pychromecast
@ -226,15 +222,15 @@ class CastDevice(MediaPlayerDevice):
CAST_SPLASH, pychromecast.STREAM_TYPE_BUFFERED) CAST_SPLASH, pychromecast.STREAM_TYPE_BUFFERED)
def turn_off(self): def turn_off(self):
""" Turns Chromecast off. """ """Turn Chromecast off."""
self.cast.quit_app() self.cast.quit_app()
def mute_volume(self, mute): def mute_volume(self, mute):
""" mute the volume. """ """Mute the volume."""
self.cast.set_volume_muted(mute) self.cast.set_volume_muted(mute)
def set_volume_level(self, volume): def set_volume_level(self, volume):
""" set volume level, range 0..1. """ """Set volume level, range 0..1."""
self.cast.set_volume(volume) self.cast.set_volume(volume)
def media_play(self): def media_play(self):
@ -258,11 +254,10 @@ class CastDevice(MediaPlayerDevice):
self.cast.media_controller.seek(position) self.cast.media_controller.seek(position)
def play_media(self, media_type, media_id): def play_media(self, media_type, media_id):
""" Plays media from a URL """ """Play media from a URL."""
self.cast.media_controller.play_media(media_id, media_type) self.cast.media_controller.play_media(media_id, media_type)
# implementation of chromecast status_listener methods # Implementation of chromecast status_listener methods
def new_cast_status(self, status): def new_cast_status(self, status):
"""Called when a new cast status is received.""" """Called when a new cast status is received."""
self.cast_status = status self.cast_status = status

View File

@ -14,7 +14,7 @@ from homeassistant.const import STATE_OFF, STATE_PAUSED, STATE_PLAYING
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the media palyer demo platform.""" """Setup the media player demo platform."""
add_devices([ add_devices([
DemoYoutubePlayer( DemoYoutubePlayer(
'Living Room', 'eyU3bRy2x44', 'Living Room', 'eyU3bRy2x44',
@ -39,10 +39,12 @@ NETFLIX_PLAYER_SUPPORT = \
class AbstractDemoPlayer(MediaPlayerDevice): class AbstractDemoPlayer(MediaPlayerDevice):
"""A demo media players""" """A demo media players."""
# We only implement the methods that we support # We only implement the methods that we support
# pylint: disable=abstract-method # pylint: disable=abstract-method
def __init__(self, name): def __init__(self, name):
"""Initialize the demo device."""
self._name = name self._name = name
self._player_state = STATE_PLAYING self._player_state = STATE_PLAYING
self._volume_level = 1.0 self._volume_level = 1.0
@ -106,9 +108,11 @@ class AbstractDemoPlayer(MediaPlayerDevice):
class DemoYoutubePlayer(AbstractDemoPlayer): class DemoYoutubePlayer(AbstractDemoPlayer):
"""A Demo media player that only supports YouTube.""" """A Demo media player that only supports YouTube."""
# We only implement the methods that we support # We only implement the methods that we support
# pylint: disable=abstract-method # pylint: disable=abstract-method
def __init__(self, name, youtube_id=None, media_title=None): def __init__(self, name, youtube_id=None, media_title=None):
"""Initialize the demo device."""
super().__init__(name) super().__init__(name)
self.youtube_id = youtube_id self.youtube_id = youtube_id
self._media_title = media_title self._media_title = media_title
@ -145,7 +149,7 @@ class DemoYoutubePlayer(AbstractDemoPlayer):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
"""Flags of media commands that are supported.""" """Flag of media commands that are supported."""
return YOUTUBE_PLAYER_SUPPORT return YOUTUBE_PLAYER_SUPPORT
def play_media(self, media_type, media_id): def play_media(self, media_type, media_id):
@ -156,6 +160,7 @@ class DemoYoutubePlayer(AbstractDemoPlayer):
class DemoMusicPlayer(AbstractDemoPlayer): class DemoMusicPlayer(AbstractDemoPlayer):
"""A Demo media player that only supports YouTube.""" """A Demo media player that only supports YouTube."""
# We only implement the methods that we support # We only implement the methods that we support
# pylint: disable=abstract-method # pylint: disable=abstract-method
tracks = [ tracks = [
@ -181,6 +186,7 @@ class DemoMusicPlayer(AbstractDemoPlayer):
] ]
def __init__(self): def __init__(self):
"""Initialize the demo device."""
super().__init__('Walkman') super().__init__('Walkman')
self._cur_track = 0 self._cur_track = 0
@ -222,14 +228,12 @@ class DemoMusicPlayer(AbstractDemoPlayer):
@property @property
def media_track(self): def media_track(self):
""" """Return the track number of current media (Music track only)."""
Return the track number of current playing media (Music track only).
"""
return self._cur_track + 1 return self._cur_track + 1
@property @property
def supported_media_commands(self): def supported_media_commands(self):
"""Flags of media commands that are supported.""" """Flag of media commands that are supported."""
support = MUSIC_PLAYER_SUPPORT support = MUSIC_PLAYER_SUPPORT
if self._cur_track > 0: if self._cur_track > 0:
@ -255,9 +259,11 @@ class DemoMusicPlayer(AbstractDemoPlayer):
class DemoTVShowPlayer(AbstractDemoPlayer): class DemoTVShowPlayer(AbstractDemoPlayer):
"""A Demo media player that only supports YouTube.""" """A Demo media player that only supports YouTube."""
# We only implement the methods that we support # We only implement the methods that we support
# pylint: disable=abstract-method # pylint: disable=abstract-method
def __init__(self): def __init__(self):
"""Initialize the demo device."""
super().__init__('Lounge room') super().__init__('Lounge room')
self._cur_episode = 1 self._cur_episode = 1
self._episode_count = 13 self._episode_count = 13

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.denon Support for Denon Network Receivers.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to Denon Network Receivers.
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.denon/ https://home-assistant.io/components/media_player.denon/
@ -23,7 +21,7 @@ SUPPORT_DENON = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Denon platform. """ """Setup the Denon platform."""
if not config.get(CONF_HOST): if not config.get(CONF_HOST):
_LOGGER.error( _LOGGER.error(
"Missing required configuration items in %s: %s", "Missing required configuration items in %s: %s",
@ -43,11 +41,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class DenonDevice(MediaPlayerDevice): class DenonDevice(MediaPlayerDevice):
""" Represents a Denon device. """ """Representation of a Denon device."""
# pylint: disable=too-many-public-methods, abstract-method # pylint: disable=too-many-public-methods, abstract-method
def __init__(self, name, host): def __init__(self, name, host):
"""Initialize the Denon device."""
self._name = name self._name = name
self._host = host self._host = host
self._pwstate = "PWSTANDBY" self._pwstate = "PWSTANDBY"
@ -57,18 +55,19 @@ class DenonDevice(MediaPlayerDevice):
@classmethod @classmethod
def telnet_request(cls, telnet, command): def telnet_request(cls, telnet, command):
""" Executes `command` and returns the response. """ """Execute `command` and return the response."""
telnet.write(command.encode("ASCII") + b"\r") telnet.write(command.encode("ASCII") + b"\r")
return telnet.read_until(b"\r", timeout=0.2).decode("ASCII").strip() return telnet.read_until(b"\r", timeout=0.2).decode("ASCII").strip()
def telnet_command(self, command): def telnet_command(self, command):
""" Establishes a telnet connection and sends `command`. """ """Establish a telnet connection and sends `command`."""
telnet = telnetlib.Telnet(self._host) telnet = telnetlib.Telnet(self._host)
telnet.write(command.encode("ASCII") + b"\r") telnet.write(command.encode("ASCII") + b"\r")
telnet.read_very_eager() # skip response telnet.read_very_eager() # skip response
telnet.close() telnet.close()
def update(self): def update(self):
"""Get the latest details from the device."""
try: try:
telnet = telnetlib.Telnet(self._host) telnet = telnetlib.Telnet(self._host)
except ConnectionRefusedError: except ConnectionRefusedError:
@ -88,12 +87,12 @@ class DenonDevice(MediaPlayerDevice):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Return the name of the device."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Return the state of the device."""
if self._pwstate == "PWSTANDBY": if self._pwstate == "PWSTANDBY":
return STATE_OFF return STATE_OFF
if self._pwstate == "PWON": if self._pwstate == "PWON":
@ -118,45 +117,46 @@ class DenonDevice(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_DENON return SUPPORT_DENON
def turn_off(self): def turn_off(self):
""" turn_off media player. """ """Turn off media player."""
self.telnet_command("PWSTANDBY") self.telnet_command("PWSTANDBY")
def volume_up(self): def volume_up(self):
""" volume_up media player. """ """Volume up media player."""
self.telnet_command("MVUP") self.telnet_command("MVUP")
def volume_down(self): def volume_down(self):
""" volume_down media player. """ """Volume down media player."""
self.telnet_command("MVDOWN") self.telnet_command("MVDOWN")
def set_volume_level(self, volume): def set_volume_level(self, volume):
""" set volume level, range 0..1. """ """Set volume level, range 0..1."""
# 60dB max # 60dB max
self.telnet_command("MV" + str(round(volume * 60)).zfill(2)) self.telnet_command("MV" + str(round(volume * 60)).zfill(2))
def mute_volume(self, mute): def mute_volume(self, mute):
""" mute (true) or unmute (false) media player. """ """Mute (true) or unmute (false) media player."""
self.telnet_command("MU" + ("ON" if mute else "OFF")) self.telnet_command("MU" + ("ON" if mute else "OFF"))
def media_play(self): def media_play(self):
""" media_play media player. """ """Play media media player."""
self.telnet_command("NS9A") self.telnet_command("NS9A")
def media_pause(self): def media_pause(self):
""" media_pause media player. """ """Pause media player."""
self.telnet_command("NS9B") self.telnet_command("NS9B")
def media_next_track(self): def media_next_track(self):
""" Send next track command. """ """Send the next track command."""
self.telnet_command("NS9D") self.telnet_command("NS9D")
def media_previous_track(self): def media_previous_track(self):
"""Send the previous track command."""
self.telnet_command("NS9E") self.telnet_command("NS9E")
def turn_on(self): def turn_on(self):
""" turn the media player on. """ """Turn the media player on."""
self.telnet_command("PWON") self.telnet_command("PWON")

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.firetv Support for functionality to interact with FireTV devices.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to interact with FireTV devices.
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.firetv/ https://home-assistant.io/components/media_player.firetv/
@ -31,7 +29,7 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the FireTV platform. """ """Setup the FireTV platform."""
host = config.get('host', 'localhost:5556') host = config.get('host', 'localhost:5556')
device_id = config.get('device', 'default') device_id = config.get('device', 'default')
try: try:
@ -54,7 +52,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class FireTV(object): class FireTV(object):
""" firetv-server client. """The firetv-server client.
Should a native Python 3 ADB module become available, python-firetv can Should a native Python 3 ADB module become available, python-firetv can
support Python 3, it can be added as a dependency, and this class can be support Python 3, it can be added as a dependency, and this class can be
@ -65,6 +63,7 @@ class FireTV(object):
""" """
def __init__(self, host, device_id): def __init__(self, host, device_id):
"""Initialize the FireTV server."""
self.host = host self.host = host
self.device_id = device_id self.device_id = device_id
@ -101,18 +100,18 @@ class FireTV(object):
class FireTVDevice(MediaPlayerDevice): class FireTVDevice(MediaPlayerDevice):
""" Represents an Amazon Fire TV device on the network. """ """Representation of an Amazon Fire TV device on the network."""
# pylint: disable=abstract-method # pylint: disable=abstract-method
def __init__(self, host, device, name): def __init__(self, host, device, name):
"""Initialize the FireTV device."""
self._firetv = FireTV(host, device) self._firetv = FireTV(host, device)
self._name = name self._name = name
self._state = STATE_UNKNOWN self._state = STATE_UNKNOWN
@property @property
def name(self): def name(self):
""" Get the device name. """ """Return the device name."""
return self._name return self._name
@property @property
@ -122,16 +121,16 @@ class FireTVDevice(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_FIRETV return SUPPORT_FIRETV
@property @property
def state(self): def state(self):
""" State of the player. """ """Return the state of the player."""
return self._state return self._state
def update(self): def update(self):
""" Update device state. """ """Get the latest date and update device state."""
self._state = { self._state = {
'idle': STATE_IDLE, 'idle': STATE_IDLE,
'off': STATE_OFF, 'off': STATE_OFF,
@ -142,11 +141,11 @@ class FireTVDevice(MediaPlayerDevice):
}.get(self._firetv.state, STATE_UNKNOWN) }.get(self._firetv.state, STATE_UNKNOWN)
def turn_on(self): def turn_on(self):
""" Turns on the device. """ """Turn on the device."""
self._firetv.action('turn_on') self._firetv.action('turn_on')
def turn_off(self): def turn_off(self):
""" Turns off the device. """ """Turn off the device."""
self._firetv.action('turn_off') self._firetv.action('turn_off')
def media_play(self): def media_play(self):

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.itunes Support for interfacing to iTunes API.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to iTunes 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.itunes/ https://home-assistant.io/components/media_player.itunes/
@ -30,22 +28,23 @@ DOMAIN = 'itunes'
class Itunes(object): class Itunes(object):
""" itunes-api client. """ """iTunes API client."""
def __init__(self, host, port): def __init__(self, host, port):
"""Initialize the iTunes device."""
self.host = host self.host = host
self.port = port self.port = port
@property @property
def _base_url(self): def _base_url(self):
""" Returns the base url for endpoints. """ """Return the base url for endpoints."""
if self.port: if self.port:
return self.host + ":" + str(self.port) return self.host + ":" + str(self.port)
else: else:
return self.host return self.host
def _request(self, method, path, params=None): def _request(self, method, path, params=None):
""" Makes the actual request and returns the parsed response. """ """Make the actual request and returns the parsed response."""
url = self._base_url + path url = self._base_url + path
try: try:
@ -65,39 +64,39 @@ class Itunes(object):
return {'player_state': 'offline'} return {'player_state': 'offline'}
def _command(self, named_command): def _command(self, named_command):
""" Makes a request for a controlling command. """ """Make a request for a controlling command."""
return self._request('PUT', '/' + named_command) return self._request('PUT', '/' + named_command)
def now_playing(self): def now_playing(self):
""" Returns the current state. """ """Return the current state."""
return self._request('GET', '/now_playing') return self._request('GET', '/now_playing')
def set_volume(self, level): def set_volume(self, level):
""" Sets the volume and returns the current state, level 0-100. """ """Set the volume and returns the current state, level 0-100."""
return self._request('PUT', '/volume', {'level': level}) return self._request('PUT', '/volume', {'level': level})
def set_muted(self, muted): def set_muted(self, muted):
""" Mutes and returns the current state, muted True or False. """ """Mute and returns the current state, muted True or False."""
return self._request('PUT', '/mute', {'muted': muted}) return self._request('PUT', '/mute', {'muted': muted})
def play(self): def play(self):
""" Sets playback to play and returns the current state. """ """Set playback to play and returns the current state."""
return self._command('play') return self._command('play')
def pause(self): def pause(self):
""" Sets playback to paused and returns the current state. """ """Set playback to paused and returns the current state."""
return self._command('pause') return self._command('pause')
def next(self): def next(self):
""" Skips to the next track and returns the current state. """ """Skip to the next track and returns the current state."""
return self._command('next') return self._command('next')
def previous(self): def previous(self):
""" Skips back and returns the current state. """ """Skip back and returns the current state."""
return self._command('previous') return self._command('previous')
def play_playlist(self, playlist_id_or_name): def play_playlist(self, playlist_id_or_name):
""" Sets a playlist to be current and returns the current state. """ """Set a playlist to be current and returns the current state."""
response = self._request('GET', '/playlists') response = self._request('GET', '/playlists')
playlists = response.get('playlists', []) playlists = response.get('playlists', [])
@ -111,25 +110,25 @@ class Itunes(object):
return self._request('PUT', path) return self._request('PUT', path)
def artwork_url(self): def artwork_url(self):
""" Returns a URL of the current track's album art. """ """Return a URL of the current track's album art."""
return self._base_url + '/artwork' return self._base_url + '/artwork'
def airplay_devices(self): def airplay_devices(self):
""" Returns a list of AirPlay devices. """ """Return a list of AirPlay devices."""
return self._request('GET', '/airplay_devices') return self._request('GET', '/airplay_devices')
def airplay_device(self, device_id): def airplay_device(self, device_id):
""" Returns an AirPlay device. """ """Return an AirPlay device."""
return self._request('GET', '/airplay_devices/' + device_id) return self._request('GET', '/airplay_devices/' + device_id)
def toggle_airplay_device(self, device_id, toggle): def toggle_airplay_device(self, device_id, toggle):
""" Toggles airplay device on or off, id, toggle True or False. """ """Toggle airplay device on or off, id, toggle True or False."""
command = 'on' if toggle else 'off' command = 'on' if toggle else 'off'
path = '/airplay_devices/' + device_id + '/' + command path = '/airplay_devices/' + device_id + '/' + command
return self._request('PUT', path) return self._request('PUT', path)
def set_volume_airplay_device(self, device_id, level): def set_volume_airplay_device(self, device_id, level):
""" Sets volume, returns current state of device, id,level 0-100. """ """Set volume, returns current state of device, id,level 0-100."""
path = '/airplay_devices/' + device_id + '/volume' path = '/airplay_devices/' + device_id + '/volume'
return self._request('PUT', path, {'level': level}) return self._request('PUT', path, {'level': level})
@ -137,8 +136,7 @@ class Itunes(object):
# pylint: disable=unused-argument, abstract-method # pylint: disable=unused-argument, abstract-method
# pylint: disable=too-many-instance-attributes # pylint: disable=too-many-instance-attributes
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the itunes platform. """ """Setup the itunes platform."""
add_devices([ add_devices([
ItunesDevice( ItunesDevice(
config.get('name', 'iTunes'), config.get('name', 'iTunes'),
@ -150,10 +148,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class ItunesDevice(MediaPlayerDevice): class ItunesDevice(MediaPlayerDevice):
""" Represents a iTunes-API instance. """ """Representation of an iTunes API instance."""
# pylint: disable=too-many-public-methods # pylint: disable=too-many-public-methods
def __init__(self, name, host, port, add_devices): def __init__(self, name, host, port, add_devices):
"""Initialize the iTunes device."""
self._name = name self._name = name
self._host = host self._host = host
self._port = port self._port = port
@ -189,13 +188,12 @@ class ItunesDevice(MediaPlayerDevice):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Return the name of the device."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Return the state of the device."""
if self.player_state == 'offline' or self.player_state is None: if self.player_state == 'offline' or self.player_state is None:
return 'offline' return 'offline'
@ -260,7 +258,6 @@ class ItunesDevice(MediaPlayerDevice):
@property @property
def media_image_url(self): def media_image_url(self):
"""Image url of current playing media.""" """Image url of current playing media."""
if self.player_state in (STATE_PLAYING, STATE_IDLE, STATE_PAUSED) and \ if self.player_state in (STATE_PLAYING, STATE_IDLE, STATE_PAUSED) and \
self.current_title is not None: self.current_title is not None:
return self.client.artwork_url() return self.client.artwork_url()
@ -275,12 +272,12 @@ class ItunesDevice(MediaPlayerDevice):
@property @property
def media_artist(self): def media_artist(self):
""" Artist of current playing media. (Music track only) """ """Artist of current playing media (Music track only)."""
return self.current_artist return self.current_artist
@property @property
def media_album_name(self): def media_album_name(self):
""" Album of current playing media. (Music track only) """ """Album of current playing media (Music track only)."""
return self.current_album return self.current_album
@property @property
@ -290,56 +287,54 @@ class ItunesDevice(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_ITUNES return SUPPORT_ITUNES
def set_volume_level(self, volume): def set_volume_level(self, volume):
""" set volume level, range 0..1. """ """Set volume level, range 0..1."""
response = self.client.set_volume(int(volume * 100)) response = self.client.set_volume(int(volume * 100))
self.update_state(response) self.update_state(response)
def mute_volume(self, mute): def mute_volume(self, mute):
""" mute (true) or unmute (false) media player. """ """Mute (true) or unmute (false) media player."""
response = self.client.set_muted(mute) response = self.client.set_muted(mute)
self.update_state(response) self.update_state(response)
def media_play(self): def media_play(self):
""" media_play media player. """ """Send media_play command to media player."""
response = self.client.play() response = self.client.play()
self.update_state(response) self.update_state(response)
def media_pause(self): def media_pause(self):
""" media_pause media player. """ """Send media_pause command to media player."""
response = self.client.pause() response = self.client.pause()
self.update_state(response) self.update_state(response)
def media_next_track(self): def media_next_track(self):
""" media_next media player. """ """Send media_next command to media player."""
response = self.client.next() response = self.client.next()
self.update_state(response) self.update_state(response)
def media_previous_track(self): def media_previous_track(self):
""" media_previous media player. """ """Send media_previous command media player."""
response = self.client.previous() response = self.client.previous()
self.update_state(response) self.update_state(response)
def play_media(self, media_type, media_id): def play_media(self, media_type, media_id):
""" play_media media player. """ """Send the play_media command to the media player."""
if media_type == MEDIA_TYPE_PLAYLIST: if media_type == MEDIA_TYPE_PLAYLIST:
response = self.client.play_playlist(media_id) response = self.client.play_playlist(media_id)
self.update_state(response) self.update_state(response)
class AirPlayDevice(MediaPlayerDevice): class AirPlayDevice(MediaPlayerDevice):
""" Represents an AirPlay device via an iTunes-API instance. """ """Representation an AirPlay device via an iTunes API instance."""
# pylint: disable=too-many-public-methods # pylint: disable=too-many-public-methods
def __init__(self, device_id, client): def __init__(self, device_id, client):
"""Initialize the AirPlay device."""
self._id = device_id self._id = device_id
self.client = client self.client = client
self.device_name = "AirPlay" self.device_name = "AirPlay"
self.kind = None self.kind = None
self.active = False self.active = False
@ -351,7 +346,6 @@ class AirPlayDevice(MediaPlayerDevice):
def update_state(self, state_hash): def update_state(self, state_hash):
"""Update all the state properties with the passed in dictionary.""" """Update all the state properties with the passed in dictionary."""
if 'player_state' in state_hash: if 'player_state' in state_hash:
self.player_state = state_hash.get('player_state', None) self.player_state = state_hash.get('player_state', None)
@ -379,12 +373,12 @@ class AirPlayDevice(MediaPlayerDevice):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Return the name of the device."""
return self.device_name return self.device_name
@property @property
def icon(self): def icon(self):
""" Icon to use in the frontend, if any. """ """Return the icon to use in the frontend, if any."""
if self.selected is True: if self.selected is True:
return "mdi:volume-high" return "mdi:volume-high"
else: else:
@ -392,8 +386,7 @@ class AirPlayDevice(MediaPlayerDevice):
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Return the state of the device."""
if self.selected is True: if self.selected is True:
return STATE_ON return STATE_ON
else: else:
@ -404,19 +397,21 @@ class AirPlayDevice(MediaPlayerDevice):
@property @property
def volume_level(self): def volume_level(self):
"""Return the volume."""
return float(self.volume)/100.0 return float(self.volume)/100.0
@property @property
def media_content_type(self): def media_content_type(self):
"""Flag of media content that is supported."""
return MEDIA_TYPE_MUSIC return MEDIA_TYPE_MUSIC
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_AIRPLAY return SUPPORT_AIRPLAY
def set_volume_level(self, volume): def set_volume_level(self, volume):
""" set volume level, range 0..1. """ """Set volume level, range 0..1."""
volume = int(volume * 100) volume = int(volume * 100)
response = self.client.set_volume_airplay_device(self._id, volume) response = self.client.set_volume_airplay_device(self._id, volume)
self.update_state(response) self.update_state(response)

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.kodi Support for interfacing with the XBMC/Kodi JSON-RPC API.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the XBMC/Kodi JSON-RPC 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.kodi/ https://home-assistant.io/components/media_player.kodi/
@ -23,8 +21,7 @@ SUPPORT_KODI = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the kodi platform. """ """Setup the Kodi platform."""
url = '{}:{}'.format(config.get('host'), config.get('port', '8080')) url = '{}:{}'.format(config.get('host'), config.get('port', '8080'))
jsonrpc_url = config.get('url') # deprecated jsonrpc_url = config.get('url') # deprecated
@ -42,11 +39,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class KodiDevice(MediaPlayerDevice): class KodiDevice(MediaPlayerDevice):
""" Represents a XBMC/Kodi device. """ """Representation of a XBMC/Kodi device."""
# pylint: disable=too-many-public-methods, abstract-method # pylint: disable=too-many-public-methods, abstract-method
def __init__(self, name, url, auth=None): def __init__(self, name, url, auth=None):
"""Initialize the Kodi device."""
import jsonrpc_requests import jsonrpc_requests
self._name = name self._name = name
self._url = url self._url = url
@ -61,11 +58,11 @@ class KodiDevice(MediaPlayerDevice):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Return the name of the device."""
return self._name return self._name
def _get_players(self): def _get_players(self):
""" Returns the active player objects or None """ """Return the active player objects or None."""
import jsonrpc_requests import jsonrpc_requests
try: try:
return self._server.Player.GetActivePlayers() return self._server.Player.GetActivePlayers()
@ -76,7 +73,7 @@ class KodiDevice(MediaPlayerDevice):
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Return the state of the device."""
if self._players is None: if self._players is None:
return STATE_OFF return STATE_OFF
@ -180,31 +177,31 @@ class KodiDevice(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_KODI return SUPPORT_KODI
def turn_off(self): def turn_off(self):
""" turn_off media player. """ """Turn off media player."""
self._server.System.Shutdown() self._server.System.Shutdown()
self.update_ha_state() self.update_ha_state()
def volume_up(self): def volume_up(self):
""" volume_up media player. """ """Volume up the media player."""
assert self._server.Input.ExecuteAction('volumeup') == 'OK' assert self._server.Input.ExecuteAction('volumeup') == 'OK'
self.update_ha_state() self.update_ha_state()
def volume_down(self): def volume_down(self):
""" volume_down media player. """ """Volume down the media player."""
assert self._server.Input.ExecuteAction('volumedown') == 'OK' assert self._server.Input.ExecuteAction('volumedown') == 'OK'
self.update_ha_state() self.update_ha_state()
def set_volume_level(self, volume): def set_volume_level(self, volume):
""" set volume level, range 0..1. """ """Set volume level, range 0..1."""
self._server.Application.SetVolume(int(volume * 100)) self._server.Application.SetVolume(int(volume * 100))
self.update_ha_state() self.update_ha_state()
def mute_volume(self, mute): def mute_volume(self, mute):
""" mute (true) or unmute (false) media player. """ """Mute (true) or unmute (false) media player."""
self._server.Application.SetMute(mute) self._server.Application.SetMute(mute)
self.update_ha_state() self.update_ha_state()
@ -218,15 +215,15 @@ class KodiDevice(MediaPlayerDevice):
self.update_ha_state() self.update_ha_state()
def media_play_pause(self): def media_play_pause(self):
""" media_play_pause media player. """ """Pause media on media player."""
self._set_play_state('toggle') self._set_play_state('toggle')
def media_play(self): def media_play(self):
""" media_play media player. """ """Play media."""
self._set_play_state(True) self._set_play_state(True)
def media_pause(self): def media_pause(self):
""" media_pause media player. """ """Pause the media player."""
self._set_play_state(False) self._set_play_state(False)
def _goto(self, direction): def _goto(self, direction):

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.mpd Support to interact with a Music Player Daemon.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to interact with a Music Player Daemon.
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.mpd/ https://home-assistant.io/components/media_player.mpd/
@ -24,8 +22,7 @@ SUPPORT_MPD = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_TURN_OFF | \
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the MPD platform. """ """Setup the MPD platform."""
daemon = config.get('server', None) daemon = config.get('server', None)
port = config.get('port', 6600) port = config.get('port', 6600)
location = config.get('location', 'MPD') location = config.get('location', 'MPD')
@ -64,12 +61,12 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class MpdDevice(MediaPlayerDevice): class MpdDevice(MediaPlayerDevice):
""" Represents a MPD server. """ """Representation of a MPD server."""
# MPD confuses pylint # MPD confuses pylint
# pylint: disable=no-member, abstract-method # pylint: disable=no-member, abstract-method
def __init__(self, server, port, location, password): def __init__(self, server, port, location, password):
"""Initialize the MPD device."""
import mpd import mpd
self.server = server self.server = server
@ -85,6 +82,7 @@ class MpdDevice(MediaPlayerDevice):
self.update() self.update()
def update(self): def update(self):
"""Get the latest data and update the state."""
import mpd import mpd
try: try:
self.status = self.client.status() self.status = self.client.status()
@ -100,12 +98,12 @@ class MpdDevice(MediaPlayerDevice):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Return the name of the device."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the media state. """ """Return the media state."""
if self.status['state'] == 'play': if self.status['state'] == 'play':
return STATE_PLAYING return STATE_PLAYING
elif self.status['state'] == 'pause': elif self.status['state'] == 'pause':
@ -146,21 +144,22 @@ class MpdDevice(MediaPlayerDevice):
@property @property
def media_artist(self): def media_artist(self):
""" Artist of current playing media. (Music track only) """ """Artist of current playing media (Music track only)."""
return self.currentsong.get('artist') return self.currentsong.get('artist')
@property @property
def media_album_name(self): def media_album_name(self):
""" Album of current playing media. (Music track only) """ """Album of current playing media (Music track only)."""
return self.currentsong.get('album') return self.currentsong.get('album')
@property @property
def volume_level(self): def volume_level(self):
"""Return the volume level."""
return int(self.status['volume'])/100 return int(self.status['volume'])/100
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_MPD return SUPPORT_MPD
def turn_off(self): def turn_off(self):
@ -172,7 +171,7 @@ class MpdDevice(MediaPlayerDevice):
self.client.play() self.client.play()
def set_volume_level(self, volume): def set_volume_level(self, volume):
""" Sets volume """ """Set volume of media player."""
self.client.setvol(int(volume * 100)) self.client.setvol(int(volume * 100))
def volume_up(self): def volume_up(self):

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.plex Support to interface with the Plex API.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the Plex 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.plex/ https://home-assistant.io/components/media_player.plex/
@ -61,8 +59,7 @@ def config_from_file(filename, config=None):
# pylint: disable=abstract-method # pylint: disable=abstract-method
def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Sets up the plex platform. """ """Setup the Plex platform."""
config = config_from_file(hass.config.path(PLEX_CONFIG_FILE)) config = config_from_file(hass.config.path(PLEX_CONFIG_FILE))
if len(config): if len(config):
# Setup a configured PlexServer # Setup a configured PlexServer
@ -119,7 +116,7 @@ def setup_plexserver(host, token, hass, add_devices_callback):
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS) @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_devices(): def update_devices():
""" Updates the devices objects. """ """Update the devices objects."""
try: try:
devices = plexserver.clients() devices = plexserver.clients()
except plexapi.exceptions.BadRequest: except plexapi.exceptions.BadRequest:
@ -145,7 +142,7 @@ def setup_plexserver(host, token, hass, add_devices_callback):
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS) @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_sessions(): def update_sessions():
""" Updates the sessions objects. """ """Update the sessions objects."""
try: try:
sessions = plexserver.sessions() sessions = plexserver.sessions()
except plexapi.exceptions.BadRequest: except plexapi.exceptions.BadRequest:
@ -172,7 +169,7 @@ def request_configuration(host, hass, add_devices_callback):
return return
def plex_configuration_callback(data): def plex_configuration_callback(data):
""" Actions to do when our configuration callback is called. """ """The actions to do when our configuration callback is called."""
setup_plexserver(host, data.get('token'), hass, add_devices_callback) setup_plexserver(host, data.get('token'), hass, add_devices_callback)
_CONFIGURING[host] = configurator.request_config( _CONFIGURING[host] = configurator.request_config(
@ -185,33 +182,34 @@ def request_configuration(host, hass, add_devices_callback):
class PlexClient(MediaPlayerDevice): class PlexClient(MediaPlayerDevice):
""" Represents a Plex device. """ """Representation of a Plex device."""
# pylint: disable=too-many-public-methods, attribute-defined-outside-init # pylint: disable=too-many-public-methods, attribute-defined-outside-init
def __init__(self, device, plex_sessions, update_devices, update_sessions): def __init__(self, device, plex_sessions, update_devices, update_sessions):
"""Initialize the Plex device."""
self.plex_sessions = plex_sessions self.plex_sessions = plex_sessions
self.update_devices = update_devices self.update_devices = update_devices
self.update_sessions = update_sessions self.update_sessions = update_sessions
self.set_device(device) self.set_device(device)
def set_device(self, device): def set_device(self, device):
""" Sets the device property. """ """Set the device property."""
self.device = device self.device = device
@property @property
def unique_id(self): def unique_id(self):
""" Returns the id of this plex client """ """Return the id of this plex client."""
return "{}.{}".format( return "{}.{}".format(
self.__class__, self.device.machineIdentifier or self.device.name) self.__class__, self.device.machineIdentifier or self.device.name)
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Return the name of the device."""
return self.device.name or DEVICE_DEFAULT_NAME return self.device.name or DEVICE_DEFAULT_NAME
@property @property
def session(self): def session(self):
""" Returns the session, if any. """ """Return the session, if any."""
if self.device.machineIdentifier not in self.plex_sessions: if self.device.machineIdentifier not in self.plex_sessions:
return None return None
@ -219,7 +217,7 @@ class PlexClient(MediaPlayerDevice):
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Return the state of the device."""
if self.session: if self.session:
state = self.session.player.state state = self.session.player.state
if state == 'playing': if state == 'playing':
@ -235,6 +233,7 @@ class PlexClient(MediaPlayerDevice):
return STATE_UNKNOWN return STATE_UNKNOWN
def update(self): def update(self):
"""Get the latest details."""
self.update_devices(no_throttle=True) self.update_devices(no_throttle=True)
self.update_sessions(no_throttle=True) self.update_sessions(no_throttle=True)
@ -284,7 +283,7 @@ class PlexClient(MediaPlayerDevice):
@property @property
def media_series_title(self): def media_series_title(self):
""" Series title of current playing media (TV Show only). """ """The title of the series of current playing media (TV Show only)."""
from plexapi.video import Show from plexapi.video import Show
if isinstance(self.session, Show): if isinstance(self.session, Show):
return self.session.grandparentTitle return self.session.grandparentTitle
@ -298,15 +297,15 @@ class PlexClient(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_PLEX return SUPPORT_PLEX
def media_play(self): def media_play(self):
""" media_play media player. """ """Send play command."""
self.device.play() self.device.play()
def media_pause(self): def media_pause(self):
""" media_pause media player. """ """Send pause command."""
self.device.pause() self.device.pause()
def media_next_track(self): def media_next_track(self):

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.denon Support for interface with an Samsung TV.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to Samsung TV with a Laninterface.
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.samsungtv/ https://home-assistant.io/components/media_player.samsungtv/
@ -31,8 +29,7 @@ SUPPORT_SAMSUNGTV = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Samsung TV platform. """ """Setup the Samsung TV platform."""
# Validate that all required config options are given # Validate that all required config options are given
if not validate_config({DOMAIN: config}, {DOMAIN: [CONF_HOST]}, _LOGGER): if not validate_config({DOMAIN: config}, {DOMAIN: [CONF_HOST]}, _LOGGER):
return False return False
@ -55,10 +52,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=abstract-method # pylint: disable=abstract-method
class SamsungTVDevice(MediaPlayerDevice): class SamsungTVDevice(MediaPlayerDevice):
""" Represents a Samsung TV. """ """Representation of a Samsung TV."""
# pylint: disable=too-many-public-methods # pylint: disable=too-many-public-methods
def __init__(self, name, config): def __init__(self, name, config):
"""Initialize the samsung device."""
from samsungctl import Remote from samsungctl import Remote
# Save a reference to the imported class # Save a reference to the imported class
self._remote_class = Remote self._remote_class = Remote
@ -72,12 +70,12 @@ class SamsungTVDevice(MediaPlayerDevice):
self._config = config self._config = config
def update(self): def update(self):
"""Retrieve the latest data."""
# Send an empty key to see if we are still connected # Send an empty key to see if we are still connected
return self.send_key('KEY_POWER') return self.send_key('KEY_POWER')
def get_remote(self): def get_remote(self):
""" Creates or Returns a remote control instance """ """Create or return a remote control instance."""
if self._remote is None: if self._remote is None:
# We need to create a new instance to reconnect. # We need to create a new instance to reconnect.
self._remote = self._remote_class(self._config) self._remote = self._remote_class(self._config)
@ -85,7 +83,7 @@ class SamsungTVDevice(MediaPlayerDevice):
return self._remote return self._remote
def send_key(self, key): def send_key(self, key):
""" Sends a key to the tv and handles exceptions """ """Send a key to the tv and handles exceptions."""
try: try:
self.get_remote().control(key) self.get_remote().control(key)
self._state = STATE_ON self._state = STATE_ON
@ -106,11 +104,12 @@ class SamsungTVDevice(MediaPlayerDevice):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Return the name of the device."""
return self._name return self._name
@property @property
def state(self): def state(self):
"""Return the state of the device."""
return self._state return self._state
@property @property
@ -120,22 +119,23 @@ class SamsungTVDevice(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_SAMSUNGTV return SUPPORT_SAMSUNGTV
def turn_off(self): def turn_off(self):
""" turn_off media player. """ """Turn off media player."""
self.send_key("KEY_POWEROFF") self.send_key("KEY_POWEROFF")
def volume_up(self): def volume_up(self):
""" volume_up media player. """ """Volume up the media player."""
self.send_key("KEY_VOLUP") self.send_key("KEY_VOLUP")
def volume_down(self): def volume_down(self):
""" volume_down media player. """ """Volume down media player."""
self.send_key("KEY_VOLDOWN") self.send_key("KEY_VOLDOWN")
def mute_volume(self, mute): def mute_volume(self, mute):
"""Send mute command."""
self.send_key("KEY_MUTE") self.send_key("KEY_MUTE")
def media_play_pause(self): def media_play_pause(self):
@ -146,12 +146,12 @@ class SamsungTVDevice(MediaPlayerDevice):
self.media_play() self.media_play()
def media_play(self): def media_play(self):
""" media_play media player. """ """Send play command."""
self._playing = True self._playing = True
self.send_key("KEY_PLAY") self.send_key("KEY_PLAY")
def media_pause(self): def media_pause(self):
""" media_pause media player. """ """Send media pause command to media player."""
self._playing = False self._playing = False
self.send_key("KEY_PAUSE") self.send_key("KEY_PAUSE")
@ -160,8 +160,9 @@ class SamsungTVDevice(MediaPlayerDevice):
self.send_key("KEY_FF") self.send_key("KEY_FF")
def media_previous_track(self): def media_previous_track(self):
"""Send the previous track command."""
self.send_key("KEY_REWIND") self.send_key("KEY_REWIND")
def turn_on(self): def turn_on(self):
""" turn the media player on. """ """Turn the media player on."""
self.send_key("KEY_POWERON") self.send_key("KEY_POWERON")

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.snapcast Support for interacting with Snapcast clients.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to interact 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/
@ -22,7 +20,7 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Snapcast platform. """ """Setup the Snapcast platform."""
import snapcast.control import snapcast.control
host = config.get('host') host = config.get('host')
port = config.get('port', snapcast.control.CONTROL_PORT) port = config.get('port', snapcast.control.CONTROL_PORT)
@ -39,21 +37,21 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class SnapcastDevice(MediaPlayerDevice): class SnapcastDevice(MediaPlayerDevice):
""" Represents a Snapcast client device. """ """Representation of a Snapcast client device."""
# pylint: disable=abstract-method # pylint: disable=abstract-method
def __init__(self, client): def __init__(self, client):
"""Initialize the Snapcast device."""
self._client = client self._client = client
@property @property
def name(self): def name(self):
""" Device name. """ """Return the name of the device."""
return self._client.identifier return self._client.identifier
@property @property
def volume_level(self): def volume_level(self):
""" Volume level. """ """Return the volume level."""
return self._client.volume / 100 return self._client.volume / 100
@property @property
@ -63,20 +61,20 @@ class SnapcastDevice(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_SNAPCAST return SUPPORT_SNAPCAST
@property @property
def state(self): def state(self):
""" State of the player. """ """Return the state of the player."""
if self._client.connected: if self._client.connected:
return STATE_ON return STATE_ON
return STATE_OFF return STATE_OFF
def mute_volume(self, mute): def mute_volume(self, mute):
""" Mute status. """ """Send the mute command."""
self._client.muted = mute self._client.muted = mute
def set_volume_level(self, volume): def set_volume_level(self, volume):
""" Volume level. """ """Set the volume level."""
self._client.volume = round(volume * 100) self._client.volume = round(volume * 100)

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.sonos Support to interface with Sonos players (via SoCo).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to Sonos players (via SoCo)
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/
@ -34,7 +32,7 @@ SUPPORT_SONOS = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE |\
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Sonos platform. """ """Setup the Sonos platform."""
import soco import soco
import socket import socket
@ -67,15 +65,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
def only_if_coordinator(func): def only_if_coordinator(func):
""" """Decorator for coordinator.
If used as decorator, avoid calling the decorated method if
player is not a coordinator.
If not, a grouped speaker (not in coordinator role)
will throw soco.exceptions.SoCoSlaveException
"""
If used as decorator, avoid calling the decorated method if player is not
a coordinator. If not, a grouped speaker (not in coordinator role) will
throw soco.exceptions.SoCoSlaveException
"""
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
""" Decorator wrapper """ """Decorator wrapper."""
if args[0].is_coordinator: if args[0].is_coordinator:
return func(*args, **kwargs) return func(*args, **kwargs)
else: else:
@ -89,10 +86,11 @@ def only_if_coordinator(func):
# pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=abstract-method # pylint: disable=abstract-method
class SonosDevice(MediaPlayerDevice): class SonosDevice(MediaPlayerDevice):
""" Represents a Sonos device. """ """Representation of a Sonos device."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, hass, player): def __init__(self, hass, player):
"""Initialize the Sonos device."""
self.hass = hass self.hass = hass
super(SonosDevice, self).__init__() super(SonosDevice, self).__init__()
self._player = player self._player = player
@ -100,25 +98,26 @@ class SonosDevice(MediaPlayerDevice):
@property @property
def should_poll(self): def should_poll(self):
"""No polling needed."""
return True return True
def update_sonos(self, now): def update_sonos(self, now):
""" Updates state, called by track_utc_time_change. """ """Update state, called by track_utc_time_change."""
self.update_ha_state(True) self.update_ha_state(True)
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Return the name of the device."""
return self._name return self._name
@property @property
def unique_id(self): def unique_id(self):
""" Returns a unique id. """ """Return a unique ID."""
return "{}.{}".format(self.__class__, self._player.uid) return "{}.{}".format(self.__class__, self._player.uid)
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Return the state of the device."""
if self._status == 'PAUSED_PLAYBACK': if self._status == 'PAUSED_PLAYBACK':
return STATE_PAUSED return STATE_PAUSED
if self._status == 'PLAYING': if self._status == 'PLAYING':
@ -129,7 +128,7 @@ class SonosDevice(MediaPlayerDevice):
@property @property
def is_coordinator(self): def is_coordinator(self):
""" Returns true if player is a coordinator """ """Return true if player is a coordinator."""
return self._player.is_coordinator return self._player.is_coordinator
def update(self): def update(self):
@ -147,6 +146,7 @@ class SonosDevice(MediaPlayerDevice):
@property @property
def is_volume_muted(self): def is_volume_muted(self):
"""Return true if volume is muted."""
return self._player.mute return self._player.mute
@property @property
@ -192,7 +192,7 @@ class SonosDevice(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_SONOS return SUPPORT_SONOS
@only_if_coordinator @only_if_coordinator

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.squeezebox Support for interfacing to the Logitech SqueezeBox API.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the Logitech SqueezeBox 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.squeezebox/ https://home-assistant.io/components/media_player.squeezebox/
@ -26,7 +24,7 @@ SUPPORT_SQUEEZEBOX = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | \
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the squeezebox platform. """ """Setup the squeezebox platform."""
if not config.get(CONF_HOST): if not config.get(CONF_HOST):
_LOGGER.error( _LOGGER.error(
"Missing required configuration items in %s: %s", "Missing required configuration items in %s: %s",
@ -49,9 +47,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class LogitechMediaServer(object): class LogitechMediaServer(object):
""" Represents a Logitech media server. """ """Representation of a Logitech media server."""
def __init__(self, host, port, username, password): def __init__(self, host, port, username, password):
"""Initialize the Logitech device."""
self.host = host self.host = host
self.port = port self.port = port
self._username = username self._username = username
@ -133,10 +132,11 @@ class LogitechMediaServer(object):
# pylint: disable=too-many-instance-attributes # pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-public-methods # pylint: disable=too-many-public-methods
class SqueezeBoxDevice(MediaPlayerDevice): class SqueezeBoxDevice(MediaPlayerDevice):
""" Represents a SqueezeBox device. """ """Representation of a SqueezeBox device."""
# pylint: disable=too-many-arguments, abstract-method # pylint: disable=too-many-arguments, abstract-method
def __init__(self, lms, player_id): def __init__(self, lms, player_id):
"""Initialize the SqeezeBox device."""
super(SqueezeBoxDevice, self).__init__() super(SqueezeBoxDevice, self).__init__()
self._lms = lms self._lms = lms
self._id = player_id self._id = player_id
@ -145,12 +145,12 @@ class SqueezeBoxDevice(MediaPlayerDevice):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Return the name of the device."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Return the state of the device."""
if 'power' in self._status and self._status['power'] == '0': if 'power' in self._status and self._status['power'] == '0':
return STATE_OFF return STATE_OFF
if 'mode' in self._status: if 'mode' in self._status:
@ -174,6 +174,7 @@ class SqueezeBoxDevice(MediaPlayerDevice):
@property @property
def is_volume_muted(self): def is_volume_muted(self):
"""Return true if volume is muted."""
if 'mixer volume' in self._status: if 'mixer volume' in self._status:
return self._status['mixer volume'].startswith('-') return self._status['mixer volume'].startswith('-')
@ -225,48 +226,48 @@ class SqueezeBoxDevice(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
return SUPPORT_SQUEEZEBOX return SUPPORT_SQUEEZEBOX
def turn_off(self): def turn_off(self):
""" turn_off media player. """ """Turn off media player."""
self._lms.query(self._id, 'power', '0') self._lms.query(self._id, 'power', '0')
self.update_ha_state() self.update_ha_state()
def volume_up(self): def volume_up(self):
""" volume_up media player. """ """Volume up media player."""
self._lms.query(self._id, 'mixer', 'volume', '+5') self._lms.query(self._id, 'mixer', 'volume', '+5')
self.update_ha_state() self.update_ha_state()
def volume_down(self): def volume_down(self):
""" volume_down media player. """ """Volume down media player."""
self._lms.query(self._id, 'mixer', 'volume', '-5') self._lms.query(self._id, 'mixer', 'volume', '-5')
self.update_ha_state() self.update_ha_state()
def set_volume_level(self, volume): def set_volume_level(self, volume):
""" set volume level, range 0..1. """ """Set volume level, range 0..1."""
volume_percent = str(int(volume*100)) volume_percent = str(int(volume*100))
self._lms.query(self._id, 'mixer', 'volume', volume_percent) self._lms.query(self._id, 'mixer', 'volume', volume_percent)
self.update_ha_state() self.update_ha_state()
def mute_volume(self, mute): def mute_volume(self, mute):
""" mute (true) or unmute (false) media player. """ """Mute (true) or unmute (false) media player."""
mute_numeric = '1' if mute else '0' mute_numeric = '1' if mute else '0'
self._lms.query(self._id, 'mixer', 'muting', mute_numeric) self._lms.query(self._id, 'mixer', 'muting', mute_numeric)
self.update_ha_state() self.update_ha_state()
def media_play_pause(self): def media_play_pause(self):
""" media_play_pause media player. """ """Send pause command to media player."""
self._lms.query(self._id, 'pause') self._lms.query(self._id, 'pause')
self.update_ha_state() self.update_ha_state()
def media_play(self): def media_play(self):
""" media_play media player. """ """Send play command to media player."""
self._lms.query(self._id, 'play') self._lms.query(self._id, 'play')
self.update_ha_state() self.update_ha_state()
def media_pause(self): def media_pause(self):
""" media_pause media player. """ """Send pause command to media player."""
self._lms.query(self._id, 'pause', '1') self._lms.query(self._id, 'pause', '1')
self.update_ha_state() self.update_ha_state()
@ -286,6 +287,6 @@ class SqueezeBoxDevice(MediaPlayerDevice):
self.update_ha_state() self.update_ha_state()
def turn_on(self): def turn_on(self):
""" turn the media player on. """ """Turn the media player on."""
self._lms.query(self._id, 'power', '1') self._lms.query(self._id, 'power', '1')
self.update_ha_state() self.update_ha_state()

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.media_player.universal Combination of multiple media players into one for a universal controller.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Combines multiple media players into one for a universal controller.
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.universal/ https://home-assistant.io/components/media_player.universal/
@ -47,7 +45,7 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" sets up the universal media players """ """Setup the universal media players."""
if not validate_config(config): if not validate_config(config):
return return
@ -61,10 +59,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
def validate_config(config): def validate_config(config):
""" validate universal media player configuration """ """Validate universal media player configuration."""
del config[CONF_PLATFORM] del config[CONF_PLATFORM]
# validate name # Validate name
if CONF_NAME not in config: if CONF_NAME not in config:
_LOGGER.error('Universal Media Player configuration requires name') _LOGGER.error('Universal Media Player configuration requires name')
return False return False
@ -87,7 +85,7 @@ def validate_config(config):
def validate_children(config): def validate_children(config):
""" validate children """ """Validate children."""
if CONF_CHILDREN not in config: if CONF_CHILDREN not in config:
_LOGGER.info( _LOGGER.info(
'No children under Universal Media Player (%s)', config[CONF_NAME]) 'No children under Universal Media Player (%s)', config[CONF_NAME])
@ -101,7 +99,7 @@ def validate_children(config):
def validate_commands(config): def validate_commands(config):
""" validate commands """ """Validate commands."""
if CONF_COMMANDS not in config: if CONF_COMMANDS not in config:
config[CONF_COMMANDS] = {} config[CONF_COMMANDS] = {}
elif not isinstance(config[CONF_COMMANDS], dict): elif not isinstance(config[CONF_COMMANDS], dict):
@ -113,7 +111,7 @@ def validate_commands(config):
def validate_attributes(config): def validate_attributes(config):
""" validate attributes """ """Validate attributes."""
if CONF_ATTRS not in config: if CONF_ATTRS not in config:
config[CONF_ATTRS] = {} config[CONF_ATTRS] = {}
elif not isinstance(config[CONF_ATTRS], dict): elif not isinstance(config[CONF_ATTRS], dict):
@ -131,10 +129,11 @@ def validate_attributes(config):
class UniversalMediaPlayer(MediaPlayerDevice): class UniversalMediaPlayer(MediaPlayerDevice):
""" Represents a universal media player in HA """ """Representation of an universal media player."""
# pylint: disable=too-many-public-methods
# pylint: disable=too-many-public-methods
def __init__(self, hass, name, children, commands, attributes): def __init__(self, hass, name, children, commands, attributes):
"""Initialize the Universal media device."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
self.hass = hass self.hass = hass
self._name = name self._name = name
@ -144,7 +143,7 @@ class UniversalMediaPlayer(MediaPlayerDevice):
self._child_state = None self._child_state = None
def on_dependency_update(*_): def on_dependency_update(*_):
""" update ha state when dependencies update """ """Update ha state when dependencies update."""
self.update_ha_state(True) self.update_ha_state(True)
depend = copy(children) depend = copy(children)
@ -154,7 +153,7 @@ class UniversalMediaPlayer(MediaPlayerDevice):
track_state_change(hass, depend, on_dependency_update) track_state_change(hass, depend, on_dependency_update)
def _entity_lkp(self, entity_id, state_attr=None): def _entity_lkp(self, entity_id, state_attr=None):
""" Looks up an entity state from hass """ """Look up an entity state."""
state_obj = self.hass.states.get(entity_id) state_obj = self.hass.states.get(entity_id)
if state_obj is None: if state_obj is None:
@ -165,7 +164,7 @@ class UniversalMediaPlayer(MediaPlayerDevice):
return state_obj.state return state_obj.state
def _override_or_child_attr(self, attr_name): def _override_or_child_attr(self, attr_name):
""" returns either the override or the active child for attr_name """ """Return either the override or the active child for attr_name."""
if attr_name in self._attrs: if attr_name in self._attrs:
return self._entity_lkp(self._attrs[attr_name][0], return self._entity_lkp(self._attrs[attr_name][0],
self._attrs[attr_name][1]) self._attrs[attr_name][1])
@ -173,13 +172,13 @@ class UniversalMediaPlayer(MediaPlayerDevice):
return self._child_attr(attr_name) return self._child_attr(attr_name)
def _child_attr(self, attr_name): def _child_attr(self, attr_name):
""" returns the active child's attr """ """Return the active child's attributes."""
active_child = self._child_state active_child = self._child_state
return active_child.attributes.get(attr_name) if active_child else None return active_child.attributes.get(attr_name) if active_child else None
def _call_service(self, service_name, service_data=None, def _call_service(self, service_name, service_data=None,
allow_override=False): allow_override=False):
""" calls either a specified or active child's service """ """Call either a specified or active child's service."""
if allow_override and service_name in self._cmds: if allow_override and service_name in self._cmds:
call_from_config( call_from_config(
self.hass, self._cmds[service_name], blocking=True) self.hass, self._cmds[service_name], blocking=True)
@ -196,12 +195,12 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property @property
def should_poll(self): def should_poll(self):
""" Indicates whether HA should poll for updates """ """No polling needed."""
return False return False
@property @property
def master_state(self): def master_state(self):
""" gets the master state from entity or none """ """Get the master state from entity or none."""
if CONF_STATE in self._attrs: if CONF_STATE in self._attrs:
master_state = self._entity_lkp(self._attrs[CONF_STATE][0], master_state = self._entity_lkp(self._attrs[CONF_STATE][0],
self._attrs[CONF_STATE][1]) self._attrs[CONF_STATE][1])
@ -211,17 +210,16 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property @property
def name(self): def name(self):
""" name of universal player """ """Return the name of universal player."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" """Current state of media player.
Current state of media player
Off if master state is off Off if master state is off
ELSE Status of first active child else Status of first active child
ELSE master state or off else master state or off
""" """
master_state = self.master_state # avoid multiple lookups master_state = self.master_state # avoid multiple lookups
if master_state == STATE_OFF: if master_state == STATE_OFF:
@ -235,12 +233,12 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property @property
def volume_level(self): def volume_level(self):
""" Volume level of entity specified in attributes or active child """ """Volume level of entity specified in attributes or active child."""
return self._child_attr(ATTR_MEDIA_VOLUME_LEVEL) return self._child_attr(ATTR_MEDIA_VOLUME_LEVEL)
@property @property
def is_volume_muted(self): def is_volume_muted(self):
""" boolean if volume is muted """ """Boolean if volume is muted."""
return self._override_or_child_attr(ATTR_MEDIA_VOLUME_MUTED) \ return self._override_or_child_attr(ATTR_MEDIA_VOLUME_MUTED) \
in [True, STATE_ON] in [True, STATE_ON]
@ -271,37 +269,37 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property @property
def media_artist(self): def media_artist(self):
""" Artist of current playing media. (Music track only) """ """Artist of current playing media (Music track only)."""
return self._child_attr(ATTR_MEDIA_ARTIST) return self._child_attr(ATTR_MEDIA_ARTIST)
@property @property
def media_album_name(self): def media_album_name(self):
""" Album name of current playing media. (Music track only) """ """Album name of current playing media (Music track only)."""
return self._child_attr(ATTR_MEDIA_ALBUM_NAME) return self._child_attr(ATTR_MEDIA_ALBUM_NAME)
@property @property
def media_album_artist(self): def media_album_artist(self):
""" Album arist of current playing media. (Music track only) """ """Album artist of current playing media (Music track only)."""
return self._child_attr(ATTR_MEDIA_ALBUM_ARTIST) return self._child_attr(ATTR_MEDIA_ALBUM_ARTIST)
@property @property
def media_track(self): def media_track(self):
""" Track number of current playing media. (Music track only) """ """Track number of current playing media (Music track only)."""
return self._child_attr(ATTR_MEDIA_TRACK) return self._child_attr(ATTR_MEDIA_TRACK)
@property @property
def media_series_title(self): def media_series_title(self):
""" Series title of current playing media. (TV Show only)""" """The title of the series of current playing media (TV Show only)."""
return self._child_attr(ATTR_MEDIA_SERIES_TITLE) return self._child_attr(ATTR_MEDIA_SERIES_TITLE)
@property @property
def media_season(self): def media_season(self):
""" Season of current playing media. (TV Show only) """ """Season of current playing media (TV Show only)."""
return self._child_attr(ATTR_MEDIA_SEASON) return self._child_attr(ATTR_MEDIA_SEASON)
@property @property
def media_episode(self): def media_episode(self):
""" Episode of current playing media. (TV Show only) """ """Episode of current playing media (TV Show only)."""
return self._child_attr(ATTR_MEDIA_EPISODE) return self._child_attr(ATTR_MEDIA_EPISODE)
@property @property
@ -326,7 +324,7 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property @property
def supported_media_commands(self): def supported_media_commands(self):
""" Flags of media commands that are supported. """ """Flag of media commands that are supported."""
flags = self._child_attr(ATTR_SUPPORTED_MEDIA_COMMANDS) or 0 flags = self._child_attr(ATTR_SUPPORTED_MEDIA_COMMANDS) or 0
if SERVICE_TURN_ON in self._cmds: if SERVICE_TURN_ON in self._cmds:
@ -353,20 +351,20 @@ class UniversalMediaPlayer(MediaPlayerDevice):
if active_child else {} if active_child else {}
def turn_on(self): def turn_on(self):
""" turn the media player on. """ """Turn the media player on."""
self._call_service(SERVICE_TURN_ON, allow_override=True) self._call_service(SERVICE_TURN_ON, allow_override=True)
def turn_off(self): def turn_off(self):
""" turn the media player off. """ """Turn the media player off."""
self._call_service(SERVICE_TURN_OFF, allow_override=True) self._call_service(SERVICE_TURN_OFF, allow_override=True)
def mute_volume(self, is_volume_muted): def mute_volume(self, is_volume_muted):
""" mute the volume. """ """Mute the volume."""
data = {ATTR_MEDIA_VOLUME_MUTED: is_volume_muted} data = {ATTR_MEDIA_VOLUME_MUTED: is_volume_muted}
self._call_service(SERVICE_VOLUME_MUTE, data, allow_override=True) self._call_service(SERVICE_VOLUME_MUTE, data, allow_override=True)
def set_volume_level(self, volume_level): def set_volume_level(self, volume_level):
""" set volume level, range 0..1. """ """Set volume level, range 0..1."""
data = {ATTR_MEDIA_VOLUME_LEVEL: volume_level} data = {ATTR_MEDIA_VOLUME_LEVEL: volume_level}
self._call_service(SERVICE_VOLUME_SET, data) self._call_service(SERVICE_VOLUME_SET, data)
@ -392,24 +390,24 @@ class UniversalMediaPlayer(MediaPlayerDevice):
self._call_service(SERVICE_MEDIA_SEEK, data) self._call_service(SERVICE_MEDIA_SEEK, data)
def play_media(self, media_type, media_id): def play_media(self, media_type, media_id):
""" Plays a piece of media. """ """Play a piece of media."""
data = {'media_type': media_type, 'media_id': media_id} data = {'media_type': media_type, 'media_id': media_id}
self._call_service(SERVICE_PLAY_MEDIA, data) self._call_service(SERVICE_PLAY_MEDIA, data)
def volume_up(self): def volume_up(self):
""" volume_up media player. """ """Volume up media player."""
self._call_service(SERVICE_VOLUME_UP, allow_override=True) self._call_service(SERVICE_VOLUME_UP, allow_override=True)
def volume_down(self): def volume_down(self):
""" volume_down media player. """ """Volume down media player."""
self._call_service(SERVICE_VOLUME_DOWN, allow_override=True) self._call_service(SERVICE_VOLUME_DOWN, allow_override=True)
def media_play_pause(self): def media_play_pause(self):
""" media_play_pause media player. """ """Send play/pause command media player."""
self._call_service(SERVICE_MEDIA_PLAY_PAUSE) self._call_service(SERVICE_MEDIA_PLAY_PAUSE)
def update(self): def update(self):
""" event to trigger a state update in HA """ """Event to trigger a state update."""
for child_name in self._children: for child_name in self._children:
child_state = self.hass.states.get(child_name) child_state = self.hass.states.get(child_name)
if child_state and child_state.state not in OFF_STATES: if child_state and child_state.state not in OFF_STATES: