Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Aioshelly
https://github.com/home-assistant-libs/aioshelly
Admin
Aioshelly is an asynchronous library to control Shelly devices.
Tokens:
101,993
Snippets:
662
Trust Score:
8
License:
Apache-2.0
Update:
1 month ago
Context
Chat
Benchmark
75
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Script usage example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Shows a minimal usage sequence: create a script, put its code, and start it. ```python await device.script_create("my_script") await device.script_putcode(1, "print('hello')") await device.script_start(1) ``` -------------------------------- ### Show example script usage help Source: https://github.com/home-assistant-libs/aioshelly/blob/main/README.md Displays usage help for the example script. ```bash python3 tools/example.py -h ``` -------------------------------- ### Usage example for component setters/getters Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Example calls to several component methods on the device object. Shows how to turn a switch on, set a cover position, set a climate target temperature, and get the cover status. ```python await device.switch_set(0, True) # turn switch 0 on await device.cover_set_position(0, pos=50) await device.climate_set_target_temperature(0, 21.5) print(await device.cover_get_status(0)) ``` -------------------------------- ### Run example script to connect to all devices in devices.json Source: https://github.com/home-assistant-libs/aioshelly/blob/main/README.md Runs the example script to connect to all devices listed in devices.json at once and print their status. ```bash python3 tools/example.py -d -i ``` -------------------------------- ### Install aioshelly from source with pip Source: https://github.com/home-assistant-libs/aioshelly/blob/main/README.md Installs the library from the source directory, upgrading any existing installation. Run inside the repository folder. ```bash pip install --upgrade . ``` -------------------------------- ### async_start_scanner(device, active, event_type, data_version) Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/ble.md Starts the BLE scanner on the device. Creates the script if missing, substitutes variables into the script code, writes it only when the installed code differs, and starts the script. ```APIDOC ## async_start_scanner(device, active, event_type, data_version) ### Description Starts the BLE scanner on the device. Creates the script if missing, substitutes variables into the script code, writes it only when the installed code differs, and starts the script. ### Method async_start_scanner ### Parameters - **device** (RpcDevice) - Required - The RPC device instance. - **active** (bool) - Required - Whether the scanner should be in active mode. - **event_type** (str) - Required - The event type to emit scan results. - **data_version** (int) - Required - The version of the scan result data. ### Returns None ``` -------------------------------- ### Usage example: ensure BLE enabled, start scanner, stop scanner Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/ble.md Shows how to use the aioshelly.ble functions to ensure BLE is enabled, start the scanner with specific parameters, and later stop it. The example uses async_ensure_ble_enabled, async_start_scanner, and async_stop_scanner. ```python from aioshelly.ble import ( async_start_scanner, async_stop_scanner, async_ensure_ble_enabled, ) restarted = await async_ensure_ble_enabled(device) await async_start_scanner(device, active=False, event_type="ble.scan_result", data_version=2) # ... later await async_stop_scanner(device) ``` -------------------------------- ### BlockDevice.create usage example from README Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Example usage of BlockDevice.create with aiohttp session and COAP context. Creates a device with ConnectionOptions and then initializes it. ```python import aiohttp from aioshelly.block_device import COAP, BlockDevice from aioshelly.common import ConnectionOptions async with aiohttp.ClientSession() as session, COAP() as coap_context: device = await BlockDevice.create( session, coap_context, ConnectionOptions("192.168.1.165", "user", "pass") ) await device.initialize() ``` -------------------------------- ### Run example script to connect to a device and print status changes Source: https://github.com/home-assistant-libs/aioshelly/blob/main/README.md Runs the example script to connect to a single device and print its status whenever a state change is received. Replace <ip> with the device IP; optionally provide username and password. ```bash python3 tools/example.py -ip <ip> [-u <username>] [-p <password] -i ``` -------------------------------- ### Device properties usage example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Example usage of device properties to print device information and check switch status. The example accesses device.name, model, firmware_version, gen, and status. ```python print(device.name, device.model, device.firmware_version, device.gen) if "switch:0" in device.status: print(device.status["switch:0"]["output"]) ``` -------------------------------- ### WsServer.initialize(port, api_url) Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/wsrpc.md Initializes the WebSocket server in standalone mode. Creates an aiohttp Application, adds a GET route at api_url (default /api/shelly/ws), sets up the AppRunner, and starts a TCPSite on the given port. Serves WebSocket connections with subprotocol json-rpc. ```python async def initialize(self, port: int, api_url: str = WS_API_URL) -> None: """Initialize the websocket server, used only in standalone mode.""" app = Application() app.add_routes([get(api_url, self.websocket_handler)]) self._runner = AppRunner(app) await self._runner.setup() site = TCPSite(self._runner, port=port) await site.start() ``` -------------------------------- ### Prepare development environment with venv and uv Source: https://github.com/home-assistant-libs/aioshelly/blob/main/README.md Sets up a Python virtual environment, activates it, installs uv, syncs all dependency groups, and installs pre-commit hooks. Run inside the repository folder. ```bash python3 -m venv .venv source .venv/bin/activate pip install uv uv sync --all-groups prek install ``` -------------------------------- ### get_info basic usage example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/common.md Example of calling get_info with a shared aiohttp session and printing the device type, generation, and firmware version. Requires an aiohttp session and a reachable device IP. ```python import asyncio import aiohttp from aioshelly.common import get_info async def main() -> None: async with aiohttp.ClientSession() as session: info = await get_info(session, "192.168.1.165") print(info["type"], info["gen"], info["fw"]) asyncio.run(main()) ``` -------------------------------- ### is_firmware_supported usage example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/common.md Example usage of is_firmware_supported with GEN2, model 'SNSW-001P16EU', and a firmware version string. Prints True. ```python from aioshelly.common import is_firmware_supported from aioshelly.const import GEN2 supported = is_firmware_supported(GEN2, "SNSW-001P16EU", "20231219-133956/1.1.0-g34b5d4f") print(supported) # True ``` -------------------------------- ### WsServer usage example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/wsrpc.md Shows how to instantiate WsServer, initialize it on a port, and clean up. The close() method is async cleanup and should not be awaited. ```python from aioshelly.rpc_device import WsServer ws_context = WsServer() await ws_context.initialize(8123) # listen on port 8123 # ... create RpcDevice with ws_context; battery devices connect back here ... ws_context.close() # async cleanup, do not await ``` -------------------------------- ### Install aioshelly with pip Source: https://github.com/home-assistant-libs/aioshelly/blob/main/README.md Installs the aioshelly library from PyPI. Requires Python >= 3.11 and the dependencies bluetooth-data-tools, aiohttp, and orjson. ```bash pip install aioshelly ``` -------------------------------- ### get_info error-handling example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/common.md Example of catching specific exceptions from get_info: MacAddressMismatchError, DeviceConnectionTimeoutError, and DeviceConnectionError/InvalidHostError. Shows how to handle MAC mismatch, timeouts, and connection failures. ```python from aioshelly.exceptions import ( DeviceConnectionError, DeviceConnectionTimeoutError, InvalidHostError, MacAddressMismatchError, ) try: info = await get_info(session, "192.168.1.165", device_mac="C049EF8873E8") except MacAddressMismatchError: print("Device MAC does not match the expected MAC") except DeviceConnectionTimeoutError: print("Device did not answer in time") except (DeviceConnectionError, InvalidHostError) as err: print(f"Connection failed: {err!r}") ``` -------------------------------- ### BLE provisioning example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/blerpc.md Scans for a BLE Shelly device, creates an RpcDevice, initializes it, performs a Wi-Fi scan, and shuts down. Requires aioshelly and bleak. ```python from bleak import BleakScanner from aioshelly.common import ConnectionOptions from aioshelly.rpc_device import RpcDevice # scan for a BLE Shelly device once device = await BleakScanner.find_device_by_address("A4C138123456", timeout=10) options = ConnectionOptions(ble_device=device) rpc_device = await RpcDevice.create(None, None, options) await rpc_device.initialize() print(await rpc_device.wifi_scan()) await rpc_device.shutdown() ``` -------------------------------- ### Usage example for WiFi provisioning Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/ble.md Shows how to scan for WiFi networks and provision credentials using the aioshelly BLE provisioning functions. ```python from aioshelly.ble.provisioning import async_provision_wifi, async_scan_wifi_networks networks = await async_scan_wifi_networks(ble_device) await async_provision_wifi(ble_device, "MyWiFi", "secret") ``` -------------------------------- ### Usage example for async_discover_devices Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/zeroconf.md Shows how to use async_discover_devices with AsyncServiceBrowser instances for each service type in SHELLY_TYPES, then print discovered device info. ```python from zeroconf.asyncio import AsyncServiceBrowser, AsyncZeroconf from aioshelly.zeroconf import SHELLY_TYPES, async_discover_devices async with AsyncZeroconf() as aiozc: for service_type in SHELLY_TYPES: AsyncServiceBrowser(aiozc.zeroconf, service_type, handlers=[]) infos = await async_discover_devices(aiozc, timeout=5) for info in infos: print(info.name, info.parsed_addresses(), info.port) ``` -------------------------------- ### Iterating blocks and using dynamic attributes Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-coap.md Example usage iterating device.blocks, printing block representation, accessing dynamic sensor values, current_values, and toggling. Shows GET /relay/0?turn=on for set_state. ```python for block in device.blocks: print(block) # <relay {'I': '0', 'D': 'relay_0', ...}> print(block.output) # dynamic sensor value: "off" / "on" print(block.current_values()) # {'output': 'on', 'power': '12.3', ...} await block.toggle() # GET /relay/0?turn=on ``` -------------------------------- ### README pattern: create and initialize RpcDevice Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Example from the README showing how to create an RpcDevice with a WsServer and ConnectionOptions, then initialize it. Handles InvalidAuthError and DeviceConnectionError, and shuts down the device and closes the ws_context in the finally block. ```python import aiohttp from aioshelly.common import ConnectionOptions from aioshelly.exceptions import InvalidAuthError, DeviceConnectionError from aioshelly.rpc_device import RpcDevice, WsServer async with aiohttp.ClientSession() as aiohttp_session: ws_context = WsServer() await ws_context.initialize(8123) options = ConnectionOptions("192.168.1.188", "username", "password") device = await RpcDevice.create(aiohttp_session, ws_context, options) try: await device.initialize() print(device.status) except (InvalidAuthError, DeviceConnectionError) as err: print(f"Connection failed: {err!r}") finally: await device.shutdown() ws_context.close() ``` -------------------------------- ### Raw transport use example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/wsrpc.md Example of using WsRPC directly with raw transport. Connects to a device, sets authentication data, and makes a single RPC call. The callback prints the method and params for incoming events. ```python from aioshelly.rpc_device.wsrpc import WsRPC rpc = WsRPC("192.168.1.188", lambda source, method, params: print(method, params)) await rpc.connect(session) rpc.set_auth_data("shelly", "user", "pass") result = await rpc.call("Shelly.GetStatus") await rpc.disconnect() ``` -------------------------------- ### Usage example for async_lookup_device_by_name Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/zeroconf.md Shows how to use async_lookup_device_by_name with an AsyncZeroconf instance to find a device by name and print its endpoint. ```python from zeroconf.asyncio import AsyncZeroconf from aioshelly.zeroconf import async_lookup_device_by_name async with AsyncZeroconf() as aiozc: endpoint = await async_lookup_device_by_name(aiozc, "ShellyPlugUS-C049EF8873E8") if endpoint: host, port = endpoint print(f"Device at {host}:{port}") else: print("Device not found") ``` -------------------------------- ### Example - One COAP context for many devices Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-coap.md Shows how to use COAP as an async context manager with multiple BlockDevice instances. Creates a shared COAP context, initializes devices, uses them, and shuts them down before context exit. ```python import aiohttp from aioshelly.block_device import COAP, BlockDevice from aioshelly.common import ConnectionOptions async with aiohttp.ClientSession() as session, COAP() as coap: dev1 = await BlockDevice.create(session, coap, "192.168.1.165") dev2 = await BlockDevice.create(session, coap, ConnectionOptions("192.168.1.166", "user", "pass")) await dev1.initialize() await dev2.initialize() # ... use devices ... await dev1.shutdown() await dev2.shutdown() # coap.close() runs automatically on context exit ``` -------------------------------- ### Using DEVICES and MODEL_NAMES Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/const.md Shows how to access device information from the DEVICES dictionary and model names from MODEL_NAMES. The example prints the name, generation, and model_id for a specific device, and the human-readable name for a model string. ```python from aioshelly.const import DEVICES, MODEL_NAMES device = DEVICES["SNSW-001P16EU"] print(device.name, device.gen, device.model_id) # Shelly Plus 1PM 2 0x1001 print(MODEL_NAMES["SHSW-1"]) # Shelly 1 ``` -------------------------------- ### Turn relay on and reboot device Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Example showing how to turn on a relay (channel 0) via a Block and then reboot the device. ```python # Turn the relay (channel 0) on through a Block, then reboot the device: await device.blocks[0].set_state(turn="on") await device.trigger_reboot() ``` -------------------------------- ### Handling BlockDevice.initialize() errors Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Example of calling initialize() and catching InvalidAuthError and DeviceConnectionError. Prints error messages on failure. ```python try: await device.initialize() except InvalidAuthError: print("Invalid or missing authorization") except DeviceConnectionError as err: print(f"Error connecting: {err!r}") ``` -------------------------------- ### BlockDevice.subscribe_updates() with callback example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Shows how to subscribe to device status updates. The update_listener is called as listener(device, BlockUpdateType) on every state change, init, or online event. The example defines an on_update callback that prints device.status when the update type is INITIALIZED, then subscribes it. ```python def subscribe_updates(self, update_listener: Callable) -> None: """Subscribe to device status updates.""" ``` ```python def on_update(device: BlockDevice, update_type: BlockUpdateType) -> None: if update_type is BlockUpdateType.INITIALIZED: print(device.status) device.subscribe_updates(on_update) ``` -------------------------------- ### json_bytes usage example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/json.md Shows how to use json_bytes to create a frame and send it over a WebSocket. ```python from aioshelly.json import json_bytes frame = json_bytes({"id": 3, "method": "Switch.Set", "params": {"id": 0, "on": True}}) await ws.send_frame(frame, WSMsgType.TEXT) ``` -------------------------------- ### Call RPC method usage Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Example usage of call_rpc and call_rpc_multiple to fetch device status and configuration. Shows how to call a single method and multiple methods with a timeout. ```python status = await device.call_rpc("Shelly.GetStatus") config, status = await device.call_rpc_multiple( [("Shelly.GetConfig", None), ("Shelly.GetStatus", None)], timeout=30 ) ``` -------------------------------- ### Block properties and methods Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-coap.md Properties index, description, channel; methods info, current_values, set_state, toggle, and __getattr__ for dynamic sensor access. set_state issues GET /<type>/<channel>?<kwargs>. ```python @property def index(self) -> str: """Block index.""" return cast(str, self.blk["I"]) @property def description(self) -> str: """Block description.""" return cast(str, self.blk["D"]) @property def channel(self) -> str | None: """Block description for channel.""" return self.description.split("_")[1] if "_" in self.description else None def info(self, attr: str) -> dict[str, Any]: """Return info over attribute.""" return self.sensors[self.sensor_ids[attr]] def current_values(self) -> dict[str, Any]: """Block values.""" if self.device.coap_s is None: return {} return { desc: self.device.coap_s.get(index) for desc, index in self.sensor_ids.items() } async def set_state(self, **kwargs: Any) -> dict[str, Any]: """Set state request (HTTP).""" return await self.device.http_request( "get", f"{self.type}/{self.channel}", kwargs ) async def toggle(self) -> dict[str, Any]: """Toggle status.""" return await self.set_state(turn="off" if self.output else "on") def __getattr__(self, attr: str) -> str | None: """Get attribute.""" ``` -------------------------------- ### Usage example for parse_shelly_manufacturer_data Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/ble.md Shows how to parse Shelly manufacturer data and check for RPC-over-BLE. Requires the manufacturer data from a BLE advertisement. ```python from aioshelly.ble.manufacturer_data import ( parse_shelly_manufacturer_data, has_rpc_over_ble, ) parsed = parse_shelly_manufacturer_data(adv.manufacturer_data) if parsed and has_rpc_over_ble(adv.manufacturer_data): print(parsed["mac"], hex(parsed["model_id"])) ``` -------------------------------- ### Script management methods Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Defines methods for listing, getting code, putting code, creating, starting, stopping, and evaluating scripts, plus a supports_scripts check. These wrap the corresponding Shelly RPC methods. ```python async def methods_list(self) -> list[str]: # Shelly.ListMethods → result["methods"] line 823 async def script_list(self) -> list[ShellyScript]: # Script.List → result["scripts"] line 828 async def script_getcode(self, script_id: int, offset: int = 0, bytes_to_read: int | None = None) -> ShellyScriptCode: # Script.GetCode {id, len?} line 834 async def script_putcode(self, script_id: int, code: str) -> None: # Script.PutCode {id, code} line 848 async def script_create(self, name: str) -> None: # Script.Create {name} line 852 async def script_start(self, script_id: int) -> None: # Script.Start {id} line 856 async def script_stop(self, script_id: int) -> None: # Script.Stop {id} line 860 async def script_eval(self, script_id: int, code: str) -> Any:# Script.Eval {id, code} line 864 async def supports_scripts(self) -> bool: # SCRIPT_SUPPORT_METHODS ⊆ methods_list() line 1191 ``` -------------------------------- ### Batch error handling example Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/wsrpc.md Example of handling errors when making a batch RPC call. Catches RpcCallError for RPC errors and DeviceConnectionTimeoutError for timeouts. ```python from aioshelly.exceptions import RpcCallError, DeviceConnectionTimeoutError try: results = await rpc.calls([("Switch.Set", {"id": 0, "on": True})], timeout=10) except RpcCallError as err: print(f"RPC error {err.code}: {err.message}") except DeviceConnectionTimeoutError: print("device did not answer in time") ``` -------------------------------- ### RpcDevice.initialize() Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Initializes the device by connecting to the WebSocket RPC interface, fetching device info and configuration, and setting up authentication if required. ```APIDOC ## `RpcDevice.initialize()` ### Description Initializes the device by connecting to the WebSocket RPC interface, fetching device info and configuration, and setting up authentication if required. ### Method `async def initialize(self) -> None` ### Endpoint N/A (RPC method) ### Parameters None ### Request Example ```python await device.initialize() ``` ### Response #### Success Response - Returns `None` on success. - On success, sets `initialized = True` and notifies listeners with `RpcUpdateType.INITIALIZED`. #### Error Handling - Raises `RuntimeError("Already initializing")` if `_initialize_lock` is locked. - Raises `InvalidAuthError` (401, retries exhausted) - Raises `MacAddressMismatchError` if device MAC does not match expected. - Raises `DeviceConnectionError` (connection errors or RPC call errors) - Raises `ValueError` if no `aiohttp_session` is available for WsRPC. - On any failure, the transport is disconnected and the error is stored in `last_error`. ### Notes - Connects under `asyncio.timeout(DEVICE_INIT_TIMEOUT)` (30 seconds). - Performs `Shelly.GetDeviceInfo` and stores result in `self._shelly`. - Sets WsRPC digest auth via `set_auth_data(auth_domain or shelly["id"], username, password)` when `requires_auth` and credentials exist. - Verifies `options.device_mac` vs `shelly["mac"]`. - Batches `Shelly.GetConfig` and `Shelly.GetStatus` (when no wake-up status) and dynamic components when supported and firmware >= `VIRTUAL_COMPONENTS_MIN_FIRMWARE`. Source: `aioshelly/rpc_device/device.py:248` ``` -------------------------------- ### WsRPC.__init__ Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/wsrpc.md Constructor for the WsRPC client. ```APIDOC ## WsRPC.__init__ ### Description Initializes the WsRPC client with the device IP address, a notification callback, port, and SSL verification setting. ### Method Constructor ### Endpoint N/A (Python class constructor) ### Parameters - **ip_address** (str) - Required - Device host/IP - **on_notification** (Callable[[RPCSource, str, dict | None], None]) - Required - Called as `(source, method, params)` for notifications (e.g. `RpcDevice._on_notification`) - **port** (int) - Optional - Device port; 443 switches to TLS. Default: DEFAULT_HTTP_PORT (80) - **verify_ssl** (bool) - Optional - TLS certificate verification. Default: False ### Request Example ```python wsrpc = WsRPC( ip_address="192.168.1.100", on_notification=my_notification_handler, port=80, verify_ssl=False, ) ``` ``` -------------------------------- ### GET /reboot Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Reboots the device. ```APIDOC ## GET /reboot ### Description Reboots the device. ### Method GET ### Endpoint /reboot ### Response #### Success Response (200) - **JSON object** - The reboot status as a JSON object. #### Response Example { "status": "rebooting" } ``` -------------------------------- ### BlockDevice.initialize() method definition Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Defines the async initialize method that performs device initialization. Raises RuntimeError if already initializing, CustomPortNotSupported for non-default ports, and various connection/auth errors as documented. ```python async def initialize(self) -> None: """Device initialization.""" ``` -------------------------------- ### WsRPC.__init__ Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/wsrpc.md Initializes the WsRPC client with device IP, notification callback, port, and SSL verification flag. ```python def __init__( self, ip_address: str, on_notification: Callable[[RPCSource, str, dict | None], None], port: int = DEFAULT_HTTP_PORT, verify_ssl: bool = False, ) -> None: """Initialize WsRPC class.""" ``` -------------------------------- ### GET /unmute Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Unmutes the alarm on a Shelly Gas device. ```APIDOC ## GET /unmute ### Description Unmutes the alarm on a Shelly Gas device. ### Method GET ### Endpoint /unmute ### Response #### Success Response (200) - **JSON object** - The unmute status as a JSON object. #### Response Example { "status": "unmuted" } ``` -------------------------------- ### GET /mute Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Mutes the alarm on a Shelly Gas device. ```APIDOC ## GET /mute ### Description Mutes the alarm on a Shelly Gas device. ### Method GET ### Endpoint /mute ### Response #### Success Response (200) - **JSON object** - The mute status as a JSON object. #### Response Example { "status": "muted" } ``` -------------------------------- ### WsServer.initialize(port, api_url) Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/wsrpc.md Initializes the WebSocket server, binding to the specified port and serving the given API URL (default /api/shelly/ws) as a WebSocket endpoint with subprotocol json-rpc. ```APIDOC ## [WS] /api/shelly/ws ### Description Initializes the WebSocket server, binding to the specified port and serving the given API URL (default /api/shelly/ws) as a WebSocket endpoint with subprotocol json-rpc. ### Method WS ### Endpoint /api/shelly/ws ### Parameters #### Path Parameters - **port** (integer) - Required - The port to listen on. #### Query Parameters - **api_url** (string) - Optional - The URL path to serve the WebSocket endpoint on. Defaults to /api/shelly/ws. ### Request Example ``` WS /api/shelly/ws HTTP/1.1 Host: example.com:8123 Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13 Sec-WebSocket-Protocol: json-rpc ``` ### Response #### Success Response (101) - **Upgrade** (string) - websocket - **Connection** (string) - Upgrade - **Sec-WebSocket-Accept** (string) - The accept key. - **Sec-WebSocket-Protocol** (string) - json-rpc #### Response Example ``` HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: json-rpc ``` ``` -------------------------------- ### GET /self_test Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Triggers a self-test on a Shelly Gas device. ```APIDOC ## GET /self_test ### Description Triggers a self-test on a Shelly Gas device. ### Method GET ### Endpoint /self_test ### Response #### Success Response (200) - **JSON object** - The self-test status as a JSON object. #### Response Example { "status": "testing" } ``` -------------------------------- ### GET /ota Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Triggers an over-the-air firmware update on the device. ```APIDOC ## GET /ota ### Description Triggers an over-the-air firmware update on the device. ### Method GET ### Endpoint /ota ### Parameters #### Query Parameters - **update** (boolean) - Optional - Set to true to trigger an update. - **url** (string) - Optional - URL to a firmware image. - **beta** (boolean) - Optional - Set to true to use beta firmware. ### Response #### Success Response (200) - **JSON object** - The OTA status as a JSON object. #### Response Example { "status": "updating" } ``` -------------------------------- ### async_stop_scanner(device) Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/ble.md Stops the BLE scanner script if it is installed on the device. ```APIDOC ## async_stop_scanner(device) ### Description Stops the BLE scanner script if it is installed on the device. ### Method async_stop_scanner ### Parameters - **device** (RpcDevice) - Required - The RPC device instance. ### Returns None ``` -------------------------------- ### trigger_reboot Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Triggers a device reboot by sending a GET request to /reboot. ```APIDOC ## [GET] /reboot ### Description Triggers a device reboot. ### Method GET ### Endpoint /reboot ### Parameters None ### Request Example {} ### Response #### Success Response (200) - **body** (object) - Parsed JSON response #### Response Example { "status": "rebooting" } ``` -------------------------------- ### get_name_from_model_id(model_id) Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/ble.md Gets the device name from a BLE model ID. ```APIDOC ## get_name_from_model_id(model_id) ### Description Gets the device name from a BLE model ID. ### Parameters - **model_id** (int) - Required - The BLE model ID. ### Returns str | None - The device name, or None if not found. ### Source `aioshelly/ble/__init__.py:171` ``` -------------------------------- ### GET /rpc Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md WebSocket endpoint for JSON-RPC communication with Gen2/3/4 devices. ```APIDOC ## GET /rpc ### Description WebSocket endpoint for JSON-RPC communication with Gen2/3/4 devices. ### Method GET ### Endpoint /rpc ### Parameters #### Query Parameters - **heartbeat** (integer) - Optional - Heartbeat interval in seconds (default 55). ### Request Example { "id": 1, "method": "Shelly.GetDeviceInfo", "src": "aios-123" } ### Response #### Success Response (200) - **id** (integer) - Request ID. - **result** (object) - Result of the RPC call. #### Response Example { "id": 1, "result": { "name": "My Device" } } ``` -------------------------------- ### BlockDevice.__init__ Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Initializes a BlockDevice instance with a shared COAP context, aiohttp session, and connection options. Requires ip_address in options. ```APIDOC ## `BlockDevice.__init__` ### Description Initializes a BlockDevice instance. Subscribes to the COAP context and initializes internal state. ### Method Constructor ### Signature ```python def __init__( self, coap_context: COAP, aiohttp_session: ClientSession, options: ConnectionOptions, ) -> None: ``` ### Parameters - **coap_context** (COAP) - Required - Shared `COAP` datagram context; must be initialized before use - **aiohttp_session** (ClientSession) - Required - Shared aiohttp session for HTTP calls - **options** (ConnectionOptions) - Required - Connection options; `ip_address` must be set ### Exceptions - **ValueError** - If `options.ip_address is None` ### Notes - Subscribes to the COAP context with the device MAC suffix (`device_mac[-6:]`) if provided, otherwise the IP address. - Initializes internal state: `initialized = False`, `coap_d`/`coap_s`/`_status`/`_settings`/`_shelly = None`, `blocks = []`. ``` -------------------------------- ### GET /thermostat/{channel} Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Sets the thermostat state for a given channel. ```APIDOC ## GET /thermostat/{channel} ### Description Sets the thermostat state for a given channel. ### Method GET ### Endpoint /thermostat/{channel} ### Parameters #### Path Parameters - **channel** (integer) - Required - The thermostat channel (default 0). #### Query Parameters - **target_t_C** (number) - Optional - Target temperature in Celsius. - **kwargs** - Optional - Additional parameters. ### Response #### Success Response (200) - **JSON object** - The thermostat state as a JSON object. #### Response Example { "target_t_C": 21.0 } ``` -------------------------------- ### Construct ConnectionOptions for HTTP and BLE devices Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/configuration.md Shows three valid ways to construct a ConnectionOptions instance: with IP and credentials on the default HTTP port, with custom port and TLS verification, and with a BLE device. The BLE example requires a prior BleakScanner call. Invalid combos raise ValueError per validation rules. ```python from aioshelly.common import ConnectionOptions # Gen1/Gen2 device with auth on the default HTTP port options = ConnectionOptions("192.168.1.165", "username", "password") # No auth, custom port, HTTPS verification on options = ConnectionOptions( ip_address="192.168.1.166", port=443, verify_ssl=True, device_mac="C049EF8873E8", ) # RPC-over-BLE device (Gen2/3/4) from bleak import BleakScanner ble_device = await BleakScanner.find_device_by_address("A4C138123456", timeout=10) options = ConnectionOptions(ble_device=ble_device) ``` -------------------------------- ### BleRPC.__init__(ble_device) Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/blerpc.md Initializes a new BleRPC client instance with the given BLE device. The device must be obtained from a BLE scan (e.g., via BleakScanner). ```APIDOC ## BleRPC.__init__(ble_device) ### Description Initializes a new BleRPC client instance with the given BLE device. The device must be obtained from a BLE scan (e.g., via BleakScanner). ### Method Constructor ### Endpoint BleRPC.__init__ ### Parameters #### Path Parameters - **ble_device** (BLEDevice) - Required - `bleak.BLEDevice` from a BLE scan (e.g. `bleak`/`habluetooth` scanner result) ### Request Example ```python from bleak import BleakScanner from aioshelly.rpc_device.blerpc import BleRPC # Example: scan for a device and create a BleRPC instance scanner = BleakScanner() # ... scan and get device ... ble_device = scanner.discover().pop() # placeholder client = BleRPC(ble_device) ``` ### Response #### Success Response (None) - No return value (None) #### Response Example ```python None ``` ``` -------------------------------- ### trigger_shelly_gas_unmute Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Triggers a Shelly Gas unmute action by sending a GET request to /unmute. ```APIDOC ## [GET] /unmute ### Description Triggers a Shelly Gas unmute action. ### Method GET ### Endpoint /unmute ### Parameters None ### Request Example {} ### Response #### Success Response (200) - **body** (object) - Parsed JSON response #### Response Example { "status": "unmuted" } ``` -------------------------------- ### trigger_shelly_gas_mute Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Triggers a Shelly Gas mute action by sending a GET request to /mute. ```APIDOC ## [GET] /mute ### Description Triggers a Shelly Gas mute action. ### Method GET ### Endpoint /mute ### Parameters None ### Request Example {} ### Response #### Success Response (200) - **body** (object) - Parsed JSON response #### Response Example { "status": "muted" } ``` -------------------------------- ### RpcDevice.__init__ constructor signature Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Constructor for RpcDevice. Requires ws_context, aiohttp_session, and options. The rpc parameter is optional; if not provided, a WsRPC or BleRPC transport is constructed automatically based on options. With ws_context and WsRPC, subscribes to the server under options.device_mac (preferred) or options.ip_address. ```python def __init__( self, ws_context: WsServer | None, aiohttp_session: ClientSession | None, options: ConnectionOptions, rpc: WsRPC | BleRPC | None = None, ) -> None: """Device init.""" ``` -------------------------------- ### GET /camera/{id}/snapshot Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Retrieves a snapshot image from a Gen3 Camera device. ```APIDOC ## GET /camera/{id}/snapshot ### Description Retrieves a snapshot image from a Gen3 Camera device. ### Method GET ### Endpoint /camera/{id}/snapshot ### Parameters #### Path Parameters - **id** (string) - Required - The camera ID. ### Response #### Success Response (200) - **bytes** - The raw image bytes. #### Response Example [image bytes] ``` -------------------------------- ### GET /{mode}/{channel} Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Sets the state of a light block (e.g., RGBW2) on a given channel. ```APIDOC ## GET /{mode}/{channel} ### Description Sets the state of a light block (e.g., RGBW2) on a given channel. ### Method GET ### Endpoint /{mode}/{channel} ### Parameters #### Path Parameters - **mode** (string) - Required - The light mode (e.g., color, white). - **channel** (integer) - Required - The channel number. #### Query Parameters - **kwargs** - Optional - Additional parameters. ### Response #### Success Response (200) - **JSON object** - The light state as a JSON object. #### Response Example { "ison": true } ``` -------------------------------- ### BlockDevice.__init__ constructor signature Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Constructor for BlockDevice. Requires a shared COAP context, aiohttp session, and ConnectionOptions with ip_address set. Raises ValueError if ip_address is None. Subscribes to COAP context and initializes internal state. ```python def __init__( self, coap_context: COAP, aiohttp_session: ClientSession, options: ConnectionOptions, ) -> None: """Device init.""" ``` -------------------------------- ### GET /{block_type}/{channel} Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Sets the state of a block (e.g., relay, roller) on a given channel. ```APIDOC ## GET /{block_type}/{channel} ### Description Sets the state of a block (e.g., relay, roller) on a given channel. ### Method GET ### Endpoint /{block_type}/{channel} ### Parameters #### Path Parameters - **block_type** (string) - Required - The block type (e.g., relay, roller). - **channel** (integer) - Required - The channel number. #### Query Parameters - **turn** (string) - Optional - Set to "on" or "off". - **kwargs** - Optional - Additional parameters. ### Response #### Success Response (200) - **JSON object** - The block state as a JSON object. #### Response Example { "ison": true } ``` -------------------------------- ### GET /settings Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Retrieves or updates device settings. Used by the library for various settings operations. ```APIDOC ## GET /settings ### Description Retrieves or updates device settings. Used by the library for various settings operations. ### Method GET ### Endpoint /settings ### Parameters #### Query Parameters - **motion_enable** (boolean) - Optional - Enable or disable motion detection. - **mode** (string) - Optional - Set the light mode. ### Response #### Success Response (200) - **JSON object** - The device settings as a JSON object. #### Response Example { "device": { "name": "My Device" } } ``` -------------------------------- ### BLU TRV command methods Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Defines eight async methods for controlling BLU TRV devices. Each method sends a BluTRV.Call RPC with the given TRV ID and method-specific parameters, using a 60-second timeout. Calibration uses Trv.Calibrate, target temperature uses Trv.SetTarget, external temperature uses Trv.SetExternalTemperature, valve position uses Trv.SetPosition, boost uses Trv.SetBoost (with optional duration), and clear boost uses Trv.ClearBoost. The firmware update method calls BluTrv.UpdateFirmware with a 300-second timeout, and the check-for-updates method returns the firmware ID from the response. ```python async def trigger_blu_trv_calibration(self, trv_id: int) -> None: async def blu_trv_set_target_temperature(self, trv_id: int, temperature: float) -> None: async def blu_trv_set_external_temperature(self, trv_id: int, temperature: float) -> None: async def blu_trv_set_valve_position(self, trv_id: int, position: float) -> None: async def blu_trv_set_boost(self, trv_id: int, duration: int | None = None) -> None: async def blu_trv_clear_boost(self, trv_id: int) -> None: async def blu_trv_update_firmware(self, trv_id: int) -> None: async def blu_trv_check_for_updates(self) -> str: ``` -------------------------------- ### GET /status Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Retrieves the current device status. Emitted by the library's update_status method. ```APIDOC ## GET /status ### Description Retrieves the current device status. Emitted by the library's update_status method. ### Method GET ### Endpoint /status ### Response #### Success Response (200) - **JSON object** - The device status as a JSON object. #### Response Example { "relays": [ { "ison": true, "has_timer": false } ] } ``` -------------------------------- ### POST /settings/advanced Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/endpoints.md Configures the CoIoT protocol settings on the device. ```APIDOC ## POST /settings/advanced ### Description Configures the CoIoT protocol settings on the device. ### Method POST ### Endpoint /settings/advanced ### Parameters #### Query Parameters - **coiot_enable** (boolean) - Required - Enable or disable CoIoT. - **coiot_peer** (string) - Required - The peer address and port in the format <address>:<port>. ### Response #### Success Response (200) - **JSON object** - The updated settings as a JSON object. #### Response Example { "coiot": { "enabled": true, "peer": "192.168.1.100:5683" } } ``` -------------------------------- ### System / OTA update and reboot methods Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Defines three async methods for triggering OTA updates, add-on OTA updates, and reboots. The OTA update uses the Shelly.Update RPC with a beta flag, the add-on update uses AddOn.Update with a configurable timeout (default 600 s, call timeout 25 s), and the reboot uses Shelly.Reboot with a delay in milliseconds (default 1000). ```python async def trigger_ota_update(self, beta: bool = False) -> None: # Shelly.Update {stage: beta|stable} line 333 async def trigger_add_on_ota_update(self, timeout: int = 600) -> None: # AddOn.Update {timeout}, call timeout 25s line 338 async def trigger_reboot(self, delay_ms: int = 1000) -> None: # Shelly.Reboot {delay_ms} line 344 ``` -------------------------------- ### switch_light_mode Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/block-device.md Changes the device mode to color or white by sending a GET request to /settings with the mode parameter. ```APIDOC ## [GET] /settings ### Description Changes the device mode to color or white. ### Method GET ### Endpoint /settings ### Parameters #### Query Parameters - **mode** (string) - Required - The mode to set, e.g. "color" or "white" ### Request Example { "mode": "color" } ### Response #### Success Response (200) - **body** (object) - Parsed JSON response #### Response Example { "mode": "color" } ``` -------------------------------- ### Add-on and dynamic component methods Source: https://github.com/home-assistant-libs/aioshelly/blob/main/_autodocs/api-reference/rpc-device.md Methods for retrieving add-on info and dynamic components. Dynamic components are supported only for non-sleeping devices on firmware >= VIRTUAL_COMPONENTS_MIN_FIRMWARE; results are merged into _config and _status, and blutrv components are enriched via BluTrv.GetRemoteConfig. ```python async def add_on_info(self) -> dict[str, Any]: # config["sys"]["device"].get("addon_type") + AddOn.GetInfo (if listed) line 1119 async def get_dynamic_components(self) -> None: # Shelly.GetComponents {dynamic_only} + parse + BLU TRV line 1130 async def get_all_pages(self, first_page: dict[str, Any]) -> dict[str, Any]: # pagination loop (< MAX_ITERATIONS) line 810 ```