Skip to content

WebsocketClient

pybticino.websocket.WebsocketClient

Handles the WebSocket connection for receiving real-time push notifications.

This client connects to the BTicino WebSocket endpoint, authenticates using an AuthHandler, subscribes to updates, and invokes a user-provided asynchronous callback function for each received message. It includes automatic reconnection logic.

Attributes:

Name Type Description
_auth_handler AuthHandler

Instance used for authentication.

_message_callback Callable

Async function called with received messages.

_app_version str

Application version string.

_platform str

Platform identifier string.

_websocket Optional[ClientConnection]

The active WebSocket connection.

_listener_task Optional[Task]

The task running the message listener loop.

_is_running bool

Flag indicating if the client is actively running/connecting.

_connection_lock Lock

Lock to prevent race conditions during connect/disconnect operations.

__init__

__init__(auth_handler: AuthHandler, message_callback: Callable[[dict[str, Any]], Awaitable[None]], app_version: str = DEFAULT_APP_VERSION, platform: str = DEFAULT_PLATFORM) -> None

Initialize the WebSocket client.

Parameters:

Name Type Description Default
auth_handler AuthHandler

An initialized and authenticated AuthHandler instance.

required
message_callback Callable[[dict[str, Any]], Awaitable[None]]

An asynchronous function that will be called with each decoded JSON message received from the WebSocket.

required
app_version str

The application version string. Defaults to DEFAULT_APP_VERSION.

DEFAULT_APP_VERSION
platform str

The platform identifier string. Defaults to DEFAULT_PLATFORM.

DEFAULT_PLATFORM

Raises:

Type Description
TypeError

If auth_handler is not an instance of AuthHandler or if message_callback is not an async function.

get_listener_task

get_listener_task() -> asyncio.Task | None

Return the internal listener task, if active.

resubscribe async

resubscribe() -> None

Re-subscribe on the existing connection with a fresh token.

Sends a new Subscribe message with a refreshed OAuth token on the current WebSocket connection. This keeps the session alive without disconnecting and reconnecting. Matches the official Android app behavior.

Note: This only sends the message — it does NOT wait for a response, because the listener loop is already consuming recv(). The server's response will arrive as a message in the listener and be ignored.

Raises:

Type Description
PyBticinoException

If no active connection or send fails.

connect async

connect() -> None

Establish the WebSocket connection, subscribe, and start listening.

Connects to the WebSocket server, sends the subscription message, and creates a background task to listen for incoming messages. Uses a lock to prevent concurrent connection attempts.

Raises:

Type Description
PyBticinoException

If connection or subscription fails. Wraps underlying exceptions like websockets.exceptions, AuthError, TimeoutError.

disconnect async

disconnect() -> None

Disconnect the WebSocket client gracefully.

Cancels the listener task and closes the WebSocket connection. Uses a lock to prevent concurrent disconnect operations.

run_forever async

run_forever(reconnect_delay: int = 30) -> None

Connect and maintain the WebSocket connection indefinitely.

This method runs a loop that attempts to connect(). If the connection drops (indicated by the listener task ending or an error during connection), it waits for reconnect_delay seconds before attempting to disconnect() cleanly and then connect() again.

This method typically runs forever until the client is explicitly stopped (e.g., by cancelling the task running this method or calling disconnect from another task).

Parameters:

Name Type Description Default
reconnect_delay int

The number of seconds to wait before attempting to reconnect after a disconnection. Defaults to 30.

30