home-assistant-libs / pychromecast

Library for Python 3 to communicate with the Google Chromecast.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

chromecast.wait() never returns

lufinkey opened this issue · comments

I'm trying to connect to a chromecast using an instance of CastBrowser, and I can't seem to get the Chromecast instance to connect. Here is an example script where chromecast.wait() never returns:

#!/usr/bin/env python3

import asyncio
import zeroconf
import pychromecast
from pychromecast import CastBrowser, SimpleCastListener

async def test_pychromecast():
	print("starting cast discovery")
	# create CastBrowser instance and start cast discovery
	zconf = zeroconf.Zeroconf()
	chromecasts = {}
	def add_callback(uuid, service):
		cast_info = browser.devices[uuid]
		chromecasts[uuid] = pychromecast.get_chromecast_from_cast_info(
			cast_info,
			zconf=zconf)
		print("found "+cast_info.friendly_name)
	def update_callback(uuid, service):
		cast_info = browser.devices[uuid]
		chromecasts[uuid] = pychromecast.get_chromecast_from_cast_info(
			cast_info,
			zconf=zconf)
		print("updated "+cast_info.friendly_name)
	def remove_callback(uuid, service, cast_info):
		chromecasts.pop(uuid)
		print("removed "+cast_info.friendly_name)
	
	browser = CastBrowser(
		SimpleCastListener(
			add_callback=add_callback,
			remove_callback=remove_callback,
			update_callback=update_callback),
		zeroconf_instance=zconf)
	browser.start_discovery()
	
	# wait 4 seconds
	await asyncio.sleep(4)
	
	# get Chromecast instance
	chromecast: pychromecast.Chromecast = None
	for cmpChromecast in chromecasts.values():
		if cmpChromecast.cast_info.friendly_name == "Living Room TV":
			chromecast = cmpChromecast
			break
	if chromecast is None:
		print("couldn't find chromecast")
		return

	# wait for Chromecast to connect
	print("Connecting to "+chromecast.cast_info.friendly_name)
	chromecast.wait() # << code never makes it past this point
	print("Connected to "+chromecast.cast_info.friendly_name)
	
	# cast video to the chromecast
	mc = chromecast.media_controller
	stream_url = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
	print("playing media url "+stream_url)
	mc.play_media(stream_url, content_type="video/mp4")
	mc.block_until_active(timeout=10.0)
	
	await asyncio.sleep(20)
	
asyncio.run(test_pychromecast())

Edit: To add to this, if I add a timeout to wait, then any pychromecast methods after that fail due to not being connected

Closing as it seems to work if given a high enough timeout (over a minute)