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 
25 #include <algorithm>
26 #include <regex>
27 #include <thread>
28 
30 
32 
33 namespace armarx
34 {
37  {
40  }
41 
42  void
44  {
45  _driver = std::make_unique<BLEProthesisInterface>(getProperty<std::string>("MAC"));
46  //addShapeName("Open"); //is added by something else already
47  addShapeName("Close");
48  addShapeName("G0");
49  addShapeName("G1");
50  addShapeName("G2");
51  addShapeName("G3");
52  addShapeName("G4");
53  addShapeName("G5");
54  addShapeName("G6");
55  addShapeName("G7");
56  addShapeName("G8");
57 
58  offeringTopic(getProperty<std::string>("DebugObserverName"));
59  if (!getProperty<std::string>("RemoteGuiName").getValue().empty())
60  {
61  usingProxy(getProperty<std::string>("RemoteGuiName"));
62  }
63  }
64 
65  void
67  {
68  _debugObserver =
69  getTopic<DebugObserverInterfacePrx>(getProperty<std::string>("DebugObserverName"));
70  if (!getProperty<std::string>("RemoteGuiName").getValue().empty())
71  {
72  _remoteGuiPrx = getProxy<RemoteGuiInterfacePrx>(
73  getProperty<std::string>("RemoteGuiName").getValue());
74 
75 
77 
78  auto addFinger = [&](std::string name, float min, float max, float val, int steps)
79  {
80  rootLayoutBuilder.addChild(
84  .addChild(
85  RemoteGui::makeFloatSlider(name).min(min).max(max).value(val).steps(
86  steps))
88  rootLayoutBuilder.addChild(
90  .addChild(RemoteGui::makeTextLabel(name + " Pos "))
91  .addChild(RemoteGui::makeLabel(name + "_pos").value("0"))
92  .addChild(new RemoteGui::HSpacer()));
93  rootLayoutBuilder.addChild(
95  .addChild(RemoteGui::makeTextLabel(name + " PWM "))
96  .addChild(RemoteGui::makeLabel(name + "_pwm").value("0"))
97  .addChild(new RemoteGui::HSpacer()));
98  };
99 
100  addFinger("Thumb", 0, 1, _lastGuiValueThumb, _driver->getMaxPosThumb());
101  addFinger("Fingers", 0, 1, _lastGuiValueFingers, _driver->getMaxPosFingers());
102 
103  rootLayoutBuilder.addChild(new RemoteGui::VSpacer());
104 
105  _guiTask = new SimplePeriodicTask<>(
106  [&]()
107  {
108  _guiTab.receiveUpdates();
109  _driver->getMaxPosThumb();
110  const float t = _guiTab.getValue<float>("Thumb").get();
111  const float f = _guiTab.getValue<float>("Fingers").get();
112 
113  bool updateT = t != _lastGuiValueThumb;
114  bool updateF = f != _lastGuiValueFingers;
115  _lastGuiValueThumb = t;
116  _lastGuiValueFingers = f;
117 
118  if (updateT && updateF)
119  {
120  setJointAngles({{"Thumb", t}, {"Fingers", f}});
121  }
122  else if (updateT)
123  {
124  setJointAngles({{"Thumb", t}});
125  }
126  else if (updateF)
127  {
128  setJointAngles({{"Fingers", f}});
129  }
130 
131  _guiTab.getValue<std::string>("Thumb_pos")
132  .set(std::to_string(_driver->getThumbPos()));
133  _guiTab.getValue<std::string>("Thumb_pwm")
134  .set(std::to_string(_driver->getThumbPWM()));
135  _guiTab.getValue<std::string>("Fingers_pos")
136  .set(std::to_string(_driver->getFingerPos()));
137  _guiTab.getValue<std::string>("Fingers_pwm")
138  .set(std::to_string(_driver->getFingerPWM()));
139  _guiTab.sendUpdates();
140  },
141  10);
142 
143  RemoteGui::WidgetPtr rootLayout = rootLayoutBuilder;
144 
145  _remoteGuiPrx->createTab("KITProstheticHandUnit", rootLayout);
146  _guiTab = RemoteGui::TabProxy(_remoteGuiPrx, "KITProstheticHandUnit");
147 
148  _guiTask->start();
149  }
150  }
151 
152  void
154  {
155  _driver.reset();
156  }
157 
158  void
160  const Ice::Current&)
161  {
162  ARMARX_CHECK_NOT_NULL(_driver);
163 
164  for (const auto& pair : targetJointAngles)
165  {
166  if (pair.first == "Fingers")
167  {
168  const std::uint64_t pos = std::clamp(
169  static_cast<std::uint64_t>(pair.second * _driver->getMaxPosFingers()),
170  0ul,
171  _driver->getMaxPosFingers());
172  ARMARX_INFO << "set fingers " << pos;
173  _driver->sendFingerPWM(200, 2999, pos);
174  // fix until hw driver is fixed to handle multiple commands at the same time
175  std::this_thread::sleep_for(std::chrono::milliseconds(100));
176  }
177  else if (pair.first == "Thumb")
178  {
179  const std::uint64_t pos =
180  std::clamp(static_cast<std::uint64_t>(pair.second * _driver->getMaxPosThumb()),
181  0ul,
182  _driver->getMaxPosThumb());
183  ARMARX_INFO << "set thumb " << pos;
184  _driver->sendThumbPWM(200, 2999, pos);
185  // fix until hw driver is fixed to handle multiple commands at the same time
186  std::this_thread::sleep_for(std::chrono::milliseconds(100));
187  }
188  else
189  {
190  ARMARX_WARNING << "Invalid HandJointName '" << pair.first << "', ignoring.";
191  }
192  }
193  }
194 
197  {
198  NameValueMap jointValues;
199  jointValues["Fingers"] = _driver->getFingerPos() * 1.f / _driver->getMaxPosFingers();
200  jointValues["Thumb"] = _driver->getThumbPos() * 1.f / _driver->getMaxPosThumb();
201  return jointValues;
202  }
203 
204  void
205  KITProstheticHandUnit::addShape(const std::string& name,
206  const std::map<std::string, float>& shape)
207  {
208  _shapes[name] = shape;
209  addShapeName(name);
210  }
211 
212  void
213  KITProstheticHandUnit::addShapeName(const std::string& name)
214  {
215  Variant currentPreshape;
216  currentPreshape.setString(name);
217  shapeNames->addVariant(currentPreshape);
218  }
219 
220  void
221  KITProstheticHandUnit::setShape(const std::string& shapeName, const Ice::Current&)
222  {
223  if (std::regex_match(shapeName, std::regex{"[gG](0|[1-9][0-9]*)"}))
224  {
225  _driver->sendGrasp(std::stoul(shapeName.substr(1)));
226  }
227  else if (shapeName == "Open")
228  {
229  _driver->sendGrasp(0);
230  }
231  else if (shapeName == "Close")
232  {
233  _driver->sendGrasp(1);
234  }
235  else if (!_shapes.count(shapeName))
236  {
237  ARMARX_WARNING << "Unknown shape name '" << shapeName << "'\nKnown shapes: " << _shapes;
238  }
239  else
240  {
241  setJointAngles(_shapes.at(shapeName));
242  }
243  }
244 } // namespace armarx
armarx::KITProstheticHandUnit::onInitHandUnit
void onInitHandUnit() override
Definition: KITProstheticHandUnit.cpp:43
armarx::Variant
The Variant class is described here: Variants.
Definition: Variant.h:223
armarx::RemoteGui::makeVBoxLayout
detail::VBoxLayoutBuilder makeVBoxLayout(std::string const &name="")
Definition: LayoutWidgets.h:286
armarx::HandUnit::shapeNames
SingleTypeVariantListPtr shapeNames
List containing the names of all valid shapes.
Definition: HandUnit.h:167
KITProstheticHandUnit.h
armarx::RemoteGui::makeHBoxLayout
detail::HBoxLayoutBuilder makeHBoxLayout(std::string const &name="")
Definition: LayoutWidgets.h:268
armarx::KITProstheticHandUnit::addShape
void addShape(const std::string &name, const std::map< std::string, float > &shape)
Definition: KITProstheticHandUnit.cpp:205
armarx::RemoteGui::detail::VBoxLayoutBuilder
Definition: LayoutWidgets.h:108
armarx::KITProstheticHandUnit::setShape
void setShape(const std::string &shapeName, const Ice::Current &c=Ice::emptyCurrent) override
Definition: KITProstheticHandUnit.cpp:221
armarx::RemoteGui::makeLabel
detail::LabelBuilder makeLabel(std::string const &name)
Definition: StaticWidgets.h:18
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:428
armarx::max
std::vector< T > max(const std::vector< T > &v1, const std::vector< T > &v2)
Definition: VectorHelpers.h:297
armarx::RemoteGui::makeTextLabel
detail::LabelBuilder makeTextLabel(std::string const &text)
Definition: StaticWidgets.h:24
armarx::KITProstheticHandUnitPropertyDefinitions
Definition: KITProstheticHandUnit.h:41
armarx::KITProstheticHandUnit::onStartHandUnit
void onStartHandUnit() override
Definition: KITProstheticHandUnit.cpp:66
armarx::KITProstheticHandUnit::onExitHandUnit
void onExitHandUnit() override
Definition: KITProstheticHandUnit.cpp:153
clamp
double clamp(double x, double a, double b)
Definition: point.hpp:136
cxxopts::empty
bool empty(const std::string &s)
Definition: cxxopts.hpp:234
armarx::RemoteGui::TabProxy
Definition: WidgetProxy.h:17
cxxopts::value
std::shared_ptr< Value > value()
Definition: cxxopts.hpp:855
armarx::RemoteGui::TabProxy::receiveUpdates
void receiveUpdates()
Definition: WidgetProxy.h:135
armarx::RemoteGui::detail::ChildrenMixin::addChild
Derived & addChild(WidgetPtr const &child)
Definition: LayoutWidgets.h:27
armarx::RemoteGui::makeFloatSlider
detail::FloatSliderBuilder makeFloatSlider(std::string const &name)
Definition: FloatWidgets.h:64
armarx::to_string
const std::string & to_string(const std::string &s)
Definition: StringHelpers.h:41
armarx::WidgetDescription::WidgetPtr
::IceInternal::Handle<::armarx::WidgetDescription::Widget > WidgetPtr
Definition: NJointControllerBase.h:67
armarx::RemoteGui::TabProxy::getValue
ValueProxy< T > getValue(std::string const &name)
Definition: WidgetProxy.h:167
ExpressionException.h
armarx::control::njoint_controller::platform::platform_follower_controller::NameValueMap
std::map< std::string, float > NameValueMap
Definition: PlatformFollowerController.h:88
armarx::Component::getConfigIdentifier
std::string getConfigIdentifier()
Retrieve config identifier for this component as set in constructor.
Definition: Component.cpp:79
ARMARX_INFO
#define ARMARX_INFO
Definition: Logging.h:181
armarx::ManagedIceObject::offeringTopic
void offeringTopic(const std::string &name)
Registers a topic for retrival after initialization.
Definition: ManagedIceObject.cpp:300
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
Definition: forward_declarations.h:30
armarx::min
std::vector< T > min(const std::vector< T > &v1, const std::vector< T > &v2)
Definition: VectorHelpers.h:327
armarx::RemoteGui::TabProxy::sendUpdates
void sendUpdates()
Definition: WidgetProxy.h:151
armarx::KITProstheticHandUnit::addShapeName
void addShapeName(const std::string &name)
Definition: KITProstheticHandUnit.cpp:213
armarx::KITProstheticHandUnit::createPropertyDefinitions
armarx::PropertyDefinitionsPtr createPropertyDefinitions() override
Definition: KITProstheticHandUnit.cpp:36
ARMARX_WARNING
#define ARMARX_WARNING
Definition: Logging.h:193
armarx::PropertyDefinitionsPtr
IceUtil::Handle< class PropertyDefinitionContainer > PropertyDefinitionsPtr
PropertyDefinitions smart pointer type.
Definition: forward_declarations.h:35
armarx::KITProstheticHandUnit::setJointAngles
void setJointAngles(const NameValueMap &targetJointAngles, const Ice::Current &=Ice::emptyCurrent) override
Definition: KITProstheticHandUnit.cpp:159
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:154
armarx
This file offers overloads of toIce() and fromIce() functions for STL container types.
Definition: ArmarXTimeserver.cpp:27
armarx::SimplePeriodicTask
Usage:
Definition: ApplicationNetworkStats.h:32
armarx::KITProstheticHandUnit::getCurrentJointValues
NameValueMap getCurrentJointValues(const Ice::Current &) override
Definition: KITProstheticHandUnit.cpp:196