Nav2 Navigation Stack - humble  humble
ROS 2 Navigation Stack
node_utils.cpp
1 // Copyright (c) 2019 Intel Corporation
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 #include "nav2_util/node_utils.hpp"
16 #include <chrono>
17 #include <string>
18 #include <algorithm>
19 #include <cctype>
20 
21 using std::chrono::high_resolution_clock;
22 using std::to_string;
23 using std::string;
24 using std::replace_if;
25 using std::isalnum;
26 
27 namespace nav2_util
28 {
29 
30 string sanitize_node_name(const string & potential_node_name)
31 {
32  string node_name(potential_node_name);
33  // read this as `replace` characters in `node_name` `if` not alphanumeric.
34  // replace with '_'
35  replace_if(
36  begin(node_name), end(node_name),
37  [](auto c) {return !isalnum(c);},
38  '_');
39  return node_name;
40 }
41 
42 string add_namespaces(const string & top_ns, const string & sub_ns)
43 {
44  if (!top_ns.empty() && top_ns.back() == '/') {
45  if (top_ns.front() == '/') {
46  return top_ns + sub_ns;
47  } else {
48  return "/" + top_ns + sub_ns;
49  }
50  }
51 
52  return top_ns + "/" + sub_ns;
53 }
54 
55 std::string time_to_string(size_t len)
56 {
57  string output(len, '0'); // prefill the string with zeros
58  auto timepoint = high_resolution_clock::now();
59  auto timecount = timepoint.time_since_epoch().count();
60  auto timestring = to_string(timecount);
61  if (timestring.length() >= len) {
62  // if `timestring` is shorter, put it at the end of `output`
63  output.replace(
64  0, len,
65  timestring,
66  timestring.length() - len, len);
67  } else {
68  // if `output` is shorter, just copy in the end of `timestring`
69  output.replace(
70  len - timestring.length(), timestring.length(),
71  timestring,
72  0, timestring.length());
73  }
74  return output;
75 }
76 
77 std::string generate_internal_node_name(const std::string & prefix)
78 {
79  return sanitize_node_name(prefix) + "_" + time_to_string(8);
80 }
81 
82 rclcpp::Node::SharedPtr generate_internal_node(const std::string & prefix)
83 {
84  auto options =
85  rclcpp::NodeOptions()
86  .start_parameter_services(false)
87  .start_parameter_event_publisher(false)
88  .arguments({"--ros-args", "-r", "__node:=" + generate_internal_node_name(prefix), "--"});
89  return rclcpp::Node::make_shared("_", options);
90 }
91 
92 } // namespace nav2_util