Joint Position Example

Jump to: navigation , search

The joint position example(keyboard, joystick) demonstrates basic joint position control. The key or button mapped to either increasing or decreasing the angle of a particular joint on Sawyer's arm.

Introduction

Use a game controller or your dev machine's keyboard to control the angular joint positions of Sawyer's arm. If you would like to follow along with the actual source code for these examples on GitHub, it can be found through link for joint position joystick and link for joint position keyboard.

Usage

Start the joint position keyboard example program, ex:

$ rosrun intera_examples joint_position_keyboard.py

Start the joint position joystick example program, ex:

$ rosrun intera_examples joint_position_joystick.py

Upon startup, you will be prompted with the following:

Initializing node...
Getting robot state...
Enabling robot...
[INFO] [WallTime: 1399575163.891211] Robot Enabled
Controlling joints. Press ? for help, Esc to quit.

Arguments

Important Arguments:

See the joint position example available arguments on the command line by passing:

$ rosrun intera_examples joint_position_keyboard.py -h
usage: joint_position_keyboard.py [-h] [-l LIMB]

RSDK Joint Position Example: Keyboard Control
    Use your dev machine's keyboard to control joint positions.
    Each key corresponds to increasing or decreasing the angle
    of a joint on Sawyer'
s arm. The increasing and descreasing
    are represented by number key and letter key next to the number.
   

optional arguments:
  -h, --help            show this help message and exit
  -l LIMB, --limb LIMB
                        Limb on which to run the joint position keyboard example

For joint position joystick example:

$ rosrun intera_examples joint_position_joystick.py -h
usage: joint_position_joystick.py [-h] [-l LIMB] [-j JOYSTICK]

SDK Joint Position Example: Joystick Control
    Use a game controller to control the angular joint positions
    of Sawyer's arms.
    Attach a game controller to your dev machine and run this
    example along with the ROS joy_node to control the position
    of each joint in Sawyer'
s arm using the joystick. Be sure to
    provide your *joystick* type to setup appropriate key mappings.
    Each stick axis maps to a joint angle; which joints are currently
    controlled can be incremented by using the mapped increment buttons.
    Ex:
      (x,y -> e0,e1) >>increment>> (x,y -> e1,e2)

required arguments:
  -j, --joystick        specify the type of joystick to use

optional arguments:
  -h, --help            show this help message and exit
  -l LIMB, --limb LIMB
                        Limb on which to run the joint position joystick example


Joint Position Keyboard Code Walkthrough

Now, let's break down the code.

  1. """
  2. SDK Joint Position Example: keyboard
  3. """
  4. import argparse
  5.  
  6. import rospy
  7.  
  8. import intera_interface
  9. import intera_external_devices
  10.  
  11. from intera_interface import CHECK_VERSION

This imports the intera interface for accessing the limb and the gripper class. The intera_external_devices is imported to use its getch function, that captures the key presses on the keyboard. The CHECK_VERSION is imported to check if the software running on the robot would be compatible with this local version. It is not necessary to check the version in custom programs.

  1. def map_keyboard(side):
  2.     limb = intera_interface.Limb(side)
  3.    
  4.     try:
  5.         gripper = intera_interface.Gripper(side)
  6.     except:
  7.         has_gripper = False
  8.         rospy.logerr("Could not initalize the gripper.")
  9.     else:
  10.         has_gripper = True
  11.  
  12.     joints = limb.joint_names()

The instance of Limb class, limb and the instance of Gripper class, gripper are created. joint_names() method returns an array of joints of the limb.

  1.     def set_j(limb, joint_name, delta):
  2.         current_position = limb.joint_angle(joint_name)
  3.         joint_command = {joint_name: current_position + delta}
  4.         limb.set_joint_positions(joint_command)
  5.  
  6.     def set_g(action):
  7.         if has_gripper:
  8.             if action == "close":
  9.                 gripper.close()
  10.             elif action == "open":
  11.                 gripper.open()
  12.             elif action == "calibrate":
  13.                 gripper.calibrate()

The set_j() function is invoked whenever a valid key press occurs. The limb refers to the limb instance of Sawyer's limb. delta refers to the required displacement of the joint from its current position. The method joint_angle() returns the current position of that joint. Then the joint command message is updated for that corresponding joint to indicate the new position. set_joint_position() method publishes the joint commands to the position controller. The set_g function calls gripper action function(open(), or close() or calibrate()) when corresponding action is provided.

  1.     bindings = {
  2.         '1': (set_j, [limb, joints[0], 0.1], joints[0]+" increase"),
  3.         'q': (set_j, [limb, joints[0], -0.1], joints[0]+" decrease"),
  4.         '2': (set_j, [limb, joints[1], 0.1], joints[1]+" increase"),
  5.         'w': (set_j, [limb, joints[1], -0.1], joints[1]+" decrease"),
  6.         '3': (set_j, [limb, joints[2], 0.1], joints[2]+" increase"),
  7.         'e': (set_j, [limb, joints[2], -0.1], joints[2]+" decrease"),
  8.         '4': (set_j, [limb, joints[3], 0.1], joints[3]+" increase"),
  9.         'r': (set_j, [limb, joints[3], -0.1], joints[3]+" decrease"),
  10.         '5': (set_j, [limb, joints[4], 0.1], joints[4]+" increase"),
  11.         't': (set_j, [limb, joints[4], -0.1], joints[4]+" decrease"),
  12.         '6': (set_j, [limb, joints[5], 0.1], joints[5]+" increase"),
  13.         'y': (set_j, [limb, joints[5], -0.1], joints[5]+" decrease"),
  14.         '7': (set_j, [limb, joints[6], 0.1], joints[6]+" increase"),
  15.         'u': (set_j, [limb, joints[6], -0.1], joints[6]+" decrease"),
  16.         '8': (set_g, "close", side+" gripper close"),
  17.         'i': (set_g, "open", side+" gripper open"),
  18.         '9': (set_g, "calibrate", side+" gripper calibrate")
  19.      }

The bindings is a dictionary that holds the set of characters in the keyboard and their corresponding joints.

  1.     done = False
  2.     print("Controlling joints. Press ? for help, Esc to quit.")
  3.     while not done and not rospy.is_shutdown():
  4.         c = intera_external_devices.getch()
  5.         if c:
  6.             #catch Esc or ctrl-c
  7.             if c in ['\x1b', '\x03']:
  8.                 done = True
  9.                 rospy.signal_shutdown("Example finished.")

The done variable captures whether "esc" or "ctrl-c" was hit. The while loop iterates as long as the "esc" or "ctrl-c" is hit or ros-shutdown signal is given. c captures the keyboard input. If "esc" or "ctrl-c" is given then done gets updated as true, and a shutdown signal will be sent.

  1.             elif c in bindings:
  2.                 cmd = bindings[c]
  3.                 if c == '8' or c == 'i' or c == '9':
  4.                     cmd[0](cmd[1])
  5.                     print("command: %s" % (cmd[2],))
  6.                 else:
  7.                     #expand binding to something like "set_j(right, 'j0', 0.1)"
  8.                     cmd[0](*cmd[1])
  9.                     print("command: %s" % (cmd[2],))

The user inputted key is checked whether it is in the bindings dictionary. bindings[c] returns the value of the key c from the dictionary. The 0th index of the value refers to the function to be called and the next index holds the arguments to be sent along with that function. cmd[2] is the description of the joint command from the dictionary above.

  1.             else:
  2.                 print("key bindings: ")
  3.                 print("  Esc: Quit")
  4.                 print("  ?: Help")
  5.                 for key, val in sorted(bindings.items(),
  6.                                        key=lambda x: x[1][2]):
  7.                     print("  %s: %s" % (key, val[2]))

This case is executed when the key pressed is not a valid input. So, the key is sorted and is printed along with its corresponding description.

  1. def main():
  2.     """RSDK Joint Position Example: Keyboard Control
  3.    Use your dev machine's keyboard to control joint positions.
  4.    Each key corresponds to increasing or decreasing the angle
  5.    of a joint on Sawyer's arm. The increasing and descreasing
  6.    are represented by number key and letter key next to the number.
  7.    """
  8.     epilog = """
  9. See help inside the example with the '?' key for key bindings.
  10.    """
  11.     rp = intera_interface.RobotParams()
  12.     valid_limbs = rp.get_limb_names()
  13.     if not valid_limbs:
  14.         rp.log_message(("Cannot detect any limb parameters on this robot. "
  15.                         "Exiting."), "ERROR")
  16.         return
  17.     arg_fmt = argparse.RawDescriptionHelpFormatter
  18.     parser = argparse.ArgumentParser(formatter_class=arg_fmt,
  19.                                      description=main.__doc__,
  20.                                      epilog=epilog)
  21.     parser.add_argument(
  22.         "-l", "--limb", dest="limb", default=valid_limbs[0],
  23.         choices=valid_limbs,
  24.         help="Limb on which to run the joint position keyboard example"
  25.     )
  26.     args = parser.parse_args(rospy.myargv()[1:])
  27.  
  28.     print("Initializing node... ")
  29.     rospy.init_node("sdk_joint_position_keyboard")
  30.     print("Getting robot state... ")
  31.     rs = intera_interface.RobotEnable(CHECK_VERSION)
  32.     init_state = rs.state().enabled

The node is initialized and then the software version is checked for compatiblity with the local version. init_state captures Sawyer's initial state. This is to make sure that Sawyer is sent back to the same state after the program exits.

  1.     def clean_shutdown():
  2.         print("\nExiting example.")
  3.         if not init_state:
  4.             print("Disabling robot...")
  5.             rs.disable()
  6.     rospy.on_shutdown(clean_shutdown)

As explained above, the robot is checked if it was initially disabled and if so, it is disabled upon the program's termination.

  1.     rospy.loginfo("Enabling robot...")
  2.     rs.enable()
  3.     map_keyboard(args.limb)
  4.     print("Done.")
  5.  
  6.  
  7. if __name__ == '__main__':
  8.     main()

The robot is enabled before the programs execution. It is important to note that Sawyer should be auto-enabled before trying to move its joints. map_keyboard() function captures the key input and moves the joint as explained above.

Joint Position Joystick Code Walkthrough

Now, let's break down the code.

  1. import argparse
  2.  
  3. import rospy
  4.  
  5. import intera_interface
  6. import intera_external_devices
  7.  
  8. from intera_interface import CHECK_VERSION

This imports the intera interface for accessing the limb and the gripper class. The intera_external_devices is imported to use its joystick function, that captures the key presses on the joystick. The CHECK_VERSION is imported to check if the software running on the robot would be compatible with this local version. It is not necessary to check the version in custom programs.

  1. def rotate(l):
  2.     """
  3.    Rotates a list left.
  4.    @param l: the list
  5.    """
  6.     if len(l):
  7.         v = l[0]
  8.         l[:-1] = l[1:]
  9.         l[-1] = v

The rotate function rotates a list, it will be used in bindings. This moves all the elements in the list to one position to their left. So the element at 0th position moves to the nth position, element at nth position moves to (n-1)th position, and so on.

  1. def set_j(cmd, limb, joints, index, delta):
  2.     """
  3.    Set the selected joint to current pos + delta.
  4.    @param cmd: the joint command dictionary
  5.    @param limb: the limb to get the pos from
  6.    @param joints: a list of joint names
  7.    @param index: the index in the list of names
  8.    @param delta: delta to update the joint by
  9.    joint/index is to make this work in the bindings.
  10.    """
  11.     joint = joints[index]
  12.     cmd[joint] = delta + limb.joint_angle(joint)

joint_angle() method returns the current angle of the corresponding joint. This function builds the dictionary that is to be passed as a joint command. The last line assigns the new position which has an offset of delta from the current position.

  1. def map_joystick(joystick, side):
  2.     """
  3.    Maps joystick input to joint position commands.
  4.    @param joystick: an instance of a Joystick
  5.    """
  6.     limb = intera_interface.Limb(side)
  7.     gripper = None
  8.     try:
  9.         gripper = intera_interface.Gripper(side)
  10.     except:
  11.         rospy.loginfo("Could not detect a connected electric gripper.")

The instance of Limb class and the instance of Gripper class are created. No gripper will raise could not detect gripper info.

  1.     def set_g(action):
  2.         if gripper is not None:
  3.             if action == "close":
  4.                 gripper.close()
  5.             elif action == "open":
  6.                 gripper.open()
  7.             elif action == "calibrate":
  8.                 gripper.calibrate()

The set_g function calls gripper action function(open(), or close() or calibrate()) when corresponding action is provided.

  1.     limb_cmd = {}
  2.  
  3.     #available joints
  4.     joints = limb.joint_names()
  5.  
  6.     #abbreviations
  7.     jhi = lambda s: joystick.stick_value(s) > 0
  8.     jlo = lambda s: joystick.stick_value(s) < 0
  9.     bdn = joystick.button_down
  10.     bup = joystick.button_up

Create instance of joint names and abbreviations for joystick values, button up and button down. The joint_names() method returns a list of joints associated with the limb. The stick_value() method returns the dead-banded, scaled and offset value of the axis. The abbreviations for all these functions are created to be used within the bindings dictionary below.

  1.     def print_help(bindings_list):
  2.         print("Press Ctrl-C to quit.")
  3.         for bindings in bindings_list:
  4.             for (test, _cmd, doc) in bindings:
  5.                 if callable(doc):
  6.                     doc = doc()
  7.                 print("%s: %s" % (str(test[1][0]), doc))

The information about the joystick buttons and the corresponding joints are displayed. This information is available in bindings_list as below. The doc refers to the last element of the tuple and it is checked if it is a callable function. So, if there is a lambda function that evaluates and returns a string, then that function is called. Finally, the results are displayed.

  1.     bindings_list = []
  2.     bindings = [
  3.         ((jlo, ['leftStickHorz']), (set_j, [limb_cmd, limb, joints, 0, 0.1]),
  4.             lambda: "Increase " + joints[0]),
  5.         ((jhi, ['leftStickHorz']), (set_j, [limb_cmd, limb, joints, 0, -0.1]),
  6.             lambda: "Decrease " + joints[0]),
  7.         ((jlo, ['leftStickVert']), (set_j, [limb_cmd, limb, joints, 1, 0.1]),
  8.             lambda: "Increase " + joints[1]),
  9.         ((jhi, ['leftStickVert']), (set_j, [limb_cmd, limb, joints, 1, -0.1]),
  10.             lambda: "Decrease " + joints[1]),
  11.         ((jlo, ['rightStickHorz']), (set_j, [limb_cmd, limb, joints, 2, 0.1]),
  12.             lambda: "Increase " + joints[2]),
  13.         ((jhi, ['rightStickHorz']), (set_j, [limb_cmd, limb, joints, 2, -0.1]),
  14.             lambda: "Decrease " + joints[2]),
  15.         ((jlo, ['rightStickVert']), (set_j, [limb_cmd, limb, joints, 3, 0.1]),
  16.             lambda: "Increase " + joints[3]),
  17.         ((jhi, ['rightStickVert']), (set_j, [limb_cmd, limb, joints, 3, -0.1]),
  18.             lambda: "Decrease " + joints[3]),
  19.         ((bdn, ['leftBumper']), (rotate, [joints]), side + ": cycle joint"),
  20.         ((bdn, ['function1']), (print_help, [bindings_list]), "help"),
  21.         ((bdn, ['function2']), (print_help, [bindings_list]), "help"),
  22.         ]
  23.     if gripper:
  24.         bindings.extend([
  25.             ((bdn, ['rightTrigger']), (set_g, ['close'], gripper), side + " gripper close"),
  26.             ((bup, ['rightTrigger']), (set_g, ['open'], gripper), side + " gripper open"),
  27.             ((bdn, ['btnLeft']), (set_g, ['calibrate'], gripper), "right calibrate")
  28.             ])
  29.     bindings_list.append(bindings)

The first element of every tuple refers to the command that has to be executed. As indicated above set_j, bdn, bup, jhi and jlo refers to the function and their acronyms. The second tuple has a list that holds the list of arguments to be passed along with that function. The last element holds a string or a function that evaluates and forms a string to detail the joint under consideration.

  1.     rate = rospy.Rate(100)
  2.     print_help(bindings_list)
  3.     print("Press Ctrl-C to stop. ")
  4.     while not rospy.is_shutdown():
  5.         for (test, cmd, doc) in bindings:
  6.             if test[0](*test[1]):
  7.                 cmd[0](*cmd[1])
  8.                 if callable(doc):
  9.                     print(doc())
  10.                 else:
  11.                     print(doc)
  12.         if len(limb_cmd):
  13.             limb.set_joint_positions(limb_cmd)
  14.             limb_cmd.clear()
  15.         rate.sleep()
  16.     return False

The test tuple holds the function that needs to be called for a particular value to be tested. For instance, the first tuple holds the abbreviation bdn and the parameter rightTrigger that is passed along. This test function checks whether the joystick's button_down is pressed. If this is true then the cmd, that refers to the second tuple (gripper.close,[]) is parsed as above. For the first binding, the expression cmd[0](*cmd[1]) returns the function call gripper.close([]). The next line checks if the last tuple is a function (lambda) or not (string). Since the joints being controlled are updated dynamically, the lambda function is used to retrieve the current joints rj[0] and rj[1]. The dictionaries limb_cmd hold the joint commands for the limb. These dictionaries get populated when the set_j method is called by the previous section of code.

  1. def main():
  2.     """SDK Joint Position Example: Joystick Control
  3.    Use a game controller to control the angular joint positions
  4.    of Sawyer's arms.
  5.    Attach a game controller to your dev machine and run this
  6.    example along with the ROS joy_node to control the position
  7.    of each joint in Sawyer's arm using the joystick. Be sure to
  8.    provide your *joystick* type to setup appropriate key mappings.
  9.    Each stick axis maps to a joint angle; which joints are currently
  10.    controlled can be incremented by using the mapped increment buttons.
  11.    Ex:
  12.      (x,y -> e0,e1) >>increment>> (x,y -> e1,e2)
  13.    """
  14.     epilog = """
  15. See help inside the example with the "Start" button for controller
  16. key bindings.
  17.    """
  18.     rp = intera_interface.RobotParams()
  19.     valid_limbs = rp.get_limb_names()
  20.     if not valid_limbs:
  21.         rp.log_message(("Cannot detect any limb parameters on this robot. "
  22.                         "Exiting."), "ERROR")
  23.         return
  24.     arg_fmt = argparse.RawDescriptionHelpFormatter
  25.     parser = argparse.ArgumentParser(formatter_class=arg_fmt,
  26.                                      description=main.__doc__,
  27.                                      epilog=epilog)
  28.     required = parser.add_argument_group('required arguments')
  29.     required.add_argument(
  30.         '-j', '--joystick', required=True,
  31.         choices=['xbox', 'logitech', 'ps3'],
  32.         help='specify the type of joystick to use'
  33.     )
  34.     parser.add_argument(
  35.         "-l", "--limb", dest="limb", default=valid_limbs[0],
  36.         choices=valid_limbs,
  37.         help="Limb on which to run the joint position joystick example"
  38.     )
  39.     args = parser.parse_args(rospy.myargv()[1:])
  40.  
  41.     joystick = None
  42.     if args.joystick == 'xbox':
  43.         joystick = intera_external_devices.joystick.XboxController()
  44.     elif args.joystick == 'logitech':
  45.         joystick = intera_external_devices.joystick.LogitechController()
  46.     elif args.joystick == 'ps3':
  47.         joystick = intera_external_devices.joystick.PS3Controller()
  48.     else:
  49.         parser.error("Unsupported joystick type '%s'" % (args.joystick))
  50.  
  51.     print("Initializing node... ")
  52.     rospy.init_node("sdk_joint_position_joystick")
  53.     print("Getting robot state... ")
  54.     rs = intera_interface.RobotEnable(CHECK_VERSION)
  55.     init_state = rs.state().enabled

The type of joystick input is captured as entered by the user and an instance of the corresponding interface is created. The node is initialized and the robot is enabled.

  1.     def clean_shutdown():
  2.         print("\nExiting example.")
  3.         if not init_state:
  4.             print("Disabling robot...")
  5.             rs.disable()
  6.     rospy.on_shutdown(clean_shutdown)
  7.  
  8.     rospy.loginfo("Enabling robot...")
  9.     rs.enable()
  10.  
  11.     map_joystick(joystick, args.limb)
  12.     print("Done.")
  13.  
  14.  
  15. if __name__ == '__main__':
  16.     main()

The map_joystick() method performs the mapping and execution of the commands as explained above.