soco.services module
Classes representing Sonos UPnP services.
>>> import soco
>>> device = soco.SoCo('192.168.1.102')
>>> print(RenderingControl(device).GetMute([('InstanceID', 0),
... ('Channel', 'Master')]))
{'CurrentMute': '0'}
>>> r = ContentDirectory(device).Browse([
... ('ObjectID', 'Q:0'),
... ('BrowseFlag', 'BrowseDirectChildren'),
... ('Filter', '*'),
... ('StartingIndex', '0'),
... ('RequestedCount', '100'),
... ('SortCriteria', '')
... ])
>>> print(r['Result'])
<?xml version="1.0" ?><DIDL-Lite xmlns="urn:schemas-upnp-org:metadata ...
>>> for action, in_args, out_args in AlarmClock(device).iter_actions():
... print(action, in_args, out_args)
...
SetFormat [Argument(name='DesiredTimeFormat', vartype='string'), Argument(
name='DesiredDateFormat', vartype='string')] []
GetFormat [] [Argument(name='CurrentTimeFormat', vartype='string'),
Argument(name='CurrentDateFormat', vartype='string')] ...
- class soco.services.Action(name, in_args, out_args)[source]
A UPnP Action and its arguments.
Create new instance of ActionBase(name, in_args, out_args)
- class soco.services.Argument(name, vartype)[source]
A UPnP Argument and its type.
Create new instance of ArgumentBase(name, vartype)
- class soco.services.Vartype(datatype, default, list, range)[source]
An argument type with default value and range.
Create new instance of VartypeBase(datatype, default, list, range)
- class soco.services.Service(soco)[source]
A class representing a UPnP service.
This is the base class for all Sonos Service classes. This class has a dynamic method dispatcher. Calls to methods which are not explicitly defined here are dispatched automatically to the service action with the same name.
- cache
A cache for storing the result of network calls. By default, this is a
TimedCache
with a default timeout=0.
- static wrap_arguments(args=None)[source]
Wrap a list of tuples in xml ready to pass into a SOAP request.
- Parameters
args (list) – a list of (name, value) tuples specifying the name of each argument and its value, eg
[('InstanceID', 0), ('Speed', 1)]
. The value can be a string or something with a string representation. The arguments are escaped and wrapped in <name> and <value> tags.
Example
>>> from soco import SoCo >>> device = SoCo('192.168.1.101') >>> s = Service(device) >>> print(s.wrap_arguments([('InstanceID', 0), ('Speed', 1)])) <InstanceID>0</InstanceID><Speed>1</Speed>'
- static unwrap_arguments(xml_response)[source]
Extract arguments and their values from a SOAP response.
- compose_args(action_name, in_argdict)[source]
Compose the argument list from an argument dictionary, with respect for default values.
- Parameters
- Returns
a list of
(name, value)
tuples.- Return type
- Raises
AttributeError – If this service does not support the action.
ValueError – If the argument lists do not match the action signature.
- build_command(action, args=None)[source]
Build a SOAP request.
- Parameters
- Returns
a tuple containing the POST headers (as a dict) and a string containing the relevant SOAP body. Does not set content-length, or host headers, which are completed upon sending.
- Return type
- send_command(action, args=None, cache=None, cache_timeout=None, **kwargs)[source]
Send a command to a Sonos device.
- Parameters
action (str) – the name of an action (a string as specified in the service description XML file) to be sent.
args (list, optional) – Relevant arguments as a list of (name, value) tuples, as an alternative to
kwargs
.cache (Cache) – A cache is operated so that the result will be stored for up to
cache_timeout
seconds, and a subsequent call with the same arguments within that period will be returned from the cache, saving a further network call. The cache may be invalidated or even primed from another thread (for example if a UPnP event is received to indicate that the state of the Sonos device has changed). Ifcache_timeout
is missing orNone
, the cache will use a default value (which may be 0 - seecache
). By default, the cache identified by the service’scache
attribute will be used, but a different cache object may be specified in thecache
parameter.kwargs – Relevant arguments for the command.
- Returns
a dict of
{argument_name, value}
items.- Return type
- Raises
AttributeError – If this service does not support the action.
ValueError – If the argument lists do not match the action signature.
SoCoUPnPException – if a SOAP error occurs.
UnknownSoCoException – if an unknown UPnP error occurs.
requests.exceptions.HTTPError – if an http error occurs.
- handle_upnp_error(xml_error)[source]
Disect a UPnP error, and raise an appropriate exception.
- Parameters
xml_error (str) – a unicode string containing the body of the UPnP/SOAP Fault response. Raises an exception containing the error code.
- subscribe(requested_timeout=None, auto_renew=False, event_queue=None, strict=True)[source]
Subscribe to the service’s events.
- Parameters
requested_timeout (int, optional) – If requested_timeout is provided, a subscription valid for that number of seconds will be requested, but not guaranteed. Check
timeout
on return to find out what period of validity is actually allocated.auto_renew (bool) – If auto_renew is
True
, the subscription will automatically be renewed just before it expires, if possible. Default isFalse
.event_queue (
Queue
) – a thread-safe queue object on which received events will be put. If not specified, a (Queue
) will be created and used.strict (bool, optional) – If True and an Exception occurs during execution, the Exception will be raised or, if False, the Exception will be logged and the Subscription instance will be returned. Default
True
.
- Returns
an instance of
Subscription
, representing the new subscription. If config.EVENTS_MODULE has been set to refer toevents_twisted
, a deferred will be returned with the Subscription as its result and deferred.subscription will be set to refer to the Subscription.- Return type
To unsubscribe, call the
unsubscribe()
method on the returned object.
- property actions
The service’s actions with their arguments.
- Returns
A list of Action namedtuples, consisting of action_name (str), in_args (list of Argument namedtuples, consisting of name and argtype), and out_args (ditto).
- Return type
list(
Action
)
The return value looks like this:
[ Action( name='GetMute', in_args=[ Argument(name='InstanceID', ...), Argument( name='Channel', vartype='string', list=['Master', 'LF', 'RF', 'SpeakerOnly'], range=None ) ], out_args=[ Argument(name='CurrentMute, ...) ] ) Action(...) ]
Its string representation will look like this:
GetMute(InstanceID: ui4, Channel: [Master, LF, RF, SpeakerOnly]) -> {CurrentMute: boolean}
- iter_actions()[source]
Yield the service’s actions with their arguments.
- Yields
Action
– the next action.
Each action is an Action namedtuple, consisting of action_name (a string), in_args (a list of Argument namedtuples consisting of name and argtype), and out_args (ditto), eg:
Action( name='SetFormat', in_args=[ Argument(name='DesiredTimeFormat', vartype=<Vartype>), Argument(name='DesiredDateFormat', vartype=<Vartype>)], out_args=[] )
- property event_vars
The service’s eventable variables.
- class soco.services.AlarmClock(soco)[source]
Sonos alarm service, for setting and getting time and alarms.
- class soco.services.MusicServices(soco)[source]
Sonos music services service, for functions related to 3rd party music services.
- class soco.services.AudioIn(soco)[source]
Sonos audio in service, for functions related to RCA audio input.
- class soco.services.DeviceProperties(soco)[source]
Sonos device properties service, for functions relating to zones, LED state, stereo pairs etc.
- class soco.services.SystemProperties(soco)[source]
Sonos system properties service, for functions relating to authentication etc.
- class soco.services.ZoneGroupTopology(soco)[source]
Sonos zone group topology service, for functions relating to network topology, diagnostics and updates.
- class soco.services.GroupManagement(soco)[source]
Sonos group management service, for services relating to groups.
- class soco.services.ContentDirectory(soco)[source]
UPnP standard Content Directory service, for functions relating to browsing, searching and listing available music.
- class soco.services.MS_ConnectionManager(soco)[source]
UPnP standard connection manager service for the media server.
- class soco.services.RenderingControl(soco)[source]
UPnP standard rendering control service, for functions relating to playback rendering, eg bass, treble, volume and EQ.
- class soco.services.MR_ConnectionManager(soco)[source]
UPnP standard connection manager service for the media renderer.
- class soco.services.AVTransport(soco)[source]
UPnP standard AV Transport service, for functions relating to transport management, eg play, stop, seek, playlists etc.