### Install fritzconnection Source: https://github.com/kbr/fritzconnection/blob/master/README.md Installs the fritzconnection library using pip. The optional '[qr]' extra installs the 'segno' package for QR-code creation, useful for Wi-Fi login. ```bash pip install fritzconnection or pip install fritzconnection[qr] ``` -------------------------------- ### Accessing Network Topology with FritzMeshTopology Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md This example demonstrates how to initialize a FritzConnection, create a FritzMeshTopology instance, load the network data, and print the resulting topology overview. ```python from fritzconnection import FritzConnection from fritzconnection.lib.fritztopology import FritzMeshTopology # assume user and password are read from the environment: fc = FritzConnection(address="192.168.178.1") # create a topology-instance fm = FritzMeshTopology(fc=fc) # read the topology data (can take some time) fm.load_topology() # print the instance: print(fm) ``` -------------------------------- ### Manual FritzMonitor Lifecycle Management Source: https://context7.com/kbr/fritzconnection/llms.txt Demonstrates how to manually start and stop a FritzMonitor instance to track router events without using a context manager. This approach requires explicit calls to start() and stop() to manage the background thread. ```python monitor = FritzMonitor(address="192.168.178.1", port=1012, timeout=10, encoding="utf-8") event_queue = monitor.start() print(f"Monitor thread running: {monitor.is_alive}") print(f"Has monitor thread: {monitor.has_monitor_thread}") # ... process events ... monitor.stop() ``` -------------------------------- ### Monitor Phone Calls Programmatically with Python Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/call_monitoring.md This example demonstrates how to use the FritzMonitor class as a context manager to start a monitoring thread. It processes events from a queue and includes a health check mechanism to ensure the connection remains active. ```python 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: if not monitor.is_alive: raise OSError("Error: fritzmonitor connection failed") else: print(event) def main(): try: 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() ``` -------------------------------- ### Get Smart Home Device Temperatures via HTTP API with fritzconnection Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md This example demonstrates how to retrieve the temperature of smart home devices configured as switches using the HTTP API of a FRITZ!Box router via the fritzconnection library. It first fetches a list of switch identifiers and then queries the temperature for each. The output is a float representing the temperature in Celsius, adjusted by a factor of 0.1. ```python from fritzconnection.core.fritzconnection import FritzConnection fc = FritzConnection(address="192.168.178.1", use_cache=True) result = fc.call_http("getswitchlist") switch_identifiers = result["content"].split(",") for identifier in switch_identifiers: result = fc.call_http("gettemperature", identifier.strip()) temperature = float(result["content"]) * 0.1 print(temperature) ``` -------------------------------- ### Initialize FritzConnection and Call TR-064 Action Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md Demonstrates how to initialize the FritzConnection class and use the call_action method to interact with the Fritz!Box via the TR-064 API. This example shows how to reconnect the router. ```python fc = FritzConnection(address="192.168.178.1") fc.call_action("WANIPConn1", "ForceTermination", arguments={}) ``` -------------------------------- ### Guest WLAN QR Code Generation Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Example of how to generate a QR code for Wi-Fi access using the FritzGuestWLAN class. This allows easy sharing of network credentials. ```APIDOC ## Create QR Code for Wi-Fi Access ### Description Generates a QR code for Wi-Fi access, which can be saved as SVG or PNG. This is useful for providing guest network access. ### Method `FritzGuestWLAN.get_wifi_qr_code()` ### Parameters - **kind** (str) - Optional - The format of the QR code. Allowed values: "svg", "png", "pdf". Defaults to "svg". ### Request Example ```python from fritzconnection.lib.fritzwlan import FritzGuestWLAN guest_wlan = FritzGuestWLAN(address="192.168.178.1", user="user", password="password") qr_code_svg = guest_wlan.get_wifi_qr_code(kind="svg") with open("qr_code.svg", "wb") as fobj: fobj.write(qr_code_svg.read()) qr_code_png = guest_wlan.get_wifi_qr_code(kind="png") with open("qr_code.png", "wb") as fobj: fobj.write(qr_code_png.read()) ``` ### Response Returns a file-like object containing the QR code data. ### Error Handling - Raises `AttributeError` if the `segno` package is not installed. ``` -------------------------------- ### Control Fritz!Box Switches and Get Device Info (Python) Source: https://context7.com/kbr/fritzconnection/llms.txt Demonstrates how to call HTTP methods on a FritzConnection object to retrieve switch lists, device temperatures, switch states, and device statistics. It also shows how to set switch states (on, off, toggle). ```Python from fritzconnection import FritzConnection fc = FritzConnection() # Get list of all switch devices (returns comma-separated AINs) result = fc.call_http("getswitchlist") print(f"Content-type: {result['content-type']}") # text/plain print(f"Encoding: {result['encoding']}") # utf-8 switch_identifiers = result["content"].split(",") print(f"Switch AINs: {switch_identifiers}") # Get temperature from a device for identifier in switch_identifiers: result = fc.call_http("gettemperature", identifier.strip()) temperature = float(result["content"]) * 0.1 # Convert to Celsius print(f"Device {identifier}: {temperature}°C") # Get switch state (returns "1" for on, "0" for off) result = fc.call_http("getswitchstate", "12345 6789012") is_on = result["content"] == "1" # Set switch state fc.call_http("setswitchon", "12345 6789012") # Turn on fc.call_http("setswitchoff", "12345 6789012") # Turn off fc.call_http("setswitchtoggle", "12345 6789012") # Toggle # Get device statistics (returns XML data) result = fc.call_http("getbasicdevicestats", "12345 6789012") xml_content = result["content"] # XML string with temperature/energy history ``` -------------------------------- ### POST /fritzmonitor/start Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md Starts the monitor thread to listen for incoming, outgoing, and finished call events from the Fritz!Box. ```APIDOC ## POST /fritzmonitor/start ### Description Starts the monitor thread to receive real-time phone call events. Requires the CallMonitor service to be activated on the Fritz!Box (via #96*5*). ### Method POST ### Endpoint /fritzmonitor/start ### Parameters #### Query Parameters - **queue_size** (int) - Optional - Number of events the queue can store (default: 256). - **block_on_filled_queue** (bool) - Optional - Whether to block when the queue is full (default: False). - **reconnect_delay** (float) - Optional - Max time in seconds between reconnection attempts (default: 60). - **reconnect_tries** (int) - Optional - Number of reconnection attempts before giving up (default: 10). ### Request Example { "queue_size": 256, "block_on_filled_queue": false } ### Response #### Success Response (200) - **queue** (Queue) - A Queue instance containing call_monitor events as strings. #### Response Example { "status": "started", "queue_instance": "" } ``` -------------------------------- ### GET /system_management Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md System management methods including reboot and reconnect. ```APIDOC ## GET /system_management ### Description Methods to manage the router's power and network state. ### Methods - **reboot()**: Reboots the system. - **reconnect()**: Terminates the current connection and reconnects with a new IP. ### Response #### Success Response (200) - **status** (null) - Returns None upon successful execution. ``` -------------------------------- ### GET /description/system_info Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md Retrieves system version information including hardware, major/minor versions, and build numbers from the device description. ```APIDOC ## GET /description/system_info ### Description Retrieves the system version attributes as a tuple (HW, Major, Minor, Patch, Buildnumber, Display) from the tr64desc.xml file. ### Method GET ### Endpoint /description/system_info ### Parameters None ### Request Example N/A ### Response #### Success Response (200) - **system_info** (tuple) - A tuple containing (HW, Major, Minor, Patch, Buildnumber, Display). #### Response Example { "system_info": ["FRITZ!Box 7590", "7", "10", "0", "12345", "FRITZ!Box 7590"] } ``` -------------------------------- ### Call FritzBox Actions with Service Names Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/version_history.md This example shows how to use the FritzConnection class to call specific actions on a FritzBox service. It highlights the use of long qualified service names (e.g., 'WANIPConnection:2') and the default behavior when a service name extension is omitted. ```python from fritzconnection import FritzConnection connection = FritzConnection() info = connection.call_action('WANIPConnection:2', 'GetInfo') ``` -------------------------------- ### Get total WLAN devices count Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Demonstrates how to initialize a FritzWLAN instance and retrieve the total number of connected WLAN devices. ```python from fritzconnection.lib.fritzwlan import FritzWLAN fw = FritzWLAN(address='192.168.178.1', password='password') print(fw.total_host_number) ``` -------------------------------- ### Fritzconnection CLI Usage Source: https://context7.com/kbr/fritzconnection/llms.txt Provides examples of using the fritzconnection command-line interface to inspect router APIs, manage settings, and monitor device status. These commands allow for quick administrative tasks without writing custom Python scripts. ```bash fritzconnection -i 192.168.178.1 -s fritzconnection -i 192.168.178.1 -S WLANConfiguration1 fritzconnection -i 192.168.178.1 -A WLANConfiguration1 GetInfo fritzconnection -i 192.168.178.1 -p your_password -r fritzconnection -i 192.168.178.1 -p your_password -R fritzmonitor -i 192.168.178.1 fritzhosts -i 192.168.178.1 -p your_password ``` -------------------------------- ### Create Wi-Fi Access QR Code (Python) Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Generates a QR code for Wi-Fi access and saves it as an SVG or PNG file. This is useful for providing easy access to guest networks. The function requires the 'segno' package to be installed. It takes a filename and an optional 'kind' parameter ('svg', 'png', 'pdf') to specify the output format. ```python from fritzconnection.lib.fritzwlan import FritzGuestWLAN def write_qr_code_to_file(filename, kind="svg"): guest_wlan = FritzGuestWLAN(address="192.168.178.1", user="user", password="password") qr_code = guest_wlan.get_wifi_qr_code(kind=kind) with open(filename, "wb") as fobj: fobj.write(qr_code.read()) write_qr_code_to_file("qr_code.svg", kind="svg") # do the same as png-file: write_qr_code_to_file("qr_code.png", kind="png") ``` -------------------------------- ### Initialize FritzConnection Library Modules Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Demonstrates how to initialize FritzWLAN and FritzHomeAutomation modules by reusing an existing FritzConnection instance to avoid redundant API inspections. ```python from fritzconnection import FritzConnection from fritzconnection.lib.fritzhomeauto import FritzHomeAutomation from fritzconnection.lib.fritzwlan import FritzWLAN fc = FritzConnection(address='192.168.178.1', password=) # library modules can be initialised with an existing FritzConnection instance fw = FritzWLAN(fc) print(fw.total_host_number) fh = FritzHomeAutomation(fc) ain = '11657 0240192' fh.set_switch(ain, on=True) ``` -------------------------------- ### Initialize FritzConnection and FritzHomeAutomation Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md Sets up the base connection to the FritzBox and initializes the home automation interface for further device interaction. ```python from fritzconnection.core.fritzconnection import FritzConnection from fritzconnection.lib.fritzhomeauto import FritzHomeAutomation fc = FritzConnection(address="192.168.178.1", use_cache=True) fh = FritzHomeAutomation(fc) ``` -------------------------------- ### FritzMonitor Start and Stop Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md Starts and stops the FritzMonitor thread for real-time call event monitoring. The start method returns a Queue for events and handles reconnection logic. The stop method terminates the monitor thread. ```python class FritzMonitor(address: str = '169.254.1.1', port: int = 1012, timeout: int = 10, encoding: str = 'utf-8') Start the monitor thread and return a Queue instance with the given size to report the call_monitor events. Events are of type string. Raises an OSError if the socket can not get connected in a given timeout. Raises a RuntimeError if start() get called a second time without calling stop() first. queue_size is the number of events the queue can store. If block_on_filled_queue is False the event will get discarded in case of no free block (default). On True the EventReporter will block until a slot is available. reconnect_delay defines the maximum time interval in seconds between reconnection tries, in case that a socket-connection gets lost. reconnect_tries defines the number of consecutive to reconnect a socket before giving up. sock is used for testing to inject a mock-socket. def start(queue_size: int = 256, block_on_filled_queue: bool = False, reconnect_delay: float = 60, reconnect_tries: float = 10, sock=None) -> Queue Stop the current running monitor_thread. def stop() -> None ``` -------------------------------- ### Access Device Information via Python API Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Shows how to initialize the FritzHomeAutomation client and retrieve a list of all registered home automation devices. ```python from fritzconnection.lib.fritzhomeauto import FritzHomeAutomation fha = FritzHomeAutomation(address='192.168.178.1', password=) info = fha.device_information() ``` -------------------------------- ### Manage Home Automation Devices via CLI Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Demonstrates how to list connected home automation devices and toggle switch states using the fritzhomeauto command-line tool. ```bash $ fritzhomeauto -i 192.168.178.1 -p $ fritzhomeauto -i 192.168.178.1 -p -s '11657 0240192' off ``` -------------------------------- ### Enable and configure guest WLAN Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Shows how to enable the guest access point and optionally set a new password using the FritzGuestWLAN class. ```python from fritzconnection.lib.fritzwlan import FritzGuestWLAN def enable_guest_access_point(new_password=None): guest_wlan = FritzGuestWLAN(address="192.168.178.1", user="user", password="password") if not guest_wlan.is_enabled: guest_wlan.enable() if new_password: guest_wlan.set_password(new_password) enable_guest_access_point(new_password="new_strong_password") ``` -------------------------------- ### GET /fritzwlan/hosts Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Retrieves information about hosts registered at specific WLAN configurations. ```APIDOC ## GET /fritzwlan/hosts ### Description Retrieves a list of active devices connected to the FRITZ!Box WLAN configurations. ### Method GET ### Endpoint /fritzwlan/hosts ### Request Example from fritzconnection.lib.fritzwlan import FritzWLAN fw = FritzWLAN(address='192.168.178.1', password='password') hosts = fw.get_hosts_info() ### Response #### Success Response (200) - **mac** (string) - The MAC address of the connected device - **ip** (string) - The IP address of the connected device - **signal** (int) - Signal strength - **speed** (int) - Connection speed ``` -------------------------------- ### GET /hosts/active Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Retrieves a list of all currently active devices connected to the Fritz!Box. ```APIDOC ## GET /hosts/active ### Description Returns a list of dictionaries containing information about all currently active devices on the network. ### Method GET ### Endpoint /hosts/active ### Response #### Success Response (200) - **hosts** (list) - A list of device objects containing 'ip', 'name', 'mac', 'status', 'interface_type', 'address_source', and 'lease_time_remaining'. #### Response Example [ { "ip": "192.168.1.10", "name": "My-Device", "mac": "AA:BB:CC:DD:EE:FF", "status": true, "interface_type": "wlan", "address_source": "dhcp", "lease_time_remaining": 3600 } ] ``` -------------------------------- ### Configure Fritzconnection Logging Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md Demonstrates how to import the fritzlogger, activate local debug mode with custom handlers, and reset the logger to its default state. ```python from fritzconnection.core.logger import fritzlogger from fritzconnection.core.logger import activate_local_debug_mode, reset import logging # Activate debug mode with a StreamHandler activate_local_debug_mode(handler=logging.StreamHandler()) # Or activate with a FileHandler # activate_local_debug_mode(handler=logging.FileHandler('debug.log')) # Reset the logger to initial state reset() ``` -------------------------------- ### Instantiate and Reuse FritzConnection Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md Demonstrates how to create a FritzConnection instance with address and password, and highlights that instances can be reused for multiple calls to save resources. It also mentions the use of environment variables for credentials. ```python from fritzconnection import FritzConnection # Instantiate with password fc = FritzConnection(address="192.168.178.1", password="the_password") # Alternatively, use environment variables FRITZ_USERNAME and FRITZ_PASSWORD # fc = FritzConnection(address="192.168.178.1") ``` -------------------------------- ### GET /service/actions Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md Retrieves a dictionary of available actions for a specific service defined in the SCPD. ```APIDOC ## GET /service/actions ### Description Returns all known actions of a service as a dictionary where action names are keys and action objects are values. ### Method GET ### Endpoint /service/actions ### Parameters None ### Request Example N/A ### Response #### Success Response (200) - **actions** (dict) - Dictionary of action names and their corresponding objects. #### Response Example { "actions": { "GetInfo": "", "Reboot": "" } } ``` -------------------------------- ### GET /hosts/{mac_address} Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Retrieves detailed information for a specific host identified by its MAC address. ```APIDOC ## GET /hosts/{mac_address} ### Description Returns a dictionary with detailed information about a specific device identified by the provided MAC address. ### Method GET ### Endpoint /hosts/{mac_address} ### Parameters #### Path Parameters - **mac_address** (string) - Required - The MAC address of the target device. ### Response #### Success Response (200) - **device_info** (dict) - Dictionary containing device details. #### Response Example { "ip": "192.168.1.10", "name": "My-Device", "mac": "AA:BB:CC:DD:EE:FF", "status": true } ``` -------------------------------- ### Basic FritzConnection Usage Source: https://github.com/kbr/fritzconnection/blob/master/README.md Demonstrates initializing FritzConnection and performing basic TR-064 and HTTP interface calls. It shows how to print router model information, trigger a WAN IP connection re-establishment, and fetch device statistics. ```python from fritzconnection import FritzConnection fc = FritzConnection(address="192.168.178.1", user="user", password="pw") print(fc) # print router model information # tr-064 interface: reconnect for a new ip fc.call_action("WANIPConn1", "ForceTermination") # http interface: gets history data from a device with given 'ain' fc.call_http("getbasicdevicestats", "12345 7891011") ``` -------------------------------- ### GET /call_http (AHA-HTTP) Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md Interacts with smart-home devices using the AHA-HTTP interface by sending commands. ```APIDOC ## GET /call_http ### Description Sends an HTTP command to the router to interact with smart-home devices (AHA-HTTP-Interface). ### Method GET ### Endpoint /call_http ### Parameters #### Query Parameters - **command** (string) - Required - The AHA command to execute (e.g., getswitchlist, gettemperature) - **identifier** (string) - Optional - The device identifier (AIN) for specific device queries. ### Request Example GET /call_http?command=gettemperature&identifier=12345 ### Response #### Success Response (200) - **content-type** (string) - The MIME type of the response (e.g., text/plain) - **encoding** (string) - The character encoding (e.g., utf-8) - **content** (string) - The raw response data from the command. #### Response Example { "content-type": "text/plain", "encoding": "utf-8", "content": "225" } ``` -------------------------------- ### Initialize FritzCall and Dial Number Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Demonstrates how to instantiate the FritzCall class and use the dial method to initiate a phone call. Requires the Fritz!Box dial-help feature to be enabled. ```python from fritzconnection.lib.fritzcall import FritzCall fc = FritzCall(address='192.168.178.1', user='admin', password='password') fc.dial('0123456789') ``` -------------------------------- ### FritzConnection Initialization and Basic Usage Source: https://github.com/kbr/fritzconnection/blob/master/docs/index.md Demonstrates how to initialize the FritzConnection object and perform basic operations like printing router information, reconnecting, and calling TR-064 actions. ```APIDOC ## FritzConnection Initialization and Basic Usage ### Description This section shows how to instantiate the `FritzConnection` class and perform initial operations. ### Method N/A (Initialization and method calls) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from fritzconnection import FritzConnection # Initialize connection fc = FritzConnection(address="192.168.178.1", user="user", password="pw") # Print router model information print(fc) # TR-064 interface: reconnect for a new ip fc.call_action("WANIPConn1", "ForceTermination") fc.reconnect() # do the same with a shortcut ``` ### Response #### Success Response (200) N/A (This is example code, not an API endpoint response) #### Response Example ``` FRITZ!Box 7590 ``` ``` -------------------------------- ### GET /call_action (TR-064) Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md Executes a specific action on a TR-064 service, such as retrieving WLAN configuration details. ```APIDOC ## POST /call_action ### Description Executes a service action on the FRITZ!Box router using the TR-064 protocol. ### Method POST ### Endpoint /call_action ### Parameters #### Request Body - **service** (string) - Required - The name of the service (e.g., WLANConfiguration1) - **action** (string) - Required - The action to perform (e.g., GetInfo) ### Request Example { "service": "WLANConfiguration1", "action": "GetInfo" } ### Response #### Success Response (200) - **result** (object) - A dictionary containing the status information returned by the router. #### Response Example { "SSID": "the_wlan_name", "Channel": 6, "Status": "Up" } ``` -------------------------------- ### Initialize Smart Home Automation Source: https://context7.com/kbr/fritzconnection/llms.txt Initializes the interface for controlling smart home devices like plugs and thermostats connected to the Fritz!Box. ```python from fritzconnection.lib.fritzhomeauto import FritzHomeAutomation fh = FritzHomeAutomation(address="192.168.178.1", password="your_password") ``` -------------------------------- ### POST /fritzwlan/guest/enable Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Enables the guest WLAN access point and optionally updates the password. ```APIDOC ## POST /fritzwlan/guest/enable ### Description Enables the guest network access point on the FRITZ!Box and allows setting a new password. ### Method POST ### Endpoint /fritzwlan/guest/enable ### Parameters #### Request Body - **new_password** (string) - Optional - The new password to set for the guest network. ### Request Example from fritzconnection.lib.fritzwlan import FritzGuestWLAN guest_wlan = FritzGuestWLAN(address="192.168.178.1", user="user", password="password") guest_wlan.enable() guest_wlan.set_password("new_strong_password") ### Response #### Success Response (200) - **status** (boolean) - Returns true if the operation was successful. ``` -------------------------------- ### Access FritzConnection Package Version Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/version_history.md This snippet demonstrates how to import the fritzconnection package and access its package version attribute. It's useful for checking the installed version of the library. ```python import fritzconnection print(fritzconnection.package_version) ``` -------------------------------- ### Get Boolean from String with Default Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md Safely converts a string to a boolean, returning a specified default value instead of raising an exception if the conversion fails. Handles common boolean string formats. ```python def get_boolean_from_string(value, default=None): """Same as boolean_from_string but returns the default argument instead of raising an exception. """ try: return boolean_from_string(value) except (ValueError, AttributeError): return default ``` -------------------------------- ### Retrieve Fritz!Box Device Information and Logs Source: https://context7.com/kbr/fritzconnection/llms.txt Demonstrates how to fetch basic device metadata, check for firmware updates, and retrieve system logs filtered by category. ```python device_info = fs.get_device_info() print(f"Manufacturer: {device_info.manufacturer_name}") print(f"Model: {device_info.model_name}") print(f"Serial: {device_info.serial_number}") print(f"Software: {device_info.software_version}") new_version = fs.update_available if new_version: print(f"Update available: {new_version}") device_log = fs.get_avm_device_log() for event in device_log: print(f"{event.datetime}: [{event.group}] {event.msg}") net_log = fs.get_avm_device_log(filter='net') fs.reconnect() ``` -------------------------------- ### Fetch Content from URL Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md Performs a GET request to a given URL and returns the text content. For secure (HTTPS) requests, certificate verification is disabled to accommodate self-signed certificates commonly used in local networks like Fritz!Box. ```python import requests def get_content_from(url, timeout=None, session=None): """Returns text from a get-request for the given url. In case of a secure request (using TLS) the parameter verify is set to False, in order to disable certificate verifications. As the Fritz!Box creates a self-signed certificate for use in the LAN, encryption will work but verification will fail. """ if session is None: session = requests.Session() try: response = session.get(url, timeout=timeout, verify=False) response.raise_for_status() # Raise an exception for bad status codes return response.text except requests.exceptions.RequestException as e: print(f"Error fetching content from {url}: {e}") return None ``` -------------------------------- ### Retrieve and Control Specific Device Properties Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Demonstrates how to extract specific data like temperature from a device and how to toggle a switch state using the Python API. ```python ain = '11657 0240192' temp = fha.get_device_information_by_identifier(ain)['NewTemperatureCelsius'] * 0.1 fha.set_switch(ain, on=True) ``` -------------------------------- ### Inspect Fritz!Box Service Actions via CLI Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md Shows how to use the fritzconnection command-line interface to inspect the parameters required for a specific action on a service. This is helpful for understanding API requirements before coding. ```bash $ fritzconnection -i 192.168.178.1 -A WLANConfiguration1 SetEnable fritzconnection v1.10.0 FRITZ!Box 7590 at http://192.168.178.1 FRITZ!OS: 7.29 Service: WLANConfiguration1 Action: SetEnable Parameters: Name direction data type NewEnable -> in boolean ``` -------------------------------- ### Get Boolean from Environment Variable Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md Retrieves the value of an environment variable and converts it to a boolean. Supports common boolean string formats ('true', 'false', '1', '0', 'on', 'off'). Returns a default value if the variable is not set or cannot be converted. ```python import os def get_bool_env(key, default=None): """Return the value of the environment variable key converted to a boolean if it exists, or default if it doesn’t or can’t get converted to a boolean. keys convertable to a boolean are “true”, “on”, “1” and “false”, “off”, “0”. """ value = os.environ.get(key) if value is None: return default try: return boolean_from_string(value) except ValueError: return default ``` -------------------------------- ### Initialize FritzConnection and Execute API Commands Source: https://github.com/kbr/fritzconnection/blob/master/docs/index.md Demonstrates how to instantiate a FritzConnection object using router credentials and perform basic operations using both the TR-064 and AHA-HTTP interfaces. ```python from fritzconnection import FritzConnection fc = FritzConnection(address="192.168.178.1", user="user", password="pw") print(fc) # print router model information # tr-064 interface: reconnect for a new ip fc.call_action("WANIPConn1", "ForceTermination") fc.reconnect() # do the same with a shortcut # http interface: get history data from a device with given 'ain' fc.call_http("getbasicdevicestats", "12345 7891011") ``` -------------------------------- ### List Service Actions via CLI Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md Uses the -S flag to list all available actions for a specific service name on the FRITZ!Box. ```bash fritzconnection -i 192.168.178.1 -S WANIPConnection1 ``` -------------------------------- ### HomeAutomationDevice Methods Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Methods for retrieving and managing HomeAutomationDevice instances. ```APIDOC ## HomeAutomationDevice Methods ### get_homeautomation_device(identifier: str | None = None, index: int | None = None) → HomeAutomationDevice | None #### Description Returns a HomeAutomationDevice instance. The device can be identified by the identifier (ain) or the index in the internal router device list. If both arguments are given, identifier takes preference. If neither identifier nor index are given None gets returned. #### Parameters - **identifier** (str | None) - Optional - The unique identifier (AIN) of the device. - **index** (int | None) - Optional - The internal index of the device. #### Response Example ```json { "NewAIN": "11657 0240192", "NewDeviceId": 16, "NewDeviceName": "FRITZ!DECT 210 #1", "NewMultimeterEnergy": 75, "NewSwitchState": "ON", "NewTemperatureCelsius": 265, "NewTemperatureIsEnabled": "ENABLED" } ``` ### get_homeautomation_devices() → list[HomeAutomationDevice] #### Description Returns a list with HomeAutomationDevice instances of all known home-automation devices. The list is ordered in the way the router provided the data. #### Response Example ```json [ { "NewAIN": "11657 0240192", "NewDeviceId": 16, "NewDeviceName": "FRITZ!DECT 210 #1", "NewMultimeterEnergy": 75, "NewSwitchState": "ON", "NewTemperatureCelsius": 265, "NewTemperatureIsEnabled": "ENABLED" } ] ``` ``` -------------------------------- ### Get Fritz!Box WLAN Host Information (Python) Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Retrieves a list of dictionaries containing information about connected WLAN devices. Each dictionary includes details such as service, index, status, MAC address, IP address, signal strength, and speed. This functionality is provided by the FritzWLAN class. ```python from fritzconnection.lib.fritzwlan import FritzWLAN # Assuming FritzConnection instance 'fc' is already created # fc = FritzConnection(address='192.168.178.1', user='user', password='password') wlan = FritzWLAN(fc=fc) # Or FritzGuestWLAN for guest network hosts_info = wlan.get_hosts_info() print(hosts_info) ``` -------------------------------- ### Manage WLAN and Guest Networks Source: https://context7.com/kbr/fritzconnection/llms.txt Shows how to configure wireless settings, monitor connected devices, manage passwords, and generate WiFi access QR codes. ```python from fritzconnection.lib.fritzwlan import FritzWLAN, FritzGuestWLAN wlan = FritzWLAN(address="192.168.178.1", password="your_password", service=1) print(f"SSID: {wlan.ssid}") for host in wlan.get_hosts_info(): print(f"MAC: {host['mac']}, IP: {host['ip']}") wlan.set_channel(6) wlan.set_password("MySecurePassword123") guest = FritzGuestWLAN(address="192.168.178.1", password="your_password") guest.enable() stream = guest.get_wifi_qr_code(kind='png', scale=6) ``` -------------------------------- ### Call Fritz!Box Action: GetInfo Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md Shows how to call a specific action ('GetInfo') on a service ('WLANConfiguration1') using a FritzConnection instance. It details the required arguments and the expected dictionary output containing device information. ```python from fritzconnection import FritzConnection fc = FritzConnection(address="192.168.178.1", password="the_password") state = fc.call_action("WLANConfiguration1", "GetInfo") # Example output structure: # { # 'NewAllowedCharsPSK': '0123456789ABCDEFabcdef', # 'NewSSID': 'the WLAN name', # 'NewStatus': 'Up' # } ``` -------------------------------- ### Get Smart Home Device Temperatures via TR-064 API with fritzconnection Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md This Python code snippet shows how to obtain the temperature of switchable smart home devices connected to a FRITZ!Box router using the TR-064 API through the fritzconnection library's FritzHomeAutomation module. It initializes FritzHomeAutomation, retrieves all devices, filters for switchable ones, and then accesses their temperature property. This method is generally faster than the HTTP API. ```python from fritzconnection.lib.fritzhomeauto import FritzHomeAutomation # Assuming 'fc' is an initialized FritzConnection instance # fc = FritzConnection(address="192.168.178.1", use_cache=True) fh = FritzHomeAutomation(fc) # create a list of HomeAutomationDevice instances: devices = [d for d in fh.get_homeautomation_devices() if d.is_switchable] for device in devices: temperature = device.TemperatureCelsius * 0.1 print(temperature) ``` -------------------------------- ### Import FritzConnection and FritzMonitor Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/fritzconnection_api.md Provides shortcuts for importing the main FritzConnection and FritzMonitor classes from the library. These are essential for establishing connections and monitoring the Fritz!Box. ```python from fritzconnection import FritzConnection from fritzconnection import FritzMonitor ``` -------------------------------- ### Periodic Network Transmission Rate Monitoring in Python Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Demonstrates how to monitor real-time transmission rates by creating a FritzStatus instance and polling the connection status in a loop. ```python 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) ``` -------------------------------- ### Inspect FritzBox TR-064 API via CLI Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md Displays the help menu for the fritzconnection command line tool, detailing available flags for connection settings, caching, and API inspection. ```shell fritzconnection -h ``` -------------------------------- ### Retrieve Network Host Information Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/library_modules.md Shows how to use the FritzHosts class to connect to a FRITZ!Box and retrieve a list of registered network hosts. It iterates through the host information to display IP, name, MAC, and active status. ```python 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}') ``` -------------------------------- ### Perform Router Reconnection via Python Source: https://github.com/kbr/fritzconnection/blob/master/docs/sources/getting_started.md Demonstrates how to instantiate a FritzConnection object and trigger a ForceTermination action to initiate a router reconnection. ```python from fritzconnection import FritzConnection fc = FritzConnection() fc.call_action('WANIPConnection1', 'ForceTermination') ```