KITProstheticHandUnit.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of ArmarX.
3  *
4  * ArmarX is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * ArmarX is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  *
16  * @package RobotAPI::ArmarXObjects::KITProstheticHandUnit
17  * @author Raphael Grimm ( raphael dot grimm at kit dot edu )
18  * @date 2018
19  * @copyright http://www.gnu.org/licenses/gpl-2.0.txt
20  * GNU General Public License
21  */
22 
23 #include "KITProstheticHandUnit.h"
24 
27 
28 #include <algorithm>
29 #include <thread>
30 #include <regex>
31 
32 namespace armarx
33 {
35  {
38  }
39 
41  {
42  _driver = std::make_unique<BLEProthesisInterface>(getProperty<std::string>("MAC"));
43  //addShapeName("Open"); //is added by something else already
44  addShapeName("Close");
45  addShapeName("G0");
46  addShapeName("G1");
47  addShapeName("G2");
48  addShapeName("G3");
49  addShapeName("G4");
50  addShapeName("G5");
51  addShapeName("G6");
52  addShapeName("G7");
53  addShapeName("G8");
54 
55  offeringTopic(getProperty<std::string>("DebugObserverName"));
56  if (!getProperty<std::string>("RemoteGuiName").getValue().empty())
57  {
58  usingProxy(getProperty<std::string>("RemoteGuiName"));
59  }
60  }
61 
63  {
64  _debugObserver = getTopic<DebugObserverInterfacePrx>(getProperty<std::string>("DebugObserverName"));
65  if (!getProperty<std::string>("RemoteGuiName").getValue().empty())
66  {
67  _remoteGuiPrx = getProxy<RemoteGuiInterfacePrx>(getProperty<std::string>("RemoteGuiName").getValue());
68 
69 
71 
72  auto addFinger = [&](std::string name, float min, float max, float val, int steps)
73  {
74  rootLayoutBuilder.addChild(
78  .addChild(RemoteGui::makeFloatSlider(name).min(min).max(max).value(val).steps(steps))
80  );
81  rootLayoutBuilder.addChild(
83  .addChild(RemoteGui::makeTextLabel(name + " Pos "))
84  .addChild(RemoteGui::makeLabel(name + "_pos").value("0"))
85  .addChild(new RemoteGui::HSpacer())
86  );
87  rootLayoutBuilder.addChild(
89  .addChild(RemoteGui::makeTextLabel(name + " PWM "))
90  .addChild(RemoteGui::makeLabel(name + "_pwm").value("0"))
91  .addChild(new RemoteGui::HSpacer())
92  );
93  };
94 
95  addFinger("Thumb", 0, 1, _lastGuiValueThumb, _driver->getMaxPosThumb());
96  addFinger("Fingers", 0, 1, _lastGuiValueFingers, _driver->getMaxPosFingers());
97 
98  rootLayoutBuilder.addChild(new RemoteGui::VSpacer());
99 
100  _guiTask = new SimplePeriodicTask<>([&]()
101  {
102  _guiTab.receiveUpdates();
103  _driver->getMaxPosThumb();
104  const float t = _guiTab.getValue<float>("Thumb").get();
105  const float f = _guiTab.getValue<float>("Fingers").get();
106 
107  bool updateT = t != _lastGuiValueThumb;
108  bool updateF = f != _lastGuiValueFingers;
109  _lastGuiValueThumb = t;
110  _lastGuiValueFingers = f;
111 
112  if (updateT && updateF)
113  {
114  setJointAngles({{"Thumb", t}, {"Fingers", f}});
115  }
116  else if (updateT)
117  {
118  setJointAngles({{"Thumb", t}});
119  }
120  else if (updateF)
121  {
122  setJointAngles({{"Fingers", f}});
123  }
124 
125  _guiTab.getValue<std::string>("Thumb_pos").set(std::to_string(_driver->getThumbPos()));
126  _guiTab.getValue<std::string>("Thumb_pwm").set(std::to_string(_driver->getThumbPWM()));
127  _guiTab.getValue<std::string>("Fingers_pos").set(std::to_string(_driver->getFingerPos()));
128  _guiTab.getValue<std::string>("Fingers_pwm").set(std::to_string(_driver->getFingerPWM()));
129  _guiTab.sendUpdates();
130  }, 10);
131 
132  RemoteGui::WidgetPtr rootLayout = rootLayoutBuilder;
133 
134  _remoteGuiPrx->createTab("KITProstheticHandUnit", rootLayout);
135  _guiTab = RemoteGui::TabProxy(_remoteGuiPrx, "KITProstheticHandUnit");
136 
137  _guiTask->start();
138  }
139  }
140 
142  {
143  _driver.reset();
144  }
145 
146  void KITProstheticHandUnit::setJointAngles(const NameValueMap& targetJointAngles, const Ice::Current&)
147  {
148  ARMARX_CHECK_NOT_NULL(_driver);
149 
150  for (const auto& pair : targetJointAngles)
151  {
152  if (pair.first == "Fingers")
153  {
154  const std::uint64_t pos = std::clamp(
155  static_cast<std::uint64_t>(pair.second * _driver->getMaxPosFingers()),
156  0ul, _driver->getMaxPosFingers());
157  ARMARX_INFO << "set fingers " << pos;
158  _driver->sendFingerPWM(200, 2999, pos);
159  // fix until hw driver is fixed to handle multiple commands at the same time
160  std::this_thread::sleep_for(std::chrono::milliseconds(100));
161  }
162  else if (pair.first == "Thumb")
163  {
164  const std::uint64_t pos = std::clamp(
165  static_cast<std::uint64_t>(pair.second * _driver->getMaxPosThumb()),
166  0ul, _driver->getMaxPosThumb());
167  ARMARX_INFO << "set thumb " << pos;
168  _driver->sendThumbPWM(200, 2999, pos);
169  // fix until hw driver is fixed to handle multiple commands at the same time
170  std::this_thread::sleep_for(std::chrono::milliseconds(100));
171  }
172  else
173  {
174  ARMARX_WARNING << "Invalid HandJointName '" << pair.first << "', ignoring.";
175  }
176  }
177  }
178 
180  {
181  NameValueMap jointValues;
182  jointValues["Fingers"] = _driver->getFingerPos() * 1.f / _driver->getMaxPosFingers();
183  jointValues["Thumb"] = _driver->getThumbPos() * 1.f / _driver->getMaxPosThumb();
184  return jointValues;
185  }
186 
187  void KITProstheticHandUnit::addShape(const std::string& name, const std::map<std::string, float>& shape)
188  {
189  _shapes[name] = shape;
190  addShapeName(name);
191  }
192 
193  void KITProstheticHandUnit::addShapeName(const std::string& name)
194  {
195  Variant currentPreshape;
196  currentPreshape.setString(name);
197  shapeNames->addVariant(currentPreshape);
198  }
199 
200  void KITProstheticHandUnit::setShape(const std::string& shapeName, const Ice::Current&)
201  {
202  if (std::regex_match(shapeName, std::regex{"[gG](0|[1-9][0-9]*)"}))
203  {
204  _driver->sendGrasp(std::stoul(shapeName.substr(1)));
205  }
206  else if (shapeName == "Open")
207  {
208  _driver->sendGrasp(0);
209  }
210  else if (shapeName == "Close")
211  {
212  _driver->sendGrasp(1);
213  }
214  else if (!_shapes.count(shapeName))
215  {
216  ARMARX_WARNING << "Unknown shape name '" << shapeName
217  << "'\nKnown shapes: " << _shapes;
218  }
219  else
220  {
221  setJointAngles(_shapes.at(shapeName));
222  }
223  }
224 }
armarx::KITProstheticHandUnit::onInitHandUnit
void onInitHandUnit() override
Definition: KITProstheticHandUnit.cpp:40
armarx::Variant
The Variant class is described here: Variants.
Definition: Variant.h:224
armarx::RemoteGui::makeVBoxLayout
detail::VBoxLayoutBuilder makeVBoxLayout(std::string const &name="")
Definition: LayoutWidgets.h:245
armarx::HandUnit::shapeNames
SingleTypeVariantListPtr shapeNames
List containing the names of all valid shapes.
Definition: HandUnit.h:158
KITProstheticHandUnit.h
armarx::RemoteGui::makeHBoxLayout
detail::HBoxLayoutBuilder makeHBoxLayout(std::string const &name="")
Definition: LayoutWidgets.h:230
armarx::KITProstheticHandUnit::addShape
void addShape(const std::string &name, const std::map< std::string, float > &shape)
Definition: KITProstheticHandUnit.cpp:187
armarx::RemoteGui::detail::VBoxLayoutBuilder
Definition: LayoutWidgets.h:94
armarx::KITProstheticHandUnit::setShape
void setShape(const std::string &shapeName, const Ice::Current &c=Ice::emptyCurrent) override
Definition: KITProstheticHandUnit.cpp:200
armarx::RemoteGui::makeLabel
detail::LabelBuilder makeLabel(std::string const &name)
Definition: StaticWidgets.h:17
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
WidgetBuilder.h
armarx::Variant::setString
void setString(const std::string &s, const Ice::Current &c=Ice::emptyCurrent) override
Sets the Variant's value to s.
Definition: Variant.cpp:340
armarx::max
std::vector< T > max(const std::vector< T > &v1, const std::vector< T > &v2)
Definition: VectorHelpers.h:267
armarx::RemoteGui::makeTextLabel
detail::LabelBuilder makeTextLabel(std::string const &text)
Definition: StaticWidgets.h:22
armarx::KITProstheticHandUnitPropertyDefinitions
Definition: KITProstheticHandUnit.h:41
armarx::KITProstheticHandUnit::onStartHandUnit
void onStartHandUnit() override
Definition: KITProstheticHandUnit.cpp:62
armarx::KITProstheticHandUnit::onExitHandUnit
void onExitHandUnit() override
Definition: KITProstheticHandUnit.cpp:141
clamp
double clamp(double x, double a, double b)
Definition: point.hpp:125
cxxopts::empty
bool empty(const std::string &s)
Definition: cxxopts.hpp:255
armarx::RemoteGui::TabProxy
Definition: WidgetProxy.h:17
cxxopts::value
std::shared_ptr< Value > value()
Definition: cxxopts.hpp:926
armarx::RemoteGui::TabProxy::receiveUpdates
void receiveUpdates()
Definition: WidgetProxy.h:131
armarx::RemoteGui::detail::ChildrenMixin::addChild
Derived & addChild(WidgetPtr const &child)
Definition: LayoutWidgets.h:22
armarx::RemoteGui::makeFloatSlider
detail::FloatSliderBuilder makeFloatSlider(std::string const &name)
Definition: FloatWidgets.h:57
armarx::to_string
const std::string & to_string(const std::string &s)
Definition: StringHelpers.h:40
armarx::WidgetDescription::WidgetPtr
::IceInternal::Handle<::armarx::WidgetDescription::Widget > WidgetPtr
Definition: NJointControllerBase.h:66
armarx::RemoteGui::TabProxy::getValue
ValueProxy< T > getValue(std::string const &name)
Definition: WidgetProxy.h:161
ExpressionException.h
armarx::control::njoint_controller::platform::platform_follower_controller::NameValueMap
std::map< std::string, float > NameValueMap
Definition: PlatformFollowerController.h:91
armarx::Component::getConfigIdentifier
std::string getConfigIdentifier()
Retrieve config identifier for this component as set in constructor.
Definition: Component.cpp:74
ARMARX_INFO
#define ARMARX_INFO
Definition: Logging.h:174
armarx::ManagedIceObject::offeringTopic
void offeringTopic(const std::string &name)
Registers a topic for retrival after initialization.
Definition: ManagedIceObject.cpp:290
set
set(LIBS ArmarXCoreInterfaces ${CMAKE_THREAD_LIBS_INIT} ${dl_LIBRARIES} ${rt_LIBRARIES} ${QT_LIBRARIES} ${Boost_LIBRARIES} BoostAssertionHandler ArmarXCPPUtility SimoxUtility) set(LIB_FILES ArmarXManager.cpp ArmarXMultipleObjectsScheduler.cpp ArmarXObjectScheduler.cpp ManagedIceObject.cpp ManagedIceObjectPlugin.cpp Component.cpp ComponentPlugin.cpp IceGridAdmin.cpp ArmarXObjectObserver.cpp IceManager.cpp PackagePath.cpp RemoteReferenceCount.cpp logging/LoggingUtil.cpp logging/Logging.cpp logging/LogSender.cpp logging/ArmarXLogBuf.cpp system/ArmarXDataPath.cpp system/DynamicLibrary.cpp system/ProcessWatcher.cpp system/FactoryCollectionBase.cpp system/cmake/CMakePackageFinder.cpp system/cmake/CMakePackageFinderCache.cpp system/cmake/ArmarXPackageToolInterface.cpp system/RemoteObjectNode.cpp services/sharedmemory/HardwareId.cpp services/tasks/RunningTask.cpp services/tasks/ThreadList.cpp services/tasks/ThreadPool.cpp services/profiler/Profiler.cpp services/profiler/FileLoggingStrategy.cpp services/profiler/IceLoggingStrategy.cpp application/Application.cpp application/ApplicationOptions.cpp application/ApplicationProcessFacet.cpp application/ApplicationNetworkStats.cpp application/properties/PropertyUser.cpp application/properties/Property.cpp application/properties/PropertyDefinition.cpp application/properties/PropertyDefinitionContainer.cpp application/properties/PropertyDefinitionHelpFormatter.cpp application/properties/PropertyDefinitionConfigFormatter.cpp application/properties/PropertyDefinitionBriefHelpFormatter.cpp application/properties/PropertyDefinitionXmlFormatter.cpp application/properties/PropertyDefinitionDoxygenFormatter.cpp application/properties/PropertyDefinitionDoxygenComponentPagesFormatter.cpp application/properties/PropertyDefinitionContainerBriefHelpFormatter.cpp application/properties/IceProperties.cpp exceptions/Exception.cpp exceptions/local/UnexpectedEnumValueException.cpp util/FileSystemPathBuilder.cpp util/StringHelpers.cpp util/IceReportSkipper.cpp util/Throttler.cpp util/distributed/AMDCallbackCollection.cpp util/distributed/RemoteHandle/ClientSideRemoteHandleControlBlock.cpp util/distributed/RemoteHandle/RemoteHandle.cpp util/distributed/RemoteHandle/RemoteHandleControlBlock.cpp time/ice_conversions.cpp time/json_conversions.cpp time/CallbackWaitLock.cpp time/Clock.cpp time/ClockType.cpp time/ClockTypeNames.cpp time/CycleUtil.cpp time/DateTime.cpp time/Duration.cpp time/Frequency.cpp time/LocalTimeServer.cpp time/Metronome.cpp time/ScopedStopWatch.cpp time/StopWatch.cpp time/Timer.cpp time/TimeKeeper.cpp time/TimeUtil.cpp csv/CsvWriter.cpp csv/CsvReader.cpp eigen/conversions.cpp eigen/ice_conversions.cpp) set(LIB_HEADERS ArmarXManager.h ArmarXDummyManager.h ArmarXMultipleObjectsScheduler.h ArmarXObjectObserver.h ArmarXObjectScheduler.h ArmarXFwd.h Component.h ComponentPlugin.h ComponentFactories.h CoreObjectFactories.h IceGridAdmin.h IceManager.h IceManagerImpl.h json_conversions.h ManagedIceObject.h ManagedIceObjectPlugin.h ManagedIceObjectImpl.h ManagedIceObjectDependency.h ManagedIceObjectRegistryInterface.h PackagePath.h RemoteReferenceCount.h system/ImportExport.h system/ImportExportComponent.h system/AbstractFactoryMethod.h system/FactoryCollectionBase.h system/Synchronization.h system/ArmarXDataPath.h system/DynamicLibrary.h system/ProcessWatcher.h system/ConditionSynchronization.h system/cmake/CMakePackageFinder.h system/cmake/CMakePackageFinderCache.h system/cmake/FindPackageX.cmake system/cmake/ArmarXPackageToolInterface.h system/RemoteObjectNode.h logging/LoggingUtil.h logging/LogSender.h logging/Logging.h logging/ArmarXLogBuf.h logging/SpamFilterData.h services/tasks/RunningTask.h services/tasks/PeriodicTask.h services/tasks/ThreadList.h services/tasks/TaskUtil.h services/tasks/ThreadPool.h services/sharedmemory/SharedMemoryProvider.h services/sharedmemory/SharedMemoryConsumer.h services/sharedmemory/IceSharedMemoryProvider.h services/sharedmemory/IceSharedMemoryConsumer.h services/sharedmemory/HardwareIdentifierProvider.h services/sharedmemory/HardwareId.h services/sharedmemory/exceptions/SharedMemoryExceptions.h services/profiler/Profiler.h services/profiler/LoggingStrategy.h services/profiler/FileLoggingStrategy.h services/profiler/IceLoggingStrategy.h application/Application.h application/ApplicationOptions.h application/ApplicationProcessFacet.h application/ApplicationNetworkStats.h application/properties/forward_declarations.h application/properties/Properties.h application/properties/Property.h application/properties/PluginEigen.h application/properties/PluginEnumNames.h application/properties/PluginCfgStruct.h application/properties/PluginAll.h application/properties/PropertyUser.h application/properties/PropertyDefinition.h application/properties/PropertyDefinition.hpp application/properties/PropertyDefinitionInterface.h application/properties/PropertyDefinitionContainer.h application/properties/PropertyDefinitionFormatter.h application/properties/PropertyDefinitionContainerFormatter.h application/properties/PropertyDefinitionConfigFormatter.h application/properties/PropertyDefinitionHelpFormatter.h application/properties/PropertyDefinitionBriefHelpFormatter.h application/properties/PropertyDefinitionXmlFormatter.h application/properties/PropertyDefinitionDoxygenFormatter.h application/properties/PropertyDefinitionDoxygenComponentPagesFormatter.h application/properties/PropertyDefinitionContainerBriefHelpFormatter.h application/properties/ProxyPropertyDefinition.h application/properties/IceProperties.h exceptions/Exception.h exceptions/LocalException.h exceptions/local/DynamicLibraryException.h exceptions/local/ExpressionException.h exceptions/local/FileIOException.h exceptions/local/InvalidPropertyValueException.h exceptions/local/MissingRequiredPropertyException.h exceptions/local/PropertyInheritanceCycleException.h exceptions/local/ProxyNotInitializedException.h exceptions/local/UnexpectedEnumValueException.h exceptions/local/UnmappedValueException.h exceptions/local/ValueRangeExceededException.h exceptions/user/NotImplementedYetException.h rapidxml/rapidxml.hpp rapidxml/rapidxml_print.hpp rapidxml/rapidxml_iterators.hpp rapidxml/rapidxml_utils.hpp rapidxml/wrapper/RapidXmlReader.h rapidxml/wrapper/RapidXmlWriter.h rapidxml/wrapper/DefaultRapidXmlReader.h rapidxml/wrapper/MultiNodeRapidXMLReader.h util/IceBlobToObject.h util/ObjectToIceBlob.h util/FileSystemPathBuilder.h util/FiniteStateMachine.h util/StringHelpers.h util/StringHelperTemplates.h util/algorithm.h util/OnScopeExit.h util/Predicates.h util/Preprocessor.h util/PropagateConst.h util/Registrar.h util/TemplateMetaProgramming.h util/TripleBuffer.h util/IceReportSkipper.h util/Throttler.h util/distributed/AMDCallbackCollection.h util/distributed/RemoteHandle/ClientSideRemoteHandleControlBlock.h util/distributed/RemoteHandle/RemoteHandle.h util/distributed/RemoteHandle/RemoteHandleControlBlock.h util/SimpleStatemachine.h time.h time_minimal.h time/forward_declarations.h time/ice_conversions.h time/json_conversions.h time/CallbackWaitLock.h time/Clock.h time/ClockType.h time/ClockTypeNames.h time/CycleUtil.h time/DateTime.h time/Duration.h time/Frequency.h time/LocalTimeServer.h time/Metronome.h time/ScopedStopWatch.h time/StopWatch.h time/Timer.h time/TimeUtil.h time/TimeKeeper.h csv/CsvWriter.h csv/CsvReader.h eigen/conversions.h eigen/ice_conversions.h ice_conversions.h ice_conversions/ice_conversions_boost_templates.h ice_conversions/ice_conversions_templates.h ice_conversions/ice_conversions_templates.tpp $
Definition: CMakeLists.txt:12
IceUtil::Handle< class PropertyDefinitionContainer >
armarx::min
std::vector< T > min(const std::vector< T > &v1, const std::vector< T > &v2)
Definition: VectorHelpers.h:294
armarx::RemoteGui::TabProxy::sendUpdates
void sendUpdates()
Definition: WidgetProxy.h:146
armarx::KITProstheticHandUnit::addShapeName
void addShapeName(const std::string &name)
Definition: KITProstheticHandUnit.cpp:193
armarx::KITProstheticHandUnit::createPropertyDefinitions
armarx::PropertyDefinitionsPtr createPropertyDefinitions() override
Definition: KITProstheticHandUnit.cpp:34
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
armarx::KITProstheticHandUnit::setJointAngles
void setJointAngles(const NameValueMap &targetJointAngles, const Ice::Current &=Ice::emptyCurrent) override
Definition: KITProstheticHandUnit.cpp:146
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
armarx::SimplePeriodicTask
Usage:
Definition: ApplicationNetworkStats.h:32
armarx::KITProstheticHandUnit::getCurrentJointValues
NameValueMap getCurrentJointValues(const Ice::Current &) override
Definition: KITProstheticHandUnit.cpp:179