Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
node_utils.hpp
1 // Copyright (c) 2019 Intel Corporation
2 // Copyright (c) 2023 Open Navigation LLC
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #ifndef NAV2_ROS_COMMON__NODE_UTILS_HPP_
17 #define NAV2_ROS_COMMON__NODE_UTILS_HPP_
18 
19 #include <vector>
20 #include <string>
21 #include <chrono>
22 #include <algorithm>
23 #include <cctype>
24 #include <stdexcept>
25 #include "rclcpp/version.h"
26 #include "rclcpp/clock.hpp"
27 #include "rclcpp/exceptions.hpp"
28 #include "rclcpp/logger.hpp"
29 #include "rclcpp/logging.hpp"
30 #include "rclcpp/node.hpp"
31 #include "rclcpp/node_interfaces/node_parameters_interface.hpp"
32 #include "rclcpp/node_options.hpp"
33 #include "rclcpp/parameter.hpp"
34 #include "rclcpp/parameter_value.hpp"
35 #include "rclcpp/qos.hpp"
36 #include "rcl_interfaces/srv/list_parameters.hpp"
37 #include "pluginlib/exceptions.hpp"
38 #if RCLCPP_VERSION_GTE(30, 1, 4)
39 #include "ament_index_cpp/get_package_share_path.hpp"
40 #else
41 #include "ament_index_cpp/get_package_share_directory.hpp"
42 #endif
43 
44 #ifdef __APPLE__
45  #include <pthread.h>
46  #include <mach/mach.h>
47  #include <mach/thread_policy.h>
48 #elif defined(_WIN32)
49  #ifndef NOMINMAX
50  #define NOMINMAX
51  #endif
52  #include <windows.h>
53 #else
54  #include <sched.h>
55  #include <errno.h>
56 #endif
57 
58 using std::chrono::high_resolution_clock;
59 using std::to_string;
60 using std::string;
61 using std::replace_if;
62 using std::isalnum;
63 
64 namespace nav2
65 {
66 
68 
77 inline std::string sanitize_node_name(const std::string & potential_node_name)
78 {
79  string node_name(potential_node_name);
80  // read this as `replace` characters in `node_name` `if` not alphanumeric.
81  // replace with '_'
82  replace_if(
83  begin(node_name), end(node_name),
84  [](auto c) {return !isalnum(c);},
85  '_');
86  return node_name;
87 }
88 
90 
95 inline std::string add_namespaces(const std::string & top_ns, const std::string & sub_ns = "")
96 {
97  if (!top_ns.empty() && top_ns.back() == '/') {
98  if (top_ns.front() == '/') {
99  return top_ns + sub_ns;
100  } else {
101  return "/" + top_ns + sub_ns;
102  }
103  }
104 
105  return top_ns + "/" + sub_ns;
106 }
107 
109 
117 inline std::string time_to_string(size_t len)
118 {
119  string output(len, '0'); // prefill the string with zeros
120  auto timepoint = high_resolution_clock::now();
121  auto timecount = timepoint.time_since_epoch().count();
122  auto timestring = to_string(timecount);
123  if (timestring.length() >= len) {
124  // if `timestring` is shorter, put it at the end of `output`
125  output.replace(
126  0, len,
127  timestring,
128  timestring.length() - len, len);
129  } else {
130  // if `output` is shorter, just copy in the end of `timestring`
131  output.replace(
132  len - timestring.length(), timestring.length(),
133  timestring,
134  0, timestring.length());
135  }
136  return output;
137 }
138 
140 
150 inline std::string generate_internal_node_name(const std::string & prefix = "")
151 {
152  return sanitize_node_name(prefix) + "_" + time_to_string(8);
153 }
154 
156 
165 inline rclcpp::Node::SharedPtr generate_internal_node(const std::string & prefix = "")
166 {
167  auto options =
168  rclcpp::NodeOptions()
169  .start_parameter_services(false)
170  .start_parameter_event_publisher(false)
171  .arguments({"--ros-args", "-r", "__node:=" + generate_internal_node_name(prefix), "--"});
172  return rclcpp::Node::make_shared("_", options);
173 }
174 
175 using ParameterDescriptor = rcl_interfaces::msg::ParameterDescriptor;
176 
178 /* Declares static ROS2 parameter and sets it to a given value
179  * if it was not already declared.
180  *
181  * \param[in] node A node in which given parameter to be declared
182  * \param[in] parameter_name The name of parameter
183  * \param[in] default_value Parameter value to initialize with
184  * \param[in] parameter_descriptor Parameter descriptor (optional)
185  */
186 template<typename NodeT>
187 inline void declare_parameter_if_not_declared(
188  NodeT node,
189  const std::string & parameter_name,
190  const rclcpp::ParameterValue & default_value,
191  const ParameterDescriptor & parameter_descriptor = ParameterDescriptor())
192 {
193  if (!node->has_parameter(parameter_name)) {
194  node->declare_parameter(parameter_name, default_value, parameter_descriptor);
195  }
196 }
197 
199 /* Declares static ROS2 parameter with given type if it was not already declared.
200  *
201  * \param[in] node A node in which given parameter to be declared
202  * \param[in] parameter_name Name of the parameter
203  * \param[in] param_type The type of parameter
204  * \param[in] parameter_descriptor Parameter descriptor (optional)
205  */
206 template<typename NodeT>
207 inline void declare_parameter_if_not_declared(
208  NodeT node,
209  const std::string & parameter_name,
210  const rclcpp::ParameterType & param_type,
211  const ParameterDescriptor & parameter_descriptor = ParameterDescriptor())
212 {
213  if (!node->has_parameter(parameter_name)) {
214  node->declare_parameter(parameter_name, param_type, parameter_descriptor);
215  }
216 }
217 
220 /* Declares a parameter with the specified type if it was not already declared.
221  * If the parameter was overridden, its value is returned, otherwise an
222  * rclcpp::exceptions::InvalidParameterValueException is thrown
223  *
224  * \param[in] node A node in which given parameter to be declared
225  * \param[in] parameter_name Name of the parameter
226  * \param[in] parameter_descriptor Parameter descriptor (optional)
227  * \return The value of the parameter or an exception
228  */
229 template<typename ParameterT, typename NodeT>
230 inline ParameterT declare_or_get_parameter(
231  NodeT node,
232  const std::string & parameter_name,
233  const ParameterDescriptor & parameter_descriptor = ParameterDescriptor())
234 {
235  if (node->has_parameter(parameter_name)) {
236  return node->get_parameter(parameter_name).template get_value<ParameterT>();
237  }
238  auto param_type = rclcpp::ParameterValue{ParameterT{}}.get_type();
239  auto parameter = node->declare_parameter(parameter_name, param_type, parameter_descriptor);
240  if (parameter.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) {
241  std::string description = "Parameter " + parameter_name + " not in overrides";
242  throw rclcpp::exceptions::InvalidParameterValueException(description.c_str());
243  }
244  return parameter.template get<ParameterT>();
245 }
246 
247 using NodeParamInterfacePtr = rclcpp::node_interfaces::NodeParametersInterface::SharedPtr;
248 
251 
265 template<typename ParamType>
266 inline ParamType declare_or_get_parameter(
267  const rclcpp::Logger & logger, NodeParamInterfacePtr param_interface,
268  const std::string & parameter_name, const ParamType & default_value,
269  bool warn_if_no_override = false, bool strict_param_loading = false,
270  const ParameterDescriptor & parameter_descriptor = ParameterDescriptor())
271 {
272  if (param_interface->has_parameter(parameter_name)) {
273  rclcpp::Parameter param(parameter_name, default_value);
274  param_interface->get_parameter(parameter_name, param);
275  return param.get_value<ParamType>();
276  }
277 
278  auto return_value = param_interface
279  ->declare_parameter(
280  parameter_name, rclcpp::ParameterValue{default_value},
281  parameter_descriptor)
282  .get<ParamType>();
283 
284  const bool no_param_override = param_interface->get_parameter_overrides().find(parameter_name) ==
285  param_interface->get_parameter_overrides().end();
286  if (no_param_override) {
287  if (warn_if_no_override) {
288  RCLCPP_WARN_STREAM(
289  logger,
290  "Failed to get param " << parameter_name << " from overrides, using default value.");
291  }
292  if (strict_param_loading) {
293  std::string description = "Parameter " + parameter_name +
294  " not in overrides and strict_param_loading is True";
295  throw rclcpp::exceptions::InvalidParameterValueException(description.c_str());
296  }
297  }
298 
299  return return_value;
300 }
301 
304 
317 template<typename ParamType, typename NodeT>
318 inline ParamType declare_or_get_parameter(
319  NodeT node, const std::string & parameter_name,
320  const ParamType & default_value,
321  const ParameterDescriptor & parameter_descriptor = ParameterDescriptor())
322 {
323  declare_parameter_if_not_declared(node, "warn_on_missing_params", rclcpp::ParameterValue(false));
324  bool warn_if_no_override{false};
325  node->get_parameter("warn_on_missing_params", warn_if_no_override);
326  declare_parameter_if_not_declared(node, "strict_param_loading", rclcpp::ParameterValue(false));
327  bool strict_param_loading{false};
328  node->get_parameter("strict_param_loading", strict_param_loading);
329  return declare_or_get_parameter(
330  node->get_logger(), node->get_node_parameters_interface(),
331  parameter_name, default_value, warn_if_no_override, strict_param_loading, parameter_descriptor);
332 }
333 
335 
343 template<typename NodeT>
344 inline std::string get_plugin_type_param(
345  NodeT node,
346  const std::string & plugin_name)
347 {
348  declare_parameter_if_not_declared(node, plugin_name + ".plugin", rclcpp::PARAMETER_STRING);
349  std::string plugin_type;
350  try {
351  if (!node->get_parameter(plugin_name + ".plugin", plugin_type)) {
352  RCLCPP_FATAL(
353  node->get_logger(), "Can not get 'plugin' param value for %s", plugin_name.c_str());
354  throw pluginlib::PluginlibException("No 'plugin' param for param ns!");
355  }
356  } catch (rclcpp::exceptions::ParameterUninitializedException & ex) {
357  RCLCPP_FATAL(node->get_logger(), "'plugin' param not defined for %s", plugin_name.c_str());
358  throw pluginlib::PluginlibException("No 'plugin' param for param ns!");
359  }
360 
361  return plugin_type;
362 }
363 
369 inline void setSoftRealTimePriority()
370 {
371 #ifdef __APPLE__
372  // macOS: Use Mach thread API to approximate real-time scheduling
373  thread_port_t thread = pthread_mach_thread_np(pthread_self());
374 
375  thread_time_constraint_policy_data_t policy;
376  policy.period = 1000; // in microseconds (1 kHz loop)
377  policy.computation = 800; // expected compute time per period
378  policy.constraint = 1000; // max latency
379  policy.preemptible = 1; // allow preemption by higher-priority threads
380 
381  kern_return_t result = thread_policy_set(
382  thread,
383  THREAD_TIME_CONSTRAINT_POLICY,
384  (thread_policy_t)&policy,
385  THREAD_TIME_CONSTRAINT_POLICY_COUNT
386  );
387 
388  if (result != KERN_SUCCESS) {
389  std::string errmsg =
390  "Failed to set THREAD_TIME_CONSTRAINT_POLICY on macOS. "
391  "Thread remains at default priority. Mach Error Code: " +
392  std::to_string(result);
393  throw std::runtime_error(errmsg);
394  }
395 #elif defined(_WIN32)
396  // Windows: Raise only the current thread one level above its normal priority
397  // within the existing process priority class.
398  if (!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL)) {
399  throw std::runtime_error(
400  "Failed to set soft real-time thread priority on Windows. Error: " +
401  std::to_string(GetLastError()));
402  }
403 #else
404  // Linux: True real-time scheduling (requires privileges)
405  sched_param sch;
406  sch.sched_priority = 49;
407  if (sched_setscheduler(0, SCHED_FIFO, &sch) == -1) {
408  std::string errmsg(
409  "Cannot set as real-time thread. Users must set: <username> hard rtprio 99 and "
410  "<username> soft rtprio 99 in /etc/security/limits.conf to enable "
411  "realtime prioritization! Error: ");
412  throw std::runtime_error(errmsg + std::strerror(errno));
413  }
414 #endif
415 }
416 
417 template<typename InterfaceT>
418 inline void setIntrospectionMode(
419  InterfaceT & ros_interface,
420  rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_parameters_interface,
421  rclcpp::Clock::SharedPtr clock)
422 {
423  #if RCLCPP_VERSION_GTE(29, 0, 0)
424  rcl_service_introspection_state_t introspection_state = RCL_SERVICE_INTROSPECTION_OFF;
425  if (!node_parameters_interface->has_parameter("introspection_mode")) {
426  node_parameters_interface->declare_parameter(
427  "introspection_mode", rclcpp::ParameterValue("disabled"));
428  }
429  std::string introspection_mode =
430  node_parameters_interface->get_parameter("introspection_mode").as_string();
431  if (introspection_mode == "metadata") {
432  introspection_state = RCL_SERVICE_INTROSPECTION_METADATA;
433  } else if (introspection_mode == "contents") {
434  introspection_state = RCL_SERVICE_INTROSPECTION_CONTENTS;
435  }
436 
437  ros_interface->configure_introspection(clock, rclcpp::ServicesQoS(), introspection_state);
438  #else
439  (void)ros_interface;
440  (void)node_parameters_interface;
441  (void)clock;
442  #endif
443 }
444 
450 inline void replaceOrAddArgument(
451  std::vector<std::string> & arguments, const std::string & option,
452  const std::string & arg_name, const std::string & new_argument)
453 {
454  auto argument = std::find_if(
455  arguments.begin(), arguments.end(),
456  [arg_name](const std::string & value) {return value.find(arg_name) != std::string::npos;});
457  if (argument != arguments.end()) {
458  *argument = new_argument;
459  } else {
460  arguments.push_back("--ros-args");
461  arguments.push_back(option);
462  arguments.push_back(new_argument);
463  }
464 }
465 
466 inline std::string get_package_share_directory(const std::string & package_name)
467 {
468  #if RCLCPP_VERSION_GTE(30, 1, 4)
469  std::filesystem::path pkg_share_dir = ament_index_cpp::get_package_share_path(package_name);
470  return pkg_share_dir.string();
471  #else
472  return ament_index_cpp::get_package_share_directory(package_name);
473  #endif
474 }
475 
476 } // namespace nav2
477 
478 #endif // NAV2_ROS_COMMON__NODE_UTILS_HPP_