コード例 #1
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Xbox One platform"""
    from xbox.webapi.authentication.manager import AuthenticationManager
    from xbox.sg.enum import ConnectionState
    from xbox.sg.console import Console
    hass.loop.set_debug(True)
    ip_address = config.get(CONF_IP_ADDRESS)
    live_id = config.get(CONF_LIVE_ID)
    name = config.get(CONF_NAME)
    tokens_file_name = hass.config.path(config.get(CONF_TOKEN_FILE))
    _LOGGER.debug('Trying to authenticate')
    try:
        auth_mgr = AuthenticationManager.from_file(tokens_file_name)
        auth_mgr.authenticate(do_refresh=False)
        auth_mgr.dump(tokens_file_name)
    except Exception as e:
        _LOGGER.error(e)

    _LOGGER.debug('Authenticated, starting discovery.')
    consoles = Console.discover(timeout=1, addr=ip_address)

    if not consoles:
        _LOGGER.debug('No consoles found, could be turned off')
        async_add_devices([XboxOne(auth_mgr, live_id, ip_address, name)])
    else:
        async_add_devices([
            XboxOne(auth_mgr, live_id, ip_address, name, console)
            for console in consoles if console.liveid == live_id
        ])
コード例 #2
0
def cli_discover_consoles(args):
    """
    Discover consoles
    """
    LOGGER.info('Sending discovery packets to IP: {0}'.format(
        'IP: ' + args.address if args.address else '<MULTICAST>'))
    discovered = Console.discover(addr=args.address, timeout=1)

    if not len(discovered):
        LOGGER.error('No consoles discovered')
        sys.exit(ExitCodes.DiscoveryError)

    LOGGER.info('Discovered consoles ({0}): {1}'.format(
        len(discovered), ', '.join([str(c) for c in discovered])))

    if args.liveid:
        LOGGER.info('Filtering discovered consoles for LIVEID: {0}'.format(
            args.liveid))
        discovered = [c for c in discovered if c.liveid == args.liveid]
    if args.address:
        LOGGER.info('Filtering discovered consoles for IP address: {0}'.format(
            args.address))
        discovered = [c for c in discovered if c.address == args.address]

    return discovered
コード例 #3
0
def protocol_runner(video_pipe, audio_pipe):
    import gevent
    import logging
    from xbox.sg.console import Console
    from xbox.nano.manager import NanoManager
    from xbox.nano.render.client import Client

    logging.basicConfig(level=logging.DEBUG)

    consoles = Console.discover(timeout=1)
    if len(consoles):
        console = consoles[0]

        console.add_manager(NanoManager)
        console.connect()
        gevent.sleep(1)
        print('connected')
        console.nano.start_stream()
        console.wait(2)

        client = Client(PipedSink(video_pipe), PipedSink(audio_pipe), Sink())
        console.nano.start_gamestream(client)
        print('stream started')
        try:
            console.protocol.serve_forever()
        except KeyboardInterrupt:
            pass

    print('protocol_runner exit')
コード例 #4
0
def main():
    parser = argparse.ArgumentParser(description="Basic smartglass client")
    parser.add_argument('--tokens',
                        '-t',
                        default=TOKENS_FILE,
                        help="Token file, created by xbox-authenticate script")
    parser.add_argument('--address', '-a', help="IP address of console")
    parser.add_argument('--refresh',
                        '-r',
                        action='store_true',
                        help="Refresh xbox live tokens in provided token file")

    args = parser.parse_args()

    logging.basicConfig(level=logging.DEBUG)

    try:
        auth_mgr = AuthenticationManager.from_file(args.tokens)
        auth_mgr.authenticate(do_refresh=args.refresh)
        auth_mgr.dump(args.tokens)
    except Exception as e:
        print("Failed to authenticate with provided tokens, Error: %s" % e)
        print("Please re-run xbox-authenticate to get a fresh set")
        sys.exit(1)

    userhash = auth_mgr.userinfo.userhash
    token = auth_mgr.xsts_token.jwt
    discovered = Console.discover(timeout=1, addr=args.address)
    if len(discovered):
        console = discovered[0]
        console.on_timeout += on_timeout
        console.add_manager(InputManager)
        state = console.connect(userhash, token)
        if state != ConnectionState.Connected:
            print("Connection failed")
            sys.exit(1)
        console.wait(1)

        getch = get_getch_func()
        while True:
            ch = getch()
            print(ch)
            if ord(ch) == 3:  # CTRL-C
                sys.exit(1)

            elif ch not in input_map:
                continue

            button = input_map[ch]
            console.gamepad_input(button)
            console.wait(0.1)
            console.gamepad_input(GamePadButton.Clear)

        signal.signal(signal.SIGINT, lambda *args: console.protocol.stop())
        console.protocol.serve_forever()
    else:
        print("No consoles discovered")
        sys.exit(1)
コード例 #5
0
 def do_discovery(self, addr, tries):
     consoles = Console.discover(addr=addr, tries=tries)
     print("[Xbox.do_discovery] Consoles found:")
     print(consoles)
     if len(consoles) > 0:
         print("[Xbox.do_discovery] Console found")
         return consoles[0]
     else:
         print("[Xbox.do_discovery] No consoles found")
         return False
コード例 #6
0
def main():
    parser = argparse.ArgumentParser(description="Power off xbox one console")
    parser.add_argument('--tokens',
                        '-t',
                        default=TOKENS_FILE,
                        help="Token file, created by xbox-authenticate script")
    parser.add_argument('--liveid', '-l', help="Console Live ID")
    parser.add_argument('--address', '-a', help="IP address of console")
    parser.add_argument('--all',
                        action='store_true',
                        help="Power off all consoles")
    parser.add_argument('--refresh',
                        '-r',
                        action='store_true',
                        help="Refresh xbox live tokens in provided token file")

    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO)

    try:
        auth_mgr = AuthenticationManager.from_file(args.tokens)
        auth_mgr.authenticate(do_refresh=args.refresh)
        auth_mgr.dump(args.tokens)
    except Exception as e:
        print("Failed to authenticate with provided tokens, Error: %s" % e)
        print("Please re-run xbox-authenticate to get a fresh set")
        sys.exit(1)

    userhash = auth_mgr.userinfo.userhash
    token = auth_mgr.xsts_token.jwt

    if not args.liveid and not args.address and not args.all:
        print("No arguments supplied!")
        parser.print_help()
        sys.exit(1)

    consoles = Console.discover(timeout=1, addr=args.address)
    if not len(consoles):
        print("No consoles found!")
        sys.exit(1)

    if not args.all and args.liveid:
        consoles = [c for c in consoles if c.liveid == args.liveid]
    if not args.all and args.address:
        consoles = [c for c in consoles if c.address == args.address]

    for c in consoles:
        state = c.connect(userhash, token)
        if state != ConnectionState.Connected:
            print("Connecting to %s failed" % c)
            continue
        c.wait(1)
        print("Shutting down %s ..." % c)
        c.power_off()
コード例 #7
0
def main():
    parser = argparse.ArgumentParser(description="Basic smartglass client")
    parser.add_argument('--tokens',
                        '-t',
                        default=TOKENS_FILE,
                        help="Token file, created by xbox-authenticate script")
    parser.add_argument('--address', '-a', help="IP address of console")
    parser.add_argument('--refresh',
                        '-r',
                        action='store_true',
                        help="Refresh xbox live tokens in provided token file")
    parser.add_argument('--verbose',
                        '-v',
                        action='store_true',
                        help="Verbose flag, also log message content")

    args = parser.parse_args()

    if args.verbose:
        fmt = VerboseFormatter(logging.BASIC_FORMAT)
    else:
        fmt = logging.Formatter(logging.BASIC_FORMAT)

    handler = logging.StreamHandler()
    handler.setFormatter(fmt)
    logging.root.addHandler(handler)
    logging.root.setLevel(logging.DEBUG)

    # logging.basicConfig(level=logging.DEBUG, format=logfmt)

    try:
        auth_mgr = AuthenticationManager.from_file(args.tokens)
        auth_mgr.authenticate(do_refresh=args.refresh)
        auth_mgr.dump(args.tokens)
    except Exception as e:
        print("Failed to authenticate with provided tokens, Error: %s" % e)
        print("Please re-run xbox-authenticate to get a fresh set")
        sys.exit(1)

    userhash = auth_mgr.userinfo.userhash
    token = auth_mgr.xsts_token.jwt
    discovered = Console.discover(timeout=1, addr=args.address)
    if len(discovered):
        console = discovered[0]
        console.on_timeout += on_timeout
        state = console.connect(userhash, token)
        if state != ConnectionState.Connected:
            logging.error("Connection failed")
            sys.exit(1)

        signal.signal(signal.SIGINT, lambda *args: console.protocol.stop())
        console.protocol.serve_forever()
    else:
        logging.error("No consoles discovered")
        sys.exit(1)
コード例 #8
0
def main():
    parser = argparse.ArgumentParser(description="Basic smartglass client")
    parser.add_argument('--tokens',
                        '-t',
                        default=TOKENS_FILE,
                        help="Token file, created by xbox-authenticate script")
    parser.add_argument('--address', '-a', help="IP address of console")
    parser.add_argument('--refresh',
                        '-r',
                        action='store_true',
                        help="Refresh xbox live tokens in provided token file")
    args = parser.parse_args()

    logging.basicConfig(level=logging.DEBUG)

    try:
        auth_mgr = AuthenticationManager.from_file(args.tokens)
        auth_mgr.authenticate(do_refresh=args.refresh)
        auth_mgr.dump(args.tokens)
    except Exception as e:
        print("Failed to authenticate with provided tokens, Error: %s" % e)
        print("Please re-run xbox-authenticate to get a fresh set")
        sys.exit(1)

    userhash = auth_mgr.userinfo.userhash
    token = auth_mgr.xsts_token.jwt

    discovered = Console.discover(timeout=1, addr=args.address)
    if len(discovered):
        console = discovered[0]

        console.add_manager(NanoManager)
        console.connect(userhash, token)
        if console.connection_state != ConnectionState.Connected:
            print("Connection failed")
            sys.exit(1)

        console.wait(1)
        console.nano.start_stream()
        console.wait(5)

        client = SDLClient(1920, 1080)
        console.nano.start_gamestream(client)

        try:
            console.protocol.serve_forever()
        except KeyboardInterrupt:
            pass
    else:
        print("No consoles discovered")
        sys.exit(1)
コード例 #9
0
def main():
    parser = argparse.ArgumentParser(description="Basic smartglass client")
    parser.add_argument('--tokens',
                        '-t',
                        default=TOKENS_FILE,
                        help="Token file, created by xbox-authenticate script")
    parser.add_argument('--address', '-a', help="IP address of console")
    parser.add_argument('--refresh',
                        '-r',
                        action='store_true',
                        help="Refresh xbox live tokens in provided token file")

    args = parser.parse_args()

    logging.basicConfig(level=logging.DEBUG)

    try:
        auth_mgr = AuthenticationManager.from_file(args.tokens)
        auth_mgr.authenticate(do_refresh=args.refresh)
        auth_mgr.dump(args.tokens)
    except Exception as e:
        print("Failed to authenticate with provided tokens, Error: %s" % e)
        print("Please re-run xbox-authenticate to get a fresh set")
        sys.exit(1)

    userhash = auth_mgr.userinfo.userhash
    token = auth_mgr.xsts_token.jwt
    discovered = Console.discover(timeout=1, addr=args.address)
    if len(discovered):
        console = discovered[0]
        console.on_timeout += on_timeout
        console.add_manager(TextManager)
        console.text.on_systemtext_configuration += on_text_config
        console.text.on_systemtext_input += functools.partial(
            on_text_input, console)
        console.text.on_systemtext_done += on_text_done
        state = console.connect(userhash, token)
        if state != ConnectionState.Connected:
            print("Connection failed")
            sys.exit(1)
        console.wait(1)

        signal.signal(signal.SIGINT, lambda *args: console.protocol.stop())
        console.protocol.serve_forever()
    else:
        print("No consoles discovered")
        sys.exit(1)
コード例 #10
0
def main():
    parser = argparse.ArgumentParser(
        description="Discover consoles on the network")
    parser.add_argument('--address', '-a', help="IP address of console")

    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO)

    print("Discovering consoles...")
    discovered = Console.discover(timeout=1, addr=args.address)
    if len(discovered):
        print("Discovered %d consoles:" % len(discovered))
        for console in discovered:
            print("\t%s" % console)
    else:
        print("No consoles discovered!")
コード例 #11
0
    def async_update(self):
        from xbox.sg.console import Console
        from xbox.sg.manager import MediaManager
        userhash = self._auth_mgr.userinfo.userhash
        token = self._auth_mgr.xsts_token.jwt
        _LOGGER.debug(f'Start update')

        if self._console:
            _LOGGER.debug(
                f'Console is present: {self._console.to_dict()} and {self._console.connected}'
            )
            if not self.connected:
                self._console.add_manager(MediaManager)
                self._console.connect(userhash=userhash, xsts_token=token)
            if self.connected:
                active_media = self._console.media.active_media
                title_id = self._console.media.title_id
                aum_id = self._console.media.aum_id
                asset_id = self._console.media.asset_id
                media_type = self._console.media.media_type
                sound_level = self._console.media.sound_level
                playback_status = self._console.media.playback_status
                position = self._console.media.position
                media_start = self._console.media.media_start
                metadata = self._console.media.metadata
                _LOGGER.debug(f'The active_media is {active_media}.')
                _LOGGER.debug(f'The title_id is {title_id}.')
                _LOGGER.debug(f'The aum_id is {aum_id}.')
                _LOGGER.debug(f'The asset_id is {asset_id}.')
                _LOGGER.debug(f'The media_type is {media_type}.')
                _LOGGER.debug(f'The sound_level is {active_media}.')
                _LOGGER.debug(f'The playback_status is {playback_status}.')
                _LOGGER.debug(f'The position is {position}.')
                _LOGGER.debug(f'The media_start is {media_start}.')
                _LOGGER.debug(f'The metadata is {metadata}.')
        else:
            consoles = Console.discover(timeout=1, addr=self._ip_address)
            if consoles:
                filtered_cons = [
                    c for c in consoles if c.liveid == self._live_id
                ]
                if filtered_cons:
                    _LOGGER.debug('Console discovered during update.')
                    self._console = filtered_cons[0]
        _LOGGER.debug(f'End update')
コード例 #12
0
    def _refresh(self):
        discovered = Console.discover(blocking=True)

        liveids = [d.liveid for d in discovered]
        for i, c in enumerate(self.consoles):
            if c.liveid in liveids:
                # Refresh existing entries
                idx = liveids.index(c.liveid)
                if c.device_status != discovered[idx].device_status:
                    self.consoles[i] = discovered[idx]
                del discovered[idx]
                del liveids[idx]
            elif c.liveid not in liveids:
                # Set unresponsive consoles to Unavailable
                self.consoles[i].device_status = DeviceStatus.Unavailable

        # Add newly discovered consoles
        self.consoles.extend(discovered)

        # Update the consolelist view
        self.walker[:] = [ConsoleButton(self.app, c) for c in self.consoles]
コード例 #13
0
 def discover(self, addr=None):
     discovered = Console.discover(addr=addr, timeout=10)
     self.discovered = discovered
コード例 #14
0
 def discover():
     if os.environ['XBOX_IP']:
         return Console.discover(os.environ['XBOX_IP'])
     else:
         return Console.discover()
コード例 #15
0
 def discover():
     return Console.discover()
コード例 #16
0
 def connect(timeout):
     discovered = Console.discover(timeout=1)
     if len(discovered):
         return discovered[0]
     return discovered
コード例 #17
0
 def discover(*args, **kwargs):
     return Console.discover(*args, **kwargs)
コード例 #18
0
        def mainloop(skip_connection=False):
            while True:
                if skip_connection:
                    new_item = None
                    try:
                        new_item = self.inq.get_nowait()
                    except:
                        pass
                    if new_item is not None:
                        if isinstance(new_item, DiscoverRequest):
                            try:
                                discovered = Console.discover(
                                    addr=new_item.addr)
                            except OSError as e:
                                self.outq.put(
                                    XboxEvent(EVT_XBOX_DISCOVERYFAILURE_ID, e))
                            for console in discovered:
                                dc = DiscoveredConsole(console)
                                self.outq.put(
                                    XboxEvent(EVT_XBOX_DISCOVERED_CONSOLE_ID,
                                              dc))
                            if len(discovered) < 1:
                                try:
                                    Console.__protocol__.start()
                                    Console.__protocol__._discover(
                                        xbox.sg.factory.discovery(),
                                        xbox.sg.protocol.BROADCAST, 5)
                                except OSError as e:
                                    self.outq.put(
                                        XboxEvent(EVT_XBOX_DISCOVERYFAILURE_ID,
                                                  e))
                            self.inq.task_done()
                        if isinstance(new_item,
                                      ConnectionRequest) or isinstance(
                                          new_item, DiscoveredConsole):
                            on_connect_request(
                                new_item)  # this instantiates self._console
                            self.inq.task_done()
                        if isinstance(new_item, SystemTextSend):
                            if self._console is None or not self._console.connected:
                                error = "Failed to send text. Disconnected!"
                                self.outq.put(error)
                                print(error)
                            else:
                                self._console.send_systemtext_input(
                                    new_item.text)
                                self._console.finish_text_input()
                                self.outq.put(
                                    f"Sent {new_item.text} to console")
                                self.inq.task_done()
                        if isinstance(new_item, DisconnectRequest):
                            if self._console:
                                if self._console.connected:
                                    self._console.protocol._stop_event.set()
                                    self._console.disconnect()
                                    self.inq.task_done()
                                    self.outq.put(
                                        XboxEvent(
                                            EVT_XBOX_DISCONNECT_ID,
                                            self._console.address
                                            if self._console else None))
                                else:
                                    self.inq.task_done()
                                    self.outq.put(
                                        XboxEvent(
                                            EVT_XBOX_DISCONNECT_ID,
                                            self._console.address
                                            if self._console else None))
                            else:
                                self.inq.task_done()
                                self.outq.put(
                                    XboxEvent(
                                        EVT_XBOX_DISCONNECT_ID,
                                        self._console.address
                                        if self._console else None))
                        if new_item == POISON_PILL:
                            if self._console:
                                if self._console.connected:
                                    self._console.disconnect()
                                    self._console = None
                            self.inq.put("STOP")
                            self.inq.task_done()
                            break
                    gevent.sleep(0)

                if self._console:
                    if self._console.connected:
                        # print("console instantiated. started:", self._console.protocol.started)
                        # print("console status:", self._console.connection_state)
                        # print("Closed?:", self._console.protocol.closed)
                        # print("Timedout?:", self._timedout.is_set())
                        try:
                            ""
                            gevent.sleep(
                                self._console.protocol.HEARTBEAT_INTERVAL)
                            self._console.protocol.ack([], [],
                                                       ServiceChannel.Core,
                                                       need_ack=True)
                        except (OSError, AttributeError) as e:
                            self._console.protocol.on_timeout()
                            self.outq.put(
                                XboxEvent(EVT_XBOX_DISCONNECT_ID,
                                          f"Failed to connect {e}"))
                        finally:
                            if self._stay_connected.is_set(
                            ) and self._timedout.is_set():
                                gevent.sleep(10)
                                on_connect_request(
                                    ConnectionRequest(self._console))
                gevent.sleep(0.1)