Python module to talk to Google Chromecast.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
The main Chromecast class provides comprehensive device connection management, app launching, volume control, and status monitoring. It handles connection lifecycle, error recovery, and provides access to specialized controllers for extended functionality.
Main class for interacting with a specific Chromecast device, handling all aspects of device communication and control.
class Chromecast:
"""
Class to interface with a ChromeCast device.
Parameters:
- cast_info: CastInfo, Information for the device
- tries: int | None, Number of retries if connection fails. None for infinite retries.
- timeout: float | None, Socket timeout in seconds. None for default (30 seconds).
- retry_wait: float | None, Seconds to wait between retries. None for default (5 seconds).
- zconf: zeroconf.Zeroconf | None, Zeroconf instance for mDNS services.
"""
def __init__(self, cast_info, *, tries=None, timeout=None, retry_wait=None, zconf=None): ...Control the connection lifecycle and wait for device readiness.
def wait(self, timeout=None):
"""
Waits until the cast device is ready for communication.
If the worker thread is not already running, it will be started.
If the status has already been received then the method returns immediately.
Parameters:
- timeout: float | None, Timeout for the operation in seconds. None to block forever.
Raises:
- RequestTimeout: If timeout expires before device is ready
"""
def start(self):
"""Start the chromecast connection's worker thread."""
def disconnect(self, timeout=None):
"""
Disconnects the chromecast and waits for it to terminate.
Parameters:
- timeout: float | None, Timeout for the operation in seconds. None to block forever.
Set to 0 to not block.
"""
def join(self, timeout=None):
"""
Blocks the thread of the caller until the chromecast connection is stopped.
Parameters:
- timeout: float | None, Timeout for the operation in seconds. None to block forever.
Raises:
- TimeoutError: If timeout expires before connection stops
"""Usage Example:
import pychromecast
# Get a device
chromecasts, browser = pychromecast.get_chromecasts()
cast = chromecasts[0]
# Wait for device to be ready
try:
cast.wait(timeout=10.0)
print("Device is ready for communication")
except pychromecast.RequestTimeout:
print("Device did not become ready within timeout")
# Use the device...
# Disconnect when done
cast.disconnect(timeout=5.0)
browser.stop_discovery()Launch and quit applications on the Chromecast device.
def start_app(self, app_id, force_launch=False, timeout=REQUEST_TIMEOUT):
"""
Start an app on the Chromecast.
Parameters:
- app_id: str, Application ID to launch
- force_launch: bool, Force launch even if app is already running
- timeout: float, Request timeout in seconds
Raises:
- RequestTimeout: If app launch times out
- RequestFailed: If app launch fails
"""
def quit_app(self, timeout=REQUEST_TIMEOUT):
"""
Tells the Chromecast to quit current app.
Parameters:
- timeout: float, Request timeout in seconds
Raises:
- RequestTimeout: If quit request times out
- RequestFailed: If quit request fails
"""Usage Example:
# Launch YouTube app
cast.start_app(pychromecast.APP_YOUTUBE)
# Wait for app to start
cast.wait()
# Check what's running
print(f"Current app: {cast.app_display_name} (ID: {cast.app_id})")
# Quit the current app
cast.quit_app()
# Launch with force (stops current app first)
cast.start_app(pychromecast.APP_MEDIA_RECEIVER, force_launch=True)Control device volume level and mute state.
def volume_up(self, delta=0.1, timeout=REQUEST_TIMEOUT):
"""
Increment volume by delta unless it is already maxed.
Parameters:
- delta: float, Volume increase amount (must be > 0)
- timeout: float, Request timeout in seconds
Returns:
float: New volume level
Raises:
- ValueError: If delta <= 0
- NotConnected: If not connected to device
- RequestTimeout: If request times out
"""
def volume_down(self, delta=0.1, timeout=REQUEST_TIMEOUT):
"""
Decrement the volume by delta unless it is already 0.
Parameters:
- delta: float, Volume decrease amount (must be > 0)
- timeout: float, Request timeout in seconds
Returns:
float: New volume level
Raises:
- ValueError: If delta <= 0
- NotConnected: If not connected to device
- RequestTimeout: If request times out
"""
def set_volume(self, volume, timeout=REQUEST_TIMEOUT):
"""
Set the volume level (forwarded from receiver controller).
Parameters:
- volume: float, Volume level (0.0 to 1.0)
- timeout: float, Request timeout in seconds
Returns:
float: New volume level
"""
def set_volume_muted(self, muted, timeout=REQUEST_TIMEOUT):
"""
Set the mute state (forwarded from receiver controller).
Parameters:
- muted: bool, True to mute, False to unmute
- timeout: float, Request timeout in seconds
"""Usage Example:
# Check current volume
print(f"Current volume: {cast.status.volume_level}")
print(f"Muted: {cast.status.volume_muted}")
# Adjust volume
new_volume = cast.volume_up(0.2) # Increase by 20%
print(f"New volume: {new_volume}")
cast.volume_down(0.1) # Decrease by 10%
# Set specific volume
cast.set_volume(0.5) # Set to 50%
# Mute/unmute
cast.set_volume_muted(True) # Mute
cast.set_volume_muted(False) # UnmuteAccess device information and current status.
@property
def uuid(self) -> UUID:
"""Returns the unique UUID of the Chromecast device."""
@property
def name(self) -> str | None:
"""
Returns the friendly name set for the Chromecast device.
This is the name that the end-user chooses for the cast device.
"""
@property
def uri(self) -> str:
"""Returns the device URI (ip:port)"""
@property
def model_name(self) -> str:
"""Returns the model name of the Chromecast device."""
@property
def cast_type(self) -> str:
"""
Returns the type of the Chromecast device.
One of CAST_TYPE_CHROMECAST, CAST_TYPE_AUDIO, or CAST_TYPE_GROUP.
"""
@property
def app_id(self) -> str | None:
"""Returns the current app_id."""
@property
def app_display_name(self) -> str | None:
"""Returns the name of the current running app."""
@property
def status(self) -> CastStatus | None:
"""Returns the current cast status."""
@property
def is_idle(self) -> bool:
"""Returns if there is currently an app running."""
@property
def ignore_cec(self) -> bool:
"""Returns whether the CEC data should be ignored."""
@property
def media_controller(self) -> MediaController:
"""Returns the media controller."""Usage Example:
# Device information
print(f"Device: {cast.name}")
print(f"UUID: {cast.uuid}")
print(f"Model: {cast.model_name}")
print(f"Type: {cast.cast_type}")
print(f"URI: {cast.uri}")
# Current state
print(f"Is idle: {cast.is_idle}")
if cast.status:
print(f"Volume: {cast.status.volume_level}")
print(f"Muted: {cast.status.volume_muted}")
if cast.app_id:
print(f"Running app: {cast.app_display_name} ({cast.app_id})")
# Access controllers
media_ctrl = cast.media_controller
print(f"Media controller: {media_ctrl}")Register listeners for device status changes and errors.
def register_status_listener(self, listener):
"""
Register a status listener for when a new Chromecast status has been received.
Listeners will be called with listener.new_cast_status(status).
Parameters:
- listener: CastStatusListener, Object with new_cast_status method
"""
def register_launch_error_listener(self, listener):
"""
Register a listener for when a new launch error message has been received.
Listeners will be called with listener.new_launch_error(launch_failure).
Parameters:
- listener: LaunchErrorListener, Object with new_launch_error method
"""
def register_connection_listener(self, listener):
"""
Register a connection listener (forwarded from socket client).
Parameters:
- listener: ConnectionStatusListener, Object with connection status methods
"""
def new_cast_status(self, status):
"""
Called when a new status received from the Chromecast.
Parameters:
- status: CastStatus, New status information
"""Usage Example:
class MyStatusListener:
def new_cast_status(self, status):
print(f"Status update - App: {status.display_name}, Volume: {status.volume_level}")
class MyLaunchErrorListener:
def new_launch_error(self, launch_failure):
print(f"Launch failed: {launch_failure.reason} for app {launch_failure.app_id}")
# Register listeners
status_listener = MyStatusListener()
error_listener = MyLaunchErrorListener()
cast.register_status_listener(status_listener)
cast.register_launch_error_listener(error_listener)
# Now status changes and launch errors will trigger the listenersRegister custom message handlers and forward media control methods.
def register_handler(self, handler):
"""Register message handler (forwarded from socket client)."""
def unregister_handler(self, handler):
"""Unregister message handler (forwarded from socket client)."""
def play_media(self, url, content_type, **kwargs):
"""Play media (forwarded from media controller)."""class CastStatus:
"""Current cast device status"""
is_active_input: bool | None
is_stand_by: bool | None
volume_level: float
volume_muted: bool
app_id: str | None
display_name: str | None
namespaces: list[str]
session_id: str | None
transport_id: str | None
status_text: str
icon_url: str | None
volume_control_type: str
class CastStatusListener:
"""Abstract listener for cast status events"""
def new_cast_status(self, status: CastStatus) -> None: ...
class LaunchErrorListener:
"""Abstract listener for launch error events"""
def new_launch_error(self, status: LaunchFailure) -> None: ...
class LaunchFailure:
"""Launch failure information"""
reason: str | None
app_id: str | None
request_id: int | NoneREQUEST_TIMEOUT = 10.0 # Default request timeout in seconds
IDLE_APP_ID = "E8C28D3C" # Backdrop/idle app ID
# Cast Types
CAST_TYPE_CHROMECAST = "cast"
CAST_TYPE_AUDIO = "audio"
CAST_TYPE_GROUP = "group"
# Volume Control Types
VOLUME_CONTROL_TYPE_ATTENUATION = "attenuation"
VOLUME_CONTROL_TYPE_FIXED = "fixed"
VOLUME_CONTROL_TYPE_MASTER = "master"Install with Tessl CLI
npx tessl i tessl/pypi-pychromecast