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.

soco.core.only_on_soundbars(function)[source]

Decorator to raise an exception on soundbar property access on non-soundbars.

class soco.core.SoCo(*args, **kwargs)[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.

Basic Methods

play_from_queue(index[, start])

Play a track from the queue by index.

play()

Play the currently selected track.

play_uri([uri, meta, title, start, force_radio])

Play a URI.

pause()

Pause the currently playing track.

stop()

Stop the currently playing track.

end_direct_control_session()

Ends all third-party controlled streaming sessions.

seek([position, track])

Seek to a given position.

next()

Go to the next track.

previous()

Go back to the previously played track.

mute

The speaker's mute state.

volume

The speaker's volume.

play_mode

The queue's play mode.

shuffle

The queue's shuffle option.

repeat

The queue's repeat option.

cross_fade

The speaker's cross fade state.

ramp_to_volume(volume[, ramp_type])

Smoothly change the volume.

set_relative_volume(relative_volume)

Adjust the volume up or down by a relative amount.

get_current_track_info()

Get information about the currently playing track.

get_current_media_info()

Get information about the currently playing media.

get_speaker_info([refresh, timeout])

Get information about the Sonos speaker.

get_current_transport_info()

Get the current playback state.

Queue Management

get_queue([start, max_items, full_album_art_uri])

Get information about the queue.

queue_size

Size of the queue.

add_to_queue(queueable_item[, position, as_next])

Add a queueable item to the queue.

add_uri_to_queue(uri[, position, as_next])

Add the URI to the queue.

add_multiple_to_queue(items[, container])

Add a sequence of items to the queue.

remove_from_queue(index)

Remove a track from the queue by index.

clear_queue()

Remove all tracks from the queue.

Group Management

group

The Zone Group of which this device is a member.

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.

all_groups

All available groups.

all_zones

All available zones.

visible_zones

All visible zones.

Player Identity and Settings

player_name

The speaker's name.

uid

A unique identifier.

household_id

A unique identifier for all players in a household.

is_visible

Is this zone visible?

is_bridge

Is this zone a bridge?

is_coordinator

Is this zone a group coordinator?

is_soundbar

Is this zone a soundbar (i.e.

is_satellite

Is this zone a satellite in a home theater setup?

has_satellites

Is this zone configured with satellites in a home theater setup?

sub_enabled

Reports if the subwoofer is enabled.

sub_gain

The current subwoofer gain level.

is_subwoofer

Is this zone a subwoofer?

has_subwoofer

Is this zone configured with a subwoofer?

channel

Location of this zone in a home theater or paired configuration.

bass

The speaker's bass EQ.

treble

The speaker's treble EQ.

loudness

The speaker's loudness compensation.

balance

The left/right balance for the speaker(s).

audio_delay

The TV Dialog Sync audio delay.

night_mode

The speaker's night mode.

dialog_mode

The speaker's dialog mode.

surround_enabled

Reports if the home theater surround speakers are enabled.

surround_full_volume_enabled

Return True if surround full volume is enabled for surround music playback.

surround_volume_tv

Get the relative volume for surround speakers in TV playback mode.

surround_volume_music

Return the relative volume for surround speakers in music mode, in the range -15 to +15.

soundbar_audio_input_format

Return a string presentation of the audio input format.

supports_fixed_volume

Whether the device supports fixed volume output.

fixed_volume

The device's fixed volume output setting.

soundbar_audio_input_format

Return a string presentation of the audio input format.

soundbar_audio_input_format_code

Return audio input format code as reported by the device.

trueplay

Whether Trueplay is enabled on this device.

status_light

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

buttons_enabled

Whether the control buttons on the device are enabled.

voice_service_configured

Is a voice service configured on this device?

mic_enabled

Is the device's microphone enabled?

Playlists and Favorites

get_sonos_playlists(*args, **kwargs)

Convenience method for calling soco.music_library.get_music_library_information('sonos_playlists')

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.

reorder_sonos_playlist(sonos_playlist, ...)

Reorder and/or Remove tracks in a Sonos playlist.

clear_sonos_playlist(sonos_playlist[, update_id])

Clear all tracks from a Sonos playlist.

move_in_sonos_playlist(sonos_playlist, ...)

Move a track to a new position within a Sonos Playlist.

remove_from_sonos_playlist(sonos_playlist, track)

Remove a track from a Sonos Playlist.

get_sonos_playlist_by_attr(attr_name, match)

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

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.

Miscellaneous

music_source

The current music source (radio, TV, line-in, etc.).

music_source_from_uri(uri)

Determine a music source from a URI.

is_playing_radio

Is the speaker playing radio?

is_playing_tv

Is the playbar speaker input from TV?

is_playing_line_in

Is the speaker playing line-in?

switch_to_line_in([source])

Switch the speaker's input to line-in.

switch_to_tv()

Switch the playbar speaker's input to TV.

available_actions

The transport actions that are currently available on the speaker.

set_sleep_timer(sleep_time_seconds)

Sets the sleep timer.

get_sleep_timer()

Retrieves remaining sleep time, if any

create_stereo_pair(rh_slave_speaker)

Create a stereo pair.

separate_stereo_pair()

Separate a stereo pair.

get_battery_info([timeout])

Get battery information for a Sonos speaker.

boot_seqnum

The boot sequence number.

Warning

Properties on this object 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.

Note

Since all methods/properties on this object will result in an UPnP request, they might result in an exception without it being mentioned in the Raises section.

In most cases, the exception will be a soco.exceptions.SoCoUPnPException (if the player returns an UPnP error code), but in special cases it might also be another soco.exceptions.SoCoException or even a requests exception.

ip_address

The speaker’s ip address

property boot_seqnum

The boot sequence number.

Type

int

property player_name

The speaker’s name.

Type

str

property uid

A unique identifier.

Looks like: 'RINCON_000XXXXXXXXXX1400'

Type

str

property household_id

A unique identifier for all players in a household.

Looks like: 'Sonos_asahHKgjgJGjgjGjggjJgjJG34'

Type

str

property 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.

Type

bool

property is_bridge

Is this zone a bridge?

Type

bool

property is_coordinator

Is this zone a group coordinator?

Type

bool

property is_satellite

Is this zone a satellite in a home theater setup?

Type

bool

property has_satellites

Is this zone configured with satellites in a home theater setup?

Will only return True on the primary device in a home theater configuration.

Type

bool

property is_subwoofer

Is this zone a subwoofer?

Type

bool

property has_subwoofer

Is this zone configured with a subwoofer?

Only provides reliable results when called on the soundbar or subwoofer devices if configured in a home theater setup.

Type

bool

property channel

Location of this zone in a home theater or paired configuration.

Can be one of “LF,RF”, “LF”, “RF”, “LR”, “RR”, “SW”, or None.

Type

str

property is_soundbar

Is this zone a soundbar (i.e. has night mode etc.)?

Type

bool

property play_mode

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.

  • 'REPEAT_ONE' – Turns on repeat one and turns off shuffle.

  • 'SHUFFLE_REPEAT_ONE' – Turns on shuffle and repeat one. (It’s strange, I know.)

Type

str

property shuffle

The queue’s shuffle option.

True if enabled, False otherwise.

Type

bool

property repeat

The queue’s repeat option.

True if enabled, False otherwise.

Can also be the string 'ONE' for play mode 'REPEAT_ONE'.

Type

bool

property cross_fade

The speaker’s cross fade state.

True if enabled, False otherwise

Type

bool

ramp_to_volume(volume, ramp_type='SLEEP_TIMER_RAMP_TYPE')[source]

Smoothly change the volume.

There are three ramp types available:

  • 'SLEEP_TIMER_RAMP_TYPE' (default): Linear ramp from the current volume up or down to the new volume. The ramp rate is 1.25 steps per second. For example: To change from volume 50 to volume 30 would take 16 seconds.

  • 'ALARM_RAMP_TYPE': Resets the volume to zero, waits for about 30 seconds, and then ramps the volume up to the desired value at a rate of 2.5 steps per second. For example: Volume 30 would take 12 seconds for the ramp up (not considering the wait time).

  • 'AUTOPLAY_RAMP_TYPE': Resets the volume to zero and then quickly ramps up at a rate of 50 steps per second. For example: Volume 30 will take only 0.6 seconds.

The ramp rate is selected by Sonos based on the chosen ramp type and the resulting transition time returned. This method is non blocking and has no network overhead once sent.

Parameters
  • volume (int) – The new volume.

  • ramp_type (str, optional) – The desired ramp type, as described above.

Returns

The ramp time in seconds, rounded down. Note that this does not include the wait time.

Return type

int

set_relative_volume(relative_volume)[source]

Adjust the volume up or down by a relative amount.

If the adjustment causes the volume to overshoot the maximum value of 100, the volume will be set to 100. If the adjustment causes the volume to undershoot the minimum value of 0, the volume will be set to 0.

Note that this method is an alternative to using addition and subtraction assignment operators (+=, -=) on the volume property of a SoCo instance. These operators perform the same function as set_relative_volume but require two network calls per operation instead of one.

Parameters

relative_volume (int) – The relative volume adjustment. Can be positive or negative.

Returns

The new volume setting.

Return type

int

Raises

ValueError – If relative_volume cannot be cast as an integer.

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.

Parameters
  • index (int) – 0-based index of the track to play

  • start (bool) – If the item that has been set should start playing

play()[source]

Play the currently selected track.

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

Play a URI.

Playing a URI will replace what was playing with the stream given by the URI. For some streams at least a title is required as metadata. This can be provided using the meta argument or the title argument. If the title argument is provided minimal metadata will be generated. If meta argument is provided the title argument is ignored.

Parameters
  • uri (str) – URI of the stream to be played.

  • meta (str) – The metadata to show in the player, DIDL format.

  • title (str) – The title to show in the player (if no meta).

  • start (bool) – If the URI that has been set should start playing.

  • force_radio (bool) – forces a uri to play as a radio stream.

On a Sonos controller music is shown with one of the following display formats and controls:

  • Radio format: Shows the name of the radio station and other available data. No seek, next, previous, or voting capability. Examples: TuneIn, radioPup

  • Smart Radio: Shows track name, artist, and album. Limited seek, next and sometimes voting capability depending on the Music Service. Examples: Amazon Prime Stations, Pandora Radio Stations.

  • Track format: Shows track name, artist, and album the same as when playing from a queue. Full seek, next and previous capabilities. Examples: Spotify, Napster, Rhapsody.

How it is displayed is determined by the URI prefix: x-sonosapi-stream:, x-sonosapi-radio:, x-rincon-mp3radio:, hls-radio: default to radio or smart radio format depending on the stream. Others default to track format: x-file-cifs:, aac:, http:, https:, x-sonos-spotify: (used by Spotify), x-sonosapi-hls-static: (Amazon Prime), x-sonos-http: (Google Play & Napster).

Some URIs that default to track format could be radio streams, typically http:, https: or aac:. To force display and controls to Radio format set force_radio=True

Note

Other URI prefixes exist but are less common. If you have information on these please add to this doc string.

Note

A change in Sonos® (as of at least version 6.4.2) means that the devices no longer accepts ordinary http: and https: URIs for radio stations. This method has the option to replaces these prefixes with the one that Sonos® expects: x-rincon-mp3radio: by using the “force_radio=True” parameter. A few streams may fail if not forced to to Radio format.

pause()[source]

Pause the currently playing track.

stop()[source]

Stop the currently playing track.

end_direct_control_session()[source]

Ends all third-party controlled streaming sessions.

seek(position=None, track=None)[source]

Seek to a given position.

You can seek both a relative position in the current track and a track number in the queue. It is even possible to seek to a tuple or dict containing the absolute position (relative pos. and track nr.):

t = ('0:00:00', 0)
player.seek(*t)
d = {'position': '0:00:00', 'track': 0}
player.seek(**d)
Parameters
  • position (str) – The desired timestamp in the current track, specified in the format of HH:MM:SS or H:MM:SS

  • track (int) – The (zero-based) track index in the queue

Raises
  • ValueError – If neither position nor track are specified.

  • SoCoUPnPException – UPnP Error 701 if seeking is not supported, UPnP Error 711 if the target is invalid.

Note

The ‘track’ parameter can only be used if the queue is currently playing. If not, use play_from_queue().

This is currently faster than play_from_queue() if already using the queue, as it does not reinstate the queue.

If speaker is already playing it will continue to play after seek. If paused it will remain paused.

next()[source]

Go to the next track.

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.

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.

property mute

The speaker’s mute state.

True if muted, False otherwise.

Type

bool

property volume

The speaker’s volume.

An integer between 0 and 100.

Type

int

property bass

The speaker’s bass EQ.

An integer between -10 and 10.

Type

int

property treble

The speaker’s treble EQ.

An integer between -10 and 10.

Type

int

property loudness

The speaker’s loudness compensation.

True if on, False otherwise.

Loudness is a complicated topic. You can read about it on Wikipedia: https://en.wikipedia.org/wiki/Loudness

Type

bool

property surround_enabled

Reports if the home theater surround speakers are enabled.

Should only be called on the primary device in a home theater setup.

True if on, False if off, None if not supported.

Type

bool

property sub_enabled

Reports if the subwoofer is enabled.

True if on, False if off, None if not supported.

Type

bool

property sub_gain

The current subwoofer gain level.

Returns the current value or None if not supported.

Type

int

property balance

The left/right balance for the speaker(s).

Returns

A 2-tuple (left_channel, right_channel) of integers between 0 and 100, representing the volume of each channel. E.g., (100, 100) represents full volume to both channels, whereas (100, 0) represents left channel at full volume, right channel at zero volume.

Return type

tuple

property audio_delay

The TV Dialog Sync audio delay.

Returns the current value or None if not supported.

Type

int

property night_mode

The speaker’s night mode.

True if on, False if off, None if not supported.

Type

bool

property dialog_mode

The speaker’s dialog mode.

True if on, False if off, None if not supported.

Type

bool

property surround_full_volume_enabled

Return True if surround full volume is enabled for surround music playback.

If False, playback on surround speakers uses ambient volume.

Note: does not apply to TV playback.

property surround_mode

Convenience surround_full_volume_enabled getter to match raw Sonos API.

property surround_volume_tv

Get the relative volume for surround speakers in TV playback mode. Ranges from -15 to +15.

property surround_level

Convenience getter for surround_volume_tv to match raw Sonos API.

property surround_volume_music

Return the relative volume for surround speakers in music mode, in the range -15 to +15.

property music_surround_level

Convenience getter for surround_volume_music to match raw Sonos API.

property dialog_level

Convenience wrapper for dialog_mode getter to match raw Sonos API.

property trueplay

Whether Trueplay is enabled on this device. True if on, False if off.

Devices that do not support Trueplay, or which do not have a current Trueplay calibration, will return None on getting the property, and raise a NotSupportedException when setting the property.

Can only be set on visible devices. Attempting to set on non-visible devices will raise a SoCoNotVisibleException.

Type

bool

property soundbar_audio_input_format_code

Return audio input format code as reported by the device.

Returns None when the device is not a soundbar.

While the variable is available on non-soundbar devices, it is likely always 0 for devices without audio inputs.

See also soundbar_audio_input_format() for obtaining a human-readable description of the format.

property soundbar_audio_input_format

Return a string presentation of the audio input format.

Returns None when the device is not a soundbar. Otherwise, this will return the string presentation of the currently active sound format (e.g., “Dolby 5.1” or “No input”)

See also soundbar_audio_input_format_code() for the raw value.

property supports_fixed_volume

Whether the device supports fixed volume output.

Type

bool

property fixed_volume

The device’s fixed volume output setting.

True if on, False if off. Only applicable to certain Sonos devices (Connect and Port at the time of writing). All other devices always return False.

Attempting to set this property for a non-applicable device will raise a NotSupportedException.

Type

bool

property zone_group_state

Return the assocated ZoneGroupState instance.

property all_groups

All available groups.

Type

set of soco.groups.ZoneGroup

property group

The Zone Group of which this device is a member.

None if this zone is a slave in a stereo pair.

Type

soco.groups.ZoneGroup

property all_zones

All available zones.

Type

set of soco.groups.ZoneGroup

property visible_zones

All visible zones.

Type

set of soco.groups.ZoneGroup

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.

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.

create_stereo_pair(rh_slave_speaker)[source]

Create a stereo pair.

This speaker becomes the master, left-hand speaker of the stereo pair. The rh_slave_speaker becomes the right-hand speaker. Note that this operation will succeed on dissimilar speakers, unlike when using the official Sonos apps.

Parameters

rh_slave_speaker (SoCo) – The speaker that will be added as the right-hand, slave speaker of the stereo pair.

Raises

SoCoUPnPException – if either speaker is already part of a stereo pair.

separate_stereo_pair()[source]

Separate a stereo pair.

This can be called on either the master (left-hand) speaker, or on the slave (right-hand) speaker, to create two independent zones.

Raises

SoCoUPnPException – if the speaker is not a member of a stereo pair.

switch_to_line_in(source=None)[source]

Switch the speaker’s input to line-in.

Parameters

source (SoCo) – The speaker whose line-in should be played. Default is line-in from the speaker itself.

property is_playing_radio

Is the speaker playing radio?

Type

bool

property is_playing_line_in

Is the speaker playing line-in?

Type

bool

property is_playing_tv

Is the playbar speaker input from TV?

Type

bool

static music_source_from_uri(uri)[source]

Determine a music source from a URI.

Parameters

uri (str) – The URI representing the music source

Returns

The current source of music.

Return type

str

Possible return values are:

  • 'NONE' – speaker has no music to play.

  • 'LIBRARY' – speaker is playing queued titles from the music library.

  • 'RADIO' – speaker is playing radio.

  • 'WEB_FILE' – speaker is playing a music file via http/https.

  • 'LINE_IN' – speaker is playing music from line-in.

  • 'TV' – speaker is playing input from TV.

  • 'AIRPLAY' – speaker is playing from AirPlay.

  • 'UNKNOWN' – any other input.

The strings above can be imported as MUSIC_SRC_LIBRARY, MUSIC_SRC_RADIO, etc.

property music_source

The current music source (radio, TV, line-in, etc.).

Possible return values are the same as used in music_source_from_uri().

Type

str

switch_to_tv()[source]

Switch the playbar speaker’s input to TV.

property status_light

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

True if on, otherwise False.

Type

bool

property buttons_enabled

Whether the control buttons on the device are enabled.

True if the control buttons are enabled, False if disabled.

This property can only be set on visible speakers, and will enable or disable the buttons for all speakers in any bonded set (e.g., a stereo pair). Attempting to set it on invisible speakers (e.g., the RH speaker of a stereo pair) will raise a SoCoNotVisibleException.

Type

bool

property voice_service_configured

Is a voice service configured on this device?

Type

bool

property mic_enabled

Is the device’s microphone enabled?

Note

Returns None if the device does not have a microphone or if a voice service is not configured.

Type

bool

get_current_track_info()[source]

Get information about the currently playing track.

Returns

A dictionary containing information about the currently playing track: playlist_position, duration, title, artist, album, position and an album_art link.

Return type

dict

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_current_media_info()[source]

Get information about the currently playing media.

Returns

A dictionary containing information about the currently playing media: uri, channel.

Return type

dict

If we’re unable to return data for a field, we’ll return an empty string.

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

Get information about the Sonos speaker.

Parameters
  • refresh (bool) – Refresh the speaker info cache.

  • timeout – How long to wait for the server to send 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.

Return type

dict

get_current_transport_info()[source]

Get the current playback state.

Returns

The following information about the speaker’s playing state:

  • current_transport_state (PLAYING, TRANSITIONING, PAUSED_PLAYBACK, STOPPED)

  • current_transport_status (OK, ?)

  • current_speed(1, ?)

Return type

dict

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

property available_actions

The transport actions that are currently available on the speaker.

Returns

list: A list of strings representing the available actions, such as [‘Set’, ‘Stop’, ‘Play’].

Possible list items are: ‘Set’, ‘Stop’, ‘Pause’, ‘Play’, ‘Next’, ‘Previous’, ‘SeekTime’, ‘SeekTrackNr’.

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 heavily based on Sam Soffes (aka soffes) ruby implementation

property queue_size

Size of the queue.

Type

int

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

Convenience method for calling soco.music_library.get_music_library_information('sonos_playlists')

Refer to the docstring for that method: get_music_library_information

add_uri_to_queue(uri, position=0, as_next=False, **kwargs)[source]

Add the URI to the queue.

For arguments and return value see add_to_queue.

add_to_queue(queueable_item, position=0, as_next=False, **kwargs)[source]

Add a queueable item to the queue.

Parameters
  • queueable_item (DidlObject or MusicServiceItem) – The item to be added to the queue

  • position (int) – The index (1-based) at which the URI should be added. Default is 0 (add URI at the end of the queue).

  • as_next (bool) – Whether this URI should be played as the next track in shuffle mode. This only works if play_mode=SHUFFLE.

Returns

The index of the new item in the queue.

Return type

int

add_multiple_to_queue(items, container=None, **kwargs)[source]

Add a sequence of items to the queue.

Parameters
  • items (list) – A sequence of items to the be added to the queue

  • container (DidlObject, optional) – A container object which includes the items.

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.

Parameters

index (int) – The (0-based) index of the track to remove

clear_queue()[source]

Remove all tracks from the queue.

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

Get favorite radio shows from Sonos’ Radio app.

Returns:

dict: A dictionary 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.

Deprecated since version 0.13: Will be removed in version 0.15. Use soco.music_library.get_favorite_radio_shows instead.

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

Get favorite radio stations from Sonos’ Radio app.

See get_favorite_radio_shows() for return type and remarks.

Deprecated since version 0.13: Will be removed in version 0.15. Use soco.music_library.get_favorite_radio_stations instead.

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

Get Sonos favorites.

See get_favorite_radio_shows() for return type and remarks.

Deprecated since version 0.13: Will be removed in version 0.15. Use soco.music_library.get_sonos_favorites instead.

create_sonos_playlist(title)[source]

Create a new empty Sonos playlist.

Parameters

title – Name of the playlist

Return type

DidlPlaylistContainer

create_sonos_playlist_from_queue(title)[source]

Create a new Sonos playlist from the current queue.

Parameters

title – Name of the playlist

Return type

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 (DidlObject) – the item to add to the Sonos’ playlist

  • sonos_playlist (DidlPlaylistContainer) – the Sonos’ playlist to which the item should be added

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
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

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

Example:

device.get_sonos_playlist_by_attr('title', 'Foo')
device.get_sonos_playlist_by_attr('item_id', 'SQ:3')
get_battery_info(timeout=3.0)[source]

Get battery information for a Sonos speaker.

Obtains battery information for Sonos speakers that report it. This only applies to Sonos Move speakers at the time of writing.

This method may only work on Sonos ‘S2’ systems.

Parameters

timeout (float, optional) – The timeout to use when making the HTTP request.

Returns

A dict containing battery status data.

Example return value:

{'Health': 'GREEN',
 'Level': 100,
 'Temperature': 'NORMAL',
 'PowerSource': 'SONOS_CHARGING_RING'}

Return type

dict

Raises
  • NotSupportedException – If the speaker does not report battery information.

  • ConnectionError – If the HTTP connection failed, or returned an unsuccessful status code.

  • TimeoutError – If making the HTTP connection, or reading the response, timed out.