Ejemplo n.º 1
0
    def PlayVideo(self):
        cast = pc.PyChromecast()
        print cast.device

        # Make sure an app is running that supports RAMP protocol
        if not cast.app or pc.PROTOCOL_RAMP not in cast.app.service_protocols:
            pc.play_youtube_video(YOUTUBE_SUFFIX, cast.host)
            cast.refresh()

        ramp = cast.get_protocol(pc.PROTOCOL_RAMP)

        # It can take some time to setup websocket connection
        # if we just switched to a new channel
        while not ramp:
            time.sleep(1)
            ramp = cast.get_protocol(pc.PROTOCOL_RAMP)

        # Give ramp some time to init
        time.sleep(1)
Ejemplo n.º 2
0
def setup_chromecast(casts, host):
    """ Tries to convert host to Chromecast object and set it up. """

    # Check if already setup
    if any(cast.host == host for cast in casts.values()):
        return

    try:
        cast = pychromecast.PyChromecast(host)

        entity_id = util.ensure_unique_string(
            ENTITY_ID_FORMAT.format(
                util.slugify(cast.device.friendly_name)),
            casts.keys())

        casts[entity_id] = cast

    except pychromecast.ChromecastConnectionError:
        pass
Ejemplo n.º 3
0
Archivo: cast.py Proyecto: naterh/cast
def main():
    """ Read the options given on the command line and do the required actions.

    This method is used in the entry_point `cast`.
    """
    opts = docopt(__doc__, version="cast 0.1")

    cast = pychromecast.PyChromecast(CHROMECAST_HOST)
    ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)

    # Wait for ramp connection to be initted.
    time.sleep(SLEEP_TIME)

    if ramp is None:
        print 'Chromecast is not up or current app does not handle RAMP.'
        return 1

    if opts['next']:
        ramp.next()
    elif opts['pause']:
        ramp.pause()
    elif opts['play']:
        ramp.play()
    elif opts['toggle']:
        ramp.playpause()
    elif opts['seek']:
        ramp.seek(opts['<second>'])
    elif opts['rewind']:
        ramp.rewind()
    elif opts['status']:
        _status_command(cast, ramp)
    elif opts['volume']:
        _volume_command(ramp, opts['<value>'])

    # Wait for command to be sent.
    time.sleep(SLEEP_TIME)
Ejemplo n.º 4
0
#!/usr/bin/python

import time, sys

if (len(sys.argv) > 0):
    video = sys.argv[1]
else:
    video = "REjj1ruFQww"

try:
    import pychromecast
    pychromecast.play_youtube_video(video, pychromecast.PyChromecast().host)
except:
    pass
Ejemplo n.º 5
0
def setup(hass, config):
    """ Listen for chromecast events. """
    logger = logging.getLogger(__name__)

    try:
        import pychromecast
    except ImportError:
        logger.exception(("Failed to import pychromecast. "
                          "Did you maybe not install the 'pychromecast' "
                          "dependency?"))

        return False

    if CONF_HOSTS in config[DOMAIN]:
        hosts = config[DOMAIN][CONF_HOSTS].split(",")

    # If no hosts given, scan for chromecasts
    else:
        logger.info("Scanning for Chromecasts")
        hosts = pychromecast.discover_chromecasts()

    casts = {}

    for host in hosts:
        try:
            cast = pychromecast.PyChromecast(host)

            entity_id = util.ensure_unique_string(
                ENTITY_ID_FORMAT.format(util.slugify(
                    cast.device.friendly_name)), casts.keys())

            casts[entity_id] = cast

        except pychromecast.ChromecastConnectionError:
            pass

    if not casts:
        logger.error("Could not find Chromecasts")
        return False

    def update_chromecast_state(entity_id, chromecast):
        """ Retrieve state of Chromecast and update statemachine. """
        chromecast.refresh()

        status = chromecast.app

        state_attr = {ATTR_FRIENDLY_NAME: chromecast.device.friendly_name}

        if status and status.app_id != pychromecast.APP_ID['HOME']:
            state = status.app_id

            ramp = chromecast.get_protocol(pychromecast.PROTOCOL_RAMP)

            if ramp and ramp.state != pychromecast.RAMP_STATE_UNKNOWN:

                if ramp.state == pychromecast.RAMP_STATE_PLAYING:
                    state_attr[ATTR_MEDIA_STATE] = MEDIA_STATE_PLAYING
                else:
                    state_attr[ATTR_MEDIA_STATE] = MEDIA_STATE_STOPPED

                if ramp.content_id:
                    state_attr[ATTR_MEDIA_CONTENT_ID] = ramp.content_id

                if ramp.title:
                    state_attr[ATTR_MEDIA_TITLE] = ramp.title

                if ramp.artist:
                    state_attr[ATTR_MEDIA_ARTIST] = ramp.artist

                if ramp.album:
                    state_attr[ATTR_MEDIA_ALBUM] = ramp.album

                if ramp.image_url:
                    state_attr[ATTR_MEDIA_IMAGE_URL] = ramp.image_url

                if ramp.duration:
                    state_attr[ATTR_MEDIA_DURATION] = ramp.duration

                state_attr[ATTR_MEDIA_VOLUME] = ramp.volume
        else:
            state = STATE_NO_APP

        hass.states.set(entity_id, state, state_attr)

    def update_chromecast_states(time):  # pylint: disable=unused-argument
        """ Updates all chromecast states. """
        logger.info("Updating Chromecast status")

        for entity_id, cast in casts.items():
            update_chromecast_state(entity_id, cast)

    def _service_to_entities(service):
        """ Helper method to get entities from service. """
        entity_ids = extract_entity_ids(hass, service)

        if entity_ids:
            for entity_id in entity_ids:
                cast = casts.get(entity_id)

                if cast:
                    yield entity_id, cast

        else:
            yield from casts.items()

    def turn_off_service(service):
        """ Service to exit any running app on the specified ChromeCast and
        shows idle screen. Will quit all ChromeCasts if nothing specified.
        """
        for entity_id, cast in _service_to_entities(service):
            cast.quit_app()
            update_chromecast_state(entity_id, cast)

    def volume_up_service(service):
        """ Service to send the chromecast the command for volume up. """
        for _, cast in _service_to_entities(service):
            ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)

            if ramp:
                ramp.volume_up()

    def volume_down_service(service):
        """ Service to send the chromecast the command for volume down. """
        for _, cast in _service_to_entities(service):
            ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)

            if ramp:
                ramp.volume_down()

    def media_play_pause_service(service):
        """ Service to send the chromecast the command for play/pause. """
        for _, cast in _service_to_entities(service):
            ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)

            if ramp:
                ramp.playpause()

    def media_play_service(service):
        """ Service to send the chromecast the command for play/pause. """
        for _, cast in _service_to_entities(service):
            ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)

            if ramp and ramp.state == pychromecast.RAMP_STATE_STOPPED:
                ramp.playpause()

    def media_pause_service(service):
        """ Service to send the chromecast the command for play/pause. """
        for _, cast in _service_to_entities(service):
            ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)

            if ramp and ramp.state == pychromecast.RAMP_STATE_PLAYING:
                ramp.playpause()

    def media_next_track_service(service):
        """ Service to send the chromecast the command for next track. """
        for entity_id, cast in _service_to_entities(service):
            ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)

            if ramp:
                next(ramp)
                update_chromecast_state(entity_id, cast)

    def play_youtube_video_service(service, video_id):
        """ Plays specified video_id on the Chromecast's YouTube channel. """
        if video_id:  # if service.data.get('video') returned None
            for entity_id, cast in _service_to_entities(service):
                pychromecast.play_youtube_video(video_id, cast.host)
                update_chromecast_state(entity_id, cast)

    hass.track_time_change(update_chromecast_states)

    hass.services.register(DOMAIN, SERVICE_TURN_OFF, turn_off_service)

    hass.services.register(DOMAIN, SERVICE_VOLUME_UP, volume_up_service)

    hass.services.register(DOMAIN, SERVICE_VOLUME_DOWN, volume_down_service)

    hass.services.register(DOMAIN, SERVICE_MEDIA_PLAY_PAUSE,
                           media_play_pause_service)

    hass.services.register(DOMAIN, SERVICE_MEDIA_PLAY, media_play_service)

    hass.services.register(DOMAIN, SERVICE_MEDIA_PAUSE, media_pause_service)

    hass.services.register(DOMAIN, SERVICE_MEDIA_NEXT_TRACK,
                           media_next_track_service)

    hass.services.register(
        DOMAIN, "start_fireplace",
        lambda service: play_youtube_video_service(service, "eyU3bRy2x44"))

    hass.services.register(
        DOMAIN, "start_epic_sax",
        lambda service: play_youtube_video_service(service, "kxopViU98Xo"))

    hass.services.register(
        DOMAIN, SERVICE_YOUTUBE_VIDEO,
        lambda service: play_youtube_video_service(service,
                                                   service.data.get('video')))

    update_chromecast_states(None)

    return True