Structure and API

fritzconnection is structured into subpackages:

fritzconnection --|-- cli
                  |-- core --|-- devices
                  |          |-- exceptions
                  |          |-- fritzconnection
                  |          |-- fritzmonitor
                  |          |-- logger
                  |          |-- processor
                  |          |-- soaper
                  |          |-- utils
                  |
                  |-- lib
                  |-- tests

The package cli implements the entry-points for command line usage, the tests are in the tests package and the library modules are in lib. The implementation of fritzconnection itself is structured in the core package.

Public API

The public interface is provided by the FritzConnection class, the fritzmonitor- and the exceptions-module.

There are shortcuts to import FritzConnection and FritzMonitor:

from fritzconnection import FritzConnection
from fritzconnection import FritzMonitor

fritzconnection

Module to communicate with the AVM Fritz!Box.

class fritzconnection.core.fritzconnection.FritzConnection(address=None, port=None, user=None, password=None, timeout=None, use_tls=False, pool_connections=10, pool_maxsize=10)

Main class to set up a connection to the Fritz!Box router. All parameters are optional. address should be the ip of a router, in case that are multiple Fritz!Box routers in a network, the ip must be given. Otherwise it is undefined which router will respond. If user and password are not provided, the environment gets checked for FRITZ_USERNAME and FRITZ_PASSWORD settings and taken from there, if found.

The optional parameter timeout is a floating number in seconds limiting the time waiting for a router response. This is a global setting for the internal communication with the router. In case of a timeout a requests.ConnectTimeout exception gets raised. (New in version 1.1)

use_tls accepts a boolean for using encrypted communication with the Fritz!Box. Default is False. (New in version 1.2)

For some actions the Fritz!Box needs a password and since Fritz!OS 7.24 also requires a username, the previous default username is just valid for OS versions < 7.24. In case the username is not given and the system version is 7.24 or newer, FritzConnection uses the last logged in username as default. (New in version 1.5)

For applications where the urllib3 default connection-pool size should get adapted, the arguments pool_connections and pool_maxsize can get set explicitly. (New in version 1.6)

call_action(service_name, action_name, *, arguments=None, **kwargs)

Executes the given action of the given service. Both parameters are required. Arguments are optional and can be provided as a dictionary given to ‘arguments’ or as separate keyword parameters. If ‘arguments’ is given additional keyword-parameters as further arguments are ignored. The argument values can be of type str, int or bool. (Note: bool is provided since 1.3. In former versions booleans must provided as numeric values: 1, 0). If the service_name does not end with a number (like 1), a 1 gets added by default. If the service_name ends with a colon and a number, the colon gets removed. So i.e. WLANConfiguration expands to WLANConfiguration1 and WLANConfiguration:2 converts to WLANConfiguration2. Invalid service names will raise a ServiceError and invalid action names will raise an ActionError.

modelname

Returns the modelname of the router.

static normalize_name(name)

Returns the normalized service name. E.g. WLANConfiguration and WLANConfiguration:1 will get converted to WLANConfiguration1.

reboot()

Reboot the system.

reconnect()

Terminate the connection and reconnects with a new ip.

services

Dictionary of service instances. Keys are the service names.

static set_protocol(url, use_tls)

Sets the protocol of the url according to the use_tls-flag and returns the modified url. Does not check whether the url given as parameter is correct.

system_version

Returns system version if known, otherwise None.

fritzmonitor

Module to communicate with the AVM Fritz!Box service providing real time phone-call events.

To run fritzmonitor, the CallMonitor service of the box has to be activated. This can be done with any registered Phone by typing the following codes: activate: #96*5* deactivate: #96*4*

class fritzconnection.core.fritzmonitor.EventReporter(monitor_queue, block_on_filled_queue=False)

Takes a Queue and implements a buffer for line-separated data. If at least one line is in the buffer, the line gets put into the Queue for further processing elsewhere (by a routine reading the queue).

add(data)

Adds the given ‘data’ to the buffer. If the buffer holds at least one line (separated by newline-character), the line (or lines) are put into the ‘monitor_queue’ as events to be processed from a reader elsewhere.

class fritzconnection.core.fritzmonitor.FritzMonitor(address='169.254.1.1', port=1012, timeout=10, encoding='utf-8')

Monitor Fritz!Box events about started, finished, incoming and outgoing calls.

has_monitor_thread

Returns True if a monitor-thread has been created. That should be the case after calling start() and before calling stop().

is_alive

Returns True if there is a monitor-thread and the thread is running. Returns False otherwise.

start(queue_size=256, block_on_filled_queue=False, reconnect_delay=60, reconnect_tries=10, sock=None)

Start the monitor thread and return a Queue instance with the given size to report the call_monitor events. Events are of type string. Raises an OSError if the socket can not get connected in a given timeout. Raises a RuntimeError if start() get called a second time without calling stop() first. queue_size is the number of events the queue can store. If block_on_filled_queue is False the event will get discarded in case of no free block (default). On True the EventReporter will block until a slot is awailable. reconnect_delay defines the maximum time intervall in seconds between reconnection tries, in case that a socket-connection gets lost. reconnect_tries defines the number of consecutive to reconnect a socket before giving up.

stop()

Stop the current running monitor_thread.

fritzconnection.core.fritzmonitor.delayer(min_delay=0.02, max_delay=60, multiplier=10)

delay generator with increasing sleep-times.

exceptions

Exceptions can get imported by:

from fritzconnection.core.exceptions import FritzServiceError
# or:
from fritzconnection.core.exceptions import *

The latter style is often discouraged because of possible namespace-pollution, less clarity about the origin of imported objects and potential name clashings. By using a * import fritzconnection will just import exceptions starting with Fritz in their names.

Exception Hierarchy:

FritzConnectionException
                |
                |--> ActionError --> FritzActionError
                |--> ServiceError --> FritzServiceError
                |
                |--> FritzArgumentError
                |       |
                |       |--> FritzArgumentValueError
                |               |
                |               |--> FritzArgumentStringToShortError
                |               |--> FritzArgumentStringToLongError
                |               |--> FritzArgumentCharacterError
                |
                |--> FritzInternalError
                |       |
                |       |--> FritzActionFailedError
                |       |--> FritzOutOfMemoryError
                |
                |--> FritzSecurityError
                |
                |-->|--> FritzLookUpError
                |   |
KeyError -------+-->|
                |
                |
                |-->|--> FritzArrayIndexError
                    |
IndexError -------->|

Module defining fritzconnection specific exceptions.

exception fritzconnection.core.exceptions.FritzConnectionException

Base Exception for communication errors with the Fritz!Box

exception fritzconnection.core.exceptions.FritzActionError

Exception raised by calling nonexisting actions.

exception fritzconnection.core.exceptions.FritzActionFailedError

Exception raised by the box unable to execute the action properly. Inherits from the more generic FritzInternalError.

exception fritzconnection.core.exceptions.FritzArgumentCharacterError

Exception raised by arguments with invalid characters. Inherits from the more generic FritzArgumentValueError.

exception fritzconnection.core.exceptions.FritzArgumentError

Exception raised by invalid arguments.

exception fritzconnection.core.exceptions.FritzArgumentStringToLongError

Exception raised by arguments with invalid string length for the string being to long. Inherits from the more generic FritzArgumentValueError.

exception fritzconnection.core.exceptions.FritzArgumentStringToShortError

Exception raised by arguments with invalid string length for the string being to short. Inherits from the more generic FritzArgumentValueError.

exception fritzconnection.core.exceptions.FritzArgumentValueError

Exception raised by arguments with invalid values. Inherits from the more generic FritzArgumentError.

exception fritzconnection.core.exceptions.FritzArrayIndexError

Addressing an entry in an internal array by index failed. Inherits from IndexError. So IndexError can also be used for exception handling.

exception fritzconnection.core.exceptions.FritzInternalError

Exception raised by panic in the box.

exception fritzconnection.core.exceptions.FritzLookUpError

Lookup for id or entry in existing internal array failed. Inherits from KeyError. So KeyError can also be used for exception handling.

exception fritzconnection.core.exceptions.FritzOutOfMemoryError

Exception raised by memory shortage of the box. Inherits from the more generic FritzInternalError.

exception fritzconnection.core.exceptions.FritzSecurityError

Authorization error or wrong security context.

exception fritzconnection.core.exceptions.FritzServiceError

Exception raised by calling nonexisting services.

Legathy Exceptions:

exception fritzconnection.core.exceptions.ActionError

Exception raised by calling nonexisting actions. Legathy Exception. Use FritzActionError instead.

exception fritzconnection.core.exceptions.ServiceError

Exception raised by calling nonexisting services. Legathy Exception. Use FritzServiceError instead.

Internal API

The devices-, processor- and soaper-module don’t provide a public interface and are used internally.

devices

Implements the DeviceManager for physical and virtual devices. Every physical device (a router) has a set of virtual subdevices.

class fritzconnection.core.devices.DeviceManager(timeout=None, session=None)

Knows all data about the device and the subdevices, including the available services. Takes an optional timeout parameter to limit the time waiting for a router response. The optional parameter session is a reusable connection and can speed up the communication with the device. In case session is given, timeout will not get used.

add_description(source)

Adds description data about the devices and the according services. ‘source’ is a string with the xml-data, like the content of an igddesc- or tr64desc-file.

load_service_descriptions(address, port)

Triggers the load of the scpd files of the services, so they known their actions.

modelname

Take the root-device of the first description and return the according modelname. This is the name of the Fritz!Box itself. Will raise an IndexError if the method is called before descriptions are added.

scan()

Scans all available services defined by the description files. Must get called after all xml-descriptions are added.

system_info

Returns a tuple with Hardwarecode, Major-, Minor-, Patch-Level, Buildnumber and Display-String, in this order. Return None if this informations are not available.

system_version

Returns the system-version as string with minor- and patch-level. This corresponds to the OS version reported by the router web-interface. Returns None if no system informations are available.

logger

Logging interface for the fritzconnection library.

On module level an instance of FritzLogger gets created as fritzlogger that can get imported by:

>>> from fritzconnection.core.logger import fritzlogger

The fritzlogger instance is preset to report on DEBUG level, the default handler is the NullHandler. To do some logging, a handler must be provided:

>>> fritzlogger.add_handler(the_handler)
>>> fritzlogger.log("the message")  # will get logged now

In case that another logger is already in use, the other logger can get set as parent for fritzlogger. fritzlogger will then use the parent handlers.

>>> fritzlogger.set_parent(another_logger)
>>> fritzlogger.log("the message")  # will get logged now

For convenience fritzlogger provides the methods set_streamhandler and set_filehandler to add predefined handlers.

If logging is activated at debug-level, fritzconnection will log all requests and responses. This can produce a lot of output, especial on initializing a FritzConnection-instance. To suppress output the methods disable and enable can get called. Default mode is enable.

class fritzconnection.core.logger.FritzLogger(level=10)

Wrapper for the logging library to reduce executable code on module global level. As multiple instances would use the same logger, to not get confused this class is a singleton.

add_handler(handler)

Add a handler to the logger.

Handlers will just added once, even if this method get called multiple times with the same handler.

delete_parent()

Deletes the parent logger.

disable()

Disables the logger.

enable()

Enables the logger.

log(message, level=10, **kwargs)

Send the message to the logger. Unknown levels are ignored.

remove_handler(handler)

Remove the given handler from the list of handler. Unknown handlers are ignored.

set_filehandler(filename)

Sets the FileHandler logging to the given filename.

set_level(level)

Set the log-level for the logger.

set_parent(parent)

Set a parent manually.

After calling all registered handlers FritzLogger will call the handlers of the parent chain (which must also all be loggers). Be careful not to create a closed loop of parents!

set_streamhandler()

Sets the StreamHandler logging to stderr.

processor

Module to parse and store the device description and the service data provided by xml and the scpd protocol based on xml. Names partly violate PEP8 representing node-names from xml description files.

class fritzconnection.core.processor.Action

Every Action has a name and a list of arguments.

arguments

Returns the action-arguments as a dict. argument-names are the keys and the argument objects are the values. The dictionary gets cached.

class fritzconnection.core.processor.ActionList(storage)

Collection of actions of a service. The Action instances are stored in the Scpd.actions attribute.

class fritzconnection.core.processor.Argument

An argument with name, direction and relatedStateVariable attributes.

class fritzconnection.core.processor.ArgumentList(storage)

Collects the arguments for an action.

class fritzconnection.core.processor.Description(root)

Root class for a given description information as the content from the files igddesc.xml or tr64desc.xml.

services

Returns dictionary with the known services as values and the according service-names as keys.

system_buildnumber

Returns the buildnumber or None. This information is only available by the ‘tr64desc.xml’ file.

system_display

Returns the system display-string or None. This information is only available by the ‘tr64desc.xml’ file.

system_info

Returns the systemVersion attributes as a tuple: (HW, Major, Minor, Patch, Bildnumber, Display). This information is only available by the ‘tr64desc.xml’ file.

system_version

Returns the system version of the Fritz!Box as a string like ‘7.10’ or None. This information is only available by the ‘tr64desc.xml’ file.

class fritzconnection.core.processor.Device

Storage for devices attributes and device subnodes. Subnodes are the serviceList and the deviceList. The services provided by a device are collected in services. Subdevices are collected in devices. All instance attributes are public for read only use.

class fritzconnection.core.processor.DeviceList(storage)

Collection of sub-devices of a device. The Device instances are stored in the device.devices attribute of the parent device.

class fritzconnection.core.processor.InstanceAttributeFactory(cls)

Non data descriptor returning instances of ‘cls’ and registering these instances in the ‘_storage’ attribute of the calling instance.

class fritzconnection.core.processor.Scpd(root)

Provides informations about the Service Control Point Definitions for every Service. Every Service has one instance of this class for accessing the description of it’s own actions and the according parameters. Root class for processing the content of an scpd-file.

actions

Returns a dictionary with the actions from the actions-list. The action-names are the keys and the actions themself are the values.

state_variables

Returns a dictionary with the state_variable name as keys and the StateVariable itself as value.

class fritzconnection.core.processor.Service

Class describing a service.

actions

Returns all known actions of this service as a dictionary. Action names are keys, the action objects are the values. Caches the dictionary once retrieved from _scpd.

load_scpd(address, port, timeout=None, session=None)

Loads the scpd data

state_variables

Returns all known stateVariables of this service as a dictionary. Names are keys, the stateVariables objects are the values. Caches the dictionary once retrieved from _scpd.

class fritzconnection.core.processor.ServiceList(storage)

Collection of Service instances for a device. The service instances are stored in the device.services attribute.

class fritzconnection.core.processor.ServiceStateTable(storage)

Collection of stateVariables.

class fritzconnection.core.processor.SpecVersion

Specification version from the schema device or service informations.

class fritzconnection.core.processor.StateVariable

Represents a stateVariable with the attributes name, dataType, defaultValue, allowedValueList and allowedValueRange.

class fritzconnection.core.processor.Storage(storage)

Baseclass for classes working with InstanceAttributeFactory.

class fritzconnection.core.processor.SystemVersion

Information about the Fritz!OS version of the Fritz!Box. Information is just provided by the ‘tr64desc.xml’ file.

info

Returns a tuple with all instance attributes ‘HW, Major, Minor, Patch, Buildnumber, Display’ in this order.

version

Returns system version as string like ‘7.10’ or None if system version is unknown.

class fritzconnection.core.processor.ValueSequencer(sequence_name)

Data descriptor storing a value (assigned as attribute value) in a given sequence.

fritzconnection.core.processor.process_node(obj, root)

Take an object and a root of nodes. The node.text of nodes with the same name as an instance-attribute of ‘obj’ are set as values for the corresponding instance-attribute. If the attribute is a callable, processing the node gets delegated to the callable (which in turn calls process_node).

fritzconnection.core.processor.processor(cls)

Class decorator to add the functionality of calling ‘process_node’ on invoking an instance as a callable.

soaper

Module handling the SOAP based communication with the router.

class fritzconnection.core.soaper.Soaper(address, port, user, password, timeout=None, session=None)

Class making the soap on its own to communicate with the FritzBox. Instead of ham, spam and eggs, it’s hopelessly addicted to soap.

For accessing the Fritz!Box the parameters address for the router ip, port, user, password and session are required. (These parameters will get set by FritzConnection,)

execute(service, action_name, arguments)

Builds the soap request and returns the response as dictionary. Numeric and boolean values are converted from strings to Python datatypes.

get_body(service, action_name, arguments)

Returns the body by template substitution.

parse_response(response, service, action_name)

Extracts all known parameters of the given action from the response and returns this as a dictionary with the out-parameter names as keys and the corresponding response as values. Will raise an ActionError on unknown action_name.

fritzconnection.core.soaper.boolean_convert(value)

Converts a string like ‘1’ or ‘0’ to a boolean value. Raise ValueError if it is something else than ‘1’ or ‘0’, because this violates the data_type according to the AVM documentation.

fritzconnection.core.soaper.datetime_convert(value)

Converts a string in ISO 8601 format to a datetime-object. Raise ValueError if value does not match ISO 8601.

fritzconnection.core.soaper.encode_boolean(value)

Returns 1 or 0 if the value is True or False. None gets interpreted as False. Otherwise the original value is returned.

fritzconnection.core.soaper.get_argument_value(root, argument_name)

Takes an etree-root object, which is a parsed soap-response from the Fritz!Box, and an argument_name, which corresponds to a node-name in the element-tree hierarchy. Returns the text-attribute of the node as a string. Raise an AttributeError in case that a node is not found.

fritzconnection.core.soaper.get_converted_value(data_type, value)

Try to convert the value from string to the given data_type. The data_type is used as key in the CONVERSION_TABLE dictionary. In case the data_type is unknown, the original value is returned.

fritzconnection.core.soaper.get_html_safe_value(value)

Returns an xml encoded value if it’s an encodable value. value can be of any type. If it is a boolean or None it gets converted to the integer 1 or 0. If it is a string the characters in the set &<>’” are converted to html-safe sequences. Any other datatype get’s returned as is.

fritzconnection.core.soaper.preprocess_arguments(arguments)

Takes a dictionary with arguments for a soap call and converts all values which are True, False or None to the according integers: 1, 0, 0. Returns a new dictionary with the processed values.

fritzconnection.core.soaper.raise_fritzconnection_error(response)

Handles all responses with status codes other than 200. Will raise the relevant FritzConnectionException with the error code and description if available

fritzconnection.core.soaper.uuid_convert(value)

Strips the leading ‘uuid:’ part from the string.