def infos():
    from platform import platform as platform_version
    from notebook import __version__ as notebook_version
    web_access = True
    try:
        requests.get('https://www.poppy-project.org/')
    except:
        web_access = False
    check_version()

    def service_running(service):
        if os.system('sudo systemctl is-active {}'.format(service)) == 0:
            return True
        else:
            return False

    return render_template(
        'infos.html',
        ip=find_local_ip(),
        platform_version=platform_version().replace('-', ' '),
        python_version=sys.version.replace('\n', ''),
        notebook_version=notebook_version,
        web_access=web_access,
        api_running=pm.running,
        pm_running=service_running(pm.config.services.PuppetMaster),
        jupyter_running=service_running(pm.config.services.JupyterNotebook),
        docs_running=service_running(pm.config.services.PoppyDocs),
        viewer_running=service_running(pm.config.services.PoppyViewer)
    )
Exemple #2
0
    def __new__(cls,
                base_path=None,
                config=None,
                simulator=None,
                scene=None,
                host='localhost',
                port=19997,
                id=0,
                use_snap=False,
                snap_host='0.0.0.0',
                snap_port=6969,
                snap_quiet=True,
                use_http=False,
                http_host='0.0.0.0',
                http_port=8080,
                http_quiet=True,
                use_remote=False,
                remote_host='0.0.0.0',
                remote_port=4242,
                start_background_services=True,
                sync=True,
                **extra):
        """ Poppy Creature Factory.

        Creates a Robot (real or simulated) and specifies it to make it a specific Poppy Creature.

        :param str config: path to a specific json config (if None uses the default config of the poppy creature - e.g. poppy_humanoid.json)

        :param str simulator: name of the simulator used : 'vrep' or 'poppy-simu'
        :param str scene: specify a particular simulation scene (if None uses the default scene of the poppy creature - e.g. poppy_humanoid.ttt)
        :param str host: host of the simulator
        :param int port: port of the simulator
        :param bool use_snap: start or not the Snap! API
        :param str snap_host: host of Snap! API
        :param int snap_port: port of the Snap!
        :param bool use_http: start or not the HTTP API
        :param str http_host: host of HTTP API
        :param int http_port: port of the HTTP API
        :param int id: id of robot in the v-rep scene (not used yet!)
        :param bool sync: choose if automatically starts the synchronization loops

        You can also add extra keyword arguments to disable sensor. For instance, to use a DummyCamera, you can add the argument: camera='dummy'.

        .. warning:: You can not specify a particular config when using a simulated robot!

        """
        if config and simulator:
            raise ValueError('Cannot set a specific config '
                             'when using a simulated version!')

        creature = camelcase_to_underscore(cls.__name__)
        base_path = (os.path.dirname(__import__(creature).__file__)
                     if base_path is None else base_path)

        default_config = os.path.join(os.path.join(base_path, 'configuration'),
                                      '{}.json'.format(creature))

        if config is None:
            config = default_config

        if simulator is not None:
            if simulator == 'vrep':
                from pypot.vrep import from_vrep, VrepConnectionError

                scene_path = os.path.join(base_path, 'vrep-scene')

                if scene is None:
                    scene = '{}.ttt'.format(creature)

                if not os.path.exists(scene):
                    if ((os.path.basename(scene) != scene) or
                        (not os.path.exists(os.path.join(scene_path, scene)))):
                        raise ValueError(
                            'Could not find the scene "{}"!'.format(scene))

                    scene = os.path.join(scene_path, scene)
                # TODO: use the id so we can have multiple poppy creatures
                # inside a single vrep scene
                try:
                    poppy_creature = from_vrep(config, host, port, scene)
                except VrepConnectionError:
                    raise IOError('Connection to V-REP failed!')

            elif simulator == 'poppy-simu':
                use_http = True
                poppy_creature = use_dummy_robot(config)
            else:
                raise ValueError(
                    'Unknown simulation mode: "{}"'.format(simulator))

            poppy_creature.simulated = True

        else:
            try:
                poppy_creature = from_json(config, sync, **extra)
            except IndexError as e:
                raise IOError('Connection to the robot failed! {}'.format(
                    str(e)))
            poppy_creature.simulated = False

        with open(config) as f:
            poppy_creature.config = json.load(f)

        urdf_file = os.path.join(
            os.path.join(base_path, '{}.urdf'.format(creature)))
        poppy_creature.urdf_file = urdf_file

        if use_snap:
            poppy_creature.snap = SnapRobotServer(poppy_creature,
                                                  snap_host,
                                                  snap_port,
                                                  quiet=snap_quiet)
            snap_url = 'http://snap.berkeley.edu/snapsource/snap.html'
            block_url = 'http://{}:{}/snap-blocks.xml'.format(
                find_local_ip(), snap_port)
            url = '{}#open:{}'.format(snap_url, block_url)
            print('SnapRobotServer is now running on: http://{}:{}\n'.format(
                snap_host, snap_port))
            print('You can open Snap! interface with loaded blocks at "{}"\n'.
                  format(url))

        if use_http:
            from pypot.server.httpserver import HTTPRobotServer
            poppy_creature.http = HTTPRobotServer(poppy_creature,
                                                  http_host,
                                                  http_port,
                                                  cross_domain_origin="*",
                                                  quiet=http_quiet)
            print('HTTPRobotServer is now running on: http://{}:{}\n'.format(
                http_host, http_port))

        if use_remote:
            from pypot.server import RemoteRobotServer
            poppy_creature.remote = RemoteRobotServer(poppy_creature,
                                                      remote_host, remote_port)
            print('RemoteRobotServer is now running on: http://{}:{}\n'.format(
                remote_host, remote_port))

        cls.setup(poppy_creature)

        if start_background_services:
            cls.start_background_services(poppy_creature)

        return poppy_creature
Exemple #3
0
def main():
    parser = argparse.ArgumentParser(description=(
        'Poppy services launcher. Use it to quickly instantiate a ' +
        'poppy creature with Snap!, an http server, or a remote robot.'),
                                     epilog="""
Examples:
* poppy-services --snap poppy-torso
* poppy-services --snap --vrep poppy-humanoid""",
                                     formatter_class=RawTextHelpFormatter)

    parser.add_argument('creature',
                        type=str,
                        help='poppy creature name',
                        action='store',
                        nargs='?',
                        choices=installed_poppy_creatures.keys())
    parser.add_argument('--dummy',
                        help='use a simulated dummy robot',
                        action='store_true')
    parser.add_argument('--vrep',
                        help='use a V-REP simulated Poppy Creature',
                        action='store_true')
    parser.add_argument(
        '--poppy-simu',
        help=
        'start a simulated dummy robot and the HTTP API to connect to the viewer on simu.poppy-project.org',
        action='store_true')
    parser.add_argument('--snap',
                        help='start a Snap! robot server',
                        action='store_true')
    parser.add_argument('--snap-port',
                        help='port used by the Snap! server',
                        default=6969,
                        type=int)
    parser.add_argument('-nb',
                        '--no-browser',
                        help='avoid automatic start of Snap! in web browser',
                        action='store_true')
    parser.add_argument('--http',
                        help='start a http robot server',
                        action='store_true')
    parser.add_argument('--http-port',
                        help='port of HttpRobotServer, used for poppy-simu',
                        default=8080,
                        type=int)
    parser.add_argument('--remote',
                        help='start a remote robot server',
                        action='store_true')
    parser.add_argument(
        '--zmq',
        help='start a remote robot server (but with faster ZMQ)',
        action='store_true')
    parser.add_argument('--ws',
                        help='start the websocket server',
                        action='store_true')
    parser.add_argument('--ws-port',
                        help='port of Websocket Server',
                        default=9009,
                        type=int)
    parser.add_argument('--disable-camera',
                        help='Start the robot without the camera.',
                        action='store_true')
    parser.add_argument(
        '-v',
        '--verbose',
        help=
        'start services with verbose mode. There is 3 debug levels, add as "v" as debug level you want',
        action='count')
    parser.add_argument('-kl',
                        '--with-keylogger',
                        help='start a background key logger for hit detection',
                        action='store_true')
    parser.add_argument('-f',
                        '--log-file',
                        help='Log filename',
                        action='store')

    nb_creatures = len(installed_poppy_creatures.keys())
    if nb_creatures == 0:
        print('No installed poppy creature were found!')
        print('You should first install the python package '
              'corresponding to your robot or check your python environment.')
        sys.exit(1)

    args = parser.parse_args()

    # If no creature are specified and only one is installed
    # We use it as default.
    if args.creature is None:
        if nb_creatures > 1:
            parser.print_help()
            sys.exit(1)

        args.creature = installed_poppy_creatures.keys()[0]
        print('No creature specified, use {}'.format(args.creature))

    if args.log_file:
        fh = logging.FileHandler(args.log_file)
        fh.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        logging.getLogger('').addHandler(fh)

    if args.verbose:
        args.snap_quiet = False
        args.http_quiet = False
        args.ws_quiet = False

        if args.verbose == 1:
            lvl = logging.WARNING
        elif args.verbose == 2:
            lvl = logging.INFO
        elif args.verbose > 2:
            lvl = logging.DEBUG

        if args.log_file is not None:
            ch = logging.FileHandler(args.log_file)
        else:
            ch = logging.StreamHandler()

        logging.basicConfig(
            level=lvl)  #FIXME: this is still not working properly.
        # I.e. logging level isn't set properly across all files, because they are all initiated with
        # the wrong logger name (non-dependent, just filename).
        formatter = logging.Formatter(
            '%(name)-12s: %(levelname)-8s %(message)s')
        ch.setFormatter(formatter)
        logging.getLogger('').addHandler(ch)

    if not any([
            args.snap, args.http, args.remote, args.zmq, args.poppy_simu,
            args.ws, args.dummy
    ]):
        print('No service specified! See --help for details.')
        sys.exit(1)

    if args.snap and not args.no_browser:
        snap_url = 'http://snap.berkeley.edu/snapsource/snap.html'
        block_url = 'http://{}:{}/snap-blocks.xml'.format(
            find_local_ip(), args.snap_port)
        url = '{}#open:{}'.format(snap_url, block_url)

        # Wait for the Snap server to be started before openning the Snap URL
        time.sleep(3)

        for browser_name in [
                'chromium-browser', 'chromium', 'google-chrome', 'chrome',
                'safari', 'midori', None
        ]:
            try:
                browser = webbrowser.get(browser_name)
                browser.open(url, new=0, autoraise=True)
                break
            except Exception:
                pass

    with closing(start_poppy_with_services(args)):
        print('Robot created and running!')
        sys.stdout.flush()

        # Just run4ever (until Ctrl-c...)
        try:
            while (True):
                time.sleep(1000)
        except KeyboardInterrupt:
            print("Bye bye!")
            raise SystemExit
Exemple #4
0
def main():
    parser = argparse.ArgumentParser(description=(
        'Poppy services launcher. Use it to quickly instantiate a ' +
        'poppy creature with Snap!, an http server, or a remote robot.'),
                                     epilog="""
Examples:
* poppy-services --snap poppy-torso
* poppy-services --snap --vrep poppy-humanoid""",
                                     formatter_class=RawTextHelpFormatter)

    parser.add_argument('creature',
                        type=str,
                        help='poppy creature name',
                        action='store',
                        nargs='?',
                        choices=list(installed_poppy_creatures.keys()))
    parser.add_argument('--dummy',
                        help='use a simulated dummy robot',
                        action='store_true')
    parser.add_argument('--vrep',
                        help='use a V-REP simulated Poppy Creature',
                        action='store_true')
    parser.add_argument(
        '--poppy-simu',
        help=
        'start a simulated dummy robot and the HTTP API to connect to the viewer on simu.poppy-project.org',
        action='store_true')
    parser.add_argument('--snap',
                        help='start a Snap! robot server',
                        action='store_true')
    parser.add_argument('--snap-port',
                        help='port used by the Snap! server',
                        default=6969,
                        type=int)
    parser.add_argument('-nb',
                        '--no-browser',
                        help='avoid automatic start of Snap! in web browser',
                        action='store_true')
    parser.add_argument('--http',
                        help='start a http robot server',
                        action='store_true')
    parser.add_argument('--http-port',
                        help='port of HttpRobotServer, used for poppy-simu',
                        default=8080,
                        type=int)
    parser.add_argument('--remote',
                        help='start a remote robot server',
                        action='store_true')
    parser.add_argument('--ws',
                        help='start the websocket server',
                        action='store_true')
    parser.add_argument('--ws-port',
                        help='port of Websocket Server',
                        default=9009,
                        type=int)
    parser.add_argument('--disable-camera',
                        help='Start the robot without the camera.',
                        action='store_true')
    parser.add_argument(
        '-v',
        '--verbose',
        help=
        'start services with verbose mode. There is 3 debug levels, add as "v" as debug level you want',
        action='count')
    parser.add_argument('-f',
                        '--log-file',
                        help='Log filename',
                        action='store')

    nb_creatures = len(installed_poppy_creatures.keys())
    if nb_creatures == 0:
        print('No installed poppy creature were found!')
        print('You should first install the python package '
              'corresponding to your robot or check your python environment.')
        sys.exit(1)

    args = parser.parse_args()

    # If no creature are specified and only one is installed
    # We use it as default.
    if args.creature is None:
        if nb_creatures > 1:
            parser.print_help()
            sys.exit(1)

        args.creature = list(installed_poppy_creatures.keys())[0]
        print('No creature specified, use {}'.format(args.creature))

    if args.log_file:
        fh = logging.FileHandler(args.log_file)
        fh.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        logging.getLogger('').addHandler(fh)

    if args.verbose:
        args.snap_quiet = False
        args.http_quiet = False
        args.ws_quiet = False

        if args.verbose == 1:
            lvl = logging.WARNING
        elif args.verbose == 2:
            lvl = logging.INFO
        elif args.verbose > 2:
            lvl = logging.DEBUG

        if args.log_file is not None:
            ch = logging.FileHandler(args.log_file)
        else:
            ch = logging.StreamHandler()

        ch.setLevel(lvl)
        formatter = logging.Formatter(
            '%(name)-12s: %(levelname)-8s %(message)s')
        ch.setFormatter(formatter)
        logging.getLogger('').addHandler(ch)

    if not any([
            args.snap, args.http, args.remote, args.poppy_simu, args.ws,
            args.dummy
    ]):
        print('No service specified! See --help for details.')
        sys.exit(1)

    static_server_started = False
    if args.snap and not args.no_browser:
        snap_static_port = 8888
        snap_static_server = HTTPServer(("0.0.0.0", snap_static_port),
                                        SimpleHTTPRequestHandler)

        from pypot.vpl.snap import download_snap_interactively
        static_app = download_snap_interactively()
        if static_app is None:
            print(
                "The static server was not started because the VPL app has not been downloaded"
            )
        else:
            os.chdir(static_app)
            snap_static_server_process = Process(
                target=snap_static_server.serve_forever, args=())
            static_server_started = True
            snap_static_server_process.start()

            snap_url = 'http://127.0.0.1:{}/snap.html'.format(snap_static_port)
            block_url = 'http://{}:{}/snap-blocks.xml'.format(
                find_local_ip(), args.snap_port)
            url = '{}#open:{}'.format(snap_url, block_url)

    with closing(start_poppy_with_services(args)):

        msg = ''

        if args.dummy or args.poppy_simu:
            msg += 'Simulated robot created! He is running on: ip={}'.format(
                find_local_ip())
        else:
            msg += 'Robot instantiated! He is running on: ip={},'.format(
                find_local_ip())
            if args.disable_camera: msg += ' without camera access.'
            else: msg += ' with camera access.'

        if args.vrep: msg += ' With V-REP link.'

        if args.snap or args.ws or args.http or args.poppy_simu:
            msg += '\nServer started on:'
            if args.http or args.poppy_simu:
                msg += ' http_port={},'.format(args.http_port)
            if args.snap: msg += ' Snap_port={},'.format(args.snap_port)
            if args.ws: msg += ' ws_port={},'.format(args.ws_port)
            msg = msg[0:-1] + '.'

        print(msg)

        sys.stdout.flush()

        if static_server_started:
            for browser_name in [
                    'chromium-browser', 'chromium', 'google-chrome', 'chrome',
                    'safari', 'midori', None
            ]:
                try:
                    browser = webbrowser.get(browser_name)
                    browser.open(url, new=0, autoraise=True)
                    break
                except Exception:
                    pass

        # Just run4ever (until Ctrl-c...)
        try:
            while (True):
                time.sleep(1000)
        except KeyboardInterrupt:
            print("Bye bye!")
            if static_server_started:
                snap_static_server_process.terminate()
                snap_static_server_process.join()
Exemple #5
0
    def __new__(cls,
                base_path=None, config="monrobot.json",
                simulator=None, scene=None, host='localhost', port=19997, id=0,
                use_snap=True, snap_host='0.0.0.0', snap_port=6969, snap_quiet=True,
                use_http=False, http_host='0.0.0.0', http_port=8080, http_quiet=True,
                use_remote=False, remote_host='0.0.0.0', remote_port=4242,
                start_background_services=True, sync=True,
                **extra):
        """ Poppy Creature Factory.
        Creates a Robot (real or simulated) and specifies it to make it a specific Poppy Creature.
        :param str config: path to a specific json config (if None uses the default config of the poppy creature - e.g. poppy_humanoid.json)
        :param str simulator: name of the simulator used : 'vrep' or 'poppy-simu'
        :param str scene: specify a particular simulation scene (if None uses the default scene of the poppy creature - e.g. poppy_humanoid.ttt)
        :param str host: host of the simulator
        :param int port: port of the simulator
        :param bool use_snap: start or not the Snap! API
        :param str snap_host: host of Snap! API
        :param int snap_port: port of the Snap!
        :param bool use_http: start or not the HTTP API
        :param str http_host: host of HTTP API
        :param int http_port: port of the HTTP API
        :param int id: id of robot in the v-rep scene (not used yet!)
        :param bool sync: choose if automatically starts the synchronization loops
        You can also add extra keyword arguments to disable sensor. For instance, to use a DummyCamera, you can add the argument: camera='dummy'.
        .. warning:: You can not specify a particular config when using a simulated robot!
        """
        print(config)
        if config and simulator:
            raise ValueError('Cannot set a specific config '
                             'when using a simulated version!')

        #creature = camelcase_to_underscore(cls.__name__)
        #base_path = (os.path.dirname(__import__(creature).__file__)
        #             if base_path is None else base_path)

        #default_config = os.path.join(os.path.join(base_path, 'configuration'),
        #                              '{}.json'.format(creature))

        if config is None:
            config = default_config

        if simulator is not None:
            if simulator == 'vrep':
                from pypot.vrep import from_vrep, VrepConnectionError

                scene_path = os.path.join(base_path, 'vrep-scene')

                if scene is None:
                    scene = '{}.ttt'.format(creature)

                if not os.path.exists(scene):
                    if ((os.path.basename(scene) != scene) or
                            (not os.path.exists(os.path.join(scene_path, scene)))):
                        raise ValueError('Could not find the scene "{}"!'.format(scene))

                    scene = os.path.join(scene_path, scene)
                # TODO: use the id so we can have multiple poppy creatures
                # inside a single vrep scene
                try:
                    poppy_creature = from_vrep(config, host, port, scene)
                except VrepConnectionError:
                    raise IOError('Connection to V-REP failed!')

            elif simulator == 'poppy-simu':
                use_http = True
                poppy_creature = use_dummy_robot(config)
            else:
                raise ValueError('Unknown simulation mode: "{}"'.format(simulator))

            poppy_creature.simulated = True

        else:
            try:
                poppy_creature = from_json(config, sync, **extra)
            except IndexError as e:
                raise IOError('Connection to the robot failed! {}'.format(e.message))
            poppy_creature.simulated = False

        with open(config) as f:
            poppy_creature.config = json.load(f)

      #  urdf_file = os.path.join(os.path.join(base_path,
      #                                        '{}.urdf'.format(creature)))
      #  poppy_creature.urdf_file = urdf_file

        if use_snap:
            poppy_creature.snap = SnapRobotServer(
                poppy_creature, snap_host, snap_port, quiet=snap_quiet)
            snap_url = 'http://snap.berkeley.edu/snapsource/snap.html'
            block_url = 'http://{}:{}/snap-blocks.xml'.format(find_local_ip(), snap_port)
            url = '{}#open:{}'.format(snap_url, block_url)
            print('SnapRobotServer is now running on: http://{}:{}\n'.format(snap_host, snap_port))
            print('You can open Snap! interface with loaded blocks at "{}"\n'.format(url))

        if use_http:
            from pypot.server.httpserver import HTTPRobotServer
            poppy_creature.http = HTTPRobotServer(poppy_creature, http_host, http_port,
                                                  cross_domain_origin="*", quiet=http_quiet)
            print('HTTPRobotServer is now running on: http://{}:{}\n'.format(http_host, http_port))

        if use_remote:
            from pypot.server import RemoteRobotServer
            poppy_creature.remote = RemoteRobotServer(poppy_creature, remote_host, remote_port)
            print('RemoteRobotServer is now running on: http://{}:{}\n'.format(remote_host, remote_port))

        cls.setup(poppy_creature)

        if start_background_services:
            cls.start_background_services(poppy_creature)

        return poppy_creature
Exemple #6
0
def main():
    parser = argparse.ArgumentParser(
        description=('Poppy services launcher. Use it to quickly instantiate a ' +
                     'poppy creature with Snap!, an http server, or a remote robot.'),
        epilog="""
Examples:
* poppy-services --snap poppy-torso
* poppy-services --snap --vrep poppy-humanoid""",
        formatter_class=RawTextHelpFormatter)

    parser.add_argument('creature', type=str,
                        help='poppy creature name',
                        action='store', nargs='?',
                        choices=installed_poppy_creatures.keys())
    parser.add_argument('--vrep',
                        help='use a V-REP simulated Poppy Creature',
                        action='store_true')
    parser.add_argument('--poppy-simu',
                        help='use a Three.js visualization',
                        action='store_true')
    parser.add_argument('--snap',
                        help='start a Snap! robot server',
                        action='store_true')
    parser.add_argument('--snap-port',
                        help='port used by the Snap! server',
                        default=6969, type=int)
    parser.add_argument('-nb', '--no-browser',
                        help='avoid automatic start of Snap! in web browser',
                        action='store_true')
    parser.add_argument('--http',
                        help='start a http robot server',
                        action='store_true')
    parser.add_argument('--http-port',
                        help='port of HttpRobotServer, used for poppy-simu',
                        default=8080, type=int)
    parser.add_argument('--remote',
                        help='start a remote robot server',
                        action='store_true')
    parser.add_argument('--ws',
                        help='start the websocket server',
                        action='store_true')
    parser.add_argument('--ws-port',
                        help='port of Websocket Server',
                        default=9009, type=int)
    parser.add_argument('--disable-camera',
                        help='Start the robot without the camera.',
                        action='store_true')
    parser.add_argument('-v', '--verbose',
                        help='start services with verbose mode. There is 3 debug levels, add as "v" as debug level you want',
                        action='count')
    parser.add_argument('-f', '--log-file',
                        help='Log filename',
                        action='store')

    nb_creatures = len(installed_poppy_creatures.keys())
    if nb_creatures == 0:
        print('No installed poppy creature were found!')
        print('You should first install the python package '
              'corresponding to your robot or check your python environment.')
        sys.exit(1)

    args = parser.parse_args()

    # If no creature are specified and only one is installed
    # We use it as default.
    if args.creature is None:
        if nb_creatures > 1:
            parser.print_help()
            sys.exit(1)

        args.creature = installed_poppy_creatures.keys()[0]
        print('No creature specified, use {}'.format(args.creature))

    if args.log_file:
        fh = logging.FileHandler(args.log_file)
        fh.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        logging.getLogger('').addHandler(fh)

    if args.verbose:
        args.snap_quiet = False
        args.http_quiet = False
        args.ws_quiet = False

        if args.verbose == 1:
            lvl = logging.WARNING
        elif args.verbose == 2:
            lvl = logging.INFO
        elif args.verbose > 2:
            lvl = logging.DEBUG

        if args.log_file is not None:
            ch = logging.FileHandler(args.log_file)
        else:
            ch = logging.StreamHandler()

        ch.setLevel(lvl)
        formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
        ch.setFormatter(formatter)
        logging.getLogger('').addHandler(ch)

    if not any([args.snap, args.http, args.remote, args.poppy_simu, args.ws]):
        print('No service specified! See --help for details.')
        sys.exit(1)

    if args.snap and not args.no_browser:
        snap_url = 'http://snap.berkeley.edu/snapsource/snap.html'
        block_url = 'http://{}:{}/snap-blocks.xml'.format(find_local_ip(), args.snap_port)
        url = '{}#open:{}'.format(snap_url, block_url)

        for browser_name in ['chromium-browser', 'chromium', 'google-chrome',
                             'chrome', 'safari', 'midori', None]:
            try:
                browser = webbrowser.get(browser_name)
                browser.open(url, new=0, autoraise=True)
                break
            except:
                pass

    with closing(start_poppy_with_services(args)):
        print('Robot created and running!')
        sys.stdout.flush()

        # Just run4ever (until Ctrl-c...)
        try:
            while(True):
                time.sleep(1000)
        except KeyboardInterrupt:
            print("Bye bye!")
Exemple #7
0
    def __new__(cls,
                base_path=None,
                config=None,
                simulator=None,
                scene=None,
                host='localhost',
                port=19997,
                id=None,
                shared_vrep_io=None,
                use_snap=False,
                snap_host='0.0.0.0',
                snap_port=6969,
                snap_quiet=True,
                use_http=False,
                http_host='0.0.0.0',
                http_port=8080,
                http_quiet=True,
                use_remote=False,
                remote_host='0.0.0.0',
                remote_port=4242,
                use_ws=False,
                ws_host='0.0.0.0',
                ws_port=9009,
                start_background_services=True,
                sync=True,
                **extra):
        """ Poppy Creature Factory.

        Creates a Robot (real or simulated) and specifies it to make it a specific Poppy Creature.

        :param str config: path to a specific json config (if None uses the default config of the poppy creature - e.g. poppy_humanoid.json)

        :param str simulator: name of the simulator used : 'vrep', 'poppy-simu', or 'dummy-robot'
        :param str scene: specify a particular simulation scene (if None uses the default scene of the poppy creature, use "keep-existing" to keep the current VRep scene - e.g. poppy_humanoid.ttt)
        :param str host: host of the simulator
        :param int port: port of the simulator
        :param int id: robot id in simulator (useful when using a scene with multiple robots)
        :param vrep_io: use an already connected VrepIO (useful when using a scene with multiple robots)
        :type vrep_io: :class:`~pypot.vrep.io.VrepIO`
        :param bool use_snap: start or not the Snap! API
        :param str snap_host: host of Snap! API
        :param int snap_port: port of the Snap!
        :param bool use_http: start or not the HTTP API
        :param str http_host: host of HTTP API
        :param int http_port: port of the HTTP API
        :param int id: id of robot in the v-rep scene (not used yet!)
        :param bool sync: choose if automatically starts the synchronization loops

        You can also add extra keyword arguments to disable sensor. For instance, to use a DummyCamera, you can add the argument: camera='dummy'.

        .. warning:: You can not specify a particular config when using a simulated robot!

        """
        if config and simulator:
            raise ValueError('Cannot set a specific config '
                             'when using a simulated version!')

        creature = camelcase_to_underscore(cls.__name__)
        base_path = (os.path.dirname(__import__(creature).__file__)
                     if base_path is None else base_path)

        default_config = os.path.join(os.path.join(base_path, 'configuration'),
                                      '{}.json'.format(creature))

        if config is None:
            config = default_config

        if simulator is not None:
            if simulator == 'vrep':
                from pypot.vrep import from_vrep, VrepConnectionError

                scene_path = os.path.join(base_path, 'vrep-scene')
                if scene != "keep-existing":
                    if scene is None:
                        scene = '{}.ttt'.format(creature)

                    elif not os.path.exists(scene):
                        if ((os.path.basename(scene) != scene)
                                or (not os.path.exists(
                                    os.path.join(scene_path, scene)))):
                            raise ValueError(
                                'Could not find the scene "{}"!'.format(scene))

                    scene = os.path.join(scene_path, scene)
                # TODO: use the id so we can have multiple poppy creatures
                # inside a single vrep scene

                # vrep.simxStart no longer listen on localhost
                if host == 'localhost':
                    host = '127.0.0.1'

                try:
                    poppy_creature = from_vrep(
                        config,
                        host,
                        port,
                        scene if scene != "keep-existing" else None,
                        id=id,
                        shared_vrep_io=shared_vrep_io)
                except VrepConnectionError:
                    raise IOError('Connection to V-REP failed!')

            elif simulator == 'poppy-simu':
                use_http = True
                poppy_creature = use_dummy_robot(config)
            elif simulator == 'dummy':
                poppy_creature = use_dummy_robot(config)
            else:
                raise ValueError(
                    'Unknown simulation mode: "{}"'.format(simulator))

            poppy_creature.simulated = True

        else:
            for _ in range(MAX_SETUP_TRIALS):
                try:
                    poppy_creature = from_json(config, sync, **extra)
                    logger.info('Init successful')
                    break
                except Exception as e:
                    logger.warning('Init fail: {}'.format(str(e)))
                    exc_type, exc_inst, tb = sys.exc_info()

            else:
                raise OSError(
                    'Could not initialize robot: {} '.format(exc_inst))
            poppy_creature.simulated = False

        with open(config) as f:
            poppy_creature.config = json.load(f)

        urdf_file = os.path.join(
            os.path.join(base_path, '{}.urdf'.format(creature)))
        poppy_creature.urdf_file = urdf_file

        if use_snap:
            poppy_creature.snap = SnapRobotServer(poppy_creature,
                                                  snap_host,
                                                  snap_port,
                                                  quiet=snap_quiet)
            snap_url = 'http://snap.berkeley.edu/snapsource/snap.html'
            block_url = 'http://{}:{}/snap-blocks.xml'.format(
                find_local_ip(), snap_port)
            url = '{}#open:{}'.format(snap_url, block_url)
            logger.info(
                'SnapRobotServer is now running on: http://{}:{}\n'.format(
                    snap_host, snap_port))
            logger.info(
                'You can open Snap! interface with loaded blocks at "{}"\n'.
                format(url))

        if use_http:
            from pypot.server.httpserver import HTTPRobotServer
            poppy_creature.http = HTTPRobotServer(poppy_creature,
                                                  http_host,
                                                  http_port,
                                                  cross_domain_origin="*",
                                                  quiet=http_quiet)
            logger.info(
                'HTTPRobotServer is now running on: http://{}:{}\n'.format(
                    http_host, http_port))

        if use_remote:
            from pypot.server import RemoteRobotServer
            poppy_creature.remote = RemoteRobotServer(poppy_creature,
                                                      remote_host, remote_port)
            logger.info(
                'RemoteRobotServer is now running on: http://{}:{}\n'.format(
                    remote_host, remote_port))

        if use_ws:
            from pypot.server import WsRobotServer
            poppy_creature.ws = WsRobotServer(poppy_creature, ws_host, ws_port)
            logger.info('Ws server is now running on: ws://{}:{}\n'.format(
                ws_host, ws_port))

        cls.setup(poppy_creature)

        if start_background_services:
            cls.start_background_services(poppy_creature)

        return poppy_creature
    def __new__(cls,
                base_path=None, config=None,
                simulator=None, scene=None, host='localhost', port=19997, id=None, shared_vrep_io=None,
                use_snap=False, snap_host='0.0.0.0', snap_port=6969, snap_quiet=True,
                use_http=False, http_host='0.0.0.0', http_port=8080, http_quiet=True,
                use_remote=False, remote_host='0.0.0.0', remote_port=4242,
                use_ws=False, ws_host='0.0.0.0', ws_port=9009,
                start_background_services=True, sync=True,
                **extra):
        """ Poppy Creature Factory.

        Creates a Robot (real or simulated) and specifies it to make it a specific Poppy Creature.

        :param str config: path to a specific json config (if None uses the default config of the poppy creature - e.g. poppy_humanoid.json)

        :param str simulator: name of the simulator used : 'vrep', 'poppy-simu', or 'dummy-robot'
        :param str scene: specify a particular simulation scene (if None uses the default scene of the poppy creature, use "keep-existing" to keep the current VRep scene - e.g. poppy_humanoid.ttt)
        :param str host: host of the simulator
        :param int port: port of the simulator
        :param int id: robot id in simulator (useful when using a scene with multiple robots)
        :param vrep_io: use an already connected VrepIO (useful when using a scene with multiple robots)
        :type vrep_io: :class:`~pypot.vrep.io.VrepIO`
        :param bool use_snap: start or not the Snap! API
        :param str snap_host: host of Snap! API
        :param int snap_port: port of the Snap!
        :param bool use_http: start or not the HTTP API
        :param str http_host: host of HTTP API
        :param int http_port: port of the HTTP API
        :param int id: id of robot in the v-rep scene (not used yet!)
        :param bool sync: choose if automatically starts the synchronization loops

        You can also add extra keyword arguments to disable sensor. For instance, to use a DummyCamera, you can add the argument: camera='dummy'.

        .. warning:: You can not specify a particular config when using a simulated robot!

        """
        if config and simulator:
            raise ValueError('Cannot set a specific config '
                             'when using a simulated version!')

        creature = camelcase_to_underscore(cls.__name__)
        base_path = (os.path.dirname(__import__(creature).__file__)
                     if base_path is None else base_path)

        default_config = os.path.join(os.path.join(base_path, 'configuration'),
                                      '{}.json'.format(creature))

        if config is None:
            config = default_config

        if simulator is not None:
            if simulator == 'vrep':
                from pypot.vrep import from_vrep, VrepConnectionError

                scene_path = os.path.join(base_path, 'vrep-scene')
                if scene != "keep-existing":
                    if scene is None:
                        scene = '{}.ttt'.format(creature)

                    elif not os.path.exists(scene):
                        if ((os.path.basename(scene) != scene) or
                                (not os.path.exists(os.path.join(scene_path, scene)))):
                            raise ValueError('Could not find the scene "{}"!'.format(scene))

                    scene = os.path.join(scene_path, scene)
                # TODO: use the id so we can have multiple poppy creatures
                # inside a single vrep scene

                # vrep.simxStart no longer listen on localhost
                if host == 'localhost':
                    host = '127.0.0.1'

                try:
                    poppy_creature = from_vrep(config, host, port, scene if scene != "keep-existing" else None, id=id, shared_vrep_io=shared_vrep_io)
                except VrepConnectionError:
                    raise IOError('Connection to V-REP failed!')

            elif simulator == 'poppy-simu':
                use_http = True
                poppy_creature = use_dummy_robot(config)
            elif simulator == 'dummy':
                poppy_creature = use_dummy_robot(config)
            else:
                raise ValueError('Unknown simulation mode: "{}"'.format(simulator))

            poppy_creature.simulated = True

        else:
            for _ in range(MAX_SETUP_TRIALS):
                try:
                    poppy_creature = from_json(config, sync, **extra)
                    logger.info('Init successful')
                    break
                except Exception as e:
                    logger.warning('Init fail: {}'.format(str(e)))
                    exc_type, exc_inst, tb = sys.exc_info()

            else:
                raise OSError('Could not initalize robot: {} '.format(exc_inst))
            poppy_creature.simulated = False

        with open(config) as f:
            poppy_creature.config = json.load(f)

        urdf_file = os.path.join(os.path.join(base_path,
                                              '{}.urdf'.format(creature)))
        poppy_creature.urdf_file = urdf_file

        if use_snap:
            poppy_creature.snap = SnapRobotServer(
                poppy_creature, snap_host, snap_port, quiet=snap_quiet)
            snap_url = 'http://snap.berkeley.edu/snapsource/snap.html'
            block_url = 'http://{}:{}/snap-blocks.xml'.format(find_local_ip(), snap_port)
            url = '{}#open:{}'.format(snap_url, block_url)
            logger.info('SnapRobotServer is now running on: http://{}:{}\n'.format(snap_host, snap_port))
            logger.info('You can open Snap! interface with loaded blocks at "{}"\n'.format(url))

        if use_http:
            from pypot.server.httpserver import HTTPRobotServer
            poppy_creature.http = HTTPRobotServer(poppy_creature, http_host, http_port,
                                                  cross_domain_origin="*", quiet=http_quiet)
            logger.info('HTTPRobotServer is now running on: http://{}:{}\n'.format(http_host, http_port))

        if use_remote:
            from pypot.server import RemoteRobotServer
            poppy_creature.remote = RemoteRobotServer(poppy_creature, remote_host, remote_port)
            logger.info('RemoteRobotServer is now running on: http://{}:{}\n'.format(remote_host, remote_port))

        if use_ws:
            from pypot.server import WsRobotServer
            poppy_creature.ws = WsRobotServer(poppy_creature, ws_host, ws_port)
            logger.info('Ws server is now running on: ws://{}:{}\n'.format(ws_host, ws_port))

        cls.setup(poppy_creature)

        if start_background_services:
            cls.start_background_services(poppy_creature)

        return poppy_creature