def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the cast platform.""" import pychromecast # Import CEC IGNORE attributes pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, []) known_hosts = hass.data.get(KNOWN_HOSTS_KEY) if known_hosts is None: known_hosts = hass.data[KNOWN_HOSTS_KEY] = [] if discovery_info: host = (discovery_info.get('host'), discovery_info.get('port')) if host in known_hosts: return hosts = [host] elif CONF_HOST in config: host = (config.get(CONF_HOST), DEFAULT_PORT) if host in known_hosts: return hosts = [host] else: hosts = [tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in known_hosts] casts = [] # get_chromecasts() returns Chromecast objects with the correct friendly # name for grouped devices all_chromecasts = pychromecast.get_chromecasts() for host in hosts: (_, port) = host found = [device for device in all_chromecasts if (device.host, device.port) == host] if found: try: casts.append(CastDevice(found[0])) known_hosts.append(host) except pychromecast.ChromecastConnectionError: pass # do not add groups using pychromecast.Chromecast as it leads to names # collision since pychromecast.Chromecast will get device name instead # of group name elif port == DEFAULT_PORT: try: # add the device anyway, get_chromecasts couldn't find it casts.append(CastDevice(pychromecast.Chromecast(*host))) known_hosts.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def __init__(self, chromecast_name='Living Room'): chromecasts = pychromecast.get_chromecasts() if len(chromecasts) > 0: self.cast = next(cc for cc in chromecasts if cc.device.friendly_name == chromecast_name) else: print("No Chromecasts found") exit(1)
def your_main_loop(): t = 1 cast = None def callback(chromecast): chromecast.connect() nonlocal cast cast = chromecast stop_discovery() stop_discovery = pychromecast.get_chromecasts(blocking=False, callback=callback) while True: if cast: polltime = 0.1 can_read, _, _ = select.select([cast.socket_client.get_socket()], [], [], polltime) if can_read: #received something on the socket, handle it with run_once() cast.socket_client.run_once() do_actions(cast, t) t += 1 if(t > 50): break else: print("=> Waiting for cast discovery...") time.sleep(1)
def _connect_chromecast(self, available_devices=None): ''' Attempt to (re)connect to cast device named in `__init__`. ''' self.cast = None if not available_devices: available_devices = pychromecast.get_chromecasts(tries=1) matching_devices = [ c for c in available_devices if c.device.friendly_name == self.cast_name ] if not matching_devices: click.echo('Could not connect to device "%s"' % self.cast_name) return if len(matching_devices) > 1: click.echo('WARNING: Multiple devices available. Choosing first.') self.cast = matching_devices[0] # Wait for the device to be available self.cast.wait() click.echo('Using chromecast: %s' % self.cast.device.friendly_name)
def cast_now(url): chromecasts = pychromecast.get_chromecasts() cast = next(cc for cc in chromecasts if cc.device.friendly_name == "Lisa's RuV TV") cast.wait() mc = cast.media_controller mc.play_media(f"{url}", "video/mp4") mc.block_until_active() print(mc.status)
def _get_chromecasts(self): # compatibility try: return list(pychromecast.get_chromecasts_as_dict().keys()) except AttributeError: self._chromecasts_by_name = {c.name: c for c in pychromecast.get_chromecasts( tries=self.tries)} return list(self._chromecasts_by_name.keys())
def snoop(): import pychromecast, time chromecasts = pychromecast.get_chromecasts() cast = next(cc for cc in chromecasts if cc.device.friendly_name == target_cast_name) cast.wait() print("Connected to {}".format(cast.device.friendly_name)) cast.media_controller.register_status_listener(Listener()) while True: time.sleep(15)
def _discoverAll(self): self._disconnectAll() try: casts = pychromecast.get_chromecasts(timeout=10) for i in casts: self._logger.info(i) self._chromecasts[i.device.friendly_name] = i self._chromecasts_OK = True except Exception as e: self._chromecasts_OK = False self._logger.erro(e)
def autodetect(config, emitter): """ Autodetect chromecasts on the network and create backends for each """ casts = pychromecast.get_chromecasts() ret = [] for c in casts: LOG.info(c.name + " found.") ret.append(ChromecastService(config, emitter, c.name.lower(), c)) return ret
def autodetect(config, bus): """ Autodetect chromecasts on the network and create backends for each """ casts = pychromecast.get_chromecasts(timeout=5, tries=2, retry_wait=2) ret = [] for c in casts: LOG.info(c.name + " found.") ret.append(ChromecastService(config, bus, c.name.lower(), c)) return ret
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the cast platform.""" import pychromecast # import CEC IGNORE attributes ignore_cec = config.get(CONF_IGNORE_CEC, []) if isinstance(ignore_cec, list): pychromecast.IGNORE_CEC += ignore_cec else: _LOGGER.error('CEC config "%s" must be a list.', CONF_IGNORE_CEC) hosts = [] if discovery_info and discovery_info in KNOWN_HOSTS: return elif discovery_info: hosts = [discovery_info] elif CONF_HOST in config: hosts = [(config.get(CONF_HOST), DEFAULT_PORT)] else: hosts = [tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in KNOWN_HOSTS] casts = [] # get_chromecasts() returns Chromecast objects # with the correct friendly name for grouped devices all_chromecasts = pychromecast.get_chromecasts() for host in hosts: found = [device for device in all_chromecasts if (device.host, device.port) == host] if found: try: casts.append(CastDevice(found[0])) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass else: try: # add the device anyway, get_chromecasts couldn't find it casts.append(CastDevice(pychromecast.Chromecast(*host))) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def __init__(self): cache = Cache() cached_ip = cache.get() try: if not cached_ip: raise ValueError self.cast = pychromecast.Chromecast(cached_ip) except (pychromecast.error.ChromecastConnectionError, ValueError): devices = pychromecast.get_chromecasts() self.cast = min(devices, key=lambda cc: cc.name) cache.set(self.cast.host) self.cast.wait() self.listener = StatusListener(self.cast.app_id)
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the cast platform.""" import pychromecast # Import CEC IGNORE attributes pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, []) hosts = [] if discovery_info: host = (discovery_info.get('host'), discovery_info.get('port')) if host in KNOWN_HOSTS: return hosts = [host] elif CONF_HOST in config: hosts = [(config.get(CONF_HOST), DEFAULT_PORT)] else: hosts = [tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in KNOWN_HOSTS] casts = [] # get_chromecasts() returns Chromecast objects with the correct friendly # name for grouped devices all_chromecasts = pychromecast.get_chromecasts() for host in hosts: found = [device for device in all_chromecasts if (device.host, device.port) == host] if found: try: casts.append(CastDevice(found[0])) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass else: try: # add the device anyway, get_chromecasts couldn't find it casts.append(CastDevice(pychromecast.Chromecast(*host))) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def refreshChromecastsList(): global chromecasts, casts try : chromecastsCurrentList=pychromecast.get_chromecasts(tries=2) chromecastsCurrent={cc.device.friendly_name: cc for cc in chromecastsCurrentList} #chromecastsCurrent=pychromecast.get_chromecasts_as_dict(tries=2) #chromecastsCurrent=pychromecast.get_chromecasts_as_dict() except AttributeError as e: print '====================' print 'exception get_chromecasts' print("args: ", e.args) print '====================' except Exception,e: print 'exception scan chromecasts 2', e logger.debug('exception occurs during scan chromecasts 2!!!!')
def _connect(self, message): LOG.info('Trying to connect to chromecast') casts = pychromecast.get_chromecasts() if self.config is None or 'identifier' not in self.config: LOG.error("Chromecast identifier not found!") return # Can't connect since no id is specified else: identifier = self.config['identifier'] for c in casts: if c.name == identifier: self.cast = c break else: LOG.info('Couldn\'t find chromecast ' + identifier) self.connection_attempts += 1 time.sleep(10) self.bus.emit(Message('ChromecastServiceConnect')) return
def cast_result(self, event): """Cast the currently-focused result.""" def f(device, result): """Cast result to the specified device.""" if isinstance(result, URLStream): url = result.url else: url = application.api.get_stream_url(result.id) self.do_stop(None) device.wait() set_volume(device.status.volume_level * 100) device.play_media(url, 'audio/mp3') self.cast_device = device res = self.get_result() if res is None: return wx.Bell() devices = sorted(get_chromecasts(), key=lambda result: result.name) dlg = wx.SingleChoiceDialog( self, 'Choose a device to cast to', 'Cast', ['{} ({})'.format( x.name, (x.status.status_text or 'Not Playing') if x.status is not None else 'No Status' ) for x in devices] ) if dlg.ShowModal() == wx.ID_OK: device = devices[dlg.GetSelection()] else: device = None dlg.Destroy() if device is not None: try: f(device, res) except NotLoggedIn: return do_login(callback=f, args=[device, res])
def get_chromecasts(): devices = pychromecast.get_chromecasts() devices.sort(key=lambda cc: cc.name) return devices
import logging import time import pychromecast from traktcast.trakt import configure_trakt_client from traktcast.hulu import HuluHandler from traktcast.scrobble import TraktScrobblerListener if __name__ == '__main__': logging.basicConfig() logging.getLogger('traktcast').setLevel(logging.DEBUG) configure_trakt_client() devices = pychromecast.get_chromecasts() for device in devices: device.register_handler(HuluHandler(device)) device.media_controller.register_status_listener( TraktScrobblerListener(device)) while True: time.sleep(0.01)
# sending videos import pychromecast if __name__ == "__main__": cast = pychromecast.get_chromecasts()[0] mc = cast.media_controller mc.play_media("http://192.168.0.103:8000/video_test.mp4", content_type = "video/mp4") mc.block_until_active() mc.play()
import sys # if no argument supplied, exit try: if sys.argv[1]: print('[inputSwitch] Searching for Chromecast:') print(sys.argv[1]) except IndexError: print( '[inputSwitch] No Chromecast name found. Remember to set your environment variables.' ) exit() # get a list of chromecasts, find the one we're looking for chromecasts = pychromecast.get_chromecasts() chromecast = False chromecast = next(cc for cc in chromecasts if cc.device.friendly_name == sys.argv[1]) if chromecast: print('[inputSwitch] Found Chromecast:') print(chromecast) else: print( "[inputSwitch] Couldn't find a Chromecast. Did you set your chromecast name env variable correctly?" ) exit() #Checks to see if the Chromecast has been used, and when it finds it has, and no longer is, switches back to Dashboard. has_watched = False
def get_chromecast(host: str = None, name: str = None): if host: return pychromecast.Chromecast(host=host) elif name: chromecasts = pychromecast.get_chromecasts() return next(cc for cc in chromecasts if cc.device.friendly_name == name)
import logging import time import pychromecast from traktcast.trakt import configure_trakt_client from traktcast.hulu import HuluHandler from traktcast.scrobble import TraktScrobblerListener if __name__ == '__main__': logging.basicConfig() logging.getLogger('traktcast').setLevel(logging.DEBUG) configure_trakt_client() devices = pychromecast.get_chromecasts() for device in devices: device.register_handler(HuluHandler(device)) device.media_controller.register_status_listener(TraktScrobblerListener(device)) while True: time.sleep(0.01)
def __init__(self): chromecasts = pychromecast.get_chromecasts() self.chromecasts = [] for chromecast in chromecasts: device = ChromecastDevice(chromecast) self.chromecasts.append(device)
def main(config, wizard, verbose): if verbose: logger.setLevel('DEBUG') else: # pychromecast is by default pretty noisy about caught exceptions logging.getLogger('pychromecast').setLevel('CRITICAL') if wizard: return config_wizard() paths = [config] if config else ['./lastcast.toml', '~/.lastcast.toml'] for path in paths: path = os.path.expanduser(path) if os.path.exists(path): config = load_config(path) break else: click.echo('Config file not found!\n\nUse --wizard to create a config') sys.exit(1) cast_config = config.get('chromecast', {}) device_names = cast_config.get('devices', []) # `name` is the legacy parameter name, supporting it for now. if not device_names and 'name' in cast_config: device_names = [cast_config['name']] if not device_names: click.echo('Need to specify either `devices` or `name` in ' '`[chromecast]` config block!') sys.exit(1) available = pychromecast.get_chromecasts() listeners, missing = connect_to_devices(config, device_names, available) retry_missing = cast_config.get('retry_missing', False) if cast_config.get('ignore_missing', False) and missing: click.echo('Continuing without missing devices: %s' % ', '.join(missing)) missing = [] if missing and not retry_missing: click.echo('Failed to connect to %s. Exiting' % ', '.join(missing)) click.echo('Available devices: %s' % ', '.join([ d.device.friendly_name for d in available ])) sys.exit(1) for i in itertools.count(): for listener in listeners: listener.poll() # If we have any devices missing, periodically try to connect to them if retry_missing and missing and i % RECONNECT_INTERVAL == 0: click.echo('Retrying missing devices: %s' % ', '.join(missing)) available = pychromecast.get_chromecasts(tries=1) new_devices, missing = connect_to_devices(config, missing, available) listeners.extend(new_devices) time.sleep(POLL_INTERVAL)
def find_media_controller(my_uuid): all_cast_devices = pychromecast.get_chromecasts() my_cast_device = next(x for x in all_cast_devices if str(x.device.uuid) == my_uuid) return my_cast_device.media_controller
"Classic Trance": "classictrance_hi", "Eurodance": "eurodance_hi", "Club Sounds": "clubsounds_hi", "Vocal Lounge": "vocalounge_hi", "Electro House": "electrohouse_hi", "Disco House": "discohouse_hi" } audio_model_names = [ "Google Home", "Google Home Mini", "Google Cast Group", "Insignia NS-CSPGASP2", "Insignia NS-CSPGASP" ] ###################################### ######## GLOBALS ##################### ccs = pychromecast.get_chromecasts(tries=3, retry_wait=2, timeout=10) chomecast_names = [] app = Flask(__name__) ###################################### def stop(device): if debug: print("Stopping device: " + device) if device in chomecast_names: cast = next(cc for cc in ccs if cc.device.friendly_name == device) mc = cast.media_controller mc.stop() else: print("Bad device")
def _initialize_cache(self): data = {} devices = pychromecast.get_chromecasts() for device in devices: data[device.name] = device.host self._write_cache(data)
def stop(): chromecasts = pychromecast.get_chromecasts() for cc in chromecasts: cc.media_controller.stop() return {'success': True}
def get_all_casts(): global all_casts if len(all_casts) == 0: all_casts = pychromecast.get_chromecasts() return all_casts
def get_chromecast_player(host=None, name=None): # pragma: no cover """ Get a chromecast preferable using host direcly, if not we will use the name and mnds (slow), if that dont work we will grab the first one. """ try: import pychromecast except ImportError: LOG.warning('Failed to import pychromecast') return None, None # All isnt used atm, lets keep it and # ill fix it later then i create a pr # for plexapi or pychromecast. MESSAGE_TYPE = 'type' TYPE_PLAY = 'PLAY' TYPE_PAUSE = 'PAUSE' TYPE_STOP = 'STOP' TYPE_STEPFORWARD = 'STEPFORWARD' TYPE_STEPBACKWARD = 'STEPBACK' TYPE_PREVIOUS = 'PREVIOUS' TYPE_NEXT = 'NEXT' TYPE_LOAD = 'LOAD' TYPE_DETAILS = 'SHOWDETAILS' TYPE_SEEK = 'SEEK' TYPE_MEDIA_STATUS = 'MEDIA_STATUS' TYPE_GET_STATUS = 'GET_STATUS' TYPE_EDIT_TRACKS_INFO = 'EDIT_TRACKS_INFO' from pychromecast.controllers import BaseController class PlexController(BaseController): """ Controller to interact with Plex namespace. """ def __init__(self): super(PlexController, self).__init__('urn:x-cast:plex', '9AC194DC') self.app_id = '9AC194DC' self.namespace = 'urn:x-cast:plex' self.request_id = 0 def _send_cmd(self, msg, namespace=None, inc_session_id=False, callback_function=None, inc=True): """Wrapper the commands.""" self.logger.debug('Sending msg %r %s %s %s %s', msg, namespace, inc_session_id, callback_function, inc) if inc: self._inc_request() if namespace: old = self.namespace try: self.namespace = namespace self.send_message(msg, inc_session_id=inc_session_id, callback_function=callback_function) finally: self.namespace = old else: self.send_message(msg, inc_session_id=inc_session_id, callback_function=callback_function) def _inc_request(self): self.request_id += 1 return self.request_id def receive_message(self, message, data): """ Called when a messag from plex to our controller is received. I havnt seen any message for ut but lets keep for for now, the tests i have done is minimal. """ self.logger.debug('Plex media receive function called.') if data[MESSAGE_TYPE] == TYPE_MEDIA_STATUS: self.logger.debug('(PlexController) MESSAGE RECEIVED: ' + data) return True return False def stop(self): """Send stop command.""" self._send_cmd({MESSAGE_TYPE: TYPE_STOP}) def pause(self): """Send pause command.""" self._send_cmd({MESSAGE_TYPE: TYPE_PAUSE}) def play(self): """Send play command.""" self._send_cmd({MESSAGE_TYPE: TYPE_PLAY}) def previous(self): """Send previous command.""" self._send_cmd({MESSAGE_TYPE: TYPE_PREVIOUS}) def next(self): self._send_cmd({MESSAGE_TYPE: TYPE_NEXT}) def seek(self, position, resume_state='PLAYBACK_START'): """Send seek command""" self._send_cmd({ MESSAGE_TYPE: TYPE_SEEK, 'currentTime': position, 'resumeState': resume_state }) def rewind(self): """Rewind back to the start""" self.seek(0) def set_volume(self, percent): # Feels dirty.. self._socket_client.receiver_controller.set_volume( float(percent / 100)) def volume_up(self, delta=0.1): """ Increment volume by 0.1 (or delta) unless it is already maxed. Returns the new volume. """ if delta <= 0: raise ValueError( "volume delta must be greater than zero, not {}".format( delta)) return self.set_volume(self.status.volume_level + delta) def volume_down(self, delta=0.1): """ Decrement the volume by 0.1 (or delta) unless it is already 0. Returns the new volume. """ if delta <= 0: raise ValueError( "volume delta must be greater than zero, not {}".format( delta)) return self.set_volume(self.status.volume_level - delta) def mute(self, status=None): """ mute the sound. status is just a override. """ if status is not None: st = status else: st = not status.volume_muted self._socket_client.receiver_controller.set_volume_muted(st) def show_media(self, media): """Show the media on the screen, but don't start it.""" msg = media_to_chromecast_command(media, type=TYPE_DETAILS, requestid=self._inc_request()) def cb(): self._send_cmd(msg, inc_session_id=True, inc=False) self.launch(cb) def quit_app(self): """Quit the plex app""" self._socket_client.receiver_controller.stop_app() @property def status(self): # So to get this we could add a listener and update the data ourself # or get can just use socket_clients # status should get a own pr so we can grab the subtitle (episode title.) # Lets just patch this for now.. def episode_title(self): return self.media_metadata.get('subtitle') mc = self._socket_client.media_controller.status mc.episode_title = property(episode_title) return self._socket_client.media_controller.status def disable_subtitle(self): # Shit does not work. """Disable subtitle.""" self._send_cmd( { MESSAGE_TYPE: TYPE_EDIT_TRACKS_INFO, "activeTrackIds": [] }, namespace='urn:x-cast:com.google.cast.media') def _send_start_play(self, media): msg = media_to_chromecast_command(media, requestid=self._inc_request()) self._send_cmd(msg, namespace='urn:x-cast:com.google.cast.media', inc_session_id=True, inc=False) def play_media(self, item): """Start playback in the chromecast using the selected media. """ def app_launched_callback(): self._send_start_play(item) self.launch(app_launched_callback) def join(self, timeout=None): self._socket_client.join(timeout=timeout) def disconnect(self, timeout=None, blocking=True): self._socket_client.disconnect() if blocking: self.join(timeout=timeout) cast = None try: cast = pychromecast.Chromecast(host=host) except pychromecast.ChromecastConnectionError: chromecasts = pychromecast.get_chromecasts() if len(chromecasts) > 1: cast = next(cc for cc in chromecasts if cc.device.friendly_name == name) else: cast = chromecasts[0] pc = PlexController() cast.register_handler(pc) return pc, cast
def get_chromecasts(self): self.chromecasts, self.browser = get_chromecasts() self.devices = [cc.device.friendly_name for cc in self.chromecasts]
import time import pychromecast import urllib.request class SyncCastDevice: def __init__(self, zone, cc): self.zone = zone self.device = cc self.baseUrl = 'http://localhost:5000/api/control/' self.status = 'off' print("Initializing...") print("Getting all Chromecasts on the network.") all_ccs = pychromecast.get_chromecasts() """ Assign relevant Chromecasts/Groups Zones assigned in order of list/tuple """ cc_list = ("Dining Room group", "Guest Bathroom group", "Office group", "Master Bathroom group") cc_devices = [] for cc in all_ccs: for sel in cc_list: if (cc.device.friendly_name == sel): zone = cc_list.index(cc.device.friendly_name) + 1 print("Adding Zone " + str(zone) + ": " + sel) cc_devices.append(SyncCastDevice(zone, cc))
import pychromecast all_casts = pychromecast.get_chromecasts() livingroom = next((x for x in all_casts if x.device.friendly_name == 'Living Room'), None) if livingroom == None: print "Living Room Chromecast not found." exit(1) livingroom.wait() def is_casting(media_status): return media_status.player_state != pychromecast.controllers.media.MEDIA_PLAYER_STATE_UNKNOWN def is_connected(cast_status): return cast_status.session_id != None class Listener: def __init__(self, cast): self.curr_is_connected = is_connected(cast.status) cast.register_status_listener(self) def new_cast_status(self, status): new_is_connected = is_connected(status) if not self.curr_is_connected and new_is_connected: print "Connected" elif self.curr_is_connected and not new_is_connected: print "Disconnected" self.curr_is_connected = new_is_connected
def com_chromecast_discover(self): """ # find chromecast as dict """ self.chromecast_dev = pychromecast.get_chromecasts() return self.chromecast_dev
def config_wizard(): ''' Text User Interface to generate initial lastcast.toml config. ''' config = {'chromecast': {}} if click.confirm('Set up last.fm account?', default=True): click.echo(''' You'll need to create a last.fm API application first. Do so here: http://www.last.fm/api/account/create What you fill in doesn't matter at all, just make sure to save the API Key and Shared Secret. ''') config['lastfm'] = { key: click.prompt(key, type=str, hide_input=hidden) for (key, hidden) in [('user_name', False), ('password', True), ('api_key', False), ('api_secret', True)] } if click.confirm('Set up Libre.fm account?'): libre_conf = { key: click.prompt(key, type=str, hide_input=hidden) for (key, hidden) in [('user_name', False), ('password', True)] } libre = pylast.LibreFMNetwork( username=libre_conf['user_name'], password_hash=pylast.md5(libre_conf['password'])) skg = pylast.SessionKeyGenerator(libre) url = skg.get_web_auth_url() click.echo('''Please grant lastcast access to your Libre.fm account: %s ''' % url) click.echo('Hit enter when ready') click.getchar() libre_conf['session_key'] = skg.get_web_auth_session_key(url) config['librefm'] = libre_conf available = [ cc.device.friendly_name for cc in pychromecast.get_chromecasts() ] if len(available) == 1: config['chromecast']['devices'] = [available[0]] if len(available) > 1 or click.confirm('Manually specify cast device?', default=True): click.echo('\n\nAvailable cast devices: %s' % ', '.join(available)) device_names = click.prompt('Which device(s) should be used? (comma separated)') device_names = [d.strip() for d in device_names.split(',') if d.strip != ''] config['chromecast']['devices'] = device_names click.echo('\n\nDefault chromecast apps to scrobble from: %s' % ', '.join(APP_WHITELIST)) apps = click.prompt('Comma separated apps [blank for default]', default='', show_default=False) apps = [app.strip() for app in apps.split(',') if app.strip() != ''] if apps: config['chromecast']['app_whitelist'] = apps generated = toml.dumps(config) click.echo('Generated config:\n\n%s' % generated) if click.confirm('Write to ~/.lastcast.toml?', default=True): with open(os.path.expanduser('~/.lastcast.toml'), 'w') as fp: fp.write(generated)
import pychromecast import zeroconf parser = argparse.ArgumentParser( description="Example on how to list chromecasts.") parser.add_argument("--show-debug", help="Enable debug log", action="store_true") parser.add_argument("--show-zeroconf-debug", help="Enable zeroconf debug log", action="store_true") args = parser.parse_args() if args.show_debug: logging.basicConfig(level=logging.DEBUG) if args.show_zeroconf_debug: print("Zeroconf version: " + zeroconf.__version__) logging.getLogger("zeroconf").setLevel(logging.DEBUG) casts, browser = pychromecast.get_chromecasts() # Shut down discovery as we don't care about updates pychromecast.discovery.stop_discovery(browser) if len(casts) == 0: print("No Devices Found") exit() print("Found cast devices:") for cast in casts: print(' "{}" on mDNS service {} with UUID:{}'.format( cast.name, cast._services, cast.uuid))
class connlistener: def __init__(self, mz): self._mz=mz def new_connection_status(self, connection_status): """Handle reception of a new ConnectionStatus.""" if connection_status.status == 'CONNECTED': self._mz.update_members() class mzlistener: def multizone_member_added(self, uuid): print("New member: {}".format(uuid)) def multizone_member_removed(self, uuid): print("Removed member: {}".format(uuid)) def multizone_status_received(self): print("Members: {}".format(mz.members)) chromecasts = pychromecast.get_chromecasts(timeout=2) cast = next(cc for cc in chromecasts if cc.device.friendly_name == CAST_NAME) mz = MultizoneController(cast.uuid) mz.register_listener(mzlistener()) cast.register_handler(mz) cast.register_connection_listener(connlistener(mz)) cast.wait() while True: time.sleep(1)
def print_all_chromecasts(): all_cast_devices = pychromecast.get_chromecasts() print("All Chromecast devices:", all_cast_devices)