hrpsys_config.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import os
4 import rtm
5 
6 from rtm import *
7 from OpenHRP import *
8 from hrpsys import * # load ModelLoader
9 from hrpsys import ImpedanceControllerService_idl
10 from waitInput import waitInputConfirm
11 
12 import socket
13 import time
14 import subprocess
15 from distutils.version import StrictVersion
16 
17 # copy from transformations.py, Christoph Gohlke, The Regents of the University of California
18 
19 import numpy
20 # map axes strings to/from tuples of inner axis, parity, repetition, frame
21 _AXES2TUPLE = {
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)}
30 
31 # axis sequences for Euler angles
32 _NEXT_AXIS = [1, 2, 0, 1]
33 
34 # epsilon for testing whether a number is close to zero
35 _EPS = numpy.finfo(float).eps * 4.0
36 
37 
38 def euler_matrix(ai, aj, ak, axes='sxyz'):
39  """Return homogeneous rotation matrix from Euler angles and axis sequence.
40 
41  ai, aj, ak : Euler's roll, pitch and yaw angles
42  axes : One of 24 axis sequences as string or encoded tuple
43 
44  >>> R = euler_matrix(1, 2, 3, 'syxz')
45  >>> numpy.allclose(numpy.sum(R[0]), -1.34786452)
46  True
47  >>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1))
48  >>> numpy.allclose(numpy.sum(R[0]), -0.383436184)
49  True
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)
55 
56  """
57  try:
58  firstaxis, parity, repetition, frame = _AXES2TUPLE[axes]
59  except (AttributeError, KeyError):
60  _ = _TUPLE2AXES[axes]
61  firstaxis, parity, repetition, frame = axes
62 
63  i = firstaxis
64  j = _NEXT_AXIS[i + parity]
65  k = _NEXT_AXIS[i - parity + 1]
66 
67  if frame:
68  ai, ak = ak, ai
69  if parity:
70  ai, aj, ak = -ai, -aj, -ak
71 
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
76 
77  M = numpy.identity(4)
78  if repetition:
79  M[i, i] = cj
80  M[i, j] = sj * si
81  M[i, k] = sj * ci
82  M[j, i] = sj * sk
83  M[j, j] = -cj * ss + cc
84  M[j, k] = -cj * cs - sc
85  M[k, i] = -sj * ck
86  M[k, j] = cj * sc + cs
87  M[k, k] = cj * cc - ss
88  else:
89  M[i, i] = cj * ck
90  M[i, j] = sj * sc - cs
91  M[i, k] = sj * cc + ss
92  M[j, i] = cj * sk
93  M[j, j] = sj * ss + cc
94  M[j, k] = sj * cs - sc
95  M[k, i] = -sj
96  M[k, j] = cj * si
97  M[k, k] = cj * ci
98  return M
99 
100 
101 def euler_from_matrix(matrix, axes='sxyz'):
102  """Return Euler angles from rotation matrix for specified axis sequence.
103 
104  axes : One of 24 axis sequences as string or encoded tuple
105 
106  Note that many Euler angle triplets can describe one matrix.
107 
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)
112  True
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"
118 
119  """
120  try:
121  firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
122  except (AttributeError, KeyError):
123  _ = _TUPLE2AXES[axes]
124  firstaxis, parity, repetition, frame = axes
125 
126  i = firstaxis
127  j = _NEXT_AXIS[i + parity]
128  k = _NEXT_AXIS[i - parity + 1]
129 
130  M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:3, :3]
131  if repetition:
132  sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k])
133  if sy > _EPS:
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])
137  else:
138  ax = math.atan2(-M[j, k], M[j, j])
139  ay = math.atan2(sy, M[i, i])
140  az = 0.0
141  else:
142  cy = math.sqrt(M[i, i] * M[i, i] + M[j, i] * M[j, i])
143  if cy > _EPS:
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])
147  else:
148  ax = math.atan2(-M[j, k], M[j, j])
149  ay = math.atan2(-M[k, i], cy)
150  az = 0.0
151 
152  if parity:
153  ax, ay, az = -ax, -ay, -az
154  if frame:
155  ax, az = az, ax
156  return ax, ay, az
157 
158 
159 # class for configure hrpsys RTCs and ports
160 # In order to specify robot-dependent code, please inherit this HrpsysConfigurator
161 class HrpsysConfigurator(object):
162 
163  # RobotHardware
164  rh = None
165  rh_svc = None
166  ep_svc = None
167  rh_version = None
168 
169  # SequencePlayer
170  seq = None
171  seq_svc = None
172  seq_version = None
173 
174  # StateHolder
175  sh = None
176  sh_svc = None
177  sh_version = None
178 
179  # ServoController
180  sc= None
181  sc_svc = None
182  sc_version = None
183 
184  # ForwardKinematics
185  fk = None
186  fk_svc = None
187  fk_version = None
188 
189  tf = None # TorqueFilter
190  kf = None # KalmanFilter
191  vs = None # VirtualForceSensor
192  rmfo = None # RemoveForceSensorLinkOffset
193  ic = None # ImpedanceController
194  abc = None # AutoBalancer
195  st = None # Stabilizer
196 
197  tf_version = None
198  kf_version = None
199  vs_version = None
200  rmfo_version = None
201  ic_version = None
202  abc_version = None
203  st_version = None
204 
205  # EmergencyStopper
206  es = None
207  es_svc = None
208  es_version = None
209 
210  # EmergencyStopper (HardEmergencyStopper)
211  hes = None
212  hes_svc = None
213  hes_version = None
214 
215  # CollisionDetector
216  co = None
217  co_svc = None
218  co_version = None
219 
220  # GraspController
221  gc = None
222  gc_svc = None
223  gc_version = None
224 
225  # SoftErrorLimiter
226  el = None
227  el_svc = None
228  el_version = None
229 
230  # ThermoEstimator
231  te = None
232  te_svc = None
233  te_version = None
234 
235  # ThermoLimiter
236  tl = None
237  tl_svc = None
238  tl_version = None
239 
240  # TorqueController
241  tc = None
242  tc_svc = None
243  tc_version = None
244 
245  # DataLogger
246  log = None
247  log_svc = None
248  log_version = None
249  log_use_owned_ec = False
250 
251  # Beeper
252  bp = None
253  bp_svc = None
254  bp_version = None
255 
256  # ReferenceForceUpdater
257  rfu = None
258  rfu_svc = None
259  rfu_version = None
260 
261  # Acceleration Filter
262  acf = None
263  acf_svc = None
264  acf_version = None
265 
266  # ObjectContactTurnaroundDetector
267  octd = None
268  octd_svc = None
269  octd_version = None
270 
271  # rtm manager
272  ms = None
273 
274  # HGController(Simulation)
275  hgc = None
276 
277  # PDController(Simulation)
278  pdc = None
279 
280  # flag isSimulation?
281  simulation_mode = None
282 
283  # sensors
284  sensors = None
285 
286  # for setSelfGroups
287  Groups = [] # [['torso', ['CHEST_JOINT0']], ['head', ['HEAD_JOINT0', 'HEAD_JOINT1']], ....]
288 
289  hrpsys_version = None
290 
291  # flag isKinamticsOnlyMode?
292  kinematics_only_mode = False
293 
294  # public method
295  def connectComps(self):
296  '''!@brief
297  Connect components(plugins)
298  '''
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")
301  return
302  # connection for reference joint angles
303  tmp_controllers = self.getJointAngleControllerList()
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):
307  connectPorts(tmp_controllers[i].port("q"),
308  tmp_controllers[i + 1].port("qRef"))
309  if self.simulation_mode:
310  if self.pdc:
311  connectPorts(tmp_controllers[-1].port("q"), self.pdc.port("angleRef"))
312  else:
313  connectPorts(tmp_controllers[-1].port("q"), self.hgc.port("qIn"))
314  connectPorts(self.hgc.port("qOut"), self.rh.port("qRef"))
315  else:
316  connectPorts(tmp_controllers[-1].port("q"), self.rh.port("qRef"))
317  else:
318  if self.simulation_mode:
319  if self.pdc:
320  connectPorts(self.sh.port("qOut"), self.pdc.port("angleRef"))
321  else:
322  connectPorts(self.sh.port("qOut"), self.hgc.port("qIn"))
323  connectPorts(self.hgc.port("qOut"), self.rh.port("qRef"))
324  else:
325  connectPorts(self.sh.port("qOut"), self.rh.port("qRef"))
326 
327  # only for kinematics simulator
328  if rtm.findPort(self.rh.ref, "basePoseRef"):
330  if self.abc:
331  connectPorts(self.abc.port("basePoseOut"), self.rh.port("basePoseRef"))
332  else:
333  connectPorts(self.sh.port("basePoseOut"), self.rh.port("basePoseRef"))
334 
335  # connection for kf
336  if self.kf:
337  # currently use first acc and rate sensors for kf
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: # check existence of sensor ;; currently original HRP4C.xml has different naming rule of gsensor and gyrometer
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: # check existence of sensor ;; currently original HRP4C.xml has different naming rule of gsensor and gyrometer
343  connectPorts(self.rh.port(s_rate[0].name), self.kf.port("rate"))
344  connectPorts(self.rh.port("q"), self.kf.port("qCurrent"))
345 
346  # connection for rh
347  if self.rh.port("servoState") != None:
348  if self.te and self.el:
349  connectPorts(self.rh.port("servoState"),
350  self.te.port("servoStateIn"))
351  connectPorts(self.te.port("servoStateOut"),
352  self.el.port("servoStateIn"))
353  elif self.el:
354  connectPorts(self.rh.port("servoState"),
355  self.el.port("servoStateIn"))
356  elif self.te:
357  connectPorts(self.rh.port("servoState"),
358  self.te.port("servoStateIn"))
359 
360  # connection for sh, seq, fk
361  connectPorts(self.rh.port("q"), [self.sh.port("currentQIn"),
362  self.fk.port("q")]) # connection for actual joint angles
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"))
378  for sen in self.getForceSensorNames():
379  connectPorts(self.seq.port(sen + "Ref"),
380  self.sh.port(sen + "In"))
381 
382  # connection for st
383  if rtm.findPort(self.rh.ref, "lfsensor") and rtm.findPort(
384  self.rh.ref, "rfsensor") and self.st:
385  connectPorts(self.kf.port("rpy"), self.st.port("rpy"))
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"))
401  if self.es:
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"))
406  if self.rfu:
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"))
410  if self.octd:
411  connectPorts(self.abc.port("contactStates"), self.octd.port("contactStates"))
412 
413  # ref force moment connection
414  for sen in self.getForceSensorNames():
415  if self.abc and self.st:
416  connectPorts(self.abc.port(sen),
417  self.st.port(sen + "Ref"))
418  connectPorts(self.abc.port("limbCOPOffset_"+sen),
419  self.st.port("limbCOPOffset_"+sen))
420  if self.rfu:
421  ref_force_port_from = self.rfu.port("ref_"+sen+"Out")
422  elif self.es:
423  ref_force_port_from = self.es.port(sen+"Out")
424  else:
425  ref_force_port_from = self.sh.port(sen+"Out")
426  if self.ic:
427  connectPorts(ref_force_port_from,
428  self.ic.port("ref_" + sen+"In"))
429  if self.abc:
430  connectPorts(ref_force_port_from,
431  self.abc.port("ref_" + sen))
432  if self.es:
433  connectPorts(self.sh.port(sen+"Out"),
434  self.es.port(sen+"In"))
435  if self.rfu:
436  connectPorts(self.es.port(sen+"Out"),
437  self.rfu.port("ref_" + sen+"In"))
438  else:
439  if self.rfu:
440  connectPorts(self.sh.port(sen+"Out"),
441  self.rfu.port("ref_" + sen+"In"))
442 
443  # actual force sensors
444  if self.rmfo:
445  if self.kf: # use IMU values if exists
446  # connectPorts(self.kf.port("rpy"), self.ic.port("rpy"))
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))
451  if self.ic:
452  connectPorts(self.rmfo.port("off_" + sen.name),
453  self.ic.port(sen.name))
454  if self.rfu:
455  connectPorts(self.rmfo.port("off_" + sen.name),
456  self.rfu.port(sen.name))
457  if self.st:
458  connectPorts(self.rmfo.port("off_" + sen.name),
459  self.st.port(sen.name))
460  elif self.ic: # if the robot does not have rmfo and kf, but have ic
461  for sen in filter(lambda x: x.type == "Force", self.sensors):
462  connectPorts(self.rh.port(sen.name),
463  self.ic.port(sen.name))
464 
465  # connection for ic
466  if self.ic:
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"))
471  # connection for rfu
472  if self.rfu:
473  if self.es:
474  connectPorts(self.es.port("q"), self.rfu.port("qRef"))
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"))
478  # connection for tf
479  if self.tf:
480  # connection for actual torques
481  if rtm.findPort(self.rh.ref, "tau") != None:
482  connectPorts(self.rh.port("tau"), self.tf.port("tauIn"))
483  connectPorts(self.rh.port("q"), self.tf.port("qCurrent"))
484  # connection for vs
485  if self.vs:
486  connectPorts(self.rh.port("q"), self.vs.port("qCurrent"))
487  connectPorts(self.tf.port("tauOut"), self.vs.port("tauIn"))
488  # virtual force sensors
489  if self.ic:
490  for vfp in filter(lambda x: str.find(x, 'v') >= 0 and
491  str.find(x, 'sensor') >= 0, self.vs.ports.keys()):
492  connectPorts(self.vs.port(vfp), self.ic.port(vfp))
493  # connection for co
494  if self.co:
495  connectPorts(self.rh.port("q"), self.co.port("qCurrent"))
496  connectPorts(self.rh.port("servoState"), self.co.port("servoStateIn"))
497  # connection for octd
498  if self.octd:
499  connectPorts(self.rh.port("q"), self.octd.port("qCurrent"))
500  if self.kf:
501  connectPorts(self.kf.port("rpy"), self.octd.port("rpy"))
502  if self.rmfo:
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))
505 
506  # connection for gc
507  if self.gc:
508  connectPorts(self.rh.port("q"), self.gc.port("qCurrent")) # other connections
509  tmp_controller = self.getJointAngleControllerList()
510  index = tmp_controller.index(self.gc)
511  if index == 0:
512  connectPorts(self.sh.port("qOut"), self.gc.port("qIn"))
513  else:
514  connectPorts(tmp_controller[index - 1].port("q"),
515  self.gc.port("qIn"))
516 
517  # connection for te
518  if self.te:
519  connectPorts(self.rh.port("q"), self.te.port("qCurrentIn"))
520  connectPorts(self.sh.port("qOut"), self.te.port("qRefIn"))
521  if self.tf:
522  connectPorts(self.tf.port("tauOut"), self.te.port("tauIn"))
523  else:
524  connectPorts(self.rh.port("tau"), self.te.port("tauIn"))
525  # sevoStateIn is connected above
526 
527  # connection for tl
528  if self.tl:
529  if self.te:
530  connectPorts(self.te.port("tempOut"), self.tl.port("tempIn"))
531 
532  # connection for tc
533  if self.tc:
534  connectPorts(self.rh.port("q"), self.tc.port("qCurrent"))
535  if self.tf:
536  connectPorts(self.tf.port("tauOut"),
537  self.tc.port("tauCurrent"))
538  else:
539  connectPorts(self.rh.port("tau"), self.tc.port("tauCurrent"))
540  if self.tl:
541  connectPorts(self.tl.port("tauMax"), self.tc.port("tauMax"))
542 
543  # connection for el
544  if self.el:
545  connectPorts(self.rh.port("q"), self.el.port("qCurrent"))
546 
547  # connection for es
548  if self.es:
549  connectPorts(self.rh.port("servoState"), self.es.port("servoStateIn"))
550 
551  # connection for bp
552  if self.bp:
553  if self.tl:
554  connectPorts(self.tl.port("beepCommand"), self.bp.port("beepCommand"))
555  if self.es:
556  connectPorts(self.es.port("beepCommand"), self.bp.port("beepCommand"))
557  if self.el:
558  connectPorts(self.el.port("beepCommand"), self.bp.port("beepCommand"))
559  if self.co:
560  connectPorts(self.co.port("beepCommand"), self.bp.port("beepCommand"))
561 
562  # connection for acf
563  if self.acf:
564  # currently use first acc and rate sensors for acf
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"))
571  if self.kf:
572  connectPorts(self.kf.port("rpy"), self.acf.port("rpyIn"))
573  if self.abc:
574  connectPorts(self.abc.port("basePosOut"), self.acf.port("posIn"))
575 
576  def activateComps(self):
577  '''!@brief
578  Activate components(plugins)
579  '''
580  rtcList = self.getRTCInstanceList()
581  rtm.serializeComponents(rtcList)
582  for r in rtcList:
583  r.start()
584 
585  def deactivateComps(self):
586  '''!@brief
587  Deactivate components(plugins)
588  '''
589  rtcList = self.getRTCInstanceList()
590  for r in reversed(rtcList):
591  r.stop()
592 
593  def createComp(self, compName, instanceName):
594  '''!@brief
595  Create RTC component (plugins)
596 
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.
599  '''
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))
604  if comp == None:
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]
610  else:
611  return [comp, None, version]
612 
613  def createComps(self):
614  '''!@brief
615  Create components(plugins) in getRTCList()
616  '''
617  for rn in self.getRTCList():
618  try:
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] + "\")"
622  print(self.configurator_name + " eval : " + create_str)
623  exec(create_str)
624  except Exception:
625  _, e, _ = sys.exc_info()
626  print(self.configurator_name + '\033[31mFail to createComps ' + str(e) + '\033[0m')
627 
628 
629  def deleteComp(self, compName):
630  '''!@brief
631  Delete RTC component (plugins)
632 
633  @param compName str: name of component that to be deleted
634  '''
635  # component must be stoppped before delete
636  comp = rtm.findRTC(compName)
637  comp.stop()
638  return self.ms.delete(compName)
639 
640  def deleteComps(self):
641  '''!@brief
642  Delete components(plugins) in getRTCInstanceList()
643  '''
644  self.deactivateComps()
645  rtcList = self.getRTCInstanceList()
646  if rtcList:
647  try:
648  rtcList.remove(self.rh)
649  for r in reversed(rtcList):
650  if r.isActive():
651  print(self.configurator_name, '\033[31m ' + r.name() + ' is staill active\033[0m')
652  self.deleteComp(r.name())
653  except Exception:
654  _, e, _ = sys.exc_info()
655  print(self.configurator_name + '\033[31mFail to deleteComps' + str(e) + '\033[0m')
656 
657  def findComp(self, compName, instanceName, max_timeout_count=10, verbose=True):
658  '''!@brief
659  Find component(plugin)
660 
661  @param compName str: component name
662  @param instanceName str: instance name
663  @max_timeout_count int: max timeout in seconds
664  '''
665  timeout_count = 0
666  comp = rtm.findRTC(instanceName)
667  version = None
668  while comp == None and timeout_count < max_timeout_count:
669  comp = rtm.findRTC(instanceName)
670  if comp != None:
671  break
672  if verbose:
673  print(self.configurator_name + " find Comp wait for " + instanceName)
674  time.sleep(1)
675  timeout_count += 1
676  if comp and comp.ref:
677  version = comp.ref.get_component_profile().version
678  if verbose:
679  print(self.configurator_name + " find Comp : %s = %s (%s)" % (instanceName, comp, version))
680  if comp == None:
681  if verbose:
682  print(self.configurator_name + " Cannot find component: %s (%s)" % (instanceName, compName))
683  return [None, None, None]
684  comp_svc_port = comp.service("service0")
685  if comp_svc_port:
686  comp_svc = narrow(comp_svc_port, compName + "Service")
687  if verbose:
688  print(self.configurator_name + " find CompSvc : %s_svc = %s"%(instanceName, comp_svc))
689  return [comp, comp_svc, version]
690  else:
691  return [comp, None, version]
692 
693  def findComps(self, max_timeout_count = 10, verbose=True):
694  '''!@brief
695  Check if all components in getRTCList() are created
696  '''
697  for rn in self.getRTCList():
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) + ")"
701  if verbose:
702  print(self.configurator_name + create_str)
703  exec(create_str)
704  if eval(rn2) == None:
705  max_timeout_count = 0
706 
707  # public method to configure all RTCs to be activated on rtcd
708  def getRTCList(self):
709  '''!@brief
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.
713  '''
714  return [
715  ['seq', "SequencePlayer"],
716  ['sh', "StateHolder"],
717  ['fk', "ForwardKinematics"],
718  # ['tf', "TorqueFilter"],
719  # ['kf', "KalmanFilter"],
720  # ['vs', "VirtualForceSensor"],
721  # ['rmfo', "RemoveForceSensorLinkOffset"],
722  # ['ic', "ImpedanceController"],
723  # ['abc', "AutoBalancer"],
724  # ['st', "Stabilizer"],
725  ['co', "CollisionDetector"],
726  # ['tc', "TorqueController"],
727  # ['te', "ThermoEstimator"],
728  # ['tl', "ThermoLimiter"],
729  ['el', "SoftErrorLimiter"],
730  ['log', "DataLogger"]
731  ]
732 
733  # public method to configure all RTCs to be activated on rtcd which includes unstable RTCs
735  '''!@brief
736  Get list of available components including stable and unstable.
737 
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.
740  '''
741  return [
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"],
761  ['bp', "Beeper"],
762  ['acf', "AccelerationFilter"],
763  ['log', "DataLogger"]
764  ]
765 
767  '''!@brief
768  Get list of controller list that need to control joint angles
769  '''
770  controller_list = [self.es, self.ic, self.gc, self.abc, self.st, self.co,
771  self.tc, self.hes, self.el]
772  return filter(lambda c: c != None, controller_list) # only return existing controllers
773 
774  def getRTCInstanceList(self, verbose=True):
775  '''!@brief
776  Get list of RTC Instance
777  '''
778  ret = [self.rh]
779  for rtc in self.getRTCList():
780  r = 'self.'+rtc[0]
781  try:
782  if eval(r):
783  ret.append(eval(r))
784  else:
785  if verbose:
786  print(self.configurator_name + '\033[31mFail to find instance ('+str(rtc)+') for getRTCInstanceList\033[0m')
787  except Exception:
788  _, e, _ = sys.exc_info()
789  print(self.configurator_name + '\033[31mFail to getRTCInstanceList'+str(e)+'\033[0m')
790  return ret
791 
792  # private method to replace $(PROJECT_DIR)
793  # PROJECT_DIR=(OpenHRP3 installed directory)/share/OpenHRP-3.1/sample/project
794  # see http://www.openrtp.jp/openhrp3/3.1.0.beta/jp/install_ubuntu.html
795  def parseUrl(self, url):
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)
800  return url
801 
802  # public method to get bodyInfo
803  def getBodyInfo(self, url):
804  '''!@brief
805  Get bodyInfo
806  '''
807  import CosNaming
808  obj = rtm.rootnc.resolve([CosNaming.NameComponent('ModelLoader', '')])
809  mdlldr = obj._narrow(ModelLoader_idl._0_OpenHRP__POA.ModelLoader)
810  url = self.parseUrl(url)
811  print(self.configurator_name + " bodyinfo URL = file://" + url)
812  return mdlldr.getBodyInfo("file://" + url)
813 
814  # public method to get sensors list
815  def getSensors(self, url):
816  '''!@brief
817  Get list of sensors
818 
819  @param url str: model file url
820  '''
821  if url == '':
822  return []
823  else:
824  return sum(map(lambda x: x.sensors,
825  filter(lambda x: len(x.sensors) > 0,
826  self.getBodyInfo(url)._get_links())), []) # sum is for list flatten
827 
828  # public method to get sensors list
830  '''!@brief
831  Get list of force sensor names. Returns existence force sensors and virtual force sensors. self.sensors and virtual force sensors are assumed.
832  '''
833  ret = map (lambda x : x.name, filter(lambda x: x.type == "Force", self.sensors))
834  if self.vs != None:
835  ret += filter(lambda x: str.find(x, 'v') >= 0 and str.find(x, 'sensor') >= 0, self.vs.ports.keys())
836  return ret
837 
838  def connectLoggerPort(self, artc, sen_name, log_name=None):
839  '''!@brief
840  Connect port to logger
841 
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
845  '''
846  log_name = log_name if log_name else artc.name() + "_" + sen_name
847  if artc and rtm.findPort(artc.ref, sen_name) != None:
848  sen_type = rtm.dataTypeOfPort(artc.port(sen_name)).split("/")[1].split(":")[0]
849  if rtm.findPort(self.log.ref, log_name) == None:
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)
852  else:
853  print(self.configurator_name + " setupLogger : %s arleady exists in DataLogger"% sen_name)
854  connectPorts(artc.port(sen_name), self.log.port(log_name))
855 
856  # public method to configure default logger data ports
857  def setupLogger(self, maxLength=4000):
858  '''!@brief
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
862  '''
863  if self.log == None:
864  print(self.configurator_name + "\033[31m setupLogger : self.log is not defined, please check rtcd.conf or rtcd arguments\033[0m")
865  return
866  self.log_svc.maxLength(maxLength);
867  #
868  for pn in ['q', 'dq', 'tau']:
869  self.connectLoggerPort(self.rh, pn)
870  # sensor logger ports
871  print(self.configurator_name + "sensor names for DataLogger")
872  for sen in self.sensors:
873  self.connectLoggerPort(self.rh, sen.name)
874  #
875  if self.kf != None:
876  self.connectLoggerPort(self.kf, 'rpy')
877  if self.sh != None:
878  self.connectLoggerPort(self.sh, 'qOut')
879  self.connectLoggerPort(self.sh, 'tqOut')
880  self.connectLoggerPort(self.sh, 'basePosOut')
881  self.connectLoggerPort(self.sh, 'baseRpyOut')
882  self.connectLoggerPort(self.sh, 'zmpOut')
883  if self.ic != None:
884  self.connectLoggerPort(self.ic, 'q')
885  if self.abc != None:
886  self.connectLoggerPort(self.abc, 'zmpOut')
887  self.connectLoggerPort(self.abc, 'baseTformOut')
888  self.connectLoggerPort(self.abc, 'q')
889  self.connectLoggerPort(self.abc, 'contactStates')
890  self.connectLoggerPort(self.abc, 'controlSwingSupportTime')
891  self.connectLoggerPort(self.abc, 'cogOut')
892  if self.st != None:
893  self.connectLoggerPort(self.st, 'zmp')
894  self.connectLoggerPort(self.st, 'originRefZmp')
895  self.connectLoggerPort(self.st, 'originRefCog')
896  self.connectLoggerPort(self.st, 'originRefCogVel')
897  self.connectLoggerPort(self.st, 'originNewZmp')
898  self.connectLoggerPort(self.st, 'originActZmp')
899  self.connectLoggerPort(self.st, 'originActCog')
900  self.connectLoggerPort(self.st, 'originActCogVel')
901  self.connectLoggerPort(self.st, 'allRefWrench')
902  self.connectLoggerPort(self.st, 'allEEComp')
903  self.connectLoggerPort(self.st, 'q')
904  self.connectLoggerPort(self.st, 'actBaseRpy')
905  self.connectLoggerPort(self.st, 'currentBasePos')
906  self.connectLoggerPort(self.st, 'currentBaseRpy')
907  self.connectLoggerPort(self.st, 'debugData')
908  if self.el != None:
909  self.connectLoggerPort(self.el, 'q')
910  if self.rh != None:
911  self.connectLoggerPort(self.rh, 'emergencySignal',
912  'emergencySignal')
913  self.connectLoggerPort(self.rh, 'servoState')
914  if self.simulation_mode:
915  self.connectLoggerPort(self.rh, 'WAIST')
916  for sen in filter(lambda x: x.type == "Force", self.sensors):
917  self.connectLoggerPort(self.sh, sen.name + "Out")
918  if self.rmfo != None:
919  for sen in filter(lambda x: x.type == "Force", self.sensors):
920  self.connectLoggerPort(self.rmfo, "off_"+sen.name)
921  if self.rfu != None:
922  for sen in filter(lambda x: x.type == "Force", self.sensors):
923  self.connectLoggerPort(self.rfu, "ref_"+sen.name+"Out")
924  if self.octd != None:
925  self.connectLoggerPort(self.octd, "octdData")
926  self.log_svc.clear()
927  ## parallel running log process (outside from rtcd) for saving logs by emergency signal
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])
932 
933  def waitForRTCManager(self, managerhost=nshost):
934  '''!@brief
935  Wait for RTC manager.
936 
937  @param managerhost str: name of host computer that manager is running
938  '''
939  self.ms = None
940  while self.ms == None:
941  time.sleep(1)
942  if managerhost == "localhost":
943  managerhost = socket.gethostname()
944  self.ms = rtm.findRTCmanager(managerhost)
945  print(self.configurator_name + "wait for RTCmanager : " + str(managerhost))
946 
947  def waitForRobotHardware(self, robotname="Robot"):
948  '''!@brief
949  Wait for RobotHardware is exists and activated.
950 
951  @param robotname str: name of RobotHardware component.
952  '''
953  self.rh = None
954  timeout_count = 0
955  # wait for simulator or RobotHardware setup which sometime takes a long time
956  while self.rh == None and timeout_count < 10: # <- time out limit
957  if timeout_count > 0: # do not sleep initial loop
958  time.sleep(1);
959  self.rh = rtm.findRTC("RobotHardware0")
960  if not self.rh:
961  self.rh = rtm.findRTC(robotname)
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: # just in case rh is not ready...
964  self.rh = None
965  timeout_count += 1
966  if not self.rh:
967  print(self.configurator_name + "Could not find " + robotname)
968  if self.ms:
969  print(self.configurator_name + "Candidates are .... " + str([x.name() for x in self.ms.get_components()]))
970  print(self.configurator_name + "Exitting.... " + robotname)
971  exit(1)
972 
973  print(self.configurator_name + "findComps -> %s : %s isActive? = %s " % (self.rh.name(), self.rh, self.rh.isActive()))
974 
976  '''!@brief
977  Check if this is running as simulation
978  '''
979  # distinguish real robot from simulation by check "HG/PD controller" ( > 315.3.0)
980  # distinguish real robot from simulation by using "servoState" port (<= 315.3.0)
981  self.hgc = findRTC("HGcontroller0")
982  self.pdc = findRTC("PDcontroller0")
983  if self.hgc or self.pdc:
984  self.simulation_mode = True
985  else:
986  self.simulation_mode = False
987 
988  if rtm.findPort(self.rh.ref, "servoState"): # for RobotHadware <= 315.3.0, which does not have service port
989  self.rh_svc = narrow(self.rh.service("service0"), "RobotHardwareService")
990  self.ep_svc = narrow(self.rh.ec, "ExecutionProfileService")
991 
992  print(self.configurator_name + "simulation_mode : %s" % self.simulation_mode)
993 
994  def waitForRTCManagerAndRoboHardware(self, robotname="Robot", managerhost=nshost):
995  print("\033[93m%s waitForRTCManagerAndRoboHardware has renamed to " % self.configurator_name + \
996  "waitForRTCManagerAndRoboHardware: Please update your code\033[0m")
997  return self.waitForRTCManagerAndRobotHardware(robotname=robotname, managerhost=managerhost)
998 
999  def waitForRTCManagerAndRobotHardware(self, robotname="Robot", managerhost=nshost):
1000  '''!@brief
1001  Wait for both RTC Manager (waitForRTCManager()) and RobotHardware (waitForRobotHardware())
1002 
1003  @param managerhost str: name of host computer that manager is running
1004  @param robotname str: name of RobotHardware component.
1005  '''
1006  self.waitForRTCManager(managerhost)
1007  self.waitForRobotHardware(robotname)
1008  self.checkSimulationMode()
1009 
1010  def findModelLoader(self):
1011  '''!@brief
1012  Try to find ModelLoader
1013  '''
1014  try:
1015  return rtm.findObject("ModelLoader")
1016  except:
1017  return None
1018 
1020  '''!@brief
1021  Wait for ModelLoader.
1022  '''
1023  while self.findModelLoader() == None: # seq uses modelloader
1024  print(self.configurator_name + "wait for ModelLoader")
1025  time.sleep(3)
1026 
1027  def setSelfGroups(self):
1028  '''!@brief
1029  Set to the hrpsys.SequencePlayer the groups of links and joints that
1030  are statically defined as member variables (Groups) within this class.
1031  '''
1032  for item in self.Groups:
1033  self.seq_svc.addJointGroup(item[0], item[1])
1034 
1035  # #
1036  # # service interface for RTC component
1037  # #
1038  def goActual(self):
1039  '''!@brief
1040  Adjust commanded values to the angles in the physical state
1041  by calling StateHolder::goActual.
1042 
1043  This needs to be run BEFORE servos are turned on.
1044  '''
1045  self.sh_svc.goActual()
1046 
1047  def setJointAngle(self, jname, angle, tm):
1048  '''!@brief
1049  Set angle to the given joint.
1050  \verbatim
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.
1058  \endverbatim
1059 
1060  @param jname str: name of joint
1061  @param angle float: In degree.
1062  @param tm float: Time to complete.
1063  @rtype bool
1064  @return False upon any problem during execution.
1065  '''
1066  radangle = angle / 180.0 * math.pi
1067  return self.seq_svc.setJointAngle(jname, radangle, tm)
1068 
1069  def setJointAngles(self, angles, tm):
1070  '''!@brief
1071  Set all joint angles.
1072  \verbatim
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.
1077  \endverbatim
1078  @param angles list of float: In degree.
1079  @param tm float: Time to complete.
1080  @rtype bool
1081  @return False upon any problem during execution.
1082  '''
1083  ret = []
1084  for angle in angles:
1085  ret.append(angle / 180.0 * math.pi)
1086  return self.seq_svc.setJointAngles(ret, tm)
1087 
1088  def setJointAnglesOfGroup(self, gname, pose, tm, wait=True):
1089  '''!@brief
1090  Set the joint angles to aim. By default it waits interpolation to be
1091  over.
1092 
1093  \verbatim
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.
1098  \endverbatim
1099 
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.
1105  @rtype bool
1106  @return False upon any problem during execution.
1107  '''
1108  angles = [x / 180.0 * math.pi for x in pose]
1109  ret = self.seq_svc.setJointAnglesOfGroup(gname, angles, tm)
1110  if wait:
1111  self.waitInterpolationOfGroup(gname)
1112  return ret
1113 
1114  def setJointAnglesSequence(self, angless, tms):
1115  '''!@brief
1116  Set all joint angles. len(angless) should be equal to len(tms).
1117  \verbatim
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.
1122  \endverbatim
1123  @param sequential list of angles in float: In rad
1124  @param tm sequential list of time in float: Time to complete, In Second
1125  @rtype bool
1126  @return False upon any problem during execution.
1127  '''
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)
1132 
1133  def setJointAnglesSequenceOfGroup(self, gname, angless, tms):
1134  '''!@brief
1135  Set all joint angles.
1136  \verbatim
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.
1141  \endverbatim
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
1145  @rtype bool
1146  @return False upon any problem during execution.
1147  '''
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)
1152 
1153  def loadPattern(self, fname, tm):
1154  '''!@brief
1155  Load a pattern file that is created offline.
1156 
1157  Format of the pattern file:
1158  - example format:
1159  \verbatim
1160  t0 j0 j1 j2...jn
1161  t1 j0 j1 j2...jn
1162  :
1163  tn j0 j1 j2...jn
1164  \endverbatim
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.
1169 
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.
1173  '''
1174  fname = self.parseUrl(fname)
1175  return self.seq_svc.loadPattern(fname, tm)
1176 
1178  '''!@brief
1179  Lets SequencePlayer wait until the movement currently happening to
1180  finish.
1181  '''
1182  self.seq_svc.waitInterpolation()
1183 
1184  def waitInterpolationOfGroup(self, gname):
1185  '''!@brief
1186  Lets SequencePlayer wait until the movement currently happening to
1187  finish.
1188 
1189  @see: SequencePlayer.waitInterpolationOfGroup
1190  @see: http://wiki.ros.org/joint_trajectory_action. This method
1191  corresponds to JointTrajectoryGoal in ROS.
1192 
1193  @param gname str: Name of the joint group.
1194  '''
1195  self.seq_svc.waitInterpolationOfGroup(gname)
1196 
1197  def setInterpolationMode(self, mode):
1198  '''!@brief
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
1202  '''
1203  return self.seq_svc.setInterpolationMode(mode)
1204 
1205  def getJointAngles(self):
1206  '''!@brief
1207  Returns the commanded joint angle values.
1208 
1209  @see: HrpsysConfigurator.getJointAngles
1210 
1211  Note that it's not the physical state of the robot's joints, which
1212  can be obtained by getActualState().angle.
1213 
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, ..).
1216  '''
1217  return [x * 180.0 / math.pi for x in self.sh_svc.getCommand().jointRefs]
1218 
1219  def getCurrentPose(self, lname=None, frame_name=None):
1220  '''!@brief
1221  Returns the current physical pose of the specified joint in the joint space.
1222  cf. getReferencePose that returns commanded value.
1223 
1224  eg.
1225  \verbatim
1226  IN: robot.getCurrentPose('LARM_JOINT5')
1227  OUT: [-0.0017702356144599085,
1228  0.00019034630541264752,
1229  -0.9999984150158207,
1230  0.32556275164378523,
1231  0.00012155879975329215,
1232  0.9999999745367515,
1233  0.0001901314142046251,
1234  0.18236394191140365,
1235  0.9999984257434246,
1236  -0.00012122202968358842,
1237  -0.001770258707652326,
1238  0.07462472659364472,
1239  0.0,
1240  0.0,
1241  0.0,
1242  1.0]
1243  \endverbatim
1244 
1245  @type lname: str
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:
1251  \verbatim
1252  [a11, a12, a13, x,
1253  a21, a22, a23, y,
1254  a31, a32, a33, z,
1255  0, 0, 0, 1]
1256  \endverbatim
1257  '''
1258  if not lname:
1259  for item in self.Groups:
1260  eef_name = item[1][-1]
1261  print("{}: {}".format(eef_name, self.getCurrentPose(eef_name)))
1262  raise RuntimeError("need to specify joint name")
1263  if frame_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)
1268  if not pose[0]:
1269  raise RuntimeError("Could not find reference : " + lname)
1270  return pose[1].data
1271 
1272  def getCurrentPosition(self, lname=None, frame_name=None):
1273  '''!@brief
1274  Returns the current physical position of the specified joint in Cartesian space.
1275  cf. getReferencePosition that returns commanded value.
1276 
1277  eg.
1278  \verbatim
1279  robot.getCurrentPosition('LARM_JOINT5')
1280  [0.325, 0.182, 0.074]
1281  \endverbatim
1282 
1283  @type lname: str
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.
1288  '''
1289  if not lname:
1290  for item in self.Groups:
1291  eef_name = item[1][-1]
1292  print("{}: {}".format(eef_name, self.getCurrentPosition(eef_name)))
1293  raise RuntimeError("need to specify joint name")
1294  pose = self.getCurrentPose(lname, frame_name)
1295  return [pose[3], pose[7], pose[11]]
1296 
1297  def getCurrentRotation(self, lname, frame_name=None):
1298  '''!@brief
1299  Returns the current physical rotation of the specified joint.
1300  cf. getReferenceRotation that returns commanded value.
1301 
1302  @type lname: str
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,
1307  that is:
1308  \verbatim
1309  [[a11, a12, a13],
1310  [a21, a22, a23],
1311  [a31, a32, a33]]
1312  \endverbatim
1313  '''
1314  if not lname:
1315  for item in self.Groups:
1316  eef_name = item[1][-1]
1317  print("{}: {}".format(eef_name, self.getCurrentRotation(eef_name)))
1318  raise RuntimeError("need to specify joint name")
1319  pose = self.getCurrentPose(lname, frame_name)
1320  return [pose[0:3], pose[4:7], pose[8:11]]
1321 
1322  def getCurrentRPY(self, lname, frame_name=None):
1323  '''!@brief
1324  Returns the current physical rotation in RPY of the specified joint.
1325  cf. getReferenceRPY that returns commanded value.
1326 
1327  @type lname: str
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.
1332  '''
1333  if not lname:
1334  for item in self.Groups:
1335  eef_name = item[1][-1]
1336  print("{}: {}".format(eef_name, self.getCurrentRPY(eef_name)))
1337  raise RuntimeError("need to specify joint name")
1338  return euler_from_matrix(self.getCurrentRotation(lname), 'sxyz')
1339 
1340  def getReferencePose(self, lname, frame_name=None):
1341  '''!@brief
1342  Returns the current commanded pose of the specified joint in the joint space.
1343  cf. getCurrentPose that returns physical pose.
1344 
1345  @type lname: str
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:
1351  \verbatim
1352  [a11, a12, a13, x,
1353  a21, a22, a23, y,
1354  a31, a32, a33, z,
1355  0, 0, 0, 1]
1356  \endverbatim
1357  '''
1358  if not lname:
1359  for item in self.Groups:
1360  eef_name = item[1][-1]
1361  print("{}: {}".format(eef_name, self.getReferencePose(eef_name)))
1362  raise RuntimeError("need to specify joint name")
1363  if frame_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)
1368  if not pose[0]:
1369  raise RuntimeError("Could not find reference : " + lname)
1370  return pose[1].data
1371 
1372  def getReferencePosition(self, lname, frame_name=None):
1373  '''!@brief
1374  Returns the current commanded position of the specified joint in Cartesian space.
1375  cf. getCurrentPosition that returns physical value.
1376 
1377  @type lname: str
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, ..).
1383  '''
1384  if not lname:
1385  for item in self.Groups:
1386  eef_name = item[1][-1]
1387  print("{}: {}".format(eef_name, self.getReferencePosition(eef_name)))
1388  raise RuntimeError("need to specify joint name")
1389  pose = self.getReferencePose(lname, frame_name)
1390  return [pose[3], pose[7], pose[11]]
1391 
1392  def getReferenceRotation(self, lname, frame_name=None):
1393  '''!@brief
1394  Returns the current commanded rotation of the specified joint.
1395  cf. getCurrentRotation that returns physical value.
1396 
1397  @type lname: str
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,
1402  that is:
1403  \verbatim
1404  [[a11, a12, a13],
1405  [a21, a22, a23],
1406  [a31, a32, a33]]
1407  \endverbatim
1408  '''
1409  if not lname:
1410  for item in self.Groups:
1411  eef_name = item[1][-1]
1412  print("{}: {}".format(eef_name, self.getReferencePotation(eef_name)))
1413  raise RuntimeError("need to specify joint name")
1414  pose = self.getReferencePose(lname, frame_name)
1415  return [pose[0:3], pose[4:7], pose[8:11]]
1416 
1417  def getReferenceRPY(self, lname, frame_name=None):
1418  '''!@brief
1419  Returns the current commanded rotation in RPY of the specified joint.
1420  cf. getCurrentRPY that returns physical value.
1421 
1422  @type lname: str
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.
1427  '''
1428  if not lname:
1429  for item in self.Groups:
1430  eef_name = item[1][-1]
1431  print("{}: {}".format(eef_name, self.getReferenceRPY(eef_name)))
1432  raise RuntimeError("need to specify joint name")
1433  return euler_from_matrix(self.getReferenceRotation(lname, frame_name), 'sxyz')
1434 
1435  def setTargetPose(self, gname, pos, rpy, tm, frame_name=None):
1436  '''!@brief
1437  Move the end-effector to the given absolute pose.
1438  All d* arguments are in meter.
1439 
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
1446  references to.
1447  @return bool: False if unreachable.
1448  '''
1449  print(gname, frame_name, pos, rpy, tm)
1450  if frame_name:
1451  gname = gname + ':' + frame_name
1452  result = self.seq_svc.setTargetPose(gname, pos, rpy, tm)
1453  if not result:
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.")
1458  return result
1459 
1460  def setTargetPoseRelative(self, gname, eename, dx=0, dy=0, dz=0,
1461 dr=0, dp=0, dw=0, tm=10, wait=True):
1462  '''!@brief
1463  Move the end-effector's location relative to its current pose.
1464 
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.
1468 
1469  For d*, distance arguments are in meter while rotations are in degree.
1470 
1471  Example usage: The following moves RARM_JOINT5 joint 0.1mm forward
1472  within 0.1sec.
1473  \verbatim
1474  robot.setTargetPoseRelative('rarm', 'RARM_JOINT5', dx=0.0001, tm=0.1)
1475  \endverbatim
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.
1489  '''
1490  self.waitInterpolationOfGroup(gname)
1491  # curPose = self.getCurrentPose(eename)
1492  posRef = None
1493  rpyRef = None
1494  tds = self.getCurrentPose(eename)
1495  if tds:
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]))
1500  rpyRef = euler_from_matrix(matRef)
1501  print(posRef, rpyRef)
1502  ret = self.setTargetPose(gname, list(posRef), list(rpyRef), tm)
1503  if ret and wait:
1504  self.waitInterpolationOfGroup(gname)
1505  return ret
1506  return False
1507 
1508  def clear(self):
1509  '''!@brief
1510  Clears the Sequencer's current operation. Works for joint groups too.
1511  @see HrpsysConfigurator.clear
1512 
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
1515  '''
1516  self.seq_svc.clear()
1517 
1518  def clearOfGroup(self, gname, tm=0.0):
1519  '''!@brief
1520  Clears the Sequencer's current operation for joint groups.
1521  '''
1522  self.seq_svc.clearOfGroup(gname, tm)
1523 
1524  def saveLog(self, fname='sample'):
1525  '''!@brief
1526  Save log to the given file name
1527 
1528  @param fname str: name of the file
1529  '''
1530  self.log_svc.save(fname)
1531  print(self.configurator_name + "saved data to " + fname)
1532 
1533  def clearLog(self):
1534  '''!@brief
1535  Clear logger's buffer
1536  '''
1537  self.log_svc.clear()
1538 
1539  def setMaxLogLength(self, length):
1540  '''!@brief
1541  Set logger's buffer
1542  @param length int: length of log, if the system runs at 500hz and you want to store 2min, set 2*60*500.
1543  '''
1544  self.log_svc.maxLength(length)
1545 
1547  '''!@brief
1548  Returns the length of digital input port
1549  '''
1550  return self.rh_svc.lengthDigitalInput()
1551 
1553  '''!@brief
1554  Returns the length of digital output port
1555  '''
1556  return self.rh_svc.lengthDigitalOutput()
1557 
1558  def writeDigitalOutput(self, dout):
1559  '''!@brief
1560  Using writeDigitalOutputWithMask is recommended for the less data
1561  transport.
1562 
1563  @param dout list of int: List of bits, length of 32 bits where elements are
1564  0 or 1.
1565 
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.
1569  '''
1570  if self.simulation_mode:
1571  return True
1572  doutBitLength = self.lengthDigitalOutput() * 8
1573  if len(dout) < doutBitLength:
1574  for i in range(doutBitLength - len(dout)):
1575  dout.append(0)
1576  outStr = ''
1577  for i in range(0, len(dout), 8):
1578  oneChar = 0
1579  for j in range(8):
1580  if dout[i + j]:
1581  oneChar += 1 << j
1582  outStr = outStr + chr(oneChar)
1583 
1584  # octet sequences are mapped to strings in omniorbpy
1585  return self.rh_svc.writeDigitalOutput(outStr)
1586 
1587  def writeDigitalOutputWithMask(self, dout, mask):
1588  '''!@brief
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
1591  evaluated.
1592 
1593  Example:
1594  \verbatim
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]
1600 
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]
1606 
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]
1612  \endverbatim
1613  @param dout list of int: List of bits, length of 32 bits where elements are
1614  0 or 1.
1615  @param mask list of int: List of masking bits, length of 32 bits where elements are
1616  0 or 1.
1617  @return bool: RobotHardware.writeDigitalOutput returns True if writable. False otherwise.
1618  '''
1619  if self.simulation_mode:
1620  return True
1621  doutBitLength = self.lengthDigitalOutput() * 8
1622  if len(dout) < doutBitLength and \
1623  len(mask) < doutBitLength and \
1624  len(dout) == len(mask):
1625  for i in range(doutBitLength - len(dout)):
1626  dout.append(0)
1627  mask.append(0)
1628  outStr = ''
1629  outMsk = ''
1630  for i in range(0, len(dout), 8):
1631  oneChar = 0
1632  oneMask = 0
1633  for j in range(8):
1634  if dout[i + j]:
1635  oneChar += 1 << j
1636  if mask[i + j]:
1637  oneMask += 1 << j
1638  outStr = outStr + chr(oneChar)
1639  outMsk = outMsk + chr(oneMask)
1640 
1641  # octet sequences are mapped to strings in omniorbpy
1642  return self.rh_svc.writeDigitalOutputWithMask(outStr, outMsk)
1643 
1644  def readDigitalInput(self):
1645  '''!@brief
1646  Read data from Digital Input
1647  @see: HrpsysConfigurator.readDigitalInput
1648 
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.
1653 
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'
1657  '''
1658  if self.simulation_mode:
1659  return []
1660  ret, din = self.rh_svc.readDigitalInput()
1661  retList = []
1662  for item in din:
1663  for i in range(8):
1664  if (ord(item) >> i) & 1:
1665  retList.append(1)
1666  else:
1667  retList.append(0)
1668  return retList
1669 
1671  '''!@brief
1672  Read data from Digital Output
1673 
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.
1676 
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'
1680 
1681  @author Hajime Saito (\@emijah)
1682  @return list of int: List of the values in digital input register. Range: 0 or 1.
1683  '''
1684  ret, dout = self.rh_svc.readDigitalOutput()
1685  retList = []
1686  for item in dout:
1687  for i in range(8):
1688  if (ord(item) >> i) & 1:
1689  retList.append(1)
1690  else:
1691  retList.append(0)
1692  return retList
1693 
1694  def getActualState(self):
1695  '''!@brief
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
1698  RobotHardware.idl
1699  (found at https://github.com/fkanehiro/hrpsys-base/blob/3fd7671de5129101a4ade3f98e2eac39fd6b26c0/idl/RobotHardwareService.idl#L32_L57 as of version 315.11.0)
1700  \verbatim
1701  /**
1702  * @brief status of the robot
1703  */
1704  struct RobotState
1705  {
1706  DblSequence angle; ///< current joint angles[rad]
1707  DblSequence command;///< reference joint angles[rad]
1708  DblSequence torque; ///< joint torques[Nm]
1709  /**
1710  * @brief servo statuses(32bit+extra states)
1711  *
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
1716  * 19-23: unused
1717  * 24-31: driver temperature (deg)
1718  */
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]
1725  };
1726  \endverbatim
1727  '''
1728  return self.rh_svc.getStatus()
1729 
1730  def isCalibDone(self):
1731  '''!@brief
1732  Check whether joints have been calibrated.
1733  @return bool: True if all joints are calibrated
1734  '''
1735  if self.simulation_mode:
1736  return True
1737  else:
1738  rstt = self.rh_svc.getStatus()
1739  for item in rstt.servoState:
1740  if not item[0] & 1:
1741  return False
1742  return True
1743 
1744  def isServoOn(self, jname='any'):
1745  '''!@brief
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
1752  '''
1753  if self.simulation_mode:
1754  return True
1755  else:
1756  s_s = self.getActualState().servoState
1757  if jname.lower() == 'any' or jname.lower() == 'all':
1758  for s in s_s:
1759  # print(self.configurator_name, 's = ', s)
1760  if (s[0] & 2) == 0:
1761  return False
1762  return True
1763  elif jname.lower() == 'some':
1764  for s in s_s:
1765  # print(self.configurator_name, 's = ', s)
1766  if (s[0] & 2) != 0:
1767  return True
1768  return False
1769  else:
1770  jid = eval('self.' + jname)
1771  print(self.configurator_name + s_s[jid])
1772  if s_s[jid][0] & 1 == 0:
1773  return False
1774  else:
1775  return True
1776 
1777  def flat2Groups(self, flatList):
1778  '''!@brief
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.
1782  '''
1783  retList = []
1784  index = 0
1785  for group in self.Groups:
1786  joint_num = len(group[1])
1787  retList.append(flatList[index: index + joint_num])
1788  index += joint_num
1789  return retList
1790 
1791  def servoOn(self, jname='all', destroy=1, tm=3):
1792  '''!@brief
1793  Turn on servos.
1794  Joints need to be calibrated (otherwise error returns).
1795 
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.
1800  '''
1801  # check joints are calibrated
1802  if not self.isCalibDone():
1803  waitInputConfirm('!! Calibrate Encoders with checkEncoders first !!\n\n')
1804  return -1
1805 
1806  # check servo state
1807  if self.isServoOn():
1808  return 1
1809 
1810  # check jname is acceptable
1811  if jname == '':
1812  jname = 'all'
1813 
1814  try:
1815  r = waitInputConfirm(\
1816  '!! Robot Motion Warning (SERVO_ON) !!\n\n'
1817  'Confirm RELAY switched ON\n'
1818  'Push [OK] to switch servo ON(%s).' % (jname))
1819  if not r:
1820  print(self.configurator_name, 'servo on: canceled')
1821  return 0
1822  except: # ths needs to change
1823  self.rh_svc.power('all', SWITCH_OFF)
1824  raise
1825 
1826  try:
1827  self.goActual()
1828  time.sleep(0.1)
1829  self.rh_svc.servo(jname, SWITCH_ON)
1830  time.sleep(2)
1831  if not self.isServoOn(jname):
1832  print(self.configurator_name + 'servo on failed.')
1833  raise
1834  except:
1835  print(self.configurator_name + 'exception occured')
1836 
1837  return 1
1838 
1839  def servoOff(self, jname='all', wait=True):
1840  '''!@brief
1841  Turn off servos.
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.
1846  '''
1847  # do nothing for simulation
1848  if self.simulation_mode:
1849  print(self.configurator_name + 'omit servo off')
1850  return 0
1851 
1852  print('Turn off Hand Servo')
1853  if self.sc_svc:
1854  self.sc_svc.servoOff()
1855  # if the servos aren't on switch power off
1856  if not self.isServoOn(jname):
1857  if jname.lower() == 'all':
1858  self.rh_svc.power('all', SWITCH_OFF)
1859  return 1
1860 
1861  # if jname is not set properly set to all -> is this safe?
1862  if jname == '':
1863  jname = 'all'
1864 
1865  if wait:
1866  r = waitInputConfirm(
1867  '!! Robot Motion Warning (Servo OFF)!!\n\n'
1868  'Push [OK] to servo OFF (%s).' % (jname)) # :
1869  if not r:
1870  print(self.configurator_name, 'servo off: canceled')
1871  return 2
1872  try:
1873  self.rh_svc.servo('all', SWITCH_OFF)
1874  time.sleep(0.2)
1875  if jname == 'all':
1876  self.rh_svc.power('all', SWITCH_OFF)
1877 
1878  # turn off hand motors
1879  print('Turn off Hand Servo')
1880  if self.sc_svc:
1881  self.sc_svc.servoOff()
1882 
1883  return 2
1884  except:
1885  print(self.configurator_name + 'servo off: communication error')
1886  return -1
1887 
1888  def checkEncoders(self, jname='all', option=''):
1889  '''!@brief
1890  Run the encoder checking sequence for specified joints,
1891  run goActual and turn on servos.
1892 
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.
1896  '''
1897  if self.isServoOn():
1898  waitInputConfirm('Servo must be off for calibration')
1899  return
1900  # do not check encoders twice
1901  elif self.isCalibDone():
1902  waitInputConfirm('System has been calibrated')
1903  return
1904 
1905  self.rh_svc.power('all', SWITCH_ON)
1906  msg = '!! Robot Motion Warning !!\n'\
1907  'Turn Relay ON.\n'\
1908  'Then Push [OK] to '
1909  if option == '-overwrite':
1910  msg = msg + 'calibrate(OVERWRITE MODE) '
1911  else:
1912  msg = msg + 'check '
1913 
1914  if jname == 'all':
1915  msg = msg + 'the Encoders of all.'
1916  else:
1917  msg = msg + 'the Encoder of the Joint "' + jname + '".'
1918 
1919  try:
1920  waitInputConfirm(msg)
1921  except:
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)
1925  return 0
1926 
1927  print(self.configurator_name + 'calib-joint ' + jname + ' ' + option)
1928  self.rh_svc.initializeJointAngle(jname, option)
1929  print(self.configurator_name + 'done')
1930  self.rh_svc.power('all', SWITCH_OFF)
1931  self.goActual()
1932  time.sleep(0.1)
1933  self.rh_svc.servo(jname, SWITCH_ON)
1934 
1935  # turn on hand motors
1936  print('Turn on Hand Servo')
1937  if self.sc_svc:
1938  self.sc_svc.servoOn()
1939 
1941  '''!@brief
1942  remove force sensor offset
1943  '''
1944  self.rh_svc.removeForceSensorOffset()
1945 
1946  def playPattern(self, jointangles, rpy, zmp, tm):
1947  '''!@brief
1948  Play motion pattern using a given trajectory that is represented by
1949  a list of joint angles, rpy, zmp and time.
1950 
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).
1959  @return bool:
1960  '''
1961  return self.seq_svc.playPattern(jointangles, rpy, zmp, tm)
1962 
1963  def playPatternOfGroup(self, gname, jointangles, tm):
1964  '''!@brief
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.
1968 
1969  Example:
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]],
1974  [3, 3, 10])
1975 
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:
1982 
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.
1985  :
1986  [am-0, am-1,...,am-n]] # mth path in the trajectory
1987  @type tm: [float]
1988  @param tm float: Sequence of the time values to complete the task,
1989  each element of which corresponds to a set of jointangles
1990  in the same order.
1991  @return bool:
1992  '''
1993  return self.seq_svc.playPatternOfGroup(gname, jointangles, tm)
1994 
1996  '''!@brief
1997  Set joint angles for sensor calibration.
1998  Please override joint angles to avoid self collision.
1999  '''
2000  self.setJointAngles([0]*len(self.rh_svc.getStatus().servoState), 4.0)
2001  self.waitInterpolation()
2002 
2004  '''!@brief
2005  Calibrate inertia sensor
2006  '''
2007  self.rh_svc.calibrateInertiaSensor()
2008 
2010  '''!@brief
2011  Calibrate inertia sensor with dialog and setting calibration pose
2012  '''
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
2022  self.calibrateInertiaSensor()
2023  r = waitInputConfirm (
2024  '!! Put the robot up!!\n\n'
2025  'Push [OK] to the next step.')
2026  if not r: return False
2027  return True
2028 
2029  # #
2030  # # service interface for Unstable RTC component
2031  # #
2032  def startAutoBalancer(self, limbs=None):
2033  '''!@brief
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.
2038  '''
2039  if limbs==None:
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"]
2042  else:
2043  limbs=["rleg", "lleg"]
2044  self.abc_svc.startAutoBalancer(limbs)
2045 
2046  def stopAutoBalancer(self):
2047  '''!@brief
2048  Stop AutoBalancer mode
2049  '''
2050  self.abc_svc.stopAutoBalancer()
2051 
2052  def startStabilizer(self):
2053  '''!@brief
2054  Start Stabilzier mode
2055  '''
2056  self.st_svc.startStabilizer()
2057 
2058  def stopStabilizer(self):
2059  '''!@brief
2060  Stop Stabilzier mode
2061  '''
2062  self.st_svc.stopStabilizer()
2063 
2064  def startImpedance_315_4(self, arm,
2065  M_p = 100.0,
2066  D_p = 100.0,
2067  K_p = 100.0,
2068  M_r = 100.0,
2069  D_r = 2000.0,
2070  K_r = 2000.0,
2071  force_gain = [1, 1, 1],
2072  moment_gain = [0, 0, 0],
2073  sr_gain = 1.0,
2074  avoid_gain = 0.0,
2075  reference_gain = 0.0,
2076  manipulability_limit = 0.1,
2077  controller_mode = None,
2078  ik_optional_weight_vector = None):
2079  '''!@brief
2080  start impedance mode
2081 
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).
2085  '''
2086  r, p = self.ic_svc.getImpedanceControllerParam(arm)
2087  if not r:
2088  print('{}, Failt to getImpedanceControllerParam({})'.format(self.configurator_name, arm))
2089  return False
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)
2106 
2107  def stopImpedance_315_4(self, arm):
2108  '''!@brief
2109  stop impedance mode
2110  '''
2111  return self.ic_svc.stopImpedanceController(arm)
2112 
2113  def startImpedance(self, arm, **kwargs):
2114  '''!@brief
2115  Enable the ImpedanceController RT component.
2116  This method internally calls startImpedance-*, hrpsys version-specific method.
2117 
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:
2123 
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:
2125 
2126  self.seq_svc.setWrenches([0, 0, 0, 0, 0, 0,
2127  fx, fy, fz, tx, ty, tz,
2128  0, 0, 0, 0, 0, 0,
2129  0, 0, 0, 0, 0, 0,])
2130 
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.
2133 
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.
2138  '''
2139  if self.hrpsys_version and StrictVersion(self.hrpsys_version) < StrictVersion('315.2.0'):
2140  print(self.configurator_name + '\033[31mstartImpedance: Try to connect unsupported RTC' + str(self.hrpsys_version) + '\033[0m')
2141  else:
2142  self.startImpedance_315_4(arm, **kwargs)
2143 
2144  def stopImpedance(self, arm):
2145  if self.hrpsys_version and StrictVersion(self.hrpsys_version) < StrictVersion('315.2.0'):
2146  print(self.configurator_name + '\033[31mstopImpedance: Try to connect unsupported RTC' + str(self.hrpsys_version) + '\033[0m')
2147  else:
2148  self.stopImpedance_315_4(arm)
2149 
2150  def startDefaultUnstableControllers (self, ic_limbs=[], abc_limbs=[]):
2151  '''!@brief
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".
2155  By default,
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.
2159  Use cases:
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.
2164  '''
2165  print(self.configurator_name + "Start Default Unstable Controllers")
2166  # Check robot setting
2167  is_legged_robot = map(lambda x: x[0], filter(lambda x : re.match(".*leg", x[0]), self.Groups))
2168  # Select all arms in "Groups" for impedance as a default setting
2169  if not ic_limbs:
2170  ic_limbs = map(lambda x: x[0], filter(lambda x : re.match(".*(arm)", x[0]), self.Groups))
2171  # Select all arms/legs in "Groups" for autobalancer as a default setting
2172  if not abc_limbs:
2173  abc_limbs = map(lambda x: x[0], filter(lambda x : re.match(".*(leg|arm)", x[0]), self.Groups))
2174  # Start controllers
2175  for limb in ic_limbs:
2176  self.ic_svc.startImpedanceControllerNoWait(limb)
2177  if is_legged_robot:
2178  self.startAutoBalancer(abc_limbs)
2179  self.startStabilizer()
2180  for limb in ic_limbs:
2181  self.ic_svc.waitImpedanceControllerTransition(limb)
2182  # Print
2183  if is_legged_robot:
2184  print(self.configurator_name + " Start AutoBalancer = "+str(abc_limbs))
2185  print(self.configurator_name + " Start Stabilizer")
2186  if len(ic_limbs) != 0:
2187  print(self.configurator_name + " Start ImpedanceController = "+str(ic_limbs))
2188 
2189  def stopDefaultUnstableControllers (self, ic_limbs=[]):
2190  '''!@brief
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().
2194  '''
2195  print(self.configurator_name + "Stop Default Unstable Controllers")
2196  # Check robot setting
2197  is_legged_robot = map(lambda x: x[0], filter(lambda x : re.match(".*leg", x[0]), self.Groups))
2198  # Select all arms in "Groups" for impedance as a default setting
2199  if not ic_limbs:
2200  ic_limbs = map(lambda x: x[0], filter(lambda x : re.match(".*(arm)", x[0]), self.Groups))
2201  # Stop controllers
2202  if is_legged_robot:
2203  self.stopStabilizer()
2204  for limb in ic_limbs:
2205  self.ic_svc.stopImpedanceControllerNoWait(limb)
2206  if is_legged_robot:
2207  self.stopAutoBalancer()
2208  for limb in ic_limbs:
2209  self.ic_svc.waitImpedanceControllerTransition(limb)
2210  # Print
2211  if is_legged_robot:
2212  print(self.configurator_name + " Stop AutoBalancer")
2213  print(self.configurator_name + " Stop Stabilizer")
2214  if len(ic_limbs) != 0:
2215  print(self.configurator_name + " Stop ImpedanceController = "+str(ic_limbs))
2216 
2217  def setFootSteps(self, footstep, overwrite_fs_idx = 0):
2218  '''!@brief
2219  setFootSteps
2220  @param footstep : FootstepSequence.
2221  @param overwrite_fs_idx : Index to be overwritten. overwrite_fs_idx is used only in walking.
2222  '''
2223  self.abc_svc.setFootSteps(footstep, overwrite_fs_idx)
2224 
2225  def setFootStepsWithParam(self, footstep, stepparams, overwrite_fs_idx = 0):
2226  '''!@brief
2227  setFootSteps
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.
2231  '''
2232  self.abc_svc.setFootStepsWithParam(footstep, stepparams, overwrite_fs_idx)
2233 
2234  def clearJointAngles(self):
2235  '''!@brief
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.
2238  @return bool
2239  '''
2240  return self.seq_svc.clearJointAngles()
2241 
2242  def clearJointAnglesOfGroup(self, gname):
2243  '''!@brief
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.
2247  @return bool
2248  '''
2249  return self.seq_svc.clearJointAnglesOfGroup(gname)
2250 
2251  def removeForceSensorOffsetRMFO(self, sensor_names=[], tm=8.0):
2252  '''!@brief
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
2257  '''
2258  return self.rmfo_svc.removeForceSensorOffset(sensor_names, tm)
2259 
2260  # ##
2261  # ## initialize
2262  # ##
2263 
2264  def init(self, robotname="Robot", url=""):
2265  '''!@brief
2266  Calls init from its superclass, which tries to connect RTCManager,
2267  looks for ModelLoader, and starts necessary RTC components. Also runs
2268  config, logger.
2269  Also internally calls setSelfGroups().
2270 
2271  @type robotname: str
2272  @type url: str
2273  '''
2274  print(self.configurator_name + "waiting ModelLoader")
2275  self.waitForModelLoader()
2276  print(self.configurator_name + "start hrpsys")
2277 
2278  print(self.configurator_name + "finding RTCManager and RobotHardware")
2279  self.waitForRTCManagerAndRobotHardware(robotname)
2280  self.sensors = self.getSensors(url)
2281 
2282  print(self.configurator_name + "creating components")
2283  self.createComps()
2284 
2285  print(self.configurator_name + "connecting components")
2286  self.connectComps()
2287 
2288  print(self.configurator_name + "activating components")
2289  self.activateComps()
2290 
2291  print(self.configurator_name + "setup logger")
2292  self.setupLogger()
2293 
2294  print(self.configurator_name + "setup joint groups")
2295  self.setSelfGroups()
2296 
2297  print(self.configurator_name + '\033[32minitialized successfully\033[0m')
2298 
2299  # set hrpsys_version
2300  try:
2301  self.hrpsys_version = self.fk.ref.get_component_profile().version
2302  except:
2303  print(self.configurator_name + '\033[34mCould not get hrpsys_version\033[0m')
2304 
2305  pass
2306 
2307  def __init__(self, cname="[hrpsys.py] "):
2308  initCORBA()
2309  self.configurator_name = cname
2310 
2311 
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])
2318  else:
2319  hcf.init()
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
Definition: jython/rtm.py:341
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 waitInputConfirm(msg)
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
Definition: jython/rtm.py:709
def startImpedance(self, arm, kwargs)
Enable the ImpedanceController RT component.
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&#39;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&#39;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&#39;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
Definition: jython/rtm.py:373
def clear(self)
Clears the Sequencer&#39;s current operation.
def findRTCmanager(hostname=None, rnc=None)
get RTCmanager
Definition: jython/rtm.py:321
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
Definition: jython/rtm.py:433
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
Definition: jython/rtm.py:308
def euler_matrix(ai, aj, ak, axes='sxyz')
def findPort(rtc, name)
get a port of RT component
Definition: jython/rtm.py:358
def getSensors(self, url)
Get list of sensors.
def clearOfGroup(self, gname, tm=0.0)
Clears the Sequencer&#39;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 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
Definition: jython/rtm.py:416
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
Definition: jython/rtm.py:272
def waitForModelLoader(self)
Wait for ModelLoader.
def getJointAngleControllerList(self)
Get list of controller list that need to control joint angles.


hrpsys
Author(s): AIST, Fumio Kanehiro
autogenerated on Thu May 6 2021 02:41:50