9 from hrpsys
import ImpedanceControllerService_idl
10 from waitInput
import waitInputConfirm
15 from distutils.version
import StrictVersion
22 'sxyz': (0, 0, 0, 0),
'sxyx': (0, 0, 1, 0),
'sxzy': (0, 1, 0, 0),
23 'sxzx': (0, 1, 1, 0),
'syzx': (1, 0, 0, 0),
'syzy': (1, 0, 1, 0),
24 'syxz': (1, 1, 0, 0),
'syxy': (1, 1, 1, 0),
'szxy': (2, 0, 0, 0),
25 'szxz': (2, 0, 1, 0),
'szyx': (2, 1, 0, 0),
'szyz': (2, 1, 1, 0),
26 'rzyx': (0, 0, 0, 1),
'rxyx': (0, 0, 1, 1),
'ryzx': (0, 1, 0, 1),
27 'rxzx': (0, 1, 1, 1),
'rxzy': (1, 0, 0, 1),
'ryzy': (1, 0, 1, 1),
28 'rzxy': (1, 1, 0, 1),
'ryxy': (1, 1, 1, 1),
'ryxz': (2, 0, 0, 1),
29 'rzxz': (2, 0, 1, 1),
'rxyz': (2, 1, 0, 1),
'rzyz': (2, 1, 1, 1)}
32 _NEXT_AXIS = [1, 2, 0, 1]
35 _EPS = numpy.finfo(float).eps * 4.0
39 """Return homogeneous rotation matrix from Euler angles and axis sequence. 41 ai, aj, ak : Euler's roll, pitch and yaw angles 42 axes : One of 24 axis sequences as string or encoded tuple 44 >>> R = euler_matrix(1, 2, 3, 'syxz') 45 >>> numpy.allclose(numpy.sum(R[0]), -1.34786452) 47 >>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1)) 48 >>> numpy.allclose(numpy.sum(R[0]), -0.383436184) 50 >>> ai, aj, ak = (4.0*math.pi) * (numpy.random.random(3) - 0.5) 51 >>> for axes in _AXES2TUPLE.keys(): 52 ... R = euler_matrix(ai, aj, ak, axes) 53 >>> for axes in _TUPLE2AXES.keys(): 54 ... R = euler_matrix(ai, aj, ak, axes) 58 firstaxis, parity, repetition, frame = _AXES2TUPLE[axes]
59 except (AttributeError, KeyError):
61 firstaxis, parity, repetition, frame = axes
64 j = _NEXT_AXIS[i + parity]
65 k = _NEXT_AXIS[i - parity + 1]
70 ai, aj, ak = -ai, -aj, -ak
72 si, sj, sk = math.sin(ai), math.sin(aj), math.sin(ak)
73 ci, cj, ck = math.cos(ai), math.cos(aj), math.cos(ak)
74 cc, cs = ci * ck, ci * sk
75 sc, ss = si * ck, si * sk
83 M[j, j] = -cj * ss + cc
84 M[j, k] = -cj * cs - sc
86 M[k, j] = cj * sc + cs
87 M[k, k] = cj * cc - ss
90 M[i, j] = sj * sc - cs
91 M[i, k] = sj * cc + ss
93 M[j, j] = sj * ss + cc
94 M[j, k] = sj * cs - sc
102 """Return Euler angles from rotation matrix for specified axis sequence. 104 axes : One of 24 axis sequences as string or encoded tuple 106 Note that many Euler angle triplets can describe one matrix. 108 >>> R0 = euler_matrix(1, 2, 3, 'syxz') 109 >>> al, be, ga = euler_from_matrix(R0, 'syxz') 110 >>> R1 = euler_matrix(al, be, ga, 'syxz') 111 >>> numpy.allclose(R0, R1) 113 >>> angles = (4.0*math.pi) * (numpy.random.random(3) - 0.5) 114 >>> for axes in _AXES2TUPLE.keys(): 115 ... R0 = euler_matrix(axes=axes, *angles) 116 ... R1 = euler_matrix(axes=axes, *euler_from_matrix(R0, axes)) 117 ... if not numpy.allclose(R0, R1): print axes, "failed" 121 firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
122 except (AttributeError, KeyError):
123 _ = _TUPLE2AXES[axes]
124 firstaxis, parity, repetition, frame = axes
127 j = _NEXT_AXIS[i + parity]
128 k = _NEXT_AXIS[i - parity + 1]
130 M = numpy.array(matrix, dtype=numpy.float64, copy=
False)[:3, :3]
132 sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k])
134 ax = math.atan2(M[i, j], M[i, k])
135 ay = math.atan2(sy, M[i, i])
136 az = math.atan2(M[j, i], -M[k, i])
138 ax = math.atan2(-M[j, k], M[j, j])
139 ay = math.atan2(sy, M[i, i])
142 cy = math.sqrt(M[i, i] * M[i, i] + M[j, i] * M[j, i])
144 ax = math.atan2(M[k, j], M[k, k])
145 ay = math.atan2(-M[k, i], cy)
146 az = math.atan2(M[j, i], M[i, i])
148 ax = math.atan2(-M[j, k], M[j, j])
149 ay = math.atan2(-M[k, i], cy)
153 ax, ay, az = -ax, -ay, -az
249 log_use_owned_ec =
False 281 simulation_mode =
None 289 hrpsys_version =
None 292 kinematics_only_mode =
False 297 Connect components(plugins) 299 if self.
rh ==
None or self.
seq ==
None or self.
sh ==
None or self.
fk ==
None:
300 print(self.
configurator_name +
"\033[31m connectComps : hrpsys requries rh, seq, sh and fk, please check rtcd.conf or rtcd arguments\033[0m")
304 if len(tmp_controllers) > 0:
305 connectPorts(self.sh.port(
"qOut"), tmp_controllers[0].port(
"qRef"))
306 for i
in range(len(tmp_controllers) - 1):
308 tmp_controllers[i + 1].port(
"qRef"))
311 connectPorts(tmp_controllers[-1].port(
"q"), self.pdc.port(
"angleRef"))
313 connectPorts(tmp_controllers[-1].port(
"q"), self.hgc.port(
"qIn"))
314 connectPorts(self.hgc.port(
"qOut"), self.rh.port(
"qRef"))
316 connectPorts(tmp_controllers[-1].port(
"q"), self.rh.port(
"qRef"))
320 connectPorts(self.sh.port(
"qOut"), self.pdc.port(
"angleRef"))
322 connectPorts(self.sh.port(
"qOut"), self.hgc.port(
"qIn"))
323 connectPorts(self.hgc.port(
"qOut"), self.rh.port(
"qRef"))
325 connectPorts(self.sh.port(
"qOut"), self.rh.port(
"qRef"))
331 connectPorts(self.abc.port(
"basePoseOut"), self.rh.port(
"basePoseRef"))
333 connectPorts(self.sh.port(
"basePoseOut"), self.rh.port(
"basePoseRef"))
338 s_acc = filter(
lambda s: s.type ==
'Acceleration', self.
sensors)
339 if (len(s_acc) > 0)
and self.rh.port(s_acc[0].name) !=
None:
340 connectPorts(self.rh.port(s_acc[0].name), self.kf.port(
'acc'))
341 s_rate = filter(
lambda s: s.type ==
'RateGyro', self.
sensors)
342 if (len(s_rate) > 0)
and self.rh.port(s_rate[0].name) !=
None:
343 connectPorts(self.rh.port(s_rate[0].name), self.kf.port(
"rate"))
344 connectPorts(self.rh.port(
"q"), self.kf.port(
"qCurrent"))
347 if self.rh.port(
"servoState") !=
None:
348 if self.
te and self.
el:
350 self.te.port(
"servoStateIn"))
352 self.el.port(
"servoStateIn"))
355 self.el.port(
"servoStateIn"))
358 self.te.port(
"servoStateIn"))
361 connectPorts(self.rh.port(
"q"), [self.sh.port(
"currentQIn"),
363 connectPorts(self.sh.port(
"qOut"), self.fk.port(
"qRef"))
364 connectPorts(self.seq.port(
"qRef"), self.sh.port(
"qIn"))
365 connectPorts(self.seq.port(
"tqRef"), self.sh.port(
"tqIn"))
366 connectPorts(self.seq.port(
"basePos"), self.sh.port(
"basePosIn"))
367 connectPorts(self.seq.port(
"baseRpy"), self.sh.port(
"baseRpyIn"))
368 connectPorts(self.seq.port(
"zmpRef"), self.sh.port(
"zmpIn"))
369 if StrictVersion(self.
seq_version) >= StrictVersion(
'315.2.6'):
370 connectPorts(self.seq.port(
"optionalData"), self.sh.port(
"optionalDataIn"))
371 connectPorts(self.sh.port(
"basePosOut"), [self.seq.port(
"basePosInit"),
372 self.fk.port(
"basePosRef")])
373 connectPorts(self.sh.port(
"baseRpyOut"), [self.seq.port(
"baseRpyInit"),
374 self.fk.port(
"baseRpyRef")])
375 connectPorts(self.sh.port(
"qOut"), self.seq.port(
"qInit"))
376 if StrictVersion(self.
seq_version) >= StrictVersion(
'315.2.0'):
377 connectPorts(self.sh.port(
"zmpOut"), self.seq.port(
"zmpRefInit"))
380 self.sh.port(sen +
"In"))
384 self.rh.ref,
"rfsensor")
and self.
st:
386 connectPorts(self.sh.port(
"zmpOut"), self.abc.port(
"zmpIn"))
387 connectPorts(self.sh.port(
"basePosOut"), self.abc.port(
"basePosIn"))
388 connectPorts(self.sh.port(
"baseRpyOut"), self.abc.port(
"baseRpyIn"))
389 connectPorts(self.sh.port(
"optionalDataOut"), self.abc.port(
"optionalData"))
390 connectPorts(self.abc.port(
"zmpOut"), self.st.port(
"zmpRef"))
391 connectPorts(self.abc.port(
"baseRpyOut"), self.st.port(
"baseRpyIn"))
392 connectPorts(self.abc.port(
"basePosOut"), self.st.port(
"basePosIn"))
393 connectPorts(self.abc.port(
"accRef"), self.kf.port(
"accRef"))
394 connectPorts(self.abc.port(
"contactStates"), self.st.port(
"contactStates"))
395 connectPorts(self.abc.port(
"controlSwingSupportTime"), self.st.port(
"controlSwingSupportTime"))
396 connectPorts(self.rh.port(
"q"), self.st.port(
"qCurrent"))
397 connectPorts(self.seq.port(
"qRef"), self.st.port(
"qRefSeq"))
398 connectPorts(self.abc.port(
"walkingStates"), self.st.port(
"walkingStates"))
399 connectPorts(self.abc.port(
"sbpCogOffset"), self.st.port(
"sbpCogOffset"))
400 connectPorts(self.abc.port(
"toeheelRatio"), self.st.port(
"toeheelRatio"))
402 connectPorts(self.st.port(
"emergencySignal"), self.es.port(
"emergencySignal"))
403 connectPorts(self.st.port(
"emergencySignal"), self.abc.port(
"emergencySignal"))
404 connectPorts(self.st.port(
"diffCapturePoint"), self.abc.port(
"diffCapturePoint"))
405 connectPorts(self.st.port(
"actContactStates"), self.abc.port(
"actContactStates"))
407 connectPorts(self.st.port(
"diffFootOriginExtMoment"), self.rfu.port(
"diffFootOriginExtMoment"))
408 connectPorts(self.rfu.port(
"refFootOriginExtMoment"), self.abc.port(
"refFootOriginExtMoment"))
409 connectPorts(self.rfu.port(
"refFootOriginExtMomentIsHoldValue"), self.abc.port(
"refFootOriginExtMomentIsHoldValue"))
411 connectPorts(self.abc.port(
"contactStates"), self.octd.port(
"contactStates"))
415 if self.
abc and self.
st:
417 self.st.port(sen +
"Ref"))
419 self.st.port(
"limbCOPOffset_"+sen))
421 ref_force_port_from = self.rfu.port(
"ref_"+sen+
"Out")
423 ref_force_port_from = self.es.port(sen+
"Out")
425 ref_force_port_from = self.sh.port(sen+
"Out")
428 self.ic.port(
"ref_" + sen+
"In"))
431 self.abc.port(
"ref_" + sen))
434 self.es.port(sen+
"In"))
437 self.rfu.port(
"ref_" + sen+
"In"))
441 self.rfu.port(
"ref_" + sen+
"In"))
447 connectPorts(self.kf.port(
"rpy"), self.rmfo.port(
"rpy"))
448 connectPorts(self.rh.port(
"q"), self.rmfo.port(
"qCurrent"))
449 for sen
in filter(
lambda x: x.type ==
"Force", self.
sensors):
450 connectPorts(self.rh.port(sen.name), self.rmfo.port(sen.name))
453 self.ic.port(sen.name))
456 self.rfu.port(sen.name))
459 self.st.port(sen.name))
461 for sen
in filter(
lambda x: x.type ==
"Force", self.
sensors):
463 self.ic.port(sen.name))
467 connectPorts(self.rh.port(
"q"), self.ic.port(
"qCurrent"))
468 if StrictVersion(self.
seq_version) >= StrictVersion(
'315.3.0'):
469 connectPorts(self.sh.port(
"basePosOut"), self.ic.port(
"basePosIn"))
470 connectPorts(self.sh.port(
"baseRpyOut"), self.ic.port(
"baseRpyIn"))
475 if StrictVersion(self.
seq_version) >= StrictVersion(
'315.3.0'):
476 connectPorts(self.sh.port(
"basePosOut"), self.rfu.port(
"basePosIn"))
477 connectPorts(self.sh.port(
"baseRpyOut"), self.rfu.port(
"baseRpyIn"))
482 connectPorts(self.rh.port(
"tau"), self.tf.port(
"tauIn"))
483 connectPorts(self.rh.port(
"q"), self.tf.port(
"qCurrent"))
486 connectPorts(self.rh.port(
"q"), self.vs.port(
"qCurrent"))
487 connectPorts(self.tf.port(
"tauOut"), self.vs.port(
"tauIn"))
490 for vfp
in filter(
lambda x: str.find(x,
'v') >= 0
and 491 str.find(x,
'sensor') >= 0, self.vs.ports.keys()):
495 connectPorts(self.rh.port(
"q"), self.co.port(
"qCurrent"))
496 connectPorts(self.rh.port(
"servoState"), self.co.port(
"servoStateIn"))
499 connectPorts(self.rh.port(
"q"), self.octd.port(
"qCurrent"))
501 connectPorts(self.kf.port(
"rpy"), self.octd.port(
"rpy"))
503 for sen
in filter(
lambda x: x.type ==
"Force", self.
sensors):
504 connectPorts(self.rmfo.port(
"off_" + sen.name), self.octd.port(sen.name))
508 connectPorts(self.rh.port(
"q"), self.gc.port(
"qCurrent"))
510 index = tmp_controller.index(self.
gc)
519 connectPorts(self.rh.port(
"q"), self.te.port(
"qCurrentIn"))
520 connectPorts(self.sh.port(
"qOut"), self.te.port(
"qRefIn"))
522 connectPorts(self.tf.port(
"tauOut"), self.te.port(
"tauIn"))
524 connectPorts(self.rh.port(
"tau"), self.te.port(
"tauIn"))
530 connectPorts(self.te.port(
"tempOut"), self.tl.port(
"tempIn"))
534 connectPorts(self.rh.port(
"q"), self.tc.port(
"qCurrent"))
537 self.tc.port(
"tauCurrent"))
539 connectPorts(self.rh.port(
"tau"), self.tc.port(
"tauCurrent"))
541 connectPorts(self.tl.port(
"tauMax"), self.tc.port(
"tauMax"))
545 connectPorts(self.rh.port(
"q"), self.el.port(
"qCurrent"))
549 connectPorts(self.rh.port(
"servoState"), self.es.port(
"servoStateIn"))
554 connectPorts(self.tl.port(
"beepCommand"), self.bp.port(
"beepCommand"))
556 connectPorts(self.es.port(
"beepCommand"), self.bp.port(
"beepCommand"))
558 connectPorts(self.el.port(
"beepCommand"), self.bp.port(
"beepCommand"))
560 connectPorts(self.co.port(
"beepCommand"), self.bp.port(
"beepCommand"))
565 s_acc = filter(
lambda s: s.type ==
'Acceleration', self.
sensors)
566 if (len(s_acc) > 0)
and self.rh.port(s_acc[0].name) !=
None:
567 connectPorts(self.rh.port(s_acc[0].name), self.acf.port(
'accIn'))
568 s_rate = filter(
lambda s: s.type ==
'RateGyro', self.
sensors)
569 if (len(s_rate) > 0)
and self.rh.port(s_rate[0].name) !=
None:
570 connectPorts(self.rh.port(s_rate[0].name), self.acf.port(
"rateIn"))
572 connectPorts(self.kf.port(
"rpy"), self.acf.port(
"rpyIn"))
574 connectPorts(self.abc.port(
"basePosOut"), self.acf.port(
"posIn"))
578 Activate components(plugins) 587 Deactivate components(plugins) 590 for r
in reversed(rtcList):
595 Create RTC component (plugins) 597 @param instanceName str: name of instance, choose one of https://github.com/fkanehiro/hrpsys-base/tree/master/rtc 598 @param comName str: name of component that to be created. 600 self.ms.load(compName)
601 comp = self.ms.create(compName, instanceName)
602 version = comp.ref.get_component_profile().version
603 print(self.
configurator_name +
"create Comp -> %s : %s (%s)" % (compName, comp, version))
605 raise RuntimeError(
"Cannot create component: " + compName)
606 if comp.service(
"service0"):
607 comp_svc =
narrow(comp.service(
"service0"), compName +
"Service")
608 print(self.
configurator_name +
"create CompSvc -> %s Service : %s" % (compName, comp_svc))
609 return [comp, comp_svc, version]
611 return [comp,
None, version]
615 Create components(plugins) in getRTCList() 619 rn2 =
'self.' + rn[0]
620 if eval(rn2) ==
None:
621 create_str =
"[self." + rn[0] +
", self." + rn[0] +
"_svc, self." + rn[0] +
"_version] = self.createComp(\"" + rn[1] +
"\",\"" + rn[0] +
"\")" 625 _, e, _ = sys.exc_info()
626 print(self.
configurator_name +
'\033[31mFail to createComps ' + str(e) +
'\033[0m')
631 Delete RTC component (plugins) 633 @param compName str: name of component that to be deleted 638 return self.ms.delete(compName)
642 Delete components(plugins) in getRTCInstanceList() 648 rtcList.remove(self.
rh)
649 for r
in reversed(rtcList):
651 print(self.
configurator_name,
'\033[31m ' + r.name() +
' is staill active\033[0m')
654 _, e, _ = sys.exc_info()
655 print(self.
configurator_name +
'\033[31mFail to deleteComps' + str(e) +
'\033[0m')
657 def findComp(self, compName, instanceName, max_timeout_count=10, verbose=True):
659 Find component(plugin) 661 @param compName str: component name 662 @param instanceName str: instance name 663 @max_timeout_count int: max timeout in seconds 668 while comp ==
None and timeout_count < max_timeout_count:
676 if comp
and comp.ref:
677 version = comp.ref.get_component_profile().version
679 print(self.
configurator_name +
" find Comp : %s = %s (%s)" % (instanceName, comp, version))
682 print(self.
configurator_name +
" Cannot find component: %s (%s)" % (instanceName, compName))
683 return [
None,
None,
None]
684 comp_svc_port = comp.service(
"service0")
686 comp_svc =
narrow(comp_svc_port, compName +
"Service")
688 print(self.
configurator_name +
" find CompSvc : %s_svc = %s"%(instanceName, comp_svc))
689 return [comp, comp_svc, version]
691 return [comp,
None, version]
693 def findComps(self, max_timeout_count = 10, verbose=True):
695 Check if all components in getRTCList() are created 698 rn2 =
'self.' + rn[0]
699 if eval(rn2) ==
None:
700 create_str =
"[self." + rn[0] +
", self." + rn[0] +
"_svc, self." + rn[0] +
"_version] = self.findComp(\"" + rn[1] +
"\",\"" + rn[0] +
"\"," + str(max_timeout_count) +
"," + str(verbose) +
")" 704 if eval(rn2) ==
None:
705 max_timeout_count = 0
710 Get list of available STABLE components 711 @return list of list: List of available components. Each element consists of a list 712 of abbreviated and full names of the component. 715 [
'seq',
"SequencePlayer"],
716 [
'sh',
"StateHolder"],
717 [
'fk',
"ForwardKinematics"],
725 [
'co',
"CollisionDetector"],
729 [
'el',
"SoftErrorLimiter"],
730 [
'log',
"DataLogger"]
736 Get list of available components including stable and unstable. 738 @return list of list: List of available unstable components. Each element consists 739 of a list of abbreviated and full names of the component. 742 [
'seq',
"SequencePlayer"],
743 [
'sh',
"StateHolder"],
744 [
'fk',
"ForwardKinematics"],
745 [
'tf',
"TorqueFilter"],
746 [
'kf',
"KalmanFilter"],
747 [
'vs',
"VirtualForceSensor"],
748 [
'rmfo',
"RemoveForceSensorLinkOffset"],
749 [
'octd',
"ObjectContactTurnaroundDetector"],
750 [
'es',
"EmergencyStopper"],
751 [
'rfu',
"ReferenceForceUpdater"],
752 [
'ic',
"ImpedanceController"],
753 [
'abc',
"AutoBalancer"],
754 [
'st',
"Stabilizer"],
755 [
'co',
"CollisionDetector"],
756 [
'tc',
"TorqueController"],
757 [
'te',
"ThermoEstimator"],
758 [
'hes',
"EmergencyStopper"],
759 [
'el',
"SoftErrorLimiter"],
760 [
'tl',
"ThermoLimiter"],
762 [
'acf',
"AccelerationFilter"],
763 [
'log',
"DataLogger"]
768 Get list of controller list that need to control joint angles 770 controller_list = [self.
es, self.
ic, self.
gc, self.
abc, self.
st, self.
co,
772 return filter(
lambda c: c !=
None, controller_list)
776 Get list of RTC Instance 786 print(self.
configurator_name +
'\033[31mFail to find instance ('+str(rtc)+
') for getRTCInstanceList\033[0m')
788 _, e, _ = sys.exc_info()
789 print(self.
configurator_name +
'\033[31mFail to getRTCInstanceList'+str(e)+
'\033[0m')
796 if '$(PROJECT_DIR)' in url:
797 path = subprocess.Popen([
'pkg-config',
'openhrp3.1',
'--variable=prefix'], stdout=subprocess.PIPE).communicate()[0].rstrip()
798 path = os.path.join(path,
'share/OpenHRP-3.1/sample/project')
799 url = url.replace(
'$(PROJECT_DIR)', path)
808 obj = rtm.rootnc.resolve([CosNaming.NameComponent(
'ModelLoader',
'')])
809 mdlldr = obj._narrow(ModelLoader_idl._0_OpenHRP__POA.ModelLoader)
812 return mdlldr.getBodyInfo(
"file://" + url)
819 @param url str: model file url 824 return sum(
map(
lambda x: x.sensors,
825 filter(
lambda x: len(x.sensors) > 0,
831 Get list of force sensor names. Returns existence force sensors and virtual force sensors. self.sensors and virtual force sensors are assumed. 833 ret = map (
lambda x : x.name, filter(
lambda x: x.type ==
"Force", self.
sensors))
835 ret += filter(
lambda x: str.find(x,
'v') >= 0
and str.find(x,
'sensor') >= 0, self.vs.ports.keys())
840 Connect port to logger 842 @param artc object: object of component that contains sen_name port 843 @param sen_name str: name of port for logging 844 @param log_name str: name of port in logger 846 log_name = log_name
if log_name
else artc.name() +
"_" + sen_name
850 print(self.
configurator_name +
" setupLogger : record type = %s, name = %s to %s" % ( sen_type, sen_name, log_name))
851 self.log_svc.add(sen_type, log_name)
853 print(self.
configurator_name +
" setupLogger : %s arleady exists in DataLogger"% sen_name)
854 connectPorts(artc.port(sen_name), self.log.port(log_name))
859 Setup logging function. 860 @param maxLength : max length of data from DataLogger.h #define DEFAULT_MAX_LOG_LENGTH (200*20) 861 if the robot running at 200hz (5msec) 4000 means 20 secs 864 print(self.
configurator_name +
"\033[31m setupLogger : self.log is not defined, please check rtcd.conf or rtcd arguments\033[0m")
866 self.log_svc.maxLength(maxLength);
868 for pn
in [
'q',
'dq',
'tau']:
916 for sen
in filter(
lambda x: x.type ==
"Force", self.
sensors):
918 if self.
rmfo !=
None:
919 for sen
in filter(
lambda x: x.type ==
"Force", self.
sensors):
922 for sen
in filter(
lambda x: x.type ==
"Force", self.
sensors):
924 if self.
octd !=
None:
928 if self.
log and (self.
log_use_owned_ec or not isinstance(self.log.owned_ecs[0], OpenRTM._objref_ExtTrigExecutionContextService)):
929 print(self.
configurator_name +
"\033[32mruning DataLogger with own Execution Context\033[0m")
930 self.log.owned_ecs[0].start()
931 self.log.start(self.log.owned_ecs[0])
935 Wait for RTC manager. 937 @param managerhost str: name of host computer that manager is running 940 while self.
ms ==
None:
942 if managerhost ==
"localhost":
943 managerhost = socket.gethostname()
949 Wait for RobotHardware is exists and activated. 951 @param robotname str: name of RobotHardware component. 956 while self.
rh ==
None and timeout_count < 10:
957 if timeout_count > 0:
962 print(self.
configurator_name +
"wait for %s : %s ( timeout %d < 10)" % ( robotname, self.
rh, timeout_count))
963 if self.
rh and self.rh.isActive() ==
None:
969 print(self.
configurator_name +
"Candidates are .... " + str([x.name()
for x
in self.ms.get_components()]))
973 print(self.
configurator_name +
"findComps -> %s : %s isActive? = %s " % (self.rh.name(), self.
rh, self.rh.isActive()))
977 Check if this is running as simulation 989 self.
rh_svc =
narrow(self.rh.service(
"service0"),
"RobotHardwareService")
990 self.
ep_svc =
narrow(self.rh.ec,
"ExecutionProfileService")
995 print(
"\033[93m%s waitForRTCManagerAndRoboHardware has renamed to " % self.
configurator_name + \
996 "waitForRTCManagerAndRoboHardware: Please update your code\033[0m")
1001 Wait for both RTC Manager (waitForRTCManager()) and RobotHardware (waitForRobotHardware()) 1003 @param managerhost str: name of host computer that manager is running 1004 @param robotname str: name of RobotHardware component. 1012 Try to find ModelLoader 1021 Wait for ModelLoader. 1029 Set to the hrpsys.SequencePlayer the groups of links and joints that 1030 are statically defined as member variables (Groups) within this class. 1033 self.seq_svc.addJointGroup(item[0], item[1])
1040 Adjust commanded values to the angles in the physical state 1041 by calling StateHolder::goActual. 1043 This needs to be run BEFORE servos are turned on. 1045 self.sh_svc.goActual()
1049 Set angle to the given joint. 1051 NOTE-1: It's known that this method does not do anything after 1052 some group operation is done. 1053 TODO: at least need to warn users. 1054 NOTE-2: While this method does not check angle value range, 1055 any joints could emit position limit over error, which has not yet 1056 been thrown by hrpsys so that there's no way to catch on this python client. 1057 Worthwhile opening an enhancement ticket at designated issue tracker. 1060 @param jname str: name of joint 1061 @param angle float: In degree. 1062 @param tm float: Time to complete. 1064 @return False upon any problem during execution. 1066 radangle = angle / 180.0 * math.pi
1067 return self.seq_svc.setJointAngle(jname, radangle, tm)
1071 Set all joint angles. 1073 NOTE: While this method does not check angle value range, 1074 any joints could emit position limit over error, which has not yet 1075 been thrown by hrpsys so that there's no way to catch on this python client. 1076 Worthwhile opening an enhancement ticket at designated issue tracker. 1078 @param angles list of float: In degree. 1079 @param tm float: Time to complete. 1081 @return False upon any problem during execution. 1084 for angle
in angles:
1085 ret.append(angle / 180.0 * math.pi)
1086 return self.seq_svc.setJointAngles(ret, tm)
1090 Set the joint angles to aim. By default it waits interpolation to be 1094 NOTE: While this method does not check angle value range, 1095 any joints could emit position limit over error, which has not yet 1096 been thrown by hrpsys so that there's no way to catch on this python client. 1097 Worthwhile opening an enhancement ticket at designated issue tracker. 1100 @param gname str: Name of the joint group. 1101 @param pose list of float: list of positions and orientations 1102 @param tm float: Time to complete. 1103 @param wait bool: If true, all other subsequent commands wait until 1104 the movement commanded by this method call finishes. 1106 @return False upon any problem during execution. 1108 angles = [x / 180.0 * math.pi
for x
in pose]
1109 ret = self.seq_svc.setJointAnglesOfGroup(gname, angles, tm)
1116 Set all joint angles. len(angless) should be equal to len(tms). 1118 NOTE: While this method does not check angle value range, 1119 any joints could emit position limit over error, which has not yet 1120 been thrown by hrpsys so that there's no way to catch on this python client. 1121 Worthwhile opening an enhancement ticket at designated issue tracker. 1123 @param sequential list of angles in float: In rad 1124 @param tm sequential list of time in float: Time to complete, In Second 1126 @return False upon any problem during execution. 1128 for angles
in angless:
1129 for i
in range(len(angles)):
1130 angles[i] = angles[i] / 180.0 * math.pi
1131 return self.seq_svc.setJointAnglesSequence(angless, tms)
1135 Set all joint angles. 1137 NOTE: While this method does not check angle value range, 1138 any joints could emit position limit over error, which has not yet 1139 been thrown by hrpsys so that there's no way to catch on this python client. 1140 Worthwhile opening an enhancement ticket at designated issue tracker. 1142 @param gname str: Name of the joint group. 1143 @param sequential list of angles in float: In rad 1144 @param tm sequential list of time in float: Time to complete, In Second 1146 @return False upon any problem during execution. 1148 for angles
in angless:
1149 for i
in range(len(angles)):
1150 angles[i] = angles[i] / 180.0 * math.pi
1151 return self.seq_svc.setJointAnglesSequenceOfGroup(gname, angless, tms)
1155 Load a pattern file that is created offline. 1157 Format of the pattern file: 1165 - Delimmitted by space 1166 - Each line consists of an action. 1167 - Time between each action is defined by tn+1 - tn 1168 - The time taken for the 1st line is defined by the arg tm. 1170 @param fname str: Name of the pattern file. 1171 @param tm float: - The time to take for the 1st line. 1172 @return: List of 2 oct(string) values. 1175 return self.seq_svc.loadPattern(fname, tm)
1179 Lets SequencePlayer wait until the movement currently happening to 1182 self.seq_svc.waitInterpolation()
1186 Lets SequencePlayer wait until the movement currently happening to 1189 @see: SequencePlayer.waitInterpolationOfGroup 1190 @see: http://wiki.ros.org/joint_trajectory_action. This method 1191 corresponds to JointTrajectoryGoal in ROS. 1193 @param gname str: Name of the joint group. 1195 self.seq_svc.waitInterpolationOfGroup(gname)
1199 Set interpolation mode. You may need to import OpenHRP in order to pass an argument. For more info See https://github.com/fkanehiro/hrpsys-base/pull/1012#issue-160802911. 1200 @param mode new interpolation mode. Either { OpenHRP.SequencePlayerService.LINEAR, OpenHRP.SequencePlayerService.HOFFARBIB }. 1201 @return true if set successfully, false otherwise 1203 return self.seq_svc.setInterpolationMode(mode)
1207 Returns the commanded joint angle values. 1209 @see: HrpsysConfigurator.getJointAngles 1211 Note that it's not the physical state of the robot's joints, which 1212 can be obtained by getActualState().angle. 1214 @return List of float: List of angles (degree) of all joints, in the order defined 1215 in the member variable 'Groups' (eg. chest, head1, head2, ..). 1217 return [x * 180.0 / math.pi
for x
in self.sh_svc.getCommand().jointRefs]
1221 Returns the current physical pose of the specified joint in the joint space. 1222 cf. getReferencePose that returns commanded value. 1226 IN: robot.getCurrentPose('LARM_JOINT5') 1227 OUT: [-0.0017702356144599085, 1228 0.00019034630541264752, 1229 -0.9999984150158207, 1230 0.32556275164378523, 1231 0.00012155879975329215, 1233 0.0001901314142046251, 1234 0.18236394191140365, 1236 -0.00012122202968358842, 1237 -0.001770258707652326, 1238 0.07462472659364472, 1246 @param lname: Name of the link. 1247 @param frame_name str: set reference frame name (from 315.2.5) 1248 @rtype: list of float 1249 @return: Rotational matrix and the position of the given joint in 1250 1-dimensional list, that is: 1260 eef_name = item[1][-1]
1262 raise RuntimeError(
"need to specify joint name")
1264 lname = lname +
':' + frame_name
1265 if StrictVersion(self.
fk_version) < StrictVersion(
'315.2.5')
and ':' in lname:
1266 raise RuntimeError(
'frame_name ('+lname+
') is not supported')
1267 pose = self.fk_svc.getCurrentPose(lname)
1269 raise RuntimeError(
"Could not find reference : " + lname)
1274 Returns the current physical position of the specified joint in Cartesian space. 1275 cf. getReferencePosition that returns commanded value. 1279 robot.getCurrentPosition('LARM_JOINT5') 1280 [0.325, 0.182, 0.074] 1284 @param lname: Name of the link. 1285 @param frame_name str: set reference frame name (from 315.2.5) 1286 @rtype: list of float 1287 @return: List of x, y, z positions about the specified joint. 1291 eef_name = item[1][-1]
1293 raise RuntimeError(
"need to specify joint name")
1295 return [pose[3], pose[7], pose[11]]
1299 Returns the current physical rotation of the specified joint. 1300 cf. getReferenceRotation that returns commanded value. 1303 @param lname: Name of the link. 1304 @param frame_name str: set reference frame name (from 315.2.5) 1305 @rtype: list of float 1306 @return: Rotational matrix of the given joint in 2-dimensional list, 1316 eef_name = item[1][-1]
1318 raise RuntimeError(
"need to specify joint name")
1320 return [pose[0:3], pose[4:7], pose[8:11]]
1324 Returns the current physical rotation in RPY of the specified joint. 1325 cf. getReferenceRPY that returns commanded value. 1328 @param lname: Name of the link. 1329 @param frame_name str: set reference frame name (from 315.2.5) 1330 @rtype: list of float 1331 @return: List of orientation in rpy form about the specified joint. 1335 eef_name = item[1][-1]
1336 print(
"{}: {}".format(eef_name, self.
getCurrentRPY(eef_name)))
1337 raise RuntimeError(
"need to specify joint name")
1342 Returns the current commanded pose of the specified joint in the joint space. 1343 cf. getCurrentPose that returns physical pose. 1346 @param lname: Name of the link. 1347 @param frame_name str: set reference frame name (from 315.2.5) 1348 @rtype: list of float 1349 @return: Rotational matrix and the position of the given joint in 1350 1-dimensional list, that is: 1360 eef_name = item[1][-1]
1362 raise RuntimeError(
"need to specify joint name")
1364 lname = lname +
':' + frame_name
1365 if StrictVersion(self.
fk_version) < StrictVersion(
'315.2.5')
and ':' in lname:
1366 raise RuntimeError(
'frame_name ('+lname+
') is not supported')
1367 pose = self.fk_svc.getReferencePose(lname)
1369 raise RuntimeError(
"Could not find reference : " + lname)
1374 Returns the current commanded position of the specified joint in Cartesian space. 1375 cf. getCurrentPosition that returns physical value. 1378 @param lname: Name of the link. 1379 @param frame_name str: set reference frame name (from 315.2.5) 1380 @rtype: list of float 1381 @return: List of angles (degree) of all joints, in the order defined 1382 in the member variable 'Groups' (eg. chest, head1, head2, ..). 1386 eef_name = item[1][-1]
1388 raise RuntimeError(
"need to specify joint name")
1390 return [pose[3], pose[7], pose[11]]
1394 Returns the current commanded rotation of the specified joint. 1395 cf. getCurrentRotation that returns physical value. 1398 @param lname: Name of the link. 1399 @param frame_name str: set reference frame name (from 315.2.5) 1400 @rtype: list of float 1401 @return: Rotational matrix of the given joint in 2-dimensional list, 1411 eef_name = item[1][-1]
1412 print(
"{}: {}".format(eef_name, self.getReferencePotation(eef_name)))
1413 raise RuntimeError(
"need to specify joint name")
1415 return [pose[0:3], pose[4:7], pose[8:11]]
1419 Returns the current commanded rotation in RPY of the specified joint. 1420 cf. getCurrentRPY that returns physical value. 1423 @param lname: Name of the link. 1424 @param frame_name str: set reference frame name (from 315.2.5) 1425 @rtype: list of float 1426 @return: List of orientation in rpy form about the specified joint. 1430 eef_name = item[1][-1]
1432 raise RuntimeError(
"need to specify joint name")
1437 Move the end-effector to the given absolute pose. 1438 All d* arguments are in meter. 1440 @param gname str: Name of the joint group. 1441 @param pos list of float: In meter. 1442 @param rpy list of float: In radian. 1443 @param tm float: Second to complete the command. This only includes the time taken for execution 1444 (i.e. time for planning and other misc. processes are not considered). 1445 @param frame_name str: Name of the frame that this particular command 1447 @return bool: False if unreachable. 1449 print(gname, frame_name, pos, rpy, tm)
1451 gname = gname +
':' + frame_name
1452 result = self.seq_svc.setTargetPose(gname, pos, rpy, tm)
1454 print(
"setTargetPose failed. Maybe SequencePlayer failed to solve IK.\n" 1455 +
"Currently, returning IK result error\n" 1456 +
"(like the one in https://github.com/start-jsk/rtmros_hironx/issues/103)" 1457 +
" is not implemented. Patch is welcomed.")
1461 dr=0, dp=0, dw=0, tm=10, wait=
True):
1463 Move the end-effector's location relative to its current pose. 1465 Note that because of "relative" nature, the method waits for the commands 1466 run previously to finish. Do not get confused with the "wait" argument, 1467 which regulates all subsequent commands, not previous ones. 1469 For d*, distance arguments are in meter while rotations are in degree. 1471 Example usage: The following moves RARM_JOINT5 joint 0.1mm forward 1474 robot.setTargetPoseRelative('rarm', 'RARM_JOINT5', dx=0.0001, tm=0.1) 1476 @param gname str: Name of the joint group that is to be manipulated. 1477 @param eename str: Name of the joint that the manipulated joint group references to. 1478 @param dx float: In meter. 1479 @param dy float: In meter. 1480 @param dz float: In meter. 1481 @param dr float: In radian. 1482 @param dp float: In radian. 1483 @param dw float: In radian. 1484 @param tm float: Second to complete the command. This only includes the time taken for execution 1485 (i.e. time for planning and other misc. processes are not considered). 1486 @param wait bool: If true, all other subsequent commands wait until 1487 the movement commanded by this method call finishes. 1488 @return bool: False if unreachable. 1496 posRef = numpy.array([tds[3], tds[7], tds[11]])
1497 matRef = numpy.array([tds[0:3], tds[4:7], tds[8:11]])
1498 posRef += [dx, dy, dz]
1499 matRef = matRef.dot(numpy.array(
euler_matrix(dr, dp, dw)[:3, :3]))
1501 print(posRef, rpyRef)
1502 ret = self.
setTargetPose(gname, list(posRef), list(rpyRef), tm)
1510 Clears the Sequencer's current operation. Works for joint groups too. 1511 @see HrpsysConfigurator.clear 1513 Discussed in https://github.com/fkanehiro/hrpsys-base/issues/158 1514 Examples is found in a unit test: https://github.com/start-jsk/rtmros_hironx/blob/bb0672be3e03e5366e03fe50520e215302b8419f/hironx_ros_bridge/test/test_hironx.py#L293 1516 self.seq_svc.clear()
1520 Clears the Sequencer's current operation for joint groups. 1522 self.seq_svc.clearOfGroup(gname, tm)
1526 Save log to the given file name 1528 @param fname str: name of the file 1530 self.log_svc.save(fname)
1535 Clear logger's buffer 1537 self.log_svc.clear()
1542 @param length int: length of log, if the system runs at 500hz and you want to store 2min, set 2*60*500. 1544 self.log_svc.maxLength(length)
1548 Returns the length of digital input port 1550 return self.rh_svc.lengthDigitalInput()
1554 Returns the length of digital output port 1556 return self.rh_svc.lengthDigitalOutput()
1560 Using writeDigitalOutputWithMask is recommended for the less data 1563 @param dout list of int: List of bits, length of 32 bits where elements are 1566 What each element stands for depends on how 1567 the robot's imlemented. Consult the hardware manual. 1568 @return bool: RobotHardware.writeDigitalOutput returns True if writable. False otherwise. 1573 if len(dout) < doutBitLength:
1574 for i
in range(doutBitLength - len(dout)):
1577 for i
in range(0, len(dout), 8):
1582 outStr = outStr + chr(oneChar)
1585 return self.rh_svc.writeDigitalOutput(outStr)
1589 Both dout and mask are lists with length of 32. Only the bit in dout 1590 that corresponds to the bits in mask that are flagged as 1 will be 1595 Case-1. Only 18th bit will be evaluated as 1. 1596 dout [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1597 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1598 mask [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1599 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1601 Case-2. Only 18th bit will be evaluated as 0. 1602 dout [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1603 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1604 mask [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1605 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1607 Case-3. None will be evaluated since there's no flagged bit in mask. 1608 dout [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1609 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1610 mask [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1611 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1613 @param dout list of int: List of bits, length of 32 bits where elements are 1615 @param mask list of int: List of masking bits, length of 32 bits where elements are 1617 @return bool: RobotHardware.writeDigitalOutput returns True if writable. False otherwise. 1622 if len(dout) < doutBitLength
and \
1623 len(mask) < doutBitLength
and \
1624 len(dout) == len(mask):
1625 for i
in range(doutBitLength - len(dout)):
1630 for i
in range(0, len(dout), 8):
1638 outStr = outStr + chr(oneChar)
1639 outMsk = outMsk + chr(oneMask)
1642 return self.rh_svc.writeDigitalOutputWithMask(outStr, outMsk)
1646 Read data from Digital Input 1647 @see: HrpsysConfigurator.readDigitalInput 1649 Digital input consits of 14 bits. The last 2 bits are lacking 1650 and compensated, so that the last 4 bits are 0x4 instead of 0x1. 1651 @author Hajime Saito (\@emijah) 1652 @return list of int: List of the values (2 octtets) in digital input register. Range: 0 or 1. 1654 #TODO: Catch AttributeError that occurs when RobotHardware not found. 1655 # Typically with simulator, erro msg might look like this; 1656 # 'NoneType' object has no attribute 'readDigitalInput' 1660 ret, din = self.rh_svc.readDigitalInput()
1664 if (ord(item) >> i) & 1:
1672 Read data from Digital Output 1674 Digital input consits of 14 bits. The last 2 bits are lacking 1675 and compensated, so that the last 4 bits are 0x4 instead of 0x1. 1677 #TODO: Catch AttributeError that occurs when RobotHardware not found. 1678 # Typically with simulator, erro msg might look like this; 1679 # 'NoneType' object has no attribute 'readDigitaloutput' 1681 @author Hajime Saito (\@emijah) 1682 @return list of int: List of the values in digital input register. Range: 0 or 1. 1684 ret, dout = self.rh_svc.readDigitalOutput()
1688 if (ord(item) >> i) & 1:
1696 Get actual states of the robot that includes current reference joint angles and joint torques. 1697 @return: This returns actual states of the robot, which is defined in 1699 (found at https://github.com/fkanehiro/hrpsys-base/blob/3fd7671de5129101a4ade3f98e2eac39fd6b26c0/idl/RobotHardwareService.idl#L32_L57 as of version 315.11.0) 1702 * @brief status of the robot 1706 DblSequence angle; ///< current joint angles[rad] 1707 DblSequence command;///< reference joint angles[rad] 1708 DblSequence torque; ///< joint torques[Nm] 1710 * @brief servo statuses(32bit+extra states) 1712 * 0: calib status ( 1 => done )\n 1713 * 1: servo status ( 1 => on )\n 1714 * 2: power status ( 1 => supplied )\n 1715 * 3-18: servo alarms (see @ref iob.h)\n 1717 * 24-31: driver temperature (deg) 1719 LongSequenceSequence servoState; 1720 sequence<DblSequence6> force; ///< forces[N] and torques[Nm] 1721 sequence<DblSequence3> rateGyro; ///< angular velocities[rad/s] 1722 sequence<DblSequence3> accel; ///< accelerations[m/(s^2)] 1723 double voltage; ///< voltage of power supply[V] 1724 double current; ///< current[A] 1728 return self.rh_svc.getStatus()
1732 Check whether joints have been calibrated. 1733 @return bool: True if all joints are calibrated 1738 rstt = self.rh_svc.getStatus()
1739 for item
in rstt.servoState:
1746 Check whether servo control has been turned on. 1747 @param jname str: Name of a link (that can be obtained by "hiro.Groups" 1748 as lists of groups). 1749 When jname = 'all' or 'any' => If all joints are servoOn, return True, otherwise, return False. 1750 When jname = 'some' => If some joint is servoOn, return True, otherwise return False. 1751 @return bool: True if servo is on 1757 if jname.lower() ==
'any' or jname.lower() ==
'all':
1763 elif jname.lower() ==
'some':
1770 jid = eval(
'self.' + jname)
1772 if s_s[jid][0] & 1 == 0:
1779 Convert list of angles into list of joint list for each groups. 1780 @param flatList list: single dimension list with its length of 15 1781 @return list of list: 2-dimensional list of Groups. 1785 for group
in self.
Groups:
1786 joint_num = len(group[1])
1787 retList.append(flatList[index: index + joint_num])
1794 Joints need to be calibrated (otherwise error returns). 1796 @param jname str: The value 'all' works iteratively for all servos. 1797 @param destroy int: Not used. 1798 @param tm float: Second to complete. 1799 @return int: 1 or -1 indicating success or failure, respectively. 1816 '!! Robot Motion Warning (SERVO_ON) !!\n\n' 1817 'Confirm RELAY switched ON\n' 1818 'Push [OK] to switch servo ON(%s).' % (jname))
1823 self.rh_svc.power(
'all', SWITCH_OFF)
1829 self.rh_svc.servo(jname, SWITCH_ON)
1842 @param jname str: The value 'all' works iteratively for all servos. 1843 @param wait bool: Wait for user's confirmation via GUI 1844 @return int: 1 = all arm servo off. 2 = all servo on arms and hands off. 1845 -1 = Something wrong happened. 1852 print(
'Turn off Hand Servo')
1854 self.sc_svc.servoOff()
1857 if jname.lower() ==
'all':
1858 self.rh_svc.power(
'all', SWITCH_OFF)
1867 '!! Robot Motion Warning (Servo OFF)!!\n\n' 1868 'Push [OK] to servo OFF (%s).' % (jname))
1873 self.rh_svc.servo(
'all', SWITCH_OFF)
1876 self.rh_svc.power(
'all', SWITCH_OFF)
1879 print(
'Turn off Hand Servo')
1881 self.sc_svc.servoOff()
1890 Run the encoder checking sequence for specified joints, 1891 run goActual and turn on servos. 1893 @param jname str: The value 'all' works iteratively for all servos. 1894 @param option str: Possible values are follows (w/o double quote):\ 1895 "-overwrite": Overwrite calibration value. 1905 self.rh_svc.power(
'all', SWITCH_ON)
1906 msg =
'!! Robot Motion Warning !!\n'\
1908 'Then Push [OK] to ' 1909 if option ==
'-overwrite':
1910 msg = msg +
'calibrate(OVERWRITE MODE) ' 1912 msg = msg +
'check ' 1915 msg = msg +
'the Encoders of all.' 1917 msg = msg +
'the Encoder of the Joint "' + jname +
'".' 1922 print(
"If you're connecting to the robot from remote, " + \
1923 "make sure tunnel X (eg. -X option with ssh).")
1924 self.rh_svc.power(
'all', SWITCH_OFF)
1928 self.rh_svc.initializeJointAngle(jname, option)
1930 self.rh_svc.power(
'all', SWITCH_OFF)
1933 self.rh_svc.servo(jname, SWITCH_ON)
1936 print(
'Turn on Hand Servo')
1938 self.sc_svc.servoOn()
1942 remove force sensor offset 1944 self.rh_svc.removeForceSensorOffset()
1948 Play motion pattern using a given trajectory that is represented by 1949 a list of joint angles, rpy, zmp and time. 1951 @type jointangles: [[float]] 1952 @param jointangles: Sequence of the sets of joint angles in radian. 1953 The whole list represents a trajectory. Each element 1954 of the 1st degree in the list consists of the joint angles. 1955 @param rpy list of float: Orientation in rpy. 1956 @param zmp list of float: TODO: description 1957 @param tm float: Second to complete the command. This only includes the time taken for execution 1958 (i.e. time for planning and other misc. processes are not considered). 1961 return self.seq_svc.playPattern(jointangles, rpy, zmp, tm)
1965 Play motion pattern using a set of given trajectories that are represented by 1966 lists of joint angles. Each trajectory aims to run within the specified time (tm), 1967 and there's no slow down between trajectories unless the next one is the last. 1970 self.playPatternOfGroup('larm', 1971 [[0.0, 0.0, -2.2689280275926285, 0.0, 0.0, 0.0], 1972 [0.0, 0.0, -1.9198621771937625, 0.0, 0.0, 0.0], 1973 [0.0, 0.0, -1.5707963, 0.0, 0.0, 0.0]], 1976 @param gname str: Name of the joint group. 1977 @type jointangles: [[float]] 1978 @param jointangles: Sequence of the sets of joint angles in radian. 1979 The whole list represents a trajectory. Each element 1980 of the 1st degree in the list consists of the joint 1981 angles. To illustrate: 1983 [[a0-0, a0-1,...,a0-n], # a)ngle. 1st path in trajectory 1984 [a1-0, a1-1,...,a1-n], # 2nd path in the trajectory. 1986 [am-0, am-1,...,am-n]] # mth path in the trajectory 1988 @param tm float: Sequence of the time values to complete the task, 1989 each element of which corresponds to a set of jointangles 1993 return self.seq_svc.playPatternOfGroup(gname, jointangles, tm)
1997 Set joint angles for sensor calibration. 1998 Please override joint angles to avoid self collision. 2000 self.
setJointAngles([0]*len(self.rh_svc.getStatus().servoState), 4.0)
2005 Calibrate inertia sensor 2007 self.rh_svc.calibrateInertiaSensor()
2011 Calibrate inertia sensor with dialog and setting calibration pose 2013 r = waitInputConfirm (
2014 '!! Robot Motion Warning (Move to Sensor Calibration Pose)!!\n\n' 2015 'Push [OK] to move to sensor calibration pose.')
2016 if not r:
return False 2018 r = waitInputConfirm (
2019 '!! Put the robot down!!\n\n' 2020 'Push [OK] to the next step.')
2021 if not r:
return False 2023 r = waitInputConfirm (
2024 '!! Put the robot up!!\n\n' 2025 'Push [OK] to the next step.')
2026 if not r:
return False 2034 Start AutoBalancer mode 2035 @param limbs list of end-effector name to control. 2036 If Groups has rarm and larm, rleg, lleg, rarm, larm by default. 2037 If Groups is not defined or Groups does not have rarm and larm, rleg and lleg by default. 2040 if self.
Groups !=
None and "rarm" in map (
lambda x : x[0], self.
Groups)
and "larm" in map (
lambda x : x[0], self.
Groups):
2041 limbs=[
"rleg",
"lleg",
"rarm",
"larm"]
2043 limbs=[
"rleg",
"lleg"]
2044 self.abc_svc.startAutoBalancer(limbs)
2048 Stop AutoBalancer mode 2050 self.abc_svc.stopAutoBalancer()
2054 Start Stabilzier mode 2056 self.st_svc.startStabilizer()
2060 Stop Stabilzier mode 2062 self.st_svc.stopStabilizer()
2071 force_gain = [1, 1, 1],
2072 moment_gain = [0, 0, 0],
2075 reference_gain = 0.0,
2076 manipulability_limit = 0.1,
2077 controller_mode =
None,
2078 ik_optional_weight_vector =
None):
2080 start impedance mode 2082 @type arm: str name of artm to be controlled, this must be initialized using setSelfGroups() 2083 @param force_gain, moment_gain: multipliers to the eef offset position vel_p and orientation vel_r. 2084 3-dimensional vector (then converted internally into a diagonal matrix). 2086 r, p = self.ic_svc.getImpedanceControllerParam(arm)
2088 print(
'{}, Failt to getImpedanceControllerParam({})'.format(self.
configurator_name, arm))
2090 if M_p !=
None: p.M_p = M_p
2091 if D_p !=
None: p.M_p = D_p
2092 if K_p !=
None: p.M_p = K_p
2093 if M_r !=
None: p.M_r = M_r
2094 if D_r !=
None: p.M_r = D_r
2095 if K_r !=
None: p.M_r = K_r
2096 if force_gain !=
None: p.force_gain = force_gain
2097 if moment_gain !=
None: p.moment_gain = moment_gain
2098 if sr_gain !=
None: p.sr_gain = sr_gain
2099 if avoid_gain !=
None: p.avoid_gain = avoid_gain
2100 if reference_gain !=
None: p.reference_gain = reference_gain
2101 if manipulability_limit !=
None: p.manipulability_limit = manipulability_limit
2102 if controller_mode !=
None: p.controller_mode = controller_mode
2103 if ik_optional_weight_vector !=
None: p.ik_optional_weight_vector = ik_optional_weight_vector
2104 self.ic_svc.setImpedanceControllerParam(arm, p)
2105 return self.ic_svc.startImpedanceController(arm)
2111 return self.ic_svc.stopImpedanceController(arm)
2115 Enable the ImpedanceController RT component. 2116 This method internally calls startImpedance-*, hrpsys version-specific method. 2118 @requires: hrpsys version greather than 315.2.0. 2119 @requires: ImpedanceController RTC to be activated on the robot's controller. 2120 @change: From 315.2.0 onward, following arguments are dropped and can be set by 2121 self.seq_svc.setWrenches instead of this method. 2122 See an example at https://github.com/fkanehiro/hrpsys-base/pull/434/files#diff-6204f002204dd9ae80f203901f155fa9R44: 2124 - ref_force[fx, fy, fz] (unit: N) and ref_moment[tx, ty, tz] (unit: Nm) can be set via self.seq_svc.setWrenches. For example: 2126 self.seq_svc.setWrenches([0, 0, 0, 0, 0, 0, 2127 fx, fy, fz, tx, ty, tz, 2131 setWrenches takes 6 values per sensor, so the robot in the example above has 4 sensors where each line represents a sensor. 2132 See this link (https://github.com/fkanehiro/hrpsys-base/pull/434/files) for a concrete example. 2134 @param arm: Name of the kinematic group (i.e. self.Groups[n][0]). 2135 @param kwargs: This varies depending on the version of hrpsys your robot's controller runs on 2136 (which you can find by "self.hrpsys_version" command). For instance, if your 2137 hrpsys is 315.10.1, refer to "startImpedance_315_4" method. 2152 Start default unstable RTCs controller mode. 2153 Currently Stabilzier, AutoBalancer, and ImpedanceController are started based on "Groups" setting. 2154 If ic_limbs or abc_limbs is not specified, default setting is set according to "Groups". 2156 If the robot has an arm, start impedance for the arm. 2157 If the robot has a leg, start st and autobalancer. 2158 autobalancer's fixed limbs are all existing arms and legs. 2160 Biped robot (leg only) : no impedance, start st, start autobalancer with ["rleg", "lleg"]. 2161 Dual-arm robot (arm only) : start impedance ["rarm", "larm"], no st, no autobalancer. 2162 Dual-arm+biped robot (=humanoid robot) : start impedance ["rarm", "larm"], start st, start autobalancer with ["rleg", "lleg", "rarm", "larm"]. 2163 Quadruped robot : same as "humanoid robot" by default. 2167 is_legged_robot =
map(
lambda x: x[0], filter(
lambda x : re.match(
".*leg", x[0]), self.
Groups))
2170 ic_limbs =
map(
lambda x: x[0], filter(
lambda x : re.match(
".*(arm)", x[0]), self.
Groups))
2173 abc_limbs =
map(
lambda x: x[0], filter(
lambda x : re.match(
".*(leg|arm)", x[0]), self.
Groups))
2175 for limb
in ic_limbs:
2176 self.ic_svc.startImpedanceControllerNoWait(limb)
2180 for limb
in ic_limbs:
2181 self.ic_svc.waitImpedanceControllerTransition(limb)
2186 if len(ic_limbs) != 0:
2191 Stop default unstable RTCs controller mode. 2192 Currently Stabilzier, AutoBalancer, and ImpedanceController are stopped based on "Groups" setting. 2193 Please see documentation of startDefaultUnstableControllers(). 2197 is_legged_robot =
map(
lambda x: x[0], filter(
lambda x : re.match(
".*leg", x[0]), self.
Groups))
2200 ic_limbs =
map(
lambda x: x[0], filter(
lambda x : re.match(
".*(arm)", x[0]), self.
Groups))
2204 for limb
in ic_limbs:
2205 self.ic_svc.stopImpedanceControllerNoWait(limb)
2208 for limb
in ic_limbs:
2209 self.ic_svc.waitImpedanceControllerTransition(limb)
2214 if len(ic_limbs) != 0:
2220 @param footstep : FootstepSequence. 2221 @param overwrite_fs_idx : Index to be overwritten. overwrite_fs_idx is used only in walking. 2223 self.abc_svc.setFootSteps(footstep, overwrite_fs_idx)
2228 @param footstep : FootstepSequence. 2229 @param stepparams : StepParamSeuqnce. 2230 @param overwrite_fs_idx : Index to be overwritten. overwrite_fs_idx is used only in walking. 2232 self.abc_svc.setFootStepsWithParam(footstep, stepparams, overwrite_fs_idx)
2236 Cancels the commanded sequence of joint angle, by overwriting the command by the values of instant the method was invoked. 2237 Note that this only cancels the queue once. Icoming commands after this method is called will be processed as usual. 2240 return self.seq_svc.clearJointAngles()
2244 Cancels the commanded sequence of joint angle for the specified joint group, by overwriting the command by the values of instant the method was invoked. 2245 Note that this only cancels the queue once. Icoming commands after this method is called will be processed as usual. 2246 @param gname: Name of the joint group. 2249 return self.seq_svc.clearJointAnglesOfGroup(gname)
2253 remove force sensor offset by RemoveForceSensorOffset (RMFO) RTC. 2254 @param sensor_names : list of sensor names to be calibrated. If not specified, all sensors are calibrated by default. 2255 @param tm : calibration time[s]. 8.0[s] by default. 2256 @return bool : true if set successfully, false otherwise 2258 return self.rmfo_svc.removeForceSensorOffset(sensor_names, tm)
2264 def init(self, robotname="Robot", url=""):
2266 Calls init from its superclass, which tries to connect RTCManager, 2267 looks for ModelLoader, and starts necessary RTC components. Also runs 2269 Also internally calls setSelfGroups(). 2271 @type robotname: str 2301 self.
hrpsys_version = self.fk.ref.get_component_profile().version
2312 if __name__ ==
'__main__':
2314 if len(sys.argv) > 2:
2315 hcf.init(sys.argv[1], sys.argv[2])
2316 elif len(sys.argv) > 1:
2317 hcf.init(sys.argv[1])
def waitInterpolationOfGroup(self, gname)
Lets SequencePlayer wait until the movement currently happening to finish.
def waitForRTCManager(self, managerhost=nshost)
Wait for RTC manager.
def startImpedance_315_4(self, arm, M_p=100.0, D_p=100.0, K_p=100.0, M_r=100.0, D_r=2000.0, K_r=2000.0, force_gain=[1, moment_gain=[0, sr_gain=1.0, avoid_gain=0.0, reference_gain=0.0, manipulability_limit=0.1, controller_mode=None, ik_optional_weight_vector=None)
start impedance mode
def getReferencePose(self, lname, frame_name=None)
Returns the current commanded pose of the specified joint in the joint space.
def readDigitalOutput(self)
Read data from Digital Output.
def activateComps(self)
Activate components(plugins)
def lengthDigitalOutput(self)
Returns the length of digital output port.
def getCurrentRPY(self, lname, frame_name=None)
Returns the current physical rotation in RPY of the specified joint.
def getActualState(self)
Get actual states of the robot that includes current reference joint angles and joint torques...
def clearJointAngles(self)
Cancels the commanded sequence of joint angle, by overwriting the command by the values of instant th...
def getRTCInstanceList(self, verbose=True)
Get list of RTC Instance.
def startDefaultUnstableControllers(self, ic_limbs=[], abc_limbs=[])
Start default unstable RTCs controller mode.
def servoOn(self, jname='all', destroy=1, tm=3)
Turn on servos.
def findRTC(name, rnc=None)
get RT component
def deactivateComps(self)
Deactivate components(plugins)
def writeDigitalOutputWithMask(self, dout, mask)
Both dout and mask are lists with length of 32.
def loadPattern(self, fname, tm)
Load a pattern file that is created offline.
def stopDefaultUnstableControllers(self, ic_limbs=[])
Stop default unstable RTCs controller mode.
def setJointAngles(self, angles, tm)
Set all joint angles.
def clearJointAnglesOfGroup(self, gname)
Cancels the commanded sequence of joint angle for the specified joint group, by overwriting the comma...
def getCurrentRotation(self, lname, frame_name=None)
Returns the current physical rotation of the specified joint.
def connectLoggerPort(self, artc, sen_name, log_name=None)
Connect port to logger.
def setFootStepsWithParam(self, footstep, stepparams, overwrite_fs_idx=0)
setFootSteps
def calibrateInertiaSensorWithDialog(self)
Calibrate inertia sensor with dialog and setting calibration pose.
def findComps(self, max_timeout_count=10, verbose=True)
Check if all components in getRTCList() are created.
def narrow(ior, klass, package="OpenHRP")
narrow ior
def startImpedance(self, arm, kwargs)
Enable the ImpedanceController RT component.
bool kinematics_only_mode
def setJointAngle(self, jname, angle, tm)
Set angle to the given joint.
def stopImpedance_315_4(self, arm)
stop impedance mode
def setJointAnglesSequence(self, angless, tms)
Set all joint angles.
def connectComps(self)
Connect components(plugins)
def getCurrentPosition(self, lname=None, frame_name=None)
Returns the current physical position of the specified joint in Cartesian space.
def playPatternOfGroup(self, gname, jointangles, tm)
Play motion pattern using a set of given trajectories that are represented by lists of joint angles...
def findComp(self, compName, instanceName, max_timeout_count=10, verbose=True)
Find component(plugin)
def lengthDigitalInput(self)
Returns the length of digital input port.
def setupLogger(self, maxLength=4000)
Setup logging function.
def setTargetPoseRelative(self, gname, eename, dx=0, dy=0, dz=0, dr=0, dp=0, dw=0, tm=10, wait=True)
Move the end-effector's location relative to its current pose.
def getRTCListUnstable(self)
Get list of available components including stable and unstable.
def saveLog(self, fname='sample')
Save log to the given file name.
def getForceSensorNames(self)
Get list of force sensor names.
def setJointAnglesOfGroup(self, gname, pose, tm, wait=True)
Set the joint angles to aim.
def getCurrentPose(self, lname=None, frame_name=None)
Returns the current physical pose of the specified joint in the joint space.
def clearLog(self)
Clear logger's buffer.
def createComp(self, compName, instanceName)
Create RTC component (plugins)
def waitInterpolation(self)
Lets SequencePlayer wait until the movement currently happening to finish.
def createComps(self)
Create components(plugins) in getRTCList()
def setMaxLogLength(self, length)
Set logger's buffer.
def checkSimulationMode(self)
Check if this is running as simulation.
def getBodyInfo(self, url)
Get bodyInfo.
def setFootSteps(self, footstep, overwrite_fs_idx=0)
setFootSteps
def waitForRTCManagerAndRobotHardware(self, robotname="Robot", managerhost=nshost)
Wait for both RTC Manager (waitForRTCManager()) and RobotHardware (waitForRobotHardware()) ...
def init(self, robotname="Robot", url="")
Calls init from its superclass, which tries to connect RTCManager, looks for ModelLoader, and starts necessary RTC components.
def serializeComponents(rtcs, stopEC=True)
set up execution context of the first RTC so that RTCs are executed sequentially
def clear(self)
Clears the Sequencer's current operation.
def findRTCmanager(hostname=None, rnc=None)
get RTCmanager
def calibrateInertiaSensor(self)
Calibrate inertia sensor.
def servoOff(self, jname='all', wait=True)
Turn off servos.
def stopStabilizer(self)
Stop Stabilzier mode.
def getReferenceRPY(self, lname, frame_name=None)
Returns the current commanded rotation in RPY of the specified joint.
def connectPorts(outP, inPs, subscription="flush", dataflow="Push", bufferlength=1, rate=1000)
connect ports
def setSensorCalibrationJointAngles(self)
Set joint angles for sensor calibration.
def flat2Groups(self, flatList)
Convert list of angles into list of joint list for each groups.
def checkEncoders(self, jname='all', option='')
Run the encoder checking sequence for specified joints, run goActual and turn on servos.
def waitForRTCManagerAndRoboHardware(self, robotname="Robot", managerhost=nshost)
def readDigitalInput(self)
Read data from Digital Input.
def findObject(name, kind="", rnc=None)
get IOR of the object
def euler_matrix(ai, aj, ak, axes='sxyz')
def findPort(rtc, name)
get a port of RT component
def getSensors(self, url)
Get list of sensors.
def clearOfGroup(self, gname, tm=0.0)
Clears the Sequencer's current operation for joint groups.
def setTargetPose(self, gname, pos, rpy, tm, frame_name=None)
Move the end-effector to the given absolute pose.
def setInterpolationMode(self, mode)
Set interpolation mode.
def removeForceSensorOffset(self)
remove force sensor offset
def getReferenceRotation(self, lname, frame_name=None)
Returns the current commanded rotation of the specified joint.
def deleteComps(self)
Delete components(plugins) in getRTCInstanceList()
def getReferencePosition(self, lname, frame_name=None)
Returns the current commanded position of the specified joint in Cartesian space. ...
def isCalibDone(self)
Check whether joints have been calibrated.
def removeForceSensorOffsetRMFO(self, sensor_names=[], tm=8.0)
remove force sensor offset by RemoveForceSensorOffset (RMFO) RTC.
def __init__(self, cname="[hrpsys.py] ")
def startStabilizer(self)
Start Stabilzier mode.
def findModelLoader(self)
Try to find ModelLoader.
def writeDigitalOutput(self, dout)
Using writeDigitalOutputWithMask is recommended for the less data transport.
def goActual(self)
Adjust commanded values to the angles in the physical state by calling StateHolder::goActual.
def deleteComp(self, compName)
Delete RTC component (plugins)
def stopImpedance(self, arm)
def setJointAnglesSequenceOfGroup(self, gname, angless, tms)
Set all joint angles.
def stopAutoBalancer(self)
Stop AutoBalancer mode.
def getRTCList(self)
Get list of available STABLE components.
def playPattern(self, jointangles, rpy, zmp, tm)
Play motion pattern using a given trajectory that is represented by a list of joint angles...
def dataTypeOfPort(port)
get data type of a port
def euler_from_matrix(matrix, axes='sxyz')
def waitForRobotHardware(self, robotname="Robot")
Wait for RobotHardware is exists and activated.
def getJointAngles(self)
Returns the commanded joint angle values.
def isServoOn(self, jname='any')
Check whether servo control has been turned on.
def setSelfGroups(self)
Set to the hrpsys.SequencePlayer the groups of links and joints that are statically defined as member...
def startAutoBalancer(self, limbs=None)
Start AutoBalancer mode.
def initCORBA()
initialize ORB
def waitForModelLoader(self)
Wait for ModelLoader.
def getJointAngleControllerList(self)
Get list of controller list that need to control joint angles.