### Install and Run Python Matter Server Source: https://context7.com/matter-js/python-matter-server/llms.txt Provides commands for installing the server and client, starting the server with default or custom settings, and running it using Docker. ```bash # Install (server + client) pip install python-matter-server[server] # Start server with default settings (data in ./data, port 5580) python -m matter_server.server # Custom storage path, port, and log level python -m matter_server.server \ --storage-path /var/lib/matter \ --port 5580 \ --log-level info \ --log-level-sdk progress # Docker (stable) docker run --rm \ -v $(pwd)/data:/data \ --network host \ ghcr.io/home-assistant-libs/python-matter-server:stable \ --storage-path /data \ --paa-root-cert-dir /data/credentials # Client-only install (no native SDK dependencies) pip install python-matter-server ``` -------------------------------- ### Install Dependencies Source: https://github.com/matter-js/python-matter-server/blob/main/dashboard/README.md Run this script to install the necessary dependencies for the dashboard development. Ensure the Python Matter Server dependencies are also present. ```bash script/setup ``` -------------------------------- ### Install Python Client Library Source: https://github.com/matter-js/python-matter-server/blob/main/DEVELOPMENT.md Install only the Python client part of the library using pip. This is useful if you only need to interact with a running Matter server and not develop the server itself. ```bash pip install python-matter-server ``` -------------------------------- ### Start Listening Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Initiate server event forwarding, including node attribute changes, after dumping existing nodes. ```APIDOC ## Start Listening ### Description When the start_listening command is issued, the server will dump all existing nodes. From that moment on all events (including node attribute changes) will be forwarded. ### Command `start_listening` ### Request Example ```json { "message_id": "3", "command": "start_listening" } ``` ``` -------------------------------- ### MatterClient - Connecting and Listening Source: https://context7.com/matter-js/python-matter-server/llms.txt Demonstrates how to initialize the MatterClient, subscribe to events, and start listening for server updates. This is the primary entrypoint for Python consumers. ```APIDOC ## MatterClient.start_listening ### Description Initializes the MatterClient, connects to the WebSocket server, loads all nodes into an in-memory cache, and begins forwarding server events to registered callbacks. ### Method `async def start_listening()` ### Parameters None ### Request Example ```python import asyncio import aiohttp from matter_server.client.client import MatterClient from matter_server.common.models import EventType async def main(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) def on_event(event: EventType, data): print(f"[EVENT] {event.value}: {data}") unsubscribe = client.subscribe_events(on_event) try: await client.start_listening() finally: unsubscribe() await client.disconnect() asyncio.run(main()) ``` ### Response This method does not return a value directly but initiates background listening for events. ``` -------------------------------- ### Run Development Server Source: https://github.com/matter-js/python-matter-server/blob/main/dashboard/README.md Starts the development server for the Matter Dashboard. The dashboard will be accessible at http://localhost:5010 and will prompt for a websocket server URL. ```bash script/develop ``` -------------------------------- ### Start Matter Server with Info Log Level Source: https://github.com/matter-js/python-matter-server/blob/main/DEVELOPMENT.md Run the Matter server with the 'info' log level for general operational messages. This is the default logging configuration. ```bash python -m matter_server.server ``` -------------------------------- ### Python Script Example for Level Control Command Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Python snippet demonstrating how to construct a MoveToLevelWithOnOff command for the LevelControl cluster, used for adjusting brightness. ```python command = clusters.LevelControl.Commands.MoveToLevelWithOnOff( level=int(value), # provide a percentage transitionTime=0, # in seconds ) ``` -------------------------------- ### Start Matter Server with SDK Progress Logging Source: https://github.com/matter-js/python-matter-server/blob/main/DEVELOPMENT.md Run the Matter server with the 'progress' log level for the SDK to display detailed progress from the Matter SDK (C++). This is useful for monitoring the low-level Matter operations. ```bash python -m matter_server.server --log-level-sdk progress ``` -------------------------------- ### Device Command Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Send a command to a specific cluster on a Matter device. Example shows turning on a switch. ```APIDOC ## Device Command ### Description Send a command to a specific cluster on a Matter device. ### Command `device_command` ### Arguments - **endpoint_id** (integer) - Required - The ID of the endpoint. - **node_id** (integer) - Required - The ID of the node. - **payload** (object) - Required - The command payload. - **cluster_id** (integer) - Required - The ID of the cluster. - **command_name** (string) - Required - The name of the command. ### Request Example (Turning on a switch) ```json { "message_id": "example", "command": "device_command", "args": { "endpoint_id": 1, "node_id": 1, "payload": {}, "cluster_id": 6, "command_name": "On" } } ``` ### Python Script Example (Turning on a switch) ```python import json from chip.clusters import Objects as clusters from matter_server.common.helpers.util import dataclass_from_dict, dataclass_to_dict command = clusters.OnOff.Commands.On() payload = dataclass_to_dict(command) messsage = { "message_id": "example", "command": "device_command", "args": { "endpoint_id": 1, "node_id": 1, "payload": payload, "cluster_id": command.cluster_id, "command_name": "On" } } print(json.dumps(message, indent=2)) ``` ### Python Script Example (Move to Level with OnOff) ```python # Example for LevelControl cluster command = clusters.LevelControl.Commands.MoveToLevelWithOnOff( level=int(value), # provide a percentage transitionTime=0, # in seconds ) ``` ``` -------------------------------- ### Connect and Listen for Events with MatterClient Source: https://context7.com/matter-js/python-matter-server/llms.txt Use MatterClient to establish a WebSocket connection, subscribe to all events, and start listening for server updates. Ensure to unsubscribe and disconnect when done. ```python import asyncio import aiohttp from matter_server.client.client import MatterClient from matter_server.common.models import EventType async def main(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) # Subscribe to ALL events before connecting def on_event(event: EventType, data): print(f"[EVENT] {event.value}: {data}") unsubscribe = client.subscribe_events(on_event) # start_listening connects, loads all nodes, then keeps reading try: await client.start_listening() finally: unsubscribe() await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### Start Matter Server with Debug Log Level Source: https://github.com/matter-js/python-matter-server/blob/main/DEVELOPMENT.md Run the Matter server with the 'debug' log level to enable verbose logging for troubleshooting. This provides more detailed information about the server's internal operations. ```bash python -m matter_server.server --log-level debug ``` -------------------------------- ### Start Listening for Events via Websocket Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Initiate event listening. The server will dump existing nodes and forward all subsequent events, including attribute changes. ```json { "message_id": "3", "command": "start_listening" } ``` -------------------------------- ### Read Attribute Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Read a specific attribute from a Matter device. Example shows reading the OnOff attribute. ```APIDOC ## Read Attribute ### Description Read a specific attribute from a Matter device. ### Command `read_attribute` ### Arguments - **node_id** (integer) - Required - The ID of the node. - **attribute_path** (string) - Required - The path to the attribute (e.g., "1/6/0"). ### Request Example ```json { "message_id": "read", "command": "read_attribute", "args": { "node_id": 1, "attribute_path": "1/6/0" } } ``` ``` -------------------------------- ### Interact with Matter Server via WebSocket API Source: https://context7.com/matter-js/python-matter-server/llms.txt Demonstrates raw JSON protocol communication over WebSockets for various Matter operations including starting listening, setting Wi-Fi credentials, commissioning, reading/writing attributes, and controlling devices. Use `wscat` or a similar client to connect. ```bash # Connect and start listening (receives all nodes + live events) wscat -c ws://localhost:5580/ws # After receiving the ServerInfoMessage, send: {"message_id": "1", "command": "start_listening"} # Set WiFi credentials {"message_id":"2","command":"set_wifi_credentials","args":{"ssid":"MyNet","credentials":"pass"}} # Commission via QR code {"message_id":"3","command":"commission_with_code","args":{"code":"MT:Y.ABCDEFG123456789"}} # Read OnOff attribute on node 1, endpoint 1 (cluster 6, attr 0) {"message_id":"4","command":"read_attribute","args":{"node_id":1,"attribute_path":"1/6/0"}} # Response: {"message_id":"4","result":{"1/6/0":true}} # Turn on a light (OnOff cluster, command On) {"message_id":"5","command":"device_command","args":{"node_id":1,"endpoint_id":1,"cluster_id":6,"command_name":"On","payload":{}}} # Write an attribute (OnTime = 30 tenths of a second) {"message_id":"6","command":"write_attribute","args":{"node_id":1,"attribute_path":"1/6/16385","value":30}} # Ping a node {"message_id":"7","command":"ping_node","args":{"node_id":1}} # Response: {"message_id":"7","result":{"192.168.1.42":true}} # Remove a node from the fabric {"message_id":"8","command":"remove_node","args":{"node_id":1}} # Server event example (pushed by server, no message_id echo): # {"event":"attribute_updated","data":[1,"1/6/0",false]} ``` -------------------------------- ### Get Node Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Retrieve detailed information about a specific commissioned node. ```APIDOC ## Get Node ### Description Get info of a single Node. ### Command `get_node` ### Arguments - **node_id** (integer) - Required - The ID of the node to retrieve information for. ### Request Example ```json { "message_id": "2", "command": "get_node", "args": { "node_id": 1 } } ``` ``` -------------------------------- ### Get Nodes Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Retrieve a list of all nodes currently commissioned on the controller. ```APIDOC ## Get Nodes ### Description Get all nodes already commissioned on the controller. ### Command `get_nodes` ### Request Example ```json { "message_id": "2", "command": "get_nodes" } ``` ``` -------------------------------- ### Get All Commissioned Nodes via Websocket Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Retrieve a list of all nodes that have already been commissioned on the controller. ```json { "message_id": "2", "command": "get_nodes" } ``` -------------------------------- ### Run Matter Server Docker Container Source: https://github.com/matter-js/python-matter-server/blob/main/docs/docker.md This command starts the Matter Server in a detached Docker container, ensuring it restarts automatically unless stopped. It maps a local 'data' directory for storing network fabric information and uses host networking for better compatibility. ```bash mkdir data docker run -d \ --name matter-server \ --restart=unless-stopped \ --security-opt apparmor=unconfined \ -v $(pwd)/data:/data \ --network=host \ ghcr.io/matter-js/python-matter-server:stable ``` -------------------------------- ### Get Single Node Info via Websocket Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Retrieve detailed information about a specific node commissioned on the controller. ```json { "message_id": "2", "command": "get_node", "args": { "node_id": 1 } } ``` -------------------------------- ### Subscribe to Matter Server Events Source: https://context7.com/matter-js/python-matter-server/llms.txt Registers callbacks for server and node events with optional filters for event type, node ID, or attribute path. Attribute-change events are only delivered for attributes the server is subscribed to. Ensure the client is started with `client.start_listening()` before subscribing. ```python import asyncio import aiohttp from matter_server.client.client import MatterClient from matter_server.common.models import EventType async def watch_events(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) received = [] # Watch only attribute updates for node 1 unsub_attr = client.subscribe_events( lambda evt, data: received.append(("attr", data)), event_filter=EventType.ATTRIBUTE_UPDATED, node_filter=1, ) # Watch availability changes for any node unsub_avail = client.subscribe_events( lambda evt, data: print(f"Node {data.node_id} available={data.available}"), event_filter=EventType.NODE_UPDATED, ) # Watch a specific attribute path (e.g., OnOff on endpoint 1) unsub_onoff = client.subscribe_events( lambda evt, data: print(f"OnOff changed to: {data}"), event_filter=EventType.ATTRIBUTE_UPDATED, node_filter=1, attr_path_filter="1/6/0", ) init_ready = asyncio.Event() try: await client.start_listening(init_ready=init_ready) finally: unsub_attr() unsub_avail() unsub_onoff() asyncio.run(watch_events()) ``` -------------------------------- ### Write Attribute Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Write a new value to a specific attribute on a Matter device. Example shows writing the OnTime attribute. ```APIDOC ## Write Attribute ### Description Write a new value to a specific attribute on a Matter device. ### Command `write_attribute` ### Arguments - **node_id** (integer) - Required - The ID of the node. - **attribute_path** (string) - Required - The path to the attribute (e.g., "1/6/16385"). - **value** (any) - Required - The new value to write to the attribute. ### Request Example ```json { "message_id": "write", "command": "write_attribute", "args": { "node_id": 1, "attribute_path": "1/6/16385", "value": 10 } } ``` ``` -------------------------------- ### Open Commissioning Window for Device Sharing Source: https://context7.com/matter-js/python-matter-server/llms.txt Opens a commissioning window on an already-commissioned node to allow a second controller to pair with it. Returns `CommissioningParameters` containing QR code and manual pairing details. Ensure the client is connected before opening the window. ```python import asyncio import aiohttp from matter_server.client.client import MatterClient async def share_device(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) await client.connect() params = await client.open_commissioning_window( node_id=1, timeout=300, # seconds the window stays open iteration=1000, option=1, # 1 = Enhanced Commissioning Method (ECM) ) print(f"QR Code: {params.setup_qr_code}") print(f"Manual Code: {params.setup_manual_code}") print(f"Pin: {params.setup_pin_code}") # QR Code: MT:Y.K9058NQ31180BI.510G00 # Manual Code: 71975309 # Pin: 12345678 await client.disconnect() asyncio.run(share_device()) ``` -------------------------------- ### Set Wi-Fi or Thread Credentials with MatterClient Source: https://context7.com/matter-js/python-matter-server/llms.txt Configure network credentials before commissioning devices. This action broadcasts a SERVER_INFO_UPDATED event. ```python import asyncio import aiohttp from matter_server.client.client import MatterClient async def setup_credentials(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) await client.connect() # Wi-Fi credentials (for Wi-Fi based Matter devices) await client.set_wifi_credentials(ssid="MyHomeNetwork", credentials="s3cr3tP@ss") # Thread Operational Dataset (for Thread-based devices, hex-encoded TLV) await client.set_thread_operational_dataset( dataset="0e080000000000010000000300001235060004001fffe0020811111111222222220708fd112233aabbccdd051000112233445566778899aabbccddeeff030e4f70656e54687265616444656d6f01021234" ) print(f"Credentials set. Server info: {client.server_info}") await client.disconnect() asyncio.run(setup_credentials()) ``` -------------------------------- ### MatterClient.open_commissioning_window Source: https://context7.com/matter-js/python-matter-server/llms.txt Opens a commissioning window on an already-commissioned node so a second controller can pair with it. Returns CommissioningParameters containing the QR code and manual pairing code to share with the secondary controller. ```APIDOC ## MatterClient.open_commissioning_window ### Description Opens a commissioning window on an already-commissioned node so a second controller can pair with it. Returns `CommissioningParameters` containing the QR code and manual pairing code to share with the secondary controller. ### Method ```python client.open_commissioning_window( node_id: int, timeout: int = 180, iteration: int = 1000, option: int = 1, ) ``` ### Parameters - **node_id** (int) - Required - The ID of the node to open the commissioning window on. - **timeout** (int) - Optional - The duration in seconds the window stays open. Defaults to 180. - **iteration** (int) - Optional - The iteration count for the pairing process. Defaults to 1000. - **option** (int) - Optional - The commissioning option. `1` for Enhanced Commissioning Method (ECM). Defaults to 1. ### Returns - `CommissioningParameters` - An object containing `setup_qr_code`, `setup_manual_code`, and `setup_pin_code`. ``` -------------------------------- ### Run Matter Server with Bluetooth Support Source: https://github.com/matter-js/python-matter-server/blob/main/docs/docker.md This command runs the Matter Server Docker container with additional configurations for local commissioning via Bluetooth. It mounts the D-Bus socket and specifies paths for storage and PAA root certificates, along with the Bluetooth adapter. ```bash docker run -d \ --name matter-server \ --restart=unless-stopped \ --security-opt apparmor=unconfined \ -v $(pwd)/data:/data \ -v /run/dbus:/run/dbus:ro \ --network=host \ ghcr.io/matter-js/python-matter-server:stable --storage-path /data --paa-root-cert-dir /data/credentials --bluetooth-adapter 0 ``` -------------------------------- ### Robust Matter Client with Error Handling Source: https://context7.com/matter-js/python-matter-server/llms.txt Shows how to use the MatterClient with aiohttp, connecting to the server, and handling various Matter-specific exceptions like NodeNotExists, NodeNotReady, and NodeCommissionFailed. ```python import asyncio import aiohttp from matter_server.client.client import MatterClient from matter_server.common.errors import ( NodeNotExists, NodeNotReady, NodeCommissionFailed, NodeInterviewFailed, NodeNotResolving, InvalidArguments, UpdateCheckError, UpdateError, SDKStackError, ) async def robust_client(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) await client.connect() try: node = client.get_node(999) # raises NodeNotExists (client-side) except NodeNotExists as exc: print(f"No such node: {exc}") try: await client.send_device_command( 999, 1, __import__("chip.clusters", fromlist=["Objects"]).Objects.OnOff.Commands.On() ) except NodeNotReady as exc: print(f"Node unavailable: {exc}") # error_code=3 from server except NodeNotExists as exc: print(f"Node missing: {exc}") # error_code=5 try: await client.commission_with_code("BADCODE") except NodeCommissionFailed as exc: print(f"Commission failed: {exc}") # error_code=1 except SDKStackError as exc: print(f"SDK error: {exc}") # error_code=7 await client.disconnect() asyncio.run(robust_client()) ``` -------------------------------- ### Python Script to Send OnOff Command Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Python script using Matter SDK datamodels to construct and send an 'On' command for the OnOff cluster. ```python import json # Import the CHIP clusters from chip.clusters import Objects as clusters # Import the ability to turn objects into dictionaries, and vice-versa from matter_server.common.helpers.util import dataclass_from_dict,dataclass_to_dict command = clusters.OnOff.Commands.On() payload = dataclass_to_dict(command) message = { "message_id": "example", "command": "device_command", "args": { "endpoint_id": 1, "node_id": 1, "payload": payload, "cluster_id": command.cluster_id, "command_name": "On" } } print(json.dumps(message, indent=2)) ``` -------------------------------- ### Commission Device with QR or Pairing Code using MatterClient Source: https://context7.com/matter-js/python-matter-server/llms.txt Commission a new Matter device using either a QR code string or a manual pairing code. For Wi-Fi and Thread devices, ensure credentials are set first. Handles potential commissioning failures. ```python import asyncio import aiohttp from matter_server.client.client import MatterClient from matter_server.common.errors import NodeCommissionFailed async def commission(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) await client.connect() try: # Commission via QR code (Bluetooth + network discovery) node_data = await client.commission_with_code("MT:Y.ABCDEFG123456789") print(f"Commissioned node_id={node_data.node_id}") # Or restrict to network-only (no Bluetooth required) node_data = await client.commission_with_code( "35325335079", network_only=True ) print(f"Node commissioned: {node_data.node_id}, " f"available={node_data.available}, " f"bridge={node_data.is_bridge}") except NodeCommissionFailed as exc: print(f"Commission failed: {exc}") finally: await client.disconnect() asyncio.run(commission()) ``` -------------------------------- ### Build Production Source: https://github.com/matter-js/python-matter-server/blob/main/dashboard/README.md Generates the production build of the Matter Dashboard. The output is placed in the matter_server folder for the Python Matter Server's webserver. ```bash script/build ``` -------------------------------- ### Configure IPv6 Route Information Options Source: https://github.com/matter-js/python-matter-server/blob/main/docs/os_requirements.md When not using NetworkManager or systemd-networkd, configure these sysctl variables for the kernel's IPv6 Neighbor Discovery Protocol handling. Ensure CONFIG_IPV6_ROUTE_INFO is enabled. ```sh sysctl -w net.ipv6.conf.wlan0.accept_ra=1 sysctl -w net.ipv6.conf.wlan0.accept_ra_rt_info_max_plen=64 ``` -------------------------------- ### Commission with Code Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Commission a new device. Supports both QR-code syntax and manual pairing code. For WiFi or Thread devices, credentials must be set upfront. ```APIDOC ## Commission with Code ### Description Commission a new device. Supports both QR-code syntax (MT:...) and manual pairing code as string. For WiFi or Thread based devices, the credentials need to be set upfront, otherwise, commissioning will fail. The controller will use Bluetooth for the commissioning of wireless devices. ### Command `commission_with_code` ### Arguments - **code** (string) - Required - The Matter QR-code or manual pairing code. - **network_only** (boolean) - Optional - If true, only use network for commissioning. ### Request Example (QR-code) ```json { "message_id": "2", "command": "commission_with_code", "args": { "code": "MT:Y.ABCDEFG123456789" } } ``` ### Request Example (Manual Pairing Code) ```json { "message_id": "2", "command": "commission_with_code", "args": { "code": "35325335079", "network_only": true } } ``` ``` -------------------------------- ### Open Commissioning Window via Websocket Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Open a commissioning window to commission a device present on this controller to another. Returns a code to use as a discriminator. ```json { "message_id": "2", "command": "open_commissioning_window", "args": { "node_id": 1 } } ``` -------------------------------- ### MatterClient.commission_with_code - Commissioning a Device Source: https://context7.com/matter-js/python-matter-server/llms.txt Details the process of commissioning a new Matter device into the fabric using either a QR code string or a manual pairing code. It returns `MatterNodeData` upon successful completion of the post-commission interview. ```APIDOC ## MatterClient.commission_with_code ### Description Commissions a new device into the Matter fabric using a QR code string (e.g., `MT:…`) or a numeric manual pairing code. For Wi-Fi and Thread devices, network credentials must be set beforehand. Returns a `MatterNodeData` dataclass upon successful completion of the full post-commission interview. ### Method `async def commission_with_code(code: str, network_only: bool = False)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **code** (str) - Required - The QR code string (e.g., `MT:Y.ABCDEFG123456789`) or manual pairing code (e.g., `35325335079`). - **network_only** (bool) - Optional - If `True`, commissioning will be restricted to network-only, bypassing Bluetooth discovery. Defaults to `False`. ### Request Example ```python import asyncio import aiohttp from matter_server.client.client import MatterClient from matter_server.common.errors import NodeCommissionFailed async def commission(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) await client.connect() try: # Commission via QR code (Bluetooth + network discovery) node_data = await client.commission_with_code("MT:Y.ABCDEFG123456789") print(f"Commissioned node_id={node_data.node_id}") # Or restrict to network-only (no Bluetooth required) node_data = await client.commission_with_code( "35325335079", network_only=True ) print(f"Node commissioned: {node_data.node_id}, " f"available={node_data.available}, " f"bridge={node_data.is_bridge}") except NodeCommissionFailed as exc: print(f"Commission failed: {exc}") finally: await client.disconnect() asyncio.run(commission()) ``` ### Response #### Success Response (200) - **MatterNodeData** (dataclass) - Contains information about the commissioned node, including `node_id`, `available`, and `is_bridge`. #### Response Example ```json { "node_id": 1, "available": true, "is_bridge": false } ``` ### Error Handling - **NodeCommissionFailed**: Raised if the commissioning process fails. ``` -------------------------------- ### Open Commissioning Window Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Open a commissioning window to commission a device present on this controller to another. Returns a code to use as a discriminator. ```APIDOC ## Open Commissioning Window ### Description Open a commissioning window to commission a device present on this controller to another. Returns code to use as discriminator. ### Command `open_commissioning_window` ### Arguments - **node_id** (integer) - Required - The ID of the node to open a commissioning window for. ### Request Example ```json { "message_id": "2", "command": "open_commissioning_window", "args": { "node_id": 1 } } ``` ``` -------------------------------- ### Docker Compose for Matter Server Source: https://github.com/matter-js/python-matter-server/blob/main/docs/docker.md This Docker Compose configuration defines a service for the Matter Server. It includes settings for automatic restarts, host networking, security options for Bluetooth, and volume mounts for data persistence and D-Bus access. ```yaml services: # python-matter-server matter-server: image: ghcr.io/matter-js/python-matter-server:stable container_name: matter-server restart: unless-stopped # Required for mDNS to work correctly network_mode: host security_opt: # Needed for Bluetooth via dbus - apparmor:unconfined volumes: # Create an .env file that sets the USERDIR environment variable. - ${USERDIR:-$HOME}/docker/matter-server/data:/data/ # Required for Bluetooth via D-Bus - /run/dbus:/run/dbus:ro # If you adjust command line, make sure to pass the default CMD arguments too: #command: --storage-path /data --paa-root-cert-dir /data/credentials --bluetooth-adapter 0 ``` -------------------------------- ### Perform OTA Firmware Update for a Node Source: https://context7.com/matter-js/python-matter-server/llms.txt Checks for available firmware updates for a specified node and initiates an over-the-air update if an update is found. Requires a running Matter server and a connected node. ```python import asyncio import aiohttp from matter_server.client.client import MatterClient async def ota_update(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) await client.connect() node_id = 1 update = await client.check_node_update(node_id) if update is None: print("Node is up to date.") else: print(f"Update available: {update.software_version_string} " f"(v{update.software_version}) from {update.update_source.value}") if update.release_notes_url: print(f"Release notes: {update.release_notes_url}") # Apply the update await client.update_node(node_id, update.software_version) print("OTA update initiated.") await client.disconnect() asyncio.run(ota_update()) ``` -------------------------------- ### Deserialize and Serialize Matter Node Data Source: https://context7.com/matter-js/python-matter-server/llms.txt Demonstrates deserializing raw dictionary data into a MatterNodeData dataclass and then serializing it back to a dictionary. Shows how strict mode handles unknown fields. ```python raw = { "node_id": 1, "date_commissioned": "2024-03-15T10:00:00", "last_interview": "2024-03-15T10:01:00", "interview_version": 6, "available": True, "is_bridge": False, "attributes": {"0/40/17": "MyDevice"}, "attribute_subscriptions": [], } node_data = dataclass_from_dict(MatterNodeData, raw) print(node_data.node_id, node_data.available) # 1 True print(node_data.date_commissioned) # 2024-03-15 10:00:00 d = dataclass_to_dict(node_data) assert d["node_id"] == 1 try: dataclass_from_dict(MatterNodeData, {**raw, "unknown_field": "oops"}, strict=True) except KeyError as exc: print(f"Unexpected field: {exc}") # Unexpected field: "Extra key(s) unknown_field not allowed for ..." ``` -------------------------------- ### Set WiFi Credentials via Websocket Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Inform the controller about WiFi credentials for commissioning new devices. Ensure the SSID and password are correct. ```json { "message_id": "1", "command": "set_wifi_credentials", "args": { "ssid": "wifi-name-here", "credentials": "wifi-password-here" } } ``` -------------------------------- ### Send Device Commands with MatterClient Source: https://context7.com/matter-js/python-matter-server/llms.txt Send Matter cluster commands to a specific node endpoint. Handles potential NodeNotReady exceptions. ```python import asyncio import aiohttp from chip.clusters import Objects as Clusters from matter_server.client.client import MatterClient from matter_server.common.errors import NodeNotReady async def control_light(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) await client.connect() try: node_id, endpoint_id = 1, 1 # Turn on await client.send_device_command( node_id, endpoint_id, Clusters.OnOff.Commands.On() ) # Set brightness to 50% with 1-second transition await client.send_device_command( node_id, endpoint_id, Clusters.LevelControl.Commands.MoveToLevelWithOnOff( level=127, # 0-254 transitionTime=10, # 10ths of a second optionsMask=0, optionsOverride=0, ) ) # Set color temperature (in mireds) await client.send_device_command( node_id, endpoint_id, Clusters.ColorControl.Commands.MoveToColorTemperature( colorTemperatureMireds=370, transitionTime=0, optionsMask=0, optionsOverride=0, ) ) except NodeNotReady as exc: print(f"Node not available: {exc}") finally: await client.disconnect() asyncio.run(control_light()) ``` -------------------------------- ### Set WiFi Credentials Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Inform the controller about the WiFi credentials it needs to send when commissioning a new device. ```APIDOC ## Set WiFi Credentials ### Description Inform the controller about the WiFi credentials it needs to send when commissioning a new device. ### Command `set_wifi_credentials` ### Arguments - **ssid** (string) - Required - The SSID of the WiFi network. - **credentials** (string) - Required - The password for the WiFi network. ### Request Example ```json { "message_id": "1", "command": "set_wifi_credentials", "args": { "ssid": "wifi-name-here", "credentials": "wifi-password-here" } } ``` ``` -------------------------------- ### Commission Device with QR Code via Websocket Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Commission a new device using a Matter QR-code. Ensure WiFi or Thread credentials are set beforehand. Uses Bluetooth for wireless devices. ```json { "message_id": "2", "command": "commission_with_code", "args": { "code": "MT:Y.ABCDEFG123456789" } } ``` -------------------------------- ### Commission Device with Manual Code via Websocket Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Commission a new device using a manual pairing code. Set `network_only` to true if only network commissioning is desired. WiFi or Thread credentials must be set upfront. ```json { "message_id": "2", "command": "commission_with_code", "args": { "code": "35325335079", "network_only": true } } ``` -------------------------------- ### Set Thread Dataset via Websocket Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Inform the controller about Thread credentials for commissioning new devices. Provide the dataset string. ```json { "message_id": "1", "command": "set_thread_dataset", "args": { "dataset": "put-credentials-here" } } ``` -------------------------------- ### Set Thread Dataset Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Inform the controller about the Thread credentials it needs to use when commissioning a new device. ```APIDOC ## Set Thread Dataset ### Description Inform the controller about the Thread credentials it needs to use when commissioning a new device. ### Command `set_thread_dataset` ### Arguments - **dataset** (string) - Required - The Thread dataset credentials. ### Request Example ```json { "message_id": "1", "command": "set_thread_dataset", "args": { "dataset": "put-credentials-here" } } ``` ``` -------------------------------- ### MatterClient.set_wifi_credentials / set_thread_operational_dataset Source: https://context7.com/matter-js/python-matter-server/llms.txt Sets Wi-Fi SSID/password or a Thread Operational Dataset hex string in the controller stack. This must be called before commissioning any wireless device and broadcasts a SERVER_INFO_UPDATED event. ```APIDOC ## MatterClient.set_wifi_credentials / set_thread_operational_dataset — network credentials Sets Wi-Fi SSID/password or a Thread Operational Dataset hex string in the controller stack. Must be called before commissioning any wireless device. Causes a `SERVER_INFO_UPDATED` event to be broadcast to all listeners. ### Method ```python await client.set_wifi_credentials(ssid: str, credentials: str) await client.set_thread_operational_dataset(dataset: str) ``` ### Parameters #### `set_wifi_credentials` - **ssid** (str) - Required - The Wi-Fi network SSID. - **credentials** (str) - Required - The Wi-Fi network password. #### `set_thread_operational_dataset` - **dataset** (str) - Required - The Thread Operational Dataset in hex-encoded TLV format. ### Request Example ```python # Wi-Fi credentials await client.set_wifi_credentials(ssid="MyHomeNetwork", credentials="s3cr3tP@ss") # Thread Operational Dataset await client.set_thread_operational_dataset(dataset="0e080000000000010000000300001235060004001fffe0020811111111222222220708fd112233aabbccdd051000112233445566778899aabbccddeeff030e4f70656e54687265616444656d6f01021234") ``` ### Response This method does not return a value directly but triggers a `SERVER_INFO_UPDATED` event. ``` -------------------------------- ### Increase IPv4 Group Limits for Network Issues Source: https://github.com/matter-js/python-matter-server/blob/main/DEVELOPMENT.md If you encounter 'OSError: [Errno 105] No buffer space available.', increase the IPv4 group limits by modifying sysctl configuration. This requires root privileges. ```bash echo "net.ipv4.igmp_max_memberships=1024" | sudo tee -a /etc/sysctl.d/local.conf sudo service procps force-reload ``` -------------------------------- ### Send Device Command via Websocket Source: https://github.com/matter-js/python-matter-server/blob/main/docs/websockets_api.md Send a command to a device. Specify endpoint ID, node ID, cluster ID, command name, and payload. ```json { "message_id": "example", "command": "device_command", "args": { "endpoint_id": 1, "node_id": 1, "payload": {}, "cluster_id": 6, "command_name": "On" } } ``` -------------------------------- ### MatterClient.send_device_command Source: https://context7.com/matter-js/python-matter-server/llms.txt Sends any Matter cluster command to a specific node endpoint. The command argument is an instantiated CHIP SDK ClusterCommand dataclass. Returns the command response (if any) or None. ```APIDOC ## MatterClient.send_device_command — sending a cluster command to a node Sends any Matter cluster command to a specific node endpoint. The `command` argument is an instantiated CHIP SDK `ClusterCommand` dataclass. Returns the command response (if any) or `None`. ### Method ```python await client.send_device_command(node_id: int, endpoint_id: int, command: ClusterCommand) ``` ### Parameters - **node_id** (int) - Required - The ID of the target node. - **endpoint_id** (int) - Required - The ID of the target endpoint on the node. - **command** (ClusterCommand) - Required - An instantiated CHIP SDK ClusterCommand dataclass representing the command to send. ### Request Example ```python # Turn on the light await client.send_device_command(node_id, endpoint_id, Clusters.OnOff.Commands.On()) # Set brightness to 50% with 1-second transition await client.send_device_command( node_id, endpoint_id, Clusters.LevelControl.Commands.MoveToLevelWithOnOff( level=127, # 0-254 transitionTime=10, # 10ths of a second optionsMask=0, optionsOverride=0, ) ) # Set color temperature await client.send_device_command( node_id, endpoint_id, Clusters.ColorControl.Commands.MoveToColorTemperature( colorTemperatureMireds=370, transitionTime=0, optionsMask=0, optionsOverride=0, ) ) ``` ### Response - **response** (Any | None) - The response from the command, if any, or None if no response is expected or received. ``` -------------------------------- ### MatterClient.ping_node / get_node_ip_addresses / node_diagnostics Source: https://context7.com/matter-js/python-matter-server/llms.txt Performs network diagnostics on a node, including pinging it on all known IP addresses and retrieving detailed network information. ```APIDOC ## MatterClient.ping_node / get_node_ip_addresses — network diagnostics Pings a node on all its known IP addresses (IPv4 and IPv6) and returns a `dict[str, bool]` indicating reachability per address. `get_node_ip_addresses` queries mDNS and returns the current address list. ### Method Asynchronous Python function calls. ### Parameters - **node_id** (int) - Required - The ID of the node to diagnose. - **prefer_cache** (bool) - Optional - If true, prefers cached IP addresses. ### Request Example ```python addresses = await client.get_node_ip_addresses(node_id) ping_results = await client.ping_node(node_id) diagnostics = await client.node_diagnostics(node_id) ``` ### Response - **get_node_ip_addresses** - Returns a list of IP addresses associated with the node. - **ping_node** - Returns a dictionary mapping IP addresses to their reachability status (boolean). - **node_diagnostics** - Returns a structured object with network type, node type, network name, and MAC address. ``` -------------------------------- ### WebSocket API - Raw JSON Protocol Source: https://context7.com/matter-js/python-matter-server/llms.txt Allows direct communication with the Matter-JS Python Server over WebSockets using a JSON-based protocol. Supports various commands for device control, configuration, and diagnostics. ```APIDOC ## WebSocket API — raw JSON protocol Any language can communicate with the server directly over WebSockets. Every message is a JSON object. On connect the server sends a `ServerInfoMessage`; clients then send `CommandMessage` objects and receive result or event messages. ### Method WebSocket connection with JSON messages. ### Commands - **start_listening**: Begin receiving node and event updates. - **set_wifi_credentials**: Configure WiFi network settings. - **commission_with_code**: Commission a device using a provisioning code. - **read_attribute**: Read a specific node attribute. - **device_command**: Send a command to a device endpoint. - **write_attribute**: Write a value to a node attribute. - **ping_node**: Ping a specific node. - **remove_node**: Remove a node from the fabric. ### Parameters Parameters vary per command. Examples: - `node_id` (int) - `attribute_path` (string) - `ssid` (string) - `credentials` (string) - `code` (string) - `endpoint_id` (int) - `cluster_id` (int) - `command_name` (string) - `payload` (object) - `value` (any) ### Request Example ```json { "message_id": "4", "command": "read_attribute", "args": { "node_id": 1, "attribute_path": "1/6/0" } } ``` ### Response Example ```json { "message_id": "4", "result": { "1/6/0": true } } ``` ### Events - **attribute_updated**: Server push indicating an attribute has been updated. ``` -------------------------------- ### Read and Write Attributes with MatterClient Source: https://context7.com/matter-js/python-matter-server/llms.txt Directly access cluster attributes using an endpoint/cluster/attribute path. Supports wildcards for reading multiple attributes. ```python import asyncio import aiohttp from matter_server.client.client import MatterClient async def rw_attributes(): async with aiohttp.ClientSession() as session: client = MatterClient("ws://localhost:5580/ws", session) await client.connect() node_id = 1 # Read the OnOff state from endpoint 1, cluster 6 (OnOff), attribute 0 (OnOff) values = await client.read_attribute(node_id, "1/6/0") print("OnOff state:", values) # {'1/6/0': True} # Read multiple attributes at once values = await client.read_attribute(node_id, ["1/6/0", "1/8/0"]) print("Batch read:", values) # {'1/6/0': True, '1/8/0': 200} # Read all attributes on endpoint 1 using wildcard all_ep1 = await client.read_attribute(node_id, "1/*/*") print(f"Endpoint 1 attributes: {len(all_ep1)} entries") # Write the OnTime attribute (cluster 6, attribute 0x4001 = 16385) await client.write_attribute(node_id, "1/6/16385", 30) # 30 x 0.1s = 3s await client.disconnect() asyncio.run(rw_attributes()) ``` -------------------------------- ### MatterClient.subscribe_events Source: https://context7.com/matter-js/python-matter-server/llms.txt Registers a callback for server and node events with optional filters for event type, node ID, or attribute path. Returns an unsubscribe callable. ```APIDOC ## MatterClient.subscribe_events ### Description Registers a callback for server and node events with optional filters for event type, node ID, or attribute path. Returns an unsubscribe callable. Attribute-change events (`ATTRIBUTE_UPDATED`) are only delivered for attributes that the server is subscribed to. ### Method ```python client.subscribe_events( callback: Callable[[EventType, Any], None], event_filter: Optional[EventType] = None, node_filter: Optional[int] = None, attr_path_filter: Optional[str] = None, ) ``` ### Parameters - **callback** (Callable[[EventType, Any], None]) - Required - The function to call when an event matches the filters. - **event_filter** (Optional[EventType]) - Optional - Filters events by type (e.g., `EventType.ATTRIBUTE_UPDATED`). - **node_filter** (Optional[int]) - Optional - Filters events by node ID. - **attr_path_filter** (Optional[str]) - Optional - Filters `ATTRIBUTE_UPDATED` events by attribute path (e.g., "1/6/0"). ### Returns - Callable - A function that can be called to unsubscribe from events. ```