How to use the pychromecast.controllers.BaseController function in PyChromecast

To help you get started, we’ve selected a few PyChromecast examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github balloob / pychromecast / pychromecast / socket_client.py View on Github external
"Chromecast is disconnected. " "Cannot ping until reconnected."
            )

    def reset(self):
        """ Reset expired counter. """
        self.last_pong = time.time()

    def is_expired(self):
        """ Indicates if connection has expired. """
        if time.time() - self.last_ping > HB_PING_TIME:
            self.ping()

        return (time.time() - self.last_pong) > HB_PING_TIME + HB_PONG_TIME


class ReceiverController(BaseController):
    """
    Controller to interact with the Chromecast platform.

    :param cast_type: Type of Chromecast device.
    """

    def __init__(self, cast_type=CAST_TYPE_CHROMECAST, blocking=True):
        super(ReceiverController, self).__init__(NS_RECEIVER, target_platform=True)

        self.status = None
        self.launch_failure = None
        self.app_to_launch = None
        self.cast_type = cast_type
        self.blocking = blocking
        self.app_launch_event = threading.Event()
        self.app_launch_event_function = None
github balloob / pychromecast / pychromecast / controllers / media.py View on Github external
"track": self.track,
            "subtitle_tracks": self.subtitle_tracks,
            "images": self.images,
            "supports_pause": self.supports_pause,
            "supports_seek": self.supports_seek,
            "supports_stream_volume": self.supports_stream_volume,
            "supports_stream_mute": self.supports_stream_mute,
            "supports_skip_forward": self.supports_skip_forward,
            "supports_skip_backward": self.supports_skip_backward,
        }
        info.update(self.__dict__)
        return "".format(info)


# pylint: disable=too-many-public-methods
class MediaController(BaseController):
    """ Controller to interact with Google media namespace. """

    def __init__(self):
        super(MediaController, self).__init__("urn:x-cast:com.google.cast.media")

        self.media_session_id = 0
        self.status = MediaStatus()
        self.session_active_event = threading.Event()
        self.app_id = APP_MEDIA_RECEIVER
        self._status_listeners = []

    def channel_connected(self):
        """ Called when media channel is connected. Will update status. """
        self.update_status()

    def channel_disconnected(self):
github balloob / pychromecast / pychromecast / socket_client.py View on Github external
self._open_channels.remove(destination_id)

            self.handle_channel_disconnected()

    def handle_channel_disconnected(self):
        """ Handles a channel being disconnected. """
        for namespace in self.app_namespaces:
            if namespace in self._handlers:
                self._handlers[namespace].channel_disconnected()

        self.app_namespaces = []
        self.destination_id = None
        self.session_id = None


class ConnectionController(BaseController):
    """ Controller to respond to connection messages. """

    def __init__(self):
        super(ConnectionController, self).__init__(NS_CONNECTION)

    def receive_message(self, message, data):
        """ Called when a connection message is received. """
        if self._socket_client.is_stopped:
            return True

        if data[MESSAGE_TYPE] == TYPE_CLOSE:
            # The cast device is asking us to acknowledge closing this channel.
            self._socket_client.disconnect_channel(message.source_id)

            # Schedule a status update so that a channel is created.
            self._socket_client.receiver_controller.update_status()
github pkkid / python-plexapi / plexapi / chromecast.py View on Github external
'accessToken': media._server._token,  # Create a server.transit-token() method.
                    'user': {
                        'username': media._server.myPlexUsername
                    }
                },
                'containerKey': '/playQueues/{}?own=1&window=200'.format(plq)
            },
            'autoplay': g('autoplay', True),
            'currentTime': g('currenttime', 0)
        }
    }

    return d


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
        self.play_media_event = threading.Event()

    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:
github balloob / pychromecast / pychromecast / controllers / spotify.py View on Github external
import threading

from . import BaseController
from ..config import APP_SPOTIFY
from ..error import LaunchError

APP_NAMESPACE = "urn:x-cast:com.spotify.chromecast.secure.v1"
TYPE_GET_INFO = "getInfo"
TYPE_GET_INFO_RESPONSE = "getInfoResponse"
TYPE_SET_CREDENTIALS = "setCredentials"
TYPE_SET_CREDENTIALS_ERROR = "setCredentialsError"
TYPE_SET_CREDENTIALS_RESPONSE = "setCredentialsResponse"


# pylint: disable=too-many-instance-attributes
class SpotifyController(BaseController):
    """ Controller to interact with Spotify namespace. """

    # pylint: disable=useless-super-delegation
    # The pylint rule useless-super-delegation doesn't realize
    # we are setting default values here.
    def __init__(self, access_token, expires):
        super(SpotifyController, self).__init__(APP_NAMESPACE, APP_SPOTIFY)
        if access_token is None or expires is None:
            raise ValueError("access_token and expires cannot be empty")

        self.logger = logging.getLogger(__name__)
        self.session_started = False
        self.access_token = access_token
        self.expires = expires
        self.is_launched = False
        self.device = None
github d8ahazard / FlexTV.bundle / Contents / Libraries / Shared / pychromecast / controllers / plex.py View on Github external
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_SEEK = "SEEK"
TYPE_MEDIA_STATUS = 'MEDIA_STATUS'
TYPE_GET_STATUS = "GET_STATUS"


class PlexController(BaseController):
    """ Controller to interact with Plex namespace. """

    def __init__(self,cast):
        super(PlexController, self).__init__(
            "urn:x-cast:plex", "9AC194DC")
        self.app_id = "9AC194DC"
        self.namespace = "urn:x-cast:plex"
        self.request_id = 0
        self.media_session_id = 0
        self.receiver = None
        self.last_message = "No messages sent"
        self.media_meta = {}
        self.volume = cast.status.volume_level
        self.muted = False
        self.stream_type = ""
        self.state = "Idle"
github balloob / pychromecast / pychromecast / controllers / multizone.py View on Github external
def deregister_listener(self, member_uuid, listener):
        """ Deregister listener for audio group changes of cast uuid."""
        self._casts[str(member_uuid)]["listeners"].remove(listener)

    def get_multizone_memberships(self, member_uuid):
        """ Return a list of audio groups in which cast member_uuid is a member
        """
        return list(self._casts[str(member_uuid)]["groups"])

    def get_multizone_mediacontroller(self, group_uuid):
        """ Get mediacontroller of a group """
        return self._groups[str(group_uuid)]["chromecast"].media_controller


class MultizoneController(BaseController):
    """ Controller to monitor audio group members. """

    def __init__(self, uuid):
        self._members = {}
        self._status_listeners = []
        self._uuid = str(uuid)
        super(MultizoneController, self).__init__(
            MULTIZONE_NAMESPACE, target_platform=True
        )

    def _add_member(self, uuid, name):
        if uuid not in self._members:
            self._members[uuid] = name
            _LOGGER.debug(
                "(%s) Added member %s(%s), members: %s",
                self._uuid,
github skorokithakis / catt / catt / youtube.py View on Github external
TYPE_STATUS = "mdxSessionStatus"
ATTR_SCREEN_ID = "screenId"
TYPE_PLAY = "PLAY"
TYPE_PAUSE = "PAUSE"
TYPE_STOP = "STOP"


class YoutubeSessionError(Exception):
    pass


class YoutubeControllerError(Exception):
    pass


class YouTubeController(BaseController):
    """ Controller to interact with Youtube."""

    def __init__(self):
        super(YouTubeController, self).__init__("urn:x-cast:com.google.youtube.mdx", "233637DE")

        self._xsrf_token = None
        self._lounge_token = None
        self._gsession_id = None
        self._sid = None
        self._ofs = 0
        self._first_video = None
        self._playlist_id = None
        self.screen_id = None
        self.video_id = None
        self.playlist = None
        self._now_playing = None
github balloob / pychromecast / pychromecast / controllers / youtube.py View on Github external
"""
import threading
from casttube import YouTubeSession

from . import BaseController
from ..error import UnsupportedNamespace
from ..config import APP_YOUTUBE

YOUTUBE_NAMESPACE = "urn:x-cast:com.google.youtube.mdx"
TYPE_GET_SCREEN_ID = "getMdxSessionStatus"
TYPE_STATUS = "mdxSessionStatus"
ATTR_SCREEN_ID = "screenId"
MESSAGE_TYPE = "type"


class YouTubeController(BaseController):
    """ Controller to interact with Youtube."""

    def __init__(self):
        super(YouTubeController, self).__init__(YOUTUBE_NAMESPACE, APP_YOUTUBE)
        self.status_update_event = threading.Event()
        self._screen_id = None
        self._session = None

    def start_session_if_none(self):
        """
        Starts a session it is not yet initialized.
        """
        if not (self._screen_id and self._session):
            self.update_screen_id()
            self._session = YouTubeSession(screen_id=self._screen_id)
github balloob / pychromecast / pychromecast / socket_client.py View on Github external
if self._socket_client.is_stopped:
            return True

        if data[MESSAGE_TYPE] == TYPE_CLOSE:
            # The cast device is asking us to acknowledge closing this channel.
            self._socket_client.disconnect_channel(message.source_id)

            # Schedule a status update so that a channel is created.
            self._socket_client.receiver_controller.update_status()

            return True

        return False


class HeartbeatController(BaseController):
    """ Controller to respond to heartbeat messages. """

    def __init__(self):
        super(HeartbeatController, self).__init__(NS_HEARTBEAT, target_platform=True)
        self.last_ping = 0
        self.last_pong = time.time()

    def receive_message(self, message, data):
        """ Called when a heartbeat message is received. """
        if self._socket_client.is_stopped:
            return True

        if data[MESSAGE_TYPE] == TYPE_PING:
            try:
                self._socket_client.send_message(
                    PLATFORM_DESTINATION_ID,