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

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

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). pool_connections and pool_maxsize are to override the urllib3 default settings.

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, pool_connections=10, pool_maxsize=10)

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, pool_connections=10, pool_maxsize=10)

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, pool_connections=10, pool_maxsize=10)

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 sent bytes.

connection_uptime

Connection uptime in seconds.

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

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.

uptime

Connection uptime in seconds. Alias for self.connection_uptime for backward compatibility.

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.