ros2_control - rolling
Loading...
Searching...
No Matches
sensor_interface.hpp
1// Copyright 2020 - 2021 ros2_control Development Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef HARDWARE_INTERFACE__SENSOR_INTERFACE_HPP_
16#define HARDWARE_INTERFACE__SENSOR_INTERFACE_HPP_
17
18#include <limits>
19#include <memory>
20#include <string>
21#include <unordered_map>
22#include <utility>
23#include <vector>
24
25#include "hardware_interface/component_parser.hpp"
26#include "hardware_interface/handle.hpp"
27#include "hardware_interface/hardware_info.hpp"
28#include "hardware_interface/introspection.hpp"
29#include "hardware_interface/types/hardware_interface_return_values.hpp"
30#include "hardware_interface/types/lifecycle_state_names.hpp"
31#include "lifecycle_msgs/msg/state.hpp"
32#include "rclcpp/duration.hpp"
33#include "rclcpp/logger.hpp"
34#include "rclcpp/node_interfaces/node_clock_interface.hpp"
35#include "rclcpp/time.hpp"
36#include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp"
37#include "rclcpp_lifecycle/state.hpp"
38#include "realtime_tools/async_function_handler.hpp"
39
40namespace hardware_interface
41{
42
43using CallbackReturn = rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn;
44
46
75class SensorInterface : public rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface
76{
77public:
79 : lifecycle_state_(
80 rclcpp_lifecycle::State(
81 lifecycle_msgs::msg::State::PRIMARY_STATE_UNKNOWN, lifecycle_state_names::UNKNOWN)),
82 sensor_logger_(rclcpp::get_logger("sensor_interface"))
83 {
84 }
85
87
91 SensorInterface(const SensorInterface & other) = delete;
92
93 SensorInterface(SensorInterface && other) = delete;
94
95 virtual ~SensorInterface() = default;
96
99
106 [[deprecated("Use init(HardwareInfo, rclcpp::Logger, rclcpp::Clock::SharedPtr) instead.")]]
107 CallbackReturn init(
108 const HardwareInfo & hardware_info, rclcpp::Logger logger,
109 rclcpp::node_interfaces::NodeClockInterface::SharedPtr clock_interface)
110 {
111 return this->init(hardware_info, logger, clock_interface->get_clock());
112 }
113
116
123 CallbackReturn init(
124 const HardwareInfo & hardware_info, rclcpp::Logger logger, rclcpp::Clock::SharedPtr clock)
125 {
126 sensor_clock_ = clock;
127 sensor_logger_ = logger.get_child("hardware_component.sensor." + hardware_info.name);
128 info_ = hardware_info;
129 if (info_.is_async)
130 {
131 RCLCPP_INFO_STREAM(
132 get_logger(), "Starting async handler with scheduler priority: " << info_.thread_priority);
133 read_async_handler_ = std::make_unique<realtime_tools::AsyncFunctionHandler<return_type>>();
134 read_async_handler_->init(
135 std::bind(&SensorInterface::read, this, std::placeholders::_1, std::placeholders::_2),
136 info_.thread_priority);
137 read_async_handler_->start_thread();
138 }
139 return on_init(hardware_info);
140 };
141
143
148 virtual CallbackReturn on_init(const HardwareInfo & hardware_info)
149 {
150 info_ = hardware_info;
151 parse_state_interface_descriptions(info_.joints, joint_state_interfaces_);
152 parse_state_interface_descriptions(info_.sensors, sensor_state_interfaces_);
153 return CallbackReturn::SUCCESS;
154 };
155
157
168 [[deprecated(
169 "Replaced by vector<StateInterface::ConstSharedPtr> on_export_state_interfaces() method. "
170 "Exporting is handled "
171 "by the Framework.")]] virtual std::vector<StateInterface>
173 {
174 // return empty vector by default. For backward compatibility we try calling
175 // export_state_interfaces() and only when empty vector is returned call
176 // on_export_state_interfaces()
177 return {};
178 }
179
186 virtual std::vector<hardware_interface::InterfaceDescription>
188 {
189 // return empty vector by default.
190 return {};
191 }
192
200 virtual std::vector<StateInterface::ConstSharedPtr> on_export_state_interfaces()
201 {
202 // import the unlisted interfaces
203 std::vector<hardware_interface::InterfaceDescription> unlisted_interface_descriptions =
205
206 std::vector<StateInterface::ConstSharedPtr> state_interfaces;
207 state_interfaces.reserve(
208 unlisted_interface_descriptions.size() + sensor_state_interfaces_.size() +
209 joint_state_interfaces_.size());
210
211 // add InterfaceDescriptions and create StateInterfaces from the descriptions and add to maps.
212 for (const auto & description : unlisted_interface_descriptions)
213 {
214 auto name = description.get_name();
215 unlisted_state_interfaces_.insert(std::make_pair(name, description));
216 auto state_interface = std::make_shared<StateInterface>(description);
217 sensor_states_map_.insert(std::make_pair(name, state_interface));
218 unlisted_states_.push_back(state_interface);
219 state_interfaces.push_back(std::const_pointer_cast<const StateInterface>(state_interface));
220 }
221
222 for (const auto & [name, descr] : sensor_state_interfaces_)
223 {
224 // TODO(Manuel) check for duplicates otherwise only the first appearance of "name" is inserted
225 auto state_interface = std::make_shared<StateInterface>(descr);
226 sensor_states_map_.insert(std::make_pair(name, state_interface));
227 sensor_states_.push_back(state_interface);
228 state_interfaces.push_back(std::const_pointer_cast<const StateInterface>(state_interface));
229 }
230
231 for (const auto & [name, descr] : joint_state_interfaces_)
232 {
233 auto state_interface = std::make_shared<StateInterface>(descr);
234 sensor_states_map_.insert(std::make_pair(name, state_interface));
235 joint_states_.push_back(state_interface);
236 state_interfaces.push_back(std::const_pointer_cast<const StateInterface>(state_interface));
237 }
238
239 return state_interfaces;
240 }
241
243
253 const rclcpp::Time & time, const rclcpp::Duration & period)
254 {
256 status.result = return_type::ERROR;
257 if (info_.is_async)
258 {
259 const auto result = read_async_handler_->trigger_async_callback(time, period);
260 status.successful = result.first;
261 status.result = result.second;
262 const auto execution_time = read_async_handler_->get_last_execution_time();
263 if (execution_time.count() > 0)
264 {
265 status.execution_time = execution_time;
266 }
267 if (!status.successful)
268 {
269 RCLCPP_WARN(
270 get_logger(),
271 "Trigger read called while read async handler is still in progress for hardware "
272 "interface : '%s'. Failed to trigger read cycle!",
273 info_.name.c_str());
274 status.result = return_type::OK;
275 return status;
276 }
277 }
278 else
279 {
280 const auto start_time = std::chrono::steady_clock::now();
281 status.successful = true;
282 status.result = read(time, period);
283 status.execution_time = std::chrono::duration_cast<std::chrono::nanoseconds>(
284 std::chrono::steady_clock::now() - start_time);
285 }
286 return status;
287 }
288
290
299 virtual return_type read(const rclcpp::Time & time, const rclcpp::Duration & period) = 0;
300
302
305 const std::string & get_name() const { return info_.name; }
306
308
311 const std::string & get_group_name() const { return info_.group; }
312
314
317 const rclcpp_lifecycle::State & get_lifecycle_state() const { return lifecycle_state_; }
318
320
323 void set_lifecycle_state(const rclcpp_lifecycle::State & new_state)
324 {
325 lifecycle_state_ = new_state;
326 }
327
328 template <typename T>
329 void set_state(const std::string & interface_name, const T & value)
330 {
331 auto it = sensor_states_map_.find(interface_name);
332 if (it == sensor_states_map_.end())
333 {
334 throw std::runtime_error(
335 "State interface not found: " + interface_name +
336 " in sensor hardware component: " + info_.name + ". This should not happen.");
337 }
338 auto & handle = it->second;
339 std::unique_lock<std::shared_mutex> lock(handle->get_mutex());
340 std::ignore = handle->set_value(lock, value);
341 }
342
343 template <typename T = double>
344 T get_state(const std::string & interface_name) const
345 {
346 auto it = sensor_states_map_.find(interface_name);
347 if (it == sensor_states_map_.end())
348 {
349 throw std::runtime_error(
350 "State interface not found: " + interface_name +
351 " in sensor hardware component: " + info_.name + ". This should not happen.");
352 }
353 auto & handle = it->second;
354 std::shared_lock<std::shared_mutex> lock(handle->get_mutex());
355 const auto opt_value = handle->get_optional<T>(lock);
356 if (!opt_value)
357 {
358 throw std::runtime_error(
359 "Failed to get state value from interface: " + interface_name +
360 ". This should not happen.");
361 }
362 return opt_value.value();
363 }
364
366
369 rclcpp::Logger get_logger() const { return sensor_logger_; }
370
372
375 rclcpp::Clock::SharedPtr get_clock() const { return sensor_clock_; }
376
378
381 const HardwareInfo & get_hardware_info() const { return info_; }
382
384
387 void enable_introspection(bool enable)
388 {
389 if (enable)
390 {
391 stats_registrations_.enableAll();
392 }
393 else
394 {
395 stats_registrations_.disableAll();
396 }
397 }
398
399protected:
400 HardwareInfo info_;
401 // interface names to InterfaceDescription
402 std::unordered_map<std::string, InterfaceDescription> joint_state_interfaces_;
403 std::unordered_map<std::string, InterfaceDescription> sensor_state_interfaces_;
404 std::unordered_map<std::string, InterfaceDescription> unlisted_state_interfaces_;
405
406 // Exported Command- and StateInterfaces in order they are listed in the hardware description.
407 std::vector<StateInterface::SharedPtr> joint_states_;
408 std::vector<StateInterface::SharedPtr> sensor_states_;
409 std::vector<StateInterface::SharedPtr> unlisted_states_;
410
411 rclcpp_lifecycle::State lifecycle_state_;
412 std::unique_ptr<realtime_tools::AsyncFunctionHandler<return_type>> read_async_handler_;
413
414private:
415 rclcpp::Clock::SharedPtr sensor_clock_;
416 rclcpp::Logger sensor_logger_;
417 // interface names to Handle accessed through getters/setters
418 std::unordered_map<std::string, StateInterface::SharedPtr> sensor_states_map_;
419
420protected:
421 pal_statistics::RegistrationsRAII stats_registrations_;
422};
423
424} // namespace hardware_interface
425#endif // HARDWARE_INTERFACE__SENSOR_INTERFACE_HPP_
Virtual Class to implement when integrating a stand-alone sensor into ros2_control.
Definition sensor_interface.hpp:76
virtual std::vector< StateInterface > export_state_interfaces()
Exports all state interfaces for this hardware interface.
Definition sensor_interface.hpp:172
rclcpp::Clock::SharedPtr get_clock() const
Get the clock of the SensorInterface.
Definition sensor_interface.hpp:375
const HardwareInfo & get_hardware_info() const
Get the hardware info of the SensorInterface.
Definition sensor_interface.hpp:381
const std::string & get_group_name() const
Get name of the actuator hardware group to which it belongs to.
Definition sensor_interface.hpp:311
rclcpp::Logger get_logger() const
Get the logger of the SensorInterface.
Definition sensor_interface.hpp:369
SensorInterface(const SensorInterface &other)=delete
SensorInterface copy constructor is actively deleted.
virtual return_type read(const rclcpp::Time &time, const rclcpp::Duration &period)=0
Read the current state values from the actuator.
virtual std::vector< StateInterface::ConstSharedPtr > on_export_state_interfaces()
Definition sensor_interface.hpp:200
virtual CallbackReturn on_init(const HardwareInfo &hardware_info)
Initialization of the hardware interface from data parsed from the robot's URDF.
Definition sensor_interface.hpp:148
const std::string & get_name() const
Get name of the actuator hardware.
Definition sensor_interface.hpp:305
HardwareComponentCycleStatus trigger_read(const rclcpp::Time &time, const rclcpp::Duration &period)
Triggers the read method synchronously or asynchronously depending on the HardwareInfo.
Definition sensor_interface.hpp:252
virtual std::vector< hardware_interface::InterfaceDescription > export_unlisted_state_interface_descriptions()
Definition sensor_interface.hpp:187
void enable_introspection(bool enable)
Enable or disable introspection of the sensor hardware.
Definition sensor_interface.hpp:387
void set_lifecycle_state(const rclcpp_lifecycle::State &new_state)
Set life-cycle state of the actuator hardware.
Definition sensor_interface.hpp:323
CallbackReturn init(const HardwareInfo &hardware_info, rclcpp::Logger logger, rclcpp::Clock::SharedPtr clock)
Definition sensor_interface.hpp:123
CallbackReturn init(const HardwareInfo &hardware_info, rclcpp::Logger logger, rclcpp::node_interfaces::NodeClockInterface::SharedPtr clock_interface)
Definition sensor_interface.hpp:107
const rclcpp_lifecycle::State & get_lifecycle_state() const
Get life-cycle state of the actuator hardware.
Definition sensor_interface.hpp:317
Definition actuator.hpp:34
std::vector< InterfaceDescription > parse_state_interface_descriptions(const std::vector< ComponentInfo > &component_info)
Definition component_parser.cpp:1012
Definition hardware_interface_return_values.hpp:41
This structure stores information about hardware defined in a robot's URDF.
Definition hardware_info.hpp:232
int thread_priority
Async thread priority.
Definition hardware_info.hpp:244
std::string group
Hardware group to which the hardware belongs.
Definition hardware_info.hpp:238
bool is_async
Component is async.
Definition hardware_info.hpp:242
std::vector< ComponentInfo > joints
Definition hardware_info.hpp:253
std::string name
Name of the hardware.
Definition hardware_info.hpp:234
std::vector< ComponentInfo > sensors
Definition hardware_info.hpp:262