Python module to talk to Google Chromecast.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive exception hierarchy for different error conditions including connection failures, protocol errors, timeout situations, and controller registration issues. PyChromecast provides specific exception types to help applications handle different failure scenarios appropriately.
PyChromecast defines a structured exception hierarchy for different types of errors.
class PyChromecastError(Exception):
"""Base error for PyChromecast."""
class ChromecastConnectionError(PyChromecastError):
"""When a connection error occurs within PyChromecast."""
class PyChromecastStopped(PyChromecastError):
"""
Raised when a command is invoked while the Chromecast's socket_client is stopped.
"""
class NotConnected(PyChromecastError):
"""
Raised when a command is invoked while not connected to a Chromecast.
"""
class UnsupportedNamespace(PyChromecastError):
"""
Raised when trying to send a message with a namespace that is not
supported by the current running app.
"""
class ControllerNotRegistered(PyChromecastError):
"""
Raised when trying to interact with a controller while it is
not registered with a ChromeCast object.
"""
class RequestFailed(PyChromecastError):
"""
Raised when a request failed to complete.
Attributes:
- request: str, Description of the failed request
"""
def __init__(self, request: str): ...
class RequestTimeout(PyChromecastError):
"""
Raised when a request timed out.
Attributes:
- request: str, Description of the timed out request
- timeout: float, Timeout value that was exceeded
"""
def __init__(self, request: str, timeout: float): ...
class ZeroConfInstanceRequired(PyChromecastError):
"""Raised when a zeroconf instance is required."""Handle connection-related errors during device discovery and communication.
Usage Example:
import pychromecast
from pychromecast.error import (
ChromecastConnectionError,
NotConnected,
PyChromecastStopped
)
try:
# Attempt to discover devices
chromecasts, browser = pychromecast.get_chromecasts()
if not chromecasts:
print("No Chromecast devices found")
return
cast = chromecasts[0]
try:
# Wait for connection
cast.wait(timeout=10.0)
print(f"Connected to {cast.name}")
except pychromecast.RequestTimeout as e:
print(f"Connection timeout: {e}")
except NotConnected as e:
print(f"Not connected to device: {e}")
except ChromecastConnectionError as e:
print(f"Connection error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
# Always stop discovery
if 'browser' in locals():
browser.stop_discovery()Handle request failures and timeouts during device operations.
Usage Example:
from pychromecast.error import RequestFailed, RequestTimeout
try:
# Attempt to start an app
cast.start_app(pychromecast.APP_YOUTUBE, timeout=30.0)
# Attempt to play media
cast.media_controller.play_media(
"http://example.com/video.mp4",
"video/mp4"
)
# Wait for media to become active
cast.media_controller.block_until_active(timeout=15.0)
except RequestTimeout as e:
print(f"Request timed out: {e}")
print(f"Timeout was: {e.timeout} seconds")
except RequestFailed as e:
print(f"Request failed: {e}")
except NotConnected:
print("Device is not connected")
except PyChromecastStopped:
print("Chromecast connection has been stopped")Handle controller-specific errors including unsupported operations and registration issues.
Usage Example:
from pychromecast.error import (
ControllerNotRegistered,
UnsupportedNamespace,
ZeroConfInstanceRequired
)
from pychromecast.controllers.youtube import YouTubeController
try:
# Create controller
yt_controller = YouTubeController()
# This will fail - controller not registered yet
yt_controller.play_video("dQw4w9WgXcQ")
except ControllerNotRegistered as e:
print(f"Controller not registered: {e}")
# Register the controller
cast.register_handler(yt_controller)
try:
# Launch YouTube app
yt_controller.launch()
# Now this should work
yt_controller.play_video("dQw4w9WgXcQ")
except UnsupportedNamespace as e:
print(f"Namespace not supported by current app: {e}")
except RequestTimeout as e:
print(f"YouTube operation timed out: {e}")
except ZeroConfInstanceRequired as e:
print(f"ZeroConf instance required for this operation: {e}")Handle volume control specific errors.
Usage Example:
try:
# Attempt volume control
current_volume = cast.status.volume_level if cast.status else 0.0
# Try to increase volume
new_volume = cast.volume_up(delta=0.2, timeout=10.0)
print(f"Volume changed from {current_volume:.1f} to {new_volume:.1f}")
except ValueError as e:
print(f"Invalid volume delta: {e}")
except NotConnected as e:
print(f"Cannot control volume - not connected: {e}")
except RequestTimeout as e:
print(f"Volume control timed out: {e}")Handle media-specific errors during playback operations.
Usage Example:
try:
media_ctrl = cast.media_controller
# Try to play media
media_ctrl.play_media(
"https://example.com/video.mp4",
"video/mp4",
title="Test Video"
)
# Wait for media to load
media_ctrl.block_until_active(timeout=30.0)
# Control playback
media_ctrl.pause()
media_ctrl.seek(60.0) # Seek to 1 minute
media_ctrl.play()
except RequestTimeout as e:
print(f"Media operation timed out: {e}")
if "block_until_active" in str(e):
print("Media failed to load within timeout")
except UnsupportedNamespace as e:
print(f"Media namespace not supported: {e}")
# May need to launch media receiver app first
cast.start_app(pychromecast.APP_MEDIA_RECEIVER)
except NotConnected as e:
print(f"Cannot control media - not connected: {e}")Handle errors during device discovery process.
Usage Example:
import zeroconf
from pychromecast.models import ZEROCONF_ERRORS
try:
# Discovery with custom zeroconf instance
zconf = zeroconf.Zeroconf()
chromecasts, browser = pychromecast.get_chromecasts(
zeroconf_instance=zconf,
timeout=10.0
)
if not chromecasts:
print("No devices discovered")
except ZEROCONF_ERRORS as e:
print(f"ZeroConf error during discovery: {e}")
except ChromecastConnectionError as e:
print(f"Connection error during discovery: {e}")
except Exception as e:
print(f"Unexpected discovery error: {e}")
finally:
# Clean up
if 'browser' in locals():
browser.stop_discovery()
if 'zconf' in locals():
zconf.close()A complete error handling pattern for typical PyChromecast usage.
Usage Example:
import pychromecast
from pychromecast.error import *
import time
def safe_cast_operation():
browser = None
cast = None
try:
# Discovery phase
print("Discovering Chromecast devices...")
chromecasts, browser = pychromecast.get_chromecasts(timeout=10.0)
if not chromecasts:
print("No Chromecast devices found")
return False
cast = chromecasts[0]
print(f"Found device: {cast.name}")
# Connection phase
print("Connecting to device...")
cast.wait(timeout=15.0)
print("Connected successfully")
# Operation phase
print("Playing media...")
cast.media_controller.play_media(
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
"video/mp4",
title="Big Buck Bunny"
)
# Wait for media
cast.media_controller.block_until_active(timeout=20.0)
print("Media is playing")
# Brief pause then cleanup
time.sleep(5)
return True
except RequestTimeout as e:
print(f"Operation timed out: {e}")
except ChromecastConnectionError as e:
print(f"Connection error: {e}")
except NotConnected as e:
print(f"Device not connected: {e}")
except UnsupportedNamespace as e:
print(f"Unsupported operation: {e}")
except PyChromecastError as e:
print(f"PyChromecast error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
# Cleanup phase
if cast:
try:
cast.disconnect(timeout=5.0)
print("Disconnected from device")
except Exception as e:
print(f"Error during disconnect: {e}")
if browser:
try:
browser.stop_discovery()
print("Stopped discovery")
except Exception as e:
print(f"Error stopping discovery: {e}")
return False
# Usage
success = safe_cast_operation()
print(f"Operation {'succeeded' if success else 'failed'}")ChromecastConnectionError - General connection issuesNotConnected - Operations attempted without connectionZeroConfInstanceRequired - mDNS operations requiring ZeroConfRequestTimeout - Operations exceeding time limitsRequestFailed - Failed protocol requestsUnsupportedNamespace - App doesn't support the operationControllerNotRegistered - Controller operations without registrationPyChromecastStopped - Operations on stopped connectionsValueError - Invalid parameter values (e.g., negative volume delta)TimeoutError - Standard timeout in join operationsInstall with Tessl CLI
npx tessl i tessl/pypi-pychromecast