fritzconnection documentation

fritzconnection is a Python library to communicate with the AVM Fritz!Box by the TR-064 protocol. This allows to read status-informations from the box and to read and change configuration settings and state. Also realtime phone call monitoring is provided.

_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 box. 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 informations

The reconnect() method wraps the call_action() method. With the call_action() method every service/action combination documented by the AVM support-page (Apps/TR-064) can get executed. A reconnection by means of call_action() would look like this:

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

For more information refer to Introduction.

fritzconnection comes with a library to make some common tasks easier and to serve as examples how to use fritzconnection. The library also provides a fritzmonitor module for accessing the call-monitor interface of the Fritz!Box to get realtime informations about incoming and outgoing phone calls:

from fritzconnection import FritzMonitor

fm = FritzMonitor(address='192.168.178.1')
event_queue = fm.start()  # start monitoring
# event_queue is queue.Queue instance, do event handling here ...
fm.stop()  # stop monitoring

This is described in more detail in Call Monitoring.

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

This installation will also install the required package requests. If this does not work (for whatever reason) requests can also installed by pip:

$ pip install requests

It is not necessary, but good practice, to do the installation in a virtual environment – either by means of venv or conda (comes with miniconda or anaconda).

fritzconnection runs with Python 3.6 or newer (older versions are not supported).

Introduction

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

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 user-password for the box. The set of available services and actions may vary by router models and the installed Fritz!OS version.

The installation of fritzconnection (using pip) will also install a command line tool for the Fritz!Box api-inspection. The next sections will give an introduction to this command line tool 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.

Internal defaults

To access the router in a local network, fritzconnection use some default values:

FRITZ_IP_ADDRESS = '169.254.1.1'
FRITZ_TCP_PORT = 49000
FRITZ_TLS_PORT = 49443
FRITZ_USERNAME = 'dslf-config'

The ip-adress is a fallback-value common to every fritzbox-router, regardless of the individual configuration. In case of more than a single router in the local network (i.e. multiple Fritz!Boxes building a Mesh or connected by LAN building multiple WLAN access-points) the option -i (for the command line) or the keyword-parameter address (module usage) is required to address the router, otherwise it is not defined which one of the devices will respond.

Usernames and passwords

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 informations in clear text, username and password can get stored in the environment variables FRITZ_USERNAME and FRITZ_PASSWORD. FritzConnection will check for these environment variables first and, if set, will use the corresponding values.

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

FritzConnection v1.3.0
usage: fritzconnection [-h] [-i [ADDRESS]] [--port [PORT]] [-u [USERNAME]]
                       [-p [PASSWORD]] [-r] [-s] [-S SERVICEACTIONS]
                       [-a SERVICEARGUMENTS]
                       [-A ACTIONARGUMENTS ACTIONARGUMENTS] [-c [COMPLETE]]
                       [-e [ENCRYPT]]

Fritz!Box API Inspection:

optional arguments:
  -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
  -r, --reconnect       Reconnect and get a new ip
  -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
  -e [ENCRYPT], --encrypt [ENCRYPT]
                        use secure connection

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 an additional parameter for the router ip must be given with the -i option (newer router models use 192.168.178.1 as factory setting). The number of services can vary depending on the router model:

$ fritzconnection -s -i 192.168.178.1

FritzConnection v1.3.0
FRITZ!Box 7590 at http://192.168.178.1
FRITZ!OS: 7.12
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 are 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).

Services and 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.3.0
FRITZ!Box 7590 at http://192.168.178.1
FRITZ!OS: 7.12

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

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 single action of a given service can also 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.3.0
FRITZ!Box 7590 at http://192.168.178.1
FRITZ!OS: 7.12

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 FRITZ!OS 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 a file, because the output will be really huge.

Module usage

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

from fritzconnection import FritzConnection

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

At first an instance of FritzConnection must be created (#1). There can be a short delay doing this because fritzconnection has to wait for the response of the router to inspect the router-specific api.

The method call_action takes two required arguments: the service- and the action-name as strings. In case that a service or action 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.

Note

Once a FritzConnection instance has been created, it can be reused for all future call_action calls. Because instantiation is expensive (doing a lot of i/o for API inspection) this can increase performance significantly.

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 API-calls require a 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.

The result of calling the call_action method is always a dictionary with the argument names as keys. The values are the output-arguments from the Fritz!Box. 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'}

These informations are showing a lot of details about the WLAN configuration. In this example the network is up and operating on channel 6.

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

$ $ fritzconnection -i 192.168.178.1 -A WLANConfiguration1 SetEnable

FritzConnection v1.3.0
FRITZ!Box 7590 at http://192.168.178.1
FRITZ!OS: 7.12

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:

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 (keep in mind: 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 without any out-argument keys.

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 since 1.0). Arguments like NewEnable can accept Python booleans instead of the numeric values [0, 1] (new since 1.3).

This is convenient for calls with multiple arguments for the in-direction, or for argument names not suitable as keyword parameters (like having a dash in the name) :

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

Note

Even if the router reports that a service exists, calling actions on this service may raise FritzActionErrors in case that the service is not in use.

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
                |
                |--> 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, that are 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. FritzLookUpError and FritzArrayIndexError are conceptually the same as a Python KeyError or IndexError. Because of this they are also inherited from these Exceptions.

TLS-Encryption

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

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 flag -e or --encrypt.

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.
  • The Fritz!Box backend allows to download the self signed certificate and to upload your own certificates: “Internet->Freigaben->FRITZ!Box-Dienste”.

Call Monitoring

The fritzmonitor-module is a core module of fritzconnection to provide real-time informations 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 also documented in Structure and API.

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*

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 informations about all availabe 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. 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 initialisÌation
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:

class fritzconnection.lib.fritzbase.AbstractLibraryBase(fc=None, address=None, port=None, user=None, password=None, timeout=None, use_tls=False)

Abstract base class for library classes. Implements the common initialisation. 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).

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 provides to 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 listet. 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

Can access Homeautomation devices to read the 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 informations, 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 informations 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_informations()

‘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 informations will get reported. Informations 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_informations() 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. Usecases can be to set a switch depending on the temperature or daytime.

FritzHomeAutomation API

Modul to access home-automation devices

class fritzconnection.lib.fritzhomeauto.FritzHomeAutomation(fc=None, address=None, port=None, user=None, password=None, timeout=None, use_tls=False)

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_informations()

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

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

Modul to access and control the known hosts.

class fritzconnection.lib.fritzhosts.FritzHosts(fc=None, address=None, port=None, user=None, password=None, timeout=None, use_tls=False)

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’

get_generic_host_entry(index)

Returns a dictionary with informations 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_info()

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

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 informations about a device addressed by the MAC-address.

get_specific_host_entry_by_ip(ip)

Returns a dictionary with informations 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 take 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 informations about the link-status to the service provider. Usage from the command line:

$ fritzstatus -i 192.168.178.1 -p password

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

    is linked           : True
    is connected        : True
    external ip (v4)    : 79.255.xxx.xxx
    external ip (v6)    : 2003:ee:xx:x:x
    uptime              : 190:30:56
    bytes send          : 2097630835
    bytes received      : 2866333236
    max. bit rate       : ('9.9 MBit/s', '50.5 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

Modul to read status-informations from an AVM FritzBox.

class fritzconnection.lib.fritzstatus.FritzStatus(fc=None, address=None, port=None, user=None, password=None, timeout=None, use_tls=False)

Class for requesting status-informations: 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 send bytes.

external_ip

The external v4 ip-address.

external_ipv6

The external v6 ip-address.

external_ipv6_info

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

get_monitor_data(sync_group_index=0)

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

ipv6_prefix

The internal v6 prefix.

ipv6_prefix_info

Returns the ipv6 prefix informations 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 maximun 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 maximun 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

Uptime in seconds and in human readable format.

transmission_rate

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

uptime

Uptime in seconds.

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 usecase for wlan-informations 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()

FritzWLAN API

Module to get informations about WLAN devices.

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)

channel

The WLAN channel in use

channel_infos()

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

get_generic_host_entry(index)

Return a dictionary with informations 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_specific_host_entry(mac_address)

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

host_number

Number of registered wlan devices for the active WLANConfiguration.

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

ssid

The WLAN SSID

total_host_number

Total NewAssociatedDeviceIndexumber of registered wlan devices for all WLANConfigurations.

Structure and API

fritzconnection is structured into subpackages:

fritzconnection --|-- cli
                  |-- core --|-- devices
                  |          |-- exceptions
                  |          |-- fritzconnection
                  |          |-- fritzmonitor
                  |          |-- 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)

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)

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

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

modelname

Returns the modelname of the router.

static normalize_name(name)

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

reconnect()

Terminate the connection and reconnects with a new ip.

services

Dictionary of service instances. Keys are the service names.

static set_protocol(url, use_tls)

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

system_version

Returns system version if known, otherwise None.

fritzmonitor

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

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

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

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

add(data)

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

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

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

has_monitor_thread

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

is_alive

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

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

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

stop()

Stop the current running monitor_thread.

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

delay generator with increasing sleep-times.

exceptions

Exceptions can get imported by:

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

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

Exception Hierarchy:

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

Module defining fritzconnection specific exceptions.

exception fritzconnection.core.exceptions.FritzConnectionException

Base Exception for communication errors with the Fritz!Box

exception fritzconnection.core.exceptions.FritzActionError

Exception raised by calling nonexisting actions.

exception fritzconnection.core.exceptions.FritzActionFailedError

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

exception fritzconnection.core.exceptions.FritzArgumentCharacterError

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

exception fritzconnection.core.exceptions.FritzArgumentError

Exception raised by invalid arguments.

exception fritzconnection.core.exceptions.FritzArgumentStringToLongError

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

exception fritzconnection.core.exceptions.FritzArgumentStringToShortError

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

exception fritzconnection.core.exceptions.FritzArgumentValueError

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

exception fritzconnection.core.exceptions.FritzArrayIndexError

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

exception fritzconnection.core.exceptions.FritzInternalError

Exception raised by panic in the box.

exception fritzconnection.core.exceptions.FritzLookUpError

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

exception fritzconnection.core.exceptions.FritzOutOfMemoryError

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

exception fritzconnection.core.exceptions.FritzSecurityError

Authorization error or wrong security context.

exception fritzconnection.core.exceptions.FritzServiceError

Exception raised by calling nonexisting services.

Legathy Exceptions:

exception fritzconnection.core.exceptions.ActionError

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

exception fritzconnection.core.exceptions.ServiceError

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

Internal API

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

devices

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

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

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

add_description(source)

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

load_service_descriptions(address, port)

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

modelname

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

scan()

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

system_info

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

system_version

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

processor

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

class fritzconnection.core.processor.Action

Every Action has a name and a list of arguments.

arguments

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

class fritzconnection.core.processor.ActionList(storage)

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

class fritzconnection.core.processor.Argument

An argument with name, direction and relatedStateVariable attributes.

class fritzconnection.core.processor.ArgumentList(storage)

Collects the arguments for an action.

class fritzconnection.core.processor.Description(root)

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

services

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

system_buildnumber

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

system_display

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

system_info

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

system_version

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

class fritzconnection.core.processor.Device

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

class fritzconnection.core.processor.DeviceList(storage)

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

class fritzconnection.core.processor.InstanceAttributeFactory(cls)

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

class fritzconnection.core.processor.Scpd(root)

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

actions

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

state_variables

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

class fritzconnection.core.processor.Service

Class describing a service.

actions

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

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

Loads the scpd data

state_variables

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

class fritzconnection.core.processor.ServiceList(storage)

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

class fritzconnection.core.processor.ServiceStateTable(storage)

Collection of stateVariables.

class fritzconnection.core.processor.SpecVersion

Specification version from the schema device or service informations.

class fritzconnection.core.processor.StateVariable

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

class fritzconnection.core.processor.Storage(storage)

Baseclass for classes working with InstanceAttributeFactory.

class fritzconnection.core.processor.SystemVersion

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

info

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

version

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

class fritzconnection.core.processor.ValueSequencer(sequence_name)

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

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

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

fritzconnection.core.processor.processor(cls)

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

soaper

Module handling the SOAP based communication with the router.

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

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

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

execute(service, action_name, arguments)

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

get_body(service, action_name, arguments)

Returns the body by template substitution.

parse_response(response, service, action_name)

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

fritzconnection.core.soaper.boolean_convert(value)

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

fritzconnection.core.soaper.datetime_convert(value)

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

fritzconnection.core.soaper.encode_boolean(value)

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

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

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

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

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

fritzconnection.core.soaper.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.

Further Reading

Informations about the TR-064 protocol with services and actions as well as AVM-specific extensions are listet at the AVM support-page (at present in german language only).

Version History

1.4.2

  • 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

  • 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

  • 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

  • bugfix: session ignored timeout settings (#63)

1.3.3

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

1.3.2

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

1.3.1

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

1.3.0

  • 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 informations.
  • 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

1.2.1

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

1.2.0

  • 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

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

1.1

  • 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

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

1.0

  • 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.5

  • updates the pinned lxml-dependency from version 4.3.4 to 4.5.1

0.8.4

  • 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

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

0.8.2

  • 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

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

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

Bugfixes, no new features or other changes.

0.7.0

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 informations about the status depending whether these are gathered with or without a password.

0.6.5

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

Authors

Additional authors having contributed to this project:

Since moving from bitbucket to github, an up to date list of contributers 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-now 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.