Device Interaction

Several devices which supports UPnP also support a way to control/run actions on the device. Certain devices, like TR64 supporting devices, let you totally configure and monitor any functionality. To be able to execute an actions the following information’s are needed:

  • Control URI
  • Namespace
  • Action name
  • Optional parameters

The control URI which is called to place the action and also the namespace aka service type is needed. The namespace defines the scope or service type of the given action, the same action name can appear in different namespaces.

Any device which supports TR64, DNLA or any other protocol which is based on UPnP can be controlled with this library.

See also

execute()

The scripts which have been provided with this library shows good use of the full library.

Additional short explanation of the UPnP protocol

Protocol

The protocol which controls/execute an action is based on the UPnP standard which itself uses SOAP. The following python call:

>>> device = simpletr64.DeviceTR64(hostname=192.168.178.1, port=49000)
...
>>> device.execute("/upnp/control/hosts", "urn:dslforum-org:service:Hosts:1", "GetGenericHostEntry", NewIndex=1)
{'NewActive': '0', 'NewIPAddress': '192.168.0.23', 'NewMACAddress': '9C:20:7B:E7:FF:5F', 'NewInterfaceType':
    'Ethernet', 'NewHostName': 'Apple-TV', 'NewAddressSource': 'DHCP', 'NewLeaseTimeRemaining': '0'}

will create the following Action request:

POST /upnp/control/hosts HTTP/1.1
Host: 192.168.178.1:49000
Content-Length: 422
Accept-Encoding: gzip, deflate
Soapaction: "urn:dslforum-org:service:Hosts:1#GetGenericHostEntry"
Accept: */*
User-Agent: python-requests/2.5.4.1 CPython/2.6.9 Darwin/15.2.0
Connection: keep-alive
Content-Type: text/xml; charset="UTF-8"

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soap:Header/>
    <soap:Body>
        <GetGenericHostEntry xmlns="urn:dslforum-org:service:Hosts:1">
            <NewIndex>1</NewIndex>
        </GetGenericHostEntry>
</soap:Body>
</soap:Envelope>

An example response:

HTTP/1.1 200 OK
DATE: Sat, 02 Jan 2016 14:12:44 GMT
SERVER: FRITZ!Box Fon WLAN 7390 UPnP/1.0 AVM FRITZ!Box Fon WLAN 7390 84.06.30
CONNECTION: keep-alive
CONTENT-LENGTH: 576
CONTENT-TYPE: text/xml; charset="utf-8"
EXT:

<?xml version="1.0"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<s:Body>
<u:GetGenericHostEntryResponse xmlns:u="urn:dslforum-org:service:Hosts:1">
<NewIPAddress>192.168.0.23</NewIPAddress>
<NewAddressSource>DHCP</NewAddressSource>
<NewLeaseTimeRemaining>0</NewLeaseTimeRemaining>
<NewMACAddress>9C:20:7B:E7:FF:5F</NewMACAddress>
<NewInterfaceType>Ethernet</NewInterfaceType>
<NewActive>0</NewActive>
<NewHostName>Apple-TV</NewHostName>
</u:GetGenericHostEntryResponse>
</s:Body>
</s:Envelope>

Authentication

Depending on the device and the settings some actions might need you to authenticate before you call the action. Again depending on the device and the settings you might be requested to provide a username and password or some devices might only ask for a password, please check your configuration. When you set username/password or just password the authentication will be done transparently.

Example:

device = DeviceTR64(...)
device.password = "my secret"

Proxies

For any http/https call a proxy can be set, the way depends on the Class you use. The DeviceTR64 class supports it via httpProxy() and httpsProxy(); the method discoverParticularHost() in the Discover class ask you to provide the proxy definition for each call. Please, see the dedicated methods documentation for how to specify the proxies as the definition differs.

Classes

class simpletr64.DeviceTR64(hostname, port=49000, protocol='http')

The basic class which represents an UPnP device.

A device supports methods to gather information’s about a hardware device and to execute actions.

static createFromURL(urlOfXMLDefinition)

Factory method to create a DeviceTR64 from an URL to the XML device definitions.

Parameters:urlOfXMLDefinition (str) –
Returns:the new DeviceTR64 object
Return type:DeviceTR64
deviceInformationUnknownKeys

Returns all device information’s which are very specific to this device, if loaded with loadDeviceDefinitions() before.

If the device definitions have been loaded this methods returns all parsed device information’s which are not standard conform and very specific to the device.

Returns:device specific information’s
Return type:dict[str, str]
deviceInformations

Returns all device informations if loaded before.

If the device definitions have been loaded with loadDeviceDefinitions() before this methods returns all parsed device information’s like device type, device model, manufacture, etc, is empty if device information’s have not been loaded before.

Some examples of known information keys:

deviceType, manufacturer, manufacturerURL, modelDescription, modelName, modelNumber, serialNumber

Not all keys needs to be present and can be extended any time, still it is a pre defined set and any unknown information type will be stored differently and can be obtained via deviceInformationUnknownKeys().

Returns:device information’s
Return type:dict[str, str]
deviceSCPD

Returns the loaded SCPD (Service Control Protocol Document)/action definitions.

Returns all action definitions which have been loaded before with loadSCPD(). The action definitions are usefull to understand what kind of interaction functionality a device supports.

The result is structured in the following way:

{ "<actionName>": { "inParameter": {"name": <>, "variable": <>, "dataType": <>, "defaultValue": <>},
                    "outParameter": {"name": <>, "variable": <>, "dataType": <>, "defaultValue": <>} } }

The following keys are optional: inParameter, outParameter, variable, defaultValue

Parameter keys:

  • name: the name of the parameter
  • variable: an optional name to a virtual variable
  • dataType: the data type of this parameter, these are not fixed and depend on the schema and device vendor
  • defaultValue: an optional default value for this parameter
Returns:the loaded action definitions or empty dict if not loaded
Return type:dict[str, dict[str, dict[str, str]]]
deviceServiceDefinitions

Returns all known services and dedicated URI’s if loaded before.

If the device definitions have been loaded with loadDeviceDefinitions() before this returns all the known service types, otherwise the dict will be empty. The returned dictionary maps from a service to an other dictionary which contains usually controlURL, scpdURL and optional eventSubURL:

  • The controlURL is needed to execute an action in the given service type/namespace.

  • The scpdURL is a link to an other XML which defines usually the actions for this service type. These

    will be used if loadSCPD() is called. Also for some devices it can be empty.

  • The eventSubURL is optional and can be used to subscribe to certain events, not supported by this lib yet.

Returns:the service type informations of this device
Return type:dict[dict[str, str]]
execute(uri, namespace, action, timeout=2, **kwargs)

Executes a given action with optional arguments.

The execution of an action of an UPnP/TR64 device needs more than just the name of an action. It needs the control URI which is called to place the action and also the namespace aka service type is needed. The namespace defines the scope or service type of the given action, the same action name can appear in different namespaces.

The way how to obtain the needed information’s is either through the documentation of the vendor of the device. Or through a discovery requests which return’s the URL to the root device description XML.

Parameters:
  • uri (str) – the control URI, for example /upnp/control/hosts
  • namespace (str) – the namespace for the given action, for example urn:dslforum-org:service:Hosts:1
  • action (str) – the name of the action to call, for example GetGenericHostEntry
  • timeout (float) – the timeout to wait for the action to be executed
  • kwargs (dict[str, str]) – optional arguments for the given action, depends if the action needs parameter. The arguments are given as dict where the key is the parameter name and the value the value of the parameter.
Returns:

returns the results of the action, if any. The results are structured as dict where the key is the name of the result argument and the value is the value of the result.

Return type:

dict[str,str]

Raises:
  • ValueError – if parameters are not set correctly
  • requests.exceptions.ConnectionError – when the action can not be placed on the device
  • requests.exceptions.ConnectTimeout – when download time out

Example:

device = DeviceTR64(...)
device.execute("/upnp/control/hosts", "urn:dslforum-org:service:Hosts:1",
    "GetGenericHostEntry", {"NewIndex": 1})
{'NewActive': '0', 'NewIPAddress': '192.168.0.23', 'NewMACAddress': '9C:20:7B:E7:FF:5F',
    'NewInterfaceType': 'Ethernet', 'NewHostName': 'Apple-TV', 'NewAddressSource': 'DHCP',
    'NewLeaseTimeRemaining': '0'}
getControlURL(serviceType, default=None)

Returns the control URL for a given service type.

When the device definitions have been loaded with loadDeviceDefinitions() this method returns for a given service type/namespace the associated control URL. If the device definitions have not been loaded a default value can be given which gets returned instead. The control URL is used to execute actions for a dedicated service type/namespace.

Parameters:
  • serviceType – the service type to look up for
  • default (str or None) – the default return value in case the service type is not found and device definitions are not loaded
Returns:

the URL/URI

Return type:

str or None

Raises ValueError:
 

if the device did load device definitions and the service type is not known.

getEventSubURL(serviceType, default=None)

Returns the event URL for a given service type.

When the device definitions have been loaded with loadDeviceDefinitions() this method returns for a given service type/namespace the associated event URL. If the device definitions have not been loaded a default value can be given which gets returned instead.

Parameters:
  • serviceType – the service type to look up for
  • default (str or None) – the default return value in case the service type is not found and device definitions are not loaded
Returns:

the URL/URI

Return type:

str or None

Raises ValueError:
 

if the device did load device definitions and the service type is not known.

getSCDPURL(serviceType, default=None)

Returns the SCDP (Service Control Protocol Document) URL for a given service type.

When the device definitions have been loaded with loadDeviceDefinitions() this method returns for a given service type/namespace the associated URL to the SCDP. If the device definitions have not been loaded a default value can be given which gets returned instead. The SCDP specifies all the interaction functionality a device provides.

Parameters:
  • serviceType – the service type to look up for
  • default (str or None) – the default return value in case the service type is not found and device definitions are not loaded
Returns:

the URL/URI

Return type:

str or None

Raises ValueError:
 

if the device did load device definitions and the service type is not known.

host

Return the hostname of this device which was given when instantiated.

Returns:the hostname or ip address of this device
Return type:str
httpProxy

Property to get and set the URL to the http proxy which gets used for any http requests.

Parameters:proxy (str) – the URL to the http proxy
Return type:str

Example:

device = DeviceTR64(...)
device.httpProxy("http://localhost:8888/")
httpsProxy

Property to get and set the URL to the https proxy which gets used for any https requests.

Parameters:proxy (str) – the URL to the https proxy
Return type:str

Example:

device = DeviceTR64(...)
device.httpsProxy("https://localhost:8889/")
loadDeviceDefinitions(urlOfXMLDefinition, timeout=3)

Loads the device definitions from a given URL which points to the root XML in the device.

This loads the device definitions which is needed in case you like to:

  • get additional information’s about the device like manufacture, device type, etc
  • get all support service types of this device
  • use the convenient actions classes part of this library in the actions module
Parameters:
  • urlOfXMLDefinition (str) – the URL to the root XML which sets the device definitions.
  • timeout (float) – the timeout for downloading
Raises:
  • ValueError – if the XML could not be parsed correctly
  • requests.exceptions.ConnectionError – when the device definitions can not be downloaded
  • requests.exceptions.ConnectTimeout – when download time out
loadSCPD(serviceType=None, timeout=3, ignoreFailures=False)

Load action definition(s) (Service Control Protocol Document).

If the device definitions have been loaded via loadDeviceDefinitions() this method loads actions definitions. The action definitions are needed if you like to execute an action on a UPnP device. The actions definition contains the name of the action, the input and output parameter. You use the definition either with execute() or with the actions module of this library which predefines a lot of actions based on the TR64 standard.

Parameters:
  • serviceType – the serviceType for which the action definitions should be loaded or all known service types if None.
  • timeout (float) – the timeout for downloading
  • ignoreFailures (bool) – if set to true and serviceType is None any failure in the iteration of loading all SCPD will be ignored.
Raises:
  • ValueType – if the given serviceType is not known or when the definition can not be loaded.
  • requests.exceptions.ConnectionError – when the scpd can not be downloaded
  • requests.exceptions.ConnectTimeout – when download time out
password

Property to set and get the password which gets used to authenticate, if empty it will not be used.

Return type:str
port

Return the port of this device which was given when instantiated.

Returns:the port of this device
Return type:int
protocol

Return the protocol to communicate with this device which was given when instantiated.

Returns:the communication protocol of this device
Return type:str
setupTR64Device(deviceType)

Setup actions for known devices.

For convenience reasons for some devices there is no need to discover/load device definitions before the pre defined TR 64 Protocol Actions can be used.

The following devices are currently supported (please help to extend):

  • fritz.box - Any AVM Fritz Box with the latest software version installed
Parameters:deviceType (str) – a known device type
Raises ValueError:
 if the device type is not known.
username

Property to set and get the username which gets used to authenticate, can be empty.

Return type:str