Python pychromecast.get_chromecasts() Examples

The following are 14 code examples of pychromecast.get_chromecasts(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pychromecast , or try the search function .
Example #1
Source File: sensor.py    From spotcast with Apache License 2.0 6 votes vote down vote up
def update(self):
        import pychromecast
        # from cast/media_player.py but is missing cast_type
        # KNOWN_CHROMECAST_INFO_KEY = 'cast_known_chromecasts'
        # _LOGGER.info('KNOWN_CHROMECAST_INFO_KEY: %s', self.hass.data[KNOWN_CHROMECAST_INFO_KEY])

        self._chromecast_devices = pychromecast.get_chromecasts()
        _LOGGER.debug('Found chromecast devices: %s', self._chromecast_devices)
        chromecasts = []
        for cast in self._chromecast_devices:
            device = {
                'name': cast.name,
                'cast_type': cast.cast_type,
                'model_name': cast.model_name,
                'uuid': str(cast.uuid),
                'manufacturer': cast.device.manufacturer
            }
            chromecasts.append(device)
        self._attributes['devices_json'] = json.dumps(chromecasts, ensure_ascii=False)
        self._attributes['devices'] = chromecasts
        self._attributes['last_update'] = dt.now().isoformat('T')
        self._state = STATE_OK 
Example #2
Source File: __init__.py    From lastcast with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: send-video-youtube-v2.py    From HomePWN with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        if not self.args["rhost"] and not self.args["name"]:
            print_info("Show options, it's necessary to configure onename or rhost")
            return
        if str(self.args["timeout"]) == "None":
            self.args["timeout"] = 6
        try:
            chromecasts = pychromecast.get_chromecasts(timeout=self.args["timeout"])
            cast = next(cc for cc in chromecasts if (cc.device.friendly_name == self.args["name"] or cc.host == self.args["rhost"]))
            cast.wait()
            print_info("Device found, sending video")
        except:
            print_error("Device no found")
            return

        yt = YouTubeController()
        cast.register_handler(yt)
        yt.play_video(self.args["video"])
        print_ok("Done!") 
Example #4
Source File: controllers.py    From catt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_chromecasts() -> List[pychromecast.Chromecast]:
    devices = pychromecast.get_chromecasts()
    devices.sort(key=lambda cc: cc.name)
    return devices 
Example #5
Source File: controllers.py    From catt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_chromecast(device_name: Optional[str]) -> Optional[pychromecast.Chromecast]:
    devices = get_chromecasts()
    if not devices:
        return None

    if device_name:
        try:
            return next(cc for cc in devices if cc.name == device_name)
        except StopIteration:
            return None
    else:
        return devices[0] 
Example #6
Source File: controllers.py    From catt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self):
        vhash = hashlib.sha1(__version__.encode()).hexdigest()[:8]
        cache_path = Path(tempfile.gettempdir(), "catt_{}_cache".format(vhash), "chromecast_hosts")
        super(Cache, self).__init__(cache_path)
        self._create_store_dir()

        if not self.store_path.is_file():
            devices = get_chromecasts()
            cache_data = {
                d.name: CCInfo(d.host, d.port, d.device.manufacturer, d.model_name, d.cast_type).all_info
                for d in devices
            }
            self._write_store(cache_data) 
Example #7
Source File: __init__.py    From spotcast with Apache License 2.0 5 votes vote down vote up
def getChromecastDevice(self, device_name):
        import pychromecast

        # Get cast from discovered devices of cast platform
        known_devices = self.hass.data.get(KNOWN_CHROMECAST_INFO_KEY, [])
        cast_info = next((x for x in known_devices if x.friendly_name == device_name), None)
        _LOGGER.debug("cast info: %s", cast_info)

        if cast_info:
            return pychromecast._get_chromecast_from_host(
                (
                    cast_info.host,
                    cast_info.port,
                    cast_info.uuid,
                    cast_info.model_name,
                    cast_info.friendly_name,
                )
            )
        _LOGGER.error(
            "Could not find device %s from hass.data, falling back to pychromecast scan",
            device_name,
        )

        # Discover devices manually
        chromecasts = pychromecast.get_chromecasts()
        for _cast in chromecasts:
            if _cast.name == device_name:
                _LOGGER.debug("Fallback, found cast device: %s", _cast)
                return _cast

        raise HomeAssistantError("Could not find device with name {}".format(device_name)) 
Example #8
Source File: adapter.py    From chromecast-mqtt-connector with Mozilla Public License 2.0 5 votes vote down vote up
def _internal_create_connection(self, device_name):
        try:
            self.mqtt_properties.write_connection_status(CONNECTION_STATUS_WAITING_FOR_DEVICE)
            devices = get_chromecasts(tries=5)

            for device in devices:
                if device.device.friendly_name == device_name:
                    self.device = device
                    break

            if self.device is None:
                self.logger.error("was not able to find chromecast %s" % self.device_name)
                raise ConnectionUnavailableException()

            self.device.wait()
            self.device.register_status_listener(self)
            self.device.media_controller.register_status_listener(self)
            self.device.register_launch_error_listener(self)
            self.device.register_connection_listener(self)

            self.device_connected = True  # alibi action
            self.logger.info("connected to chromecast %s" % self.device_name)
        except PyChromecastError:
            self.logger.exception("had connection error while finding chromecast %s" % self.device_name)

            self.device_connected = False 
Example #9
Source File: chromecast_device.py    From smart-tv-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def find(config: Config) -> typing.List[Device]:
        return [
            ChromecastDevice(device)
            for device in pychromecast.get_chromecasts(
                timeout=config.chromecast_scan_timeout)
        ] 
Example #10
Source File: chromecast.py    From platypush with MIT License 5 votes vote down vote up
def get_chromecast(self, chromecast=None, n_tries=2):
        import pychromecast
        if isinstance(chromecast, pychromecast.Chromecast):
            return chromecast

        if not chromecast:
            if not self.chromecast:
                raise RuntimeError('No Chromecast specified nor default Chromecast configured')
            chromecast = self.chromecast

        if chromecast not in self.chromecasts:
            casts = {}
            while n_tries > 0:
                n_tries -= 1
                casts.update({
                    cast.device.friendly_name: cast
                    for cast in pychromecast.get_chromecasts()
                })

                if chromecast in casts:
                    self.chromecasts.update(casts)
                    break

            if chromecast not in self.chromecasts:
                raise RuntimeError('Device {} not found'.format(chromecast))

        cast = self.chromecasts[chromecast]
        cast.wait()
        return cast 
Example #11
Source File: discovery.py    From HomePWN with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        print_info("Searching devices")
        chromecasts = pychromecast.get_chromecasts(timeout=self.args["timeout"])
        if chromecasts:
            for cast in [cc for cc in chromecasts]:
                print_info(f"{cast.device.friendly_name} ({cast.device.cast_type} - {cast.device.manufacturer}) => {cast.host}")
        else:
            print_info("No devices found") 
Example #12
Source File: gnomecast.py    From gnomecast with GNU General Public License v3.0 5 votes vote down vote up
def load_casts(self, device=None):
    chromecasts = pychromecast.get_chromecasts()
    def f():
      self.cast_store.clear()
      self.cast_store.append([None, "Select a cast device..."])
      self.cast_store.append([-1, 'Add a non-local Chromecast...'])
      for cc in chromecasts:
        friendly_name = cc.device.friendly_name
        if cc.cast_type!='cast':
          friendly_name = '%s (%s)' % (friendly_name, cc.cast_type)
        self.cast_store.append([cc, friendly_name])
      if device:
        found = False
        for i, cc in enumerate(chromecasts):
          if device == cc.device.friendly_name:
            self.cast_combo.set_active(i+1)
            found = True
        if not found:
          self.cast_combo.set_active(0)
          dialog = Gtk.MessageDialog(self.win, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, "Chromecast Not Found")
          dialog.format_secondary_text("The Chromecast '%s' wasn't found." % device)
          dialog.run()
          dialog.destroy()
      else:
        self.cast_combo.set_active(2 if len(chromecasts) == 1 else 0)
    GLib.idle_add(f) 
Example #13
Source File: __init__.py    From lastcast with MIT License 4 votes vote down vote up
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) 
Example #14
Source File: chromecast.py    From platypush with MIT License 4 votes vote down vote up
def get_chromecasts(self, tries=2, retry_wait=10, timeout=60,
                        blocking=True, callback=None):
        """
        Get the list of Chromecast devices

        :param tries: Number of retries (default: 2)
        :type tries: int

        :param retry_wait: Number of seconds between retries (default: 10 seconds)
        :type retry_wait: int

        :param timeout: Timeout before failing the call (default: 60 seconds)
        :type timeout: int

        :param blocking: If true, then the function will block until all the Chromecast
            devices have been scanned. If false, then the provided callback function will be
            invoked when a new device is discovered
        :type blocking: bool

        :param callback: If blocking is false, then you can provide a callback function that
            will be invoked when a new device is discovered
        :type callback: func
        """

        import pychromecast
        self.chromecasts.update({
            cast.device.friendly_name: cast
            for cast in pychromecast.get_chromecasts(tries=tries, retry_wait=retry_wait,
                                                     timeout=timeout, blocking=blocking,
                                                     callback=callback)
        })

        for name, cast in self.chromecasts.items():
            self._update_listeners(name, cast)

        return [{
            'type': cc.cast_type,
            'name': cc.name,
            'manufacturer': cc.device.manufacturer,
            'model_name': cc.model_name,
            'uuid': str(cc.device.uuid),
            'address': cc.host,
            'port': cc.port,

            'status': ({
                'app': {
                    'id': cc.app_id,
                    'name': cc.app_display_name,
                },

                'media': self.status(cc.name).output,
                'is_active_input': cc.status.is_active_input,
                'is_stand_by': cc.status.is_stand_by,
                'is_idle': cc.is_idle,
                'namespaces': cc.status.namespaces,
                'volume': round(100*cc.status.volume_level, 2),
                'muted': cc.status.volume_muted,
            } if cc.status else {}),
        } for cc in self.chromecasts.values()]