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,45 +108,47 @@ 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)
def turn_on(hass, entity_id=None): 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 {} data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_TURN_ON, data) hass.services.call(DOMAIN, SERVICE_TURN_ON, data)
def turn_off(hass, entity_id=None): 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 {} data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_TURN_OFF, data) hass.services.call(DOMAIN, SERVICE_TURN_OFF, data)
def toggle(hass, entity_id=None): 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 {} data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_TOGGLE, data) hass.services.call(DOMAIN, SERVICE_TOGGLE, data)
def volume_up(hass, entity_id=None): 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 {} data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_VOLUME_UP, data) hass.services.call(DOMAIN, SERVICE_VOLUME_UP, data)
def volume_down(hass, entity_id=None): 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 {} data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_VOLUME_DOWN, data) hass.services.call(DOMAIN, SERVICE_VOLUME_DOWN, data)
def mute_volume(hass, mute, entity_id=None): 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} data = {ATTR_MEDIA_VOLUME_MUTED: mute}
if entity_id: if entity_id:
@ -158,7 +158,7 @@ def mute_volume(hass, mute, entity_id=None):
def set_volume_level(hass, volume, 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} data = {ATTR_MEDIA_VOLUME_LEVEL: volume}
if entity_id: if entity_id:
@ -168,44 +168,44 @@ def set_volume_level(hass, volume, entity_id=None):
def media_play_pause(hass, 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 {} data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_MEDIA_PLAY_PAUSE, data) hass.services.call(DOMAIN, SERVICE_MEDIA_PLAY_PAUSE, data)
def media_play(hass, entity_id=None): 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 {} data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_MEDIA_PLAY, data) hass.services.call(DOMAIN, SERVICE_MEDIA_PLAY, data)
def media_pause(hass, entity_id=None): 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 {} data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_MEDIA_PAUSE, data) hass.services.call(DOMAIN, SERVICE_MEDIA_PAUSE, data)
def media_next_track(hass, entity_id=None): 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 {} data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_MEDIA_NEXT_TRACK, data) hass.services.call(DOMAIN, SERVICE_MEDIA_NEXT_TRACK, data)
def media_previous_track(hass, entity_id=None): 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 {} data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK, data) hass.services.call(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK, data)
def media_seek(hass, position, entity_id=None): 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_ENTITY_ID: entity_id} if entity_id else {}
data[ATTR_MEDIA_SEEK_POSITION] = position data[ATTR_MEDIA_SEEK_POSITION] = position
hass.services.call(DOMAIN, SERVICE_MEDIA_SEEK, data) hass.services.call(DOMAIN, SERVICE_MEDIA_SEEK, data)
def play_media(hass, media_type, media_id, entity_id=None): 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} data = {"media_type": media_type, "media_id": media_id}
if entity_id: if entity_id:
@ -215,7 +215,7 @@ def play_media(hass, media_type, media_id, entity_id=None):
def setup(hass, config): def setup(hass, config):
""" Track states and offer events for media_players. """ """Track states and offer events for media_players."""
component = EntityComponent( component = EntityComponent(
logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL, logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL,
DISCOVERY_PLATFORMS) DISCOVERY_PLATFORMS)
@ -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]
@ -242,7 +242,7 @@ def setup(hass, config):
descriptions.get(service)) descriptions.get(service))
def volume_set_service(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) target_players = component.extract_from_service(service)
if ATTR_MEDIA_VOLUME_LEVEL not in service.data: if ATTR_MEDIA_VOLUME_LEVEL not in service.data:
@ -260,7 +260,7 @@ def setup(hass, config):
descriptions.get(SERVICE_VOLUME_SET)) descriptions.get(SERVICE_VOLUME_SET))
def volume_mute_service(service): 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) target_players = component.extract_from_service(service)
if ATTR_MEDIA_VOLUME_MUTED not in service.data: if ATTR_MEDIA_VOLUME_MUTED not in service.data:
@ -278,7 +278,7 @@ def setup(hass, config):
descriptions.get(SERVICE_VOLUME_MUTE)) descriptions.get(SERVICE_VOLUME_MUTE))
def media_seek_service(service): def media_seek_service(service):
""" Seek to a position. """ """Seek to a position."""
target_players = component.extract_from_service(service) target_players = component.extract_from_service(service)
if ATTR_MEDIA_SEEK_POSITION not in service.data: if ATTR_MEDIA_SEEK_POSITION not in service.data:
@ -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,206 +320,205 @@ 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."""
return STATE_UNKNOWN return STATE_UNKNOWN
@property @property
def volume_level(self): def volume_level(self):
""" Volume level of the media player (0..1). """ """Volume level of the media player (0..1)."""
return None return None
@property @property
def is_volume_muted(self): def is_volume_muted(self):
""" Boolean if volume is currently muted. """ """Boolean if volume is currently muted."""
return None return None
@property @property
def media_content_id(self): def media_content_id(self):
""" Content ID of current playing media. """ """Content ID of current playing media."""
return None return None
@property @property
def media_content_type(self): def media_content_type(self):
""" Content type of current playing media. """ """Content type of current playing media."""
return None return None
@property @property
def media_duration(self): def media_duration(self):
""" Duration of current playing media in seconds. """ """Duration of current playing media in seconds."""
return None return None
@property @property
def media_image_url(self): def media_image_url(self):
""" Image url of current playing media. """ """Image url of current playing media."""
return None return None
@property @property
def media_title(self): def media_title(self):
""" Title of current playing media. """ """Title of current playing media."""
return None return None
@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
def media_channel(self): def media_channel(self):
""" Channel currently playing. """ """Channel currently playing."""
return None return None
@property @property
def media_playlist(self): def media_playlist(self):
""" Title of Playlist currently playing. """ """Title of Playlist currently playing."""
return None return None
@property @property
def app_id(self): def app_id(self):
""" ID of the current running app. """ """ID of the current running app."""
return None return None
@property @property
def app_name(self): def app_name(self):
""" Name of the current running app. """ """Name of the current running app."""
return None return None
@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):
""" Send play commmand. """ """Send play commmand."""
raise NotImplementedError() raise NotImplementedError()
def media_pause(self): def media_pause(self):
""" Send pause command. """ """Send pause command."""
raise NotImplementedError() raise NotImplementedError()
def media_previous_track(self): def media_previous_track(self):
""" Send previous track command. """ """Send previous track command."""
raise NotImplementedError() raise NotImplementedError()
def media_next_track(self): def media_next_track(self):
""" Send next track command. """ """Send next track command."""
raise NotImplementedError() raise NotImplementedError()
def media_seek(self, position): def media_seek(self, position):
""" Send seek command. """ """Send seek command."""
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.
@property @property
def support_pause(self): def support_pause(self):
""" Boolean if pause is supported. """ """Boolean if pause is supported."""
return bool(self.supported_media_commands & SUPPORT_PAUSE) return bool(self.supported_media_commands & SUPPORT_PAUSE)
@property @property
def support_seek(self): def support_seek(self):
""" Boolean if seek is supported. """ """Boolean if seek is supported."""
return bool(self.supported_media_commands & SUPPORT_SEEK) return bool(self.supported_media_commands & SUPPORT_SEEK)
@property @property
def support_volume_set(self): 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) return bool(self.supported_media_commands & SUPPORT_VOLUME_SET)
@property @property
def support_volume_mute(self): 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) return bool(self.supported_media_commands & SUPPORT_VOLUME_MUTE)
@property @property
def support_previous_track(self): 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) return bool(self.supported_media_commands & SUPPORT_PREVIOUS_TRACK)
@property @property
def support_next_track(self): 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) return bool(self.supported_media_commands & SUPPORT_NEXT_TRACK)
@property @property
def support_play_media(self): 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) 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:
self.turn_off() self.turn_off()
def volume_up(self): def volume_up(self):
""" volume_up media player. """ """volume_up media player."""
if self.volume_level < 1: if self.volume_level < 1:
self.set_volume_level(min(1, self.volume_level + .1)) self.set_volume_level(min(1, self.volume_level + .1))
def volume_down(self): def volume_down(self):
""" volume_down media player. """ """volume_down media player."""
if self.volume_level > 0: if self.volume_level > 0:
self.set_volume_level(max(0, self.volume_level - .1)) self.set_volume_level(max(0, self.volume_level - .1))
def media_play_pause(self): def media_play_pause(self):
""" media_play_pause media player. """ """media_play_pause media player."""
if self.state == STATE_PLAYING: if self.state == STATE_PLAYING:
self.media_pause() self.media_pause()
else: else:
@ -527,12 +526,12 @@ 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
def state_attributes(self): def state_attributes(self):
""" Return the state attributes. """ """Return the state attributes."""
if self.state == STATE_OFF: if self.state == STATE_OFF:
state_attr = { state_attr = {
ATTR_SUPPORTED_MEDIA_COMMANDS: self.supported_media_commands, ATTR_SUPPORTED_MEDIA_COMMANDS: self.supported_media_commands,

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:
@ -117,22 +113,22 @@ class CastDevice(MediaPlayerDevice):
@property @property
def volume_level(self): 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 return self.cast_status.volume_level if self.cast_status else None
@property @property
def is_volume_muted(self): 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 return self.cast_status.volume_muted if self.cast_status else None
@property @property
def media_content_id(self): 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 return self.media_status.content_id if self.media_status else None
@property @property
def media_content_type(self): def media_content_type(self):
""" Content type of current playing media. """ """Content type of current playing media."""
if self.media_status is None: if self.media_status is None:
return None return None
elif self.media_status.media_is_tvshow: elif self.media_status.media_is_tvshow:
@ -145,12 +141,12 @@ class CastDevice(MediaPlayerDevice):
@property @property
def media_duration(self): 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 return self.media_status.duration if self.media_status else None
@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.media_status is None: if self.media_status is None:
return None return None
@ -160,61 +156,61 @@ class CastDevice(MediaPlayerDevice):
@property @property
def media_title(self): 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 return self.media_status.title if self.media_status else None
@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
def app_name(self): def app_name(self):
""" Name of the current running app. """ """Name of the current running app."""
return self.cast.app_display_name return self.cast.app_display_name
@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,49 +222,48 @@ 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):
""" Send play commmand. """ """Send play commmand."""
self.cast.media_controller.play() self.cast.media_controller.play()
def media_pause(self): def media_pause(self):
""" Send pause command. """ """Send pause command."""
self.cast.media_controller.pause() self.cast.media_controller.pause()
def media_previous_track(self): def media_previous_track(self):
""" Send previous track command. """ """Send previous track command."""
self.cast.media_controller.rewind() self.cast.media_controller.rewind()
def media_next_track(self): def media_next_track(self):
""" Send next track command. """ """Send next track command."""
self.cast.media_controller.skip() self.cast.media_controller.skip()
def media_seek(self, position): 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) 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
self.update_ha_state() self.update_ha_state()
def new_media_status(self, status): 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.media_status = status
self.update_ha_state() self.update_ha_state()

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
@ -125,7 +129,7 @@ class DemoYoutubePlayer(AbstractDemoPlayer):
@property @property
def media_duration(self): def media_duration(self):
""" Return the duration of current playing media in seconds.""" """Return the duration of current playing media in seconds."""
return 360 return 360
@property @property
@ -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":
@ -103,60 +102,61 @@ class DenonDevice(MediaPlayerDevice):
@property @property
def volume_level(self): def volume_level(self):
""" Volume level of the media player (0..1). """ """Volume level of the media player (0..1)."""
return self._volume return self._volume
@property @property
def is_volume_muted(self): def is_volume_muted(self):
""" Boolean if volume is currently muted. """ """Boolean if volume is currently muted."""
return self._muted return self._muted
@property @property
def media_title(self): def media_title(self):
""" Current media source. """ """Current media source."""
return self._mediasource return self._mediasource
@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,12 +63,13 @@ 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
@property @property
def state(self): def state(self):
""" Get the device state. An exception means UNKNOWN state. """ """Get the device state. An exception means UNKNOWN state."""
try: try:
response = requests.get( response = requests.get(
DEVICE_STATE_URL.format( DEVICE_STATE_URL.format(
@ -85,7 +84,7 @@ class FireTV(object):
return STATE_UNKNOWN return STATE_UNKNOWN
def action(self, action_id): def action(self, action_id):
""" Perform an action on the device. """ """Perform an action on the device."""
try: try:
requests.get( requests.get(
DEVICE_ACTION_URL.format( DEVICE_ACTION_URL.format(
@ -101,37 +100,37 @@ 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
def should_poll(self): def should_poll(self):
""" Device should be polled. """ """Device should be polled."""
return True return True
@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,37 +141,37 @@ 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):
""" Send play command. """ """Send play command."""
self._firetv.action('media_play') self._firetv.action('media_play')
def media_pause(self): def media_pause(self):
""" Send pause command. """ """Send pause command."""
self._firetv.action('media_pause') self._firetv.action('media_pause')
def media_play_pause(self): def media_play_pause(self):
""" Send play/pause command. """ """Send play/pause command."""
self._firetv.action('media_play_pause') self._firetv.action('media_play_pause')
def volume_up(self): def volume_up(self):
""" Send volume up command. """ """Send volume up command."""
self._firetv.action('volume_up') self._firetv.action('volume_up')
def volume_down(self): def volume_down(self):
""" Send volume down command. """ """Send volume down command."""
self._firetv.action('volume_down') self._firetv.action('volume_down')
def media_previous_track(self): def media_previous_track(self):
""" Send previous track command (results in rewind). """ """Send previous track command (results in rewind)."""
self._firetv.action('media_previous') self._firetv.action('media_previous')
def media_next_track(self): 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') self._firetv.action('media_next')

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
@ -176,7 +175,7 @@ class ItunesDevice(MediaPlayerDevice):
self.update() self.update()
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."""
self.player_state = state_hash.get('player_state', None) self.player_state = state_hash.get('player_state', None)
self.current_volume = state_hash.get('volume', 0) self.current_volume = state_hash.get('volume', 0)
@ -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'
@ -211,7 +209,7 @@ class ItunesDevice(MediaPlayerDevice):
return STATE_PLAYING return STATE_PLAYING
def update(self): def update(self):
""" Retrieve latest state. """ """Retrieve latest state."""
now_playing = self.client.now_playing() now_playing = self.client.now_playing()
self.update_state(now_playing) self.update_state(now_playing)
@ -239,28 +237,27 @@ class ItunesDevice(MediaPlayerDevice):
@property @property
def is_volume_muted(self): def is_volume_muted(self):
""" Boolean if volume is currently muted. """ """Boolean if volume is currently muted."""
return self.muted return self.muted
@property @property
def volume_level(self): 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 return self.current_volume/100.0
@property @property
def media_content_id(self): def media_content_id(self):
""" Content ID of current playing media. """ """Content ID of current playing media."""
return self.content_id return self.content_id
@property @property
def media_content_type(self): def media_content_type(self):
""" Content type of current playing media. """ """Content type of current playing media."""
return MEDIA_TYPE_MUSIC return MEDIA_TYPE_MUSIC
@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()
@ -270,76 +267,74 @@ class ItunesDevice(MediaPlayerDevice):
@property @property
def media_title(self): def media_title(self):
""" Title of current playing media. """ """Title of current playing media."""
return self.current_title return self.current_title
@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
def media_playlist(self): def media_playlist(self):
""" Title of the currently playing playlist. """ """Title of the currently playing playlist."""
return self.current_playlist return self.current_playlist
@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
@ -350,8 +345,7 @@ class AirPlayDevice(MediaPlayerDevice):
self.player_state = None self.player_state = None
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,44 +386,45 @@ 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:
return STATE_OFF return STATE_OFF
def update(self): def update(self):
""" Retrieve latest state. """ """Retrieve latest state."""
@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)
def turn_on(self): def turn_on(self):
""" Select AirPlay. """ """Select AirPlay."""
self.update_state({"selected": True}) self.update_state({"selected": True})
self.update_ha_state() self.update_ha_state()
response = self.client.toggle_airplay_device(self._id, True) response = self.client.toggle_airplay_device(self._id, True)
self.update_state(response) self.update_state(response)
def turn_off(self): def turn_off(self):
""" Deselect AirPlay. """ """Deselect AirPlay."""
self.update_state({"selected": False}) self.update_state({"selected": False})
self.update_ha_state() self.update_ha_state()
response = self.client.toggle_airplay_device(self._id, False) response = self.client.toggle_airplay_device(self._id, False)

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
@ -89,7 +86,7 @@ class KodiDevice(MediaPlayerDevice):
return STATE_PLAYING return STATE_PLAYING
def update(self): def update(self):
""" Retrieve latest state. """ """Retrieve latest state."""
self._players = self._get_players() self._players = self._get_players()
if self._players is not None and len(self._players) > 0: if self._players is not None and len(self._players) > 0:
@ -117,31 +114,31 @@ class KodiDevice(MediaPlayerDevice):
@property @property
def volume_level(self): 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: if self._app_properties is not None:
return self._app_properties['volume'] / 100.0 return self._app_properties['volume'] / 100.0
@property @property
def is_volume_muted(self): def is_volume_muted(self):
""" Boolean if volume is currently muted. """ """Boolean if volume is currently muted."""
if self._app_properties is not None: if self._app_properties is not None:
return self._app_properties['muted'] return self._app_properties['muted']
@property @property
def media_content_id(self): def media_content_id(self):
""" Content ID of current playing media. """ """Content ID of current playing media."""
if self._item is not None: if self._item is not None:
return self._item.get('uniqueid', None) return self._item.get('uniqueid', None)
@property @property
def media_content_type(self): 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: if self._players is not None and len(self._players) > 0:
return self._players[0]['type'] return self._players[0]['type']
@property @property
def media_duration(self): def media_duration(self):
""" Duration of current playing media in seconds. """ """Duration of current playing media in seconds."""
if self._properties is not None: if self._properties is not None:
total_time = self._properties['totaltime'] total_time = self._properties['totaltime']
@ -152,12 +149,12 @@ class KodiDevice(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._item is not None: if self._item is not None:
return self._get_image_url() return self._get_image_url()
def _get_image_url(self): 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']) url_components = urllib.parse.urlparse(self._item['thumbnail'])
if url_components.scheme == 'image': if url_components.scheme == 'image':
@ -167,7 +164,7 @@ class KodiDevice(MediaPlayerDevice):
@property @property
def media_title(self): def media_title(self):
""" Title of current playing media. """ """Title of current playing media."""
# find a string we can use as a title # find a string we can use as a title
if self._item is not None: if self._item is not None:
return self._item.get( return self._item.get(
@ -180,36 +177,36 @@ 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()
def _set_play_state(self, state): def _set_play_state(self, state):
""" Helper method for play/pause/toggle. """ """Helper method for play/pause/toggle."""
players = self._get_players() players = self._get_players()
if len(players) != 0: if len(players) != 0:
@ -218,19 +215,19 @@ 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):
""" Helper method used for previous/next track. """ """Helper method used for previous/next track."""
players = self._get_players() players = self._get_players()
if len(players) != 0: if len(players) != 0:
@ -239,18 +236,18 @@ class KodiDevice(MediaPlayerDevice):
self.update_ha_state() self.update_ha_state()
def media_next_track(self): def media_next_track(self):
""" Send next track command. """ """Send next track command."""
self._goto('next') self._goto('next')
def media_previous_track(self): 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 # first seek to position 0, Kodi seems to go to the beginning
# of the current track current track is not at the beginning # of the current track current track is not at the beginning
self.media_seek(0) self.media_seek(0)
self._goto('previous') self._goto('previous')
def media_seek(self, position): def media_seek(self, position):
""" Send seek command. """ """Send seek command."""
players = self._get_players() players = self._get_players()
time = {} time = {}

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':
@ -115,23 +113,23 @@ class MpdDevice(MediaPlayerDevice):
@property @property
def media_content_id(self): def media_content_id(self):
""" Content ID of current playing media. """ """Content ID of current playing media."""
return self.currentsong['id'] return self.currentsong['id']
@property @property
def media_content_type(self): def media_content_type(self):
""" Content type of current playing media. """ """Content type of current playing media."""
return MEDIA_TYPE_MUSIC return MEDIA_TYPE_MUSIC
@property @property
def media_duration(self): def media_duration(self):
""" Duration of current playing media in seconds. """ """Duration of current playing media in seconds."""
# Time does not exist for streams # Time does not exist for streams
return self.currentsong.get('time') return self.currentsong.get('time')
@property @property
def media_title(self): def media_title(self):
""" Title of current playing media. """ """Title of current playing media."""
name = self.currentsong.get('name', None) name = self.currentsong.get('name', None)
title = self.currentsong.get('title', None) title = self.currentsong.get('title', None)
@ -146,61 +144,62 @@ 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):
""" Service to send the MPD the command to stop playing. """ """Service to send the MPD the command to stop playing."""
self.client.stop() self.client.stop()
def turn_on(self): 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() 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):
""" 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']) current_volume = int(self.status['volume'])
if current_volume <= 100: if current_volume <= 100:
self.client.setvol(current_volume + 5) self.client.setvol(current_volume + 5)
def volume_down(self): 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']) current_volume = int(self.status['volume'])
if current_volume >= 0: if current_volume >= 0:
self.client.setvol(current_volume - 5) self.client.setvol(current_volume - 5)
def media_play(self): 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) self.client.pause(0)
def media_pause(self): 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) self.client.pause(1)
def media_next_track(self): 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() self.client.next()
def media_previous_track(self): 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() self.client.previous()

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/
@ -35,7 +33,7 @@ SUPPORT_PLEX = SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK
def config_from_file(filename, config=None): def config_from_file(filename, config=None):
""" Small configuration file management function. """ """Small configuration file management function."""
if config: if config:
# We're writing configuration # We're writing configuration
try: try:
@ -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
@ -85,7 +82,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
def setup_plexserver(host, token, hass, add_devices_callback): 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.server
import plexapi.exceptions 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) @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:
@ -161,7 +158,7 @@ def setup_plexserver(host, token, hass, add_devices_callback):
def request_configuration(host, 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') configurator = get_component('configurator')
# We got an error if this method is called while we are configuring # 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 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,18 +233,19 @@ 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)
@property @property
def media_content_id(self): def media_content_id(self):
""" Content ID of current playing media. """ """Content ID of current playing media."""
if self.session is not None: if self.session is not None:
return self.session.ratingKey return self.session.ratingKey
@property @property
def media_content_type(self): def media_content_type(self):
""" Content type of current playing media. """ """Content type of current playing media."""
if self.session is None: if self.session is None:
return None return None
media_type = self.session.type media_type = self.session.type
@ -258,61 +257,61 @@ class PlexClient(MediaPlayerDevice):
@property @property
def media_duration(self): def media_duration(self):
""" Duration of current playing media in seconds. """ """Duration of current playing media in seconds."""
if self.session is not None: if self.session is not None:
return self.session.duration return self.session.duration
@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.session is not None: if self.session is not None:
return self.session.thumbUrl return self.session.thumbUrl
@property @property
def media_title(self): def media_title(self):
""" Title of current playing media. """ """Title of current playing media."""
# find a string we can use as a title # find a string we can use as a title
if self.session is not None: if self.session is not None:
return self.session.title return self.session.title
@property @property
def media_season(self): 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 from plexapi.video import Show
if isinstance(self.session, Show): if isinstance(self.session, Show):
return self.session.seasons()[0].index return self.session.seasons()[0].index
@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
@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)."""
from plexapi.video import Show from plexapi.video import Show
if isinstance(self.session, Show): if isinstance(self.session, Show):
return self.session.index return self.session.index
@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):
""" Send next track command. """ """Send next track command."""
self.device.skipNext() self.device.skipNext()
def media_previous_track(self): def media_previous_track(self):
""" Send previous track command. """ """Send previous track command."""
self.device.skipPrevious() self.device.skipPrevious()

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,62 +104,65 @@ 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
def is_volume_muted(self): def is_volume_muted(self):
""" Boolean if volume is currently muted. """ """Boolean if volume is currently muted."""
return self._muted return self._muted
@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):
""" Simulate play pause media player. """ """Simulate play pause media player."""
if self._playing: if self._playing:
self.media_pause() self.media_pause()
else: else:
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")
def media_next_track(self): def media_next_track(self):
""" Send next track command. """ """Send next track command."""
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,44 +37,44 @@ 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
def is_volume_muted(self): def is_volume_muted(self):
""" Volume muted. """ """Volume muted."""
return self._client.muted return self._client.muted
@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,11 +128,11 @@ 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):
""" Retrieve latest state. """ """Retrieve latest state."""
self._name = self._player.get_speaker_info()['zone_name'].replace( self._name = self._player.get_speaker_info()['zone_name'].replace(
' (R)', '').replace(' (L)', '') ' (R)', '').replace(' (L)', '')
self._status = self._player.get_current_transport_info().get( self._status = self._player.get_current_transport_info().get(
@ -142,26 +141,27 @@ class SonosDevice(MediaPlayerDevice):
@property @property
def volume_level(self): 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 return self._player.volume / 100.0
@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
def media_content_id(self): def media_content_id(self):
""" Content ID of current playing media. """ """Content ID of current playing media."""
return self._trackinfo.get('title', None) return self._trackinfo.get('title', None)
@property @property
def media_content_type(self): def media_content_type(self):
""" Content type of current playing media. """ """Content type of current playing media."""
return MEDIA_TYPE_MUSIC return MEDIA_TYPE_MUSIC
@property @property
def media_duration(self): 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') dur = self._trackinfo.get('duration', '0:00')
# If the speaker is playing from the "line-in" source, getting # If the speaker is playing from the "line-in" source, getting
@ -175,13 +175,13 @@ class SonosDevice(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 'album_art' in self._trackinfo: if 'album_art' in self._trackinfo:
return self._trackinfo['album_art'] return self._trackinfo['album_art']
@property @property
def media_title(self): def media_title(self):
""" Title of current playing media. """ """Title of current playing media."""
if 'artist' in self._trackinfo and 'title' in self._trackinfo: if 'artist' in self._trackinfo and 'title' in self._trackinfo:
return '{artist} - {title}'.format( return '{artist} - {title}'.format(
artist=self._trackinfo['artist'], artist=self._trackinfo['artist'],
@ -192,60 +192,60 @@ 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
def turn_off(self): def turn_off(self):
""" Turn off media player. """ """Turn off media player."""
self._player.pause() self._player.pause()
@only_if_coordinator @only_if_coordinator
def volume_up(self): def volume_up(self):
""" Volume up media player. """ """Volume up media player."""
self._player.volume += 1 self._player.volume += 1
@only_if_coordinator @only_if_coordinator
def volume_down(self): def volume_down(self):
""" Volume down media player. """ """Volume down media player."""
self._player.volume -= 1 self._player.volume -= 1
@only_if_coordinator @only_if_coordinator
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._player.volume = str(int(volume * 100)) self._player.volume = str(int(volume * 100))
@only_if_coordinator @only_if_coordinator
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._player.mute = mute self._player.mute = mute
@only_if_coordinator @only_if_coordinator
def media_play(self): def media_play(self):
""" Send paly command. """ """Send paly command."""
self._player.play() self._player.play()
@only_if_coordinator @only_if_coordinator
def media_pause(self): def media_pause(self):
""" Send pause command. """ """Send pause command."""
self._player.pause() self._player.pause()
@only_if_coordinator @only_if_coordinator
def media_next_track(self): def media_next_track(self):
""" Send next track command. """ """Send next track command."""
self._player.next() self._player.next()
@only_if_coordinator @only_if_coordinator
def media_previous_track(self): def media_previous_track(self):
""" Send next track command. """ """Send next track command."""
self._player.previous() self._player.previous()
@only_if_coordinator @only_if_coordinator
def media_seek(self, position): def media_seek(self, position):
""" Send seek command. """ """Send seek command."""
self._player.seek(str(datetime.timedelta(seconds=int(position)))) self._player.seek(str(datetime.timedelta(seconds=int(position))))
@only_if_coordinator @only_if_coordinator
def turn_on(self): def turn_on(self):
""" Turn the media player on. """ """Turn the media player on."""
self._player.play() self._player.play()

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
@ -60,7 +59,7 @@ class LogitechMediaServer(object):
self.init_success = True if self.http_port else False self.init_success = True if self.http_port else False
def _get_http_port(self): 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 http_port = None
try: try:
http_port = self.query('pref', 'httpport', '?') http_port = self.query('pref', 'httpport', '?')
@ -80,7 +79,7 @@ class LogitechMediaServer(object):
return return
def create_players(self): def create_players(self):
""" Create a list of SqueezeBoxDevices connected to the LMS. """ """Create a list of SqueezeBoxDevices connected to the LMS."""
players = [] players = []
count = self.query('player', 'count', '?') count = self.query('player', 'count', '?')
for index in range(0, int(count)): for index in range(0, int(count)):
@ -90,7 +89,7 @@ class LogitechMediaServer(object):
return players return players
def query(self, *parameters): 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) telnet = telnetlib.Telnet(self.host, self.port)
if self._username and self._password: if self._username and self._password:
telnet.write('login {username} {password}\n'.format( telnet.write('login {username} {password}\n'.format(
@ -107,7 +106,7 @@ class LogitechMediaServer(object):
return urllib.parse.unquote(response) return urllib.parse.unquote(response)
def get_player_status(self, player): def get_player_status(self, player):
""" Get ithe status of a player. """ """Get ithe status of a player."""
# (title) : Song title # (title) : Song title
# Requested Information # Requested Information
# a (artist): Artist name 'artist' # a (artist): Artist name 'artist'
@ -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:
@ -163,40 +163,41 @@ class SqueezeBoxDevice(MediaPlayerDevice):
return STATE_UNKNOWN return STATE_UNKNOWN
def update(self): def update(self):
""" Retrieve latest state. """ """Retrieve latest state."""
self._status = self._lms.get_player_status(self._id) self._status = self._lms.get_player_status(self._id)
@property @property
def volume_level(self): 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: if 'mixer volume' in self._status:
return int(float(self._status['mixer volume'])) / 100.0 return int(float(self._status['mixer volume'])) / 100.0
@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('-')
@property @property
def media_content_id(self): def media_content_id(self):
""" Content ID of current playing media. """ """Content ID of current playing media."""
if 'current_title' in self._status: if 'current_title' in self._status:
return self._status['current_title'] return self._status['current_title']
@property @property
def media_content_type(self): def media_content_type(self):
""" Content type of current playing media. """ """Content type of current playing media."""
return MEDIA_TYPE_MUSIC return MEDIA_TYPE_MUSIC
@property @property
def media_duration(self): def media_duration(self):
""" Duration of current playing media in seconds. """ """Duration of current playing media in seconds."""
if 'duration' in self._status: if 'duration' in self._status:
return int(float(self._status['duration'])) return int(float(self._status['duration']))
@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 'artwork_url' in self._status: if 'artwork_url' in self._status:
media_url = self._status['artwork_url'] media_url = self._status['artwork_url']
elif 'id' in self._status: elif 'id' in self._status:
@ -214,7 +215,7 @@ class SqueezeBoxDevice(MediaPlayerDevice):
@property @property
def media_title(self): def media_title(self):
""" Title of current playing media. """ """Title of current playing media."""
if 'artist' in self._status and 'title' in self._status: if 'artist' in self._status and 'title' in self._status:
return '{artist} - {title}'.format( return '{artist} - {title}'.format(
artist=self._status['artist'], artist=self._status['artist'],
@ -225,67 +226,67 @@ 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()
def media_next_track(self): def media_next_track(self):
""" Send next track command. """ """Send next track command."""
self._lms.query(self._id, 'playlist', 'index', '+1') self._lms.query(self._id, 'playlist', 'index', '+1')
self.update_ha_state() self.update_ha_state()
def media_previous_track(self): def media_previous_track(self):
""" Send next track command. """ """Send next track command."""
self._lms.query(self._id, 'playlist', 'index', '-1') self._lms.query(self._id, 'playlist', 'index', '-1')
self.update_ha_state() self.update_ha_state()
def media_seek(self, position): def media_seek(self, position):
""" Send seek command. """ """Send seek command."""
self._lms.query(self._id, 'time', position) self._lms.query(self._id, 'time', position)
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,98 +233,98 @@ 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]
@property @property
def media_content_id(self): 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) return self._child_attr(ATTR_MEDIA_CONTENT_ID)
@property @property
def media_content_type(self): 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) return self._child_attr(ATTR_MEDIA_CONTENT_TYPE)
@property @property
def media_duration(self): 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) return self._child_attr(ATTR_MEDIA_DURATION)
@property @property
def media_image_url(self): def media_image_url(self):
""" Image url of current playing media. """ """Image url of current playing media."""
return self._child_attr(ATTR_ENTITY_PICTURE) return self._child_attr(ATTR_ENTITY_PICTURE)
@property @property
def media_title(self): def media_title(self):
""" Title of current playing media. """ """Title of current playing media."""
return self._child_attr(ATTR_MEDIA_TITLE) return self._child_attr(ATTR_MEDIA_TITLE)
@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
def media_channel(self): def media_channel(self):
""" Channel currently playing. """ """Channel currently playing."""
return self._child_attr(ATTR_MEDIA_CHANNEL) return self._child_attr(ATTR_MEDIA_CHANNEL)
@property @property
def media_playlist(self): def media_playlist(self):
""" Title of Playlist currently playing. """ """Title of Playlist currently playing."""
return self._child_attr(ATTR_MEDIA_PLAYLIST) return self._child_attr(ATTR_MEDIA_PLAYLIST)
@property @property
def app_id(self): def app_id(self):
""" ID of the current running app. """ """ID of the current running app."""
return self._child_attr(ATTR_APP_ID) return self._child_attr(ATTR_APP_ID)
@property @property
def app_name(self): def app_name(self):
""" Name of the current running app. """ """Name of the current running app."""
return self._child_attr(ATTR_APP_NAME) return self._child_attr(ATTR_APP_NAME)
@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:
@ -347,69 +345,69 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property @property
def device_state_attributes(self): def device_state_attributes(self):
""" Extra attributes a device wants to expose. """ """Extra attributes a device wants to expose."""
active_child = self._child_state active_child = self._child_state
return {ATTR_ACTIVE_CHILD: active_child.entity_id} \ return {ATTR_ACTIVE_CHILD: active_child.entity_id} \
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)
def media_play(self): def media_play(self):
""" Send play commmand. """ """Send play commmand."""
self._call_service(SERVICE_MEDIA_PLAY) self._call_service(SERVICE_MEDIA_PLAY)
def media_pause(self): def media_pause(self):
""" Send pause command. """ """Send pause command."""
self._call_service(SERVICE_MEDIA_PAUSE) self._call_service(SERVICE_MEDIA_PAUSE)
def media_previous_track(self): def media_previous_track(self):
""" Send previous track command. """ """Send previous track command."""
self._call_service(SERVICE_MEDIA_PREVIOUS_TRACK) self._call_service(SERVICE_MEDIA_PREVIOUS_TRACK)
def media_next_track(self): def media_next_track(self):
""" Send next track command. """ """Send next track command."""
self._call_service(SERVICE_MEDIA_NEXT_TRACK) self._call_service(SERVICE_MEDIA_NEXT_TRACK)
def media_seek(self, position): def media_seek(self, position):
""" Send seek command. """ """Send seek command."""
data = {ATTR_MEDIA_SEEK_POSITION: position} data = {ATTR_MEDIA_SEEK_POSITION: position}
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: