hironx_client.py
Go to the documentation of this file.
00001 # -*- coding: utf-8 -*-
00002 
00003 # Software License Agreement (BSD License)
00004 #
00005 # Copyright (c) 2013, JSK Lab, University of Tokyo
00006 # All rights reserved.
00007 #
00008 # Redistribution and use in source and binary forms, with or without
00009 # modification, are permitted provided that the following conditions
00010 # are met:
00011 #
00012 #  * Redistributions of source code must retain the above copyright
00013 #    notice, this list of conditions and the following disclaimer.
00014 #  * Redistributions in binary form must reproduce the above
00015 #    copyright notice, this list of conditions and the following
00016 #    disclaimer in the documentation and/or other materials provided
00017 #    with the distribution.
00018 #  * Neither the name of JSK Lab, University of Tokyo. nor the
00019 #    names of its contributors may be used to endorse or promote products
00020 #    derived from this software without specific prior written permission.
00021 #
00022 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00023 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00024 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
00025 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
00026 # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
00027 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
00028 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
00029 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
00030 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
00031 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
00032 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
00033 # POSSIBILITY OF SUCH DAMAGE.
00034 
00035 import math
00036 import numpy
00037 import os
00038 import time
00039 
00040 import roslib
00041 roslib.load_manifest("hrpsys")
00042 from hrpsys.hrpsys_config import *
00043 import OpenHRP
00044 import OpenRTM_aist
00045 import OpenRTM_aist.RTM_IDL
00046 import rtm
00047 from waitInput import waitInputConfirm, waitInputSelect
00048 
00049 
00050 SWITCH_ON = OpenHRP.RobotHardwareService.SWITCH_ON
00051 SWITCH_OFF = OpenHRP.RobotHardwareService.SWITCH_OFF
00052 _MSG_ASK_ISSUEREPORT = 'Your report to ' + \
00053                        'https://github.com/start-jsk/rtmros_hironx/issues ' + \
00054                        'about the issue you are seeing is appreciated.'
00055 
00056 def delete_module(modname, paranoid=None):
00057     from sys import modules
00058     try:
00059         thismod = modules[modname]
00060     except KeyError:
00061         raise ValueError(modname)
00062     these_symbols = dir(thismod)
00063     if paranoid:
00064         try:
00065             paranoid[:]  # sequence support
00066         except:
00067             raise ValueError('must supply a finite list for paranoid')
00068         else:
00069             these_symbols = paranoid[:]
00070     del modules[modname]
00071     for mod in modules.values():
00072         try:
00073             delattr(mod, modname)
00074         except AttributeError:
00075             pass
00076         if paranoid:
00077             for symbol in these_symbols:
00078                 if symbol[:2] == '__':  # ignore special symbols
00079                     continue
00080                 try:
00081                     delattr(mod, symbol)
00082                 except AttributeError:
00083                     pass
00084 
00085 class HIRONX(HrpsysConfigurator):
00086     '''
00087     @see: <a href = "https://github.com/fkanehiro/hrpsys-base/blob/master/" +
00088                     "python/hrpsys_config.py">HrpsysConfigurator</a>
00089 
00090     This class holds methods that are specific to Kawada Industries' dual-arm
00091     robot called Hiro.
00092 
00093     For the API doc for the derived methods, please see the parent
00094     class via the link above; nicely formatted api doc web page
00095     isn't available yet (discussed in
00096     https://github.com/fkanehiro/hrpsys-base/issues/268).
00097     '''
00098 
00099     Groups = [['torso', ['CHEST_JOINT0']],
00100               ['head', ['HEAD_JOINT0', 'HEAD_JOINT1']],
00101               ['rarm', ['RARM_JOINT0', 'RARM_JOINT1', 'RARM_JOINT2',
00102                         'RARM_JOINT3', 'RARM_JOINT4', 'RARM_JOINT5']],
00103               ['larm', ['LARM_JOINT0', 'LARM_JOINT1', 'LARM_JOINT2',
00104                         'LARM_JOINT3', 'LARM_JOINT4', 'LARM_JOINT5']]]
00105 
00106     '''
00107     For OffPose and _InitialPose, the angles of each joint are listed in the
00108     ordered as defined in Groups variable.'''
00109     OffPose = [[0],
00110                [0, 0],
00111                [25, -139, -157, 45, 0, 0],
00112                [-25, -139, -157, -45, 0, 0],
00113                [0, 0, 0, 0],
00114                [0, 0, 0, 0]]
00115     # With this pose the EEFs level up the tabletop surface.
00116     _InitialPose = [[0], [0, 0],
00117                     [-0.6, 0, -100, 15.2, 9.4, 3.2],
00118                     [0.6, 0, -100, -15.2, 9.4, -3.2],
00119                     [0, 0, 0, 0],
00120                     [0, 0, 0, 0]]
00121     # This pose sets joint angles at the factory initial pose. No danger, but
00122     # no real advange either for in normal usage.
00123     # See https://github.com/start-jsk/rtmros_hironx/issues/107
00124     _InitialPose_Factory = [[0], [0, 0],
00125                             [-0, 0, -130, 0, 0, 0],
00126                             [0, 0, -130, 0, 0, 0],
00127                             [0, 0, 0, 0],
00128                             [0, 0, 0, 0]]
00129     INITPOS_TYPE_EVEN = 0
00130     INITPOS_TYPE_FACTORY = 1
00131 
00132     HandGroups = {'rhand': [2, 3, 4, 5], 'lhand': [6, 7, 8, 9]}
00133 
00134     RtcList = []
00135 
00136     # servo controller (grasper)
00137     sc = None
00138     sc_svc = None
00139 
00140     hrpsys_version = '0.0.0'
00141 
00142     def init(self, robotname="HiroNX(Robot)0", url=""):
00143         '''
00144         Calls init from its superclass, which tries to connect RTCManager,
00145         looks for ModelLoader, and starts necessary RTC components. Also runs
00146         config, logger.
00147         Also internally calls setSelfGroups().
00148 
00149         @type robotname: str
00150         @type url: str
00151         '''
00152         # reload for hrpsys 315.1.8
00153         HrpsysConfigurator.waitForModelLoader(self)
00154         HrpsysConfigurator.waitForRTCManagerAndRoboHardware(self, robotname=robotname)
00155         print self.configurator_name, "Hrpsys controller version info: "
00156         if self.ms :
00157             print self.configurator_name, "  ms = ", self.ms
00158         if self.ms and self.ms.ref :
00159             print self.configurator_name, "  ref = ", self.ms.ref
00160         if self.ms and self.ms.ref and len(self.ms.ref.get_component_profiles()) > 0:
00161             print self.configurator_name, "  version  = ", self.ms.ref.get_component_profiles()[0].version
00162         if self.ms and self.ms.ref and len(self.ms.ref.get_component_profiles()) > 0 and self.ms.ref.get_component_profiles()[0].version < '315.2.0':
00163             sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'hrpsys_315_1_9/hrpsys'))
00164             delete_module('ImpedanceControllerService_idl')
00165             import AbsoluteForceSensorService_idl
00166             import ImpedanceControllerService_idl
00167 
00168         HrpsysConfigurator.init(self, robotname=robotname, url=url)
00169         self.setSelfGroups()
00170         self.hrpsys_version = self.fk.ref.get_component_profile().version
00171 
00172         # connect ic if needed
00173         for sensor in ['lhsensor' , 'rhsensor']:
00174             if self.ic and self.ic.port(sensor) and self.ic.port(sensor).get_port_profile() and \
00175                     not self.ic.port(sensor).get_port_profile().connector_profiles :
00176                 connectPorts(self.rh.port(sensor), self.ic.port(sensor))
00177 
00178 
00179     def goOffPose(self, tm=7):
00180         '''
00181         Move arms to the predefined (as member variable) pose where robot can
00182         be safely turned off.
00183 
00184         @type tm: float
00185         @param tm: Second to complete.
00186         '''
00187         for i in range(len(self.Groups)):
00188             self.setJointAnglesOfGroup(self.Groups[i][0], self.OffPose[i], tm,
00189                                        wait=False)
00190         for i in range(len(self.Groups)):
00191             self.seq_svc.waitInterpolationOfGroup(self.Groups[i][0])
00192         self.servoOff(wait=False)
00193 
00194     def goInitial(self, tm=7, wait=True, init_pose_type=0):
00195         '''
00196         Move arms to the predefined (as member variable) "initialized" pose.
00197 
00198         @type tm: float
00199         @param tm: Second to complete.
00200         @type wait: bool
00201         @param wait: If true, SequencePlayer.waitInterpolationOfGroup gets run.
00202                      (TODO: Elaborate what this means...Even after having taken
00203                      a look at its source code I can't tell what it means.)
00204         @type init_pose_type: int
00205         @param init_pose_type: 0: default init pose (specified as _InitialPose)
00206                                1: factory init pose (specified as
00207                                   _InitialPose_Factory)
00208         '''
00209         if init_pose_type == self.INITPOS_TYPE_FACTORY:
00210             _INITPOSE = self._InitialPose_Factory
00211         else:
00212             _INITPOSE = self._InitialPose
00213 
00214         ret = True
00215         for i in range(len(self.Groups)):
00216             # radangles = [x/180.0*math.pi for x in self._InitialPose[i]]
00217             print(
00218                 '{}, JntAnglesOfGr={}, INITPOSE[i]={}, tm={}, wait={}'.format(
00219                     self.configurator_name, self.Groups[i][0], _INITPOSE[i],
00220                     tm, wait))
00221             ret &= self.setJointAnglesOfGroup(self.Groups[i][0],
00222                                               _INITPOSE[i],
00223                                               tm, wait=False)
00224         if wait:
00225             for i in range(len(self.Groups)):
00226                 self.seq_svc.waitInterpolationOfGroup(self.Groups[i][0])
00227         return ret
00228 
00229     def getRTCList(self):
00230         '''
00231         @see: HrpsysConfigurator.getRTCList
00232 
00233         @rtype [[str]]
00234         @rerutrn List of available components. Each element consists of a list
00235                  of abbreviated and full names of the component.
00236         '''
00237         rtclist = [
00238             ['seq', "SequencePlayer"],
00239             ['sh', "StateHolder"],
00240             ['fk', "ForwardKinematics"],
00241             ['ic', "ImpedanceController"],
00242             ['el', "SoftErrorLimiter"],
00243             # ['co', "CollisionDetector"],
00244             ['sc', "ServoController"],
00245             ['log', "DataLogger"],
00246             ]
00247         if hasattr(self, 'rmfo'):
00248             self.ms.load("RemoveForceSensorLinkOffset")
00249             self.ms.load("AbsoluteForceSensor")
00250             if "RemoveForceSensorLinkOffset" in self.ms.get_factory_names():
00251                 rtclist.append(['rmfo', "RemoveForceSensorLinkOffset"])
00252             elif "AbsoluteForceSensor" in self.ms.get_factory_names():
00253                 rtclist.append(['rmfo', "AbsoluteForceSensor"])
00254             else:
00255                 print "Component rmfo is not loadable."
00256         return rtclist
00257 
00258     # hand interface
00259     # effort: 1~100[%]
00260     # hiro.HandOpen("rhand", effort)
00261     # hiro.HandOpen()        # for both hand
00262     # hiro.HandClose("rhand", effort)
00263     # hiro.HandClose()       # for both hand
00264     #
00265     def HandOpen(self, hand=None, effort=None):
00266         '''
00267         Set the stretch between two fingers of the specified hand as
00268         hardcoded value (100mm), by internally calling self.setHandWidth.
00269 
00270         @type hand: str
00271         @param hand: Name of the hand joint group. In the default
00272                      setting of HIRONX, hand joint groups are defined
00273                      in member 'HandGroups' where 'lhand' and 'rhand'
00274                      are added.
00275         @type effort: int
00276         '''
00277         self.setHandWidth(hand, 100, effort=effort)
00278 
00279     def HandClose(self, hand=None, effort=None):
00280         '''
00281         Close 2-finger hand, by internally calling self.setHandWidth
00282         setting 0 width.
00283 
00284         @type hand: str
00285         @param hand: Name of the hand joint group. In the default
00286                      setting of HIRONX, hand joint groups are defined
00287                      in member 'HandGroups' where 'lhand' and 'rhand'
00288                      are added.
00289         @type effort: int
00290         '''
00291         self.setHandWidth(hand, 0, effort=effort)
00292 
00293     def setHandJointAngles(self, hand, angles, tm=1):
00294         '''
00295         @type hand: str
00296         @param hand: Name of the hand joint group. In the default
00297                      setting of HIRONX, hand joint groups are defined
00298                      in member 'HandGroups' where 'lhand' and 'rhand'
00299                      are added.
00300         @type angles: OpenHRP::ServoControllerService::dSequence.
00301         @param angles: List of (TODO: document). Elements are in degree.
00302         @param tm: Time to complete the task.
00303         '''
00304         self.sc_svc.setJointAnglesOfGroup(hand, angles, tm)
00305 
00306     def setHandEffort(self, effort=100):
00307         '''
00308         Set maximum torque for all existing hand components.
00309         @type effort: int
00310         '''
00311 
00312         for i in [v for vs in self.HandGroups.values() for v in vs]:  # flatten
00313             self.sc_svc.setMaxTorque(i, effort)
00314 
00315     def setHandWidth(self, hand, width, tm=1, effort=None):
00316         '''
00317         @type hand: str
00318         @param hand: Name of the hand joint group. In the default
00319                      setting of HIRONX, hand joint groups are defined
00320                      in member 'HandGroups' where 'lhand' and 'rhand'
00321                      are added.
00322         @param width: Max=100.
00323         @param tm: Time to complete the move.
00324         @type effort: int
00325         @param effort: Passed to self.setHandEffort if set. Not set by default.
00326         '''
00327         if effort:
00328             self.setHandEffort(effort)
00329         if hand:
00330             self.setHandJointAngles(hand, self.hand_width2angles(width), tm)
00331         else:
00332             for h in self.HandGroups.keys():
00333                 self.setHandJointAngles(h, self.hand_width2angles(width), tm)
00334 
00335     def moveHand(self, hand, av, tm=1):  # direction av: + for open, - for close
00336         '''
00337         Negate the angle value for {2, 3, 6, 7}th element in av.
00338 
00339         @type hand: str
00340         @param hand: Specifies hand. (TODO: List the possible values. Should be
00341                      listed in setHandJointAngles so just copy from its doc.)
00342         @type av: [int]
00343         @param av: angle of each joint of the specified arm
00344                   (TODO: need verified. Also what's the length of the list?)
00345         @param tm: Time in second to complete the work.
00346         '''
00347         for i in [2, 3, 6, 7]:  # do not change this line if servo is different, change HandGroups
00348             av[i] = -av[i]
00349         self.setHandJointAngles(hand, av, tm)
00350 
00351     def hand_width2angles(self, width):
00352         '''
00353         TODO: Needs documented what this method does.
00354 
00355         @type width: float
00356         @return: None if the given width is invalid.
00357         '''
00358         safetyMargin = 3
00359         l1, l2 = (41.9, 19)  # TODO: What are these variables?
00360 
00361         if width < 0.0 or width > (l1 + l2 - safetyMargin) * 2:
00362             return None
00363 
00364         xPos = width / 2.0 + safetyMargin
00365         a2Pos = xPos - l2
00366         a1radH = math.acos(a2Pos / l1)
00367         a1rad = math.pi / 2.0 - a1radH
00368 
00369         return a1rad, -a1rad, -a1rad, a1rad
00370 
00371     def setSelfGroups(self):
00372         '''
00373         Set to the hrpsys.SequencePlayer the groups of links and joints that
00374         are statically defined as member variables (Groups) within this class.
00375 
00376         That said, override Groups variable if you prefer link and joint
00377         groups set differently.
00378         '''
00379         #TODO: Accept groups variable. The name of the method sounds more
00380         #      natural if it accepts it.
00381         for item in self.Groups:
00382             self.seq_svc.addJointGroup(item[0], item[1])
00383         for k, v in self.HandGroups.iteritems():
00384             if self.sc_svc:
00385                 self.sc_svc.addJointGroup(k, v)
00386 
00387     def getActualState(self):
00388         '''
00389         Returns the physical state of robot.
00390 
00391         @rtype: <a href = "http://hrpsys-base.googlecode.com/svn/doc/df/d17/" +
00392                           "structOpenHRP_1_1RobotHardwareService_1_1" +
00393                           "RobotState.html">
00394                           OpenHRP::RobotHardwareService::RobotState</a>
00395         @return: Robot's hardware status object that contains the following
00396                  variables accessible: angle, command, torque, servoState,
00397                  force, rateGyro, accel, voltage, current. See the api doc
00398                  of the class for more detail. Each variable is accessible by
00399                  like this for example:
00400 
00401                      servostate= robot.getActualState().servoState
00402         '''
00403         #TODO: Handle AttributeError. Typically when RobotHardware is not found,
00404         #      AttributeError: 'NoneType' object has no attribute 'getStatus'
00405 
00406         return self.rh_svc.getStatus()
00407 
00408     def isCalibDone(self):
00409         '''
00410         Check whether joints have been calibrated.
00411         @rtype bool
00412         '''
00413         if self.simulation_mode:
00414             return True
00415         else:
00416             rstt = self.rh_svc.getStatus()
00417             for item in rstt.servoState:
00418                 if not item[0] & 1:
00419                     return False
00420         return True
00421 
00422     def isServoOn(self, jname='any'):
00423         '''
00424         Check whether servo control has been turned on.
00425         @type jname: str
00426         @param jname: Name of a link (that can be obtained by "hiro.Groups"
00427                       as lists of groups).
00428         @rtype bool
00429         '''
00430 
00431         if self.simulation_mode:
00432             return True
00433         else:
00434             s_s = self.getActualState().servoState
00435             if jname.lower() == 'any' or jname.lower() == 'all':
00436                 for s in s_s:
00437                     # print self.configurator_name, 's = ', s
00438                     if (s[0] & 2) == 0:
00439                         return False
00440             else:
00441                 jid = eval('self.' + jname)
00442                 print self.configurator_name, s_s[jid]
00443                 if s_s[jid][0] & 1 == 0:
00444                     return False
00445             return True
00446         return False
00447 
00448     def flat2Groups(self, flatList):
00449         '''
00450         @type flatList: [int]
00451         @param flatList: single dimension list, with its length depends on
00452                          'Groups' variable defined within this class. Excessive
00453                          elements will be dropped (see example below in @return)
00454 
00455                          eg. If the number of joints of the robot is 15,
00456                              len(flatList) should be 15.
00457         @rtype: [[]]
00458         @return: 2-dimensional list that has the same format with
00459                  'Groups' variable.
00460 
00461                  eg.
00462                  ipython> flatlist = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90,
00463                                       100, 110, 120, 130, 140, 150]
00464                  ipython> robot.flat2Groups(flatlist)
00465                  [[0], [10, 20],
00466                   [30, 40, 50, 60, 70, 80],
00467                   [90, 100, 110, 120, 130, 140]]
00468 
00469         '''
00470         retList = []
00471         index = 0
00472         for group in self.Groups:
00473             joint_num = len(group[1])
00474             retList.append(flatList[index: index + joint_num])
00475             index += joint_num
00476         return retList
00477 
00478     def servoOn(self, jname='all', destroy=1, tm=3):
00479         '''
00480         Turn on servo motors at joint specified.
00481         Joints need to be calibrated (otherwise error returns).
00482 
00483         @type jname: str
00484         @param jname: The value 'all' works iteratively for all servos.
00485         @param destroy: Not used.
00486         @type tm: float
00487         @param tm: Second to complete.
00488         @rtype: int
00489         @return: 1 or -1 indicating success or failure, respectively.
00490         '''
00491         # check joints are calibrated
00492         if not self.isCalibDone():
00493             waitInputConfirm('!! Calibrate Encoders with checkEncoders first !!\n\n')
00494             return -1
00495 
00496         # check servo state
00497         if self.isServoOn():
00498             return 1
00499 
00500         # check jname is acceptable
00501         if jname == '':
00502             jname = 'all'
00503 
00504         #self.rh_svc.power('all', SWITCH_ON)  #do not switch on before goActual
00505 
00506         try:
00507             waitInputConfirm(
00508                 '!! Robot Motion Warning (SERVO_ON) !!\n\n'
00509                 'Confirm RELAY switched ON\n'
00510                 'Push [OK] to switch servo ON(%s).' % (jname))
00511         except:  # ths needs to change
00512             self.rh_svc.power('all', SWITCH_OFF)
00513             raise
00514 
00515         # Need to reset JointGroups.
00516         # See https://code.google.com/p/rtm-ros-robotics/issues/detail?id=277
00517         try:
00518             # remove jointGroups
00519             self.seq_svc.removeJointGroup("larm")
00520             self.seq_svc.removeJointGroup("rarm")
00521             self.seq_svc.removeJointGroup("head")
00522             self.seq_svc.removeJointGroup("torso")
00523         except:
00524             print(self.configurator_name,
00525                   'Exception during servoOn while removing JoingGroup. ' +
00526                   _MSG_ASK_ISSUEREPORT)
00527         try:
00528             # setup jointGroups
00529             self.setSelfGroups()  # restart groups
00530         except:
00531             print(self.configurator_name,
00532                   'Exception during servoOn while removing setSelfGroups. ' +
00533                   _MSG_ASK_ISSUEREPORT)
00534 
00535         try:
00536             self.goActual()  # This needs to happen before turning servo on.
00537             time.sleep(0.1)
00538             self.rh_svc.servo(jname, SWITCH_ON)
00539             time.sleep(2)
00540             # time.sleep(7)
00541             if not self.isServoOn(jname):
00542                 print self.configurator_name, 'servo on failed.'
00543                 raise
00544         except:
00545             print self.configurator_name, 'exception occured'
00546 
00547         try:
00548             angles = self.flat2Groups(map(numpy.rad2deg,
00549                                           self.getActualState().angle))
00550             print 'Move to Actual State, Just a minute.'
00551             for i in range(len(self.Groups)):
00552                 self.setJointAnglesOfGroup(self.Groups[i][0], angles[i], tm,
00553                                            wait=False)
00554             for i in range(len(self.Groups)):
00555                 self.seq_svc.waitInterpolationOfGroup(self.Groups[i][0])
00556         except:
00557             print self.configurator_name, 'post servo on motion trouble'
00558 
00559         # turn on hand motors
00560         print 'Turn on Hand Servo'
00561         if self.sc_svc:
00562             self.sc_svc.servoOn()
00563 
00564         return 1
00565 
00566     def servoOff(self, jname='all', wait=True):
00567         '''
00568         @type jname: str
00569         @param jname: The value 'all' works iteratively for all servos.
00570         @type wait: bool
00571         @rtype: int
00572         @return: 1 = all arm servo off. 2 = all servo on arms and hands off.
00573                 -1 = Something wrong happened.
00574         '''
00575         # do nothing for simulation
00576         if self.simulation_mode:
00577             print self.configurator_name, 'omit servo off'
00578             return 0
00579 
00580         print 'Turn off Hand Servo'
00581         if self.sc_svc:
00582             self.sc_svc.servoOff()
00583         # if the servos aren't on switch power off
00584         if not self.isServoOn(jname):
00585             if jname.lower() == 'all':
00586                 self.rh_svc.power('all', SWITCH_OFF)
00587             return 1
00588 
00589         # if jname is not set properly set to all -> is this safe?
00590         if jname == '':
00591             jname = 'all'
00592 
00593         if wait:
00594             waitInputConfirm(
00595                 '!! Robot Motion Warning (Servo OFF)!!\n\n'
00596                 'Push [OK] to servo OFF (%s).' % (jname))  # :
00597 
00598         try:
00599             self.rh_svc.servo('all', SWITCH_OFF)
00600             time.sleep(0.2)
00601             if jname == 'all':
00602                 self.rh_svc.power('all', SWITCH_OFF)
00603 
00604             # turn off hand motors
00605             print 'Turn off Hand Servo'
00606             if self.sc_svc:
00607                 self.sc_svc.servoOff()
00608 
00609             return 2
00610         except:
00611             print self.configurator_name, 'servo off: communication error'
00612             return -1
00613 
00614     def checkEncoders(self, jname='all', option=''):
00615         '''
00616         Run the encoder checking sequence for specified joints,
00617         run goActual to adjust the direction values, and then turn servos on.
00618 
00619         @type jname: str
00620         @param jname: The value 'all' works iteratively for all servos.
00621         @type option: str
00622         @param option: Possible values are follows (w/o double quote):\
00623                         "-overwrite": Overwrite calibration value.
00624         '''
00625         if self.isServoOn():
00626             waitInputConfirm('Servo must be off for calibration')
00627             return
00628         # do not check encoders twice
00629         elif self.isCalibDone():
00630             waitInputConfirm('System has been calibrated')
00631             return
00632 
00633         self.rh_svc.power('all', SWITCH_ON)
00634         msg = '!! Robot Motion Warning !!\n'\
00635               'Turn Relay ON.\n'\
00636               'Then Push [OK] to '
00637         if option == '-overwrite':
00638             msg = msg + 'calibrate(OVERWRITE MODE) '
00639         else:
00640             msg = msg + 'check '
00641 
00642         if jname == 'all':
00643             msg = msg + 'the Encoders of all.'
00644         else:
00645             msg = msg + 'the Encoder of the Joint "' + jname + '".'
00646 
00647         try:
00648             waitInputConfirm(msg)
00649         except:
00650             print "If you're connecting to the robot from remote, " + \
00651                   "make sure tunnel X (eg. -X option with ssh)."
00652             self.rh_svc.power('all', SWITCH_OFF)
00653             return 0
00654 
00655         print self.configurator_name, 'calib-joint ' + jname + ' ' + option
00656         self.rh_svc.initializeJointAngle(jname, option)
00657         print self.configurator_name, 'done'
00658         self.rh_svc.power('all', SWITCH_OFF)
00659         self.goActual()  # This needs to happen before turning servo on.
00660         time.sleep(0.1)
00661         self.rh_svc.servo(jname, SWITCH_ON)
00662 
00663         # turn on hand motors
00664         print 'Turn on Hand Servo'
00665         if self.sc_svc:
00666             self.sc_svc.servoOn()
00667 
00668     def startImpedance_315_1(self, arm,
00669                        M_p = 100.0,
00670                        D_p = 100.0,
00671                        K_p = 100.0,
00672                        M_r = 100.0,
00673                        D_r = 2000.0,
00674                        K_r = 2000.0,
00675                        ref_force = [0, 0, 0],
00676                        force_gain = [1, 1, 1],
00677                        ref_moment = [0, 0, 0],
00678                        moment_gain = [0, 0, 0],
00679                        sr_gain = 1.0,
00680                        avoid_gain = 0.0,
00681                        reference_gain = 0.0,
00682                        manipulability_limit = 0.1):
00683         ic_sensor_name = 'rhsensor'
00684         ic_target_name = 'RARM_JOINT5'
00685         if arm == 'rarm':
00686             ic_sensor_name = 'rhsensor'
00687             ic_target_name = 'RARM_JOINT5'
00688         elif arm == 'larm':
00689             ic_sensor_name = 'lhsensor'
00690             ic_target_name = 'LARM_JOINT5'
00691         else:
00692             print 'startImpedance: argument must be rarm or larm.'
00693             return
00694 
00695         self.ic_svc.setImpedanceControllerParam(
00696             OpenHRP.ImpedanceControllerService.impedanceParam(
00697                 name = ic_sensor_name,
00698                 base_name = 'CHEST_JOINT0',
00699                 target_name = ic_target_name,
00700                 M_p = M_p,
00701                 D_p = D_p,
00702                 K_p = K_p,
00703                 M_r = M_r,
00704                 D_r = D_r,
00705                 K_r = K_r,
00706                 ref_force = ref_force,
00707                 force_gain = force_gain,
00708                 ref_moment = ref_moment,
00709                 moment_gain = moment_gain,
00710                 sr_gain = sr_gain,
00711                 avoid_gain = avoid_gain,
00712                 reference_gain = reference_gain,
00713                 manipulability_limit = manipulability_limit))
00714 
00715     def stopImpedance_315_1(self, arm):
00716         ic_sensor_name = 'rhsensor'
00717         if arm == 'rarm':
00718             ic_sensor_name = 'rhsensor'
00719         elif arm == 'larm':
00720             ic_sensor_name = 'lhsensor'
00721         else:
00722             print 'startImpedance: argument must be rarm or larm.'
00723             return
00724         self.ic_svc.deleteImpedanceControllerAndWait(ic_sensor_name)
00725 
00726     def startImpedance_315_2(self, arm,
00727                        M_p = 100.0,
00728                        D_p = 100.0,
00729                        K_p = 100.0,
00730                        M_r = 100.0,
00731                        D_r = 2000.0,
00732                        K_r = 2000.0,
00733                        force_gain = [1, 1, 1],
00734                        moment_gain = [0, 0, 0],
00735                        sr_gain = 1.0,
00736                        avoid_gain = 0.0,
00737                        reference_gain = 0.0,
00738                        manipulability_limit = 0.1):
00739         self.ic_svc.setImpedanceControllerParam(
00740             arm,
00741             OpenHRP.ImpedanceControllerService.impedanceParam(
00742                 M_p = M_p,
00743                 D_p = D_p,
00744                 K_p = K_p,
00745                 M_r = M_r,
00746                 D_r = D_r,
00747                 K_r = K_r,
00748                 force_gain = force_gain,
00749                 moment_gain = moment_gain,
00750                 sr_gain = sr_gain,
00751                 avoid_gain = avoid_gain,
00752                 reference_gain = reference_gain,
00753                 manipulability_limit = manipulability_limit))
00754         return self.ic_svc.startImpedanceController(arm)
00755 
00756     def startImpedance_315_3(self, arm,
00757                        M_p = 100.0,
00758                        D_p = 100.0,
00759                        K_p = 100.0,
00760                        M_r = 100.0,
00761                        D_r = 2000.0,
00762                        K_r = 2000.0,
00763                        force_gain = [1, 1, 1],
00764                        moment_gain = [0, 0, 0],
00765                        sr_gain = 1.0,
00766                        avoid_gain = 0.0,
00767                        reference_gain = 0.0,
00768                        manipulability_limit = 0.1):
00769         r, p = self.ic_svc.getImpedanceControllerParam(arm)
00770         if not r:
00771             print('{}, Failt to getImpedanceControllerParam({})'.format(self.configurator_name, arm))
00772             return False
00773         if M_p != None: p.M_p = M_p
00774         if D_p != None: p.M_p = D_p
00775         if K_p != None: p.M_p = K_p
00776         if M_r != None: p.M_r = M_r
00777         if D_r != None: p.M_r = D_r
00778         if K_r != None: p.M_r = K_r
00779         if force_gain != None: p.force_gain = force_gain
00780         if moment_gain != None: p.moment_gain = moment_gain
00781         if sr_gain != None: p.sr_gain = sr_gain
00782         if avoid_gain != None: p.avoid_gain = avoid_gain
00783         if reference_gain != None: p.reference_gain = reference_gain
00784         if manipulability_limit != None: p.manipulability_limit = manipulability_limit
00785         self.ic_svc.setImpedanceControllerParam(arm, p)
00786         return self.ic_svc.startImpedanceController(arm)
00787 
00788     def stopImpedance_315_2(self, arm):
00789         return self.ic_svc.stopImpedanceController(arm)
00790 
00791     def stopImpedance_315_3(self, arm):
00792         return self.ic_svc.stopImpedanceController(arm)
00793 
00794     def startImpedance(self, arm, **kwargs):
00795         if self.hrpsys_version < '315.2.0':
00796             self.startImpedance_315_1(arm, **kwargs)
00797         elif self.hrpsys_version < '315.3.0':
00798             self.startImpedance_315_2(arm, **kwargs)
00799         else:
00800             self.startImpedance_315_3(arm, **kwargs)
00801 
00802     def stopImpedance(self, arm):
00803         if self.hrpsys_version < '315.2.0':
00804             self.stopImpedance_315_1(arm)
00805         elif self.hrpsys_version < '315.3.0':
00806             self.stopImpedance_315_2(arm)
00807         else:
00808             self.stopImpedance_315_3(arm)
00809 
00810     def removeForceSensorOffset(self):
00811         self.rh_svc.removeForceSensorOffset()
00812 
00813     def getCurrentPose(self, lname=None, frame_name='WAIST'):
00814         if ':' in lname:
00815             frame_name = None
00816         
00817         if self.hrpsys_version <= '315.2.4':
00818             print "\033[33m getCurrentPose({}, {}) is not supported on {}\033[0m".format(lname, frame_name, self.hrpsys_version)
00819             return HrpsysConfigurator.getCurrentPose(self, lname)
00820         else:
00821             return HrpsysConfigurator.getCurrentPose(self, lname, frame_name)
00822     
00823     def getCurrentPosition(self, lname=None, frame_name='WAIST'):
00824         if ':' in lname:
00825             frame_name = None
00826 
00827         if self.hrpsys_version <= '315.2.4':
00828             print "\033[33m getCurrentPosition({}, {}) is not supported on {}\033[0m".format(lname, frame_name, self.hrpsys_version)
00829             return HrpsysConfigurator.getCurrentPosition(self, lname)
00830         else:
00831             return HrpsysConfigurator.getCurrentPosition(self, lname, frame_name)
00832 
00833     def getCurrentRotation(self, lname=None, frame_name='WAIST'):
00834         if ':' in lname:
00835             frame_name = None
00836         
00837         if self.hrpsys_version <= '315.2.4':
00838             print "\033[33m getCurrentRotation({}, {}) is not supported on {}\033[0m".format(lname, frame_name, self.hrpsys_version)
00839             return HrpsysConfigurator.getCurrentRotation(self, lname)
00840         else:
00841             return HrpsysConfigurator.getCurrentRotation(self, lname, frame_name)
00842     
00843     def getCurrentRPY(self, lname, frame_name='WAIST'):
00844         if ':' in lname:
00845             frame_name = None
00846 
00847         if self.hrpsys_version <= '315.2.4':
00848             print "\033[33m getCurrentRPY({}, {}) is not supported on {}\033[0m".format(lname, frame_name, self.hrpsys_version)
00849             return HrpsysConfigurator.getCurrentRPY(self, lname)
00850         else:
00851             return HrpsysConfigurator.getCurrentRPY(self, lname, frame_name)
00852 
00853     def getReferencePose(self, lname, frame_name='WAIST'):
00854         if ':' in lname:
00855             frame_name = None
00856         
00857         if self.hrpsys_version <= '315.2.4':
00858             print "\033[33m getReferencePose({}, {}) is not supported on {}\033[0m".format(lname, frame_name, self.hrpsys_version)
00859             return HrpsysConfigurator.getReferencePose(self, lname)
00860         else:
00861             return HrpsysConfigurator.getReferencePose(self, lname, frame_name)
00862 
00863     def getReferencePosition(self, lname, frame_name='WAIST'):
00864         if ':' in lname:
00865             frame_name = None
00866         
00867         if self.hrpsys_version <= '315.2.4':
00868             print "\033[33m getReferencePosition({}, {}) is not supported on {}\033[0m".format(lname, frame_name, self.hrpsys_version)
00869             return HrpsysConfigurator.getReferencePosition(self, lname)
00870         else:
00871             return HrpsysConfigurator.getReferencePosition(self, lname, frame_name)
00872 
00873     def getReferenceRotation(self, lname, frame_name='WAIST'):
00874         if ':' in lname:
00875             frame_name = None
00876         
00877         if self.hrpsys_version <= '315.2.4':
00878             print "\033[33m getReferenceRotation({}, {}) is not supported on {}\033[0m".format(lname, frame_name, self.hrpsys_version)
00879             return HrpsysConfigurator.getReferenceRotation(self, lname)
00880         else:
00881             return HrpsysConfigurator.getReferenceRotation(self, lname, frame_name)
00882 
00883     def getReferenceRPY(self, lname, frame_name='WAIST'):
00884         if ':' in lname:
00885             frame_name = None
00886         
00887         if self.hrpsys_version <= '315.2.4':
00888             print "\033[33m getReferenceRPY({}, {}) is not supported on {}\033[0m".format(lname, frame_name, self.hrpsys_version)
00889             return HrpsysConfigurator.getReferenceRPY(self, lname)
00890         else:
00891             return HrpsysConfigurator.getReferenceRPY(self, lname, frame_name)
00892     
00893     def setTargetPose(self, gname, pos, rpy, tm, frame_name='WAIST'):
00894         if self.hrpsys_version <= '315.2.4':
00895             print "\033[33m setTargetPose({}, {}, {}, {}, {}) is not supported on {}\033[0m".format(gname, pos, rpy, tm, frame_name, self.hrpsys_version)
00896             return HrpsysConfigurator.setTargetPose(self, gname, pos, rpy, tm)
00897         else:
00898             return HrpsysConfigurator.setTargetPose(self, gname, pos, rpy, tm, frame_name)
00899 


hironx_ros_bridge
Author(s): Kei Okada
autogenerated on Sun Sep 13 2015 23:21:39