fritzconnection documentation

fritzconnection is a Python library to communicate with the AVM Fritz!Box by the TR-064 protocol. This allows to read status-information from the router, read and change configuration settings and state, monitor realtime phone calls and much more.

_images/fritzconnection-360x76.png

The available services are depending on the Fritz!Box model and the according system software. fritzconnection can list and access all available services and actions of a given router. Using fritzconnection is as easy as:

from fritzconnection import FritzConnection

fc = FritzConnection(address='192.168.178.1')
fc.reconnect()  # get a new external ip from the provider
print(fc)  # print router model information

fritzconnection provides a basic API call_action() that takes a service- and an action-name with optional arguments to send commands and receive data. In the example above the reconnect() method just wraps the call_action() method. A reconnection by means of call_action() would look like this:

fc = FritzConnection(address='192.168.178.1')
fc.call_action("WANIPConn1", "ForceTermination")

With the call_action() method every service/action combination documented by the AVM support-page (Apps/TR-064) can get executed. If the call to the FritzOS-API provides information call_action() returns a dictionary with the results.

fritzconnection comes with a library to make some common tasks easier. For a detailed overview refer to Getting Started and the documentation of the library.

Note

fritzconnection is neither related nor supported by AVM. Also AVM reserves the right to add, modify or remove features of their products at any time without notice.

Installation

The fritzconnection package is available on PyPi and installable by pip:

$ pip install fritzconnection

To enable the creation of QR-codes for wifi login, install fritzconnection with the qr-option:

$ pip install fritzconnection[qr]

New in version 1.9.0.

This will install an additional dependency segno. The segno-package can also get installed any time later:

$ pip install segno

It is good practice and highly recommended to do the installation in a virtual environment – either by means of venv or conda (comes with miniconda or anaconda).

fritzconnection requires Python >= 3.6

Getting Started

Technically the communication with the Fritz!Box works by UPnP using SCPD and SOAP for information transfer which is based on the TR-064 protocol. The TR-064 protocol uses the concept of services and actions. A service is a collection of actions for a given topic like WLAN-connections, registered hosts, phone calls, home-automation tasks and so on. And an action can have optional arguments for sending and receiving data.

The documentation about all services and actions is available from the vendor AVM (see Further Reading).

FritzConnection manages the inspection of a given Fritz!Box and can access all available services and corresponding actions. For some services it is required to provide the username and the password. The set of available services and actions may vary by router models and the installed Fritz!OS version.

The installation of fritzconnection (using pip) also installs some command line tools. The next sections will give an introduction to use one of the command line tools to inspect the Fritz!Box-API and how to write modules on top of fritzconnection.

Note

To use the TR-064 interface of the Fritz!Box, the settings for Allow access for applications and Transmit status information over UPnP in the Home Network -> Network -> Network Settings menu have to be activated.

Default IP-Address

To access the router in a local network, fritzconnection uses a default ip-address:

FRITZ_IP_ADDRESS = '169.254.1.1'

This ip-adress is a fallback-address common to every fritzbox-router, regardless of the individual configuration. If there are multiple devices in the local network, i.e. for building a Mesh, then it is necessary to provide the ip for the requested device, either at the command line with the option -i or the keyword-argument address for module usage. Otherwise it is not defined which device will respond.

Username and password

For some operations a username and/or a password is required. This can be given on the command line as parameters or, by using a module, as arguments. To not present these information in clear text or in the program code, username and password can get stored in the environment variables FRITZ_USERNAME and FRITZ_PASSWORD. If FritzConnection doesn’t get the username or password as arguments, then it will check for these environment variables and, if set, will use the corresponding values.

For Fritz!OS < 7.24 the username was optional. For newer versions an individual username is required. If a username is not provided, fritzconnection will try to find the username of the last logged in user from the Fritz!Box and will take this username (as AVM recommends for systems >= 7.24).

Command line inspection

Installing fritzconnection by pip will also install the command line tool fritzconnection to inspect the Fritz!Box-API. With the option -h this will show a help menu:

$ fritzconnection -h

usage: fritzconnection [-h] [-i [ADDRESS]] [--port [PORT]] [-u [USERNAME]]
                       [-p [PASSWORD]] [-e [ENCRYPT]] [-x] [-y]
                       [--cache-format [CACHE_FORMAT]]
                       [--cache-directory [CACHE_DIRECTORY]] [-r] [-R] [-s]
                       [-S SERVICEACTIONS] [-a SERVICEARGUMENTS]
                       [-A ACTIONARGUMENTS ACTIONARGUMENTS] [-c [COMPLETE]]

options:
  -h, --help            show this help message and exit
  -i [ADDRESS], --ip-address [ADDRESS]
                        Specify ip-address of the FritzBox to connect to.
                        Default: 169.254.1.1
  --port [PORT]         Port of the FritzBox to connect to. Default: 49000
  -u [USERNAME], --username [USERNAME]
                        Fritzbox authentication username
  -p [PASSWORD], --password [PASSWORD]
                        Fritzbox authentication password
  -e [ENCRYPT], --encrypt [ENCRYPT]
                        Flag: use secure connection (TLS)
  -x, --use-cache       Flag: use api cache
                        (speed-up subsequent instanciations)
  -y, --suppress-cache-verification
                        Flag: suppress cache verification, implies -x
  --cache-format [CACHE_FORMAT]
                        cache-file format: json|pickle (default: pickle)
  --cache-directory [CACHE_DIRECTORY]
                        path to cache directory (default: ~.fritzconnection)
  -r, --reconnect       Reconnect and get a new ip
  -R, --reboot          Reboot the router
  -s, --services        List all available services
  -S SERVICEACTIONS, --serviceactions SERVICEACTIONS
                        List actions for the given service: <service>
  -a SERVICEARGUMENTS, --servicearguments SERVICEARGUMENTS
                        List arguments for the actions of a specified
                        service:<service>.
  -A ACTIONARGUMENTS ACTIONARGUMENTS, --actionarguments
                        ACTIONARGUMENTS ACTIONARGUMENTS
                        List arguments for the given action of a specified
                        service: <service> <action>. Lists also direction
                        and data type of the arguments.
  -c [COMPLETE], --complete [COMPLETE]
                        List the complete api of the router

Services

With the option -s all available services are listed. If there are multiple fritz-devices in the network, it is undefined which one will respond. In this case the router-ip must be given with the option -i. The number of listed services can vary depending on the router model:

$ fritzconnection -s -i 192.168.178.1

fritzconnection v1.10.0
FRITZ!Box 7590 at http://192.168.178.1
FRITZ!OS: 7.29
Servicenames:
                    any1
                    WANCommonIFC1
                    WANDSLLinkC1
                    WANIPConn1
                    WANIPv6Firewall1
                    DeviceInfo1
                    DeviceConfig1
                    Layer3Forwarding1
                    ...
                    X_AVM-DE_OnTel1
                    X_AVM-DE_Dect1
                    ...
                    WLANConfiguration1
                    WLANConfiguration2
                    WLANConfiguration3
                    ...
                    WANPPPConnection1
                    WANIPConnection1

Services starting with X_AVM are not covered by the TR-064 standard but AVM-specific extensions.

All service-names are ending with a numeric value. In case a service is listed more than once the numeric value allows to select a specific one. Most prominent example is the WLANConfiguration service for accessing the 2.4 GHz and 5 GHz bands as well as the guest-network (given that the router-model provides these services).

Actions

Every service has a set of corresponding actions. The actions are listed by the flag -S with the servicename as parameter.

$ fritzconnection -i 192.168.178.1 -S WANIPConnection1

fritzconnection v1.10.0
FRITZ!Box 7590 at http://192.168.178.1
FRITZ!OS: 7.29


Servicename:        WANIPConnection1
Actionnames:
                    GetInfo
                    GetConnectionTypeInfo
                    SetConnectionType
                    GetStatusInfo
                    GetNATRSIPStatus
                    SetConnectionTrigger
                    ForceTermination
                    RequestConnection
                    GetGenericPortMappingEntry
                    GetSpecificPortMappingEntry
                    AddPortMapping
                    DeletePortMapping
                    GetExternalIPAddress
                    X_GetDNSServers
                    GetPortMappingNumberOfEntries
                    SetRouteProtocolRx
                    SetIdleDisconnectTime

Arguments

Action can have optional Arguments. A list of all available actions with their corresponding arguments is reported by the flag -a with the servicename as parameter:

$ fritzconnection -i 192.168.178.1 -a WANIPConnection1

This can return a lengthy output. So the arguments for a specific action of a given service can get listed with the option -A and the service- and actionname as arguments. For example the output for the service WANIPConnection1 and the action GetInfo will be:

$ fritzconnection -i 192.168.178.1 -A WANIPConnection1 GetInfo

fritzconnection v1.10.0
FRITZ!Box 7590 at http://192.168.178.1
FRITZ!OS: 7.29


Service:            WANIPConnection1
Action:             GetInfo
Parameters:

    Name                                  direction     data type

    NewEnable                                out ->     boolean
    NewConnectionStatus                      out ->     string
    NewPossibleConnectionTypes               out ->     string
    NewConnectionType                        out ->     string
    NewName                                  out ->     string
    NewUptime                                out ->     ui4
    NewLastConnectionError                   out ->     string
    NewRSIPAvailable                         out ->     boolean
    NewNATEnabled                            out ->     boolean
    NewExternalIPAddress                     out ->     string
    NewDNSServers                            out ->     string
    NewMACAddress                            out ->     string
    NewConnectionTrigger                     out ->     string
    NewRouteProtocolRx                       out ->     string
    NewDNSEnabled                            out ->     boolean
    NewDNSOverrideAllowed                    out ->     boolean

For every action all, arguments are listed with their name, direction and type. (Some arguments for other services may have the direction “in” for sending data to the router.)

The API of a FRITZ!Box depends on the model and the installed FritzOS version. To report the complete API of the router, the option -c can be used:

$ fritzconnection -i 192.168.178.1 -c > api.txt

In the above example the output is redirected to the file api.txt, because the output will be really huge.

Module usage

FritzConnection works by calling actions on services and can send and receive arguments. A simple example is to reconnect the router with the provider to get a new external ip:

from fritzconnection import FritzConnection

fc = FritzConnection()
fc.call_action('WANIPConnection1', 'ForceTermination')

At first an instance of FritzConnection must be created. There can be a short delay doing this, because fritzconnection has to do a lot of communication with the router to get the router-specific API.

Note

A FritzConnection instance can be reused for all further call_action calls without side-effects. For a single device an application needs just one instance. Because instanciation can be expensive (time consuming), having a single instance can save memory and speed up things.

The method call_action takes two required arguments: the service- and the action-name as strings. In case that a service is unknown (because of a typo or incompatible router model) fritzconnection will raise a FritzServiceError. If the service is known, but not the action, then a FritzActionError gets raised.

Let’s look at another example using an address 192.168.178.1 and calling an action GetInfo on a service WLANConfiguration that requires a password:

from fritzconnection import FritzConnection

fc = FritzConnection(address='192.168.178.1', password='the_password')
state = fc.call_action('WLANConfiguration1', 'GetInfo')

Calling the service WLANConfiguration1 without giving a password (or providing a wrong one) will raise a FritzConnectionException. Inspecting the API works without a password, but most of the other API-calls require one.

Note

Use environment variables to avoid hardcoding username and password.

In case that the servicename is given without a numeric extension (i.e ‘1’) fritzconnection adds the extension ‘1’ by default. So WLANConfiguration becomes WLANConfiguration1. The extension is required if there are multiple services with the same name. For backward compatibility servicenames like WLANConfiguration:1 are also accepted.

If a call to the Fritz-API provides a result, call_action() returns a dictionary: the keys are corresponding to the Argument name as given in the AVM-documentation and the values are the data provided from the router. In the above example state will be something like this:

{'NewAllowedCharsPSK': '0123456789ABCDEFabcdef',
 'NewAllowedCharsSSID': '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz '
                        '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~',
 'NewBSSID': '98:9B:CB:2B:93:B3',
 'NewBasicAuthenticationMode': 'None',
 'NewBasicEncryptionModes': 'None',
 'NewBeaconType': '11i',
 'NewChannel': 6,
 'NewEnable': True,
 'NewMACAddressControlEnabled': False,
 'NewMaxBitRate': 'Auto',
 'NewMaxCharsPSK': 64,
 'NewMaxCharsSSID': 32,
 'NewMinCharsPSK': 64,
 'NewMinCharsSSID': 1,
 'NewSSID': 'the WLAN name',
 'NewStandard': 'n',
 'NewStatus': 'Up'}

This information is showing a lot of details about the WLAN configuration. In this example the network is up and operating on channel 6. If the values are numeric or boolean, call_action() returns the matching Python datatype.

To activate or deactivate a network, the action SetEnable can get called. Inspection gives information about the required arguments:

$ fritzconnection -i 192.168.178.1 -A WLANConfiguration1 SetEnable

fritzconnection v1.10.0
FRITZ!Box 7590 at http://192.168.178.1
FRITZ!OS: 7.29


Service:            WLANConfiguration1
Action:             SetEnable
Parameters:

    Name                                  direction     data type

    NewEnable                             -> in         boolean

Here just one argument is listed for the in-direction. That means that this argument has to be send to the router. FritzConnection takes arguments as keyword-parameters for the call_action-method, where the keyword is set to the argument name (NewEnable in this case) :

from fritzconnection import FritzConnection

fc = FritzConnection(address='192.168.178.1', password='the_password')
fc.call_action('WLANConfiguration1', 'SetEnable', NewEnable=False)

This call will deactivate the network (beware: don’t deactivate a wireless network by not having a backup cable connection). As there are no arguments listed for the out-direction, call_action will return an empty dictionary.

In some cases it can happen, that there is a dash in an argument-name. Then this argument-name is not usable as a keyword-parameter. Therefore the call_action method also accepts a keyword-only argument with the name arguments that must be a dictionary with all input-parameters as key-value pairs (new in 1.0):

arguments = {'NewEnable': False}
fc.call_action('WLANConfiguration1', 'SetEnable', arguments=arguments)

If arguments is given, the values of all further keyword-parameters are ignored; you can use just one way to provide arguments.

Note

Prior to version 1.3 booleans must be given as numeric values 1 and 0. Since version 1.3 True and False can get used.

Example: Writing a module

Let’s write a simple module using fritzconnection to report the WLAN status of a router:

from itertools import count

from fritzconnection import FritzConnection
from fritzconnection.core.exceptions import FritzServiceError


def get_wlan_status(fc):
    status = []
    action = 'GetInfo'
    for n in count(1):
        service = f'WLANConfiguration{n}'
        try:
            result = fc.call_action(service, action)
        except FritzServiceError:
            break
        status.append((service, result))
    return status


def get_compact_wlan_status(fc):
    keys = ('NewSSID', 'NewChannel', 'NewStatus')
    return [
        (service, {key[3:]: status[key] for key in keys})
        for service, status in get_wlan_status(fc)
    ]


def main(address, password):
    fc = FritzConnection(address=address, password=password)
    for service, status in get_compact_wlan_status(fc):
        print(f'{service}: {status}')


if __name__ == '__main__':
    main(address='192.168.178.1', password='the_password')

Depending on the settings this will give an output like this:

WLANConfiguration1: {'SSID': 'the_wlan_name', 'Channel': 6, 'Status': 'Up'}
WLANConfiguration2: {'SSID': 'the_wlan_name', 'Channel': 100, 'Status': 'Up'}
WLANConfiguration3: {'SSID': 'FRITZ!Box Gastzugang', 'Channel': 6, 'Status': 'Disabled'}

The modules in the fritzconnection library (modules in the lib-folder) can be used as code-examples of how to use fritzconnection.

Exceptions

fritzconnection can raise several exceptions. For example using a service not provided by a specific router model will raise a FritzServiceError. This and all other errors are defined in fritzconnection.core.exceptions and can get imported from this module (i.e. the FritzServiceError):

from fritzconnection.core.exceptions import FritzServiceError

Exception Hierarchy:

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

All exceptions are inherited from FritzConnectionException. FritzServiceError and FritzActionError are superseding the older ServiceError and ActionError exceptions (still existing for backward compatibility). These exceptions are raised by calling unknown services and actions. All other exceptions are raised according to errors reported from the router (mirroring FritzOS errors). FritzLookUpError and FritzArrayIndexError are conceptually the same as Pythons KeyError or IndexError. Because of this they are also inherited from these Exceptions.

API-Cache

Stores the router api in an external file (new in 1.10). Loading the api-data from the router requires a lot of communication (many slow i/o) and can take up to several seconds. Reading the api-data from a single local file is much faster. The cache is activated by the use_cache argument:

fc = FritzConnection(address=192.168.178.1, use_cache=True)

At first run the api gets loaded from the router and stored in a cache-file. On the next runs the api gets loaded from the cache-file. There is a separate cache-file for every ip-address, allowing to cache the api for mutiple devices.

With the argument cache_directory the location of the cache files can be specified. Default is the ~.fritzconnection folder in the user home-directory on systems providing this default location.

Note

Default cache-format is pickle, which is compact, fast and can be considered safe as it is your own data. However, the json format is also supported. With the argument cache_format the format can set to json.

After loading the api from a cache-file, the data are verified to be still valid for the given router-model and the current installed software version. In case the cache is outdated, the api-data are reloaded from the router and the cache-file gets updated. The verifying step requires a request to the router, which can take some milliseconds. With the argument verify_cache=False verifying can turned off, loading the api even faster.

Warning

On deactivate verifying the cache data may be outdated if something has changed on the router side. (Simple solution: turn verifying on or delete the cache-file.) However, chances are that one didn’t mention it until strange things happen.

TLS-Encryption

fritzconnection supports encrypted communication with Fritz!Box devices by providing the option use_tls (new in 1.2):

fc = FritzConnection(address=192.168.178.1, password=<password>, use_tls=True)

The default setting for use_tls is False. For the command line tools encryption is provided by the flags -e or --encrypt. Encryption can be a useful option in a non-private LAN like a company-LAN.

Note

  • Using TLS will slow down the communication with the router. Especially getting a new FritzConnection instance will take longer by setting use_tls=True. Hint: reuse instances.
  • Since the router uses a self-signed certificate, currently certificate-verification is disabled.
  • In case the client communicates with the router by WLAN and WPA is enabled, the communication is already encrypted.
  • In case the client communicates by VPN there is also no need to add an additional encryption layer.

Environment-Variables

Some arguments given to FritzConnection can be stored in the environment. This has the advantage that arguments like user and password don’t have to be hardcoded and other defaults can be defined.

  • FRITZ_USERNAME provide the username
  • FRITZ_PASSWORD provide the password
  • FRITZ_USECACHE set to True or False (default: False)
  • FRITZ_CACHEFORMAT set to json or pickle (default: pickle)
  • FRITZ_CACHEDIRECTORY set to path (default: ~.fritzconnection)

The default-values are used if neither an argument is given to fritzconnection() nor an environment-variable is defined.

FritzConnection 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, use_cache=False, verify_cache=True, cache_directory=None, cache_format=None, 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.

The flag use_cache activates caching (default False). Caching can speed up instanciation significantly. The cached data are specific for the router ip, the router model and the installed FritzOS version. Multiple devices in the network can have separate cache-fies and can get used in parallel. By default the cache files are stored in the user home-directory in a .fritzconnection folder. To change this location use the parameter cache_directory providing a string or a pathlib.Path object. With cache_format two formats can specified for data serialization: json and pickle. These two values are available as constants FRITZ_CACHE_FORMAT_JSON and FRITZ_CACHE_FORMAT_PICKLE. Default is pickle. The flag verify_cache will enable cache verification (default is True). If set to False loading the api-data will be even faster, but the cache will not get renewed in case of FritzOS updates or a router change. All cache-settings can also configured in the environment: FRITZ_USECACHE (True|False), FRITZ_CACHEFORMAT (json|pickle) and FRITZ_CACHEDIRECTORY (a path).

New in version 1.10.

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 be provided as numeric values: 1, 0).

If the service_name does not end with a number-character (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.

device_description

Returns a string with the device description. This is a combination of the device model name and the installed software version.

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 available. reconnect_delay defines the maximum time interval 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
                |
                |--> FritzResourceError
                |
                |--> 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 non-existing 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.FritzResourceError

Exception raised if a description file like an igddesc-file is not provided by the router. This Exception is used internally and logged, but not reraised for the user of the library.

exception fritzconnection.core.exceptions.FritzSecurityError

Authorization error or wrong security context.

exception fritzconnection.core.exceptions.FritzServiceError

Exception raised by calling non-existing services.

Legathy Exceptions:

exception fritzconnection.core.exceptions.ActionError

Exception raised by calling non-existing actions. Legacy Exception. Use FritzActionError instead.

exception fritzconnection.core.exceptions.ServiceError

Exception raised by calling non-existing services. Legacy 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 sub-devices, 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.

deserialize(data)

Fills the collections self.descriptions and self.services with the content provided by data (from a json-source).

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.

serialize()

Returns a json-serializable list with Python-datastructures representing the known api of the device.

system_info

Returns a tuple with Hardwarecode, Major-, Minor-, Patch-Level, Buildnumber and Display-String, in this order. Return None if this information is 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 information is available.

logger

Logging module for the fritzconnection library. By default fritzconnection will emit all messages with a log-level of INFO and higher (WARNING, ERROR, CRITICAL).

The fritzconnection logger, defined as fritzlogger, is an instance of the logging.Logger class from the stdlib and can get accessed by:

>>> from fritzconnection.core.logger import fritzlogger

This module provides the additional functions activate_local_debug_mode and reset (see below) to activate a debug mode, suppressing handler-propagation, and to reset the logger to the initial state. To activate debug logging for fritzconnection call:

>>> from fritzconnection.core.logger import activate_local_debug_mode
>>> activate_local_debug_mode(handler=logging.StreamHandler())

In this debug mode fritzconnection will additionally log the data transfered between the library and the router and suppress logging-propagation to the parent-handlers. Here the StreamHandler will send all data to stderr. Because this can be a lot of data a FileHandler may be a better choice:

>>> activate_local_debug_mode(handler=logging.FileHandler(<the_file>))

To deactivate this mode call reset():

>>> from fritzconnection.core.logger import reset
>>> reset()

Beside this you can do everything with fritzlogger as with the logging.Logger, because fritzlogger is an instance of the latter.

fritzconnection.core.logger.activate_local_debug_mode(handler=None, propagate=False)

Activates all logging messages on debug level and don’t propagate to parent-handlers. If no handler is given the NullHandler will get set, avoiding a call of the lastResort-handler. If the given handler has no formatter, the fritzformatter gets set (which provides the logging.BASIC_FORMAT). If propagate is True, all debug information will also get sent to the parent-handlers. Keep in mind, that this can be a lot of data if the parent-handlers are enabled for debug-level records.

fritzconnection.core.logger.reset(keep_handlers=False, propagate=True)

Resets the logger to the initial state, i.e. after calling activate_local_debug_mode. All handlers will be removed, except keep_handlers is set to True.

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.

deserialize(data)

Deserialize the data back to an Action instance with a given name and defined Argument-instances.

serialize()

Return a dictionary with json serializable data: the name of the instance and a list of the serialized argument-instances in self._arguments.

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.

deserialize(data)

Sets the instance attributes according to data.

serialize()

Return serialized instance attributes as dictionary.

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, Buildnumber, 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 sub-nodes. Sub-nodes are the serviceList and the deviceList. The services provided by a device are collected in services. Sub-devices are collected in devices. All instance attributes are public for read only use.

deserialize(data)

Loads the data into the instance attributes. This is the reverse-function for serialize. No return value.

serialize()

Returns a dictionary with a subset of the instance attributes and a list of serialized services that can be transformed to json-format.

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

Host class providing every requested attribute

attributes

Provide all attributes of the instance as a dictionary with the attribute names as keys and the values converted to python datatypes.

class fritzconnection.core.processor.HostStorage(root)

Storage class collection all Item-nodes describing the hosts. The Item-nodes are converted to _Host instances.

hosts_attributes

Provide a list of dictionaries with the attributes of all hosts. The list is sorted with the lowest Index number first.

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 information about the Service Control Point Definitions for every Service. Every Service has one instance of this class for accessing the description of its 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 themselves 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.Serializer

Simple abstract Serializer base class. This class and should not get instanciated.

classmethod from_data(data)

Return a new instance with attributes initialized from data.

static get_sorted_dict(dictionary)

Takes a dictionary and returns another one with all keys in alphabetical order.

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.

deserialize(data)

Inverse method for serialize. Takes the data (a dictionary) and populates the instance attributes extracted by serialize.

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

Loads the scpd data

serialize()

Serialize the service instance attributes. Returns a dictionary with data that can be converted to json.

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

class fritzconnection.core.processor.StateVariable

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

deserialize(data)

Deserialize the data back to a former state of a StateVariable instance.

serialize()

Returns a dictionary with json serializable attribute data.

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.ValueRange
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 a 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 gets 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.

Library Modules

The library is a package with modules on top of FritzConnection to address specific tasks. The library-modules may not serve every need, but should be seen as examples on how to use FritzConnection and how to write more specialised modules.

Performance considerations:

Creating a FritzConnection instance will inspect the Fritz!Box API to get information about all available services and corresponding actions. As this is i/o based it’s generally slow. But once an instance is created, it can be reused for all tasks without side-effects. Therefore the library classes can optionally initialised with an existing FritzConnection instance, to not inspect the router-API multiple times:

from fritzconnection import FritzConnection
from fritzconnection.lib.fritzhomeauto import FritzHomeAutomation
from fritzconnection.lib.fritzwlan import FritzWLAN

fc = FritzConnection(address='192.168.178.1', password=<password>)

# library modules can be initialised with an existing FritzConnection instance
fw = FritzWLAN(fc)
print(fw.total_host_number)

fh = FritzHomeAutomation(fc)  # same here: use existing instance for initialisation
ain = '11657 0240192'  # assume the AIN of the switch is known
fh.set_switch(ain, on=True)

The next sections will describe the library modules in detail.

Inheritance from a common base class:

All library modules inherit from a common abstract base class that should not get instantiated:

Abstract base class for all library classes.

An internal module providing the AbstractLibraryBase class. This is an abstract class that should not get instantiated but should serve as a base class for library classes providing a common initialisation.

class fritzconnection.lib.fritzbase.AbstractLibraryBase(fc=None, *args, **kwargs)

Abstract base class for library classes. Implements the common initialisation. The first argument fc can be a FritzConnection instance. If this argument is given no further arguments are needed. If the argument fc is not given, all other arguments are forwarded to get a FritzConnection instance. These arguments have the same meaning as for FritzConnection.__init__(). Using positional arguments is strongly discouraged. Use keyword arguments instead.

modelname

The device modelname. Every library module derived from AbstractLibraryBase inherits this property.

FritzCall

Can dial phone numbers and allows access to history of phone calls: incoming, outgoing and missed ones. Usage from the command line:

$ fritzcall -i 192.168.178.1 -p <password> -t in -d 7
FRITZ!Box 7590 at ip 192.168.178.1
FRITZ!OS: 7.12

List of calls: in

  type   number                           date/time    duration

  ...
  more entries here
  ...

The flag -t indicates the type of calls to get listed: [in | out | missed]. It -t is not given, all calls are listed (up to 999). The flag -d is the number of days to look back for calls e.g. 1: calls from today and yesterday, 7: calls from the complete last week.

FritzCall can dial numbers by the method dial(). This method can also invoked by the command line with the flag -c or --call. Note: To make this work it is required to activate the dial-help service of the router first.

$ fritzcall -i 192.168.178.1 -p <password> -c <phonenumber>
dialing number: <phonenumber>
dialing done, please wait for signal.

For using a module, here is an example to list all missed calls:

from fritzconnection.lib.fritzcall import FritzCall

fc = FritzCall(address='192.168.178.1', password=<password>)
calls = fc.get_missed_calls()
for call in calls:
    print(call)

Calling back the last missed call is easy:

missed_number = calls[0].Caller  # Caller attribute holds the number
fc.dial(missed_number)  # now dial it

The module provides some constants that can be used with the get_calls() method as arguments for the calltype parameter:

ALL_CALL_TYPES = 0
RECEIVED_CALL_TYPE = 1
MISSED_CALL_TYPE = 2
OUT_CALL_TYPE = 3
ACTIVE_RECEIVED_CALL_TYPE = 9
REJECTED_CALL_TYPE = 10
ACTIVE_OUT_CALL_TYPE = 11

FritzCall API

Module to access lists of recent phone calls: incoming, outgoing and missed ones.

class fritzconnection.lib.fritzcall.FritzCall(*args, **kwargs)

Can dial phone numbers and gives access to lists of recent phone calls: incoming, outgoing and missed ones. All parameters are optional. If given, they have the following meaning: fc is an instance of FritzConnection, address the ip of the Fritz!Box, port the port to connect to, user the username, password the password, timeout a timeout as floating point number in seconds, use_tls a boolean indicating to use TLS (default False).

dial(number)

Dials the given number (number must be a string, as phone numbers are allowed to start with leading zeros). This method has no return value, but will raise an error reported from the Fritz!Box on failure. Note: The dial-help of the Fritz!Box must be activated to make this work.

get_calls(calltype=0, update=True, num=None, days=None)

Return a list of Call instances of type calltypes. If calltype is 0 all calls are listed. If update is True, all calls are reread from the router. num maximum number of entries in call list. days number of days to look back for calls e.g. 1: calls from today and yesterday, 7: calls from the complete last week.

get_missed_calls(update=True, num=None, days=None)

Return a list of Call instances of missed calls. If update is True, all calls are reread from the router. num maximum number of entries in call list. days number of days to look back for calls e.g. 1: calls from today and yesterday, 7: calls from the complete last week.

get_out_calls(update=True, num=None, days=None)

Return a list of Call instances of outgoing calls. If update is True, all calls are reread from the router. num maximum number of entries in call list. days number of days to look back for calls e.g. 1: calls from today and yesterday, 7: calls from the complete last week.

get_received_calls(update=True, num=None, days=None)

Return a list of Call instances of received calls. If update is True, all calls are reread from the router. num maximum number of entries in call list. days number of days to look back for calls e.g. 1: calls from today and yesterday, 7: calls from the complete last week.

class fritzconnection.lib.fritzcall.Call

Represents a call with the attributes provided by AVM. Instance attributes are Id, Type, Called, Caller, CallerNumber, CalledNumber, Name, Device, Port, Date, Duration and Count. The spelling represents the original xml-node names. Additionally, the following attributes can be accessed by lowercase names: id returning the Id as integer, type returning the Type as integer, date returning the Date as datetime-instance, duration returning the Duration as timedelta-instance.

FritzHomeAutomation

This library helps to access Homeautomation devices for reading current states and set the status of switches. Usage from the command line:

$ fritzhomeauto -i 192.168.178.1 -p <password>
FRITZ!Box 7590 at ip 192.168.178.1
FRITZ!OS: 7.12
Status of registered home-automation devices:

Device Name             AIN                 Power[W]   t[°C]   switch
FRITZ!DECT 210 #1       '11657 0240192'        0.000    23.5   on

The optional -v flag will give a verbose report about all device information, including the settings of radiator controls.

The -s flag can set the state of switches. This flag requires two parameters: the device identifier (AIN) and the state to set [on|off]. The following example will switch off the device with the identifier ‘11657 0240192’:

$ fritzhomeauto -i 192.168.178.1 -p <password> -s '11657 0240192' off

Example on how to get information about the known devices by using a module:

from fritzconnection.lib.fritzhomeauto import FritzHomeAutomation

fha = FritzHomeAutomation(address='192.168.178.1', password=<password>)
info = fha.device_information()

‘info’ is a list of dictionaries describing the devices:

[{'NewAIN': '11657 0240192',
  'NewDeviceId': 16,
  'NewDeviceName': 'FRITZ!DECT 210 #1',
   ...
  'NewHkrComfortVentilStatus': 'CLOSED',
   ...
  'NewMultimeterEnergy': 75,
  'NewMultimeterIsEnabled': 'ENABLED',
   ...
  'NewSwitchState': 'ON',
  'NewTemperatureCelsius': 265,
  'NewTemperatureIsEnabled': 'ENABLED',
  'NewTemperatureIsValid': 'VALID',
  'NewTemperatureOffset': 0}]

Depending on the device, different information will get reported. Information about a specific device can get obtained with the identifier NewAIN. The next example shows how to get the temperature in °C, taken the NewAIN from device_information() call:

ain = '11657 0240192'
fha.get_device_information_by_identifier(ain)['NewTemperatureCelsius'] * 0.1

It is also easy to toggle a switch (like a FRITZ!DECT 200/210 device):

fha.set_switch(ain, on=True)

This will turn the switch with the given identifier on or off depending whether the parameter ‘on’ is True or False. Use-cases can be to set a switch depending on the temperature or daytime.

FritzHomeAutomation API

Module to access home-automation devices

class fritzconnection.lib.fritzhomeauto.FritzHomeAutomation(fc=None, *args, **kwargs)

Interface for fritzbox homeauto service. All parameters are optional. If given, they have the following meaning: fc is an instance of FritzConnection, address the ip of the Fritz!Box, port the port to connect to, user the username, password the password, timeout a timeout as floating point number in seconds, use_tls a boolean indicating to use TLS (default False).

device_information()

Returns a list of dictionaries for all known homeauto-devices.

device_informations()

Deprecated since version 1.9.0: Use device_information() instead.

get_device_information_by_identifier(identifier)

Returns a dictionary with all device arguments according to the AVM documentation (x_homeauto) with the given identifier (AIN). Raise an FritzArgumentError on invalid identifier.

get_device_information_by_index(index)

Return a dictionary with all device arguments according to the AVM documentation (x_homeauto) at the given internal index. Raise a FritzArrayIndexError (subclass of IndexError) on invalid index values.

get_info

Return a dictionary with a single key-value pair: ‘NewAllowedCharsAIN’: string with all allowed chars for state variable AIN

set_switch(identifier, on=True)

Sets a switch state on devices providing a switch state. ‘identifier’ must be the AIN of the device. ‘on’ is a boolean whether the switch should be on (True) or off (False). This method has no return value. Raise a FritzArgumentError on invalid identifier.

FritzHosts

Utility module for FritzConnection to access and control the known hosts. The command line tool allows to list the current ip, name, the MAC address and the active-state for all registered hosts:

$ fritzhosts -i 192.168.178.1 -p <password>

FritzConnection v1.0
FritzHosts for FRITZ!Box 7590 at ip 192.168.178.1
FRITZ!OS: 7.12:

List of registered hosts:

  n: ip               name                         mac                 status

  1: 192.168.178.36   DE-20HAR90XXXXX              00:E1:8C:9B:DF:98   -
  2: 192.168.178.33   HUAWEI-P20-Pro-xxxxxxxxxx    B4:CD:27:37:78:E4   -
     ...
 20: 192.168.178.24   fritz.repeater               C6:25:06:83:64:C5   active
 21: 192.168.178.25   fritzbox4020                 C8:0E:14:B8:71:DD   active

Example how to use FritzHost in a module to get the same output:

from fritzconnection.lib.fritzhosts import FritzHosts

fh = FritzHosts(address='192.168.178.1', password='password')
hosts = fh.get_hosts_info()
for index, host in enumerate(hosts, start=1):
    status = 'active' if host['status'] else  '-'
    ip = host['ip'] if host['ip'] else '-'
    mac = host['mac'] if host['mac'] else '-'
    hn = host['name']
    print(f'{index:>3}: {ip:<16} {hn:<28} {mac:<17}   {status}')

FritzHosts API

Module to access and control the known hosts.

class fritzconnection.lib.fritzhosts.FritzHosts(fc=None, *args, **kwargs)

Class to access the registered hosts. All parameters are optional. If given, they have the following meaning: fc is an instance of FritzConnection, address the ip of the Fritz!Box, port the port to connect to, user the username, password the password, timeout a timeout as floating point number in seconds, use_tls a boolean indicating to use TLS (default False).

get_active_hosts()

Returns a list of dicts with information about the active devices. The dict-keys are: ‘ip’, ‘name’, ‘mac’, ‘status’, ‘interface_type’, ‘address_source’, ‘lease_time_remaining’

get_generic_host_entries()

Generator returning a dictionary for every host as provided by get_generic_host_entry(). (See also get_hosts_info() that returns a list of dictionaries with different key-names.)

get_generic_host_entry(index)

Returns a dictionary with information about a device internally registered by the position index. Index-positions are zero-based.

get_host_name(mac_address)

Returns a String with the host_name of the device with the given mac_address

get_host_status(mac_address)

Provides status information about the device with the given mac_address. Returns True if the device is active or False otherwise. Returns None if the device is not known or the mac_address is invalid.

get_hosts_attributes()

Returns a list of dictionaries with information about all hosts.

This differs from get_hosts_info as the information origins from a different FritzOS call: the information about the current host stats is provided by a Lua script returning an xml-stream. get_hosts_attributes triggers the Lua script and converts the returned data in a list of dictionaries describing the known hosts.

New in version 1.10.

get_hosts_info()

Returns a list of dicts with information about the known hosts. The dict-keys are: ‘ip’, ‘name’, ‘mac’, ‘status’, ‘interface_type’, ‘address_source’, ‘lease_time_remaining’.

get_mesh_topology(raw=False)

Returns information about the mesh network topology. If raw is False the topology gets returned as a dictionary with a list of nodes. If raw is True the data are returned as text in json format. Default is False.

get_specific_host_entry(mac_address)

Returns a dictionary with information about a device addressed by the MAC-address.

get_specific_host_entry_by_ip(ip)

Returns a dictionary with information about a device addressed by the ip-address. Provides additional information about connection speed and system-updates for AVM devices.

get_wakeonlan_status(mac_address)

Returns a boolean whether wake on LAN signal gets send to the device with the given mac_address in case of a remote access.

host_numbers

The number of known hosts.

run_host_update(mac_address)

Triggers the host with the given mac_address to run a system update. The method returns immediately, but for the device it takes some time to do the OS update. All vendor warnings about running a system update apply, like not turning power off during a system update. So run this command with caution.

set_host_name(mac_address, name)

Sets the hostname of the device with the given mac_address to the new name.

set_wakeonlan_status(mac_address, status=False)

Sets whether a wake on LAN signal should get send send to the device with the given mac_address in case of a remote access. status is a boolean, default value is False. This method has no return value.

FritzPhonebook

Allows read-only access to the phonebooks stored in the router (a Fritz!Box router can have more than a single phonebook). The command line interface allows inspection of the phonebooks and search for name and numbers. The flag -a will list the content of all phonebooks:

$ fritzphonebook -i 192.168.178.1 -p <password> -a

FritzConnection v1.1
FritzPhonebook for FRITZ!Box 7590 at ip 192.168.178.1
FRITZ!OS: 7.12

Content of phonebook: business
good customer                 0123456789
another good customer         0987654321
...
more numbers here
...

With the flags --name and --number like --name "good customer" and --number 0987654321 all phonebooks will get searched for the according entry.

Here is an example to list the entries of all phonebooks by means of a module:

from fritzconnection.lib.fritzphonebook import FritzPhonebook

fp = FritzPhonebook(address='192.168.178.1', password='password')
for phonebook_id in fp.phonebook_ids:
    contacts = fp.get_all_names(phonebook_id)
    for name, numbers in contacts.items():
        print(name, numbers)

FritzPhonebook API

Module for read-only access to the contents of the Fritz!Box phonebooks.

class fritzconnection.lib.fritzphonebook.FritzPhonebook(*args, **kwargs)

Interface to access the Fritz!Box phonebooks. All parameters are optional. If given, they have the following meaning: fc is an instance of FritzConnection, address the ip of the Fritz!Box, port the port to connect to, user the username, password the password, timeout a timeout as floating point number in seconds, use_tls a boolean indicating to use TLS (default False).

get_all_name_numbers(id)

Returns all entries from the phonebook with the given id as a list of tuples. The first item of every tuple is the contact name and the second item is the list of numbers for this contact.

get_all_names(id)

Get a dictionary with all names and their phone numbers for the phonebook with id. If a name is given more than once in a single phonebook, the last entry will overwrite the previous entries. (That’s because the names are the keys in the dictionary returned from this method. In this case use the method ‘get_all_name_numbers()’ to get all entries as a list of tuples.)

get_all_numbers(id)

Get a dictionary with all phone numbers and the according names for the phonebook with id. This method is based on the method ‘get_all_names()’ and has the same limitations.

list_phonebooks

List of integers identifying the phonebooks. This property is defined as phonebook_ids and as list_phonebooks for backward compatibility. The property list_phonebooks is deprecated and may get removed in the future.

lookup_names(id, number)

Look up the names of the contacts with phone number number in the phonebook with id. Will raise a KeyError if the number is unknown.

lookup_numbers(id, name)

Look up the phone numbers of contact name in the phonebook with id. Returns a list of numbers. Will raise a KeyError if the name is unknown.

phonebook_ids

List of integers identifying the phonebooks. This property is defined as phonebook_ids and as list_phonebooks for backward compatibility. The property list_phonebooks is deprecated and may get removed in the future.

phonebook_info(id)

Get the name, url and an optional extra id of the phonebook with integer id. Returns a dictionary with the keys name, url and xid.

FritzStatus

Reports information about the link-status to the service provider. Usage from the command line:

$ fritzstatus -i 192.168.178.1 -p password

fritzconnection v1.8.0
FRITZ!Box 7590 at http://192.168.178.1
FRITZ!OS: 7.29

FritzStatus:

    is linked             : True
    is connected          : True
    external ip (v4)      : 46.xx.xx.xx
    external ip (v6)      : 2003:ee:xx::
    internal ipv6-prefix  : 2003:ee:xx::
    uptime                : 321:41:06
    bytes send            : 6845677353
    bytes received        : 123858580962
    max. bit rate         : ('44.3 MBit/s', '113.2 MBit/s')

For periodic calls, an instance of FritzStatus (resp. FritzConnection) should only created once:

import time
from fritzconnection.lib.fritzstatus import FritzStatus

fc = FritzStatus(address='192.168.178.1', password='password')
while True:
    print(fc.str_transmission_rate)
    time.sleep(2)

This will report an output like this:

('992.0 bytes', '23.6 KB')
('0.0 bytes', '0.0 bytes')
('1.3 KB', '25.4 KB')
('3.7 KB', '36.4 KB')
('21.2 KB', '104.6 KB')

FritzStatus API

Module to read status-information from an AVM FritzBox.

class fritzconnection.lib.fritzstatus.DefaultConnectionService(prefix, connection_service, postfix)
connection_service

Alias for field number 1

postfix

Alias for field number 2

prefix

Alias for field number 0

class fritzconnection.lib.fritzstatus.FritzStatus(fc=None, *args, **kwargs)

Class for requesting status-information: up, down, ip, activity (bytes per second send/received). All parameters are optional. If given, they have the following meaning: fc is an instance of FritzConnection, address the ip of the Fritz!Box, port the port to connect to, user the username, password the password, timeout a timeout as floating point number in seconds, use_tls a boolean indicating to use TLS (default False).

attenuation

Tuple of attenuation. First item is upstream, second item downstream.

bytes_received

Total number of received bytes.

bytes_sent

Total number of sent bytes.

connection_service

The extracted connection_service from get_default_connection_service().

connection_uptime

Connection uptime in seconds.

device_has_mesh_support

True if the device supports mesh, otherwise False.

device_uptime

Device uptime in seconds.

external_ip

The external v4 ip-address.

external_ipv6

The external v6 ip-address.

external_ipv6_info

Returns the ipv6 external address information as a dictionary with the keys: NewExternalIPv6Address out -> string NewPrefixLength out -> ui1 NewValidLifetime out -> ui4 NewPreferedLifetime out -> ui4

get_default_connection_service()

Returns a namedtuple of type DefaultConnectionService: prefix -> str device_connection -> str (like “WANPPPConnection”) postfix -> str

get_device_info()

Returns an ArgumentNamespace with the attributes:

manufacturer_name, manufacturer_oui, model_name, description, product_class, serial_number, software_version, hardware_version, spec_version, provisioning_code, up_time, device_log

New in version 1.10.

get_monitor_data(sync_group_index=0)

Returns a dictionary with realtime data about the current up- and downstream rates.

has_wan_enabled

True if wan is enabled otherwise False.

has_wan_support

True is the device supports a WAN interface. False otherwise.

ipv6_prefix

The internal v6 prefix.

ipv6_prefix_info

Returns the ipv6 prefix information as a dictionary with the keys: NewIPv6Prefix out -> string NewPrefixLength out -> ui1 NewValidLifetime out -> ui4 NewPreferedLifetime out -> ui4

is_connected

A boolean whether the FritzBox has established an internet-connection.

is_linked

A boolean whether the FritzBox is physically linked to the provider.

max_bit_rate

Tuple with the maximum upstream- and downstream-rate of the given connection. The rate is given in bits/sec.

max_byte_rate

Same as max_bit_rate but rate is given in bytes/sec.

max_linked_bit_rate

Tuple with the maximum upstream- and downstream-rate of the physical link. The rate is given in bits/sec.

noise_margin

Tuple of noise margin. First item is upstream, second item downstream.

reconnect()

Makes a reconnection with a new external ip.

str_attenuation

Human-readable attenuation in dB. Value is a tuple, first item is upstream, second item downstream.

str_max_bit_rate

Human-readable maximum of the upstream- and downstream-rate in bits/sec, as given by the provider. Value is a tuple, first item is upstream, second item is downstream.

str_max_linked_bit_rate

Human-readable maximum of the physical upstream- and downstream-rate in bits/sec. Value is a tuple, first item is upstream, second item is downstream.

str_noise_margin

Human-readable noise margin in dB. Value is a tuple, first item is upstream, second item downstream.

str_transmission_rate

Tuple of human-readable transmission rate in bytes. First item is upstream, second item downstream.

str_uptime

Connection uptime in human-readable format.

transmission_rate

The upstream and downstream values as a tuple in bytes per second. Use this for periodical calling.

update_available

The new version number (as a string) if an update is available or an empty string if no update is avilable.

upnp_enabled

Returns a boolean whether upnp is enabled or raises a FritzServiceError in case the service is not available.

uptime

Deprecated since version 1.9.0: Use connection_uptime() instead.

FritzWLAN

Module for accessing basic WLANConfiguration settings. The command line tool gives an overview of active devices:

$ fritzwlan -i 192.168.178.1 -p <password>
FRITZ!Box 7590 at ip 192.168.178.1
FRITZ!OS: 7.12
Hosts registered at WLANConfiguration1:
WLAN name: the wlan name
channel  : 6
index  active                 mac                ip  signal   speed
    0       1   E2:25:06:83:64:C5    192.168.178.24      51      86

Hosts registered at WLANConfiguration2:
WLAN name: the wlan name
channel  : 36
index  active                 mac                ip  signal   speed
    0       1   A0:99:9B:10:09:81    192.168.178.28      91    1300

Example to get the total number of known WLAN-devices for all WLANConfigurations:

from fritzconnection.lib.fritzwlan import FritzWLAN

fw = FritzWLAN(address='192.168.178.1', password='password')
print(fw.total_host_number)

Example: device tracking

A common use-case for wlan-information is device tracking. The following is a basic example how to do this. The example will poll the mac-addresses of all active devices. (For this a fixed tracking duration with a short poll-period is used. This may not be appropriate for real world programs.)

import time
import datetime
import itertools

from fritzconnection.lib.fritzwlan import FritzWLAN
from fritzconnection.core.exceptions import FritzServiceError


ADDRESS = '192.168.178.1'
PASSWORD = 'the_password'  # should not be hardcoded for real usage

# short time periods for demonstration purposes
TRACKING_DURATION = 20
TRACKING_PERIOD = 5


def get_active_macs(fwlan):
    """
    Gets a FritzWLAN instance and returns a list of mac addresses
    from the active devices
    """
    active_macs = list()
    # iterate over all wlans:
    for n in itertools.count(1):
        fwlan.service = n
        try:
            hosts_info = fwlan.get_hosts_info()
        except FritzServiceError:
            break
        else:
            active_macs.extend(entry['mac'] for entry in hosts_info)
    return active_macs


def report_devices(fwlan):
    active_macs = get_active_macs(fwlan)
    # decide here what to do with this information:
    # print the mac addresses
    for mac in active_macs:
        print(mac)
    print()  # empty line for readability


def track_devices(tracking_duration, tracking_period):
    # instanciate FritzWLAN just once for reusage
    fwlan = FritzWLAN(address=ADDRESS, password=PASSWORD)
    stop = datetime.datetime.now() + tracking_duration
    while datetime.datetime.now() < stop:
        report_devices(fwlan)
        time.sleep(tracking_period)


def main():
    tracking_duration = datetime.timedelta(seconds=TRACKING_DURATION)
    track_devices(tracking_duration, TRACKING_PERIOD)
    print('done.')


if __name__ == '__main__':
    main()

Example: activate a guest network

This only works with devices providing more than one access point and additionally a guest network. If the latter is not provided the class FritzGuestWLAN will just handle the access point with highest internal service id, as this is typically the access point for guests.

The following example enables the guest access point and if a password is given will set this as the new password. If the guest access point is already active just a new password is set:

from fritzconnection.lib.fritzwlan import FritzGuestWLAN

def enable_guest_access_point(new_password=None):
    guest_wlan = FritzGuestWLAN(address="192.168.178.1", user="user", password="password")
    if not guest_wlan.is_enabled:
        guest_wlan.enable()
    if new_password:
        guest_wlan.set_password(new_password)

enable_guest_access_point(new_password="new_strong_password")

Example: create a QR-code for wifi access

This is a common task for guest networks: give visitors easy access to a public network by providing the access data as a QR-code for scanning. The following example will create a QR-code and stores this code as a svg- and a png-file:

from fritzconnection.lib.fritzwlan import FritzGuestWLAN

def write_qr_code_to_file(filename, kind="svg")
    guest_wlan = FritzGuestWLAN(address="192.168.178.1", user="user", password="password")
    qr_code = guest_wlan.get_wifi_qr_code(kind=kind)
    with open(filename, "wb") as fobj:
        fobj.write(qr_code.read())

write_qr_code_to_file("qr_code.svg", kind="svg")
# do the same as png-file:
write_qr_code_to_file("qr_code.png", kind="png")

Keep in mind to set the file-suffix to the format of the created QR-code. This is the argument kind taking “svg”, “png” and “pdf” as allowed values. Default value is “svg”.

The call of the get_wifi_qr_code() method returns a file-like object. Instead of writing the content to a file, the return value can get forwarded to any function accepting a file-like object.

New in version 1.9.0.

Note

If the segno-package is not available, calling the method will raise an AttributeError. Refer to Installation to install this requirement.

FritzWLAN API

Module to get information about WLAN devices.

class fritzconnection.lib.fritzwlan.FritzGuestWLAN(*args, **kwargs)

Inherits from FritzWLAN and provides all the same methods but for the guest network. On devices not providing a guest network this class will not fail, but handle the wlan network with the highest internal service number (which is by default the guest network on guest network providing devices).

All parameters are optional. If given, they have the following meaning: fc is an instance of FritzConnection, address the ip of the Fritz!Box, port the port to connect to, user the username, password the password, timeout a timeout as floating point number in seconds, use_tls a boolean indicating to use TLS (default False).

class fritzconnection.lib.fritzwlan.FritzWLAN(*args, service=1, **kwargs)

Class to list all known wlan devices. All parameters are optional. If given, they have the following meaning: fc is an instance of FritzConnection, address the ip of the Fritz!Box, port the port to connect to, user the username, password the password, timeout a timeout as floating point number in seconds, use_tls a boolean indicating to use TLS (default False). The service parameter specifies the configuration in use. Typically this is 1 for 2.4 GHz, 2 for 5 GHz and 3 for a guest network. This can vary depending on the router model and change with future standards.

alternative_channels

Alternative channels (as string)

beacontype

Represents the beacontype for the network as string. At time of writing (OS 7.29) possible values are: None, 11i, WPAand11i, 11iandWPA3 for the private WiFi-security settings and None, 11i, 11iandWPA3, OWETrans for the guest network.

channel

The WLAN channel in use

channel_info()

Return a dictionary with the keys NewChannel and NewPossibleChannels indicating the active channel and alternative ones.

channel_infos()

Deprecated since version 1.9.0: Use channel_info() instead.

disable()

Disables the associated network.

enable()

Enables the associated network.

get_generic_host_entry(index)

Return a dictionary with information about the device internally stored at the position ‘index’.

get_hosts_info()

Returns a list of dictionaries with information about the known hosts. The dict-keys are: ‘service’, ‘index’, ‘status’, ‘mac’, ‘ip’, ‘signal’, ‘speed’

get_info()

Returns a dictionary with general internal information about the current wlan network according to the AVM documentation.

get_password()

Returns the current password of the associated wlan.

get_specific_host_entry(mac_address)

Return a dictionary with information about the device with the given ‘mac_address’.

host_number

Number of registered wlan devices for the active WLANConfiguration.

is_enabled

Returns whether the guest network is enabled.

set_channel(number)

Set a new channel. number must be a valid channel number for the active WLAN. (Valid numbers are listed by alternative_channels.)

set_password(password=None, length=12)

Sets a new password for the associated wlan. If no password is given a new one is created with the given length (the new password can get read with a subsequent call of get_password). Also creates a new pre-shared key.

ssid

The WLAN SSID

total_host_number

Total NewAssociatedDeviceIndexNumber of registered wlan devices for all WLANConfigurations.

fritzconnection.lib.fritzwlan.get_beacon_security(instance, security)

Returns the beacon-security as a string based on the security argument. Possible return values are ‘nopass’ and ‘WPA’. If the security is None or an empty string, the function tries to find the proper security setting (‘nopass’|’WPA’). If security is neither None nor an empty string, the value is returned as is.

This function is not intended to get called directly.

New in version 1.10.

fritzconnection.lib.fritzwlan.get_wifi_qr_code(instance, kind='svg', security=None, hidden=False, scale=4)

Returns a file-like object providing a bytestring representing a qr-code for wlan access. instance is a FritzWLAN or FritzGuestWLAN instance. kind describes the type of the qr-code. Supported types are: ‘svg’, ‘png’ and ‘pdf’. Default is ‘svg’.

This function is not intended to get called directly. Instead it is available as a method on FritzWLAN instances (as well as on subclasses like FritzGuestWLAN) if the third party package segno is installed.

Consider guest_wlan is a FritzGuestWLAN instance, then the following code will return a file like object with the qr-code image data in png-format:

stream = guest_wlan.get_wifi_qr_code(kind='png')

The stream can get used anywhere, where a file like object is expected, i.e. writing the content to a file (Note: the suffix must match the kind of the qr-code format):

with open('qr_code.png', 'wb') as fobj:
    fobj.write(stream.read())

If segno is not installed the call will trigger an AttributeError when called on an instance and a NameError when called directly.

New in version 1.9.0.

The parameters security and hidden allow to forward these informations to the segno library. security is None or a string like WPA. hidden is a boolean value indicating the visibility of the network .

New in version 1.9.1.

If the security is None (default) the beacontype of the network is used to set the WLAN-Type accordingly. If the value of security is something else, this value gets used.

scale defines the size of the produced qr-code. Default value is 4.

New in version 1.10.

Library-Tools

Helper classes and functions for library-development.

fritzbase

Abstract base class for all library classes.

An internal module providing the AbstractLibraryBase class. This is an abstract class that should not get instantiated but should serve as a base class for library classes providing a common initialisation.

class fritzconnection.lib.fritzbase.AbstractLibraryBase(fc=None, *args, **kwargs)

Abstract base class for library classes. Implements the common initialisation. The first argument fc can be a FritzConnection instance. If this argument is given no further arguments are needed. If the argument fc is not given, all other arguments are forwarded to get a FritzConnection instance. These arguments have the same meaning as for FritzConnection.__init__(). Using positional arguments is strongly discouraged. Use keyword arguments instead.

modelname

The device modelname. Every library module derived from AbstractLibraryBase inherits this property.

fritztools

Some helpers for the library.

class fritzconnection.lib.fritztools.ArgumentNamespace(source, mapping=None, extract=None, suppress_new=True)

Namespace object that also behaves like a dictionary, but is not iterable.

Usecase is as a wrapper for the dictionary returned from FritzConnection.call_action(). This dictionary has keys named “arguments” as described by the AVM documentation, combined with values as the corresponding return values. Instances of ArgumentNamespace can get used to extract a subset of this dictionary and transfer the Argument-names to more readable ones. For example consider that fc is a FritzConnection instance. Then the following call:

>>> result = fc.call_action("DeviceInfo1", "GetInfo")

will return a dictionary like:

{'NewManufacturerName': 'AVM',
 'NewManufacturerOUI': '00040E',
 'NewModelName': 'FRITZ!Box 7590',
 'NewDescription': 'FRITZ!Box 7590 154.07.29',
 'NewProductClass': 'AVMFB7590',
 'NewSerialNumber': '989BCB2xxxxx',
 'NewSoftwareVersion': '154.07.29',
 'NewHardwareVersion': 'FRITZ!Box 7590',
 'NewSpecVersion': '1.0',
 'NewProvisioningCode': '000.044.004.000',
 'NewUpTime': 9516949,
 'NewDeviceLog': 'long string here ...'}

In case that just the model name and serial number are of interest, and should have better names, first define a mapping:

mapping = {
    "modelname": "NewModelName",
    "serialnumber": "NewSerialNumber"
}

and use this mapping with the dictionary result to create an ArgumentNamespace instance:

>>> info = ArgumentNamespace(result, mapping)

The info instance can now get used like a namespace object and like a dictionary:

>>> info.serialnumber
'989BCB2xxxxx'

>>> info['modelname']
'FRITZ!Box 7590'

If no mapping is given, then ArgumentNamespace will consume the provided dictionary converting all keys from “MixedCase” style to “snake_case” (PEP 8) and removes the leading “new” originating from the AVM “New” prefix for all keys:

>>> info = ArgumentNamespace(result)
>>> info.up_time
9516949

Setting the flag suppress_new to False will keep the prefix:

>>> info = ArgumentNamespace(result, suppress_new=False)
>>> info.new_up_time
9516949

To just extract a subset of result provide a sequence of key-names for the extract argument:

>>> extract = "NewSerialNumber", "NewModelName"
>>> info = ArgumentNamespace(result, extract=extract)
>>> info.serial_number
'989BCB2xxxxx'
>>> info.model_name
'FRITZ!Box 7590'

If both arguments mapping and extract are given, mapping has precedence and extract gets ignored.

New in version 1.10.

static rewrite_argument(name, suppress_new=True)

Rewrite name from MixedCase to snake_case (PEP 8). So i.e. “MixedCase” gets converted to “mixed_case”. AVM standard argument names starting with “New” like “NewMixedCase” will get converted to “new_mixed_case”. If suppress_new is True (the default) the “new”-prefix will get removed, so “NewMixedCased” will get converted to “mixed_case”. Consecutive upper-case characters are handled as a group: “ManufacturerOUI” -> “manufacturer_oui”.

New in version 1.10.

fritzconnection.lib.fritztools.byte_formatter(value)

Gets a large integer als value and returns a tuple with the value as float and the matching dimension as string, i.e. >>> byte_formatter(242981246) (242.981246, ‘MB’) Expects positive integer as input. Negative numbers are interpreted as positive numbers. values < 1 are interpreted as 0.

fritzconnection.lib.fritztools.format_dB(num)

Returns a human-readable string of dB. The value is divided by 10 to get first decimal digit

fritzconnection.lib.fritztools.format_num(num, unit='bytes')

Returns a human-readable string of a byte-value. If ‘num’ is bits, set unit=’bits’.

fritzconnection.lib.fritztools.format_rate(num, unit='bytes')

Returns a human-readable string of a byte/bits per second. If ‘num’ is bits, set unit=’bits’.

Call Monitoring

The fritzmonitor-module is a core module of fritzconnection to provide real-time information about incoming and outgoing phone-calls. This functionality is based on a separate socket-connection to the router and does not communicate by TR-064.

FritzMonitor provides a queue of type queue.Queue for accessing CallMonitor events. To check the events send from the router, fritzconnection comes with a fritzmonitor command line tool. The next block shows a typical session:

$ fritzmonitor -i 192.168.178.1

fritzconnection v1.4.0
start fritzmonitor on address: 192.168.178.1
settings for socket-timeout: 10 [sec]
settings for healthcheck-timeout: 10 [sec]
(to stop press ^C)

28.11.20 15:17:43;RING;2;<calling number>;<called number>;SIP0;
28.11.20 15:17:47;CONNECT;2;4;<calling number>;
28.11.20 15:17:50;DISCONNECT;2;4;
...

The events are of type string in a format defined by AVM. The option -i specifies the ip address of the router. The option -h provides a help menu.

Here is a basic example how to use FritzMonitor in a module to pull events:

import queue
from fritzconnection.core.fritzmonitor import FritzMonitor

def process_events(monitor, event_queue, healthcheck_interval=10):
    while True:
        try:
            event = event_queue.get(timeout=healthcheck_interval)
        except queue.Empty:
            # check health:
            if not monitor.is_alive:
                raise OSError("Error: fritzmonitor connection failed")
        else:
            # do event processing here:
            print(event)

def main():
    """Entry point: example to use FritzMonitor.
    """
    try:
        # as a context manager FritzMonitor will shut down the monitor thread
        with FritzMonitor(address='192.168.178.1') as monitor:
            event_queue = monitor.start()
            process_events(monitor, event_queue)
    except (OSError, KeyboardInterrupt) as err:
        print(err)

if __name__ == "__main__":
    main()

The FritzMonitor API is documented here.

Note

To do call monitoring, the CallMonitor service of the Fritz!Box has to be activated. This can be done with any registered phone by typing the following codes:

activate: #96*5*
deactivate: #96*4*

Further Reading

Information about the TR-064 protocol with services and actions as well as AVM-specific extensions are listed at the AVM support-page (this specific webpage about programming interfaces is mainly in german language, but the detailed documentation-files (PDFs) are in english).

Everything that can be done by means of this API - used by fritzconnection - is documented there.

Version History

1.10.3 - 2022-09-08

  • upper limit for dependency pinning removed to support installation on more recent environments.

1.10.2 - 2022-09-04

  • bugfix: missing self in FritzStatus.get_device_info() (introduced in 1.10.0) (#165)
  • dependencies pinned for requests not supporting Python 3.6 since version 2.28.0 and for segno (which still works with EOL versions).

1.10.1 - 2022-09-01

  • bugfix: cli argument forwarding (introduced in 1.10.0) (#164)
  • enhancement: cli flag -y to suppress cache-verification now implies -x (use cache)

1.10.0 - 2022-08-24

  • FritzConnection
    • API cache integration added: for faster start up times the router API can optional get saved in a cache-file. This can save up to several seconds run-time on instanciation.
  • FritzHosts:
    • New method get_hosts_attributes providing a list of dictionaries with the attribues of all known hosts (#134)
  • FritzStatus:
    • New property update_available (#156)
    • New property connection_service
    • New property has_wan_support (#162)
    • New property has_wan_enabled (#147)
    • New property upnp_enabled() (#153)
    • New property device_has_mesh_support (#146)
    • New method get_default_connection_service (#146)
    • New method get_device_info() (#155)
  • FritzWLAN:
    • QR-code now supports encryption information for the described network by auto-detecting the security settings (which is optional but set to default) (#139)
  • Testing:
    • requires opencv to check qr-codes
    • covering Python 3.11
  • New class ArgumentNamespace added in fritzconnection.lib.fritztools for convenient handling of dictionaries returned from FritzConnection.call_action() calls.
  • Better error message in case application access is disabled (#142)

1.9.1 - 2022-01-17

  • bugfix: AttributeError in FritzHomeAutomation.device_information() removed - bug introduced in 1.9.0 (#138)
  • enhancement: FritzWLAN.get_wifi_qr_code() forwards the optional security and hidden parameters to segno. (#139)

1.9.0 - 2022-01-05

  • FritzWLAN:
    • New method get_wifi_qr_code() for QR-code creation for wifi-access (#133). Requires segno as dependency. See installation for details. The method is also inherited by FritzGuestWLAN.
    • New method channel_info() (#131)
  • FritzHomeAutomation: New method device_information() (#131)
  • Deprecations:
    • fritzconnection.lib.fritzhomeauto.FritzHomeAutomation.device_informations()
    • fritzconnection.lib.fritzstatus.FritzStatus.uptime()
    • fritzconnection.lib.fritzwlan.FritzWLAN.channel_infos()
  • Documentation improvements

1.8.0 - 2021-12-27

  • FritzConnection: new command line option -R to reboot the system
  • FritzHosts:
    • New method get_generic_host_entries returning a generator to iterate over all entries as reported by the method get_generic_host_entry.
    • The methods get_active_hosts and get_hosts_info provide additional host attributes (#127)
  • Refactoring of the logging module fritzconnection.core.logger (introduced in 1.7.0). Now emitting messages from INFO-level and up by default.
  • Connection errors with the router raised from the underlying urllib3 library are caught and raised again as FritzConnectionException preserving the connection error information (#128)

1.7.2 - 2021-11-14

  • bugfix: logger deactivated by default (#123)

1.7.1 - 2021-10-10

  • Tests extended for Python 3.10

1.7.0 - 2021-09-25

  • New FritzWLAN-methods:
    • enable and disable to enable and disable a wlan network.
    • get_password and set_password to get the current password or set a new one for a wlan network.
  • New FritzGuestWLAN library class.
  • New FritzConnection method reboot.
  • New logging module fritzconnection.core.logger.

1.6.0 - 2021-07-24

  • New arguments for FritzConnection: pool_connections and pool_maxsize to adapt the default urllib3 settings (used by requests). (#114).
  • New properties FritzStatus.device_uptime and FritzStatus.connection_uptime`; the latter a replacement for FritzStatus.uptime – still existing as an alias. (#104)
  • bugfix: html-escape arguments in case that special characters are allowed by the protocol. (#115)
  • bugfix: FritzStatus.bytes_sent will return the 32 bit value from older Fritz!Box models. (#110)
  • bugfix: raise FritzActionError on accessing the mesh topology information from a device not having accesss to this information. (#107)
  • adding code-of-conduct and contributing files to the repository.

1.5.0 - 2021-05-01

  • Compatibility with Fritz!OS 7.24 and newer: takes the last logged in username as default in case that a username is not provided.

1.4.2 - 2021-03-06

  • bugfix: byte_formatter may return wrong numbers on values < 1 and has raised math domain error on values == 0. (bug introduced with version 1.4.1) (#87)

1.4.1 - 2021-02-13

  • bugfix: FritzStatus library now returns a 32 bit value for bytes_received for older Fritz!OS versions not providing the newer 64 bit information instead of raising an exception. (bug introduced with version 1.3.0) (#82)
  • change: Output of bitrate changed to log10 based calculation (#45, #52)

1.4.0 - 2020-11-29

  • New core module fritzmonitor for reporting realtime phone call events (#76).
  • Library class FritzStatus with additional properties: attenuation, str_attenuation, noise_margin and str_noise_margin (#69)
  • Library class FritzHost with additional method get_host_name (#75)
  • Namespace prefix for xml-arguments removed (#66)
  • Test extended for Python 3.9 (#73)

1.3.4 - 2020-08-06

  • bugfix: session ignored timeout settings (#63)

1.3.3 - 2020-07-17

  • bugfix: soap-xml encoding corrected (#59)
  • bugfix: soap-xml tag-attribute separation fixed (#60)

1.3.2 - 2020-07-11

  • bugfix: converting arguments returned from soap calls (#58)

1.3.1 - 2020-06-28

  • authorisation now supports ‘myfritz.net’ access (#48)
  • internal refactorings

1.3.0 - 2020-06-21

  • Library class FritzStatus reports the sent and received bytes now as 64 bit integers and provides easy access to realtime monitor data.
  • Library class FritzHost provides more methods to access devices, including wake on LAN and net topology information.
  • Library class FritzPhonebook has a new method get_all_name_numbers() to fix a bug of get_all_names() reporting just one name in case that a phonebook holds multiple entries of the same name.
  • Boolean arguments send to the router as 1 and 0 can also be given as the Python datatypes True and False (#30).
  • Flag -c added to fritzconnection cli interface to report the complete api.
  • pip installation no longer includes the tests (#39).
  • pypi classifier changed to Development Status :: 5 - Production/Stable

0.8.5 - 2020-06-01

  • updates the pinned lxml-dependency from version 4.3.4 to 4.5.1
  • last version to support Python 2.7, <=3.5 (no more updates)

1.2.1 - 2020-03-21

  • Library modules handling complex datatypes (urls) can now reuse fritzconnection sessions.

1.2.0 - 2020-01-07

  • TLS for router communication added.
  • Command line tools take the new option -e for encrypted connection.
  • Sessions added for faster connections (significant speed up for TLS)
  • Functional tests added addressing a physical router. Skipped if no router present.
  • Bugfix for rendering the documentation of the FritzPhonebook-API (bug introduced in 1.1.1)

1.1.1 - 2019-12-29

  • Bugfix in FritzConnection default parameters preventing the usage of library modules (bug introduced in 1.1.0)
  • Minor bugfix in FritzPhonebook storing image-urls

1.1.0 - 2019-12-28

  • FritzConnection takes a new optional parameter timeout limiting the time waiting for a router response.
  • FritzPhonebook module rewritten for Python 3 without lxml-dependency and added again to the library (missing in version 1.0).
  • Library module FritzStatus adapted to Python 3.

1.0.1 - 2019-12-21

  • Bugfix in fritzinspection for command line based inspection of the Fritz!Box API.

1.0.0 - 2019-12-20

  • Requires Python 3.6 or newer. The 0.8.x release is the last version supporting Python 2.7 and Python 3 up to 3.5
  • The lxml library is no longer a dependency.
  • New project layout. Library modules are now located in the new lib package.
  • Rewrite of the description parser.
  • Errors reported by the Fritz!Box are now raising specific exceptions.

0.8.4 - 2019-12-16

  • Bugfix in connection.reconnect(). This bug has been introduced with version 0.8.0. For versions 0.8.0 to 0.8.3 ‘reconnect’ requires a password because of a changed service call.
  • Documentation updated.

0.8.3 - 2019-09-09

  • Fix broken test (new in version 0.8.0)
  • Minor code enhancements

0.8.2 - 2019-08-27

  • Unified version numbering of the modules.
  • ServiceError, ActionError and AuthorizationError are also importable from the package.
  • Some code cleanup.

Changes in the development process: .hgignore removed and .gitignore added, changes in setup.py, readme changed to restructured text.

As Atlassian has announced to drop support for mercurial on bitbucket und will remove the according repositories (in June 2020), development of fritzconnection has converted from hg to git and the repository has been transfered to github. Unfortunately the issue- and discussion-history will be lost this way (even by keeping the new git-repository at bitbucket).

0.8.1 - 2019-08-24

FritzStatus: bugfix requiring a password in combination with fritzconnection >= 0.8.0

FritzStatus: added the external_ipv6 attribute

FritzStatus: added the max_linked_bit_rate attribute for the physical rate. Also added the str_max_linked_bit_rate attribute for a more readable output. (password must be provided for these infomations)

FritzConnection: added the AuthorizationError exception.

0.8.0 - 2019-08-20

Bugfix how servicenames are extracted from the xml-description files. However, the api has not changed.

The requirements are now fixed for lxml (4.3.4) and requests (2.22.0) as these versions are still supporting python 2.7

0.7.1 - 0.7.3 ~ 2019-07-24

Bugfixes, no new features or other changes.

0.7.0 - 2019-07-21

FritzConnection does now check for the environment variables FRITZ_USER and FRITZ_PASSWORD in case that neither user nor password are given.

FritzStatus now accepts user and password as keyword-parameters. Keep in mind, that FritzBoxes may return different information about the status depending whether these are gathered with or without a password.

0.6.5 - 2017-07-12

There is a new attribute package_version:

>>> import fritzconnection
>>> fritzconnection.package_version
0.6.5

Because every module of the fritzconnection-package has it’s own version, version-history of the package gets confusing over time. From now on every change of the content of the package is indicated by the the package-version. Every unchanged module keeps it’s version. So i.e. the recent package-version is 0.6.5 but the fritzconnection-module is still in version 0.6 cause nothing has changed in this module since then.

0.6

FritzConnection now uses long qualified names as servicename, i.e. WLANConfiguration:1 or WLANConfiguration:2. So these servicenames can now be used to call actions on different services with the same name:

>>> connection = FritzConnection()
>>> info = connection.call_action('WANIPConnection:2', 'GetInfo')

For backward compatibility servicename-extensions like ‘:2’ can be omitted on calling ‘call_action’. In this case FritzConnection will use the extension ‘:1’ as default.

On calling unknown services or actions in both cases KeyErrors has been raised. Calling an unknown service (or one unaccessible without a password) will now raise a ServiceError. Calling an invalid action on a service will raise an ActionError. Both Exceptions are Subclasses from the new FritzConnectionException. The Exception classes can get imported from fritzconnection:

>>> from fritzconnection import ServiceError, ActionError

< 0.6

Continuous update of features and bugfixes since first import at 2013-05-01 on bitbucket using mercurial.

Authors

Additional authors having contributed to this project:

Since moving from bitbucket to github, an up to date list of contributors is listed here: https://github.com/kbr/fritzconnection/graphs/contributors.

License

As an open source and non profit software fritzconnection has the liberal MIT-License (“Expat License”). So basically, you can do whatever you want as long as you include the original copyright and license notice in any copy of the software/source.

In short that means:

  • You are allowed to download, install and use the software for free, even for commercial products.
  • You are entirely at your own risk.

Here is the long version:

Copyright (c) 2012-2022 Klaus Bremer

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.