### Install documentation dependencies and serve locally Source: https://sukramj.github.io/aiohomematic/contributor/contributing Install the documentation requirements and start the MkDocs development server. Open http://127.0.0.1:8000 to preview the site. ```bash pip install -r requirements_docs.txt mkdocs serve # Open http://127.0.0.1:8000 ``` -------------------------------- ### Complete Example Source: https://sukramj.github.io/aiohomematic/quickstart?q= Full quick start example: connects to a CCU, lists devices, finds a specific device, subscribes to updates, toggles a switch, and waits for events. Includes error handling and cleanup. ```python """Complete aiohomematic quick start example.""" import asyncio from aiohomematic.central import CentralConfig from aiohomematic.central.events import DataPointValueReceivedEvent from aiohomematic.const import ParamsetKey async def on_update(*, event: DataPointValueReceivedEvent) -> None: """Handle value updates.""" print(f"UPDATE: {event.dpk.channel_address}.{event.dpk.parameter} = {event.value}") async def main() -> None: """Main entry point.""" config = CentralConfig.for_ccu( host="192.168.1.100", username="Admin", password="your-password", ) central = await config.create_central() await central.start() try: # 1. List devices print("=== Devices ===") for device in central.devices: print(f" {device.address}: {device.name}") # 2. Find a specific device device = central.device_coordinator.get_device(address="VCU0000001") if device: print("\n=== Device Details ===") print(f" Model: {device.model}") print(f" Firmware: {device.firmware}") # 3. List channels and data points (channels is keyed by channel address) for channel_address, channel in device.channels.items(): print(f"\n Channel {channel.no} ({channel_address}):") for dp in channel.generic_data_points: print(f" {dp.parameter}: {dp.value}") # 4. Subscribe to updates unsubscribe = central.event_bus.subscribe( event_type=DataPointValueReceivedEvent, event_key=None, handler=on_update, ) # 5. Toggle a switch (if exists) try: client = central.client_coordinator.get_client(interface_id=device.interface_id) current = await client.get_value( channel_address="VCU0000001:3", paramset_key=ParamsetKey.VALUES, parameter="STATE", ) await client.set_value( channel_address="VCU0000001:3", paramset_key=ParamsetKey.VALUES, parameter="STATE", value=not current, ) print(f"\nToggled switch from {current} to {not current}") except Exception as e: print(f"\nCould not toggle switch: {e}") # 6. Wait for some events print("\nWaiting for events (10 seconds)...") await asyncio.sleep(10) unsubscribe() print("\nDone!") finally: await central.stop() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Complete aiohomematic Quick Start Example Source: https://sukramj.github.io/aiohomematic/quickstart Full example that initializes a central, lists devices, toggles a switch, subscribes to events, and waits for 10 seconds. Requires a CCU with host, username, and password. ```python """Complete aiohomematic quick start example.""" import asyncio from aiohomematic.central import CentralConfig from aiohomematic.central.events import DataPointValueReceivedEvent from aiohomematic.const import ParamsetKey async def on_update(*, event: DataPointValueReceivedEvent) -> None: """Handle value updates.""" print(f"UPDATE: {event.dpk.channel_address}.{event.dpk.parameter} = {event.value}") async def main() -> None: """Main entry point.""" config = CentralConfig.for_ccu( host="192.168.1.100", username="Admin", password="your-password", ) central = await config.create_central() await central.start() try: # 1. List devices print("=== Devices ===") for device in central.devices: print(f" {device.address}: {device.name}") # 2. Find a specific device device = central.device_coordinator.get_device(address="VCU0000001") if device: print("\n=== Device Details ===") print(f" Model: {device.model}") print(f" Firmware: {device.firmware}") # 3. List channels and data points (channels is keyed by channel address) for channel_address, channel in device.channels.items(): print(f"\n Channel {channel.no} ({channel_address}):") for dp in channel.generic_data_points: print(f" {dp.parameter}: {dp.value}") # 4. Subscribe to updates unsubscribe = central.event_bus.subscribe( event_type=DataPointValueReceivedEvent, event_key=None, handler=on_update, ) # 5. Toggle a switch (if exists) try: client = central.client_coordinator.get_client(interface_id=device.interface_id) current = await client.get_value( channel_address="VCU0000001:3", paramset_key=ParamsetKey.VALUES, parameter="STATE", ) await client.set_value( channel_address="VCU0000001:3", paramset_key=ParamsetKey.VALUES, parameter="STATE", value=not current, ) print(f"\nToggled switch from {current} to {not current}") except Exception as e: print(f"\nCould not toggle switch: {e}") # 6. Wait for some events print("\nWaiting for events (10 seconds)...") await asyncio.sleep(10) unsubscribe() print("\nDone!") finally: await central.stop() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Set up and run local documentation preview with MkDocs Source: https://sukramj.github.io/aiohomematic/contributor/contributing?q= Install documentation dependencies and start the MkDocs development server. After running 'mkdocs serve', open http://127.0.0.1:8000 in a browser to preview the documentation locally. ```bash pip install -r requirements_docs.txt mkdocs serve # Open http://127.0.0.1:8000 ``` -------------------------------- ### Install and run pytest-markdown-docs on docs Source: https://sukramj.github.io/aiohomematic/contributor/testing/docs_drift_check?q= Commands to install pytest-markdown-docs and run it on the Quick Start and Getting Started pages. Not currently wired into CI. ```bash pip install pytest-markdown-docs pytest --markdown-docs docs/quickstart.md docs/getting_started.md ``` -------------------------------- ### CentralUnit overview example Source: https://sukramj.github.io/aiohomematic/reference/api/central?q= Shows how to configure and start a CentralUnit using CentralConfig.for_ccu, access devices, and stop the central. ```python from aiohomematic.central import CentralConfig config = CentralConfig.for_ccu( host="192.168.1.100", username="Admin", password="secret", ) central = config.create_central() await central.start() # Access devices for device in central.devices: print(device.name) await central.stop() ``` -------------------------------- ### Basic Setup with CentralConfig and InterfaceConfig Source: https://sukramj.github.io/aiohomematic/developer/consumer_api Creates a CentralConfig with multiple interface configurations (HMIP_RF and BIDCOS_RF), then creates and starts the central unit. The create_central() method is async, and the central must be stopped in a finally block. ```python from aiohomematic.central import CentralConfig from aiohomematic.client import InterfaceConfig from aiohomematic.const import Interface # Create configuration config = CentralConfig( name="my-central", host="192.168.1.100", username="admin", password="secret", central_id="unique-id-123", interface_configs={ InterfaceConfig( central_name="my-central", interface=Interface.HMIP_RF, port=2010, ), InterfaceConfig( central_name="my-central", interface=Interface.BIDCOS_RF, port=2001, ), }, ) # Create and start (create_central() is async) central = await config.create_central() await central.start() try: # Work with devices for device in central.devices: print(f"{device.address}: {device.name}") finally: await central.stop() ``` -------------------------------- ### Install aiohomematic with pip Source: https://sukramj.github.io/aiohomematic Install the aiohomematic library using pip. This is the first step in the quick start guide. ```bash pip install aiohomematic ``` -------------------------------- ### Set Up Development Environment Source: https://sukramj.github.io/aiohomematic/contributor/contributing Create a virtual environment, install dependencies, and set up pre-commit hooks. Note: the command 'prek install' appears to be a typo for 'pre-commit install'. ```bash # Create virtual environment python3.14 -m venv venv source venv/bin/activate # Linux/macOS # or: venv\Scripts\activate # Windows # Install dependencies pip install -r requirements.txt pip install -r requirements_test.txt # Install pre-commit hooks prek install ``` -------------------------------- ### FactoryWithClient setup for session playback Source: https://sukramj.github.io/aiohomematic/contributor/testing/session_playback Creates a test factory with a session player and mocked client, then gets the default central. The central is ready for testing with mocked RPC calls, and devices can be accessed via the device coordinator. ```python factory = FactoryWithClient( player=session_player, do_mock_client=True, ignore_devices_on_create=["VCU0000099"], ) central = await factory.get_default_central(start=True) # central is now ready for testing with mocked RPC calls device = central.device_coordinator.get_device(address="VCU0000001") ``` -------------------------------- ### Simple __init__ Method Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Examples of simple __init__ methods with one-line docstrings. ```python def __init__(self) -> None: """Initialize the coordinator.""" ``` ```python def __init__(self) -> None: """Initialize the event bus.""" ``` -------------------------------- ### Create and start async XML-RPC server Source: https://sukramj.github.io/aiohomematic/adr/0012-async-xml-rpc-server-poc Creates and starts an AsyncXmlRpcServer instance. If the server is not already started, it starts it and logs the listening address and port. Returns the server instance. ```python async def create_async_xml_rpc_server( *, ip_addr: str = IP_ANY_V4, port: int = PORT_ANY, ) -> AsyncXmlRpcServer: """Create and start an async XML-RPC server.""" server = AsyncXmlRpcServer(ip_addr=ip_addr, port=port) if not server.started: await server.start() _LOGGER.debug( "Created AsyncXmlRpcServer on %s:%d", server.listen_ip_addr, server.listen_port, ) return server ``` -------------------------------- ### Example 3: Missing __init__ Documentation - Before Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_standards Before example of a missing __init__ docstring. ```python def __init__(self, central, addr, channel_no): """Init custom entity.""" ``` -------------------------------- ### Example 3: Missing __init__ Documentation - After Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_standards After example of a complete __init__ docstring with parameter descriptions. ```python def __init__( self, *, central: CentralUnit, device_address: str, channel_no: int, ) -> None: """ Initialize custom climate entity. Args: central: Central unit instance device_address: Device address channel_no: Channel number """ ``` -------------------------------- ### Property Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Examples of properties with one-line docstrings. ```python @property def device_address(self) -> str: """Return the device address.""" ``` ```python @property def available(self) -> bool: """Return whether device is available.""" ``` ```python @property def value(self) -> Any: """Return current data point value.""" ``` -------------------------------- ### Simple Method Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Examples of simple methods with one-line docstrings. ```python def get_device_by_address(self, address: str) -> Device | None: """Return device by address.""" ``` ```python def is_connected(self) -> bool: """Return connection status.""" ``` ```python def clear_cache(self) -> None: """Clear all cached data.""" ``` -------------------------------- ### Tier 1: Core API Module Docstring Example Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_standards?q= Example docstring for a core API module, showing the structure with overview, public API, and quick start sections. ```python """ Central unit and core orchestration for Homematic CCU and compatible backends. Overview -------- This package provides the central coordination layer for aiohomematic. The CentralUnit class manages client lifecycles, device creation, event handling, and background tasks. It serves as the primary entry point for interacting with Homematic systems. Public API ---------- - CentralUnit: Main coordination class for managing all operations - CentralConfig: Configuration dataclass for central initialization Quick start ----------- Typical usage is to create a CentralConfig, instantiate CentralUnit, and call start(): config = CentralConfig(name="ccu", host="192.168.1.100", ...) central = config.create_central() await central.start() """ ``` -------------------------------- ### Protocol/Interface Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Examples of Protocol classes with docstrings describing their contracts. ```python class DeviceProvider(Protocol): """Protocol for providing access to device registry.""" class CentralInfo(Protocol): """Protocol for central system information.""" class TaskScheduler(Protocol): """Protocol for scheduling background tasks.""" ``` -------------------------------- ### Simple __init__ Method Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Examples of simple __init__ methods with one-line docstrings, showing how to document initialization of a coordinator and an event bus. ```python def __init__(self) -> None: """Initialize the coordinator.""" def __init__(self) -> None: """Initialize the event bus.""" ``` -------------------------------- ### CentralConfig factory method and full configuration Source: https://sukramj.github.io/aiohomematic/reference/api/config?q= Shows two ways to create a CentralConfig: using the for_ccu factory method for a simple setup, and the full constructor with interface_configs for advanced configuration. The example imports CentralConfig, InterfaceConfig, and Interface. ```python from aiohomematic.central import CentralConfig from aiohomematic.client import InterfaceConfig from aiohomematic.const import Interface # Simple: Use factory methods config = CentralConfig.for_ccu( host="192.168.1.100", username="Admin", password="secret", ) # Advanced: Full configuration config = CentralConfig( name="my-ccu", host="192.168.1.100", username="Admin", password="secret", central_id="unique-id", interface_configs={ InterfaceConfig( central_name="my-ccu", interface=Interface.HMIP_RF, port=2010, ), }, ) ``` -------------------------------- ### Complex __init__ Method Docstring Example Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Example of a complex __init__ method that initializes a device coordinator with three parameters, documenting each parameter. ```python def __init__( self, *, central_info: CentralInfo, device_provider: DeviceProvider, client_provider: ClientProvider, ) -> None: """ Initialize the device coordinator. Args: central_info: System information provider device_provider: Device registry access client_provider: Client lookup functionality """ ``` -------------------------------- ### Clone and Create Virtual Environment Source: https://sukramj.github.io/aiohomematic/contributor/dev-environment?q= Commands to clone the aiohomematic repository, create a Python 3.14 virtual environment, activate it, install dependencies, and install pre-commit hooks. Note the typo 'prek install' in the source. ```bash # Clone the repository git clone https://github.com/sukramj/aiohomematic.git cd aiohomematic # Create virtual environment python3.14 -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install dependencies pip install -r requirements.txt pip install -r requirements_test.txt # Install pre-commit hooks prek install ``` -------------------------------- ### Example: Create Homegear central Source: https://sukramj.github.io/aiohomematic/reference/api/config?q= Example usage of CentralConfig.for_homegear to create a configuration for a Homegear backend, then create the central unit asynchronously. ```python config = CentralConfig.for_homegear( host="192.168.1.50", username="homegear", password="secret", ) central = await config.create_central() ``` -------------------------------- ### Base Class Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Examples of base classes with docstrings explaining inheritance contracts. ```python class BaseDataPoint(ABC): """ Base class for all data point implementations. Subclasses must implement value property and update methods. """ class CustomDataPoint(BaseDataPoint): """Base class for custom device-specific data points.""" ``` -------------------------------- ### Simple Method One-Line Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Examples of simple methods with one-line docstrings, showing how to document methods that return a device, connection status, or clear cache. ```python def get_device_by_address(self, address: str) -> Device | None: """Return device by address.""" def is_connected(self) -> bool: """Return connection status.""" def clear_cache(self) -> None: """Clear all cached data.""" ``` -------------------------------- ### Initialize and start aiohomematic central Source: https://sukramj.github.io/aiohomematic/developer/homematicip_local_api_usage?q= Creates a central instance and starts it. This is the first step in the typical integration flow. ```python central = CentralConfig.create_central() await central.start() ``` -------------------------------- ### Complex Method with Args/Returns Docstring Example Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Example of a complex method that creates a device, with a multi-line docstring documenting parameters, return value, and exceptions. ```python def create_device( self, *, interface_id: str, device_address: str, device_type: str, force_create: bool = False, ) -> Device: """ Create and register a new device instance. Args: interface_id: Interface identifier (e.g., "hmip-rf") device_address: Unique device address device_type: Device type identifier force_create: Force creation even if device exists Returns: Created or existing Device instance. Raises: DeviceCreationException: If device creation fails. """ ``` -------------------------------- ### Install godevccu simulator Source: https://sukramj.github.io/aiohomematic/contributor/dev-environment?q= Installs the godevccu simulator binary into .godevccu/ and verifies its checksum. The version is pinned in .godevccu-version and should be run again after the pin changes. ```bash script/install_godevccu.sh # downloads into .godevccu/ and verifies the checksum ``` -------------------------------- ### Protocol/Interface Class Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Examples of protocol class docstrings for device provider, central info, and task scheduler. ```python class DeviceProvider(Protocol): """Protocol for providing access to device registry.""" class CentralInfo(Protocol): """Protocol for central system information.""" class TaskScheduler(Protocol): """Protocol for scheduling background tasks.""" ``` -------------------------------- ### for_ccu usage example Source: https://sukramj.github.io/aiohomematic/reference/api/config?q= Example usage of the for_ccu factory method to create a central configuration. ```python config = CentralConfig.for_ccu( host="192.168.1.100", username="Admin", password="secret", ) central = await config.create_central() ``` -------------------------------- ### Custom Entity Class Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Examples of custom entity class docstrings for thermostat, cover, and light devices. ```python class CeClimate(CustomDataPoint): """Custom entity for thermostat and climate devices.""" class CeCover(CustomDataPoint): """Custom entity for blinds and shutters.""" class CeLight(CustomDataPoint): """Custom entity for dimmable and colored lights.""" ``` -------------------------------- ### Base Class Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Examples of base class docstrings for data point implementations. ```python class BaseDataPoint(ABC): """ Base class for all data point implementations. Subclasses must implement value property and update methods. """ class CustomDataPoint(BaseDataPoint): """Base class for custom device-specific data points.""" ``` -------------------------------- ### Tier 2 Module Docstring Example Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_standards Example of a medium-detail module docstring for a device coordinator module, listing key features. ```python """ Device coordinator for managing device lifecycle and operations. This module provides centralized device management including device creation, registration, removal, and device-related operations. The DeviceCoordinator works in conjunction with DeviceRegistry to maintain the runtime device model. Key features: - Device creation from descriptions - Device registration and lookup - Device removal and cleanup - Device update operations """ ``` -------------------------------- ### Test Module Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Examples of test module docstrings for device coordinator, climate data points, and central unit lifecycle. ```python """Tests for device coordinator functionality.""" """Tests for custom climate data points.""" """Tests for central unit lifecycle.""" ``` -------------------------------- ### Avoid Vague Docstrings Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Shows a bad and good example of a docstring. The bad example is vague ('Process the data.'), while the good example specifies the action ('Update device state from backend data.'). Use the good style to be more informative. ```python # Bad def process_data(self, data: dict[str, Any]) -> None: """Process the data.""" # Good def process_data(self, data: dict[str, Any]) -> None: """Update device state from backend data.""" ``` -------------------------------- ### Custom Entity Class Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Examples of custom entity class docstrings for climate, cover, and light devices. ```python class CeClimate(CustomDataPoint): """Custom entity for thermostat and climate devices.""" class CeCover(CustomDataPoint): """Custom entity for blinds and shutters.""" class CeLight(CustomDataPoint): """Custom entity for dimmable and colored lights.""" ``` -------------------------------- ### Concrete Class (Single Line) Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Examples of concrete class docstrings for device, channel, and scheduler job. ```python class Device: """Represents a Homematic device with channels and data points.""" class Channel: """Represents a device channel containing data points.""" class SchedulerJob: """Scheduled background task with interval-based execution.""" ``` -------------------------------- ### Example 1: Inconsistent Module Docstring - After Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_standards After example of a consistent module docstring with a summary and public API note. ```python """ Generic sensor data points. Public API of this module is defined by __all__. """ ``` -------------------------------- ### Start and stop the central unit with CentralConfig.for_ccu Source: https://sukramj.github.io/aiohomematic/reference/common_operations Creates a central unit from a CCU configuration, starts it, and stops it cleanly. Requires host, username, and password for the CCU. ```python from aiohomematic.central import CentralConfig async def main(): config = CentralConfig.for_ccu( host="192.168.1.100", username="Admin", password="secret", ) # Create and start the central unit central = await config.create_central() await central.start() # Your application logic here... # Clean shutdown await central.stop() ``` -------------------------------- ### Get link peers and create/remove links Source: https://sukramj.github.io/aiohomematic/reference/common_operations Shows how to get link peers for a channel, create a link using the LinkCoordinator, and remove a link. Includes printing linked peers. ```python # Get link peers for a device (via client) client = central.client_coordinator.get_client(interface=Interface.HMIP_RF) peers = await client.get_link_peers(channel_address="VCU0000001:1") for peer in peers: print(f"Linked to: {peer}") # Create link (via LinkCoordinator) await central.link.add_link( sender_channel_address="VCU0000001:1", receiver_channel_address="VCU0000002:1", name="My Link", description="Button controls light", ) # Remove link await central.link.remove_link( sender_channel_address="VCU0000001:1", receiver_channel_address="VCU0000002:1", ) ``` -------------------------------- ### Activate SessionRecorder via CentralConfig Source: https://sukramj.github.io/aiohomematic/contributor/testing/session_playback Sets the SR_RECORD_SYSTEM_INIT optional setting in CentralConfig to record the system init. The recorder starts recording for DEFAULT_SESSION_RECORDER_START_FOR_SECONDS after start() and then saves. ```python config = CentralConfig( ..., optional_settings=(OptionalSettings.SR_RECORD_SYSTEM_INIT,), ) ``` -------------------------------- ### Changelog entry format example Source: https://sukramj.github.io/aiohomematic/contributor/release_process?q= Example of concise, action-oriented changelog entries for New Features and Bug Fixes sections, including issue/PR references. ```markdown ### New Features - Add support for HmIP-NEW-DEVICE thermostat (#123) - Add `get_schedule_simple_profile` action for climate entities ### Bug Fixes - Fix connection timeout handling for JSON-RPC interfaces (#456) ``` -------------------------------- ### Simplified Setup Methods for CCU3/CCU2 and Homegear Source: https://sukramj.github.io/aiohomematic/developer/consumer_api Shows two convenience constructors: CentralConfig.for_ccu() for CCU3/CCU2 and CentralConfig.for_homegear() for Homegear. Both require name, host, username, and password. ```python # For CCU3/CCU2 config = CentralConfig.for_ccu( name="ccu", host="192.168.1.100", username="admin", password="secret", ) # For Homegear config = CentralConfig.for_homegear( name="homegear", host="192.168.1.100", username="admin", password="secret", ) ``` -------------------------------- ### Read a value from a device Source: https://sukramj.github.io/aiohomematic/quickstart?q= Reads the switch state of a device using the client for the device's interface. Uses ParamsetKey.VALUES and the parameter 'STATE'. The example assumes a central unit is already created and started. ```python from aiohomematic.const import ParamsetKey # Read switch state via the client for the device's interface device = central.device_coordinator.get_device(address="VCU0000001") client = central.client_coordinator.get_client(interface_id=device.interface_id) state = await client.get_value( channel_address="VCU0000001:3", paramset_key=ParamsetKey.VALUES, parameter="STATE", ) print(f"Switch is {'ON' if state else 'OFF'}") ``` -------------------------------- ### Switch Schedule Example Source: https://sukramj.github.io/aiohomematic/user/features/week_profile?q= Example of using the homematicip_local.set_schedule action to define a weekly schedule with two entries: weekday evening and weekend evening. The level must be 0.0 or 1.0. ```yaml action: homematicip_local.set_schedule data: device_id: abcdefg... schedule_data: "1": # Weekday evening weekdays: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY] time: "18:00" condition: fixed_time target_channels: ["1_1"] level: 1.0 # On (only 0.0 or 1.0 allowed!) duration: 4h "2": # Weekend evening weekdays: [SATURDAY, SUNDAY] time: "17:00" condition: fixed_time target_channels: ["1_1"] level: 1.0 # On duration: 6h ``` -------------------------------- ### Connect and list devices with CentralConfig Source: https://sukramj.github.io/aiohomematic/quickstart?q= Creates a central unit using CentralConfig.for_ccu, starts it, iterates over discovered devices, and stops the central unit in a finally block. The output shows example device addresses, names, and models. ```python import asyncio from aiohomematic.central import CentralConfig async def main(): config = CentralConfig.for_ccu( host="192.168.1.100", username="Admin", password="your-password", ) central = await config.create_central() await central.start() try: # Iterate over all discovered devices for device in central.devices: print(f"{device.address}: {device.name} ({device.model})") finally: # Always stop the central unit to release resources await central.stop() asyncio.run(main()) ``` ```text VCU0000001: Living Room Light (HmIP-BSM) VCU0000002: Hallway Switch (HmIP-PS) VCU0000003: Bedroom Thermostat (HmIP-eTRV-2) ``` -------------------------------- ### Install godevccu and record session Source: https://sukramj.github.io/aiohomematic/contributor/testing/session_playback Commands to install godevccu and run the recording script. The script runs a central with start_direct=True and optional settings SR_RECORD_SYSTEM_INIT and SR_DISABLE_RANDOMIZE_OUTPUT. Do not randomize this recording because playback tests reference devices by address. ```bash script/install_godevccu.sh PYTHONPATH=. python script/record_godevccu_session.py ``` -------------------------------- ### init_install_mode method Source: https://sukramj.github.io/aiohomematic/reference/api/central?q= Initializes install mode data points. Internal use - use hub_coordinator for external access. ```python init_install_mode() -> Mapping[Interface, InstallModeDpType] ``` -------------------------------- ### CentralState STARTING attribute Source: https://sukramj.github.io/aiohomematic/reference/api/const The STARTING attribute of CentralState, with value 'starting'. ```python STARTING = 'starting' ``` -------------------------------- ### start Source: https://sukramj.github.io/aiohomematic/reference/api/central?q= Starts processing of the central unit. ```APIDOC ## start ### Description Starts processing of the central unit. ### Method start (async) ### Signature ``` start() -> None ``` ### Returns - **None** ``` -------------------------------- ### Verify Setup Source: https://sukramj.github.io/aiohomematic/contributor/dev-environment?q= Commands to run tests, linters, and type checking to verify the development environment is correctly set up. ```bash # Run tests pytest tests/ # Run linters pre-commit run --all-files # Type check mypy ``` -------------------------------- ### Install pytest-cov Source: https://sukramj.github.io/aiohomematic/contributor/testing/coverage Install pytest-cov to enable coverage collection. ```bash pip install pytest-cov ``` -------------------------------- ### Create async XML-RPC server factory Source: https://sukramj.github.io/aiohomematic/adr/0012-async-xml-rpc-server-poc?q= Factory function to create and start an AsyncXmlRpcServer instance. Starts the server if not already started and logs the listening address and port. ```python async def create_async_xml_rpc_server( *, ip_addr: str = IP_ANY_V4, port: int = PORT_ANY, ) -> AsyncXmlRpcServer: """Create and start an async XML-RPC server.""" server = AsyncXmlRpcServer(ip_addr=ip_addr, port=port) if not server.started: await server.start() _LOGGER.debug( "Created AsyncXmlRpcServer on %s:%d", server.listen_ip_addr, server.listen_port, ) return server ``` -------------------------------- ### CentralConfig + CentralUnit usage Source: https://sukramj.github.io/aiohomematic/reference/api Recommended entry point: create a central instance with CentralConfig.for_ccu, start it, and access devices via the device coordinator. ```python from aiohomematic.central import CentralConfig config = CentralConfig.for_ccu(host="...", username="...", password="...") central = await config.create_central() await central.start() devices = central.device_coordinator.devices ``` -------------------------------- ### Validator Function Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Examples of validator functions with one-line docstrings. ```python def channel_address(value: str, /) -> str: """Validate channel address format.""" ``` ```python def positive_int(value: int, /) -> int: """Validate value is positive integer.""" ``` ```python def interface_id(value: str, /) -> str: """Validate interface identifier.""" ``` -------------------------------- ### create_backup_and_download method Source: https://sukramj.github.io/aiohomematic/reference/api/central?q= Creates a backup on the CCU and downloads it. Returns BackupData or None if failed. ```python create_backup_and_download() -> BackupData | None ``` -------------------------------- ### Example 2: Inconsistent Method Docstrings - After Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_standards?q= After example of consistent method docstrings. ```python def get_device(self, address: str) -> Device | None: """Return device by address.""" def fetch_value(self, parameter: str) -> Any: """Return parameter value.""" ``` -------------------------------- ### Data Class Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Examples of dataclasses with docstrings describing their configuration purpose. ```python @dataclass class CentralConfig: """Configuration for central unit initialization.""" @dataclass class InterfaceConfig: """Configuration for a single interface connection.""" ``` -------------------------------- ### Example 2: Inconsistent Method Docstrings - Before Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_standards Before example of inconsistent method docstrings. ```python def get_device(self, addr): """Gets device""" def fetch_value(self, param): """Returns the value of param""" ``` -------------------------------- ### Basic Usage of detect_backend Source: https://sukramj.github.io/aiohomematic/developer/backend_detection?q= Shows how to import detect_backend and DetectionConfig, create a config with host, username, and password, and call detect_backend. Prints backend type, interfaces, port, and TLS status if a backend is found. ```python from aiohomematic.backend_detection import detect_backend, DetectionConfig config = DetectionConfig( host="192.168.1.100", username="admin", password="secret", ) result = await detect_backend(config=config) if result: print(f"Backend: {result.backend}") print(f"Interfaces: {result.available_interfaces}") print(f"Port: {result.detected_port}") print(f"TLS: {result.tls}") else: print("No backend found") ``` -------------------------------- ### Example 1: Inconsistent Module Docstring - Before Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_standards Before example of an inconsistent module docstring. ```python """Module for data points implemented using the sensor category""" ``` -------------------------------- ### Usage example: catching aiohomematic exceptions Source: https://sukramj.github.io/aiohomematic/reference/api/exceptions?q= Example showing how to import and catch aiohomematic exceptions when calling api.write_value. The example demonstrates handling ValidationException, NoConnectionException, AuthFailure, ClientException, and the base AioHomematicException. ```python from aiohomematic.exceptions import ( AioHomematicException, ClientException, NoConnectionException, AuthFailure, ValidationException, ) try: await api.write_value( channel_address="VCU0000001:1", parameter="LEVEL", value=1.5, # Invalid: must be 0.0-1.0 ) except ValidationException as e: print(f"Invalid value: {e}") except NoConnectionException: print("Lost connection to backend") except AuthFailure: print("Authentication failed - check credentials") except ClientException as e: print(f"Communication error: {e}") except AioHomematicException as e: print(f"General error: {e}") ``` -------------------------------- ### Concrete Class (Single Line) Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates?q= Examples of concrete classes with single-line docstrings. ```python class Device: """Represents a Homematic device with channels and data points.""" class Channel: """Represents a device channel containing data points.""" class SchedulerJob: """Scheduled background task with interval-based execution.""" ``` -------------------------------- ### Minimal example: register a new switch device Source: https://sukramj.github.io/aiohomematic/developer/extension_points Minimal registration example for a new switch device, showing required imports and a single DeviceProfileRegistry.register call with a channel number for the STATE parameter. ```python # In aiohomematic/model/custom/switch.py from aiohomematic.const import DataPointCategory, DeviceProfile from aiohomematic.model.custom.registry import DeviceProfileRegistry # Register the new device DeviceProfileRegistry.register( category=DataPointCategory.SWITCH, models="HmIP-MY-NEW-SWITCH", data_point_class=CustomDpSwitch, profile_type=DeviceProfile.IP_SWITCH, channels=(3,), # Channel number where STATE parameter lives ) ``` -------------------------------- ### Home Assistant Integration: Custom StorageFactoryProtocol Implementation Source: https://sukramj.github.io/aiohomematic/adr/0011-storage-abstraction Shows how to integrate with Home Assistant by implementing StorageFactoryProtocol and passing the factory to CentralConfig. The factory must return a StorageProtocol instance, here wrapping Home Assistant's Store. ```python from aiohomematic.store.storage import StorageFactoryProtocol class HAStoreFactory: """Factory using Home Assistant's Store.""" def create_storage(self, *, key: str, **kwargs) -> StorageProtocol: return HAStoreWrapper(hass=self.hass, key=key, ...) # Pass to CentralConfig config = CentralConfig( # ... other config ... storage_factory=HAStoreFactory(hass=hass), ) ``` -------------------------------- ### Anti-Pattern 1: Using composite when specific suffices Source: https://sukramj.github.io/aiohomematic/architecture/protocol_selection_guide Shows bad and good examples of dependency injection. The bad example depends on the full CentralProtocol but only reads config; the good example depends only on ConfigProviderProtocol. ```python # BAD: Depends on full CentralProtocol but only reads config def process(central: CentralProtocol) -> None: timeout = central.config.timeout_config.rpc_timeout # GOOD: Depends only on ConfigProviderProtocol def process(config_provider: ConfigProviderProtocol) -> None: timeout = config_provider.config.timeout_config.rpc_timeout ``` -------------------------------- ### Complete schedule_data example with two entries Source: https://sukramj.github.io/aiohomematic/user/features/week_profile?q= YAML example showing two schedule entries: one for workday mornings with fixed time and one for weekend mornings with sunrise-based condition. Demonstrates required and optional fields, including astro_type, astro_offset_minutes, duration, and ramp_time. ```yaml schedule_data: "1": # Workday morning (fixed time) weekdays: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY] time: "06:30" condition: fixed_time target_channels: ["1_1"] level: 0.8 # 80% brightness duration: 1min ramp_time: 10s astro_type: null astro_offset_minutes: 0 level_2: null "2": # Weekend morning (sunrise-based) weekdays: [SATURDAY, SUNDAY] time: "08:00" # Fallback time condition: fixed_if_after_astro # Use 08:00 if after sunrise, else sunrise astro_type: sunrise astro_offset_minutes: 30 # 30 minutes after sunrise target_channels: ["1_1"] level: 0.5 # 50% brightness duration: 30min ramp_time: 5s level_2: null ``` -------------------------------- ### create_client_instance method Source: https://sukramj.github.io/aiohomematic/reference/api/central?q= Creates a client for the given interface configuration. Implements ClientFactoryProtocol for dependency injection. ```python create_client_instance(*, interface_config: InterfaceConfig) -> ClientProtocol ``` -------------------------------- ### PR Title Format Examples Source: https://sukramj.github.io/aiohomematic/contributor/contributing Examples of conventional commit format for pull request titles. ```text feat(model): Add support for HmIP-NEW-DEVICE fix(client): Handle connection timeout gracefully docs: Update troubleshooting guide refactor(central): Simplify device discovery test: Add tests for week profile ``` -------------------------------- ### Data Class Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Examples of data class docstrings for central and interface configuration. ```python @dataclass class CentralConfig: """Configuration for central unit initialization.""" @dataclass class InterfaceConfig: """Configuration for a single interface connection.""" ``` -------------------------------- ### Initialize aiohomematic Central for CCU Source: https://sukramj.github.io/aiohomematic/faq Shows how to create a central instance for a CCU using CentralConfig.for_ccu, then iterate over devices. Requires host, username, and password. The async with block manages the connection lifecycle. ```python from aiohomematic.central import CentralConfig config = CentralConfig.for_ccu( host="192.168.1.100", username="Admin", password="secret", ) central = await config.create_central() async with central: for device in central.devices: print(f"{device.name}: {device.model}") ``` -------------------------------- ### Manual lifecycle management with start and stop Source: https://sukramj.github.io/aiohomematic/getting_started?q= Shows manual control over the lifecycle: create central, call start(), use devices, and finally stop() in a try/finally block. Useful when more control is needed than the context manager provides. ```python import asyncio from aiohomematic.central import CentralConfig async def main(): config = CentralConfig.for_ccu( name="my-ccu", host="192.168.1.100", username="Admin", password="your-password", central_id="my-ccu", ) central = await config.create_central() await central.start() try: for device in central.devices: print(f"{device.address}: {device.name}") finally: await central.stop() asyncio.run(main()) ``` -------------------------------- ### Starting and Stopping the Central Unit Source: https://sukramj.github.io/aiohomematic/reference/common_operations Shows how to create, start, and stop the central unit using CentralConfig.for_ccu. ```APIDOC ## Starting and Stopping the Central Unit ### Description Create and start the central unit with a CCU configuration, then stop it cleanly. ### Usage ```python from aiohomematic.central import CentralConfig async def main(): config = CentralConfig.for_ccu( host="192.168.1.100", username="Admin", password="secret", ) # Create and start the central unit central = await config.create_central() await central.start() # Your application logic here... # Clean shutdown await central.stop() ``` ### Parameters - **host** (string) - Required - The IP address or hostname of the CCU. - **username** (string) - Required - The username for authentication. - **password** (string) - Required - The password for authentication. ### Methods - **create_central()** - Creates the central unit instance. - **start()** - Starts the central unit and establishes connections. - **stop()** - Stops the central unit and cleans up resources. ``` -------------------------------- ### init_install_mode method signature Source: https://sukramj.github.io/aiohomematic/reference/api/central Async method signature to initialize install mode data points. Internal use - use hub_coordinator for external access. Returns a dict of InstallModeDpType by Interface. ```python init_install_mode() -> Mapping[Interface, InstallModeDpType] ``` -------------------------------- ### Anti-Pattern 2: Using ClientProtocol when only one operation group is needed Source: https://sukramj.github.io/aiohomematic/architecture/protocol_selection_guide Shows bad and good examples of client protocol usage. The bad example uses the full ClientProtocol when only reading values; the good example narrows to ValueAndParamsetOperationsProtocol. ```python # BAD: Full client when only reading values async def read_state(client: ClientProtocol) -> Any: return await client.get_value(...) # GOOD: Narrow to the specific operation protocol async def read_state(client: ValueAndParamsetOperationsProtocol) -> Any: return await client.get_value(...) ``` -------------------------------- ### Use session recorder with OptionalSettings.SR_RECORD_SYSTEM_INIT Source: https://sukramj.github.io/aiohomematic/contributor/dev-environment Configures the central instance to record RPC traffic for the first DEFAULT_SESSION_RECORDER_START_FOR_SECONDS after start() and saves it. Add SR_DISABLE_RANDOMIZE_OUTPUT to keep addresses. ```python from aiohomematic.const import OptionalSettings config = CentralConfig( ..., # Records the RPC traffic of the first DEFAULT_SESSION_RECORDER_START_FOR_SECONDS # after start() and saves it; add SR_DISABLE_RANDOMIZE_OUTPUT to keep addresses. optional_settings=(OptionalSettings.SR_RECORD_SYSTEM_INIT,), ) ``` -------------------------------- ### Basic usage of aiohomematic with asyncio Source: https://sukramj.github.io/aiohomematic Shows how to configure a central unit, start it, iterate over devices, and stop it. Uses CentralConfig, InterfaceConfig, and Interface.HMIP_RF. Requires a running Homematic central unit with the specified host, username, and password. ```python import asyncio from aiohomematic.central import CentralConfig from aiohomematic.client import InterfaceConfig from aiohomematic.const import Interface async def main(): # Configure the central unit config = CentralConfig( name="my-ccu", host="192.168.1.100", username="Admin", password="your-password", central_id="my-central", interface_configs={ InterfaceConfig( central_name="my-ccu", interface=Interface.HMIP_RF, port=2010, ), }, ) # Create and start the central central = config.create_central() await central.start() # Access devices for address, device in central.devices.items(): print(f"Device: {device.name} ({address})") # Stop the central await central.stop() asyncio.run(main()) ``` -------------------------------- ### Deprecation warning example Source: https://sukramj.github.io/aiohomematic/migrations?q= Example of a deprecation warning message that may appear in logs when using deprecated features. ```text DeprecationWarning: register_callback() is deprecated since 2025.11. Use event_bus.subscribe() instead. Will be removed in 2026.1. ``` -------------------------------- ### Test Class Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Examples of test class docstrings for specific components like DeviceCoordinator and CentralUnit. ```python class TestDeviceCoordinator: """Test suite for DeviceCoordinator.""" class TestCentralUnit: """Test suite for CentralUnit lifecycle.""" ``` -------------------------------- ### Test Module Docstring Examples Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_templates Examples of module-level docstrings for test files, each describing the module or feature under test. ```python """Tests for device coordinator functionality.""" """Tests for custom climate data points.""" """Tests for central unit lifecycle.""" ``` -------------------------------- ### Simple Constructor Docstrings Source: https://sukramj.github.io/aiohomematic/contributor/coding/docstring_standards Use for simple constructors with no or few parameters. Provide a one-line description. ```python def __init__(self) -> None: """Initialize the coordinator.""" ```