def setup_platform(hass, config, add_devices, discovery_info=None): """ Sets up the cast platform. """ logger = logging.getLogger(__name__) if pychromecast is None: logger.error( ("Failed to import pychromecast. Did you maybe not install the " "'pychromecast' dependency?")) return False if discovery_info: hosts = [discovery_info[0]] else: hosts = (host_port[0] for host_port in pychromecast.discover_chromecasts()) casts = [] for host in hosts: try: casts.append(CastDevice(host)) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def get_device_uuids(): device_uuids = {} devices, browser = pychromecast.discover_chromecasts() pychromecast.stop_discovery(browser) for mDNS, uuid, model, name, ip, port in devices: device_uuids[name.casefold()] = uuid return device_uuids
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the cast platform.""" import pychromecast # Import CEC IGNORE attributes pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, []) known_hosts = hass.data.get(KNOWN_HOSTS_KEY) if known_hosts is None: known_hosts = hass.data[KNOWN_HOSTS_KEY] = [] if discovery_info: host = (discovery_info.get('host'), discovery_info.get('port')) if host in known_hosts: return hosts = [host] elif CONF_HOST in config: host = (config.get(CONF_HOST), DEFAULT_PORT) if host in known_hosts: return hosts = [host] else: hosts = [tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in known_hosts] casts = [] # get_chromecasts() returns Chromecast objects with the correct friendly # name for grouped devices all_chromecasts = pychromecast.get_chromecasts() for host in hosts: (_, port) = host found = [device for device in all_chromecasts if (device.host, device.port) == host] if found: try: casts.append(CastDevice(found[0])) known_hosts.append(host) except pychromecast.ChromecastConnectionError: pass # do not add groups using pychromecast.Chromecast as it leads to names # collision since pychromecast.Chromecast will get device name instead # of group name elif port == DEFAULT_PORT: try: # add the device anyway, get_chromecasts couldn't find it casts.append(CastDevice(pychromecast.Chromecast(*host))) known_hosts.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def setup_platform(hass, config, add_devices, discovery_info=None): """ Sets up the cast platform. """ logger = logging.getLogger(__name__) if pychromecast is None: logger.error(( "Failed to import pychromecast. Did you maybe not install the " "'pychromecast' dependency?")) return False if discovery_info: hosts = [discovery_info[0]] else: hosts = (host_port[0] for host_port in pychromecast.discover_chromecasts()) casts = [] for host in hosts: try: casts.append(CastDevice(host)) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def setup_platform(hass, config, add_devices, discovery_info=None): """ Sets up the cast platform. """ logger = logging.getLogger(__name__) try: # pylint: disable=redefined-outer-name import pychromecast except ImportError: logger.exception(("Failed to import pychromecast. " "Did you maybe not install the 'pychromecast' " "dependency?")) return if discovery_info: hosts = [discovery_info[0]] else: hosts = pychromecast.discover_chromecasts() casts = [] for host in hosts: try: casts.append(CastDevice(host)) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def stream_youtube(self): """Stream youtube to every chromecast connected to the network.""" for chromecast_info in pychromecast.discover_chromecasts(): (address, port, uuid, tp, desc) = chromecast_info self.__puts('info', "Chromecast [%s] detected" % (address)) url = "http://%s:8008/apps/YouTube" % (address) self.__puts('success', "Streams %s" % (url)) head = {'Content-type': 'application/json', 'Accept': 'text/plain'} requests.post(url, self.youtube_id, headers=head)
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the cast platform.""" import pychromecast # import CEC IGNORE attributes ignore_cec = config.get(CONF_IGNORE_CEC, []) if isinstance(ignore_cec, list): pychromecast.IGNORE_CEC += ignore_cec else: _LOGGER.error('CEC config "%s" must be a list.', CONF_IGNORE_CEC) hosts = [] if discovery_info and discovery_info in KNOWN_HOSTS: return elif discovery_info: hosts = [discovery_info] elif CONF_HOST in config: hosts = [(config.get(CONF_HOST), DEFAULT_PORT)] else: hosts = [ tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in KNOWN_HOSTS ] casts = [] # get_chromecasts() returns Chromecast objects # with the correct friendly name for grouped devices all_chromecasts = pychromecast.get_chromecasts() for host in hosts: found = [ device for device in all_chromecasts if (device.host, device.port) == host ] if found: try: casts.append(CastDevice(found[0])) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass else: try: # add the device anyway, get_chromecasts couldn't find it casts.append(CastDevice(pychromecast.Chromecast(*host))) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the cast platform.""" import pychromecast # Import CEC IGNORE attributes pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, []) hosts = [] if discovery_info: host = (discovery_info.get('host'), discovery_info.get('port')) if host in KNOWN_HOSTS: return hosts = [host] elif CONF_HOST in config: hosts = [(config.get(CONF_HOST), DEFAULT_PORT)] else: hosts = [ tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in KNOWN_HOSTS ] casts = [] # get_chromecasts() returns Chromecast objects with the correct friendly # name for grouped devices all_chromecasts = pychromecast.get_chromecasts() for host in hosts: found = [ device for device in all_chromecasts if (device.host, device.port) == host ] if found: try: casts.append(CastDevice(found[0])) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass else: try: # add the device anyway, get_chromecasts couldn't find it casts.append(CastDevice(pychromecast.Chromecast(*host))) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the cast platform.""" import pychromecast # import CEC IGNORE attributes ignore_cec = config.get(CONF_IGNORE_CEC, []) if isinstance(ignore_cec, list): pychromecast.IGNORE_CEC += ignore_cec else: _LOGGER.error('CEC config "%s" must be a list.', CONF_IGNORE_CEC) hosts = [] if discovery_info and discovery_info in KNOWN_HOSTS: return elif discovery_info: hosts = [discovery_info] elif CONF_HOST in config: hosts = [(config.get(CONF_HOST), DEFAULT_PORT)] else: hosts = [tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in KNOWN_HOSTS] casts = [] # get_chromecasts() returns Chromecast objects # with the correct friendly name for grouped devices all_chromecasts = pychromecast.get_chromecasts() for host in hosts: found = [device for device in all_chromecasts if (device.host, device.port) == host] if found: try: casts.append(CastDevice(found[0])) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass else: try: # add the device anyway, get_chromecasts couldn't find it casts.append(CastDevice(pychromecast.Chromecast(*host))) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the cast platform.""" import pychromecast # Import CEC IGNORE attributes pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, []) hosts = [] if discovery_info: host = (discovery_info.get('host'), discovery_info.get('port')) if host in KNOWN_HOSTS: return hosts = [host] elif CONF_HOST in config: hosts = [(config.get(CONF_HOST), DEFAULT_PORT)] else: hosts = [tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in KNOWN_HOSTS] casts = [] # get_chromecasts() returns Chromecast objects with the correct friendly # name for grouped devices all_chromecasts = pychromecast.get_chromecasts() for host in hosts: found = [device for device in all_chromecasts if (device.host, device.port) == host] if found: try: casts.append(CastDevice(found[0])) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass else: try: # add the device anyway, get_chromecasts couldn't find it casts.append(CastDevice(pychromecast.Chromecast(*host))) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def scanForDeviceHosts(): ''' Returns: Bool Whether scanner returned any device hosts or not ''' global deviceHosts, deviceHostScanTimer # cancel currently running scanner, if any cancelDeviceHostScanner() logger.debug('Scanning for device hosts...') startTime = datetime.utcnow() deviceHosts = pychromecast.discover_chromecasts( timeout=DEVICE_HOST_SCAN_TIMEOUT) formattedScanTime = formatTimeDelta(datetime.utcnow() - startTime) formattedNextScanTimestamp = ( datetime.utcnow() + timedelta(seconds=CONTINUOUS_DEVICE_HOST_SCAN_INTERVAL)).isoformat() gotAcceptableSetOfHosts = deviceHosts is not None and len(deviceHosts) > 0 if not gotAcceptableSetOfHosts: logger.error( 'Device host scan completed with no hosts found after {}. ' 'Scheduling next scan for {}.'.format(formattedScanTime, formattedNextScanTimestamp)) cancelDeviceHostScanner() onError( Exception('Device host scan completed with no device(s) found.')) else: logger.info('Device scan completed with {} device(s) found after {}. ' 'Scheduling next scan for {}.'.format( len(deviceHosts), formattedScanTime, formattedNextScanTimestamp)) # continue to scan every N seconds deviceHostScanTimer = threading.Timer(CONTINUOUS_DEVICE_HOST_SCAN_INTERVAL, scanForDeviceHosts) deviceHostScanTimer.daemon = True deviceHostScanTimer.start() return gotAcceptableSetOfHosts
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the cast platform.""" import pychromecast logger = logging.getLogger(__name__) # import CEC IGNORE attributes ignore_cec = config.get(CONF_IGNORE_CEC, []) if isinstance(ignore_cec, list): pychromecast.IGNORE_CEC += ignore_cec else: logger.error('CEC config "%s" must be a list.', CONF_IGNORE_CEC) hosts = [] if discovery_info and discovery_info in KNOWN_HOSTS: return elif discovery_info: hosts = [discovery_info] elif CONF_HOST in config: hosts = [(config[CONF_HOST], DEFAULT_PORT)] else: hosts = [ tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in KNOWN_HOSTS ] casts = [] for host in hosts: try: casts.append(CastDevice(*host)) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
def setup_platform(hass, config, add_devices, discovery_info=None): """ Sets up the cast platform. """ global pychromecast # pylint: disable=invalid-name if pychromecast is None: import pychromecast as pychromecast_ pychromecast = pychromecast_ logger = logging.getLogger(__name__) # import CEC IGNORE attributes ignore_cec = config.get(CONF_IGNORE_CEC, []) if isinstance(ignore_cec, list): pychromecast.IGNORE_CEC += ignore_cec else: logger.error('Chromecast conig, %s must be a list.', CONF_IGNORE_CEC) hosts = [] if discovery_info and discovery_info[0] not in KNOWN_HOSTS: hosts = [discovery_info[0]] else: hosts = (host_port[0] for host_port in pychromecast.discover_chromecasts() if host_port[0] not in KNOWN_HOSTS) casts = [] for host in hosts: try: casts.append(CastDevice(host)) except pychromecast.ChromecastConnectionError: pass else: KNOWN_HOSTS.append(host) add_devices(casts)
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the cast platform.""" import pychromecast logger = logging.getLogger(__name__) # import CEC IGNORE attributes ignore_cec = config.get(CONF_IGNORE_CEC, []) if isinstance(ignore_cec, list): pychromecast.IGNORE_CEC += ignore_cec else: logger.error('CEC config "%s" must be a list.', CONF_IGNORE_CEC) hosts = [] if discovery_info and discovery_info in KNOWN_HOSTS: return elif discovery_info: hosts = [discovery_info] elif CONF_HOST in config: hosts = [(config[CONF_HOST], DEFAULT_PORT)] else: hosts = [tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in KNOWN_HOSTS] casts = [] for host in hosts: try: casts.append(CastDevice(*host)) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts)
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 'hosts' in config[DOMAIN]: hosts = config[DOMAIN]['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)), list(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 = {components.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 = components.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, components.SERVICE_TURN_OFF, turn_off_service) hass.services.register(DOMAIN, components.SERVICE_VOLUME_UP, volume_up_service) hass.services.register(DOMAIN, components.SERVICE_VOLUME_DOWN, volume_down_service) hass.services.register(DOMAIN, components.SERVICE_MEDIA_PLAY_PAUSE, media_play_pause_service) hass.services.register(DOMAIN, components.SERVICE_MEDIA_PLAY, media_play_service) hass.services.register(DOMAIN, components.SERVICE_MEDIA_PAUSE, media_pause_service) hass.services.register(DOMAIN, components.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
## GLOBAL VARS STX = chr(2); ETX = chr(3); EOT = chr(4); ENQ = chr(5); PAD = chr(127) SLP = 1 ## SET TWITTER API # https://apps.twitter.com/app/*yourappno*/keys config ={"consumer_key": *yourkeys*, "consumer_secret": *yourkeys*, "access_key": *yourkeys*, "access_secret": *yourkeys*} api = Api(config["consumer_key"], config["consumer_secret"], config["access_key"], config["access_secret"]) ## CHECK FOR CHROMECASTS cnames = pychromecast.discover_chromecasts(timeout = 10) chromecasts = pychromecast.get_chromecasts(cnames) shortnames = {u'YouTube': u'Tube', u'Yle Areena': u'Yle', u'HBO Nordic': u'HBO', u'Netflix': u'Flix'} ## SET SPOTIFY API (first time you need to give the app to rights to the scope) # Adding rights to scope you need to follow the prompt protocol from spotipy doc SPOTIPY_CLIENT_ID = *yourkeys* SPOTIPY_CLIENT_SECRET = *yourkeys* token = spotipy.util.prompt_for_user_token("ahonenlauri", "user-read-currently-playing", client_id = SPOTIPY_CLIENT_ID, client_secret = SPOTIPY_CLIENT_SECRET) sp = spotipy.Spotify(auth=token) ## SET SERIAL PORT ser = Serial("/dev/ttyUSB0", 600, SEVENBITS, PARITY_EVEN, STOPBITS_ONE)
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
def get_devices(self): chromecasts, browser = pychromecast.discover_chromecasts() pychromecast.discovery.stop_discovery(browser) self.available_devices = list( map(lambda x: CastDevice(*x), chromecasts)) return chromecasts
def setup(hass, config): # pylint: disable=unused-argument,too-many-locals """ Listen for chromecast events. """ logger = logging.getLogger(__name__) discovery = get_component('discovery') try: # pylint: disable=redefined-outer-name import pychromecast except ImportError: logger.exception(("Failed to import pychromecast. " "Did you maybe not install the 'pychromecast' " "dependency?")) return False casts = {} # If discovery component not loaded, scan ourselves if discovery.DOMAIN not in hass.components: logger.info("Scanning for Chromecasts") hosts = pychromecast.discover_chromecasts() for host in hosts: setup_chromecast(casts, host) def chromecast_discovered(service, info): """ Called when a Chromecast has been discovered. """ logger.info("New Chromecast discovered: %s", info[0]) setup_chromecast(casts, info[0]) discovery.listen( hass, discovery.services.GOOGLE_CAST, chromecast_discovered) 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): """ Updates all chromecast states. """ if casts: 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, second=range(0, 60, 15)) 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