HandUnitDynamicSimulation.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of ArmarX.
3  *
4  * Copyright (C) 2013-2016, High Performance Humanoid Technologies (H2T), Karlsruhe Institute of Technology (KIT), all rights reserved.
5  *
6  * ArmarX is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  *
10  * ArmarX is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  *
18  * @package ArmarXCore::units
19  * @author Nikolaus Vahrenkamp (vahrenkamp at kit dot edu)
20  * @date 2014
21  * @copyright http://www.gnu.org/licenses/gpl-2.0.txt
22  * GNU General Public License
23  */
24 
25 
27 
28 #include <cmath>
29 
30 #include <Eigen/Geometry>
31 
32 #include <VirtualRobot/EndEffector/EndEffector.h>
33 #include <VirtualRobot/RobotConfig.h>
34 
35 #include <RobotAPI/interface/objectpose/ObjectPoseStorageInterface.h>
40 
45 
46 
47 using namespace armarx;
48 
50 {
51  ARMARX_INFO << "Init hand unit" << flush;
52  simulatorPrxName = getProperty<std::string>("SimulatorProxyName").getValue();
54 
55  kinematicUnitName = getProperty<std::string>("KinematicUnitName").getValue();
57 
58  robotStateComponentName = getProperty<std::string>("RobotStateComponentName").getValue();
60 
61  if (getProperty<bool>("UseLegacyWorkingMemory").getValue())
62  {
63  usingProxy("WorkingMemory");
64  }
65 }
66 
68 {
69  ARMARX_INFO << "Starting hand unit" << flush;
70  simulatorPrx = getProxy<SimulatorInterfacePrx>(simulatorPrxName);
71  ARMARX_INFO << "Using simulator proxy: " << simulatorPrxName << ":" << simulatorPrx << flush;
72 
73  kinematicUnitPrx = getProxy<KinematicUnitInterfacePrx>(kinematicUnitName);
74 
75  workingMemoryPrx = getProxy<memoryx::WorkingMemoryInterfacePrx>("WorkingMemory", false, "", false);
76  robotStateComponentPrx = getProxy<RobotStateComponentInterfacePrx>(robotStateComponentName);
77 }
78 
79 
81 {
82 
83 }
84 
85 
86 /*
87 void HandUnitDynamicSimulation::open(const Ice::Current &c)
88 {
89  ARMARX_INFO << "Open Hand: setting all hand joint value targets to zero" << flush;
90  NameValueMap targetJointAngles;
91 
92  // set all joints to zero
93 
94  std::map<std::string, float>::iterator it = handJoints.begin();
95  while (it != handJoints.end())
96  {
97  targetJointAngles[it->first] = 0.0f;
98  it++;
99  }
100  ARMARX_DEBUG << "targetJointAngles:" << targetJointAngles << flush;
101  simulatorPrx->begin_actuateRobotJointsPos(robotName,targetJointAngles);
102 }*/
103 
104 
106 {
107  auto defs = PropertyDefinitionsPtr(
109 
110  defs->optional(objectPoseStorageName, "cmp.ObjectPoseStorageName",
111  "Name of the object pose storage (only used if necessary).");
112 
113  return defs;
114 }
115 
116 
117 void HandUnitDynamicSimulation::setObjectGrasped(const std::string& objectName, const Ice::Current&)
118 {
119  ARMARX_INFO << "Object grasped " << objectName << flush;
120  graspedObject = objectName;
121 
122  // inform simulator
123  if (simulatorPrx)
124  {
125  ARMARX_INFO << "Simulator call objectGrasped: " << robotName << "," << tcpName << "," << objectName << flush;
126  simulatorPrx->objectGrasped(robotName, tcpName, objectName);
127  }
128  else
129  {
130  ARMARX_WARNING << "No Simulator..." << flush;
131  }
132 }
133 
134 void HandUnitDynamicSimulation::setObjectReleased(const std::string& objectName, const Ice::Current&)
135 {
136  ARMARX_INFO << "Object released " << objectName << flush;
137  graspedObject = "";
138 
139  // inform simulator
140  if (simulatorPrx)
141  {
142  simulatorPrx->objectReleased(robotName, tcpName, objectName);
143  }
144  else
145  {
146  ARMARX_WARNING << "No Simulator..." << flush;
147  }
148 }
149 
151 {
152  NameValueMap result;
153 
154  try
155  {
156  for (const auto& j : handJoints)
157  {
158  result[j.first] = simulatorPrx->getRobotJointAngle(robotName, j.first);
159  }
160  }
161  catch (...)
162  {
163  ARMARX_WARNING << "Could not get joint angles fvrom simulator...";
164  }
165 
166  return result;
167 }
168 
169 void armarx::HandUnitDynamicSimulation::setShape(const std::string& shapeName, const Ice::Current&)
170 {
171  std::string myShapeName = shapeName;
172  ARMARX_INFO << "Setting shape " << myShapeName;
173 
174  if (!eef)
175  {
176  ARMARX_WARNING << "No EEF";
177  return;
178  }
179 
180 
181  if (!eef->hasPreshape(myShapeName))
182  {
183  ARMARX_INFO << "Shape with name " << myShapeName << " not known in eef " << eef->getName() << ". Looking for partial match";
184 
185  bool foundMatch = false;
186 
187  for (const std::string& name : eef->getPreshapes())
188  {
189  if (name.find(myShapeName) != std::string::npos)
190  {
191  foundMatch = true;
192  myShapeName = name;
193  ARMARX_INFO << "Using matching shape: " << name;
194  break;
195  }
196  }
197 
198  if (!foundMatch)
199  {
200  ARMARX_WARNING << "No match found for " << myShapeName << " in eef " << eef->getName() << " available shapes: " << eef->getPreshapes();
201  return;
202  }
203  }
204 
205  VirtualRobot::RobotConfigPtr config = eef->getPreshape(myShapeName);
206  std::map < std::string, float > jointAngles = config->getRobotNodeJointValueMap();
207 
208  NameControlModeMap controlModes;
209 
210  for (std::pair<std::string, float> pair : jointAngles)
211  {
212  controlModes.insert(std::make_pair(pair.first, ePositionControl));
213  }
214 
215  kinematicUnitPrx->switchControlMode(controlModes);
216  kinematicUnitPrx->setJointAngles(jointAngles);
217 }
218 
219 
221  const std::string& shapeName, const std::string& objectInstanceName, const Ice::Current& c)
222 {
223  std::string myShapeName = shapeName;
224  ARMARX_INFO << "Setting shape " << myShapeName << " while checking for collision with " << objectInstanceName;
225 
226  if (!eef)
227  {
228  ARMARX_WARNING << "No EEF";
229  return;
230  }
231 
232  if (!eef->hasPreshape(myShapeName))
233  {
234  ARMARX_INFO << "Shape with name " << myShapeName << " not known in eef " << eef->getName() << ". Looking for partial match";
235 
236  bool foundMatch = false;
237  for (const std::string& name : eef->getPreshapes())
238  {
239  if (name.find(myShapeName) != std::string::npos)
240  {
241  foundMatch = true;
242  myShapeName = name;
243  ARMARX_INFO << "Using matching shape: " << name;
244  break;
245  }
246  }
247 
248  if (!foundMatch)
249  {
250  ARMARX_WARNING << "No match found for " << myShapeName << " in eef " << eef->getName() << " available shapes: " << eef->getPreshapes();
251  return;
252  }
253  }
254 
255  VirtualRobot::EndEffectorPtr endeffector = robot->getEndEffector(eef->getName());
256  ARMARX_CHECK_EQUAL(endeffector.get(), eef.get()); // Is this really always the same??
257 
258  auto loadFromObjectPoseStorage = [this, &objectInstanceName]() -> VirtualRobot::ManipulationObjectPtr
259  {
260  const armarx::ObjectID objectID(objectInstanceName);
261 
263  auto fetchObjectPose = [this, &objectID, &client]() -> std::optional<Eigen::Matrix4f>
264  {
265  getProxy(client.objectPoseStorage, objectPoseStorageName, false, "", false);
266  if (client.objectPoseStorage)
267  {
268  const objpose::ObjectPoseMap objectPoses = client.fetchObjectPosesAsMap();
269  if (auto it = objectPoses.find(objectID); it != objectPoses.end())
270  {
271  return it->second.objectPoseGlobal;
272  }
273  }
274  return std::nullopt;
275  };
276  if (auto objectPose = fetchObjectPose())
277  {
278  if (std::optional<armarx::ObjectInfo> info = client.getObjectFinder().findObject(objectID))
279  {
280  VirtualRobot::ManipulationObjectPtr object = client.getObjectFinder().loadManipulationObject(info);
281  object->setGlobalPose(objectPose.value());
282  return object;
283  }
284  }
285  return nullptr;
286  };
287 
288  auto loadFromWorkingMemory = [this, &objectInstanceName]() -> VirtualRobot::ManipulationObjectPtr
289  {
290  memoryx::ObjectInstancePtr objInstance =
291  memoryx::ObjectInstancePtr::dynamicCast(workingMemoryPrx->getObjectInstancesSegment()->getObjectInstanceByName(objectInstanceName));
292 
293  VirtualRobot::RobotPtr robot = RemoteRobot::createLocalCloneFromFile(robotStateComponentPrx, VirtualRobot::RobotIO::eCollisionModel);
294  RemoteRobot::synchronizeLocalClone(robot, robotStateComponentPrx);
295 
296  const std::string objectClassName = objInstance->getMostProbableClass();
297  // Assure complete ontology tree is in object classes segment
298  auto classes = workingMemoryPrx->getObjectClassesSegment()->addPriorClassWithSubclasses(objectClassName);
299  if (classes.empty())
300  {
301  ARMARX_WARNING << "Class '" << objectClassName << "' not found ";
302  return nullptr;
303  }
304 
305  memoryx::ObjectClassPtr objclass = memoryx::ObjectClassPtr::dynamicCast(
306  workingMemoryPrx->getObjectClassesSegment()->getEntityByName(objectClassName)->ice_clone());
307  ARMARX_CHECK_NOT_NULL(objclass);
308 
309  memoryx::GridFileManagerPtr fileManager(new memoryx::GridFileManager(workingMemoryPrx->getCommonStorage()));
311  objclass->addWrapper(new memoryx::EntityWrappers::SimoxObjectWrapper(fileManager));
312 
313  objInstance->setPose(objInstance->getPose()->toGlobal(robot));
314  simoxObject->updateFromEntity(objInstance);
315 
316  return simoxObject->getManipulationObject();
317  };
318 
319  VirtualRobot::ManipulationObjectPtr manipulationObject = nullptr;
320  if (not manipulationObject)
321  {
322  manipulationObject = loadFromObjectPoseStorage();
323  }
324  if (not manipulationObject and workingMemoryPrx)
325  {
326  manipulationObject = loadFromWorkingMemory();
327  }
328 
329  if (manipulationObject)
330  {
331  endeffector->closeActors(manipulationObject);
332 
333  const std::map<std::string, float> jointAngles = endeffector->getConfiguration()->getRobotNodeJointValueMap();
334 
335  NameControlModeMap controlModes;
336  for (const auto& [name, value] : jointAngles)
337  {
338  controlModes.emplace(name, ePositionControl);
339  }
340 
341  kinematicUnitPrx->switchControlMode(controlModes);
342  kinematicUnitPrx->setJointAngles(jointAngles);
343  }
344  else
345  {
346  ARMARX_WARNING << "Could not load object '" << objectInstanceName << "'. "
347  << "Cannot set shape '" << shapeName << "' with collision check. "
348  << "Setting shape '" << shapeName << "' without collision check instead.";
349  setShape(shapeName, c);
350  return;
351  }
352 }
353 
354 
356 {
357  NameControlModeMap controlModes;
358 
359  for (std::pair<std::string, float> pair : jointAngles)
360  {
361  controlModes.insert(std::make_pair(pair.first, ePositionControl));
362  }
363 
364  kinematicUnitPrx->switchControlMode(controlModes);
365  kinematicUnitPrx->setJointAngles(jointAngles);
366  simulatorPrx->actuateRobotJointsPos(getRobotNameFromHandUnitName(), handUnitJointsToRobotJoints(jointAngles));
367 }
368 
370 {
373  ARMARX_VERBOSE << joints;
374  std::map<std::string, std::vector<std::string>> conversion_dict;
375  conversion_dict["Fingers"] = {"Index", "Middle", "Ring", "Pinky"};
376  conversion_dict["Thumb"] = {"Thumb"};
377  auto robot_joints = armarx::NameValueMap();
378  std::string side = getHandSideFromHandUnitName();
379  for (const auto& joint : joints)
380  {
381  if (conversion_dict.find(joint.first) != conversion_dict.end())
382  {
383  auto correspondences = conversion_dict.at(joint.first);
384  for (const auto& correspondence : correspondences)
385  {
386  for (int i = 1; i < 4; i++)
387  {
388  std::stringstream joint_id;
389  joint_id << correspondence << " " << side << " " << i << " Joint";
390  robot_joints[joint_id.str()] = joint.second * M_PI_2;
391  }
392  }
393  } else
394  {
395  ARMARX_WARNING << "No corresponding finger joint found for " << joint.first;
396  }
397  }
398  return robot_joints;
399 }
400 
402 {
403  return armarx::split(robotName, " ").front();
404 }
405 
407 {
408  auto side = armarx::split(robotName, " ").back();
409  std::stringstream stream;
410  stream << side.front();
411  return stream.str();
412 }
armarx::HandUnitDynamicSimulation::setShape
void setShape(const std::string &shapeName, const Ice::Current &) override
Definition: HandUnitDynamicSimulation.cpp:169
RemoteRobot.h
ARMARX_VERBOSE
#define ARMARX_VERBOSE
Definition: Logging.h:180
armarx::ObjectID
A known object ID of the form "Dataset/ClassName" or "Dataset/ClassName/InstanceName".
Definition: ObjectID.h:11
armarx::RemoteRobot::synchronizeLocalClone
static bool synchronizeLocalClone(VirtualRobot::RobotPtr robot, RobotStateComponentInterfacePrx robotStatePrx)
Definition: RemoteRobot.cpp:448
armarx::HandUnitDynamicSimulation::robotStateComponentName
std::string robotStateComponentName
Definition: HandUnitDynamicSimulation.h:112
armarx::RemoteRobot::createLocalCloneFromFile
static VirtualRobot::RobotPtr createLocalCloneFromFile(RobotStateComponentInterfacePrx robotStatePrx, VirtualRobot::RobotIO::RobotDescription loadMode=VirtualRobot::RobotIO::eFull)
This is a convenience function for createLocalClone, which automatically gets the filename from the R...
Definition: RemoteRobot.cpp:441
armarx::HandUnitDynamicSimulation::workingMemoryPrx
memoryx::WorkingMemoryInterfacePrx workingMemoryPrx
Definition: HandUnitDynamicSimulation.h:110
armarx::HandUnitDynamicSimulationPropertyDefinitions
Definition: HandUnitDynamicSimulation.h:49
armarx::HandUnitDynamicSimulation::kinematicUnitPrx
KinematicUnitInterfacePrx kinematicUnitPrx
Definition: HandUnitDynamicSimulation.h:108
Pose.h
ARMARX_CHECK_NOT_NULL
#define ARMARX_CHECK_NOT_NULL(ptr)
This macro evaluates whether ptr is not null and if it turns out to be false it will throw an Express...
Definition: ExpressionException.h:206
armarx::HandUnitDynamicSimulation::handUnitJointsToRobotJoints
armarx::NameValueMap handUnitJointsToRobotJoints(const armarx::NameValueMap &joints)
Definition: HandUnitDynamicSimulation.cpp:369
armarx::HandUnitDynamicSimulation::setObjectReleased
void setObjectReleased(const std::string &objectName, const Ice::Current &) override
Definition: HandUnitDynamicSimulation.cpp:134
armarx::HandUnit::graspedObject
std::string graspedObject
Definition: HandUnit.h:170
armarx::HandUnitDynamicSimulation::onInitHandUnit
void onInitHandUnit() override
Definition: HandUnitDynamicSimulation.cpp:49
c
constexpr T c
Definition: UnscentedKalmanFilterTest.cpp:43
armarx::navigation::platform_controller::platform_global_trajectory::NameValueMap
std::map< std::string, float > NameValueMap
Definition: PlatformGlobalTrajectoryController.h:93
ObjectClass.h
armarx::ObjectFinder::loadManipulationObject
static VirtualRobot::ManipulationObjectPtr loadManipulationObject(const std::optional< ObjectInfo > &ts)
Definition: ObjectFinder.cpp:298
armarx::objpose::ObjectPoseClient
Provides access to the armarx::objpose::ObjectPoseStorageInterface (aka the object memory).
Definition: ObjectPoseClient.h:18
armarx::HandUnitDynamicSimulation::setJointAngles
void setJointAngles(const NameValueMap &jointAngles, const Ice::Current &) override
Definition: HandUnitDynamicSimulation.cpp:355
armarx::objpose::ObjectPoseClient::getObjectFinder
const ObjectFinder & getObjectFinder() const
Get the internal object finder.
Definition: ObjectPoseClient.cpp:97
IceInternal::Handle< ObjectInstance >
armarx::HandUnitDynamicSimulation::objectPoseStorageName
std::string objectPoseStorageName
Definition: HandUnitDynamicSimulation.h:115
armarx::objpose::ObjectPoseClient::objectPoseStorage
ObjectPoseStorageInterfacePrx objectPoseStorage
Definition: ObjectPoseClient.h:105
cxxopts::value
std::shared_ptr< Value > value()
Definition: cxxopts.hpp:926
armarx::objpose::ObjectPoseClient::fetchObjectPosesAsMap
ObjectPoseMap fetchObjectPosesAsMap() const
Fetch all known object poses.
Definition: ObjectPoseClient.cpp:51
armarx::HandUnitDynamicSimulation::getCurrentJointValues
NameValueMap getCurrentJointValues(const Ice::Current &c=Ice::emptyCurrent) override
Definition: HandUnitDynamicSimulation.cpp:150
armarx::flush
const LogSender::manipulator flush
Definition: LogSender.h:251
armarx::HandUnitDynamicSimulation::simulatorPrxName
std::string simulatorPrxName
Definition: HandUnitDynamicSimulation.h:104
ObjectPoseClient.h
MemoryXCoreObjectFactories.h
armarx::HandUnitDynamicSimulation::getHandSideFromHandUnitName
std::string getHandSideFromHandUnitName()
Definition: HandUnitDynamicSimulation.cpp:406
memoryx::EntityWrappers::SimoxObjectWrapper
SimoxObjectWrapper offers a simplified access to the Simox ManipulationObject (i.e visualization,...
Definition: SimoxObjectWrapper.h:46
armarx::HandUnit::robotName
std::string robotName
Definition: HandUnit.h:165
armarx::HandUnitDynamicSimulation::setObjectGrasped
void setObjectGrasped(const std::string &objectName, const Ice::Current &) override
Definition: HandUnitDynamicSimulation.cpp:117
armarx::HandUnitDynamicSimulation::setShapeWithObjectInstance
void setShapeWithObjectInstance(const std::string &shapeName, const std::string &objectInstanceName, const Ice::Current &c=Ice::emptyCurrent) override
Definition: HandUnitDynamicSimulation.cpp:220
armarx::channels::KinematicUnitObserver::jointAngles
const KinematicUnitDatafieldCreator jointAngles("jointAngles")
armarx::Component::getConfigIdentifier
std::string getConfigIdentifier()
Retrieve config identifier for this component as set in constructor.
Definition: Component.cpp:74
SimoxObjectWrapper.h
ObjectInstance.h
ARMARX_INFO
#define ARMARX_INFO
Definition: Logging.h:174
armarx::HandUnitDynamicSimulation::createPropertyDefinitions
PropertyDefinitionsPtr createPropertyDefinitions() override
Send command to the hand to open all fingers.
Definition: HandUnitDynamicSimulation.cpp:105
memoryx::GridFileManagerPtr
std::shared_ptr< GridFileManager > GridFileManagerPtr
Definition: AbstractEntityWrapper.h:32
armarx::HandUnit::tcpName
std::string tcpName
Definition: HandUnit.h:166
armarx::HandUnitDynamicSimulation::simulatorPrx
SimulatorInterfacePrx simulatorPrx
Definition: HandUnitDynamicSimulation.h:106
IceUtil::Handle< class PropertyDefinitionContainer >
armarx::HandUnitDynamicSimulation::robotStateComponentPrx
RobotStateComponentInterfacePrx robotStateComponentPrx
Definition: HandUnitDynamicSimulation.h:113
armarx::ObjectFinder::findObject
std::optional< ObjectInfo > findObject(const std::string &dataset, const std::string &name) const
Definition: ObjectFinder.cpp:65
memoryx::GridFileManager
GridFileManager provides utility functions for working with files in Mongo GridFS and links to them s...
Definition: GridFileManager.h:42
armarx::HandUnitDynamicSimulation::onExitHandUnit
void onExitHandUnit() override
Definition: HandUnitDynamicSimulation.cpp:80
armarx::HandUnitDynamicSimulation::onStartHandUnit
void onStartHandUnit() override
Definition: HandUnitDynamicSimulation.cpp:67
armarx::HandUnit::handJoints
std::map< std::string, float > handJoints
Definition: HandUnit.h:168
armarx::HandUnit::kinematicUnitName
std::string kinematicUnitName
Definition: HandUnit.h:160
ARMARX_CHECK_EQUAL
#define ARMARX_CHECK_EQUAL(lhs, rhs)
This macro evaluates whether lhs is equal (==) rhs and if it turns out to be false it will throw an E...
Definition: ExpressionException.h:130
ARMARX_WARNING
#define ARMARX_WARNING
Definition: Logging.h:186
armarx::PropertyDefinitionsPtr
IceUtil::Handle< class PropertyDefinitionContainer > PropertyDefinitionsPtr
PropertyDefinitions smart pointer type.
Definition: forward_declarations.h:34
HandUnitDynamicSimulation.h
armarx::HandUnitDynamicSimulation::getRobotNameFromHandUnitName
std::string getRobotNameFromHandUnitName()
Definition: HandUnitDynamicSimulation.cpp:401
armarx::ManagedIceObject::usingProxy
bool usingProxy(const std::string &name, const std::string &endpoints="")
Registers a proxy for retrieval after initialization and adds it to the dependency list.
Definition: ManagedIceObject.cpp:151
armarx
This file offers overloads of toIce() and fromIce() functions for STL container types.
Definition: ArmarXTimeserver.cpp:28
VirtualRobot::RobotPtr
std::shared_ptr< class Robot > RobotPtr
Definition: Bus.h:18
ObjectFinder.h
armarx::split
std::vector< std::string > split(const std::string &source, const std::string &splitBy, bool trimElements=false, bool removeEmptyElements=false)
Definition: StringHelpers.cpp:36
armarx::objpose::ObjectPoseMap
std::map< ObjectID, ObjectPose > ObjectPoseMap
Definition: forward_declarations.h:21