soco.core module

The core module contains the SoCo class that implements the main entry to the SoCo functionality

soco.core.only_on_master(function)[source]

Decorator that raises SoCoSlaveException on master call on slave.

class soco.core.SoCo(ip_address)[source]

A simple class for controlling a Sonos speaker.

For any given set of arguments to __init__, only one instance of this class may be created. Subsequent attempts to create an instance with the same arguments will return the previously created instance. This means that all SoCo instances created with the same ip address are in fact the same SoCo instance, reflecting the real world position.

Methods

play() Play the currently selected track.
play_uri([uri, meta, title, start]) Play a given stream.
play_from_queue(index[, start]) Play a track from the queue by index.
pause() Pause the currently playing track.
stop() Stop the currently playing track.
seek(timestamp) Seeks to a given timestamp in the current track, specified in the format of HH:MM:SS or H:MM:SS.
next() Go to the next track.
previous() Go back to the previously played track.
switch_to_line_in() Switch the speaker’s input to line-in.
switch_to_tv() Switch the playbar speaker’s input to TV.
get_current_track_info() Get information about the currently playing track.
get_speaker_info([refresh, timeout]) Get information about the Sonos speaker.
partymode() Put all the speakers in the network in the same group, a.k.a Party Mode.
join(master) Join this speaker to another “master” speaker.
unjoin() Remove this speaker from a group.
get_queue([start, max_items, full_album_art_uri]) Get information about the queue.
get_current_transport_info() Get the current playback state.
add_uri_to_queue(uri) Adds the URI to the queue.
add_to_queue(queueable_item) Adds a queueable item to the queue.
remove_from_queue(index) Remove a track from the queue by index.
clear_queue() Removes all tracks from the queue.
get_favorite_radio_shows([start, max_items]) Get favorite radio shows from Sonos’ Radio app.
get_favorite_radio_stations([start, max_items]) Get favorite radio stations from Sonos’ Radio app.
get_sonos_favorites([start, max_items]) Get Sonos favorites.
create_sonos_playlist(title) Create a new empty Sonos playlist.
create_sonos_playlist_from_queue(title) Create a new Sonos playlist from the current queue.
remove_sonos_playlist(sonos_playlist) Remove a Sonos playlist.
add_item_to_sonos_playlist(queueable_item, ...) Adds a queueable item to a Sonos’ playlist.
get_item_album_art_uri(item) Get an item’s Album Art absolute URI.
set_sleep_timer(sleep_time_seconds) Sets the sleep timer.
get_sleep_timer() Retrieves remaining sleep time, if any

Properties

Warning

These properties are not generally cached and may obtain information over the network, so may take longer than expected to set or return a value. It may be a good idea for you to cache the value in your own code.

uid A unique identifier.
household_id A unique identifier for all players in a household.
mute The speaker’s mute state.
volume The speaker’s volume.
bass The speaker’s bass EQ.
treble The speaker’s treble EQ.
loudness The Sonos speaker’s loudness compensation.
cross_fade The speaker’s cross fade state.
status_light The white Sonos status light between the mute button and the volume up button on the speaker.
player_name The speaker’s name.
play_mode str: The queue’s play mode.
queue_size Get size of queue.
is_playing_tv Is the playbar speaker input from TV?
is_playing_radio Is the speaker playing radio?
is_playing_line_in Is the speaker playing line-in?
ip_address = None

The speaker’s ip address

player_name

The speaker’s name.

A string.

uid

A unique identifier.

Looks like: 'RINCON_000XXXXXXXXXX1400'

household_id

A unique identifier for all players in a household.

Looks like: 'Sonos_asahHKgjgJGjgjGjggjJgjJG34'

is_visible

Is this zone visible? A zone might be invisible if, for example it is a bridge, or the slave part of stereo pair.

return True or False

is_bridge

Is this zone a bridge?

is_coordinator

Return True if this zone is a group coordinator, otherwise False.

return True or False

play_mode

str: The queue’s play mode.

Case-insensitive options are:

  • 'NORMAL' – Turns off shuffle and repeat.
  • 'REPEAT_ALL' – Turns on repeat and turns off shuffle.
  • 'SHUFFLE' – Turns on shuffle and repeat. (It’s strange, I know.)
  • 'SHUFFLE_NOREPEAT' – Turns on shuffle and turns off repeat.
cross_fade

The speaker’s cross fade state.

True if enabled, False otherwise

play_from_queue(index, start=True)[source]

Play a track from the queue by index. The index number is required as an argument, where the first index is 0.

index: the index of the track to play; first item in the queue is 0 start: If the item that has been set should start playing

Returns: True if the Sonos speaker successfully started playing the track. False if the track did not start (this may be because it was not requested to start because “start=False”)

Raises SoCoException (or a subclass) upon errors.

play()[source]

Play the currently selected track.

Returns: True if the Sonos speaker successfully started playing the track.

Raises SoCoException (or a subclass) upon errors.

play_uri(uri='', meta='', title='', start=True)[source]

Play a given stream. Pauses the queue. If there is no metadata passed in and there is a title set then a metadata object will be created. This is often the case if you have a custom stream, it will need at least the title in the metadata in order to play.

Arguments: uri – URI of a stream to be played. meta – The track metadata to show in the player, DIDL format. title – The track title to show in the player start – If the URI that has been set should start playing

Returns: True if the Sonos speaker successfully started playing the track. False if the track did not start (this may be because it was not requested to start because “start=False”)

Raises SoCoException (or a subclass) upon errors.

pause()[source]

Pause the currently playing track.

Returns: True if the Sonos speaker successfully paused the track.

Raises SoCoException (or a subclass) upon errors.

stop()[source]

Stop the currently playing track.

Returns: True if the Sonos speaker successfully stopped the playing track.

Raises SoCoException (or a subclass) upon errors.

seek(timestamp)[source]

Seeks to a given timestamp in the current track, specified in the format of HH:MM:SS or H:MM:SS.

Returns: True if the Sonos speaker successfully seeked to the timecode.

Raises SoCoException (or a subclass) upon errors.

next()[source]

Go to the next track.

Returns: True if the Sonos speaker successfully skipped to the next track.

Raises SoCoException (or a subclass) upon errors.

Keep in mind that next() can return errors for a variety of reasons. For example, if the Sonos is streaming Pandora and you call next() several times in quick succession an error code will likely be returned (since Pandora has limits on how many songs can be skipped).

previous()[source]

Go back to the previously played track.

Returns: True if the Sonos speaker successfully went to the previous track.

Raises SoCoException (or a subclass) upon errors.

Keep in mind that previous() can return errors for a variety of reasons. For example, previous() will return an error code (error code 701) if the Sonos is streaming Pandora since you can’t go back on tracks.

mute

The speaker’s mute state.

True if muted, False otherwise

volume

The speaker’s volume.

An integer between 0 and 100.

bass

The speaker’s bass EQ.

An integer between -10 and 10.

treble

The speaker’s treble EQ.

An integer between -10 and 10.

loudness

The Sonos speaker’s loudness compensation. True if on, otherwise False.

Loudness is a complicated topic. You can find a nice summary about this feature here: http://forums.sonos.com/showthread.php?p=4698#post4698

all_groups

Return a set of all the available groups.

group

The Zone Group of which this device is a member.

group will be None if this zone is a slave in a stereo pair.

all_zones

Return a set of all the available zones.

visible_zones

Return an set of all visible zones.

partymode()[source]

Put all the speakers in the network in the same group, a.k.a Party Mode.

This blog shows the initial research responsible for this: http://blog.travelmarx.com/2010/06/exploring-sonos-via-upnp.html

The trick seems to be (only tested on a two-speaker setup) to tell each speaker which to join. There’s probably a bit more to it if multiple groups have been defined.

join(master)[source]

Join this speaker to another “master” speaker.

Note

The signature of this method has changed in 0.8. It now requires a SoCo instance to be passed as master, not an IP address

unjoin()[source]

Remove this speaker from a group.

Seems to work ok even if you remove what was previously the group master from it’s own group. If the speaker was not in a group also returns ok.

Returns: True if this speaker has left the group.

Raises SoCoException (or a subclass) upon errors.

switch_to_line_in()[source]

Switch the speaker’s input to line-in.

Returns: True if the Sonos speaker successfully switched to line-in.

If an error occurs, we’ll attempt to parse the error and return a UPnP error code. If that fails, the raw response sent back from the Sonos speaker will be returned.

Raises SoCoException (or a subclass) upon errors.

is_playing_radio

Is the speaker playing radio?

return True or False

is_playing_line_in

Is the speaker playing line-in?

return True or False

is_playing_tv

Is the playbar speaker input from TV?

return True or False

switch_to_tv()[source]

Switch the playbar speaker’s input to TV.

Returns: True if the Sonos speaker successfully switched to TV.

If an error occurs, we’ll attempt to parse the error and return a UPnP error code. If that fails, the raw response sent back from the Sonos speaker will be returned.

Raises SoCoException (or a subclass) upon errors.

status_light

The white Sonos status light between the mute button and the volume up button on the speaker.

True if on, otherwise False.

get_current_track_info()[source]

Get information about the currently playing track.

Returns: A dictionary containing the following information about the currently playing track: playlist_position, duration, title, artist, album, position and a link to the album art.

If we’re unable to return data for a field, we’ll return an empty string. This can happen for all kinds of reasons so be sure to check values. For example, a track may not have complete metadata and be missing an album name. In this case track[‘album’] will be an empty string.

Note

Calling this method on a slave in a group will not return the track the group is playing, but the last track this speaker was playing.

get_speaker_info(refresh=False, timeout=None)[source]

Get information about the Sonos speaker.

Arguments: refresh – Refresh the speaker info cache. timeout – How long to wait for the server to send

System Message: ERROR/3 (/home/docs/checkouts/readthedocs.org/user_builds/soco/checkouts/v0.12/soco/core.py:docstring of soco.core.SoCo.get_speaker_info, line 6)

Unexpected indentation.
data before giving up, as a float, or a (`connect timeout, read timeout`_) tuple e.g. (3, 5). Default is no timeout.

Returns: Information about the Sonos speaker, such as the UID, MAC Address, and Zone Name.

get_current_transport_info()[source]

Get the current playback state.

Returns: A dictionary containing the following information about the speakers playing state current_transport_state (PLAYING, PAUSED_PLAYBACK, STOPPED), current_trasnport_status (OK, ?), current_speed(1,?)

This allows us to know if speaker is playing or not. Don’t know other states of CurrentTransportStatus and CurrentSpeed.

get_queue(start=0, max_items=100, full_album_art_uri=False)[source]

Get information about the queue.

Parameters:
  • start – Starting number of returned matches
  • max_items – Maximum number of returned matches
  • full_album_art_uri – If the album art URI should include the IP address
Returns:

A Queue object

This method is heavly based on Sam Soffes (aka soffes) ruby implementation

queue_size

Get size of queue.

get_sonos_playlists(*args, **kwargs)[source]

Convenience method for: get_music_library_information(‘sonos_playlists’) Refer to the docstring for that method

add_uri_to_queue(uri)[source]

Adds the URI to the queue.

Parameters:uri (str) – The URI to be added to the queue
add_to_queue(queueable_item)[source]

Adds a queueable item to the queue.

remove_from_queue(index)[source]

Remove a track from the queue by index. The index number is required as an argument, where the first index is 0.

index: the index of the track to remove; first item in the queue is 0

Returns:True if the Sonos speaker successfully removed the track

Raises SoCoException (or a subclass) upon errors.

clear_queue()[source]

Removes all tracks from the queue.

Returns: True if the Sonos speaker cleared the queue.

Raises SoCoException (or a subclass) upon errors.

get_favorite_radio_shows(start=0, max_items=100)[source]

Get favorite radio shows from Sonos’ Radio app.

Returns: A list containing the total number of favorites, the number of favorites returned, and the actual list of favorite radio shows, represented as a dictionary with title and uri keys.

Depending on what you’re building, you’ll want to check to see if the total number of favorites is greater than the amount you requested (max_items), if it is, use start to page through and get the entire list of favorites.

get_favorite_radio_stations(start=0, max_items=100)[source]

Get favorite radio stations from Sonos’ Radio app.

Returns: A list containing the total number of favorites, the number of favorites returned, and the actual list of favorite radio stations, represented as a dictionary with title and uri keys.

Depending on what you’re building, you’ll want to check to see if the total number of favorites is greater than the amount you requested (max_items), if it is, use start to page through and get the entire list of favorites.

get_sonos_favorites(start=0, max_items=100)[source]

Get Sonos favorites.

Returns: A list containing the total number of favorites, the number of favorites returned, and the actual list of favorite radio stations, represented as a dictionary with title, uri and meta keys.

Depending on what you’re building, you’ll want to check to see if the total number of favorites is greater than the amount you requested (max_items), if it is, use start to page through and get the entire list of favorites.

create_sonos_playlist(title)[source]

Create a new empty Sonos playlist.

Params title:Name of the playlist
Returns:An instance of DidlPlaylistContainer
create_sonos_playlist_from_queue(title)[source]

Create a new Sonos playlist from the current queue.

Params title:Name of the playlist
Returns:An instance of DidlPlaylistContainer
remove_sonos_playlist(sonos_playlist)[source]

Remove a Sonos playlist.

Parameters:sonos_playlist (DidlPlaylistContainer) – Sonos playlist to remove or the item_id (str).
Returns:True if succesful, False otherwise
Return type:bool
Raises:SoCoUPnPException – If sonos_playlist does not point to a valid object.
add_item_to_sonos_playlist(queueable_item, sonos_playlist)[source]

Adds a queueable item to a Sonos’ playlist.

Parameters:
  • queueable_item – the item to add to the Sonos’ playlist
  • sonos_playlist – the Sonos’ playlist to which the item should be added
get_item_album_art_uri(item)[source]

Get an item’s Album Art absolute URI.

set_sleep_timer(sleep_time_seconds)[source]

Sets the sleep timer.

Parameters:

sleep_time_seconds (int or NoneType) – How long to wait before turning off speaker in seconds, None to cancel a sleep timer. Maximum value of 86399

Raises:
  • SoCoException – Upon errors interacting with Sonos controller
  • ValueError – Argument/Syntax errors
get_sleep_timer()[source]

Retrieves remaining sleep time, if any

Returns:Number of seconds left in timer. If there is no sleep timer currently set it will return None.
Return type:int or NoneType

Raises SoCoException (or a subclass) upon errors.

get_artists(*args, **kwargs)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.get_artists instead.

get_album_artists(*args, **kwargs)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.get_album_artists instead.

get_albums(*args, **kwargs)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.get_music_library_information instead.

get_genres(*args, **kwargs)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.get_music_library_information instead.

get_composers(*args, **kwargs)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.get_composers instead.

get_tracks(*args, **kwargs)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.get_tracks instead.

get_playlists(*args, **kwargs)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.get_playlists instead.

get_music_library_information(search_type, start=0, max_items=100, full_album_art_uri=False, search_term=None, subcategories=None, complete_result=False)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.get_music_library_information instead.

browse(ml_item=None, start=0, max_items=100, full_album_art_uri=False, search_term=None, subcategories=None)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.browse instead.

browse_by_idstring(search_type, idstring, start=0, max_items=100, full_album_art_uri=False)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.browse_by_idstring instead.

library_updating

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.library_updating instead.

start_library_update(album_artist_display_option='')[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.start_library_update instead.

search_track(artist, album=None, track=None, full_album_art_uri=False)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.search_track instead.

get_albums_for_artist(artist, full_album_art_uri=False)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.get_albums_for_artist instead.

get_tracks_for_album(artist, album, full_album_art_uri=False)[source]

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.get_tracks_for_album instead.

album_artist_display_option

Deprecated since version 0.12: Will be removed in version 0.14. Use soco.music_library.album_artist_display instead.

reorder_sonos_playlist(sonos_playlist, tracks, new_pos, update_id=0)[source]

Reorder and/or Remove tracks in a Sonos playlist.

The underlying call is quite complex as it can both move a track within the list or delete a track from the playlist. All of this depends on what tracks and new_pos specify.

If a list is specified for tracks, then a list must be used for new_pos. Each list element is a discrete modification and the next list operation must anticipate the new state of the playlist.

If a comma formatted string to tracks is specified, then use a similiar string to specify new_pos. Those operations should be ordered from the end of the list to the beginning

See the helper methods clear_sonos_playlist(), move_in_sonos_playlist(), remove_from_sonos_playlist() for simplified usage.

update_id - If you have a series of operations, tracking the update_id and setting it, will save a lookup operation.

Examples

To reorder the first two tracks:

# sonos_playlist specified by the DidlPlaylistContainer object
sonos_playlist = device.get_sonos_playlists()[0]
device.reorder_sonos_playlist(sonos_playlist,
                              tracks=[0, ], new_pos=[1, ])
# OR specified by the item_id
device.reorder_sonos_playlist('SQ:0', tracks=[0, ], new_pos=[1, ])

To delete the second track:

# tracks/new_pos are a list of int
device.reorder_sonos_playlist(sonos_playlist,
                              tracks=[1, ], new_pos=[None, ])
# OR tracks/new_pos are a list of int-like
device.reorder_sonos_playlist(sonos_playlist,
                              tracks=['1', ], new_pos=['', ])
# OR tracks/new_pos are strings - no transform is done
device.reorder_sonos_playlist(sonos_playlist, tracks='1',
                              new_pos='')

To reverse the order of a playlist with 4 items:

device.reorder_sonos_playlist(sonos_playlist, tracks='3,2,1,0',
                              new_pos='0,1,2,3')
Parameters:
  • sonos_playlist – (DidlPlaylistContainer): The Sonos playlist object or the item_id (str) of the Sonos playlist.
  • tracks – (list): list of track indices(int) to reorder. May also be a list of int like things. i.e. ['0', '1',] OR it may be a str of comma separated int like things. "0,1". Tracks are 0-based. Meaning the first track is track 0, just like indexing into a Python list.
  • new_pos (list) – list of new positions (int|None) corresponding to track_list. MUST be the same type as tracks. 0-based, see tracks above. None is the indicator to remove the track. If using a list of strings, then a remove is indicated by an empty string.
  • update_id (int) – operation id (default: 0) If set to 0, a lookup is done to find the correct value.
Returns:

Which contains 3 elements: change, length and update_id. Change in size between original playlist and the resulting playlist, the length of resulting playlist, and the new update_id.

Return type:

dict

Raises:

SoCoUPnPException – If playlist does not exist or if your tracks and/or new_pos arguments are invalid.

clear_sonos_playlist(sonos_playlist, update_id=0)[source]

Clear all tracks from a Sonos playlist. This is a convenience method for reorder_sonos_playlist().

Example:

device.clear_sonos_playlist(sonos_playlist)
Parameters:
  • sonos_playlist – (DidlPlaylistContainer): Sonos playlist object or the item_id (str) of the Sonos playlist.
  • update_id (int) – Optional update counter for the object. If left at the default of 0, it will be looked up.
Returns:

See reorder_sonos_playlist()

Return type:

dict

Raises:
move_in_sonos_playlist(sonos_playlist, track, new_pos, update_id=0)[source]

Move a track to a new position within a Sonos Playlist. This is a convenience method for reorder_sonos_playlist().

Example:

device.move_in_sonos_playlist(sonos_playlist, track=0, new_pos=1)
Parameters:
  • sonos_playlist – (DidlPlaylistContainer): Sonos playlist object or the item_id (str) of the Sonos playlist.
  • track (int) – 0-based position of the track to move. The first track is track 0, just like indexing into a Python list.
  • new_pos (int) – 0-based location to move the track.
  • update_id (int) – Optional update counter for the object. If left at the default of 0, it will be looked up.
Returns:

See reorder_sonos_playlist()

Return type:

dict

Raises:

SoCoUPnPException – See reorder_sonos_playlist()

remove_from_sonos_playlist(sonos_playlist, track, update_id=0)[source]

Remove a track from a Sonos Playlist. This is a convenience method for reorder_sonos_playlist().

Example:

device.remove_from_sonos_playlist(sonos_playlist, track=0)
Parameters:
  • sonos_playlist – (DidlPlaylistContainer): Sonos playlist object or the item_id (str) of the Sonos playlist.
  • track (int) – 0*-based position of the track to move. The first track is track 0, just like indexing into a Python list.
  • update_id (int) – Optional update counter for the object. If left at the default of 0, it will be looked up.
Returns:

See reorder_sonos_playlist()

Return type:

dict

Raises:

SoCoUPnPException – See reorder_sonos_playlist()

get_sonos_playlist_by_attr(attr_name, match)[source]

Return the first Sonos Playlist DidlPlaylistContainer that matches the attribute specified.

Parameters:
  • attr_name (str) – DidlPlaylistContainer attribute to compare. The most useful being: ‘title’ and ‘item_id’.
  • match (str) – Value to match.
Returns:

The first matching playlist object.

Return type:

(DidlPlaylistContainer)

Raises:
  • (AttributeError) – If indicated attribute name does not exist.
  • (ValueError) – If a match can not be found.

Example:

device.get_sonos_playlist_by_attr('title', 'Foo')
device.get_sonos_playlist_by_attr('item_id', 'SQ:3')