Python pychromecast.Chromecast() Examples

The following are 22 code examples of pychromecast.Chromecast(). 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: controllers.py    From catt with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, cast: pychromecast.Chromecast, app: App, prep: Optional[str] = None) -> None:
        self._cast = cast
        self.name = app.name
        self.info_type = None
        self.save_capability = None
        self.playlist_capability = None

        self._cast_listener = CastStatusListener(app.id, self._cast.app_id)
        self._cast.register_status_listener(self._cast_listener)

        try:
            self._cast.register_handler(self._controller)  # type: ignore
        except AttributeError:
            self._controller = self._cast.media_controller

        if prep == "app":
            self.prep_app()
        elif prep == "control":
            self.prep_control()
        elif prep == "info":
            self.prep_info() 
Example #2
Source File: controllers.py    From catt with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def kill(self, idle_only=False, force=False):
        """
        Kills current Chromecast session.

        :param idle_only: If set, session is only killed if the active Chromecast app
                          is idle. Use to avoid killing an active streaming session
                          when catt fails with certain invalid actions (such as trying
                          to cast an empty playlist).
        :type idle_only: bool
        :param force: If set, a dummy chromecast app is launched before killing the session.
                      This is a workaround for some devices that do not respond to this
                      command under certain circumstances.
        :type force: bool
        """

        if idle_only and not self._is_idle:
            return
        # The Google cloud app which is launched by the workaround is functionally
        # identical to the Default Media Receiver.
        if force:
            listener = CastStatusListener(CLOUD_APP_ID)
            self._cast.register_status_listener(listener)
            self._cast.start_app(CLOUD_APP_ID)
            listener.app_ready.wait()
        self._cast.quit_app() 
Example #3
Source File: chromecast.py    From platypush with MIT License 6 votes vote down vote up
def mute(self, chromecast=None):
        """
        Toggle the mute status on the Chromecast

        :param chromecast: Chromecast to cast to. If none is specified, then the default configured Chromecast
            will be used.
        :type chromecast: str
        """

        chromecast = chromecast or self.chromecast
        cast = self.get_chromecast(chromecast)
        cast.set_volume_muted(not cast.status.volume_muted)
        cast.wait()
        return self.status(chromecast=chromecast)


# vim:sw=4:ts=4:et: 
Example #4
Source File: chromecast.py    From platypush with MIT License 6 votes vote down vote up
def voldown(self, chromecast=None, step=10):
        """
        Turn down the Chromecast volume by 10% or step.

        :param chromecast: Chromecast to cast to. If none is specified, then the default configured Chromecast
            will be used.
        :type chromecast: str

        :param step: Volume decrement between 0 and 100 (default: 100%)
        :type step: float
        """

        chromecast = chromecast or self.chromecast
        cast = self.get_chromecast(chromecast)
        step /= 100
        cast.volume_down(max(step, 0))
        cast.wait()
        return self.status(chromecast=chromecast) 
Example #5
Source File: chromecast.py    From platypush with MIT License 6 votes vote down vote up
def disconnect(self, chromecast=None, timeout=None, blocking=True):
        """
        Disconnect a Chromecast and wait for it to terminate

        :param chromecast: Chromecast to cast to. If none is specified, then the default configured Chromecast
            will be used.
        :type chromecast: str

        :param timeout: Number of seconds to wait for disconnection (default: None: block until termination)
        :type timeout: float

        :param blocking: If set (default), then the code will wait until disconnection, otherwise it will return
            immediately.
        :type blocking: bool
        """

        cast = self.get_chromecast(chromecast)
        cast.disconnect(timeout=timeout, blocking=blocking) 
Example #6
Source File: chromecast.py    From platypush with MIT License 6 votes vote down vote up
def volup(self, chromecast=None, step=10):
        """
        Turn up the Chromecast volume by 10% or step.

        :param chromecast: Chromecast to cast to. If none is specified, then the default configured Chromecast
            will be used.
        :type chromecast: str

        :param step: Volume increment between 0 and 100 (default: 100%)
        :type step: float
        """

        chromecast = chromecast or self.chromecast
        cast = self.get_chromecast(chromecast)
        step /= 100
        cast.volume_up(min(step, 1))
        cast.wait()
        return self.status(chromecast=chromecast) 
Example #7
Source File: chromecast.py    From platypush with MIT License 6 votes vote down vote up
def set_volume(self, volume, chromecast=None):
        """
        Set the Chromecast volume

        :param volume: Volume to be set, between 0 and 100
        :type volume: float

        :param chromecast: Chromecast to cast to. If none is specified, then the default configured Chromecast
            will be used.
        :type chromecast: str
        """

        chromecast = chromecast or self.chromecast
        cast = self.get_chromecast(chromecast)
        cast.set_volume(volume/100)
        cast.wait()
        status = self.status(chromecast=chromecast)
        status.output['volume'] = volume
        return status 
Example #8
Source File: chromecast.py    From platypush with MIT License 5 votes vote down vote up
def join(self, chromecast=None, timeout=None):
        """
        Blocks the thread until the Chromecast connection is terminated.

        :param chromecast: Chromecast to cast to. If none is specified, then the default configured Chromecast
            will be used.
        :type chromecast: str

        :param timeout: Number of seconds to wait for disconnection (default: None: block until termination)
        :type timeout: float
        """

        cast = self.get_chromecast(chromecast)
        cast.join(timeout=timeout) 
Example #9
Source File: actions.py    From GassistPi with GNU General Public License v3.0 5 votes vote down vote up
def chromecast_control(action):
    # Chromecast declarations
    # Do not rename/change "TV" its a variable
    TV = pychromecast.Chromecast("192.168.1.13") #Change ip to match the ip-address of your Chromecast
    mc = TV.media_controller
    if 'pause'.lower() in str(action).lower():
        TV.wait()
        time.sleep(1)
        mc.pause()
    if 'resume'.lower() in str(action).lower():
        TV.wait()
        time.sleep(1)
        mc.play()
    if 'end'.lower() in str(action).lower():
        TV.wait()
        time.sleep(1)
        mc.stop()
    if 'volume'.lower() in str(action).lower():
        if 'up'.lower() in str(action).lower():
            TV.wait()
            time.sleep(1)
            TV.volume_up(0.2)
        if 'down'.lower() in str(action).lower():
            TV.wait()
            time.sleep(1)
            TV.volume_down(0.2)

#-------------------End of Chromecast Functions---------------------------------

#-------------------Start of Kickstarter Search functions----------------------- 
Example #10
Source File: actions.py    From GassistPi with GNU General Public License v3.0 5 votes vote down vote up
def chromecast_play_video(phrase):
    # Chromecast declarations
    # Do not rename/change "TV" its a variable
    TV = pychromecast.Chromecast("192.168.1.13") #Change ip to match the ip-address of your Chromecast
    mc = TV.media_controller
    idx1=phrase.find(custom_action_keyword['Dict']['Play'])
    idx2=phrase.find('on chromecast')
    query=phrase[idx1:idx2]
    query=query.replace(custom_action_keyword['Dict']['Play'],'',1)
    query=query.replace('on chromecast','',1)
    query=query.strip()
    youtubelinks=youtube_search(query)
    youtubeurl=youtubelinks[0]
    streams=youtube_stream_link(youtubeurl)
    videostream=streams[1]
    TV.wait()
    time.sleep(1)
    mc.play_media(videostream,'video/mp4') 
Example #11
Source File: actions.py    From GassistPi with GNU General Public License v3.0 5 votes vote down vote up
def YouTube_No_Autoplay(phrase):
    try:
        urllist=[]
        currenttrackid=0
        idx1=phrase.find(custom_action_keyword['Dict']['Play'])
        idx2=phrase.find(custom_action_keyword['Dict']['From_youtube'])
        track=phrase[idx1:idx2]
        track = track.replace(custom_action_keyword['Dict']['Play'],'',1)
        track = track.replace(custom_action_keyword['Dict']['From_youtube'],'',1)
        track=track.strip()
        say("Getting youtube link")
        print(track)
        urlid=youtube_search(track)
        if urlid is not None:
            fullurl="https://www.youtube.com/watch?v="+urlid
            audiostream,videostream=youtube_stream_link(fullurl)
            streamurl=audiostream
            urllist.append(streamurl)
            vlcplayer.media_manager(urllist,'YouTube')
            vlcplayer.youtube_player(currenttrackid)
        else:
            say("Unable to find songs matching your request")

    except Exception as e:
        print(e)
        say('Encountered an exception please check the logs.')

#-----------------End of Functions for YouTube Streaming---------------------



#--------------Start of Chromecast functions----------------------------------- 
Example #12
Source File: gnomecast.py    From gnomecast with GNU General Public License v3.0 5 votes vote down vote up
def get_nonlocal_cast(self):
    dialogWindow = Gtk.MessageDialog(self.win,
                          Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
                          Gtk.MessageType.QUESTION,
                          Gtk.ButtonsType.OK_CANCEL,
                          '\nPlease specify the IP address or hostname of a Chromecast device:')

    dialogWindow.set_title('Add a non-local Chromecast')

    dialogBox = dialogWindow.get_content_area()
    userEntry = Gtk.Entry()
#    userEntry.set_size_request(250,0)
    dialogBox.pack_end(userEntry, False, False, 0)

    dialogWindow.show_all()
    response = dialogWindow.run()
    text = userEntry.get_text()
    dialogWindow.destroy()
    if (response == Gtk.ResponseType.OK) and (text != ''):
      print(text)
      try:
        cast = pychromecast.Chromecast(text)
        self.cast_store.append([cast, text])
        self.cast_combo.set_active(len(self.cast_store)-1)
      except pychromecast.error.ChromecastConnectionError:
        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." % text)
        dialog.run()
        dialog.destroy() 
Example #13
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 #14
Source File: chromecast.py    From platypush with MIT License 5 votes vote down vote up
def reboot(self, chromecast=None):
        """
        Reboots the Chromecast

        :param chromecast: Chromecast to cast to. If none is specified, then the default configured Chromecast
            will be used.
        :type chromecast: str
        """

        cast = self.get_chromecast(chromecast)
        cast.reboot() 
Example #15
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 #16
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 #17
Source File: chromecast.py    From platypush with MIT License 5 votes vote down vote up
def __init__(self, chromecast=None, *args, **kwargs):
        """
        :param chromecast: Default Chromecast to cast to if no name is specified
        :type chromecast: str
        """

        super().__init__(*args, **kwargs)

        self._is_local = False
        self.chromecast = chromecast
        self.chromecasts = {}
        self._media_listeners = {} 
Example #18
Source File: controllers.py    From catt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def wait_for(self, states: list, invert: bool = False, fail: bool = False, timeout: Optional[int] = None) -> bool:
        media_listener = MediaStatusListener(
            self._cast.media_controller.status.player_state, states, invert=invert, fail=fail
        )
        self._cast.media_controller.register_status_listener(media_listener)

        try:
            return media_listener.wait_for_states(timeout=timeout)
        except pychromecast.error.UnsupportedNamespace:
            raise CastError("Chromecast app operation was interrupted") 
Example #19
Source File: controllers.py    From catt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_cast(device: Optional[str] = None) -> Tuple[pychromecast.Chromecast, CCInfo]:
    """
    Attempt to connect with requested device (or any device if none has been specified).

    :param device: Can be an ip-address or a name.
    :type device: str
    :returns: Chromecast object for use in a CastController,
              and CCInfo object for use in setup_cast and StreamInfo
    :rtype: (pychromecast.Chromecast, CCInfo)
    """

    cast = None

    if device and is_ipaddress(device):
        cast = get_chromecast_with_ip(device, DEFAULT_PORT)
        if not cast:
            msg = "No device found at {}".format(device)
            raise CastError(msg)
        cc_info = CCInfo(cast.host, cast.port, None, None, cast.cast_type)
    else:
        cache = Cache()
        maybe_cc_info = cache.get_data(device)

        if maybe_cc_info:
            # Get the Chromecast from the CCInfo IP/port.
            cast = get_chromecast_with_ip(maybe_cc_info.ip, maybe_cc_info.port)
            cc_info = maybe_cc_info

        if not cast:
            cast = get_chromecast(device)
            if not cast:
                msg = 'Specified device "{}" not found'.format(device) if device else "No devices found"
                raise CastError(msg)
            cc_info = CCInfo(cast.host, cast.port, cast.device.manufacturer, cast.model_name, cast.cast_type)
            cache.set_data(cast.name, cc_info)

    cast.wait()
    return (cast, cc_info) 
Example #20
Source File: controllers.py    From catt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_chromecast_with_ip(device_ip: str, port: int = DEFAULT_PORT) -> Optional[pychromecast.Chromecast]:
    try:
        # tries = 1 is necessary in order to stop pychromecast engaging
        # in a retry behaviour when ip is correct, but port is wrong.
        return pychromecast.Chromecast(device_ip, port=port, tries=1)
    except pychromecast.error.ChromecastConnectionError:
        return None 
Example #21
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 #22
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()]