def print_what_is_playing(loop):
    print('Discovering devices on network...')
    try:

        atvs = yield from pyatv.scan_for_apple_tvs(loop, timeout=5)
        if len(atvs) == 0:
            raise IndexError
        print('Connecting to {}'.format(atvs[0].address))
        atv = pyatv.connect_to_apple_tv(atvs[0], loop)

    except IndexError:
        """
            New module for device discovery below
        """
        print('auto discover failed')
        login_dict = device_search().login_info
        print(login_dict)
        details = pyatv.AppleTVDevice(login_dict['NAME'],
                                      login_dict['ADDRESS'],
                                      login_dict['HSGID'])

        atv = pyatv.connect_to_apple_tv(details, loop)

    try:
        playing = yield from atv.metadata.playing()
        print('Currently playing:')
        print(playing)

        # yield from atv.remote_control.play()
        # yield atv.remote_control.select()
    finally:
        # Do not forget to logout
        yield from atv.logout()
Ejemplo n.º 2
0
def async_setup_platform(hass, config, async_add_entities,
                         discovery_info=None):
    """Setup the Apple TV platform."""
    import pyatv

    if discovery_info is not None:
        name = discovery_info['name']
        host = discovery_info['host']
        login_id = discovery_info['hsgid']
        start_off = False
    else:
        name = config.get(CONF_NAME)
        host = config.get(CONF_HOST)
        login_id = config.get(CONF_LOGIN_ID)
        start_off = config.get(CONF_START_OFF)

    if DATA_APPLE_TV not in hass.data:
        hass.data[DATA_APPLE_TV] = []

    if host in hass.data[DATA_APPLE_TV]:
        return False
    hass.data[DATA_APPLE_TV].append(host)

    details = pyatv.AppleTVDevice(name, host, login_id)
    session = async_get_clientsession(hass)
    atv = pyatv.connect_to_apple_tv(details, hass.loop, session=session)
    entity = AppleTvDevice(atv, name, start_off)

    yield from async_add_entities([entity], update_before_add=True)
Ejemplo n.º 3
0
def async_setup_platform(hass,
                         config,
                         async_add_entities,
                         discovery_info=None):
    """Setup the Apple TV platform."""
    import pyatv

    if discovery_info is not None:
        name = discovery_info['name']
        host = discovery_info['host']
        login_id = discovery_info['hsgid']
        start_off = False
    else:
        name = config.get(CONF_NAME)
        host = config.get(CONF_HOST)
        login_id = config.get(CONF_LOGIN_ID)
        start_off = config.get(CONF_START_OFF)

    if DATA_APPLE_TV not in hass.data:
        hass.data[DATA_APPLE_TV] = []

    if host in hass.data[DATA_APPLE_TV]:
        return False
    hass.data[DATA_APPLE_TV].append(host)

    details = pyatv.AppleTVDevice(name, host, login_id)
    session = async_get_clientsession(hass)
    atv = pyatv.connect_to_apple_tv(details, hass.loop, session=session)
    entity = AppleTvDevice(atv, name, start_off)

    yield from async_add_entities([entity], update_before_add=True)
Ejemplo n.º 4
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Setup the Apple TV platform."""
    import pyatv

    if discovery_info is not None:
        name = discovery_info['name']
        host = discovery_info['host']
        login_id = discovery_info['properties']['hG']
        start_off = False
    else:
        name = config.get(CONF_NAME)
        host = config.get(CONF_HOST)
        login_id = config.get(CONF_LOGIN_ID)
        start_off = config.get(CONF_START_OFF)

    if DATA_APPLE_TV not in hass.data:
        hass.data[DATA_APPLE_TV] = []

    if host in hass.data[DATA_APPLE_TV]:
        return False
    hass.data[DATA_APPLE_TV].append(host)

    details = pyatv.AppleTVDevice(name, host, login_id)
    session = async_get_clientsession(hass)
    atv = pyatv.connect_to_apple_tv(details, hass.loop, session=session)
    entity = AppleTvDevice(atv, name, start_off)

    @callback
    def on_hass_stop(event):
        """Stop push updates when hass stops."""
        atv.push_updater.stop()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop)

    async_add_devices([entity])
Ejemplo n.º 5
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Setup the Apple TV platform."""
    import pyatv

    if discovery_info is not None:
        name = discovery_info['name']
        host = discovery_info['host']
        login_id = discovery_info['properties']['hG']
        start_off = False
    else:
        name = config.get(CONF_NAME)
        host = config.get(CONF_HOST)
        login_id = config.get(CONF_LOGIN_ID)
        start_off = config.get(CONF_START_OFF)

    if DATA_APPLE_TV not in hass.data:
        hass.data[DATA_APPLE_TV] = []

    if host in hass.data[DATA_APPLE_TV]:
        return False
    hass.data[DATA_APPLE_TV].append(host)

    details = pyatv.AppleTVDevice(name, host, login_id)
    session = async_get_clientsession(hass)
    atv = pyatv.connect_to_apple_tv(details, hass.loop, session=session)
    entity = AppleTvDevice(atv, name, start_off)

    @callback
    def on_hass_stop(event):
        """Stop push updates when hass stops."""
        atv.push_updater.stop()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop)

    async_add_devices([entity])
Ejemplo n.º 6
0
def pair_with_device(loop):
    """Make it possible to pair with device."""
    my_zeroconf = Zeroconf()
    details = conf.AppleTV('127.0.0.1', 'Apple TV')
    details.add_service(conf.DmapService('login_id'))
    atv = pyatv.connect_to_apple_tv(details, loop)

    yield from atv.pairing.start(zeroconf=my_zeroconf,
                                 name=REMOTE_NAME,
                                 pin=PIN_CODE)
    print('You can now pair with pyatv')

    # Wait for a minute to allow pairing
    yield from asyncio.sleep(60, loop=loop)

    yield from atv.pairing.stop()

    # Give some feedback about the process
    if atv.pairing.has_paired:
        pairing_guid = yield from atv.pairing.get('pairing_gui')
        print('Paired with device!')
        print('Pairing guid: ' + pairing_guid)
    else:
        print('Did not pair with device!')

    my_zeroconf.close()
Ejemplo n.º 7
0
def _handle_command(args, loop):
    details = pyatv.AppleTVDevice(args.name, args.address, args.hsgid)
    atv = pyatv.connect_to_apple_tv(details, loop)

    try:
        playing_resp = yield from atv.metadata.playing()
        ctrl = retrieve_commands(atv.remote_control, developer=args.developer)
        metadata = retrieve_commands(atv.metadata, developer=args.developer)
        playing = retrieve_commands(playing_resp, developer=args.developer)

        # Parse input command and argument from user
        cmd, cmd_args = _extract_command_with_args(args.command)

        if cmd == 'commands':
            _print_commands('Remote control', ctrl)
            _print_commands('Metadata', metadata)
            _print_commands('Playing commands', playing, newline=False)

        elif cmd in ctrl:
            yield from _exec_command(atv.remote_control, cmd, *cmd_args)

        elif cmd in metadata:
            yield from _exec_command(atv.metadata, cmd, *cmd_args)

        elif cmd in playing:
            yield from _exec_command(playing_resp, cmd, *cmd_args)

        else:
            logging.error('Unknown command: %s', args.command)
    finally:
        yield from atv.logout()
Ejemplo n.º 8
0
def _setup_atv(hass, atv_config):
    """Setup an Apple TV."""
    import pyatv
    name = atv_config.get(CONF_NAME)
    host = atv_config.get(CONF_HOST)
    login_id = atv_config.get(CONF_LOGIN_ID)
    start_off = atv_config.get(CONF_START_OFF)
    credentials = atv_config.get(CONF_CREDENTIALS)

    if host in hass.data[DATA_APPLE_TV]:
        return

    details = pyatv.AppleTVDevice(name, host, login_id)
    session = async_get_clientsession(hass)
    atv = pyatv.connect_to_apple_tv(details, hass.loop, session=session)
    if credentials:
        yield from atv.airplay.load_credentials(credentials)

    power = AppleTVPowerManager(hass, atv, start_off)
    hass.data[DATA_APPLE_TV][host] = {
        ATTR_ATV: atv,
        ATTR_POWER: power
    }

    hass.async_add_job(discovery.async_load_platform(
        hass, 'media_player', DOMAIN, atv_config))

    hass.async_add_job(discovery.async_load_platform(
        hass, 'remote', DOMAIN, atv_config))
Ejemplo n.º 9
0
async def _setup_atv(hass, hass_config, atv_config):
    """Set up an Apple TV."""

    name = atv_config.get(CONF_NAME)
    host = atv_config.get(CONF_HOST)
    login_id = atv_config.get(CONF_LOGIN_ID)
    start_off = atv_config.get(CONF_START_OFF)
    credentials = atv_config.get(CONF_CREDENTIALS)

    if host in hass.data[DATA_APPLE_TV]:
        return

    details = AppleTVDevice(name, host, login_id)
    session = async_get_clientsession(hass)
    atv = connect_to_apple_tv(details, hass.loop, session=session)
    if credentials:
        await atv.airplay.load_credentials(credentials)

    power = AppleTVPowerManager(hass, atv, start_off)
    hass.data[DATA_APPLE_TV][host] = {ATTR_ATV: atv, ATTR_POWER: power}

    hass.async_create_task(
        discovery.async_load_platform(hass, "media_player", DOMAIN, atv_config,
                                      hass_config))

    hass.async_create_task(
        discovery.async_load_platform(hass, "remote", DOMAIN, atv_config,
                                      hass_config))
Ejemplo n.º 10
0
 async def connect(self):
     """
     Connects to this instance's Apple TV     
     """
     if str(self._ip) == '0.0.0.0':
         if len(self._atvs) > 0:
             self.logger.debug(
                 "No device given in plugin.yaml, using first autodetected device"
             )
             self._atv_device = self._atvs[0]
             self._name = self._atv_device.name
             self._login_id = self._atv_device.login_id
             self._ip = self._atv_device.address
         else:
             return False
     self.logger.info("Connecting to '{0}' on ip '{1}'".format(
         self._name, self._ip))
     if 'name' in self._items:
         self._items['name'](self._name, self.get_shortname(), self._name)
     if self._login_id is None:
         self.logger.error(
             "Cannot connect to Apple TV {}, homesharing seems to be disabled ?"
             .format(self._name))
         return False
     else:
         self._atv = pyatv.connect_to_apple_tv(self._atv_device, self._loop)
         self._atv_rc = self._atv.remote_control
         self._device_id = self._atv.metadata.device_id
         self._credentialsfile = os.path.join(
             os.path.dirname(__file__),
             '{}.credentials'.format(self._device_id))
         try:
             _credentials = open(self._credentialsfile, 'r')
             self._credentials = _credentials.read()
             await self._atv.airplay.load_credentials(self._credentials)
             self.logger.debug("Credentials read: {}".format(
                 self._credentials))
         except:
             _credentials = open(self._credentialsfile, 'w')
             self._credentials = await self._atv.airplay.generate_credentials(
             )
             await self._atv.airplay.load_credentials(self._credentials)
             _credentials.write(self._credentials)
             self.logger.debug("Credentials written: {}".format(
                 self._credentials))
         finally:
             try:
                 await self._atv.airplay.verify_authenticated()
                 self._credentials_verified = True
             except:
                 self._credentials_verified = False
                 self.logger.info(
                     "Credentials for {} are not yet verified, airplay not possible"
                     .format(self._name))
             _credentials.close()
         self._push_listener_thread = threading.Thread(
             target=self._push_listener_thread_worker, name='ATV listener')
         self._push_listener_thread.start()
     return True
Ejemplo n.º 11
0
def print_what_is_playing(loop, details):
    """Connect to device and print what is playing."""
    print('Connecting to {}'.format(details.address))
    atv = pyatv.connect_to_apple_tv(details, loop)

    try:
        print((yield from atv.metadata.playing()))
    finally:
        # Do not forget to logout
        yield from atv.logout()
Ejemplo n.º 12
0
def print_what_is_playing(loop, details):
    print('Connecting to {}'.format(details.address))
    atv = pyatv.connect_to_apple_tv(details, loop)

    try:
        playing = yield from atv.metadata.playing()
        print('Currently playing:')
        print(playing)
    except:
        # Do not forget to logout
        yield from atv.logout()
Ejemplo n.º 13
0
def print_what_is_playing(loop):
    """Connect to device and print what is playing."""
    details = conf.AppleTV(ADDRESS, NAME)
    details.add_service(conf.DmapService(HSGID))

    print('Connecting to {}'.format(details.address))
    atv = pyatv.connect_to_apple_tv(details, loop)

    try:
        print((yield from atv.metadata.playing()))
    finally:
        # Do not forget to logout
        yield from atv.logout()
Ejemplo n.º 14
0
    def _handle(loop):
        atvs = yield from pyatv.scan_for_apple_tvs(
            loop, timeout=timeout, abort_on_found=True)

        # Take the first device found
        if atvs:
            atv = pyatv.connect_to_apple_tv(atvs[0], loop)
            try:
                yield from handler(atv)
            finally:
                yield from atv.logout()
        else:
            if not_found is not None:
                yield from not_found()
Ejemplo n.º 15
0
def _handle_command(args, loop):
    details = pyatv.AppleTVDevice(args.name, args.address, args.login_id)
    atv = pyatv.connect_to_apple_tv(details, loop)
    atv.push_updater.listener = PushListener()

    try:
        playing_resp = yield from atv.metadata.playing()
        ctrl = retrieve_commands(atv.remote_control, developer=args.developer)
        metadata = retrieve_commands(atv.metadata, developer=args.developer)
        playing = retrieve_commands(playing_resp, developer=args.developer)
        other = {'push_updates': 'Listen for push updates.'}

        # Parse input command and argument from user
        cmd, cmd_args = _extract_command_with_args(args.command)

        if cmd == 'commands':
            _print_commands('Remote control', ctrl)
            _print_commands('Metadata', metadata)
            _print_commands('Playing', playing)
            _print_commands('Other', other, newline=False)

        elif cmd == 'artwork':
            artwork = yield from atv.metadata.artwork()
            if artwork is not None:
                with open('artwork.png', 'wb') as file:
                    file.write(artwork)
            else:
                print('No artwork is currently available.')

        elif cmd == 'push_updates':
            print('Press ENTER to stop')

            atv.push_updater.start()
            yield from loop.run_in_executor(None, sys.stdin.readline)
            atv.push_updater.stop()

        elif cmd in ctrl:
            yield from _exec_command(atv.remote_control, cmd, *cmd_args)

        elif cmd in metadata:
            yield from _exec_command(atv.metadata, cmd, *cmd_args)

        elif cmd in playing:
            yield from _exec_command(playing_resp, cmd, *cmd_args)

        else:
            logging.error('Unknown command: %s', args.command)

    finally:
        yield from atv.logout()
Ejemplo n.º 16
0
def _handle_commands(args, loop):
    details = pyatv.AppleTVDevice(args.name, args.address, args.login_id)
    atv = pyatv.connect_to_apple_tv(details, loop)
    atv.push_updater.listener = PushListener()

    try:
        for cmd in args.command:
            ret = yield from _handle_command(args, cmd, atv, loop)
            if ret != 0:
                return ret
    finally:
        yield from atv.logout()

    return 0
Ejemplo n.º 17
0
def print_what_is_playing(loop):
    print('Discovering devices on network...')
    atvs = yield from pyatv.scan_for_apple_tvs(loop, timeout=5)

    if len(atvs) == 0:
        sys.stderr.print('no device found\n')
        return

    print('Connecting to {}'.format(atvs[0].address))
    atv = pyatv.connect_to_apple_tv(atvs[0], loop)

    try:
        playing = yield from atv.metadata.playing()
        print('Currently playing:')
        print(playing)
    finally:
        # Do not forget to logout
        yield from atv.logout()
Ejemplo n.º 18
0
def print_what_is_playing(loop):
    """Find a device and print what is playing."""
    print('Discovering devices on network...')
    atvs = yield from pyatv.scan_for_apple_tvs(loop, timeout=5)

    if not atvs:
        print('no device found', file=sys.stderr)
        return

    print('Connecting to {0}'.format(atvs[0].address))
    atv = pyatv.connect_to_apple_tv(atvs[0], loop)

    try:
        playing = yield from atv.metadata.playing()
        print('Currently playing:')
        print(playing)
    finally:
        # Do not forget to logout
        yield from atv.logout()
def _handle_commands(args, loop):
    #print('_handle_commands: name={0}, address={1}, login_id={2}'.format(args.name, args.address, args.login_id))
    details = pyatv.AppleTVDevice(args.name, args.address, args.login_id)
    atv = pyatv.connect_to_apple_tv(details, loop)
    atv.push_updater.listener = PushListener()

    try:
        if args.airplay_credentials is not None:
            yield from atv.airplay.load_credentials(args.airplay_credentials)

        for cmd in args.command:
            print('process cmd "{0}"'.format(str(cmd)))
            if cmd is None:
                break
            ret = yield from _handle_device_command(args, cmd, atv, loop)
            if ret != 0:
                return ret
    finally:
        yield from atv.logout()

    return 0
Ejemplo n.º 20
0
def _handle_commands(args, loop):
    details = AppleTV(args.address, args.name)
    if args.protocol == const.PROTOCOL_DMAP:
        details.add_service(DmapService(args.login_id, port=args.port))
    elif args.protocol == const.PROTOCOL_MRP:
        details.add_service(MrpService(args.port))

    atv = pyatv.connect_to_apple_tv(details, loop, protocol=args.protocol)
    atv.push_updater.listener = PushListener()

    try:
        if args.airplay_credentials is not None:
            yield from atv.airplay.load_credentials(args.airplay_credentials)

        for cmd in args.command:
            ret = yield from _handle_device_command(args, cmd, atv, loop)
            if ret != 0:
                return ret
    finally:
        yield from atv.logout()

    return 0
Ejemplo n.º 21
0
def async_setup_platform(hass,
                         config,
                         async_add_entities,
                         discovery_info=None):
    """Setup the Apple TV platform."""
    import pyatv

    if discovery_info is not None:
        name = discovery_info['name']
        host = discovery_info['host']
        login_id = discovery_info['hsgid']
    else:
        name = config.get(CONF_NAME)
        host = config.get(CONF_HOST)
        login_id = config.get(CONF_LOGIN_ID)

    if DATA_APPLE_TV not in hass.data:
        hass.data[DATA_APPLE_TV] = []

    if host in hass.data[DATA_APPLE_TV]:
        return False
    hass.data[DATA_APPLE_TV].append(host)

    details = pyatv.AppleTVDevice(name, host, login_id)
    session = async_get_clientsession(hass)
    atv = pyatv.connect_to_apple_tv(details, hass.loop, session=session)
    entity = AppleTvDevice(atv, name)

    @asyncio.coroutine
    def async_stop_subscription(event):
        """Logout device to close its session."""
        _LOGGER.info("Closing Apple TV session")
        yield from atv.logout()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                               async_stop_subscription)

    yield from async_add_entities([entity], update_before_add=True)
Ejemplo n.º 22
0
async def _poneys_skill(episode):
    print('Connecting to Apple TV')
    atv = pyatv.connect_to_apple_tv(apple_tv, asyncio.get_running_loop())
    for i in range(0, 3):
        client = _get_plex_client()
        try:
            if client is not None:
                client.stop()
        except requests.exceptions.ConnectionError:
            client = None
        if client is None:
            await _start_plex(atv, i == 1)
            time.sleep(1)
            continue
        try:
            client.playMedia(episode)
        except requests.exceptions.RequestException:
            time.sleep(0.5)
            continue
        break

    # yield from atv.logout()
    await atv._session.close(
    )  # pyatv 0.3.10 has bug in atv.logout method, it doesn't await close()
Ejemplo n.º 23
0
def async_setup_platform(hass, config, async_add_entities,
                         discovery_info=None):
    """Setup the Apple TV platform."""
    import pyatv

    if discovery_info is not None:
        name = discovery_info['name']
        host = discovery_info['host']
        login_id = discovery_info['hsgid']
    else:
        name = config.get(CONF_NAME)
        host = config.get(CONF_HOST)
        login_id = config.get(CONF_LOGIN_ID)

    if DATA_APPLE_TV not in hass.data:
        hass.data[DATA_APPLE_TV] = []

    if host in hass.data[DATA_APPLE_TV]:
        return False
    hass.data[DATA_APPLE_TV].append(host)

    details = pyatv.AppleTVDevice(name, host, login_id)
    session = async_get_clientsession(hass)
    atv = pyatv.connect_to_apple_tv(details, hass.loop, session=session)
    entity = AppleTvDevice(atv, name)

    @asyncio.coroutine
    def async_stop_subscription(event):
        """Logout device to close its session."""
        _LOGGER.info("Closing Apple TV session")
        yield from atv.logout()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                               async_stop_subscription)

    yield from async_add_entities([entity], update_before_add=True)
Ejemplo n.º 24
0
 def get_connected_device(self):
     details = AppleTVDevice('Apple TV', '127.0.0.1', HSGID, self.app.port)
     return connect_to_apple_tv(details, self.loop)
Ejemplo n.º 25
0
 def get_connected_device(self, identifier):
     conf = AppleTV('127.0.0.1', 'Apple TV')
     conf.add_service(DmapService(identifier, port=self.server.port))
     conf.add_service(AirPlayService(self.server.port))
     return connect_to_apple_tv(conf, self.loop)
Ejemplo n.º 26
0
 def get_connected_device(self, identifier):
     details = AppleTVDevice('Apple TV', '127.0.0.1', identifier,
                             self.app.port)
     return connect_to_apple_tv(details, self.loop)
Ejemplo n.º 27
0
 def get_connected_device(self, port):
     conf = AppleTV('127.0.0.1', 'Test device')
     conf.add_service(MrpService(port))
     conf.add_service(AirPlayService(self.server.port))
     return connect_to_apple_tv(conf, loop=self.loop)
Ejemplo n.º 28
0
 def get_connected_device(self, identifier):
     details = AppleTV('127.0.0.1', 'Apple TV')
     details.add_service(DmapService(identifier, port=self.app.port))
     details.add_service(AirPlayService(self.app.port))
     return connect_to_apple_tv(details, self.loop)