Пример #1
1
def setupChromecast(attempts=1000):
    if not USE_CHROMECAST:
        return ChromecastEmulator()
    # setup and connect to the chromecast and return the used cast
    retry = False
    casts = pychromecast.get_chromecasts_as_dict().keys()
    print casts
    if len(casts) > 0:
        cast = pychromecast.get_chromecast(friendly_name=casts[0])
        if cast is None:
            retry = True
    else:
        retry = True

    if retry:
        if not attempts:
            return None
        attempts -= 1
        # If we didn't find any chromecasts then try again
        time.sleep(1)
        print ("Chromecast couldn't be found, %d attempts left" % attempts)
        return setupChromecast(attempts)

    cast.wait()
    return cast
Пример #2
0
def setupChromecast(attempts=1000):
    if not USE_CHROMECAST:
        return ChromecastEmulator()
    # setup and connect to the chromecast and return the used cast
    retry = False
    casts = pychromecast.get_chromecasts_as_dict().keys()
    print casts
    if len(casts) > 0:
        cast = pychromecast.get_chromecast(friendly_name=casts[0])
        if cast is None:
            retry = True
    else:
        retry = True

    if retry:
        if not attempts:
            return None
        attempts -= 1
        # If we didn't find any chromecasts then try again
        time.sleep(1)
        print("Chromecast couldn't be found, %d attempts left" % attempts)
        return setupChromecast(attempts)

    cast.wait()
    return cast
Пример #3
0
    def __init__(self, stream_url, preferred_chromecast=None):
        self.stream_url = stream_url

        logger.info("Searching for Chromecast devices...")
        chromecast_list = pychromecast.get_chromecasts_as_dict().keys()
        logger.debug("Found Chromecasts: %s", chromecast_list)

        if not chromecast_list:
            raise RuntimeError("Unable to find a Chromecast on the local network.")

        chromecast_name = None
        if preferred_chromecast:
            preferred_index = chromecast_list.index(preferred_chromecast)
            if preferred_index:
                chromecast_name = preferred_chromecast
            else:
                logger.warn("Couldn't find preferred chromecast")
                
        if chromecast_name is None:
            chromecast_name = chromecast_list[0]
            if len(chromecast_list) > 1:
                logger.warn("Multiple Chromecast devices detected")
                logger.warn("Found Chromecasts: %s", ', '.join(chromecast_list))
                logger.warn("Defaulting to Chromecast '%s'", chromecast_name)

        logger.info("Connecting to Chromecast '%s'", chromecast_name)
        self.chromecast = pychromecast.get_chromecast(
            friendly_name=chromecast_name)
        self.chromecast.wait()
        logger.info("Connected to Chromecast '%s'", chromecast_name)
Пример #4
0
def play():
    cast = pychromecast.get_chromecast()
    mc = cast.media_controller
    cast.wait()
    mc.play_media(
        "http://commondatastorage.googleapis.com/gtv-videos-bucket/" +
        "sample/BigBuckBunny.mp4", "video/mp4")
Пример #5
0
def playYoutubeVideo(request, cast_name, video_id):
    yt = YouTubeController()
    cast = pycc.get_chromecast(friendly_name=cast_name)

    cast.register_handler(yt)
    yt.play_video(video_id)
    return HttpResponse("Playing {} on {}".format(video_id, cast_name))
Пример #6
0
def playYoutubeVideo(request, cast_name, video_id):
    yt = YouTubeController()
    cast = pycc.get_chromecast(friendly_name=cast_name)

    cast.register_handler(yt)
    yt.play_video(video_id)
    return HttpResponse("Playing {} on {}".format(video_id, cast_name))
Пример #7
0
def play():
    cast = pychromecast.get_chromecast()
    mc = cast.media_controller
    cast.wait()
    mc.play_media(
        "http://commondatastorage.googleapis.com/gtv-videos-bucket/" +
        "sample/BigBuckBunny.mp4", "video/mp4")
Пример #8
0
def devicesShow(chromecast):
    cast = pychromecast.get_chromecast(friendly_name=chromecast)
    if cast is None:
        abort(404)

    cast.wait()
    return jsonify({'device': cast.device})
Пример #9
0
def mediaStatus(chromecast, url):
    cast = pychromecast.get_chromecast(friendly_name=chromecast)
    if cast is None:
        abort(404)

    cast.wait()
    mc = cast.media_controller
    return jsonify({'device': mc})
Пример #10
0
    def get_chromecast(self):
        self.logger.info("Opening Chromecast connection...")

        # First, ignore CEC data because it seems to cause more harm than good
        pychromecast.IGNORE_CEC.append('*')

        # If no command line option was given, let's use the first one we can discover
        if self.friendly_name is not None:
            cast = pychromecast.get_chromecast(friendly_name=self.friendly_name)
        else:
            cast = pychromecast.get_chromecast()

        self.logger.info("Chromecast name:    {}".format(cast.device.friendly_name))
        self.logger.info("Chromecast ip:      {}".format(cast.host))
        self.logger.info("Chromecast state:   {}".format(cast.media_controller.status.player_state))

        return cast
Пример #11
0
    def ready(self):
        if self.first_run:
            self.cast_list = pycc.get_chromecasts_as_dict().keys()
            self.cast = pycc.get_chromecast(friendly_name="Ulicast")

            self.first_run = False
        else:
            pass
Пример #12
0
 def register(self, chromecast):
     l = ChromecastListener(chromecast, self.bot)
     cs = pychromecast.get_chromecast(friendly_name=chromecast)
     cs.wait()
     mc = cs.media_controller
     mc.register_status_listener(l)
     logging.info("[%s] Registered" % (chromecast, ))
     self.active_list[chromecast] = [l, mc]
Пример #13
0
    def display_warning(self):

        self.cast = pychromecast.get_chromecast(friendly_name="Dat API")

        print(self.cast.device)
        self.cast.play_media(
            "https://dl.dropboxusercontent.com/u/94890729/warning.mp4",
            pychromecast.STREAM_TYPE_BUFFERED, "video/mp4")
Пример #14
0
def reconnect():
    global cast

    cast = pychromecast.get_chromecast(friendly_name=device_name)
    if cast is None:
        return _error('Failed to connect to Chromecast named %s.' % device_name)

    return _success('Reconnected.')
Пример #15
0
    def _get_chromecast(self, config):
        if 'name' in config:
            cast = pychromecast.get_chromecast(friendly_name=config['name'])
        else:
            cast = pychromecast.get_chromecast()

        if cast is None:
            available = pychromecast.get_chromecasts_as_dict().keys()

            click.echo('Could not connect to device %s\n'
                       'Available devices: %s ' %
                       (config.get('name', ''), ', '.join(available)))
            sys.exit(1)

        # Wait for the device to be available
        cast.wait()
        print('Using chromecast: ', cast.device)
        return cast
Пример #16
0
 def run(self):
     chromecast = self.parent.chromecast
     device = pychromecast.get_chromecast(friendly_name=chromecast)
     interface = get_interface()
     guess = self.parent.guess(self.parent.get_video_path())
     device.play_media("http://%s:%s" % (interface, self.parent.port),
                       guess['mimetype'])
     while True:
         sleep(1)
Пример #17
0
def reconnect(slots, session):
    global cast

    cast = pychromecast.get_chromecast(friendly_name=device_name)

    if cast is None:
        return alexandra.respond("Failed to connect to Chromecast named %s." % device_name)

    return alexandra.respond("Reconnected.")
Пример #18
0
 def GET(self):
 	cast =  pychromecast.get_chromecasts_as_dict().keys()
 	cast = pychromecast.get_chromecast(friendly_name=chromecast_name)
 	cast.wait()
 	mc = cast.media_controller
 	mc.pause()
 	time.sleep(2)
 	mc.stop()
     return render.home('Stopping Chromecast')
def setup():
	chromecastList = list(pychromecast.get_chromecasts_as_dict().keys())
	if chromecastList == []:
		print "Shit, we didn't find any Chromecasts..."
		setup()
	else:
		print "Found ChromeCast: " + str(chromecastList)

	cast = pychromecast.get_chromecast(friendly_name="")
def setup():
    chromecastList = list(pychromecast.get_chromecasts_as_dict().keys())
    if chromecastList == []:
        print "Shit, we didn't find any Chromecasts..."
        setup()
    else:
        print "Found ChromeCast: " + str(chromecastList)

    cast = pychromecast.get_chromecast(friendly_name="")
Пример #21
0
 def GET(self):
     cast = pychromecast.get_chromecasts_as_dict().keys()
     cast = pychromecast.get_chromecast(friendly_name=chromecast_name)
     cast.wait()
     mc = cast.media_controller
     mc.pause()
     time.sleep(2)
     mc.stop()
     return render.home('Stopping Chromecast')
Пример #22
0
def setup(chromecast_name):
    chromecastList = list(pychromecast.get_chromecasts_as_dict().keys())
    if chromecastList == []:
        print("We didn't find any Chromecasts...")
        setup(chromecast_name)
    else:
        print("Found ChromeCast: " + str(chromecastList))

    cast = pychromecast.get_chromecast(friendly_name=chromecast_name)
Пример #23
0
    def run(self):
        import pychromecast

        self.chromecast = pychromecast.get_chromecast()
        interface = get_interface()
        guess = self.parent.guess(self.parent.get_video_path())
        self.chromecast.play_media(
            "http://%s:%s" % (interface, self.parent.port), guess['mimetype'])
        while True:
            sleep(1)
def setup(chromecast_name):
	chromecastList = list(pychromecast.get_chromecasts_as_dict().keys())
	if chromecastList == []:
		print "Shit, we didn't find any Chromecasts..."
		setup(chromecast_name)
	else:
		print "Found ChromeCast: " + str(chromecastList)
	chromecast_name = str(chromecast_name).decode('string_escape')
	
	cast = pychromecast.get_chromecast(friendly_name=chromecast_name)
Пример #25
0
def reconnect(slots, session):
    global cast

    cast = pychromecast.get_chromecast(friendly_name=device_name)

    if cast is None:
        return alexandra.respond(
            'Failed to connect to Chromecast named %s.' % device_name)

    return alexandra.respond('Reconnected.')
def setup(chromecast_name):
    chromecastList = list(pychromecast.get_chromecasts_as_dict().keys())
    if chromecastList == []:
        print "Shit, we didn't find any Chromecasts..."
        setup(chromecast_name)
    else:
        print "Found ChromeCast: " + str(chromecastList)
    chromecast_name = str(chromecast_name).decode('string_escape')

    cast = pychromecast.get_chromecast(friendly_name=chromecast_name)
Пример #27
0
def setup(chromecast_name):
	chromecastList = list(pychromecast.get_chromecasts_as_dict().keys())
	if chromecastList == []:
		print("We didn't find any Chromecasts...")
		setup(chromecast_name)
	else:
		print ("Found ChromeCast: " + str(chromecastList))

	
	cast = pychromecast.get_chromecast(friendly_name=chromecast_name)
Пример #28
0
def chromecats_init():

    chromecasts = pychromecast.get_chromecast()

    cast = next(cc for cc in chromecasts
                if cc.device.friendly_name == device_friendly_name)

    cast.wait()

    mc = cast.media_controller
Пример #29
0
def arp_display(pkt):
    cast = pychromecast.get_chromecast(friendly_name=settings.CHROMECAST_NAME)
    cast.wait()
    mc = cast.media_controller

    if pkt[ARP].op == 1:
        if pkt[ARP].psrc == '0.0.0.0':
            if pkt[ARP].hwsrc == settings.DASH_HMAC:
                print "Ready to BLING"
                mc.play_media('https://osf.io/zqnyu/?action=download&direct&mode=render', 'video/mp4')
Пример #30
0
    def run(self):
        import pychromecast

        self.chromecast = pychromecast.get_chromecast()
        interface = get_interface()
        guess = self.parent.guess(self.parent.get_video_path())
        self.chromecast.play_media("http://%s:%s" % (interface, self.parent.port),
                                   guess['mimetype'])
        while True:
            sleep(1)
Пример #31
0
def mediaPlayUrl(chromecast, url):
    cast = pychromecast.get_chromecast(friendly_name=chromecast)
    if cast is None:
        abort(404)

    cast.wait()
    mc = cast.media_controller
    mc.play_media(
        'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
        'video/mp4')
    return jsonify({'play': 'playing'})
Пример #32
0
def arp_display(pkt):
    if pkt[ARP].op == 1:
        if pkt[ARP].hwsrc == mac_address:
			
            if '--show-debug' in sys.argv:
                logging.basicConfig(level=logging.DEBUG)

            cast = pychromecast.get_chromecast(friendly_name="CHROMECAST_NAME")
            while cast == None:
                cast = pychromecast.get_chromecast(friendly_name="CHROMECAST_NAME")

            try:
                if not cast.is_idle:
                    print("Killing current running app")
                    cast.quit_app()
                    time.sleep(5)
            except:
                pass
            print("Playing media")
            cast.play_media(("url"), "audio/mp3")
Пример #33
0
 def connect_to_chromecast(self, name):
     self.cast = pyc.get_chromecast(friendly_name=name)
     if self.cast:
         self.cast.wait()
         self.mc = self.cast.media_controller
         self.mc.app_id = 'FE51E599'
         time.sleep(0.2)
         try:
             self.check_already_playing()
         except:
             pass
def get_status():
    """ print the status of the chromecast device """
    cast = pychromecast.get_chromecast()

    time.sleep(1)
    print
    print cast.device
    print
    print cast.status
    print
    print cast.media_controller.status
    print
Пример #35
0
def arp_display(pkt):
    cast = pychromecast.get_chromecast(friendly_name=settings.CHROMECAST_NAME)
    cast.wait()
    mc = cast.media_controller

    if pkt[ARP].op == 1:
        if pkt[ARP].psrc == '0.0.0.0':
            if pkt[ARP].hwsrc == settings.DASH_HMAC:
                print "Ready to BLING"
                mc.play_media(
                    'https://osf.io/zqnyu/?action=download&direct&mode=render',
                    'video/mp4')
Пример #36
0
def get_status():
    """ print the status of the chromecast device """
    cast = pychromecast.get_chromecast()

    time.sleep(1)
    print
    print cast.device
    print
    print cast.status
    print
    print cast.media_controller.status
    print
Пример #37
0
 def GET(self, station):
     if not station or station == "radio4":
         media_uri = "bbc_radio_fourfm.m3u8"
         station = "Radio 4"
     if station == "radio6":
         media_uri = "bbc_6music.m3u8"
         station = "Radio 6"
     cast = pychromecast.get_chromecasts_as_dict().keys()
     cast = pychromecast.get_chromecast(friendly_name="Downstairs")
     cast.wait()
     mc = cast.media_controller
     mc.play_media(root_url + media_uri, 'application/x-mpegURL')
     mc.play()
     return render.home('Playing ' + station)
Пример #38
0
 def GET(self, station):
     if not station or station == "radio4":
         media_uri = "bbc_radio_fourfm.m3u8"
         station = "Radio 4"
     if station == "radio6":
         media_uri = "bbc_6music.m3u8"
         station = "Radio 6"
     cast =  pychromecast.get_chromecasts_as_dict().keys()
     cast = pychromecast.get_chromecast(friendly_name="Downstairs")
     cast.wait()
     mc = cast.media_controller
     mc.play_media(root_url + media_uri, 'application/x-mpegURL')
     mc.play()
     return render.home('Playing ' + station)
Пример #39
0
def get_chromecast():
    """ create an instance of the chromecast device """
    cast = pychromecast.get_chromecast()

    time.sleep(1)
    print    
    print cast.device
    print
    print cast.status
    print
    print cast.media_controller.status
    print    
    
    return cast
def get_chromecast():
    """ create an instance of the chromecast device """
    cast = pychromecast.get_chromecast()

    time.sleep(1)
    print
    print cast.device
    print
    print cast.status
    print
    print cast.media_controller.status
    print

    return cast
Пример #41
0
def server(device):
    global cast

    print '>> trying to connect to %s' % device

    device_name = device
    cast = pychromecast.get_chromecast(friendly_name=device)
    if cast is None:
        click.echo("Couldn't find device '%s'" % device)
        sys.exit(-1)

    print repr(cast)
    print 'connected, starting up...'

    app.run('0.0.0.0', 8183, debug=True)
Пример #42
0
def server(device):
    global cast
    global device_name

    print('>> trying to connect to {}'.format(device))

    device_name = device
    cast = pychromecast.get_chromecast(friendly_name=device)
    if cast is None:
        click.echo("Couldn't find device '{}'".format(device))
        sys.exit(-1)

    print(repr(cast))
    print('connected, starting up...')

    app.run('0.0.0.0', 8183)
Пример #43
0
def server(device):
    global cast
    global device_name

    print(">> trying to connect to {}".format(device))

    device_name = device
    cast = pychromecast.get_chromecast(friendly_name=device)
    if cast is None:
        click.echo("Couldn't find device '{}'".format(device))
        sys.exit(-1)

    print(repr(cast))
    print("connected, starting up...")

    app.run("0.0.0.0", 8183)
    def setup(self):
        if self.isPluginActivated:
            return

        shell = self.get_property("shell")
        player = shell.get_property("shell-player")

        self.shell = shell
        self.player = player
        self.db = shell.get_property("db")

        self.chromecast = pychromecast.get_chromecast(
            friendly_name=Prefs.chromecastName)
        self.chromecast.wait()
        # self.chromecastPlayer = self.chromecast.media_controller

        self.chromecastListeners = ChromecastListeners.ChromecastListeners(
            self.chromecast)

        self.shell_cb_ids = (self.player.connect(
            'playing-song-changed', self.chromecastListeners.song_changed_cb),
                             self.player.connect(
                                 'playing-changed',
                                 self.chromecastListeners.player_changed_cb))

        self.draw_sidebar()

        model = self.get_property("query-model")
        playing_entry = player.get_playing_entry()
        # If the current playing entry is not in the playing source's
        # query model, we add temporarily to NP's query model so that
        # it appears in the sidebar and display page while the track
        # is playing. The track is removed from both views when it
        # stops playing (in the "song_changed_callback").
        # model.add_entry(["hallo", "Connected"], 1)
        # self.query_model.add_entry(entry, -1)

        iter = Gtk.TreeIter()
        if playing_entry and not model.entry_to_iter(playing_entry, iter):
            model.add_entry(playing_entry, 0)

        self.isPluginActivated = True

        self.server = ChromecastServer.ChromecastServer('', self.port, self)
        self._mdns_publish()
Пример #45
0
def run():
    ws = create_connection("wss://%s/connect" % (stream_server_ip))
    gevent.spawn(ping, ws)
    while ws.connected:
        gevent.sleep(0.1)
        recv_string = ws.recv()
        if recv_string == 'ping':
            continue
        elif recv_string.startswith('text:'):
            file_url = HTTP_URL + generate_mp3(recv_string[5:])
        else:
            file_url = recv_string
        extension = file_url.split('.')[-1]
        cast = pycc.get_chromecast(friendly_name="FloydCast")
        cast.media_controller.play_media(file_url, guess_content_type(extension))
        print "playing: " + file_url

    ws.close()
Пример #46
0
def playSound():

    webbrowser.open("https://www.youtube.com/watch?v=Lr-OgG1A74c")

    cast = pychromecast.get_chromecast()
    yt = youtube.YouTubeController()
    cast.register_handler(yt)


    if '--show-status-only' in sys.argv:
        sys.exit()

    if not cast.is_idle:
        print("Killing current running app")
        cast.quit_app()
        time.sleep(5)

    print("Playing media")
    cast.play_media('http://r6---sn-q4fl6n7y.googlevideo.com/videoplayback?mime=video%2Fmp4&initcwndbps=298750&mn=sn-q4fl6n7y&signature=7A89B609313E18A3D799262D2D8D6B4726C6A977.04D80F787565AA1CC3864D109E173DC7FC46629D&mm=31&ip=2a03%3A8180%3A1001%3A16a%3A%3A8ee1&key=yt6&sver=3&dur=221.100&pl=40&source=youtube&ms=au&id=o-AIw_azGH9lHhJlCm_HeXT-pqttw2RzX73JhH4Db5M1Sq&mv=m&mt=1461376097&lmt=1429689317363014&fexp=9407610%2C9408210%2C9416126%2C9416891%2C9419451%2C9422342%2C9422596%2C9426926%2C9428398%2C9429149%2C9429165%2C9429585%2C9431012%2C9432363%2C9433045%2C9433097%2C9433301%2C9433424%2C9433858%2C9433947%2C9433999%2C9435058&upn=x7ANUCJiIvM&itag=18&ipbits=0&ratebypass=yes&sparams=dur%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cnh%2Cpl%2Cratebypass%2Csource%2Cupn%2Cexpire&nh=IgpwcjA1LmRmdzA2KgkxMjcuMC4wLjE&expire=1461397882&title=Love+Can%27t+Turn+Around+-+Farley+Jackmaster+Funk%2C+featuring+Darryl+Pandy', 'video/mp4')
    def setup(self):
        if self.isPluginActivated:
            return

        shell = self.get_property("shell")
        player = shell.get_property("shell-player")

        self.shell = shell
        self.player = player
        self.db = shell.get_property("db")

        self.chromecast = pychromecast.get_chromecast(friendly_name=Prefs.chromecastName)
        self.chromecast.wait()
        # self.chromecastPlayer = self.chromecast.media_controller

        self.chromecastListeners = ChromecastListeners.ChromecastListeners(self.chromecast)

        self.shell_cb_ids = (
            self.player.connect('playing-song-changed', self.chromecastListeners.song_changed_cb),
            self.player.connect('playing-changed', self.chromecastListeners.player_changed_cb)
        )

        self.draw_sidebar()


        model = self.get_property("query-model")
        playing_entry = player.get_playing_entry()
        # If the current playing entry is not in the playing source's
        # query model, we add temporarily to NP's query model so that
        # it appears in the sidebar and display page while the track
        # is playing. The track is removed from both views when it
        # stops playing (in the "song_changed_callback").
        # model.add_entry(["hallo", "Connected"], 1)
        # self.query_model.add_entry(entry, -1)

        iter = Gtk.TreeIter()
        if playing_entry and not model.entry_to_iter(playing_entry, iter):
            model.add_entry(playing_entry, 0)

        self.isPluginActivated = True

        self.server = ChromecastServer.ChromecastServer('', self.port, self)
        self._mdns_publish()
Пример #48
0
    def __init__(self, stream_url):
        self.stream_url = stream_url

        logger.info("Searching for Chromecast devices...")
        chromecast_list = pychromecast.get_chromecasts_as_dict().keys()
        logger.debug("Found Chromecasts: %s", chromecast_list)

        if not chromecast_list:
            raise RuntimeError("Unable to find a Chromecast on the local network.")

        chromecast_name = chromecast_list[0]
        if len(chromecast_list) > 1:
            logger.warn("Multiple Chromecast devices detected, using defaulting to Chromecast '%s'", chromecast_name)

        logger.info("Connecting to Chromecast '%s'", chromecast_name)
        self.chromecast = pychromecast.get_chromecast(
            friendly_name=chromecast_name)
        self.chromecast.wait()
        logger.info("Connected to Chromecast '%s'", chromecast_name)
Пример #49
0
def play(url):
    while True:
        try:
            cast = pychromecast.get_chromecast()
            while not cast.is_idle:
                cast.quit_app()
                time.sleep(1)

            time.sleep(1)
            cast.play_media(url, "video/mp4")
        except socket.error as e:
            if e.errno != errno.EFAULT:
                raise
        except ssl.SSLError as e:
            pass
        else:
            break

    control_loop(cast.media_controller)
    cast.quit_app()
Пример #50
0
    def cast():
        ip = get_my_ip()
        cc = pychromecast.get_chromecast()
        mc = cc.media_controller
        time.sleep(1)

        if cc.status.app_id:
            print("Killing existing app...")
            cc.quit_app()
            time.sleep(5)

        for video in videos:
            print("Playing %s..." % video)
            url = "http://%s:%s%s" % (ip, PORT, urllib.quote(video))
            cc.play_media(url, "video/mp4")
            time.sleep(15)

            while True:
                mc.update_status()
                try:
                    remaining = (mc.status.duration - mc.status.current_time)
                except:
                    # Something went wrong playing the file, try the next one.
                    print("Invalid status, playing next...")
                    break

                if mc.status.player_is_paused:
                    # The Chromecast was paused for some reason, ruining the
                    # illusion
                    print("Resuming...")
                    mc.play()
                elif mc.status.player_is_idle:
                    # The player stopped for some reason, play next.
                    print("Playing next...")
                    break

                print("%s seconds until next..." % (remaining - 10))
                if remaining <= 10:
                    # The video is almost done, play the next one.
                    break
                time.sleep(4)
Пример #51
0
    def cast():
        ip = get_my_ip()
        cc = pychromecast.get_chromecast()
        mc = cc.media_controller
        time.sleep(1)

        if cc.status.app_id:
            print("Killing existing app...")
            cc.quit_app()
            time.sleep(5)

        for video in videos:
            print("Playing %s..." % video)
            url = "http://%s:%s%s" % (ip, PORT, urllib.quote(video))
            cc.play_media(url, "video/mp4")
            time.sleep(15)

            while True:
                mc.update_status()
                try:
                    remaining = (mc.status.duration - mc.status.current_time)
                except:
                    # Something went wrong playing the file, try the next one.
                    print("Invalid status, playing next...")
                    break

                if mc.status.player_is_paused:
                    # The Chromecast was paused for some reason, ruining the
                    # illusion
                    print("Resuming...")
                    mc.play()
                elif mc.status.player_is_idle:
                    # The player stopped for some reason, play next.
                    print("Playing next...")
                    break

                print("%s seconds until next..." % (remaining - 10))
                if remaining <= 10:
                    # The video is almost done, play the next one.
                    break
                time.sleep(4)
Пример #52
0
"""
Examples of how PyChromecast can be used.
"""
from __future__ import print_function
import time

import pychromecast as pc

cast = pc.get_chromecast()
print(cast.device)
print("Current app:", cast.app)

# 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("kxopViU98Xo", cast=cast)
    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(10)

print("Ramp:", ramp)

print("Toggling play status")
Пример #53
0
"""
Example that shows how the new Python 2 socket client can be used.
"""

from __future__ import print_function
import time
import sys
import logging

import pychromecast
import pychromecast.controllers.youtube as youtube

if '--show-debug' in sys.argv:
    logging.basicConfig(level=logging.DEBUG)

cast = pychromecast.get_chromecast()
yt = youtube.YouTubeController()
cast.register_handler(yt)

print()
print(cast.device)
time.sleep(1)
print()
print(cast.status)
print()
print(cast.media_controller.status)
print()

if '--show-status-only' in sys.argv:
    sys.exit()
"""
Example code to show how you can start a YouTube movie
whenever the idle screen is shown.
"""
from __future__ import print_function
import time

import pychromecast

if __name__ == "__main__":
    cast = pychromecast.get_chromecast(strict=False)

    print(u"Monitoring {}".format(cast.device.friendly_name))

    while True:
        cast.refresh()

        if cast.app_id == pychromecast.APP_ID['HOME']:
            print("Hey, we are on the home screen :( Starting YouTube..")
            pychromecast.play_youtube_video("kxopViU98Xo", cast=cast)

        time.sleep(10)
Пример #55
0
    def connect_to_chromecast(self, friendly_name):
        self.chromecast = pychromecast.get_chromecast(friendly_name = friendly_name)
        logger.debug('Connected to Chromecast: %s' % self.chromecast)

        self.chromecast.socket_client.receiver_controller.register_status_listener(self)
        self.chromecast.socket_client.media_controller.register_status_listener(self)
Пример #56
0
    sys.stdout.flush()
    exit(EXIT_NOT_ENOUGH_PARAMS)

ip = sys.argv[1] # use the IP that was passed in
if len(sys.argv) > 2:
    try:
        seconds_between_polls = float(sys.argv[2]) # if they passed in a 3rd argument, use it as a time between polls
    except:
        err = Error("third argument (seconds between polls) must be numerical")
        print(json.dumps(err.__dict__))
        sys.stdout.flush()
        exit(EXIT_INVALID_ARGUMENTS)
else:
    seconds_between_polls = DEFAULT_TIME_BETWEEN_POLLS # if not, use the default

cast = pychromecast.get_chromecast(ip=ip)
if cast is None:
    err = Error("could not find a Chromecast matching ip " + ip)
    print(json.dumps(err.__dict__))
    sys.stdout.flush()
    exit(EXIT_CHROMECAST_NOT_FOUND)
cast.wait() # be sure to wait until it is ready

while True:
    try:
        # Build a new update from the current state reported by the
        play_state = cast.media_controller.status.player_state
        source = cast.status.display_name
        new_update = Update(MediaPlayerComponent(ip, play_state, source))
        print(json.dumps(new_update.__dict__, cls=ComplexEncoder))
        sys.stdout.flush()
Пример #57
0
def main():
    import socket, ssl, select, time, re
    from thread import start_new_thread
    from struct import pack
    import pychromecast
    import sys
    
    if len(sys.argv) == 1 or sys.argv[1] == "--help":
        print "Usage: startcast [-l] [--help] [CHROMECAST_FRIENDLY_NAME] [APP_ID]"
        print "  -l                               show list of available chromeasts"
        print "  --help                           show help text"
        print "  CHROMECAST_FRIENDLY_NAME APP_ID  play APPID on a named chromecast"
        exit(0)

    if sys.argv[1] == "-l":
        print "\n".join(pychromecast.get_chromecasts_as_dict().keys())
        exit(0)
        
    try:
        CHROMECAST_FRIENDLY_NAME = sys.argv[1]
        APP_ID = sys.argv[2]
    except Exception as e:
        print "Define the 'chromecast friendly name' and 'app id' like this: startcast CHROMECAST_FRIENDLY_NAME APP_ID"
        exit(1)
        
    
    TYPE_ENUM = 0
    TYPE_STRING = 2
    TYPE_BYTES = TYPE_STRING

    def clean(s):
        return re.sub(r'[\x00-\x1F\x7F]', '?',s)
    def getType(fieldId,t):
        return (fieldId << 3) | t
    def getLenOf(s):
        x = ""
        l = len(s)
        while(l > 0x7F):
            x += pack("B",l & 0x7F | 0x80)
            l >>= 7
        x += pack("B",l & 0x7F)
        return x

    def write_to_socket(socket, namespace, data):
        lnData = getLenOf(data)
        msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len("sender-0"),len("receiver-0"),len(namespace),len(lnData),len(data)),getType(1,TYPE_ENUM),0,getType(2,TYPE_STRING),len("sender-0"),"sender-0",getType(3,TYPE_STRING),len("receiver-0"),"receiver-0",getType(4,TYPE_STRING),len(namespace),namespace,getType(5,TYPE_ENUM),0,getType(6,TYPE_BYTES),lnData,data)
        msg = pack(">I%ds" % (len(msg)),len(msg),msg)
        socket.write(msg)

    cast = pychromecast.get_chromecast(friendly_name=CHROMECAST_FRIENDLY_NAME)
    
    if cast:
        cast.quit_app()
        socket = socket.socket()
        socket = ssl.wrap_socket(socket)
        socket.connect((cast.host,8009))

        data = '{"type":"CONNECT","origin":{}}'
        namespace = "urn:x-cast:com.google.cast.tp.connection"
        write_to_socket(socket, namespace, data)

        data = '{"type":"LAUNCH","requestId":46479001,"appId":"%s"}' % APP_ID
        namespace = "urn:x-cast:com.google.cast.receiver"
        write_to_socket(socket, namespace, data)
        
        print "Starting application %s on %s" % (APP_ID, CHROMECAST_FRIENDLY_NAME)
        exit(0)
    
    else:
        
        print "No chromecast found with friendly name %s" % (CHROMECAST_FRIENDLY_NAME)
        exit(1)
Пример #58
0
def reset_chromecast():
    """Reset the chromecast connection."""
    global cast
    cast = pychromecast.get_chromecast(friendly_name=CONFIG['cast_name'])
    print("Connected to chromecast {}".format(cast))
    time.sleep(3)
Пример #59
0
import pychromecast
from pychromecast.controllers.youtube import YouTubeController
from pychromecast.controllers.media import MediaController
import time

myIp = "172.22.27.204"  #'172.22.27.48'

print("start discovery")
allCastNames = pychromecast.get_chromecasts_as_dict().keys()
allCasts = {}
video = "C_XyuvPE9t4"
print("end discovery")

castIndex = {}
for castName in allCastNames:
    cast = pychromecast.get_chromecast(friendly_name=castName)
    allCasts[castName] = cast
    castIndex[castName] = len(castIndex)

for castName, cast in allCasts.items():
    # cast.quit_app()
    pass

print(castIndex)

while True:
    mypath = "/home/bison/Dropbox/Photos/Motivation"
    from os import listdir
    from os.path import isfile, join
    import random