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.
For more details about this component, please refer to the documentation at
@ -110,45 +108,47 @@ ATTR_TO_PROPERTY = [
def is_on(hass, entity_id=None):
""" Returns true if specified media player entity_id is on.
Will check all media player if no entity_id specified. """
"""Return true if specified media player entity_id is on.
Will check all media player if no entity_id specified.
"""
entity_ids = [entity_id] if entity_id else hass.states.entity_ids(DOMAIN)
return any(not hass.states.is_state(entity_id, STATE_OFF)
for entity_id in entity_ids)
def turn_on(hass, entity_id=None):
""" Will turn on specified media player or all. """
"""Will turn on specified media player or all."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_TURN_ON, data)
def turn_off(hass, entity_id=None):
""" Will turn off specified media player or all. """
"""Will turn off specified media player or all."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_TURN_OFF, data)
def toggle(hass, entity_id=None):
""" Will toggle specified media player or all. """
"""Will toggle specified media player or all."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_TOGGLE, data)
def volume_up(hass, entity_id=None):
""" Send the media player the command for volume up. """
"""Send the media player the command for volume up."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_VOLUME_UP, data)
def volume_down(hass, entity_id=None):
""" Send the media player the command for volume down. """
"""Send the media player the command for volume down."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_VOLUME_DOWN, data)
def mute_volume(hass, mute, entity_id=None):
""" Send the media player the command for volume down. """
"""Send the media player the command for volume down."""
data = {ATTR_MEDIA_VOLUME_MUTED: mute}
if entity_id:
@ -158,7 +158,7 @@ def mute_volume(hass, mute, entity_id=None):
def set_volume_level(hass, volume, entity_id=None):
""" Send the media player the command for volume down. """
"""Send the media player the command for volume down."""
data = {ATTR_MEDIA_VOLUME_LEVEL: volume}
if entity_id:
@ -168,44 +168,44 @@ def set_volume_level(hass, volume, entity_id=None):
def media_play_pause(hass, entity_id=None):
""" Send the media player the command for play/pause. """
"""Send the media player the command for play/pause."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_MEDIA_PLAY_PAUSE, data)
def media_play(hass, entity_id=None):
""" Send the media player the command for play/pause. """
"""Send the media player the command for play/pause."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_MEDIA_PLAY, data)
def media_pause(hass, entity_id=None):
""" Send the media player the command for play/pause. """
"""Send the media player the command for play/pause."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_MEDIA_PAUSE, data)
def media_next_track(hass, entity_id=None):
""" Send the media player the command for next track. """
"""Send the media player the command for next track."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_MEDIA_NEXT_TRACK, data)
def media_previous_track(hass, entity_id=None):
""" Send the media player the command for prev track. """
"""Send the media player the command for prev track."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK, data)
def media_seek(hass, position, entity_id=None):
""" Send the media player the command to seek in current playing media. """
"""Send the media player the command to seek in current playing media."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
data[ATTR_MEDIA_SEEK_POSITION] = position
hass.services.call(DOMAIN, SERVICE_MEDIA_SEEK, data)
def play_media(hass, media_type, media_id, entity_id=None):
""" Send the media player the command for playing media. """
"""Send the media player the command for playing media."""
data = {"media_type": media_type, "media_id": media_id}
if entity_id:
@ -215,7 +215,7 @@ def play_media(hass, media_type, media_id, entity_id=None):
def setup(hass, config):
""" Track states and offer events for media_players. """
"""Track states and offer events for media_players."""
component = EntityComponent(
logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL,
DISCOVERY_PLATFORMS)
@ -226,7 +226,7 @@ def setup(hass, config):
os.path.join(os.path.dirname(__file__), 'services.yaml'))
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)
method = SERVICE_TO_METHOD[service.service]
@ -242,7 +242,7 @@ def setup(hass, config):
descriptions.get(service))
def volume_set_service(service):
""" Set specified volume on the media player. """
"""Set specified volume on the media player."""
target_players = component.extract_from_service(service)
if ATTR_MEDIA_VOLUME_LEVEL not in service.data:
@ -260,7 +260,7 @@ def setup(hass, config):
descriptions.get(SERVICE_VOLUME_SET))
def volume_mute_service(service):
""" Mute (true) or unmute (false) the media player. """
"""Mute (true) or unmute (false) the media player."""
target_players = component.extract_from_service(service)
if ATTR_MEDIA_VOLUME_MUTED not in service.data:
@ -278,7 +278,7 @@ def setup(hass, config):
descriptions.get(SERVICE_VOLUME_MUTE))
def media_seek_service(service):
""" Seek to a position. """
"""Seek to a position."""
target_players = component.extract_from_service(service)
if ATTR_MEDIA_SEEK_POSITION not in service.data:
@ -296,7 +296,7 @@ def setup(hass, config):
descriptions.get(SERVICE_MEDIA_SEEK))
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_id = service.data.get('media_id')
@ -320,206 +320,205 @@ def setup(hass, config):
class MediaPlayerDevice(Entity):
""" ABC for media player devices. """
"""An abstract class for media player devices."""
# pylint: disable=too-many-public-methods,no-self-use
# Implement these for your media player
@property
def state(self):
""" State of the player. """
"""State of the player."""
return STATE_UNKNOWN
@property
def volume_level(self):
""" Volume level of the media player (0..1). """
"""Volume level of the media player (0..1)."""
return None
@property
def is_volume_muted(self):
""" Boolean if volume is currently muted. """
"""Boolean if volume is currently muted."""
return None
@property
def media_content_id(self):
""" Content ID of current playing media. """
"""Content ID of current playing media."""
return None
@property
def media_content_type(self):
""" Content type of current playing media. """
"""Content type of current playing media."""
return None
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
"""Duration of current playing media in seconds."""
return None
@property
def media_image_url(self):
""" Image url of current playing media. """
"""Image url of current playing media."""
return None
@property
def media_title(self):
""" Title of current playing media. """
"""Title of current playing media."""
return None
@property
def media_artist(self):
""" Artist of current playing media. (Music track only) """
"""Artist of current playing media (Music track only)."""
return None
@property
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
@property
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
@property
def media_track(self):
""" Track number of current playing media. (Music track only) """
"""Track number of current playing media (Music track only)."""
return None
@property
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
@property
def media_season(self):
""" Season of current playing media. (TV Show only) """
"""Season of current playing media (TV Show only)."""
return None
@property
def media_episode(self):
""" Episode of current playing media. (TV Show only) """
"""Episode of current playing media (TV Show only)."""
return None
@property
def media_channel(self):
""" Channel currently playing. """
"""Channel currently playing."""
return None
@property
def media_playlist(self):
""" Title of Playlist currently playing. """
"""Title of Playlist currently playing."""
return None
@property
def app_id(self):
""" ID of the current running app. """
"""ID of the current running app."""
return None
@property
def app_name(self):
""" Name of the current running app. """
"""Name of the current running app."""
return None
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return 0
def turn_on(self):
""" turn the media player on. """
"""Turn the media player on."""
raise NotImplementedError()
def turn_off(self):
""" turn the media player off. """
"""Turn the media player off."""
raise NotImplementedError()
def mute_volume(self, mute):
""" mute the volume. """
"""Mute the volume."""
raise NotImplementedError()
def set_volume_level(self, volume):
""" set volume level, range 0..1. """
"""Set volume level, range 0..1."""
raise NotImplementedError()
def media_play(self):
""" Send play commmand. """
"""Send play commmand."""
raise NotImplementedError()
def media_pause(self):
""" Send pause command. """
"""Send pause command."""
raise NotImplementedError()
def media_previous_track(self):
""" Send previous track command. """
"""Send previous track command."""
raise NotImplementedError()
def media_next_track(self):
""" Send next track command. """
"""Send next track command."""
raise NotImplementedError()
def media_seek(self, position):
""" Send seek command. """
"""Send seek command."""
raise NotImplementedError()
def play_media(self, media_type, media_id):
""" Plays a piece of media. """
"""Play a piece of media."""
raise NotImplementedError()
# No need to overwrite these.
@property
def support_pause(self):
""" Boolean if pause is supported. """
"""Boolean if pause is supported."""
return bool(self.supported_media_commands & SUPPORT_PAUSE)
@property
def support_seek(self):
""" Boolean if seek is supported. """
"""Boolean if seek is supported."""
return bool(self.supported_media_commands & SUPPORT_SEEK)
@property
def support_volume_set(self):
""" Boolean if setting volume is supported. """
"""Boolean if setting volume is supported."""
return bool(self.supported_media_commands & SUPPORT_VOLUME_SET)
@property
def support_volume_mute(self):
""" Boolean if muting volume is supported. """
"""Boolean if muting volume is supported."""
return bool(self.supported_media_commands & SUPPORT_VOLUME_MUTE)
@property
def support_previous_track(self):
""" Boolean if previous track command supported. """
"""Boolean if previous track command supported."""
return bool(self.supported_media_commands & SUPPORT_PREVIOUS_TRACK)
@property
def support_next_track(self):
""" Boolean if next track command supported. """
"""Boolean if next track command supported."""
return bool(self.supported_media_commands & SUPPORT_NEXT_TRACK)
@property
def support_play_media(self):
""" Boolean if play media command supported. """
"""Boolean if play media command supported."""
return bool(self.supported_media_commands & SUPPORT_PLAY_MEDIA)
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]:
self.turn_on()
else:
self.turn_off()
def volume_up(self):
""" volume_up media player. """
"""volume_up media player."""
if self.volume_level < 1:
self.set_volume_level(min(1, self.volume_level + .1))
def volume_down(self):
""" volume_down media player. """
"""volume_down media player."""
if self.volume_level > 0:
self.set_volume_level(max(0, self.volume_level - .1))
def media_play_pause(self):
""" media_play_pause media player. """
"""media_play_pause media player."""
if self.state == STATE_PLAYING:
self.media_pause()
else:
@ -527,12 +526,12 @@ class MediaPlayerDevice(Entity):
@property
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
@property
def state_attributes(self):
""" Return the state attributes. """
"""Return the state attributes."""
if self.state == STATE_OFF:
state_attr = {
ATTR_SUPPORTED_MEDIA_COMMANDS: self.supported_media_commands,

View file

@ -1,7 +1,5 @@
"""
homeassistant.components.media_player.chromecast
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to interact with Cast devices on the network.
Provide functionality to interact with Cast devices on the network.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.cast/
@ -31,7 +29,7 @@ DEFAULT_PORT = 8009
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the cast platform. """
"""Setup the cast platform."""
import pychromecast
logger = logging.getLogger(__name__)
@ -70,12 +68,12 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class CastDevice(MediaPlayerDevice):
""" Represents a Cast device on the network. """
"""Representation of a Cast device on the network."""
# pylint: disable=abstract-method
# pylint: disable=too-many-public-methods
def __init__(self, host, port):
"""Initialize the Cast device."""
import pychromecast
self.cast = pychromecast.Chromecast(host, port)
@ -86,22 +84,20 @@ class CastDevice(MediaPlayerDevice):
self.cast_status = self.cast.status
self.media_status = self.cast.media_controller.status
# Entity properties and methods
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def name(self):
""" Returns the name of the device. """
"""Return the name of the device."""
return self.cast.device.friendly_name
# MediaPlayerDevice properties and methods
@property
def state(self):
""" State of the player. """
"""Return the state of the player."""
if self.media_status is None:
return STATE_UNKNOWN
elif self.media_status.player_is_playing:
@ -117,22 +113,22 @@ class CastDevice(MediaPlayerDevice):
@property
def volume_level(self):
""" Volume level of the media player (0..1). """
"""Volume level of the media player (0..1)."""
return self.cast_status.volume_level if self.cast_status else None
@property
def is_volume_muted(self):
""" Boolean if volume is currently muted. """
"""Boolean if volume is currently muted."""
return self.cast_status.volume_muted if self.cast_status else None
@property
def media_content_id(self):
""" Content ID of current playing media. """
"""Content ID of current playing media."""
return self.media_status.content_id if self.media_status else None
@property
def media_content_type(self):
""" Content type of current playing media. """
"""Content type of current playing media."""
if self.media_status is None:
return None
elif self.media_status.media_is_tvshow:
@ -145,12 +141,12 @@ class CastDevice(MediaPlayerDevice):
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
"""Duration of current playing media in seconds."""
return self.media_status.duration if self.media_status else None
@property
def media_image_url(self):
""" Image url of current playing media. """
"""Image url of current playing media."""
if self.media_status is None:
return None
@ -160,61 +156,61 @@ class CastDevice(MediaPlayerDevice):
@property
def media_title(self):
""" Title of current playing media. """
"""Title of current playing media."""
return self.media_status.title if self.media_status else None
@property
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
@property
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
@property
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
@property
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
@property
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
@property
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
@property
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
@property
def app_id(self):
""" ID of the current running app. """
"""Return the ID of the current running app."""
return self.cast.app_id
@property
def app_name(self):
""" Name of the current running app. """
"""Name of the current running app."""
return self.cast.app_display_name
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return SUPPORT_CAST
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
if not self.cast.status or not self.cast.status.is_active_input:
import pychromecast
@ -226,49 +222,48 @@ class CastDevice(MediaPlayerDevice):
CAST_SPLASH, pychromecast.STREAM_TYPE_BUFFERED)
def turn_off(self):
""" Turns Chromecast off. """
"""Turn Chromecast off."""
self.cast.quit_app()
def mute_volume(self, mute):
""" mute the volume. """
"""Mute the volume."""
self.cast.set_volume_muted(mute)
def set_volume_level(self, volume):
""" set volume level, range 0..1. """
"""Set volume level, range 0..1."""
self.cast.set_volume(volume)
def media_play(self):
""" Send play commmand. """
"""Send play commmand."""
self.cast.media_controller.play()
def media_pause(self):
""" Send pause command. """
"""Send pause command."""
self.cast.media_controller.pause()
def media_previous_track(self):
""" Send previous track command. """
"""Send previous track command."""
self.cast.media_controller.rewind()
def media_next_track(self):
""" Send next track command. """
"""Send next track command."""
self.cast.media_controller.skip()
def media_seek(self, position):
""" Seek the media to a specific location. """
"""Seek the media to a specific location."""
self.cast.media_controller.seek(position)
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)
# implementation of chromecast status_listener methods
# Implementation of chromecast status_listener methods
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.update_ha_state()
def new_media_status(self, status):
""" Called when a new media status is received. """
"""Called when a new media status is received."""
self.media_status = status
self.update_ha_state()

View file

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

View file

@ -1,7 +1,5 @@
"""
homeassistant.components.media_player.denon
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to Denon Network Receivers.
Support for Denon Network Receivers.
For more details about this platform, please refer to the documentation at
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):
""" Sets up the Denon platform. """
"""Setup the Denon platform."""
if not config.get(CONF_HOST):
_LOGGER.error(
"Missing required configuration items in %s: %s",
@ -43,11 +41,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class DenonDevice(MediaPlayerDevice):
""" Represents a Denon device. """
"""Representation of a Denon device."""
# pylint: disable=too-many-public-methods, abstract-method
def __init__(self, name, host):
"""Initialize the Denon device."""
self._name = name
self._host = host
self._pwstate = "PWSTANDBY"
@ -57,18 +55,19 @@ class DenonDevice(MediaPlayerDevice):
@classmethod
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")
return telnet.read_until(b"\r", timeout=0.2).decode("ASCII").strip()
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.write(command.encode("ASCII") + b"\r")
telnet.read_very_eager() # skip response
telnet.close()
def update(self):
"""Get the latest details from the device."""
try:
telnet = telnetlib.Telnet(self._host)
except ConnectionRefusedError:
@ -88,12 +87,12 @@ class DenonDevice(MediaPlayerDevice):
@property
def name(self):
""" Returns the name of the device. """
"""Return the name of the device."""
return self._name
@property
def state(self):
""" Returns the state of the device. """
"""Return the state of the device."""
if self._pwstate == "PWSTANDBY":
return STATE_OFF
if self._pwstate == "PWON":
@ -103,60 +102,61 @@ class DenonDevice(MediaPlayerDevice):
@property
def volume_level(self):
""" Volume level of the media player (0..1). """
"""Volume level of the media player (0..1)."""
return self._volume
@property
def is_volume_muted(self):
""" Boolean if volume is currently muted. """
"""Boolean if volume is currently muted."""
return self._muted
@property
def media_title(self):
""" Current media source. """
"""Current media source."""
return self._mediasource
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return SUPPORT_DENON
def turn_off(self):
""" turn_off media player. """
"""Turn off media player."""
self.telnet_command("PWSTANDBY")
def volume_up(self):
""" volume_up media player. """
"""Volume up media player."""
self.telnet_command("MVUP")
def volume_down(self):
""" volume_down media player. """
"""Volume down media player."""
self.telnet_command("MVDOWN")
def set_volume_level(self, volume):
""" set volume level, range 0..1. """
"""Set volume level, range 0..1."""
# 60dB max
self.telnet_command("MV" + str(round(volume * 60)).zfill(2))
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"))
def media_play(self):
""" media_play media player. """
"""Play media media player."""
self.telnet_command("NS9A")
def media_pause(self):
""" media_pause media player. """
"""Pause media player."""
self.telnet_command("NS9B")
def media_next_track(self):
""" Send next track command. """
"""Send the next track command."""
self.telnet_command("NS9D")
def media_previous_track(self):
"""Send the previous track command."""
self.telnet_command("NS9E")
def turn_on(self):
""" turn the media player on. """
"""Turn the media player on."""
self.telnet_command("PWON")

View file

@ -1,7 +1,5 @@
"""
homeassistant.components.media_player.firetv
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to interact with FireTV devices.
Support for functionality to interact with FireTV devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.firetv/
@ -31,7 +29,7 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
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')
device_id = config.get('device', 'default')
try:
@ -54,7 +52,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class FireTV(object):
""" firetv-server client.
"""The firetv-server client.
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
@ -65,12 +63,13 @@ class FireTV(object):
"""
def __init__(self, host, device_id):
"""Initialize the FireTV server."""
self.host = host
self.device_id = device_id
@property
def state(self):
""" Get the device state. An exception means UNKNOWN state. """
"""Get the device state. An exception means UNKNOWN state."""
try:
response = requests.get(
DEVICE_STATE_URL.format(
@ -85,7 +84,7 @@ class FireTV(object):
return STATE_UNKNOWN
def action(self, action_id):
""" Perform an action on the device. """
"""Perform an action on the device."""
try:
requests.get(
DEVICE_ACTION_URL.format(
@ -101,37 +100,37 @@ class FireTV(object):
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
def __init__(self, host, device, name):
"""Initialize the FireTV device."""
self._firetv = FireTV(host, device)
self._name = name
self._state = STATE_UNKNOWN
@property
def name(self):
""" Get the device name. """
"""Return the device name."""
return self._name
@property
def should_poll(self):
""" Device should be polled. """
"""Device should be polled."""
return True
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return SUPPORT_FIRETV
@property
def state(self):
""" State of the player. """
"""Return the state of the player."""
return self._state
def update(self):
""" Update device state. """
"""Get the latest date and update device state."""
self._state = {
'idle': STATE_IDLE,
'off': STATE_OFF,
@ -142,37 +141,37 @@ class FireTVDevice(MediaPlayerDevice):
}.get(self._firetv.state, STATE_UNKNOWN)
def turn_on(self):
""" Turns on the device. """
"""Turn on the device."""
self._firetv.action('turn_on')
def turn_off(self):
""" Turns off the device. """
"""Turn off the device."""
self._firetv.action('turn_off')
def media_play(self):
""" Send play command. """
"""Send play command."""
self._firetv.action('media_play')
def media_pause(self):
""" Send pause command. """
"""Send pause command."""
self._firetv.action('media_pause')
def media_play_pause(self):
""" Send play/pause command. """
"""Send play/pause command."""
self._firetv.action('media_play_pause')
def volume_up(self):
""" Send volume up command. """
"""Send volume up command."""
self._firetv.action('volume_up')
def volume_down(self):
""" Send volume down command. """
"""Send volume down command."""
self._firetv.action('volume_down')
def media_previous_track(self):
""" Send previous track command (results in rewind). """
"""Send previous track command (results in rewind)."""
self._firetv.action('media_previous')
def media_next_track(self):
""" Send next track command (results in fast-forward). """
"""Send next track command (results in fast-forward)."""
self._firetv.action('media_next')

View file

@ -1,7 +1,5 @@
"""
homeassistant.components.media_player.itunes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to iTunes API.
Support for interfacing to iTunes API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.itunes/
@ -30,22 +28,23 @@ DOMAIN = 'itunes'
class Itunes(object):
""" itunes-api client. """
"""iTunes API client."""
def __init__(self, host, port):
"""Initialize the iTunes device."""
self.host = host
self.port = port
@property
def _base_url(self):
""" Returns the base url for endpoints. """
"""Return the base url for endpoints."""
if self.port:
return self.host + ":" + str(self.port)
else:
return self.host
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
try:
@ -65,39 +64,39 @@ class Itunes(object):
return {'player_state': 'offline'}
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)
def now_playing(self):
""" Returns the current state. """
"""Return the current state."""
return self._request('GET', '/now_playing')
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})
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})
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')
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')
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')
def previous(self):
""" Skips back and returns the current state. """
"""Skip back and returns the current state."""
return self._command('previous')
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')
playlists = response.get('playlists', [])
@ -111,25 +110,25 @@ class Itunes(object):
return self._request('PUT', path)
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'
def airplay_devices(self):
""" Returns a list of AirPlay devices. """
"""Return a list of AirPlay devices."""
return self._request('GET', '/airplay_devices')
def airplay_device(self, device_id):
""" Returns an AirPlay device. """
"""Return an AirPlay device."""
return self._request('GET', '/airplay_devices/' + device_id)
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'
path = '/airplay_devices/' + device_id + '/' + command
return self._request('PUT', path)
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'
return self._request('PUT', path, {'level': level})
@ -137,8 +136,7 @@ class Itunes(object):
# pylint: disable=unused-argument, abstract-method
# pylint: disable=too-many-instance-attributes
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the itunes platform. """
"""Setup the itunes platform."""
add_devices([
ItunesDevice(
config.get('name', 'iTunes'),
@ -150,10 +148,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class ItunesDevice(MediaPlayerDevice):
""" Represents a iTunes-API instance. """
"""Representation of an iTunes API instance."""
# pylint: disable=too-many-public-methods
def __init__(self, name, host, port, add_devices):
"""Initialize the iTunes device."""
self._name = name
self._host = host
self._port = port
@ -176,7 +175,7 @@ class ItunesDevice(MediaPlayerDevice):
self.update()
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."""
self.player_state = state_hash.get('player_state', None)
self.current_volume = state_hash.get('volume', 0)
@ -189,13 +188,12 @@ class ItunesDevice(MediaPlayerDevice):
@property
def name(self):
""" Returns the name of the device. """
"""Return the name of the device."""
return self._name
@property
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:
return 'offline'
@ -211,7 +209,7 @@ class ItunesDevice(MediaPlayerDevice):
return STATE_PLAYING
def update(self):
""" Retrieve latest state. """
"""Retrieve latest state."""
now_playing = self.client.now_playing()
self.update_state(now_playing)
@ -239,28 +237,27 @@ class ItunesDevice(MediaPlayerDevice):
@property
def is_volume_muted(self):
""" Boolean if volume is currently muted. """
"""Boolean if volume is currently muted."""
return self.muted
@property
def volume_level(self):
""" Volume level of the media player (0..1). """
"""Volume level of the media player (0..1)."""
return self.current_volume/100.0
@property
def media_content_id(self):
""" Content ID of current playing media. """
"""Content ID of current playing media."""
return self.content_id
@property
def media_content_type(self):
""" Content type of current playing media. """
"""Content type of current playing media."""
return MEDIA_TYPE_MUSIC
@property
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 \
self.current_title is not None:
return self.client.artwork_url()
@ -270,76 +267,74 @@ class ItunesDevice(MediaPlayerDevice):
@property
def media_title(self):
""" Title of current playing media. """
"""Title of current playing media."""
return self.current_title
@property
def media_artist(self):
""" Artist of current playing media. (Music track only) """
"""Artist of current playing media (Music track only)."""
return self.current_artist
@property
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
@property
def media_playlist(self):
""" Title of the currently playing playlist. """
"""Title of the currently playing playlist."""
return self.current_playlist
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return SUPPORT_ITUNES
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))
self.update_state(response)
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)
self.update_state(response)
def media_play(self):
""" media_play media player. """
"""Send media_play command to media player."""
response = self.client.play()
self.update_state(response)
def media_pause(self):
""" media_pause media player. """
"""Send media_pause command to media player."""
response = self.client.pause()
self.update_state(response)
def media_next_track(self):
""" media_next media player. """
"""Send media_next command to media player."""
response = self.client.next()
self.update_state(response)
def media_previous_track(self):
""" media_previous media player. """
"""Send media_previous command media player."""
response = self.client.previous()
self.update_state(response)
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:
response = self.client.play_playlist(media_id)
self.update_state(response)
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
def __init__(self, device_id, client):
"""Initialize the AirPlay device."""
self._id = device_id
self.client = client
self.device_name = "AirPlay"
self.kind = None
self.active = False
@ -350,8 +345,7 @@ class AirPlayDevice(MediaPlayerDevice):
self.player_state = None
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:
self.player_state = state_hash.get('player_state', None)
@ -379,12 +373,12 @@ class AirPlayDevice(MediaPlayerDevice):
@property
def name(self):
""" Returns the name of the device. """
"""Return the name of the device."""
return self.device_name
@property
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:
return "mdi:volume-high"
else:
@ -392,44 +386,45 @@ class AirPlayDevice(MediaPlayerDevice):
@property
def state(self):
""" Returns the state of the device. """
"""Return the state of the device."""
if self.selected is True:
return STATE_ON
else:
return STATE_OFF
def update(self):
""" Retrieve latest state. """
"""Retrieve latest state."""
@property
def volume_level(self):
"""Return the volume."""
return float(self.volume)/100.0
@property
def media_content_type(self):
"""Flag of media content that is supported."""
return MEDIA_TYPE_MUSIC
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return SUPPORT_AIRPLAY
def set_volume_level(self, volume):
""" set volume level, range 0..1. """
"""Set volume level, range 0..1."""
volume = int(volume * 100)
response = self.client.set_volume_airplay_device(self._id, volume)
self.update_state(response)
def turn_on(self):
""" Select AirPlay. """
"""Select AirPlay."""
self.update_state({"selected": True})
self.update_ha_state()
response = self.client.toggle_airplay_device(self._id, True)
self.update_state(response)
def turn_off(self):
""" Deselect AirPlay. """
"""Deselect AirPlay."""
self.update_state({"selected": False})
self.update_ha_state()
response = self.client.toggle_airplay_device(self._id, False)

View file

@ -1,7 +1,5 @@
"""
homeassistant.components.media_player.kodi
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the XBMC/Kodi JSON-RPC API
Support for interfacing with the XBMC/Kodi JSON-RPC API.
For more details about this platform, please refer to the documentation at
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):
""" Sets up the kodi platform. """
"""Setup the Kodi platform."""
url = '{}:{}'.format(config.get('host'), config.get('port', '8080'))
jsonrpc_url = config.get('url') # deprecated
@ -42,11 +39,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class KodiDevice(MediaPlayerDevice):
""" Represents a XBMC/Kodi device. """
"""Representation of a XBMC/Kodi device."""
# pylint: disable=too-many-public-methods, abstract-method
def __init__(self, name, url, auth=None):
"""Initialize the Kodi device."""
import jsonrpc_requests
self._name = name
self._url = url
@ -61,11 +58,11 @@ class KodiDevice(MediaPlayerDevice):
@property
def name(self):
""" Returns the name of the device. """
"""Return the name of the device."""
return self._name
def _get_players(self):
""" Returns the active player objects or None """
"""Return the active player objects or None."""
import jsonrpc_requests
try:
return self._server.Player.GetActivePlayers()
@ -76,7 +73,7 @@ class KodiDevice(MediaPlayerDevice):
@property
def state(self):
""" Returns the state of the device. """
"""Return the state of the device."""
if self._players is None:
return STATE_OFF
@ -89,7 +86,7 @@ class KodiDevice(MediaPlayerDevice):
return STATE_PLAYING
def update(self):
""" Retrieve latest state. """
"""Retrieve latest state."""
self._players = self._get_players()
if self._players is not None and len(self._players) > 0:
@ -117,31 +114,31 @@ class KodiDevice(MediaPlayerDevice):
@property
def volume_level(self):
""" Volume level of the media player (0..1). """
"""Volume level of the media player (0..1)."""
if self._app_properties is not None:
return self._app_properties['volume'] / 100.0
@property
def is_volume_muted(self):
""" Boolean if volume is currently muted. """
"""Boolean if volume is currently muted."""
if self._app_properties is not None:
return self._app_properties['muted']
@property
def media_content_id(self):
""" Content ID of current playing media. """
"""Content ID of current playing media."""
if self._item is not None:
return self._item.get('uniqueid', None)
@property
def media_content_type(self):
""" Content type of current playing media. """
"""Content type of current playing media."""
if self._players is not None and len(self._players) > 0:
return self._players[0]['type']
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
"""Duration of current playing media in seconds."""
if self._properties is not None:
total_time = self._properties['totaltime']
@ -152,12 +149,12 @@ class KodiDevice(MediaPlayerDevice):
@property
def media_image_url(self):
""" Image url of current playing media. """
"""Image url of current playing media."""
if self._item is not None:
return self._get_image_url()
def _get_image_url(self):
""" Helper function that parses the thumbnail URLs used by Kodi. """
"""Helper function that parses the thumbnail URLs used by Kodi."""
url_components = urllib.parse.urlparse(self._item['thumbnail'])
if url_components.scheme == 'image':
@ -167,7 +164,7 @@ class KodiDevice(MediaPlayerDevice):
@property
def media_title(self):
""" Title of current playing media. """
"""Title of current playing media."""
# find a string we can use as a title
if self._item is not None:
return self._item.get(
@ -180,36 +177,36 @@ class KodiDevice(MediaPlayerDevice):
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return SUPPORT_KODI
def turn_off(self):
""" turn_off media player. """
"""Turn off media player."""
self._server.System.Shutdown()
self.update_ha_state()
def volume_up(self):
""" volume_up media player. """
"""Volume up the media player."""
assert self._server.Input.ExecuteAction('volumeup') == 'OK'
self.update_ha_state()
def volume_down(self):
""" volume_down media player. """
"""Volume down the media player."""
assert self._server.Input.ExecuteAction('volumedown') == 'OK'
self.update_ha_state()
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.update_ha_state()
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.update_ha_state()
def _set_play_state(self, state):
""" Helper method for play/pause/toggle. """
"""Helper method for play/pause/toggle."""
players = self._get_players()
if len(players) != 0:
@ -218,19 +215,19 @@ class KodiDevice(MediaPlayerDevice):
self.update_ha_state()
def media_play_pause(self):
""" media_play_pause media player. """
"""Pause media on media player."""
self._set_play_state('toggle')
def media_play(self):
""" media_play media player. """
"""Play media."""
self._set_play_state(True)
def media_pause(self):
""" media_pause media player. """
"""Pause the media player."""
self._set_play_state(False)
def _goto(self, direction):
""" Helper method used for previous/next track. """
"""Helper method used for previous/next track."""
players = self._get_players()
if len(players) != 0:
@ -239,18 +236,18 @@ class KodiDevice(MediaPlayerDevice):
self.update_ha_state()
def media_next_track(self):
""" Send next track command. """
"""Send next track command."""
self._goto('next')
def media_previous_track(self):
""" Send next track command. """
"""Send next track command."""
# first seek to position 0, Kodi seems to go to the beginning
# of the current track current track is not at the beginning
self.media_seek(0)
self._goto('previous')
def media_seek(self, position):
""" Send seek command. """
"""Send seek command."""
players = self._get_players()
time = {}

View file

@ -1,7 +1,5 @@
"""
homeassistant.components.media_player.mpd
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to interact with a Music Player Daemon.
Support to interact with a Music Player Daemon.
For more details about this platform, please refer to the documentation at
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
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the MPD platform. """
"""Setup the MPD platform."""
daemon = config.get('server', None)
port = config.get('port', 6600)
location = config.get('location', 'MPD')
@ -64,12 +61,12 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class MpdDevice(MediaPlayerDevice):
""" Represents a MPD server. """
"""Representation of a MPD server."""
# MPD confuses pylint
# pylint: disable=no-member, abstract-method
def __init__(self, server, port, location, password):
"""Initialize the MPD device."""
import mpd
self.server = server
@ -85,6 +82,7 @@ class MpdDevice(MediaPlayerDevice):
self.update()
def update(self):
"""Get the latest data and update the state."""
import mpd
try:
self.status = self.client.status()
@ -100,12 +98,12 @@ class MpdDevice(MediaPlayerDevice):
@property
def name(self):
""" Returns the name of the device. """
"""Return the name of the device."""
return self._name
@property
def state(self):
""" Returns the media state. """
"""Return the media state."""
if self.status['state'] == 'play':
return STATE_PLAYING
elif self.status['state'] == 'pause':
@ -115,23 +113,23 @@ class MpdDevice(MediaPlayerDevice):
@property
def media_content_id(self):
""" Content ID of current playing media. """
"""Content ID of current playing media."""
return self.currentsong['id']
@property
def media_content_type(self):
""" Content type of current playing media. """
"""Content type of current playing media."""
return MEDIA_TYPE_MUSIC
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
"""Duration of current playing media in seconds."""
# Time does not exist for streams
return self.currentsong.get('time')
@property
def media_title(self):
""" Title of current playing media. """
"""Title of current playing media."""
name = self.currentsong.get('name', None)
title = self.currentsong.get('title', None)
@ -146,61 +144,62 @@ class MpdDevice(MediaPlayerDevice):
@property
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')
@property
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')
@property
def volume_level(self):
"""Return the volume level."""
return int(self.status['volume'])/100
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return SUPPORT_MPD
def turn_off(self):
""" Service to send the MPD the command to stop playing. """
"""Service to send the MPD the command to stop playing."""
self.client.stop()
def turn_on(self):
""" Service to send the MPD the command to start playing. """
"""Service to send the MPD the command to start playing."""
self.client.play()
def set_volume_level(self, volume):
""" Sets volume """
"""Set volume of media player."""
self.client.setvol(int(volume * 100))
def volume_up(self):
""" Service to send the MPD the command for volume up. """
"""Service to send the MPD the command for volume up."""
current_volume = int(self.status['volume'])
if current_volume <= 100:
self.client.setvol(current_volume + 5)
def volume_down(self):
""" Service to send the MPD the command for volume down. """
"""Service to send the MPD the command for volume down."""
current_volume = int(self.status['volume'])
if current_volume >= 0:
self.client.setvol(current_volume - 5)
def media_play(self):
""" Service to send the MPD the command for play/pause. """
"""Service to send the MPD the command for play/pause."""
self.client.pause(0)
def media_pause(self):
""" Service to send the MPD the command for play/pause. """
"""Service to send the MPD the command for play/pause."""
self.client.pause(1)
def media_next_track(self):
""" Service to send the MPD the command for next track. """
"""Service to send the MPD the command for next track."""
self.client.next()
def media_previous_track(self):
""" Service to send the MPD the command for previous track. """
"""Service to send the MPD the command for previous track."""
self.client.previous()

View file

@ -1,7 +1,5 @@
"""
homeassistant.components.media_player.plex
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the Plex API.
Support to interface with the Plex API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.plex/
@ -35,7 +33,7 @@ SUPPORT_PLEX = SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK
def config_from_file(filename, config=None):
""" Small configuration file management function. """
"""Small configuration file management function."""
if config:
# We're writing configuration
try:
@ -61,8 +59,7 @@ def config_from_file(filename, config=None):
# pylint: disable=abstract-method
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))
if len(config):
# Setup a configured PlexServer
@ -85,7 +82,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
# pylint: disable=too-many-branches
def setup_plexserver(host, token, hass, add_devices_callback):
""" Setup a plexserver based on host parameter. """
"""Setup a plexserver based on host parameter."""
import plexapi.server
import plexapi.exceptions
@ -119,7 +116,7 @@ def setup_plexserver(host, token, hass, add_devices_callback):
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_devices():
""" Updates the devices objects. """
"""Update the devices objects."""
try:
devices = plexserver.clients()
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)
def update_sessions():
""" Updates the sessions objects. """
"""Update the sessions objects."""
try:
sessions = plexserver.sessions()
except plexapi.exceptions.BadRequest:
@ -161,7 +158,7 @@ def setup_plexserver(host, token, hass, add_devices_callback):
def request_configuration(host, hass, add_devices_callback):
""" Request configuration steps from the user. """
"""Request configuration steps from the user."""
configurator = get_component('configurator')
# We got an error if this method is called while we are configuring
@ -172,7 +169,7 @@ def request_configuration(host, hass, add_devices_callback):
return
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)
_CONFIGURING[host] = configurator.request_config(
@ -185,33 +182,34 @@ def request_configuration(host, hass, add_devices_callback):
class PlexClient(MediaPlayerDevice):
""" Represents a Plex device. """
"""Representation of a Plex device."""
# pylint: disable=too-many-public-methods, attribute-defined-outside-init
def __init__(self, device, plex_sessions, update_devices, update_sessions):
"""Initialize the Plex device."""
self.plex_sessions = plex_sessions
self.update_devices = update_devices
self.update_sessions = update_sessions
self.set_device(device)
def set_device(self, device):
""" Sets the device property. """
"""Set the device property."""
self.device = device
@property
def unique_id(self):
""" Returns the id of this plex client """
"""Return the id of this plex client."""
return "{}.{}".format(
self.__class__, self.device.machineIdentifier or self.device.name)
@property
def name(self):
""" Returns the name of the device. """
"""Return the name of the device."""
return self.device.name or DEVICE_DEFAULT_NAME
@property
def session(self):
""" Returns the session, if any. """
"""Return the session, if any."""
if self.device.machineIdentifier not in self.plex_sessions:
return None
@ -219,7 +217,7 @@ class PlexClient(MediaPlayerDevice):
@property
def state(self):
""" Returns the state of the device. """
"""Return the state of the device."""
if self.session:
state = self.session.player.state
if state == 'playing':
@ -235,18 +233,19 @@ class PlexClient(MediaPlayerDevice):
return STATE_UNKNOWN
def update(self):
"""Get the latest details."""
self.update_devices(no_throttle=True)
self.update_sessions(no_throttle=True)
@property
def media_content_id(self):
""" Content ID of current playing media. """
"""Content ID of current playing media."""
if self.session is not None:
return self.session.ratingKey
@property
def media_content_type(self):
""" Content type of current playing media. """
"""Content type of current playing media."""
if self.session is None:
return None
media_type = self.session.type
@ -258,61 +257,61 @@ class PlexClient(MediaPlayerDevice):
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
"""Duration of current playing media in seconds."""
if self.session is not None:
return self.session.duration
@property
def media_image_url(self):
""" Image url of current playing media. """
"""Image url of current playing media."""
if self.session is not None:
return self.session.thumbUrl
@property
def media_title(self):
""" Title of current playing media. """
"""Title of current playing media."""
# find a string we can use as a title
if self.session is not None:
return self.session.title
@property
def media_season(self):
""" Season of curent playing media (TV Show only). """
"""Season of curent playing media (TV Show only)."""
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.seasons()[0].index
@property
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
if isinstance(self.session, Show):
return self.session.grandparentTitle
@property
def media_episode(self):
""" Episode of current playing media (TV Show only). """
"""Episode of current playing media (TV Show only)."""
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.index
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return SUPPORT_PLEX
def media_play(self):
""" media_play media player. """
"""Send play command."""
self.device.play()
def media_pause(self):
""" media_pause media player. """
"""Send pause command."""
self.device.pause()
def media_next_track(self):
""" Send next track command. """
"""Send next track command."""
self.device.skipNext()
def media_previous_track(self):
""" Send previous track command. """
"""Send previous track command."""
self.device.skipPrevious()

View file

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

View file

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

View file

@ -1,7 +1,5 @@
"""
homeassistant.components.media_player.sonos
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to Sonos players (via SoCo)
Support to interface with Sonos players (via SoCo).
For more details about this platform, please refer to the documentation at
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
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Sonos platform. """
"""Setup the Sonos platform."""
import soco
import socket
@ -67,15 +65,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
def only_if_coordinator(func):
"""
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
"""
"""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
"""
def wrapper(*args, **kwargs):
""" Decorator wrapper """
"""Decorator wrapper."""
if args[0].is_coordinator:
return func(*args, **kwargs)
else:
@ -89,10 +86,11 @@ def only_if_coordinator(func):
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=abstract-method
class SonosDevice(MediaPlayerDevice):
""" Represents a Sonos device. """
"""Representation of a Sonos device."""
# pylint: disable=too-many-arguments
def __init__(self, hass, player):
"""Initialize the Sonos device."""
self.hass = hass
super(SonosDevice, self).__init__()
self._player = player
@ -100,25 +98,26 @@ class SonosDevice(MediaPlayerDevice):
@property
def should_poll(self):
"""No polling needed."""
return True
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)
@property
def name(self):
""" Returns the name of the device. """
"""Return the name of the device."""
return self._name
@property
def unique_id(self):
""" Returns a unique id. """
"""Return a unique ID."""
return "{}.{}".format(self.__class__, self._player.uid)
@property
def state(self):
""" Returns the state of the device. """
"""Return the state of the device."""
if self._status == 'PAUSED_PLAYBACK':
return STATE_PAUSED
if self._status == 'PLAYING':
@ -129,11 +128,11 @@ class SonosDevice(MediaPlayerDevice):
@property
def is_coordinator(self):
""" Returns true if player is a coordinator """
"""Return true if player is a coordinator."""
return self._player.is_coordinator
def update(self):
""" Retrieve latest state. """
"""Retrieve latest state."""
self._name = self._player.get_speaker_info()['zone_name'].replace(
' (R)', '').replace(' (L)', '')
self._status = self._player.get_current_transport_info().get(
@ -142,26 +141,27 @@ class SonosDevice(MediaPlayerDevice):
@property
def volume_level(self):
""" Volume level of the media player (0..1). """
"""Volume level of the media player (0..1)."""
return self._player.volume / 100.0
@property
def is_volume_muted(self):
"""Return true if volume is muted."""
return self._player.mute
@property
def media_content_id(self):
""" Content ID of current playing media. """
"""Content ID of current playing media."""
return self._trackinfo.get('title', None)
@property
def media_content_type(self):
""" Content type of current playing media. """
"""Content type of current playing media."""
return MEDIA_TYPE_MUSIC
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
"""Duration of current playing media in seconds."""
dur = self._trackinfo.get('duration', '0:00')
# If the speaker is playing from the "line-in" source, getting
@ -175,13 +175,13 @@ class SonosDevice(MediaPlayerDevice):
@property
def media_image_url(self):
""" Image url of current playing media. """
"""Image url of current playing media."""
if 'album_art' in self._trackinfo:
return self._trackinfo['album_art']
@property
def media_title(self):
""" Title of current playing media. """
"""Title of current playing media."""
if 'artist' in self._trackinfo and 'title' in self._trackinfo:
return '{artist} - {title}'.format(
artist=self._trackinfo['artist'],
@ -192,60 +192,60 @@ class SonosDevice(MediaPlayerDevice):
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return SUPPORT_SONOS
@only_if_coordinator
def turn_off(self):
""" Turn off media player. """
"""Turn off media player."""
self._player.pause()
@only_if_coordinator
def volume_up(self):
""" Volume up media player. """
"""Volume up media player."""
self._player.volume += 1
@only_if_coordinator
def volume_down(self):
""" Volume down media player. """
"""Volume down media player."""
self._player.volume -= 1
@only_if_coordinator
def set_volume_level(self, volume):
""" Set volume level, range 0..1. """
"""Set volume level, range 0..1."""
self._player.volume = str(int(volume * 100))
@only_if_coordinator
def mute_volume(self, mute):
""" Mute (true) or unmute (false) media player. """
"""Mute (true) or unmute (false) media player."""
self._player.mute = mute
@only_if_coordinator
def media_play(self):
""" Send paly command. """
"""Send paly command."""
self._player.play()
@only_if_coordinator
def media_pause(self):
""" Send pause command. """
"""Send pause command."""
self._player.pause()
@only_if_coordinator
def media_next_track(self):
""" Send next track command. """
"""Send next track command."""
self._player.next()
@only_if_coordinator
def media_previous_track(self):
""" Send next track command. """
"""Send next track command."""
self._player.previous()
@only_if_coordinator
def media_seek(self, position):
""" Send seek command. """
"""Send seek command."""
self._player.seek(str(datetime.timedelta(seconds=int(position))))
@only_if_coordinator
def turn_on(self):
""" Turn the media player on. """
"""Turn the media player on."""
self._player.play()

View file

@ -1,7 +1,5 @@
"""
homeassistant.components.media_player.squeezebox
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the Logitech SqueezeBox API
Support for interfacing to the Logitech SqueezeBox API.
For more details about this platform, please refer to the documentation at
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):
""" Sets up the squeezebox platform. """
"""Setup the squeezebox platform."""
if not config.get(CONF_HOST):
_LOGGER.error(
"Missing required configuration items in %s: %s",
@ -49,9 +47,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class LogitechMediaServer(object):
""" Represents a Logitech media server. """
"""Representation of a Logitech media server."""
def __init__(self, host, port, username, password):
"""Initialize the Logitech device."""
self.host = host
self.port = port
self._username = username
@ -60,7 +59,7 @@ class LogitechMediaServer(object):
self.init_success = True if self.http_port else False
def _get_http_port(self):
""" Get http port from media server, it is used to get cover art. """
"""Get http port from media server, it is used to get cover art."""
http_port = None
try:
http_port = self.query('pref', 'httpport', '?')
@ -80,7 +79,7 @@ class LogitechMediaServer(object):
return
def create_players(self):
""" Create a list of SqueezeBoxDevices connected to the LMS. """
"""Create a list of SqueezeBoxDevices connected to the LMS."""
players = []
count = self.query('player', 'count', '?')
for index in range(0, int(count)):
@ -90,7 +89,7 @@ class LogitechMediaServer(object):
return players
def query(self, *parameters):
""" Send request and await response from server. """
"""Send request and await response from server."""
telnet = telnetlib.Telnet(self.host, self.port)
if self._username and self._password:
telnet.write('login {username} {password}\n'.format(
@ -107,7 +106,7 @@ class LogitechMediaServer(object):
return urllib.parse.unquote(response)
def get_player_status(self, player):
""" Get ithe status of a player. """
"""Get ithe status of a player."""
# (title) : Song title
# Requested Information
# a (artist): Artist name 'artist'
@ -133,10 +132,11 @@ class LogitechMediaServer(object):
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-public-methods
class SqueezeBoxDevice(MediaPlayerDevice):
""" Represents a SqueezeBox device. """
"""Representation of a SqueezeBox device."""
# pylint: disable=too-many-arguments, abstract-method
def __init__(self, lms, player_id):
"""Initialize the SqeezeBox device."""
super(SqueezeBoxDevice, self).__init__()
self._lms = lms
self._id = player_id
@ -145,12 +145,12 @@ class SqueezeBoxDevice(MediaPlayerDevice):
@property
def name(self):
""" Returns the name of the device. """
"""Return the name of the device."""
return self._name
@property
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':
return STATE_OFF
if 'mode' in self._status:
@ -163,40 +163,41 @@ class SqueezeBoxDevice(MediaPlayerDevice):
return STATE_UNKNOWN
def update(self):
""" Retrieve latest state. """
"""Retrieve latest state."""
self._status = self._lms.get_player_status(self._id)
@property
def volume_level(self):
""" Volume level of the media player (0..1). """
"""Volume level of the media player (0..1)."""
if 'mixer volume' in self._status:
return int(float(self._status['mixer volume'])) / 100.0
@property
def is_volume_muted(self):
"""Return true if volume is muted."""
if 'mixer volume' in self._status:
return self._status['mixer volume'].startswith('-')
@property
def media_content_id(self):
""" Content ID of current playing media. """
"""Content ID of current playing media."""
if 'current_title' in self._status:
return self._status['current_title']
@property
def media_content_type(self):
""" Content type of current playing media. """
"""Content type of current playing media."""
return MEDIA_TYPE_MUSIC
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
"""Duration of current playing media in seconds."""
if 'duration' in self._status:
return int(float(self._status['duration']))
@property
def media_image_url(self):
""" Image url of current playing media. """
"""Image url of current playing media."""
if 'artwork_url' in self._status:
media_url = self._status['artwork_url']
elif 'id' in self._status:
@ -214,7 +215,7 @@ class SqueezeBoxDevice(MediaPlayerDevice):
@property
def media_title(self):
""" Title of current playing media. """
"""Title of current playing media."""
if 'artist' in self._status and 'title' in self._status:
return '{artist} - {title}'.format(
artist=self._status['artist'],
@ -225,67 +226,67 @@ class SqueezeBoxDevice(MediaPlayerDevice):
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
"""Flag of media commands that are supported."""
return SUPPORT_SQUEEZEBOX
def turn_off(self):
""" turn_off media player. """
"""Turn off media player."""
self._lms.query(self._id, 'power', '0')
self.update_ha_state()
def volume_up(self):
""" volume_up media player. """
"""Volume up media player."""
self._lms.query(self._id, 'mixer', 'volume', '+5')
self.update_ha_state()
def volume_down(self):
""" volume_down media player. """
"""Volume down media player."""
self._lms.query(self._id, 'mixer', 'volume', '-5')
self.update_ha_state()
def set_volume_level(self, volume):
""" set volume level, range 0..1. """
"""Set volume level, range 0..1."""
volume_percent = str(int(volume*100))
self._lms.query(self._id, 'mixer', 'volume', volume_percent)
self.update_ha_state()
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'
self._lms.query(self._id, 'mixer', 'muting', mute_numeric)
self.update_ha_state()
def media_play_pause(self):
""" media_play_pause media player. """
"""Send pause command to media player."""
self._lms.query(self._id, 'pause')
self.update_ha_state()
def media_play(self):
""" media_play media player. """
"""Send play command to media player."""
self._lms.query(self._id, 'play')
self.update_ha_state()
def media_pause(self):
""" media_pause media player. """
"""Send pause command to media player."""
self._lms.query(self._id, 'pause', '1')
self.update_ha_state()
def media_next_track(self):
""" Send next track command. """
"""Send next track command."""
self._lms.query(self._id, 'playlist', 'index', '+1')
self.update_ha_state()
def media_previous_track(self):
""" Send next track command. """
"""Send next track command."""
self._lms.query(self._id, 'playlist', 'index', '-1')
self.update_ha_state()
def media_seek(self, position):
""" Send seek command. """
"""Send seek command."""
self._lms.query(self._id, 'time', position)
self.update_ha_state()
def turn_on(self):
""" turn the media player on. """
"""Turn the media player on."""
self._lms.query(self._id, 'power', '1')
self.update_ha_state()

View file

@ -1,7 +1,5 @@
"""
homeassistant.components.media_player.universal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Combines multiple media players into one for a universal controller.
Combination of multiple media players into one for a universal controller.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.universal/
@ -47,7 +45,7 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
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):
return
@ -61,10 +59,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
def validate_config(config):
""" validate universal media player configuration """
"""Validate universal media player configuration."""
del config[CONF_PLATFORM]
# validate name
# Validate name
if CONF_NAME not in config:
_LOGGER.error('Universal Media Player configuration requires name')
return False
@ -87,7 +85,7 @@ def validate_config(config):
def validate_children(config):
""" validate children """
"""Validate children."""
if CONF_CHILDREN not in config:
_LOGGER.info(
'No children under Universal Media Player (%s)', config[CONF_NAME])
@ -101,7 +99,7 @@ def validate_children(config):
def validate_commands(config):
""" validate commands """
"""Validate commands."""
if CONF_COMMANDS not in config:
config[CONF_COMMANDS] = {}
elif not isinstance(config[CONF_COMMANDS], dict):
@ -113,7 +111,7 @@ def validate_commands(config):
def validate_attributes(config):
""" validate attributes """
"""Validate attributes."""
if CONF_ATTRS not in config:
config[CONF_ATTRS] = {}
elif not isinstance(config[CONF_ATTRS], dict):
@ -131,10 +129,11 @@ def validate_attributes(config):
class UniversalMediaPlayer(MediaPlayerDevice):
""" Represents a universal media player in HA """
# pylint: disable=too-many-public-methods
"""Representation of an universal media player."""
# pylint: disable=too-many-public-methods
def __init__(self, hass, name, children, commands, attributes):
"""Initialize the Universal media device."""
# pylint: disable=too-many-arguments
self.hass = hass
self._name = name
@ -144,7 +143,7 @@ class UniversalMediaPlayer(MediaPlayerDevice):
self._child_state = None
def on_dependency_update(*_):
""" update ha state when dependencies update """
"""Update ha state when dependencies update."""
self.update_ha_state(True)
depend = copy(children)
@ -154,7 +153,7 @@ class UniversalMediaPlayer(MediaPlayerDevice):
track_state_change(hass, depend, on_dependency_update)
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)
if state_obj is None:
@ -165,7 +164,7 @@ class UniversalMediaPlayer(MediaPlayerDevice):
return state_obj.state
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:
return self._entity_lkp(self._attrs[attr_name][0],
self._attrs[attr_name][1])
@ -173,13 +172,13 @@ class UniversalMediaPlayer(MediaPlayerDevice):
return self._child_attr(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
return active_child.attributes.get(attr_name) if active_child else None
def _call_service(self, service_name, service_data=None,
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:
call_from_config(
self.hass, self._cmds[service_name], blocking=True)
@ -196,12 +195,12 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property
def should_poll(self):
""" Indicates whether HA should poll for updates """
"""No polling needed."""
return False
@property
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:
master_state = self._entity_lkp(self._attrs[CONF_STATE][0],
self._attrs[CONF_STATE][1])
@ -211,17 +210,16 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property
def name(self):
""" name of universal player """
"""Return the name of universal player."""
return self._name
@property
def state(self):
"""
Current state of media player
"""Current state of media player.
Off if master state is off
ELSE Status of first active child
ELSE master state or off
else Status of first active child
else master state or off
"""
master_state = self.master_state # avoid multiple lookups
if master_state == STATE_OFF:
@ -235,98 +233,98 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property
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)
@property
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) \
in [True, STATE_ON]
@property
def media_content_id(self):
""" Content ID of current playing media. """
"""Content ID of current playing media."""
return self._child_attr(ATTR_MEDIA_CONTENT_ID)
@property
def media_content_type(self):
""" Content type of current playing media. """
"""Content type of current playing media."""
return self._child_attr(ATTR_MEDIA_CONTENT_TYPE)
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
"""Duration of current playing media in seconds."""
return self._child_attr(ATTR_MEDIA_DURATION)
@property
def media_image_url(self):
""" Image url of current playing media. """
"""Image url of current playing media."""
return self._child_attr(ATTR_ENTITY_PICTURE)
@property
def media_title(self):
""" Title of current playing media. """
"""Title of current playing media."""
return self._child_attr(ATTR_MEDIA_TITLE)
@property
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)
@property
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)
@property
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)
@property
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)
@property
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)
@property
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)
@property
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)
@property
def media_channel(self):
""" Channel currently playing. """
"""Channel currently playing."""
return self._child_attr(ATTR_MEDIA_CHANNEL)
@property
def media_playlist(self):
""" Title of Playlist currently playing. """
"""Title of Playlist currently playing."""
return self._child_attr(ATTR_MEDIA_PLAYLIST)
@property
def app_id(self):
""" ID of the current running app. """
"""ID of the current running app."""
return self._child_attr(ATTR_APP_ID)
@property
def app_name(self):
""" Name of the current running app. """
"""Name of the current running app."""
return self._child_attr(ATTR_APP_NAME)
@property
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
if SERVICE_TURN_ON in self._cmds:
@ -347,69 +345,69 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property
def device_state_attributes(self):
""" Extra attributes a device wants to expose. """
"""Extra attributes a device wants to expose."""
active_child = self._child_state
return {ATTR_ACTIVE_CHILD: active_child.entity_id} \
if active_child else {}
def turn_on(self):
""" turn the media player on. """
"""Turn the media player on."""
self._call_service(SERVICE_TURN_ON, allow_override=True)
def turn_off(self):
""" turn the media player off. """
"""Turn the media player off."""
self._call_service(SERVICE_TURN_OFF, allow_override=True)
def mute_volume(self, is_volume_muted):
""" mute the volume. """
"""Mute the volume."""
data = {ATTR_MEDIA_VOLUME_MUTED: is_volume_muted}
self._call_service(SERVICE_VOLUME_MUTE, data, allow_override=True)
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}
self._call_service(SERVICE_VOLUME_SET, data)
def media_play(self):
""" Send play commmand. """
"""Send play commmand."""
self._call_service(SERVICE_MEDIA_PLAY)
def media_pause(self):
""" Send pause command. """
"""Send pause command."""
self._call_service(SERVICE_MEDIA_PAUSE)
def media_previous_track(self):
""" Send previous track command. """
"""Send previous track command."""
self._call_service(SERVICE_MEDIA_PREVIOUS_TRACK)
def media_next_track(self):
""" Send next track command. """
"""Send next track command."""
self._call_service(SERVICE_MEDIA_NEXT_TRACK)
def media_seek(self, position):
""" Send seek command. """
"""Send seek command."""
data = {ATTR_MEDIA_SEEK_POSITION: position}
self._call_service(SERVICE_MEDIA_SEEK, data)
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}
self._call_service(SERVICE_PLAY_MEDIA, data)
def volume_up(self):
""" volume_up media player. """
"""Volume up media player."""
self._call_service(SERVICE_VOLUME_UP, allow_override=True)
def volume_down(self):
""" volume_down media player. """
"""Volume down media player."""
self._call_service(SERVICE_VOLUME_DOWN, allow_override=True)
def media_play_pause(self):
""" media_play_pause media player. """
"""Send play/pause command media player."""
self._call_service(SERVICE_MEDIA_PLAY_PAUSE)
def update(self):
""" event to trigger a state update in HA """
"""Event to trigger a state update."""
for child_name in self._children:
child_state = self.hass.states.get(child_name)
if child_state and child_state.state not in OFF_STATES: