Пример #1
0
    def __init__(self, simulator=None, camera=False):
        """Constructeur de la classe Cherry

        Param :
        simulator -- Mettre simulator='vrep' si vous voulez utiliser Vrep (None par défault)
        camera -- Utilisation de la camera ou non (True par défault)
        
        """

        if simulator is not None:

            self.robot = PoppyHumanoid(simulator='vrep')
            self.isCamera = False

        
        else:
            # TODO : Changer avec robot = PoppyTorso()
            self.robot = from_json("../resource/mandatory/poppy_torso_config.json")
            self.robot.start_sync()

            for m in self.robot.motors:
                m.moving_speed = 60

            for m in self.robot.torso:
                m.compliant = False
            
            if camera:
                imagePath = "../utils/img/"
                cascadePath = "../utils/haarcascade_frontalface_default.xml"
                self.camera = Camera( self.robot, imagePath, cascadePath)
                self.isCamera = True
            else:
                self.isCamera = False
Пример #2
0
    def __init__(self, simulator=None, camera=False):
        """Constructeur de la classe Cherry

        Param :
        simulator -- Mettre simulator='vrep' si vous voulez utiliser Vrep (None par défault)
        camera -- Utilisation de la camera ou non (True par défault)
        
        """

        if simulator is not None:

            self.robot = PoppyHumanoid(simulator='vrep')
            self.isCamera = False

        else:
            # TODO : Changer avec robot = PoppyTorso()
            self.robot = from_json(
                "../resource/mandatory/poppy_torso_config.json")
            self.robot.start_sync()

            for m in self.robot.motors:
                m.moving_speed = 60

            for m in self.robot.torso:
                m.compliant = False

            if camera:
                imagePath = "../utils/img/"
                cascadePath = "../utils/haarcascade_frontalface_default.xml"
                self.camera = Camera(self.robot, imagePath, cascadePath)
                self.isCamera = True
            else:
                self.isCamera = False
Пример #3
0
	def __init__(self):
		# Import desired libraries when initialised.
		# Initialise the motors by using the mkIV configuration
		# Set all 
		# Set shortname aliases
		from pypot.robot import from_json
		from contextlib import closing
		self.robot = from_json('mkiv.json')
		for m in self.robot.motors:
			m.compliant = False
			m.goal_position = 0
		self.fr = self.robot.front_right
		self.fl = self.robot.front_left
		self.br = self.robot.back_right
		self.bl = self.robot.back_left
		self.last_left = 0;
		self.last_right = 0;
		self.speed_factor = 5;
Пример #4
0
    def __init__(self, simulator=None):
        if simulator is not None:

            self.robot = PoppyHumanoid(simulator='vrep')
            self.isCamera = False

        #Vrai :
        else:
            self.robot = from_json("../utils/poppy_torso_config.json")
            self.robot.start_sync()

            for m in self.robot.motors:
                m.moving_speed = 60

            for m in self.robot.torso:
                m.compliant = False
				
            imagePath = "../utils/img/"
            cascadePath = "haarcascade_frontalface_default.xml"
            self.camera = Camera( self.robot, imagePath, cascadePath)
            self.isCamera = True
Пример #5
0
def full_reachy(config_file):
    robot = from_json(config_file)

    motors = {
        'reachy': [],
        'leachy': [],
        'head': [],
    }

    for m in robot.motors:
        if m.name.startswith('r_'):
            motors['reachy'].append(m)
        elif m.name.startswith('l_'):
            motors['leachy'].append(m)
        else:
            motors['head'].append(m)

    reachy = RobotSubPart(robot, motors['reachy'])
    leachy = RobotSubPart(robot, motors['leachy'])
    head = RobotSubPart(robot, motors['head'])

    return robot, reachy, leachy, head
Пример #6
0
    def setup(cls, config):
        
        print "Robot setup started :"
        try:
            robot = from_json(config)
        except:
            print "Unable to configure the robot"
        else:
            print "Robot configuration successful !"
        print "Starting motors configuration"
            
        for m in robot.motors:
            m.compliant_behavior = 'dummy'
            m.goto_behavior = 'minjerk'
            m.moving_speed = 70
        
        for m in robot.motors:
            m.compliant = False
            m.goal_position = 0
            print m

        for m in robot.head:
            m.compliant = True

        try:
            attach_primitives(robot)
        except:
            print "Primitives not attached "
        else:
            print "Primitives attached successfully"

        try:
            robot.test_gtts.start()
        except:
            print "Something goes wrong with gTTS"
        else:
            print "gTTS OP"
        return robot
Пример #7
0
if __name__ == '__main__':
	pair = [120, 120, 120, 70, 0, -70, -70, -70, -70]
	impair = [120, 120, 120, 0, -70, 70, -70, -70, -70]

	choix = input ('choix patte: ')
	if choix ==  1:
		leg = 'rob.leg1'
	elif choix == 2:
		leg = 'rob.leg2'
	elif choix == 3:
		leg = 'rob.leg3'
	elif choix == 4:
		leg = 'rob.leg4'
	elif choix == 5:
		leg = 'rob.leg5'
	elif choix == 6:
		leg = 'rob.leg6'

	rob = from_json('rob.json')

	all_motors_not_compliant (rob)

	initialize_to_zero(rob, impair, gpair)

	Control_mouse(impair, pair, leg)

	rob.close()


Пример #8
0
import time
from pypot.robot import from_json
from contextlib import closing




with closing(from_json('robotConfig.json')) as my_robot:
    for m in my_robot.leg1:
        m.compliant = False
	m.goal_position = 0.0
    for m in my_robot.leg3:
        m.compliant = False
	m.goal_position = 0.0
    for m in my_robot.leg5:
        m.compliant = False
	m.goal_position = 0.0

    for m in my_robot.leg2:
        m.compliant = False
	m.goal_position = -45.0
    for m in my_robot.leg4:
        m.compliant = False
	m.goal_position = -45.0
    for m in my_robot.leg6:
        m.compliant = False
	m.goal_position = -45.0
	    	

Пример #9
0
from numpy import argmax, mean

from pypot.robot import from_json

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--log-file', type=str, required=True)
    parser.add_argument('-N', type=int, required=True)
    parser.add_argument('-c', '--config', type=str, required=True)
    args = parser.parse_args()

    bp = args.log_file
    if os.path.exists(bp):
        raise IOError('File already exists: {}'.format(bp))

    robot = from_json(args.config)

    # We keep the controller with most motors connected
    motors = [len(c.motors) for c in robot._controllers]
    c = robot._controllers[argmax(motors)]

    print('Using controller with motors {}'.format([m.id for m in c.motors]))
    c = c.controllers[0]

    dt = []
    for _ in range(args.N):
        start = time.time()
        c.get_present_position_speed_load()
        end = time.time()
        dt.append(end - start)
Пример #10
0
    sr.motor_42.goal_speed = 40
    sr.motor_43.goal_speed = 35
    sr.motor_42.goal_position = -70
    sr.motor_43.goal_position = 135


if __name__ == '__main__':

    state = "waiting"

    #with pypot.dynamixel.DxlIO('/dev/ttyUSB0', baudrate=1000000) as dxl_io:
    #        found_ids = dxl_io.scan()  # this may take several seconds
    #        changeId(found_ids)

    print("Initialisation du robot")
    spider_robot = from_json('spider_robot.json')
    scorpionMode(spider_robot)
    time.sleep(1)

    import sys, tty, termios
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    ch = ''

    while (ch != 'q' and ch != 'Q'):
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
Пример #11
0
    mainloop()


if __name__ == '__main__':
    pair = [120, 120, 120, 70, 0, -70, -70, -70, -70]
    impair = [120, 120, 120, 0, -70, 70, -70, -70, -70]

    choix = input('choix patte: ')
    if choix == 1:
        leg = 'rob.leg1'
    elif choix == 2:
        leg = 'rob.leg2'
    elif choix == 3:
        leg = 'rob.leg3'
    elif choix == 4:
        leg = 'rob.leg4'
    elif choix == 5:
        leg = 'rob.leg5'
    elif choix == 6:
        leg = 'rob.leg6'

    rob = from_json('rob.json')

    all_motors_not_compliant(rob)

    initialize_to_zero(rob, impair, gpair)

    Control_mouse(impair, pair, leg)

    rob.close()
Пример #12
0
    def __new__(cls,
                base_path=None,
                config=None,
                simulator=None,
                scene=None,
                host='127.0.0.1',
                port=19997,
                id=0,
                use_snap=False,
                snap_host='0.0.0.0',
                snap_port=6969,
                sync=True):
        """ 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 (only vrep for the moment)
        :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 int id: id of robot in the v-rep scene (not used yet!)
        :param bool sync: choose if automatically starts the synchronization loops

        .. 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)

        if config is None:
            config = os.path.join(os.path.join(base_path, 'configuration'),
                                  '{}.json'.format(creature))

        if simulator is not None:
            if simulator != 'vrep':
                raise ValueError(
                    'Unknown simulation mode: "{}"'.format(simulator))

            from pypot.vrep import from_vrep

            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
            poppy_creature = from_vrep(config, host, port, scene)
            poppy_creature.simulated = True

        else:
            poppy_creature = from_json(config, sync)
            poppy_creature.simulated = False

        if use_snap:
            poppy_creature.snap = SnapRobotServer(poppy_creature, snap_host,
                                                  snap_port)

        cls.setup(poppy_creature)

        return poppy_creature
Пример #13
0
def walk(x, y, z,sleep):
	p = 30;
	if (x < p and y < p) :
		moveLegWalk(x, y, z,sleep);
	else :
		n = max(x , y) / p;
		for i in range(int(n)) :
			moveLegWalk(x/n, y/n, z,sleep);
		if ((x % p) != 0 or (y % p) != 0) :
			moveLegWalk((x % p), (y % p), z,sleep);


# demonstration 
if __name__ == '__main__' :
	
	with closing(from_json('BB-9.json')) as my_robot :
		
		for m in my_robot.motors :
			m.compliant = False
		
		posBase()
		
		#moveOneLeg(5,0,0,0)
		#time.sleep(0.5)
		#moveOneLeg(5,40,40,80)
		#time.sleep(1)
		#moveCenterDemo(48,0.01)
		#time.sleep(0.5)
		#moveCenterDemo(800,0.001)
			
		#walk(300,-200,80,0.1)
Пример #14
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
Пример #15
0
import time
from random import randint
from pypot.robot import from_json
from grovepi import *
from strategy import *
from movements import *

# === create a robot object from json config file ===
poppy = from_json(
    "/home/poppy/miniconda/lib/python2.7/site-packages/poppy_torso/configuration/poppy_torso_new.json"
)
for m in poppy.motors:
    m.compliant = False
time.sleep(1)

# === global constants ===

w, h = 3, 3
empty = ' '
player_1 = 'X'
player_2 = 'O'
robot = player_2
board = [[empty for x in range(w)] for y in range(h)]
n_play = -1
current_player = player_1
current_winner = empty

polling = True
first_move = True
robot_move = False
human_move = False
Пример #16
0
	def close(self):
		# Cleanly close program (PyPot) DOES NOT WORK
		with closing(from_json('mkiv.json')) as my_robot:
			self.robot.close()
			pass
Пример #17
0
import time

# for pip install --user poppy-ergo-jr, from_json source is at:
# ~/.local/lib/python3.8/site-packages/pypot/robot/__init__.py
from pypot.robot import from_json

# custom configuration based on PoppyErgoJr config file
# for pip install --user poppy-ergo-jr, config file is at:
# ~/.local/lib/python3.8/site-packages/poppy_ergo_jr/configuration/poppy_ergo_jr.json
json_file = "dbg_config.json"
extra = {}
r = from_json(json_file, sync=True, strict=True, use_dummy_io=False, **extra)

# get the first motor from the config
m = r.m1
print(m)

# make it non-compliant to enable motion
m.compliant = False

# make a slight motion
m.goal_position = m.present_position + 15

# wait half a second for the motion to complete
# then print the position again to see the difference
time.sleep(.5)
print(m)

# make it compliant again so it can be moved by hand
m.compliant = False
Пример #18
0
 def __init__(self):
     self.rospack = RosPack()
     robot_config = join(self.rospack.get_path('pobax_playground'),
                         'config', 'torso.json')
     self.torso = from_json(robot_config)
     self.torso.compliant = False
Пример #19
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
Пример #20
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 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
Пример #21
0
import argparse

import zerorpc

from pypot.robot import from_json
from pypot.server import RESTRobot

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config-file', type=str, required=True)
    parser.add_argument('--host', type=str, default='0.0.0.0')
    parser.add_argument('-p', '--port', type=int, default=4242)
    args = parser.parse_args()

    robot = from_json(args.config_file)
    robot.start_sync()

    rest_robot = RESTRobot(robot)

    server = zerorpc.Server(rest_robot)
    print(args.host, args.port)
    server.bind('tcp://{}:{}'.format(args.host, args.port))
    server.run()
Пример #22
0
    def __new__(cls,
                base_path=None, config=None,
                simulator=None, scene=None, host='127.0.0.1', port=19997, id=0,
                use_snap=False, snap_host='0.0.0.0', snap_port=6969,
                use_http=False, http_host='0.0.0.0', http_port=8080,
                use_remote=False, remote_host='0.0.0.0', remote_port=4242,
                sync=True):
        """ 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 (only vrep for the moment)
        :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 int id: id of robot in the v-rep scene (not used yet!)
        :param bool sync: choose if automatically starts the synchronization loops


        .. 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)

        if config is None:
            config = os.path.join(os.path.join(base_path, 'configuration'),
                                  '{}.json'.format(creature))

        if simulator is not None:
            if simulator != 'vrep':
                raise ValueError('Unknown simulation mode: "{}"'.format(simulator))

            from pypot.vrep import from_vrep

            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
            poppy_creature = from_vrep(config, host, port, scene)
            poppy_creature.simulated = True

        else:
            poppy_creature = from_json(config, sync)
            poppy_creature.simulated = False

        if use_snap:
            poppy_creature.snap = SnapRobotServer(poppy_creature, snap_host, snap_port)

        if(use_http):
            from pypot.server.httpserver import HTTPRobotServer
            poppy_creature.http = HTTPRobotServer(poppy_creature, http_host, http_port, cross_domain_origin="*")

        if(use_remote):
            from pypot.server import RemoteRobotServer
            poppy_creature.remote = RemoteRobotServer(poppy_creature, remote_host, remote_port)

        cls.setup(poppy_creature)

        return poppy_creature
    my_robot.leg4[1].goal_position= u[1]
    my_robot.leg4[2].goal_position= u[2]

    u=leg_ik(120.26+x2, 69.43+y2, -90.57+z, 51, 63.7, 93)
    my_robot.leg2[0].goal_position= u[0]
    my_robot.leg2[1].goal_position= u[1]
    my_robot.leg2[2].goal_position= u[2]

    u=leg_ik(120.26+x6, -69.43+y6, -90.57+z, 51, 63.7, 93)
    my_robot.leg6[0].goal_position= u[0]
    my_robot.leg6[1].goal_position= u[1]
    my_robot.leg6[2].goal_position= u[2]

    

with closing(from_json('Json.json')) as my_robot:
    for m in my_robot.motors:
        m.compliant=False


    x=-20
    y=-20
    while True:
        time.sleep(0.1)

        move1_ik(-x,-y,15)
        time.sleep(0.1)
        move2_ik(x,y,0)
        time.sleep(0.1)
        move1_ik(-x,-y,0)
        time.sleep(0.1)
Пример #24
0
import argparse

import zerorpc

from pypot.robot import from_json
from pypot.server import RESTRobot


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config-file', type=str, required=True)
    parser.add_argument('--host', type=str, default='0.0.0.0')
    parser.add_argument('-p', '--port', type=int, default=4242)
    args = parser.parse_args()

    robot = from_json(args.config_file)
    robot.start_sync()

    rest_robot = RESTRobot(robot)

    server = zerorpc.Server(rest_robot)
    print(args.host, args.port)
    server.bind('tcp://{}:{}'.format(args.host, args.port))
    server.run()
Пример #25
0

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--log-file',
                        type=str, required=True)
    parser.add_argument('-N', type=int, required=True)
    parser.add_argument('-c', '--config',
                        type=str, required=True)
    args = parser.parse_args()

    bp = args.log_file
    if os.path.exists(bp):
        raise IOError('File already exists: {}'.format(bp))

    robot = from_json(args.config)

    # We keep the controller with most motors connected
    ids = [len(c._ids) for c in robot._dxl_controllers]
    c = robot._dxl_controllers[argmax(ids)]

    print('Using controller with motors {}'.format(c._ids))

    dt = []
    for _ in range(args.N):
        start = time.time()
        c._get_pos_speed_load()
        end = time.time()
        dt.append(end - start)

    # We'll use raw file instead of numpy because of pypy
Пример #26
0
import time
import numpy
from pypot.dynamixel import *
import json
import sys









#with closing(from_json('BB-9.json')) as my_robot :
my_robot=from_json('BB-9.json')

for m in my_robot.motors :
	m.compliant = False	
	
angle = 20
rectificationAngleDeBase = 70
positionMotorThird = 0



while (True) :
	positionMotorSecond = min(angle * numpy.sin(time.time()), 0)
	positionMotorSecondBis = min(angle * numpy.sin(time.time() + numpy.pi), 0)

	#---------------------------Groupe 1 de leg------------------------------#
Пример #27
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
Пример #28
0
    def setup(cls):

        print "Robot setup started :"

        json_data = open('./config/conf.json')
        data = json.load(json_data)
        json_data.close()

        port = data['robot']['port']
        name = data['robot']['name']

        try:
            cls.robot = from_json('config/torso.json')
        except Exception as e:
            try:
                cls.robot = from_json('config/torso.json')
            except Exception as e:
                raise
            else:
                print "Robot configuration successful !"
            finally:
                pass
            raise
        else:
            print "Robot configuration successful !"

        # Attach Gtts
        try:
            cls.robot.attach_primitive(SayFR(cls.robot), 'say_fr')
            cls.robot.attach_primitive(SayEN(cls.robot), 'say_en')
            cls.robot.attach_primitive(SayES(cls.robot), 'say_es')
            cls.robot.attach_primitive(SayDE(cls.robot), 'say_de')

        except Exception as e:
            print "Something goes wrong with gTTS"
            raise
        else:
            print "gTTS attached successfully"

        print "Starting motors configuration"

        for m in cls.robot.motors:
            m.compliant_behavior = 'dummy'
            m.goto_behavior = 'minjerk'
            m.moving_speed = 80

        for m in cls.robot.motors:
            m.compliant = False
            m.goal_position = 0
            print m

        for m in cls.robot.head:
            m.compliant = True
        try:
            attach_primitives(cls.robot)
        except:
            print "Primitives not attached "
        else:
            print "Primitives attached successfully"

        try:
            cls.robot.torso_idle_motion.start()
            cls.robot.upper_body_idle_motion.start()
            # cls.robot.head_idle_motion.start()
        except Exception as e:
            raise
        else:
            pass

        # Voice.silent(text="Setup done",lang='en')
        try:
            Voice.silent(text="Bonjour, je m'appelle " + name +
                         ", ravi de vous rencontrer.",
                         lang='fr')
        except:
            print "WARNING : no response from google tts engine : Check internet connectivity"
        else:
            pass

        return cls.robot