  System Time

For convenience in these cases we will also provide the same API as above, but
use the name ` SystemTime ` .

` SystemTime ` will be directly tied to the system clock.


  Steady Time

Example use cases for this include hardware drivers which are interacting with
peripherals with hardware timeouts.

In nodes which require the use of ` SteadyTime ` or ` SystemTime ` for
interacting with hardware or other peripherals it is expected that they do a
best effort to isolate any ` SystemTime ` or ` SteadyTime ` information inside
their implementation and translate external interfaces to use the ROS time
abstraction when communicating over the ROS network.


##  Background  ï


ros2 pkg create --build-type ament_cmake cpp_srvcli --dependencies rclcpp example_interfaces


**Tutorial level:** Beginner


Return to ` CMakeLists.txt  ` to add the executable and target for the new
node. After removing some unnecessary boilerplate from the automatically
generated file, your ` CMakeLists.txt  ` should look like this:


I’m trying to do the part 2 of the ros2 cpp project.
Here is my code, for the moment I’m just trying to get only one scan value:


    rclcpp::TimerBase::SharedPtr timer_future_;
    rclcpp::TimerBase::SharedPtr timer_callback_;


  private:
    // | --------------------- service clients -------------------- |


##  Enumeration Type Documentation


**Goal:** Create and run service and client nodes using C++.


[ pabled91  ](https://get-help.theconstruct.ai/u/pabled91) June 27, 2023,
8:45am  3


Parameters


ros2 run cpp_srvcli server


Passing a clock with type RCL_CLOCK_UNINITIALIZED will result in
RCL_RET_INVALID_ARGUMENT being returned.


Hello,


  References

The default time source is modeled on the ROS Clock and ROS Time system used
in ROS 1.0. For more information on the implementation in ROS 1.0 see:

  * [ ROS Clock Documentation ](http://wiki.ros.org/Clock)
  * [ rospy Time Documentation ](http://wiki.ros.org/rospy/Overview/Time)
  * [ roscpp Time Documentation ](http://wiki.ros.org/roscpp/Overview/Time)

[ View Source ](https://github.com/ros2/design/blob/gh-
pages/articles/130_ros_time.md) [ Edit in Github
](https://github.com/ros2/design/edit/gh-pages/articles/130_ros_time.md)

Pull Requests

  * Open
  * Closed

[ Please Login to View Pull Requests
](https://github.com/login/oauth/authorize?client_id=efa6dd8eae9106381720)

[ Please Login to View Pull Requests
](https://github.com/login/oauth/authorize?client_id=efa6dd8eae9106381720)

Contributors

[ Please Login to View Contributors
](https://github.com/login/oauth/authorize?client_id=efa6dd8eae9106381720)

* * *

© Open Source Robotics Foundation, Inc.

Except where otherwise noted, these design documents are licensed under [
Creative Commons Attribution 3.0
](http://creativecommons.org/licenses/by/3.0/) .


Now run the service node:


    auto request = std::make_shared<example_interfaces::srv::AddTwoInts::Request>();
    request->a = atoll(argv[1]);
    request->b = atoll(argv[2]);


When [ nodes  ](../Beginner-CLI-Tools/Understanding-ROS2-Nodes/Understanding-
ROS2-Nodes.html) communicate using [ services  ](../Beginner-CLI-
Tools/Understanding-ROS2-Services/Understanding-ROS2-Services.html) , the node
that sends a request for data is called the client node, and the one that
responds to the request is the service node. The structure of the request and
response is determined by a ` .srv  ` file.


* 1 Create a package


     ` RCL_RET_OK ` if the time source was successfully finalized, or
     ` RCL_RET_INVALID_ARGUMENT ` if any arguments are invalid, or
     ` RCL_RET_ERROR ` an unspecified error occur.


Recall that packages should be created in the ` src  ` directory, not the root
of the workspace. Navigate into ` ros2_ws/src  ` and create a new package:


  Approach

To provide a simplified time interface we will provide a ROS time and duration
datatype. To query for the latest time a ROS Clock interface will be provided.
A TimeSource can manage one or more Clock instances.


Because you used the ` --dependencies  ` option during package creation, you
donât have to manually add dependencies to ` package.xml  ` or `
CMakeLists.txt  ` .


    // Improvement axis:
    // start scan subscriber after wait for msg
    // and at the end of service callback sub.shutdown();

    #include "geometry_msgs/msg/twist.hpp"
    #include "rcl/event.h"
    #include "rclcpp/rclcpp.hpp"
    #include "rclcpp/subscription_base.hpp"
    #include "rclcpp/subscription_options.hpp"
    #include "rclcpp/utilities.hpp"
    #include "rclcpp/wait_for_message.hpp"
    #include "sensor_msgs/msg/detail/laser_scan__struct.hpp"
    #include "sensor_msgs/msg/laser_scan.hpp"
    #include "wall_following_pkg/srv/find_wall.hpp"

    #include <chrono>
    #include <functional>
    #include <memory>

    using FindWall = wall_following_pkg::srv::FindWall;
    using std::placeholders::_1;
    using std::placeholders::_2;
    using namespace std::chrono_literals;

    const bool SIMULATION = true;

    class ServerNode : public rclcpp::Node {
    public:
      ServerNode() : Node("find_wall_server") {
        RCLCPP_INFO(this->get_logger(), "Robot simulated = %d", SIMULATION);

        callback_group_1_ = this->create_callback_group(
            rclcpp::CallbackGroupType::MutuallyExclusive);
        callback_group_2_ = this->create_callback_group(
            rclcpp::CallbackGroupType::MutuallyExclusive);

        srv_ = create_service<FindWall>(
            "find_wall", std::bind(&ServerNode::find_wall_callback, this, _1, _2),


##  ◆  rcl_steady_clock_init()


###  2 Write the service node  ï


    add_executable(server src/add_two_ints_server.cpp)
    ament_target_dependencies(server rclcpp example_interfaces)


C API providing common ROS client library functionality.

---

  * [ include ](dir_d44c64559bbebec7f509842c48db8b23.html)
  * [ rcl ](dir_283a3917c54ce6b1b3757c2d5b61678e.html)


/* timer_future() //{ */


This will allocate all necessary internal structures, and initialize
variables. It is specifically setting up a RCL_ROS_TIME time source.


RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "service not available, waiting again...");


##  ◆  rcl_clock_valid()


Clock


     ` RCL_RET_OK ` if the time source was successfully initialized, or
     ` RCL_RET_INVALID_ARGUMENT ` if any arguments are invalid, or
     ` RCL_RET_ERROR ` an unspecified error occur.


Navigate into the ` ros2_ws  ` directory created in a [ previous tutorial
](Creating-A-Workspace/Creating-A-Workspace.html#new-directory) .


[ Rolling ](../../../rolling/Tutorials/Beginner-Client-Libraries/Writing-A-Simple-Cpp-Service-And-Client.html)


    * [ Demos ](../Demos.html)
      * [ Using quality-of-service settings for lossy networks ](../Demos/Quality-of-Service.html)
      * [ Managing nodes with managed lifecycles ](../Demos/Managed-Nodes.html)
      * [ Setting up efficient intra-process communication ](../Demos/Intra-Process-Communication.html)
      * [ Recording and playing back data with ` rosbag  ` using the ROS 1 bridge ](../Demos/Rosbag-with-ROS1-Bridge.html)
      * [ Understanding real-time programming ](../Demos/Real-Time-Programming.html)
      * [ Experimenting with a dummy robot ](../Demos/dummy-robot-demo.html)
      * [ Logging ](../Demos/Logging-and-logger-configuration.html)
    * [ Miscellaneous ](../Miscellaneous.html)
      * [ Packaging your ROS 2 application as a snap [community-contributed] ](../Miscellaneous/Packaging-your-ROS-2-application-as-a-snap.html)
      * [ Deploying on IBM Cloud Kubernetes [community-contributed] ](../Miscellaneous/Deploying-ROS-2-on-IBM-Cloud.html)
      * [ Using Eclipse Oxygen with ` rviz2  ` [community-contributed] ](../Miscellaneous/Eclipse-Oxygen-with-ROS-2-and-rviz2.html)
      * [ Building a real-time Linux kernel [community-contributed] ](../Miscellaneous/Building-Realtime-rt_preempt-kernel-for-ROS-2.html)
      * [ Building a package with Eclipse 2021-06 ](../Miscellaneous/Building-ROS2-Package-with-eclipse-2021-06.html)
  * [ How-to Guides ](../../How-To-Guides.html)
    * [ Installation troubleshooting ](../../How-To-Guides/Installation-Troubleshooting.html)
    * [ Developing a ROS 2 package ](../../How-To-Guides/Developing-a-ROS-2-Package.html)
    * [ ament_cmake user documentation ](../../How-To-Guides/Ament-CMake-Documentation.html)
    * [ ament_cmake_python user documentation ](../../How-To-Guides/Ament-CMake-Python-Documentation.html)
    * [ Migrating launch files from ROS 1 to ROS 2 ](../../How-To-Guides/Launch-files-migration-guide.html)
    * [ Using Python, XML, and YAML for ROS 2 Launch Files ](../../How-To-Guides/Launch-file-different-formats.html)
    * [ Using ROS 2 launch to launch composable nodes ](../../How-To-Guides/Launching-composable-nodes.html)
    * [ Migrating YAML parameter files from ROS 1 to ROS 2 ](../../How-To-Guides/Parameters-YAML-files-migration-guide.html)
    * [ Passing ROS arguments to nodes via the command-line ](../../How-To-Guides/Node-arguments.html)
    * [ Synchronous vs. asynchronous service clients ](../../How-To-Guides/Sync-Vs-Async.html)
    * [ DDS tuning information ](../../How-To-Guides/DDS-tuning.html)
    * [ rosbag2: Overriding QoS Policies ](../../How-To-Guides/Overriding-QoS-Policies-For-Recording-And-Playback.html)
    * [ Working with multiple ROS 2 middleware implementations ](../../How-To-Guides/Working-with-multiple-RMW-implementations.html)
    * [ Cross-compilation ](../../How-To-Guides/Cross-compilation.html)
    * [ Releasing a Package ](../../How-To-Guides/Releasing/Releasing-a-Package.html)
      * [ First Time Release ](../../How-To-Guides/Releasing/First-Time-Release.html)
      * [ Subsequent Releases ](../../How-To-Guides/Releasing/Subsequent-Releases.html)
      * [ Release Team / Repository ](../../How-To-Guides/Releasing/Release-Team-Repository.html)
      * [ Release Track ](../../How-To-Guides/Releasing/Release-Track.html)
    * [ Using Python Packages with ROS 2 ](../../How-To-Guides/Using-Python-Packages.html)
    * [ Porting RQt plugins to Windows ](../../How-To-Guides/RQt-Port-Plugin-Windows.html)
    * [ Running ROS 2 nodes in Docker [community-contributed] ](../../How-To-Guides/Run-2-nodes-in-single-or-separate-docker-containers.html)
    * [ Visualizing ROS 2 data with Foxglove Studio ](../../How-To-Guides/Visualizing-ROS-2-Data-With-Foxglove-Studio.html)
    * [ ROS 2 Package Maintainer Guide ](../../How-To-Guides/Package-maintainer-guide.html)
    * [ Building a custom Debian package ](../../How-To-Guides/Building-a-Custom-Debian-Package.html)


###  3 Write the client node  ï


I tried tu use it but i didn’t get to make it work and the coding assistance
didn’t help.
I didn’t found a lot of examples.


    colcon build --packages-select cpp_srvcli

    colcon build --packages-select cpp_srvcli

    colcon build --merge-install --packages-select cpp_srvcli


    * [ Building ROS 2 with tracing instrumentation ](../../How-To-Guides/Building-ROS-2-with-Tracing-Instrumentation.html)
    * [ Topics vs Services vs Actions ](../../How-To-Guides/Topics-Services-Actions.html)
    * [ Using variants ](../../How-To-Guides/Using-Variants.html)
    * [ Using the ` ros2  param  ` command-line tool ](../../How-To-Guides/Using-ros2-param.html)
    * [ ROS 2 on Raspberry Pi ](../../How-To-Guides/Installing-on-Raspberry-Pi.html)
    * [ Using Callback Groups ](../../How-To-Guides/Using-callback-groups.html)
    * [ Setup ROS 2 with VSCode and Docker [community-contributed] ](../../How-To-Guides/Setup-ROS-2-with-VSCode-and-Docker-Container.html)
    * [ Building RQt from source ](../../How-To-Guides/RQt-Source-Install.html)
      * [ Building RQt from source on macOS ](../../How-To-Guides/RQt-Source-Install-MacOS.html)
      * [ Building RQt from source on Windows 10 ](../../How-To-Guides/RQt-Source-Install-Windows10.html)
  * [ Concepts ](../../Concepts.html)
    * [ The ROS_DOMAIN_ID ](../../Concepts/About-Domain-ID.html)
    * [ About different ROS 2 DDS/RTPS vendors ](../../Concepts/About-Different-Middleware-Vendors.html)
    * [ About logging and logger configuration ](../../Concepts/About-Logging.html)
    * [ About Quality of Service settings ](../../Concepts/About-Quality-of-Service-Settings.html)
    * [ About ROS 2 client libraries ](../../Concepts/About-ROS-2-Client-Libraries.html)
    * [ About ROS 2 interfaces ](../../Concepts/About-ROS-Interfaces.html)
    * [ About parameters in ROS 2 ](../../Concepts/About-ROS-2-Parameters.html)
    * [ Executors ](../../Concepts/About-Executors.html)
    * [ About topic statistics ](../../Concepts/About-Topic-Statistics.html)
    * [ Introspection with command line tools ](../../Concepts/About-Command-Line-Tools.html)
    * [ Overview and usage of RQt ](../../Concepts/About-RQt.html)
    * [ About Composition ](../../Concepts/About-Composition.html)
    * [ On the mixing of ament and catkin (catment) ](../../Concepts/About-Catment.html)
    * [ About Cross-compilation ](../../Concepts/About-Cross-Compilation.html)
    * [ About tf2 ](../../Concepts/About-Tf2.html)
    * [ About the build system ](../../Concepts/About-Build-System.html)
    * [ About internal ROS 2 interfaces ](../../Concepts/About-Internal-Interfaces.html)
    * [ About ROS 2 middleware implementations ](../../Concepts/About-Middleware-Implementations.html)
    * [ About ROS 2 client libraries ](../../Concepts/About-ROS-2-Client-Libraries.html)
  * [ Contact ](../../Contact.html)
  * [ The ROS 2 Project ](../../The-ROS2-Project.html)
    * [ Contributing ](../../The-ROS2-Project/Contributing.html)
      * [ ROS 2 developer guide ](../../The-ROS2-Project/Contributing/Developer-Guide.html)
      * [ Code style and language versions ](../../The-ROS2-Project/Contributing/Code-Style-Language-Versions.html)
      * [ Quality guide: ensuring code quality ](../../The-ROS2-Project/Contributing/Quality-Guide.html)
      * [ Migration guide from ROS 1 ](../../The-ROS2-Project/Contributing/Migration-Guide.html)
        * [ Python migration guide from ROS 1 ](../../The-ROS2-Project/Contributing/Migration-Guide-Python.html)
      * [ ROS Build Farms ](../../The-ROS2-Project/Contributing/Build-Farms.html)
      * [ Windows Tips and Tricks ](../../The-ROS2-Project/Contributing/Windows-Tips-and-Tricks.html)


This function returns true if the time source appears to be valid. It will
check that the type is not uninitialized, and that pointers are not invalid.
Note that if data is uninitialized it may give a false positive.


Finalize the clock as a ` RCL_STEADY_TIME ` time source.


[ rcl_ret_t ](types_8h.html#af66ec2e20118b821dbf3f9b0067e8796)
rcl_is_enabled_ros_time_override  |  (  |  [ rcl_clock_t
](structrcl__clock__t.html) *  |  _clock_ ,
---|---|---|---
|  |  bool *  |  _is_enabled_
|  )  |  |

Check if the ` RCL_ROS_TIME ` time source has the override enabled.


Hello,


     [in]  |  clock  |  the handle to the clock which is being initialized
---|---|---
[in]  |  allocator  |  The allocator to use for allocations

Returns


     [in]  |  clock  |  The time source from which to set the value.
---|---|---
[out]  |  time_point  |  The time_point to populate.

Returns


Classes  |  Macros  |  Typedefs  |  Enumerations  |  Functions


typedef struct [ rcl_time_point_t ](structrcl__time__point__t.html) [
rcl_time_point_t ](structrcl__time__point__t.html)
---

A single point in time, measured in nanoseconds, the reference point is based
on the source.


        //RCLCPP_INFO(this->get_logger(), "SCAN CALLBACK");
        if (SIMULATION) {
          // RCLCPP_INFO(this->get_logger(), "number of angle values = '%d'",
          // msg->ranges.size());
          //-------------------------SIM SCAN VALUES 360 values
          this->laser_left = msg->ranges[90];
          this->laser_right = msg->ranges[270];
          this->laser_forward = msg->ranges[0];
          this->laser_backward = msg->ranges[180];
        } else {
          //---------------real turtle bot values 720 values angle_min:
          //-3.1241390705108643 angle_max: 3.1415927410125732
          this->laser_left = msg->ranges[540];
          this->laser_right = msg->ranges[180];
          this->laser_forward = msg->ranges[360];
          this->laser_backward = msg->ranges[0];
        }
        scan_found = true;
        /*
        RCLCPP_INFO(this->get_logger(), "[LEFT] = '%f'", this->laser_left);
        RCLCPP_INFO(this->get_logger(), "[RIGHT] = '%f'", this->laser_right);
        RCLCPP_INFO(this->get_logger(), "[FORWARD] = '%f'", this->laser_forward);
        RCLCPP_INFO(this->get_logger(), "[BACKWARD] = '%f'", this->laser_backward);
        */
      }
    };

    int main(int argc, char *argv[]) {
      rclcpp::init(argc, argv);

      std::shared_ptr<ServerNode> find_wall_server = std::make_shared<ServerNode>();

      rclcpp::executors::MultiThreadedExecutor executor;

      executor.add_node(find_wall_server);
      executor.spin();

      rclcpp::shutdown();
      return 0;
    }


Parameters


    std::shared_ptr<rclcpp::Node> node = rclcpp::Node::make_shared("add_two_ints_client");
    rclcpp::Client<example_interfaces::srv::AddTwoInts>::SharedPtr client =
      node->create_client<example_interfaces::srv::AddTwoInts>("add_two_ints");


I may have missed something.


[ pabled91  ](https://get-help.theconstruct.ai/u/pabled91) June 28, 2023,
2:45pm  4


time.h File Reference


You created two nodes to request and respond to data over a service. You added
their dependencies and executables to the package configuration files so that
you could build and run them, and see a service/client system at work.


     ` RCL_RET_OK ` if the time source was queried successfully, or
     ` RCL_RET_INVALID_ARGUMENT ` if any arguments are invalid, or
     ` RCL_RET_ERROR ` an unspecified error occur.


[ The Construct ROS Community ](/)


##  ◆  rcl_steady_clock_fini()


// | ------------------------ callbacks ----------------------- |


    #include "geometry_msgs/msg/twist.hpp"
    #include "rclcpp/rclcpp.hpp"
    #include "rclcpp/wait_for_message.hpp"
    #include "sensor_msgs/msg/detail/laser_scan__struct.hpp"
    #include "sensor_msgs/msg/laser_scan.hpp"
    #include "wall_following_pkg/srv/find_wall.hpp"

    #include <chrono>
    #include <memory>

    using FindWall = wall_following_pkg::srv::FindWall;
    using std::placeholders::_1;
    using std::placeholders::_2;
    using namespace std::chrono_literals;

    const bool SIMULATION = true;

    class ServerNode : public rclcpp::Node {
    public:
      ServerNode() : Node("find_wall_server") {
        RCLCPP_INFO(this->get_logger(), "Robot simulated = %d", SIMULATION);
        srv_ = create_service<FindWall>( "find_wall", std::bind(&ServerNode::find_wall_callback, this, _1, _2));
        this->laser_left = 0.0;
        this->laser_right = 0.0;
        this->laser_forward = 0.0;
        this->laser_backward = 0.0;
      }

    private:
      rclcpp::Service<FindWall>::SharedPtr srv_;
      geometry_msgs::msg::Twist twist;
      rclcpp::TimerBase::SharedPtr timer_;
      float laser_left;
      float laser_right;
      float laser_forward;
      float laser_backward;

      void find_wall_callback(const std::shared_ptr<FindWall::Request> request,


Inside the ` ros2_ws/src/cpp_srvcli/src  ` directory, create a new file called
` add_two_ints_server.cpp  ` and paste the following code within:


You could build your package now, source the local setup files, and run it,
but letâs create the client node first so you can see the full system at
work.


     [in]  |  clock  |  the handle to the clock which is being finalized
---|---|---

Returns


  Challenges in using abstracted time

There are many algorithms for synchronization and they can typically achieve
accuracies which are better than the latency of the network communications
between devices on the network. However, these algorithms take advantage of
assumptions about the constant and continuous nature of time.

An important aspect of using an abstracted time is to be able to manipulate
time. In some cases, speeding up, slowing down, or pausing time entirely is
important for debugging.

The ability to support pausing time requires that we not assume that the time
values are always increasing.

When communicating the changes in time propagation, the latencies in the
communication network becomes a challenge. Any change in the time abstraction
must be communicated to the other nodes in the graph, but will be subject to
normal network communication latency. This inaccuracy is proportional to the
latency of communications and also proportional to the increase in the rate at
which simulated time advances compared to real time (the “real time factor”).
If very accurate timestamping is required when using the time abstraction, it
can be achieved by slowing down the real time factor such that the
communication latency is comparatively small.

The final challenge is that the time abstraction must be able to jump
backwards in time, a feature that is useful for log file playback. This
behavior is similar to a system clock after a negative date change, and
requires developers using the time abstraction to make sure their algorithm
can deal with the discontinuity. Appropriate APIs must be provided for to the
developer API to enable notifications of jumps in time, both forward and
backwards.


Releases


##  Typedef Documentation


Can someone tell me what I’m doing wrong? [ @bayodesegun ](/u/bayodesegun)
maybe?


Navigate back to the root of your workspace, ` ros2_ws  ` , and build your new
package:


    * [ Development process for a release ](../../Releases/Release-Process.html)
  * [ Tutorials ](../../Tutorials.html)
    * [ Beginner: CLI tools ](../Beginner-CLI-Tools.html)
      * [ Configuring environment ](../Beginner-CLI-Tools/Configuring-ROS2-Environment.html)
      * [ Using ` turtlesim  ` , ` ros2  ` , and ` rqt  ` ](../Beginner-CLI-Tools/Introducing-Turtlesim/Introducing-Turtlesim.html)
      * [ Understanding nodes ](../Beginner-CLI-Tools/Understanding-ROS2-Nodes/Understanding-ROS2-Nodes.html)
      * [ Understanding topics ](../Beginner-CLI-Tools/Understanding-ROS2-Topics/Understanding-ROS2-Topics.html)
      * [ Understanding services ](../Beginner-CLI-Tools/Understanding-ROS2-Services/Understanding-ROS2-Services.html)
      * [ Understanding parameters ](../Beginner-CLI-Tools/Understanding-ROS2-Parameters/Understanding-ROS2-Parameters.html)
      * [ Understanding actions ](../Beginner-CLI-Tools/Understanding-ROS2-Actions/Understanding-ROS2-Actions.html)
      * [ Using ` rqt_console  ` to view logs ](../Beginner-CLI-Tools/Using-Rqt-Console/Using-Rqt-Console.html)
      * [ Launching nodes ](../Beginner-CLI-Tools/Launching-Multiple-Nodes/Launching-Multiple-Nodes.html)
      * [ Recording and playing back data ](../Beginner-CLI-Tools/Recording-And-Playing-Back-Data/Recording-And-Playing-Back-Data.html)
    * [ Beginner: Client libraries ](../Beginner-Client-Libraries.html)
      * [ Using ` colcon  ` to build packages ](Colcon-Tutorial.html)
      * [ Creating a workspace ](Creating-A-Workspace/Creating-A-Workspace.html)
      * [ Creating a package ](Creating-Your-First-ROS2-Package.html)
      * [ Writing a simple publisher and subscriber (C++) ](Writing-A-Simple-Cpp-Publisher-And-Subscriber.html)
      * [ Writing a simple publisher and subscriber (Python) ](Writing-A-Simple-Py-Publisher-And-Subscriber.html)
      * Writing a simple service and client (C++)
      * [ Writing a simple service and client (Python) ](Writing-A-Simple-Py-Service-And-Client.html)
      * [ Creating custom msg and srv files ](Custom-ROS2-Interfaces.html)
      * [ Implementing custom interfaces ](Single-Package-Define-And-Use-Interface.html)
      * [ Using parameters in a class (C++) ](Using-Parameters-In-A-Class-CPP.html)
      * [ Using parameters in a class (Python) ](Using-Parameters-In-A-Class-Python.html)
      * [ Using ` ros2doctor  ` to identify issues ](Getting-Started-With-Ros2doctor.html)
      * [ Creating and using plugins (C++) ](Pluginlib.html)
    * [ Intermediate ](../Intermediate.html)
      * [ Managing Dependencies with rosdep ](../Intermediate/Rosdep.html)
      * [ Creating an action ](../Intermediate/Creating-an-Action.html)
      * [ Writing an action server and client (C++) ](../Intermediate/Writing-an-Action-Server-Client/Cpp.html)
      * [ Writing an action server and client (Python) ](../Intermediate/Writing-an-Action-Server-Client/Py.html)
      * [ Composing multiple nodes in a single process ](../Intermediate/Composition.html)
      * [ Launch ](../Intermediate/Launch/Launch-Main.html)
        * [ Creating a launch file ](../Intermediate/Launch/Creating-Launch-Files.html)
        * [ Integrating launch files into ROS 2 packages ](../Intermediate/Launch/Launch-system.html)
        * [ Using substitutions ](../Intermediate/Launch/Using-Substitutions.html)
        * [ Using event handlers ](../Intermediate/Launch/Using-Event-Handlers.html)
        * [ Managing large projects ](../Intermediate/Launch/Using-ROS2-Launch-For-Large-Projects.html)
      * [ ` tf2  ` ](../Intermediate/Tf2/Tf2-Main.html)


typedef struct [ rcl_clock_t ](structrcl__clock__t.html) [ rcl_clock_t
](structrcl__clock__t.html)
---

Encapsulation of a time source.


  No Advanced Estimating Clock By Default

There are more advanced techniques which could be included to attempt to
estimate the propagation properties and extrapolate between time ticks.
However all of these techniques will require making assumptions about the
future behavior of the time abstraction. And in the case that playback or
simulation is instantaneously paused, it will break any of these assumptions.
There are techniques which would allow potential interpolation, however to
make these possible it would require providing guarantees about the continuity
of time into the future. For more accuracy the progress of time can be slowed,
or the frequency of publishing can be increased. Tuning the parameters for the
` /clock ` topic lets you trade off time for computational effort and/or
bandwidth.


Other Versions  v: foxy


[ rcl_ret_t ](types_8h.html#af66ec2e20118b821dbf3f9b0067e8796) rcl_clock_init
|  (  |  enum [ rcl_clock_type_t
](time_8h.html#a5c734f508ce06aec7974af10ad09d071) |  _clock_type_ ,
---|---|---|---
|  |  [ rcl_clock_t ](structrcl__clock__t.html) *  |  _clock_ ,
|  |  [ rcl_allocator_t ](allocator_8h.html#ac7146d98a03ca836efa0d0d77c78984c)
*  |  _allocator_
|  )  |  |

Initialize a clock based on the passed type.


[ rcl_ret_t ](types_8h.html#af66ec2e20118b821dbf3f9b0067e8796) rcl_clock_fini
|  (  |  [ rcl_clock_t ](structrcl__clock__t.html) *  |  _clock_ |  )  |
---|---|---|---|---|---

Finalize a clock.


Parameters


##  Classes

---
struct  |  [ rcl_clock_t ](structrcl__clock__t.html)
|  Encapsulation of a time source. [ More...
](structrcl__clock__t.html#details)

struct  |  [ rcl_time_point_t ](structrcl__time__point__t.html)
|  A single point in time, measured in nanoseconds, the reference point is
based on the source. [ More... ](structrcl__time__point__t.html#details)

struct  |  [ rcl_duration_t ](structrcl__duration__t.html)
|  A duration of time, measured in nanoseconds and its source. [ More...
](structrcl__duration__t.html#details)

##  Macros

---
#define  |  [ RCL_S_TO_NS ](time_8h.html#ae5d06bff1a071f6b27f8bfc9a345381a) [
RCUTILS_S_TO_NS
](http://docs.ros2.org/ardent/api/rcutils/time_8h.html#a09bb0400aa6b85f877d616e7475aa173)
|  Convenience macro to convert seconds to nanoseconds.  More...

#define  |  [ RCL_MS_TO_NS ](time_8h.html#a2b6c1f35e2df71ebccae0921ffae7e6b) [
RCUTILS_MS_TO_NS
](http://docs.ros2.org/ardent/api/rcutils/time_8h.html#a428e1debfc4394e50ba59f1aaa2a5a03)
|  Convenience macro to convert milliseconds to nanoseconds.  More...

#define  |  [ RCL_US_TO_NS ](time_8h.html#aa5e7d0265c2375837f27bd2d76afc5f1) [
RCUTILS_US_TO_NS
](http://docs.ros2.org/ardent/api/rcutils/time_8h.html#abfe5ac86d1a02406a218b145ab79c498)
|  Convenience macro to convert microseconds to nanoseconds.  More...

#define  |  [ RCL_NS_TO_S ](time_8h.html#a4307e936b4e2e7a3932d7551671ff559) [
RCUTILS_NS_TO_S
](http://docs.ros2.org/ardent/api/rcutils/time_8h.html#aa67004f0b6b3206da7b72b7ed8dd7914)
|  Convenience macro to convert nanoseconds to seconds.  More...

#define  |  [ RCL_NS_TO_MS ](time_8h.html#acf4f610a691fd821091d6345e65e2e8b) [


enum [ rcl_clock_type_t ](time_8h.html#a5c734f508ce06aec7974af10ad09d071)
---

Time source type, used to indicate the source of a time measurement.


            rmw_qos_profile_services_default, callback_group_1_);

        publisher_ =
            this->create_publisher<geometry_msgs::msg::Twist>("cmd_vel", 1);

        this->laser_left = 0.0;
        this->laser_right = 0.0;
        this->laser_forward = 0.0;
        this->laser_backward = 0.0;
      }

    private:
      rclcpp::Service<FindWall>::SharedPtr srv_;
      rclcpp::TimerBase::SharedPtr timer_;
      rclcpp::CallbackGroup::SharedPtr callback_group_1_;
      rclcpp::CallbackGroup::SharedPtr callback_group_2_;
      rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr publisher_;
      rclcpp::Subscription<sensor_msgs::msg::LaserScan>::SharedPtr subscription_;
      geometry_msgs::msg::Twist twist_msg;
      float laser_left;
      float laser_right;
      float laser_forward;
      float laser_backward;

      void find_wall_callback(const std::shared_ptr<FindWall::Request> request,
                              const std::shared_ptr<FindWall::Response> response) {
        // non intrusive function to avoid unused value warning
        typeid(request).name();

        auto scan_message = sensor_msgs::msg::LaserScan();
        twist_msg.linear.x = 0.0;
        twist_msg.angular.z = 0.0;

        //start_scan_sub();

        RCLCPP_INFO(this->get_logger(), "starting to wait for message");
        bool scan_found = false;
        while (!scan_found) {
          scan_found =
              rclcpp::wait_for_message(scan_message, this->shared_from_this(),


namespace ros2_examples
{
  /* class ServiceClientExample //{ */


     ` RCL_RET_OK ` if the time source was enabled successfully, or
     ` RCL_RET_INVALID_ARGUMENT ` if any arguments are invalid, or
     ` RCL_RET_ERROR ` an unspecified error occur.


The ` main  ` function accomplishes the following, line by line:


The value will be computed as duration = finish - start. If start is after
finish the duration will be negative.


thank you in advance.


#define RCL_NS_TO_MS [ RCUTILS_NS_TO_MS
](http://docs.ros2.org/ardent/api/rcutils/time_8h.html#a32b8b03e8399363992e8b7b2275072d2)
---

Convenience macro to convert nanoseconds to milliseconds.


  void ServiceClientExample::timer_callback()
  {
    // it's good to firstly check if the service server is even ready to be called
    if (service_client_->service_is_ready())
    {
      auto request = std::make_shared<std_srvs::srv::SetBool::Request>();
      request->data = true;
      setbool_future_ = service_client_->async_send_request(request);
      RCLCPP_INFO(get_logger(), "[ServiceClientExample]: called service using callback");
    }
    else
      RCLCPP_WARN(get_logger(), "[ServiceClientExample]: not calling service using callback, service not ready!");
  }


RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Interrupted while waiting for the service. Exiting.");


     ` RCL_RET_OK ` if the time source was set successfully, or
     ` RCL_RET_INVALID_ARGUMENT ` if any arguments are invalid, or
     ` RCL_RET_ERROR ` an unspecified error occur.


          rclcpp::sleep_for(1s);
        }
        this->twist_msg.linear.x = 0;
        this->twist_msg.angular.z = 0;
        publisher_->publish(twist_msg);
        subscription_.reset();
        RCLCPP_INFO(this->get_logger(), "in position, end of service");
        response->wallfound = true;
      }

      int find_min_index(std::vector<float> laser_values) {
        int length = laser_values.size();
        // RCLCPP_INFO(this->get_logger(), "length= %d", length);
        float min = laser_values[0];
        int index = 0;
        for (int i = 0; i < length; i++) {
          // RCLCPP_INFO(this->get_logger(), " %f\n", laser_values[i]);
          if (laser_values[i] < min) {
            min = laser_values[i];
            index = i;
          }
        }
        return index;
      }

      void start_scan_sub() {
        rclcpp::SubscriptionOptions sub_options;
        sub_options.callback_group = callback_group_2_;
        subscription_ = this->create_subscription<sensor_msgs::msg::LaserScan>(
            "/scan", rclcpp::SensorDataQoS(),
            std::bind(&ServerNode::scan_callback, this, _1), sub_options);
      }

      void scan_callback(const sensor_msgs::msg::LaserScan::SharedPtr msg) {
        //RCLCPP_INFO(this->get_logger(), "SCAN CALLBACK");
        if (SIMULATION) {
          // RCLCPP_INFO(this->get_logger(), "number of angle values = '%d'",
          // msg->ranges.size());
          //-------------------------SIM SCAN VALUES 360 values
          this->laser_left = msg->ranges[90];


ROS Time Source


  * Initializes ROS 2 C++ client library:

        rclcpp::init(argc, argv);


This topic was automatically closed 3 days after the last reply. New replies
are no longer allowed.


The given [ Event ](classrclcpp_1_1Event.html) must be acquire through the [
get_graph_event() ](classrclcpp_1_1Node.html#a9e5851844ecb1794503b8fc0f9f5c898
"Return a graph event, which will be set anytime a graph change occurs.")
method.


|  [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) void
rclcpp_action::ServerBase::execute  |  (  |  |  )  |
---|---|---|---|---
override  virtual

Act on entities in the wait set which are ready to be acted upon.


Some additional context on the problem:
Since the last message in this topic, the ` Node::create_generic_subscription
` function was integrated from rosbag2 into the rclcpp library, which is
great. However, either i don’t understand how to use it for services, or a
generic service is still missing from rclcpp.
I believe that the service message types can be generically converted between
YAML and ROS 2 types via the [ osrf/dynamic_type_introspection
](https://github.com/osrf/dynamic_message_introspection) library, just like
for topic messages. What is explicitly missing though, is the service
equivalent to the generic pub/sub, e.g. this part:


  3.2 Add executable  ï

Return to ` CMakeLists.txt  ` to add the executable and target for the new
node. After removing some unnecessary boilerplate from the automatically
generated file, your ` CMakeLists.txt  ` should look like this:

    cmake_minimum_required(VERSION 3.5)
    project(cpp_srvcli)

    find_package(ament_cmake REQUIRED)
    find_package(rclcpp REQUIRED)
    find_package(example_interfaces REQUIRED)

    add_executable(server src/add_two_ints_server.cpp)
    ament_target_dependencies(server rclcpp example_interfaces)

    add_executable(client src/add_two_ints_client.cpp)
    ament_target_dependencies(client rclcpp example_interfaces)

    install(TARGETS
      server
      client
      DESTINATION lib/${PROJECT_NAME})

    ament_package()


See also


     [in]  |  name  |  The name of the parameter to check for being declared.
---|---|---

Returns


     [ get_sub_namespace() ](classrclcpp_1_1Node.html#aa9ac5055f3f7a3537642482bd505d4bd "Return the sub-namespace, if this is a sub-node, otherwise an empty string.")
     [ get_effective_namespace() ](classrclcpp_1_1Node.html#afe4790bba38942b795d24b6ccb3e9c5a "Return the effective namespace that is used when creating entities.")


##  ◆  create_service()


rclcpp::Node Class Reference


##  Constructor & Destructor Documentation


entry for creating publishers and subscribers.") 's internal
NodeServicesInterface implementation. [ More...
](classrclcpp_1_1Node.html#a588cb7990fd658e58c532d65e4872df3)

rclcpp::node_interfaces::NodeWaitablesInterface::SharedPtr  |  [
get_node_waitables_interface
](classrclcpp_1_1Node.html#a6708bb439e1d3bb1ea44fbae50e460b2) ()
|  Return the [ Node ](classrclcpp_1_1Node.html "Node is the single point of
entry for creating publishers and subscribers.") 's internal
NodeWaitablesInterface implementation. [ More...
](classrclcpp_1_1Node.html#a6708bb439e1d3bb1ea44fbae50e460b2)

rclcpp::node_interfaces::NodeParametersInterface::SharedPtr  |  [
get_node_parameters_interface
](classrclcpp_1_1Node.html#ab6272f2facdfb35f0ef9ce01ffedeec9) ()
|  Return the [ Node ](classrclcpp_1_1Node.html "Node is the single point of
entry for creating publishers and subscribers.") 's internal
NodeParametersInterface implementation. [ More...
](classrclcpp_1_1Node.html#ab6272f2facdfb35f0ef9ce01ffedeec9)

rclcpp::node_interfaces::NodeTimeSourceInterface::SharedPtr  |  [
get_node_time_source_interface
](classrclcpp_1_1Node.html#afa70b6e8bd3ecc39c5928d822024db39) ()
|  Return the [ Node ](classrclcpp_1_1Node.html "Node is the single point of
entry for creating publishers and subscribers.") 's internal
NodeTimeSourceInterface implementation. [ More...
](classrclcpp_1_1Node.html#afa70b6e8bd3ecc39c5928d822024db39)

const [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) & |  [
get_sub_namespace
](classrclcpp_1_1Node.html#aa9ac5055f3f7a3537642482bd505d4bd) () const
|  Return the sub-namespace, if this is a sub-node, otherwise an empty string.
[ More... ](classrclcpp_1_1Node.html#aa9ac5055f3f7a3537642482bd505d4bd)

const [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) & |  [
get_effective_namespace
](classrclcpp_1_1Node.html#afe4790bba38942b795d24b6ccb3e9c5a) () const
|  Return the effective namespace that is used when creating entities. [


` remove_on_set_parameters_callback(scoped_callback.get()) `


Set the given parameters, all at one time, and then aggregate result.


##  ◆  get_node_base_interface()


Exceptions


#  3 Writing an action client  ï


|  5  |  4300  |  September 29, 2021
[ Actions in ROS 2 ](https://discourse.ros.org/t/actions-in-ros-2/6254)


[ Node ](classrclcpp_1_1Node.html "Node is the single point of entry for
creating publishers and subscribers.") is the single point of entry for
creating publishers and subscribers.


##  ◆  OnSetParametersCallbackHandle


auto  sub_node3 = node->create_sub_node(  "foo"  );


     [in]  |  topic_name  |  The topic for this publisher to publish on.
---|---|---
[in]  |  qos  |  The Quality of [ Service ](classrclcpp_1_1Service.html)
settings for the publisher.
[in]  |  options  |  Additional options for the created [ Publisher
](classrclcpp_1_1Publisher.html "A publisher publishes messages of any type to
a topic.") .

Returns


See the simpler [ declare_parameters()
](classrclcpp_1_1Node.html#a5ebda51ed6fa4ce8f2cddc9f77e9674e "Declare and
initialize several parameters with the same namespace and type.") on this
class for more details.


            subscription_ = this->node_handle_->create_generic_subscription(
                topic_name_,
                topic_type_,
                qos,
                [this](std::shared_ptr<const rclcpp::SerializedMessage> message)
                {
                    this->process_message(message);
                }
            );


The callback functions must remain valid as long as the returned smart pointer
is valid. The returned smart pointer can be promoted to a shared version.


By default, when an instance of this class is created using one of the public
constructors, it has no sub-namespace associated with it, and therefore is not
a sub-node. That "normal" node instance may, however, be used to create
further instances of this class, based on the original instance, which have an
additional sub-namespace associated with them. This may be done by using this
method, [ create_sub_node()
](classrclcpp_1_1Node.html#a1df8e4507d17a503630317432449d69d "Create a sub-
node, which will extend the namespace of all entities created with it.") .


     [in]  |  name  |  The name of the parameter.
---|---|---
[in]  |  default_value  |  An initial value to be used if at run-time user did
not override it.
[in]  |  parameter_descriptor  |  An optional, custom description for the
parameter.
[in]  |  ignore_override  |  When ` true ` , the parameter override is
ignored. Default to ` false ` .

Returns


Returns


Let’s start by exploring three different service definitions in the [ `
std_srvs ` ](http://wiki.ros.org/std_srvs) package:


template<typename ParameterT >


###  Product


  /**
   * Similar to the previous overload, but a callback will automatically be called when a response is received.
   *
   * If the callback is never called, because we never got a reply for the service server, remove_pending_request()
   * has to be called with the returned request id or prune_pending_requests().
   * Not doing so will make the `Client` instance use more memory each time a response is not
   * received from the service server.
   * In this case, it's convenient to setup a timer to cleanup the pending requests.
   * See for example the `examples_rclcpp_async_client` package in https://github.com/ros2/examples.
   *
   * \param[in] request request to be send.
   * \param[in] cb callback that will be called when we get a response for this request.
   * \return the request id representing the request just sent.
   */
  template<
    typename CallbackT,
    typename std::enable_if<
      rclcpp::function_traits::same_arguments<
        CallbackT,
        CallbackType
      >::value
    >::type * = nullptr
  >
  SharedFutureAndRequestId
  async_send_request(SharedRequest request, CallbackT && cb)
  {
    Promise promise;
    auto shared_future = promise.get_future().share();
    auto req_id = async_send_request_impl(
      *request,
      std::make_tuple(
        CallbackType{std::forward<CallbackT>(cb)},
        shared_future,
        std::move(promise)));
    return SharedFutureAndRequestId{std::move(shared_future), req_id};
  }
  /// Send a request to the service server and schedule a callback in the executor.
  /**
   * Similar to the previous method, but you can get both the request and response in the callback.
   *


![Collaboration graph](classrclcpp_1_1Node__coll__graph.png)


rclcpp::node_interfaces::NodeServicesInterface::SharedPtr
rclcpp::Node::get_node_services_interface  |  (  |  |  )  |
---|---|---|---|---

Return the [ Node ](classrclcpp_1_1Node.html "Node is the single point of
entry for creating publishers and subscribers.") 's internal
NodeServicesInterface implementation.


a list of [ TopicEndpointInfo ](classrclcpp_1_1TopicEndpointInfo.html) representing all the publishers on this topic.


const [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) &
rclcpp::Node::get_effective_namespace  |  (  |  |  )  |  const
---|---|---|---|---

Return the effective namespace that is used when creating entities.


rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr
rclcpp::Node::get_node_logging_interface  |  (  |  |  )  |
---|---|---|---|---

Return the [ Node ](classrclcpp_1_1Node.html "Node is the single point of
entry for creating publishers and subscribers.") 's internal
NodeLoggingInterface implementation.


**[ Deprecated: ](deprecated.html#_deprecated000001) **


##  ◆  get_node_services_interface()


Parameters


Create a ` diagnostics_node.cpp ` file in your package's ` src ` folder, and
include the following libraries:


Generated by [ ![doxygen](doxygen.png) ](http://www.doxygen.org/index.html)
1.8.17


![Service request and response](/images/blog/creating-ros2-services/hero.webp)
_The client will wait for a response within a specified timeout period._


If undeclared parameters are allowed, then a default initialized descriptor
will be returned.


number of publishers that are advertised on a given topic.


If undeclared parameters are allowed, then the default type
rclcpp::ParameterType::PARAMETER_NOT_SET will be returned.


Exceptions


This method will never throw the [
rclcpp::exceptions::ParameterNotDeclaredException
](classrclcpp_1_1exceptions_1_1ParameterNotDeclaredException.html "Thrown if
parameter is not declared, e.g. either set or get was called without first
declaring.") exception because the action of listing the parameters is done
atomically with getting the values, and therefore they are only listed if
already declared and cannot be undeclared before being retrieved.


A sub-node (short for subordinate node) is an instance of this class which has
been created using an existing instance of this class, but which has an
additional sub-namespace (short for subordinate namespace) associated with it.
The sub-namespace will extend the node's namespace for the purpose of creating
additional entities, such as Publishers, Subscriptions, [ Service
](classrclcpp_1_1Service.html) Clients and Servers, and so on.


Before we send the request, let's make sure the server is active – otherwise,
our request will be lost. The function ` wait_for_service() ` requires a
**timeout** , which is the maximum time a client will wait for a response.


  Background  ï

When [ nodes  ](../Beginner-CLI-Tools/Understanding-ROS2-Nodes/Understanding-
ROS2-Nodes.html) communicate using [ services  ](../Beginner-CLI-
Tools/Understanding-ROS2-Services/Understanding-ROS2-Services.html) , the node
that sends a request for data is called the client node, and the one that
responds to the request is the service node. The structure of the request and
response is determined by a ` .srv  ` file.

The example used here is a simple integer addition system; one node requests
the sum of two integers, and the other responds with the result.


result.reason =  "the reason it could not be allowed"  ;


The results for each set action as a vector.


size_t rclcpp::Node::count_publishers  |  (  |  const [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) & |  _topic_name_
|  )  |  const
---|---|---|---|---|---

##  ◆  count_subscribers()


##  ◆  get_logger()


  * [ ` Empty.srv ` ](http://docs.ros.org/en/api/std_srvs/html/srv/Empty.html) – Empty request and response. The only data that is passed from client to server is the call itself.
  * [ ` Trigger.srv ` ](http://docs.ros.org/en/api/std_srvs/html/srv/Trigger.html) – Empty request and a response with ` success ` and ` message ` fields. This allows the server to send more information to the client.
  * [ ` SetBool.srv ` ](http://docs.ros.org/en/api/std_srvs/html/srv/SetBool.html) – Request with ` data ` field and response with ` success ` and ` message ` fields.


      * [ Beta 3 ( ` r2b3  ` ) ](../../../Releases/Beta3-Overview.html)
      * [ Beta 2 ( ` r2b2  ` ) ](../../../Releases/Beta2-Overview.html)
      * [ Beta 1 ( ` Asphalt  ` ) ](../../../Releases/Beta1-Overview.html)
      * [ Alphas ](../../../Releases/Alpha-Overview.html)
    * [ Development process for a release ](../../../Releases/Release-Process.html)
  * [ Tutorials ](../../../Tutorials.html)
    * [ Beginner: CLI tools ](../../Beginner-CLI-Tools.html)
      * [ Configuring environment ](../../Beginner-CLI-Tools/Configuring-ROS2-Environment.html)
      * [ Using ` turtlesim  ` , ` ros2  ` , and ` rqt  ` ](../../Beginner-CLI-Tools/Introducing-Turtlesim/Introducing-Turtlesim.html)
      * [ Understanding nodes ](../../Beginner-CLI-Tools/Understanding-ROS2-Nodes/Understanding-ROS2-Nodes.html)
      * [ Understanding topics ](../../Beginner-CLI-Tools/Understanding-ROS2-Topics/Understanding-ROS2-Topics.html)
      * [ Understanding services ](../../Beginner-CLI-Tools/Understanding-ROS2-Services/Understanding-ROS2-Services.html)
      * [ Understanding parameters ](../../Beginner-CLI-Tools/Understanding-ROS2-Parameters/Understanding-ROS2-Parameters.html)
      * [ Understanding actions ](../../Beginner-CLI-Tools/Understanding-ROS2-Actions/Understanding-ROS2-Actions.html)
      * [ Using ` rqt_console  ` to view logs ](../../Beginner-CLI-Tools/Using-Rqt-Console/Using-Rqt-Console.html)
      * [ Launching nodes ](../../Beginner-CLI-Tools/Launching-Multiple-Nodes/Launching-Multiple-Nodes.html)
      * [ Recording and playing back data ](../../Beginner-CLI-Tools/Recording-And-Playing-Back-Data/Recording-And-Playing-Back-Data.html)
    * [ Beginner: Client libraries ](../../Beginner-Client-Libraries.html)
      * [ Using ` colcon  ` to build packages ](../../Beginner-Client-Libraries/Colcon-Tutorial.html)
      * [ Creating a workspace ](../../Beginner-Client-Libraries/Creating-A-Workspace/Creating-A-Workspace.html)
      * [ Creating a package ](../../Beginner-Client-Libraries/Creating-Your-First-ROS2-Package.html)
      * [ Writing a simple publisher and subscriber (C++) ](../../Beginner-Client-Libraries/Writing-A-Simple-Cpp-Publisher-And-Subscriber.html)
      * [ Writing a simple publisher and subscriber (Python) ](../../Beginner-Client-Libraries/Writing-A-Simple-Py-Publisher-And-Subscriber.html)
      * [ Writing a simple service and client (C++) ](../../Beginner-Client-Libraries/Writing-A-Simple-Cpp-Service-And-Client.html)
      * [ Writing a simple service and client (Python) ](../../Beginner-Client-Libraries/Writing-A-Simple-Py-Service-And-Client.html)
      * [ Creating custom msg and srv files ](../../Beginner-Client-Libraries/Custom-ROS2-Interfaces.html)
      * [ Implementing custom interfaces ](../../Beginner-Client-Libraries/Single-Package-Define-And-Use-Interface.html)
      * [ Using parameters in a class (C++) ](../../Beginner-Client-Libraries/Using-Parameters-In-A-Class-CPP.html)
      * [ Using parameters in a class (Python) ](../../Beginner-Client-Libraries/Using-Parameters-In-A-Class-Python.html)
      * [ Using ` ros2doctor  ` to identify issues ](../../Beginner-Client-Libraries/Getting-Started-With-Ros2doctor.html)
      * [ Creating and using plugins (C++) ](../../Beginner-Client-Libraries/Pluginlib.html)
    * [ Intermediate ](../../Intermediate.html)
      * [ Managing Dependencies with rosdep ](../Rosdep.html)
      * [ Creating an action ](../Creating-an-Action.html)
      * Writing an action server and client (C++)
      * [ Writing an action server and client (Python) ](Py.html)
      * [ Writing a Composable Node (C++) ](../Writing-a-Composable-Node.html)
      * [ Composing multiple nodes in a single process ](../Composition.html)
      * [ Monitoring for parameter changes (C++) ](../Monitoring-For-Parameter-Changes-CPP.html)
      * [ Monitoring for parameter changes (Python) ](../Monitoring-For-Parameter-Changes-Python.html)


node->get_sub_namespace();  // -> ""


|  [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) bool
rclcpp_action::ServerBase::add_to_wait_set  |  (  |  [ rcl_wait_set_t
](http://docs.ros2.org/foxy/api/rcl/structrcl__wait__set__t.html) *  |
_wait_set_ |  )  |
---|---|---|---|---|---
override  virtual

Add all entities to a wait set.


[ std::map ](http://en.cppreference.com/w/cpp/container/map.html) < [
std::string ](http://en.cppreference.com/w/cpp/string/basic_string.html) , [
std::vector ](http://en.cppreference.com/w/cpp/container/vector.html) < [
std::string ](http://en.cppreference.com/w/cpp/string/basic_string.html) > >
rclcpp::Node::get_topic_names_and_types  |  (  |  |  )  |  const
---|---|---|---|---

Return a map of existing topic names to list of topic types.


auto  node = std::make_shared<rclcpp::Node>(  "my_node"  ,  "my_ns"  );


[ Next Generation ROS  ](/c/ng-ros/25)


[ std::vector ](http://en.cppreference.com/w/cpp/container/vector.html)
<uint8_t> rclcpp::Node::get_parameter_types  |  (  |  const [ std::vector
](http://en.cppreference.com/w/cpp/container/vector.html) < [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) > & |  _names_ |
)  |  const
---|---|---|---|---|---

Return a vector of parameter types, one for each of the given names.


rcl_interfaces::msg::ParameterDescriptor rclcpp::Node::describe_parameter  |
(  |  const [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) & |  _name_ |  )
|  const
---|---|---|---|---|---

Return the parameter descriptor for the given parameter name.


     [ get_sub_namespace() ](classrclcpp_1_1Node.html#aa9ac5055f3f7a3537642482bd505d4bd "Return the sub-namespace, if this is a sub-node, otherwise an empty string.")
     [ get_effective_namespace() ](classrclcpp_1_1Node.html#afe4790bba38942b795d24b6ccb3e9c5a "Return the effective namespace that is used when creating entities.")


|  [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) void
rclcpp_action::ServerBase::notify_goal_terminal_state  |  (  |  |  )  |
---|---|---|---|---
protected

##  ◆  publish_result()


You've now created a server-client communication that checks your actuators
and sensors during start-up, making sure that everything is working properly
before continuing.


[ wjwwood  ](https://discourse.ros.org/u/wjwwood) June 22, 2020, 8:00pm  4


##  ◆  declare_parameters()  [1/2]


The more fields a service contains, the more information the client and server
can exchange with each other.


  3.3 Running the action client  ï

Now that we have the action client built, we can run it. First make sure that
an action server is running in a separate terminal. Now source the workspace
we just built ( ` ros2_ws  ` ), and try to run the action client:

    ros2 run custom_action_cpp fibonacci_action_client

You should see logged messages for the goal being accepted, feedback being
printed, and the final result.


##  ◆  add_to_wait_set()


#include "rclcpp/node_interfaces/node_graph_interface.hpp"
#include "rclcpp/qos.hpp"
#include "rclcpp/type_support_decl.hpp"
#include "rclcpp/utilities.hpp"
#include "rclcpp/visibility_control.hpp"
#include "rmw/error_handling.h"
#include "rmw/impl/cpp/demangle.hpp"
#include "rmw/rmw.h"
namespace rclcpp
{
namespace detail
{
template<typename FutureT>
struct FutureAndRequestId
{
  FutureT future;
  int64_t request_id;
  FutureAndRequestId(FutureT impl, int64_t req_id)
  : future(std::move(impl)), request_id(req_id)
  {}
  /// Allow implicit conversions to `std::future` by reference.
  operator FutureT &() {return this->future;}
  /// Deprecated, use the `future` member variable instead.
  /**
   * Allow implicit conversions to `std::future` by value.
   * \deprecated
   */
  [[deprecated("FutureAndRequestId: use .future instead of an implicit conversion")]]
  operator FutureT() {return this->future;}
  // delegate future like methods in the std::future impl_
  /// See std::future::get().
  auto get() {return this->future.get();}
  /// See std::future::valid().
  bool valid() const noexcept {return this->future.valid();}
  /// See std::future::wait().
  void wait() const {return this->future.wait();}
  /// See std::future::wait_for().
  template<class Rep, class Period>
  std::future_status wait_for(
    const std::chrono::duration<Rep, Period> & timeout_duration) const


Exceptions


[ std::vector ](http://en.cppreference.com/w/cpp/container/vector.html) < [
rclcpp::TopicEndpointInfo ](classrclcpp_1_1TopicEndpointInfo.html) >
rclcpp::Node::get_publishers_info_by_topic  |  (  |  const [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) & |  _topic_name_
,
---|---|---|---
|  |  bool  |  _no_mangle_ = ` false `
|  )  |  |  const

Return the topic endpoint information about publishers on a given topic.


###  Company


  * include/rclcpp/ [ node.hpp ](node_8hpp_source.html)
  * include/rclcpp/ [ node_impl.hpp ](node__impl_8hpp_source.html)


In this tutorial, we'll learn how to **build a client and server node in C++,
and implement a service for them to pass data to each other.**


  * [ Community ](/community)
  * [ Newsletter ](/newsletter)
  * [ Schedule a demo ](/demo)
  * [ Contact us ](/contact)


[ Next Generation ROS  ](/c/ng-ros/25)


     [in]  |  event  |  pointer to an [ Event ](classrclcpp_1_1Event.html) to wait for
---|---|---
[in]  |  timeout  |  nanoseconds to wait for the [ Event
](classrclcpp_1_1Event.html) to change the state

Exceptions


The returned parameter is a list of topic endpoint information, where each
item will contain the node name, node namespace, topic type, endpoint type,
topic endpoint's GID, and its [ QoS ](classrclcpp_1_1QoS.html "Encapsulation
of Quality of Service settings.") profile.


If the type of the default value, and therefore also the type of return value,
differs from the initial value provided in the node options, then a [
rclcpp::exceptions::InvalidParameterTypeException
](classrclcpp_1_1exceptions_1_1InvalidParameterTypeException.html "Thrown if
requested parameter type is invalid.") may be thrown. To avoid this, use the [
declare_parameter()
](classrclcpp_1_1Node.html#a095ea977b26e7464d9371efea5f36c42 "Declare and
initialize a parameter, return the effective value.") method which returns an
[ rclcpp::ParameterValue ](classrclcpp_1_1ParameterValue.html "Store the type
and value of a parameter.") instead.


##  ◆  get_node_timers_interface()


Parameters


![](https://avatars.discourse-cdn.com/v4/letter/r/8797f3/48.png) rokel_race:


          auto execute_in_thread = [this, goal_handle](){return this->execute(goal_handle);};
          std::thread{execute_in_thread}.detach();
        };

Since the execution is a long-running operation, we spawn off a thread to do
the actual work and return from ` handle_accepted  ` quickly.

All further processing and updates are done in the ` execute  ` method in the
new thread:

      void execute(const std::shared_ptr<GoalHandleFibonacci> goal_handle) {
        RCLCPP_INFO(this->get_logger(), "Executing goal");
        rclcpp::Rate loop_rate(1);
        const auto goal = goal_handle->get_goal();
        auto feedback = std::make_shared<Fibonacci::Feedback>();
        auto & sequence = feedback->partial_sequence;
        sequence.push_back(0);
        sequence.push_back(1);
        auto result = std::make_shared<Fibonacci::Result>();

        for (int i = 1; (i < goal->order) && rclcpp::ok(); ++i) {
          // Check if there is a cancel request
          if (goal_handle->is_canceling()) {
            result->sequence = sequence;
            goal_handle->canceled(result);
            RCLCPP_INFO(this->get_logger(), "Goal canceled");
            return;
          }
          // Update sequence
          sequence.push_back(sequence[i] + sequence[i - 1]);
          // Publish feedback
          goal_handle->publish_feedback(feedback);
          RCLCPP_INFO(this->get_logger(), "Publish feedback");

          loop_rate.sleep();
        }


Get blog posts sent directly to your inbox.


` moveMotorToMinAndMax ` will simulate the motors moving to their maximum and
minimum positions. If the motor successfully reaches both limits, the function
will return ` true ` ; otherwise, it will return ` false ` .


![Collaboration graph](classrclcpp__action_1_1ServerBase__coll__graph.png)


     [in]  |  node_name  |  Name of the node.
---|---|---
[in]  |  namespace_  |  Namespace of the node.
[in]  |  options  |  Additional options to control creation of the node.

Exceptions


Subscribe


      * [ Beta 3 ( ` r2b3  ` ) ](../../Releases/Beta3-Overview.html)
      * [ Beta 2 ( ` r2b2  ` ) ](../../Releases/Beta2-Overview.html)
      * [ Beta 1 ( ` Asphalt  ` ) ](../../Releases/Beta1-Overview.html)
      * [ Alphas ](../../Releases/Alpha-Overview.html)
    * [ Development process for a release ](../../Releases/Release-Process.html)
  * [ Tutorials ](../../Tutorials.html)
    * [ Beginner: CLI tools ](../Beginner-CLI-Tools.html)
      * [ Configuring environment ](../Beginner-CLI-Tools/Configuring-ROS2-Environment.html)
      * [ Using ` turtlesim  ` , ` ros2  ` , and ` rqt  ` ](../Beginner-CLI-Tools/Introducing-Turtlesim/Introducing-Turtlesim.html)
      * [ Understanding nodes ](../Beginner-CLI-Tools/Understanding-ROS2-Nodes/Understanding-ROS2-Nodes.html)
      * [ Understanding topics ](../Beginner-CLI-Tools/Understanding-ROS2-Topics/Understanding-ROS2-Topics.html)
      * [ Understanding services ](../Beginner-CLI-Tools/Understanding-ROS2-Services/Understanding-ROS2-Services.html)
      * [ Understanding parameters ](../Beginner-CLI-Tools/Understanding-ROS2-Parameters/Understanding-ROS2-Parameters.html)
      * [ Understanding actions ](../Beginner-CLI-Tools/Understanding-ROS2-Actions/Understanding-ROS2-Actions.html)
      * [ Using ` rqt_console  ` to view logs ](../Beginner-CLI-Tools/Using-Rqt-Console/Using-Rqt-Console.html)
      * [ Launching nodes ](../Beginner-CLI-Tools/Launching-Multiple-Nodes/Launching-Multiple-Nodes.html)
      * [ Recording and playing back data ](../Beginner-CLI-Tools/Recording-And-Playing-Back-Data/Recording-And-Playing-Back-Data.html)
    * [ Beginner: Client libraries ](../Beginner-Client-Libraries.html)
      * [ Using ` colcon  ` to build packages ](Colcon-Tutorial.html)
      * [ Creating a workspace ](Creating-A-Workspace/Creating-A-Workspace.html)
      * [ Creating a package ](Creating-Your-First-ROS2-Package.html)
      * [ Writing a simple publisher and subscriber (C++) ](Writing-A-Simple-Cpp-Publisher-And-Subscriber.html)
      * [ Writing a simple publisher and subscriber (Python) ](Writing-A-Simple-Py-Publisher-And-Subscriber.html)
      * Writing a simple service and client (C++)
      * [ Writing a simple service and client (Python) ](Writing-A-Simple-Py-Service-And-Client.html)
      * [ Creating custom msg and srv files ](Custom-ROS2-Interfaces.html)
      * [ Implementing custom interfaces ](Single-Package-Define-And-Use-Interface.html)
      * [ Using parameters in a class (C++) ](Using-Parameters-In-A-Class-CPP.html)
      * [ Using parameters in a class (Python) ](Using-Parameters-In-A-Class-Python.html)
      * [ Using ` ros2doctor  ` to identify issues ](Getting-Started-With-Ros2doctor.html)
      * [ Creating and using plugins (C++) ](Pluginlib.html)
    * [ Intermediate ](../Intermediate.html)
      * [ Managing Dependencies with rosdep ](../Intermediate/Rosdep.html)
      * [ Creating an action ](../Intermediate/Creating-an-Action.html)
      * [ Writing an action server and client (C++) ](../Intermediate/Writing-an-Action-Server-Client/Cpp.html)
      * [ Writing an action server and client (Python) ](../Intermediate/Writing-an-Action-Server-Client/Py.html)
      * [ Writing a Composable Node (C++) ](../Intermediate/Writing-a-Composable-Node.html)
      * [ Composing multiple nodes in a single process ](../Intermediate/Composition.html)
      * [ Monitoring for parameter changes (C++) ](../Intermediate/Monitoring-For-Parameter-Changes-CPP.html)
      * [ Monitoring for parameter changes (Python) ](../Intermediate/Monitoring-For-Parameter-Changes-Python.html)


[ rclcpp::node_interfaces::NodeClock::get_clock ](classrclcpp_1_1node__interfaces_1_1NodeClock.html#a0998d27ad1fceaa0af4f101f54177f1a "Get a clock which will be kept up to date by the node.")


This method will never throw the [
rclcpp::exceptions::ParameterNotDeclaredException
](classrclcpp_1_1exceptions_1_1ParameterNotDeclaredException.html "Thrown if
parameter is not declared, e.g. either set or get was called without first
declaring.") exception, but will instead return false if the parameter has not
be previously declared.


a map of existing topic names to list of topic types.


article


The namespace of the node.


Coordinate open-ended communication between your ROS nodes


  3.1 Writing the action client code  ï

Open up ` custom_action_cpp/src/fibonacci_action_client.cpp  ` , and put the
following code in:

    #include <functional>
    #include <future>
    #include <memory>
    #include <string>
    #include <sstream>

    #include "custom_action_interfaces/action/fibonacci.hpp"

    #include "rclcpp/rclcpp.hpp"
    #include "rclcpp_action/rclcpp_action.hpp"
    #include "rclcpp_components/register_node_macro.hpp"

    namespace custom_action_cpp
    {
    class FibonacciActionClient : public rclcpp::Node
    {
    public:
      using Fibonacci = custom_action_interfaces::action::Fibonacci;
      using GoalHandleFibonacci = rclcpp_action::ClientGoalHandle<Fibonacci>;

      explicit FibonacciActionClient(const rclcpp::NodeOptions & options)
      : Node("fibonacci_action_client", options)
      {
        this->client_ptr_ = rclcpp_action::create_client<Fibonacci>(
          this,
          "fibonacci");

        auto timer_callback_lambda = [this](){ return this->send_goal(); };
        this->timer_ = this->create_wall_timer(
          std::chrono::milliseconds(500),
          timer_callback_lambda);
      }


rclcpp::Event::SharedPtr rclcpp::Node::get_graph_event  |  (  |  |  )  |
---|---|---|---|---

Return a graph event, which will be set anytime a graph change occurs.


Implemented in [ rclcpp_action::Server< ActionT >
](classrclcpp__action_1_1Server.html#a550ebc32b85cecf7d85d67f55695deed) .


  1.1 Creating the custom_action_cpp package  ï

Go into the action workspace you created in the [ previous tutorial
](../Creating-an-Action.html) (remember to source the workspace), and create a
new package for the C++ action server:

Linux  macOS  Windows

    cd ~/ros2_ws/src
    ros2 pkg create --dependencies custom_action_interfaces rclcpp rclcpp_action rclcpp_components --license Apache-2.0 -- custom_action_cpp

    cd ~/ros2_ws/src
    ros2 pkg create --dependencies custom_action_interfaces rclcpp rclcpp_action rclcpp_components --license Apache-2.0 -- custom_action_cpp

    cd \ros2_ws\src
    ros2 pkg create --dependencies custom_action_interfaces rclcpp rclcpp_action rclcpp_components --license Apache-2.0 -- custom_action_cpp


Like the templated [ get_parameter()
](classrclcpp_1_1Node.html#a0bf1077fba623d72fe1b49805f6c0a5a "Return the
parameter by the given name.") variant, this method will attempt to coerce the
parameter values into the type requested by the given template argument, which
may fail and throw an exception.


##  ◆  create_publisher()


Parameters


ROS Discourse is for news and general interest discussions. [ ROS Answers
](http://answers.ros.org) provides a Q&A site which can be filtered by tags to
make sure the relevant people can find and/or answer the question, and not
overload everyone with hundreds of posts.


##  Public Member Functions

---
virtual [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) |  [
~ServerBase
](classrclcpp__action_1_1ServerBase.html#aa9227b03f2895a5b5aa6fe7c24a7e58e) ()
[ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) size_t  |
[ get_number_of_ready_subscriptions
](classrclcpp__action_1_1ServerBase.html#a20cc467667673d0e524197b55a1656c4) ()
override
[ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) size_t  |
[ get_number_of_ready_timers
](classrclcpp__action_1_1ServerBase.html#a2ecbd86d39f77b73d9b6d50834d80785) ()
override
[ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) size_t  |
[ get_number_of_ready_clients
](classrclcpp__action_1_1ServerBase.html#a5fd4dc4cfc526f059ebfe3a1b75cd3db) ()
override
[ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) size_t  |
[ get_number_of_ready_services
](classrclcpp__action_1_1ServerBase.html#ac2e3b8f4c412af9746f974a1978a09bb) ()
override
[ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) size_t  |
[ get_number_of_ready_guard_conditions
](classrclcpp__action_1_1ServerBase.html#a8a24a8a7791b23b72d6b619c84155e1d) ()
override
[ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) bool  |  [
add_to_wait_set
](classrclcpp__action_1_1ServerBase.html#aed44420d3fc12ec1deed676cd216b29f) (
[ rcl_wait_set_t
](http://docs.ros2.org/foxy/api/rcl/structrcl__wait__set__t.html) *wait_set)
override
[ RCLCPP_ACTION_PUBLIC


number of subscribers who have created a subscription for a given topic.


[ ![Announcing Private Foxglove Studio Extensions for Your
Organization](/images/blog/announcing-private-foxglove-studio-extensions-for-
your-organization/hero.webp) ](/blog/announcing-private-foxglove-studio-
extensions-for-your-organization)


  * [ Discussions ](https://github.com/orgs/foxglove/discussions)
  * [ Slack ](/slack)
  * [ Twitter ](https://twitter.com/foxglove)


  Next steps  ï

In the last few tutorials youâve been utilizing interfaces to pass data
across topics and services. Next, youâll learn how to [ create custom
interfaces  ](Custom-ROS2-Interfaces.html) .


Note that entities which use absolute names are not affected by any
namespaces, neither the normal node namespace nor any sub-namespace. Note also
that the fully qualified node name is unaffected by a sub-namespace.


##  ◆  get_number_of_ready_clients()


##  ◆  get_node_clock_interface()


|  Get the namespace of the node. [ More...
](classrclcpp_1_1Node.html#a7be04e55e2934e05df992b188d9dce6d)

const char *  |  [ get_fully_qualified_name
](classrclcpp_1_1Node.html#a57f81aa79665cd9d16a591bddf762747) () const
|  Get the fully-qualified name of the node. [ More...
](classrclcpp_1_1Node.html#a57f81aa79665cd9d16a591bddf762747)

[ rclcpp::Logger ](classrclcpp_1_1Logger.html) |  [ get_logger
](classrclcpp_1_1Node.html#a884ebededa2125cb8316998852ca3fc5) () const
|  Get the logger of the node. [ More...
](classrclcpp_1_1Node.html#a884ebededa2125cb8316998852ca3fc5)

rclcpp::CallbackGroup::SharedPtr  |  [ create_callback_group
](classrclcpp_1_1Node.html#a90010521bef69072ec5008adddaf10a2) ( [
rclcpp::CallbackGroupType
](namespacerclcpp.html#a0027d5804ef28f0b6fea8eea4195c44a) group_type)
|  Create and return a callback group. [ More...
](classrclcpp_1_1Node.html#a90010521bef69072ec5008adddaf10a2)

const [ std::vector ](http://en.cppreference.com/w/cpp/container/vector.html)
< rclcpp::CallbackGroup::WeakPtr > & |  [ get_callback_groups
](classrclcpp_1_1Node.html#a90c0277b37f573e025853aea9a30b64f) () const
|  Return the list of callback groups in the node. [ More...
](classrclcpp_1_1Node.html#a90c0277b37f573e025853aea9a30b64f)

template<typename MessageT , typename AllocatorT = std::allocator<void>,
typename PublisherT = rclcpp::Publisher<MessageT, AllocatorT>>
[ std::shared_ptr ](http://en.cppreference.com/w/cpp/memory/shared_ptr.html) <
PublisherT > |  [ create_publisher
](classrclcpp_1_1Node.html#ad1dfc9d04d67ab93353e04a7df72bc9a) (const [
std::string ](http://en.cppreference.com/w/cpp/string/basic_string.html)
&topic_name, const [ rclcpp::QoS ](classrclcpp_1_1QoS.html) &qos, const [
PublisherOptionsWithAllocator
](structrclcpp_1_1PublisherOptionsWithAllocator.html) < AllocatorT > &options=
[ PublisherOptionsWithAllocator
](structrclcpp_1_1PublisherOptionsWithAllocator.html) < AllocatorT >())
|  Create and return a [ Publisher ](classrclcpp_1_1Publisher.html "A
publisher publishes messages of any type to a topic.") . [ More...
](classrclcpp_1_1Node.html#ad1dfc9d04d67ab93353e04a7df72bc9a)


[ rokel_race  ](https://discourse.ros.org/u/rokel_race) June 15, 2020, 4:25pm
1


So far I’ve been using the [ generic subscription
](https://github.com/ros2/rosbag2/blob/master/rosbag2_transport/src/rosbag2_transport/generic_subscription.hpp)
from ` rosbag2_transport ` along with introspection via [ ros2_introspection
](https://github.com/facontidavide/ros2_introspection) , which has worked
great for topic data.


const [ rclcpp::NodeOptions ](classrclcpp_1_1NodeOptions.html) &
rclcpp::Node::get_node_options  |  (  |  |  )  |  const
---|---|---|---|---

Return the [ NodeOptions ](classrclcpp_1_1NodeOptions.html "Encapsulation of
options for node initialization.") used when creating this node.


  1.2 Adding in visibility control  ï

In order to make the package compile and work on Windows, we need to add in
some âvisibility controlâ. For more details, see [ Windows Symbol
Visibility in the Windows Tips and Tricks document  ](../../../The-
ROS2-Project/Contributing/Windows-Tips-and-Tricks.html#windows-symbol-
visibility) .

Open up ` custom_action_cpp/include/custom_action_cpp/visibility_control.h  `
, and put the following code in:

    #ifndef CUSTOM_ACTION_CPP__VISIBILITY_CONTROL_H_
    #define CUSTOM_ACTION_CPP__VISIBILITY_CONTROL_H_

    #ifdef __cplusplus
    extern "C"
    {
    #endif

    // This logic was borrowed (then namespaced) from the examples on the gcc wiki:
    //     https://gcc.gnu.org/wiki/Visibility

    #if defined _WIN32 || defined __CYGWIN__
      #ifdef __GNUC__
        #define CUSTOM_ACTION_CPP_EXPORT __attribute__ ((dllexport))
        #define CUSTOM_ACTION_CPP_IMPORT __attribute__ ((dllimport))
      #else
        #define CUSTOM_ACTION_CPP_EXPORT __declspec(dllexport)
        #define CUSTOM_ACTION_CPP_IMPORT __declspec(dllimport)
      #endif
      #ifdef CUSTOM_ACTION_CPP_BUILDING_DLL
        #define CUSTOM_ACTION_CPP_PUBLIC CUSTOM_ACTION_CPP_EXPORT
      #else
        #define CUSTOM_ACTION_CPP_PUBLIC CUSTOM_ACTION_CPP_IMPORT
      #endif
      #define CUSTOM_ACTION_CPP_PUBLIC_TYPE CUSTOM_ACTION_CPP_PUBLIC
      #define CUSTOM_ACTION_CPP_LOCAL
    #else


Like [ get_parameters()
](classrclcpp_1_1Node.html#a25890d01a2cd47ce99af887f556c529b "Return the
parameters by the given parameter names.") , this method may throw the [
rclcpp::exceptions::ParameterNotDeclaredException
](classrclcpp_1_1exceptions_1_1ParameterNotDeclaredException.html "Thrown if
parameter is not declared, e.g. either set or get was called without first
declaring.") exception if any of the requested parameters have not been
declared and undeclared parameters are not allowed.


/**
   * \param[in] cancel_callback Optional callback that is called when the response is received.
   *   The callback takes one parameter: a shared pointer to the CancelResponse message.
   * \return A future to a CancelResponse message that is set when the request has been
   * acknowledged by an action server.
   * See
   *
   * action_msgs/CancelGoal.srv.
   */
  std::shared_future<typename CancelResponse::SharedPtr>
  async_cancel_all_goals(CancelCallback cancel_callback = nullptr)
  {
    auto cancel_request = std::make_shared<CancelRequest>();
    // std::fill(cancel_request->goal_info.goal_id.uuid, 0u);
    std::fill(
      cancel_request->goal_info.goal_id.uuid.begin(),
      cancel_request->goal_info.goal_id.uuid.end(), 0u);
    return async_cancel(cancel_request, cancel_callback);
  }
  /// Asynchronously request all goals at or before a specified time be canceled.
  /**
   * \param[in] stamp The timestamp for the cancel goal request.
   * \param[in] cancel_callback Optional callback that is called when the response is received.
   *   The callback takes one parameter: a shared pointer to the CancelResponse message.
   * \return A future to a CancelResponse message that is set when the request has been
   * acknowledged by an action server.
   * See
   *
   * action_msgs/CancelGoal.srv.
   */
  std::shared_future<typename CancelResponse::SharedPtr>
  async_cancel_goals_before(
    const rclcpp::Time & stamp,
    CancelCallback cancel_callback = nullptr)
  {
    auto cancel_request = std::make_shared<CancelRequest>();
    // std::fill(cancel_request->goal_info.goal_id.uuid, 0u);
    std::fill(
      cancel_request->goal_info.goal_id.uuid.begin(),
      cancel_request->goal_info.goal_id.uuid.end(), 0u);


   * The type erased pointer allows for this method to be used in a type
   * agnostic way along with ClientBase::create_response(),
   * ClientBase::create_request_header(), and ClientBase::handle_response().
   * The typed version of this can be used if the Service type is known,
   * \sa Client::take_response().
   *
   * \param[out] response_out The type erased pointer to a Service Response into
   *   which the middleware will copy the response being taken.
   * \param[out] request_header_out The request header to be filled by the
   *   middleware when taking, and which can be used to associte the response
   *   to a specific request.
   * \returns true if the response was taken, otherwise false.
   * \throws rclcpp::exceptions::RCLError based exceptions if the underlying
   *   rcl function fail.
   */
  RCLCPP_PUBLIC
  bool
  take_type_erased_response(void * response_out, rmw_request_id_t & request_header_out);
  /// Return the name of the service.
  /** \return The name of the service. */
  RCLCPP_PUBLIC
  const char *
  get_service_name() const;
  /// Return the rcl_client_t client handle in a std::shared_ptr.
  /**
   * This handle remains valid after the Client is destroyed.
   * The actual rcl client is not finalized until it is out of scope everywhere.
   */
  RCLCPP_PUBLIC
  std::shared_ptr<rcl_client_t>
  get_client_handle();
  /// Return the rcl_client_t client handle in a std::shared_ptr.
  /**
   * This handle remains valid after the Client is destroyed.
   * The actual rcl client is not finalized until it is out of scope everywhere.
   */
  RCLCPP_PUBLIC
  std::shared_ptr<const rcl_client_t>
  get_client_handle() const;
  /// Return if the service is ready.


     [ rclcpp::ParameterTypeException ](classrclcpp_1_1ParameterTypeException.html "Indicate the parameter type does not match the expected type.") |  if the requested type does not match the value of the parameter which is stored.
---|---

##  ◆  describe_parameter()


More... ](classrclcpp_1_1Node.html#afe4790bba38942b795d24b6ccb3e9c5a)

rclcpp::Node::SharedPtr  |  [ create_sub_node
](classrclcpp_1_1Node.html#a1df8e4507d17a503630317432449d69d) (const [
std::string ](http://en.cppreference.com/w/cpp/string/basic_string.html)
&sub_namespace)
|  Create a sub-node, which will extend the namespace of all entities created
with it. [ More...
](classrclcpp_1_1Node.html#a1df8e4507d17a503630317432449d69d)

const [ rclcpp::NodeOptions ](classrclcpp_1_1NodeOptions.html) & |  [
get_node_options ](classrclcpp_1_1Node.html#a53b6a37589d4371c9e0675acfc0f197a)
() const
|  Return the [ NodeOptions ](classrclcpp_1_1NodeOptions.html "Encapsulation
of options for node initialization.") used when creating this node. [ More...
](classrclcpp_1_1Node.html#a53b6a37589d4371c9e0675acfc0f197a)

template<typename ServiceT >
[ Client ](classrclcpp_1_1Client.html) < ServiceT >::SharedPtr  |  [
create_client ](classrclcpp_1_1Node.html#ac9aed5a03eb2420254745528a7d20443)
(const [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) &service_name,
const [ rmw_qos_profile_t
](http://docs.ros2.org/foxy/api/rmw/structrmw__qos__profile__t.html)
&qos_profile, rclcpp::CallbackGroup::SharedPtr group)
![-](closed.png) Public Member Functions inherited from [
std::enable_shared_from_this< Node >
](http://en.cppreference.com/w/cpp/memory/enable_shared_from_this.html)
T  |  [ enable_shared_from_this
](http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/enable_shared_from_this.html)
(T... args)
T  |  [ operator=
](http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/operator=.html)
(T... args)
T  |  [ shared_from_this
](http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/shared_from_this.html)
(T... args)
T  |  [ ~enable_shared_from_this
](http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/~enable_shared_from_this.html)
(T... args)


Shared pointer to the created subscription.


sub_node1->get_sub_namespace();  // -> "a"


Parameters


  Prerequisites  ï

You will need the ` custom_action_interfaces  ` package and the `
Fibonacci.action  ` interface defined in the previous tutorial, [ Creating an
action  ](../Creating-an-Action.html) .


    #include "rclcpp/rclcpp.hpp"
    #include "std_srvs/srv/trigger.hpp"
    // C++ namespace for representing time durations
    using namespace std::chrono_literals;


  2.1 Writing the action server code  ï

Open up ` custom_action_cpp/src/fibonacci_action_server.cpp  ` , and put the
following code in:

    #include <functional>
    #include <memory>
    #include <thread>

    #include "custom_action_interfaces/action/fibonacci.hpp"
    #include "rclcpp/rclcpp.hpp"
    #include "rclcpp_action/rclcpp_action.hpp"
    #include "rclcpp_components/register_node_macro.hpp"

    #include "custom_action_cpp/visibility_control.h"

    namespace custom_action_cpp
    {
    class FibonacciActionServer : public rclcpp::Node
    {
    public:
      using Fibonacci = custom_action_interfaces::action::Fibonacci;
      using GoalHandleFibonacci = rclcpp_action::ServerGoalHandle<Fibonacci>;

      CUSTOM_ACTION_CPP_PUBLIC
      explicit FibonacciActionServer(const rclcpp::NodeOptions & options = rclcpp::NodeOptions())
      : Node("fibonacci_action_server", options)
      {
        using namespace std::placeholders;

        auto handle_goal = [this](
          const rclcpp_action::GoalUUID & uuid,
          std::shared_ptr<const Fibonacci::Goal> goal)
        {
          RCLCPP_INFO(this->get_logger(), "Received goal request with order %d", goal->order);
          (void)uuid;
          return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;
        };


The names which are used as keys in the values map have the prefix removed.
For example, if you use the prefix "foo" and the parameters "foo.ping" and
"foo.pong" exist, then the returned map will have the keys "ping" and "pong".


This (interacting with unknown types at runtime) is an area that we need to
improve on still in the core API, in my opinion. But it is not on any
immediate road map that I’m aware of.


A list of parameter descriptors, one for each parameter given.


void rclcpp::Node::remove_on_set_parameters_callback  |  (  |  const [
OnSetParametersCallbackHandle
](classrclcpp_1_1Node.html#aac7e1fe50bc2683380cd9a635ac51edb) *const  |
_handler_ |  )  |
---|---|---|---|---|---

Remove a callback registered with ` add_on_set_parameters_callback ` .


Thanks for your question. However we ask that you please ask questions on [
http://answers.ros.org ](http://answers.ros.org) following our support
guidelines: [ http://wiki.ros.org/Support ](http://wiki.ros.org/Support)


     [in]  |  topic_name  |  the topic_name on which to find the subscriptions.
---|---|---
[in]  |  no_mangle  |  if ` true ` , ` topic_name ` needs to be a valid
middleware topic name, otherwise it should be a valid ROS topic name. Defaults
to ` false ` .

Returns


[ Product ](/product) [ Blog ](/blog) [ Customers ](/customers) [ Pricing
](/pricing) [ Docs ](https://docs.foxglove.dev) [ Download
](https://foxglove.dev/download) [ Sign in ](https://app.foxglove.dev/signin)
[ Get started ](https://app.foxglove.dev/signup)


1 Like


  }
  /// Send a request to the service server.
  /**
   * This method returns a `FutureAndRequestId` instance
   * that can be passed to Executor::spin_until_future_complete() to
   * wait until it has been completed.
   *
   * If the future never completes,
   * e.g. the call to Executor::spin_until_future_complete() times out,
   * Client::remove_pending_request() must be called to clean the client internal state.
   * Not doing so will make the `Client` instance to use more memory each time a response is not
   * received from the service server.
   *
   * ```cpp
   * auto future = client->async_send_request(my_request);
   * if (
   *   rclcpp::FutureReturnCode::TIMEOUT ==
   *   executor->spin_until_future_complete(future, timeout))
   * {
   *   client->remove_pending_request(future);
   *   // handle timeout
   * } else {
   *   handle_response(future.get());
   * }
   * ```
   *
   * \param[in] request request to be send.
   * \return a FutureAndRequestId instance.
   */
  FutureAndRequestId
  async_send_request(SharedRequest request)
  {
    Promise promise;
    auto future = promise.get_future();
    auto req_id = async_send_request_impl(
      *request,
      std::move(promise));
    return FutureAndRequestId(std::move(future), req_id);
  }
  /// Send a request to the service server and schedule a callback in the executor.


bool rclcpp::Node::get_parameters  |  (  |  const [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) & |  _prefix_ ,
---|---|---|---
|  |  [ std::map ](http://en.cppreference.com/w/cpp/container/map.html) < [
std::string ](http://en.cppreference.com/w/cpp/string/basic_string.html) ,
ParameterT > & |  _values_
|  )  |  |  const

Get the parameter values for all parameters that have a given prefix.


[ rclcpp::Clock::now ](classrclcpp_1_1Clock.html#a6375208429c40bd9d6e84b2b32557182)


[ RCUTILS_WARN_UNUSED
](http://docs.ros2.org/foxy/api/rcutils/macros_8h.html#a6be4031432c70fddf878bd574c8bccc4)
OnSetParametersCallbackHandle::SharedPtr
rclcpp::Node::add_on_set_parameters_callback  |  (  |  [
OnParametersSetCallbackType
](classrclcpp_1_1Node.html#ab403fecdb5ec2eb9f88e3eb7ae6f6d0c) |  _callback_ |
)  |
---|---|---|---|---|---

Add a callback for when parameters are being set.


When the server receives and accepts the goal, it will send a response to the
client. That response is handled by ` goal_response_callback  ` :

        send_goal_options.goal_response_callback = [this](const GoalHandleFibonacci::SharedPtr & goal_handle)
        {
          if (!goal_handle) {
            RCLCPP_ERROR(this->get_logger(), "Goal was rejected by server");
          } else {
            RCLCPP_INFO(this->get_logger(), "Goal accepted by server, waiting for result");
          }
        };

Assuming the goal was accepted by the server, it will start processing. Any
feedback to the client will be handled by the ` feedback_callback  ` :

        send_goal_options.feedback_callback = [this](
          GoalHandleFibonacci::SharedPtr,
          const std::shared_ptr<const Fibonacci::Feedback> feedback)
        {
          std::stringstream ss;
          ss << "Next number in sequence received: ";
          for (auto number : feedback->partial_sequence) {
            ss << number << " ";
          }
          RCLCPP_INFO(this->get_logger(), ss.str().c_str());
        };

When the server is finished processing, it will return a result to the client.
The result is handled by the ` result_callback  ` :

        send_goal_options.result_callback = [this](const GoalHandleFibonacci::WrappedResult & result)


template<typename ParameterT >


Is developing this functionality on any current roadmap, or has anybody
attempted this before?


I think this doesn’t count as a Q&A, as there is an answer to this yet.
I think there is a lot possible design concepts that could be discussed.


using [ rclcpp::Node::OnSetParametersCallbackHandle
](classrclcpp_1_1Node.html#aac7e1fe50bc2683380cd9a635ac51edb) = [
rclcpp::node_interfaces::OnSetParametersCallbackHandle
](structrclcpp_1_1node__interfaces_1_1OnSetParametersCallbackHandle.html)
---

##  ◆  OnParametersSetCallbackType


rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr
rclcpp::Node::get_node_topics_interface  |  (  |  |  )  |
---|---|---|---|---

Return the [ Node ](classrclcpp_1_1Node.html "Node is the single point of
entry for creating publishers and subscribers.") 's internal
NodeTopicsInterface implementation.


#  2 Writing an action server  ï

Letâs focus on writing an action server that computes the Fibonacci sequence
using the action we created in the [ Creating an action  ](../Creating-an-
Action.html) tutorial.


The fully-qualified name includes the local namespace and name of the node.


C++ ROS Client Library API

---

  * [ rclcpp ](namespacerclcpp.html)
  * [ Node ](classrclcpp_1_1Node.html)


](namespacerclcpp__action.html#ababbbebf29fec7c541687c724fc82ba7) , [
std::shared_ptr ](http://en.cppreference.com/w/cpp/memory/shared_ptr.html) <
void > > |  [ call_handle_goal_callback
](classrclcpp__action_1_1ServerBase.html#a7cc2bbdc20cd5c86041992be0da32a11) (
[ GoalUUID ](namespacerclcpp__action.html#a67daf44a45003173e42ccc612fcb052b)
&, [ std::shared_ptr
](http://en.cppreference.com/w/cpp/memory/shared_ptr.html) < void > request)=0
virtual [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) [
CancelResponse
](namespacerclcpp__action.html#a27ea2386548de7ad3bef27bb3c0eed05) |  [
call_handle_cancel_callback
](classrclcpp__action_1_1ServerBase.html#a0b63ea292214103e05139de594d4f310)
(const [ GoalUUID
](namespacerclcpp__action.html#a67daf44a45003173e42ccc612fcb052b) &uuid)=0
virtual [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) [ GoalUUID
](namespacerclcpp__action.html#a67daf44a45003173e42ccc612fcb052b) |  [
get_goal_id_from_goal_request
](classrclcpp__action_1_1ServerBase.html#a0ab6c2b8eb1f794d0b6aa87a224551cd)
(void *message)=0
virtual [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) [
std::shared_ptr ](http://en.cppreference.com/w/cpp/memory/shared_ptr.html) <
void > |  [ create_goal_request
](classrclcpp__action_1_1ServerBase.html#a59498822f73d618624c7ec1e191aedfe)
()=0
virtual [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) void  |  [
call_goal_accepted_callback
](classrclcpp__action_1_1ServerBase.html#ac6295e5eac92fd58c9e29486d8631e41) (
[ std::shared_ptr ](http://en.cppreference.com/w/cpp/memory/shared_ptr.html) <
[ rcl_action_goal_handle_t
](http://docs.ros2.org/foxy/api/rcl_action/structrcl__action__goal__handle__t.html)
> rcl_goal_handle, [ GoalUUID
](namespacerclcpp__action.html#a67daf44a45003173e42ccc612fcb052b) uuid, [
std::shared_ptr ](http://en.cppreference.com/w/cpp/memory/shared_ptr.html) <
void > goal_request_message)=0
virtual [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) [ GoalUUID


sub_node2->get_sub_namespace();  // -> "a/b"


     [in]  |  node_name  |  the node_name on which to count the publishers.
---|---|---
[in]  |  namespace_  |  the namespace of the node associated with the name

Returns


##  ◆  get_parameters()  [1/2]


No one is planning to do this as far as I know. It sounds like what you
proposed might work, but without digging into it, I’d have a hard time saying
one way or the other.


rcl_interfaces::msg::ListParametersResult rclcpp::Node::list_parameters  |  (
|  const [ std::vector
](http://en.cppreference.com/w/cpp/container/vector.html) < [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) > & |  _prefixes_
,
---|---|---|---
|  |  uint64_t  |  _depth_
|  )  |  |  const

Return a list of parameters with any of the given prefixes, up to the given
depth.


    cancel_request->goal_info.stamp = stamp;
    return async_cancel(cancel_request, cancel_callback);
  }
  virtual
  ~Client()
  {
    std::lock_guard<std::mutex> guard(goal_handles_mutex_);
    auto it = goal_handles_.begin();
    while (it != goal_handles_.end()) {
      typename GoalHandle::SharedPtr goal_handle = it->second.lock();
      if (goal_handle) {
        goal_handle->invalidate(exceptions::UnawareGoalHandleError());
      }
      it = goal_handles_.erase(it);
    }
  }
private:
  /// \internal
  std::shared_ptr<void>
  create_goal_response() const override
  {
    using GoalResponse = typename ActionT::Impl::SendGoalService::Response;
    return std::shared_ptr<void>(new GoalResponse());
  }
  /// \internal
  std::shared_ptr<void>
  create_result_response() const override
  {
    using GoalResultResponse = typename ActionT::Impl::GetResultService::Response;
    return std::shared_ptr<void>(new GoalResultResponse());
  }
  /// \internal
  std::shared_ptr<void>
  create_cancel_response() const override
  {
    return std::shared_ptr<void>(new CancelResponse());
  }
  /// \internal
  std::shared_ptr<void>
  create_feedback_message() const override


Make discrete requests between ROS nodes for one-off tasks


    : detail::FutureAndRequestId<std::future<SharedResponse>>
  {
    using detail::FutureAndRequestId<std::future<SharedResponse>>::FutureAndRequestId;
    /// Deprecated, use `.future.share()` instead.
    /**
     * Allow implicit conversions to `std::shared_future` by value.
     * \deprecated
     */
    [[deprecated(
      "FutureAndRequestId: use .future.share() instead of an implicit conversion")]]
    operator SharedFuture() {return this->future.share();}
    // delegate future like methods in the std::future impl_
    /// See std::future::share().
    SharedFuture share() noexcept {return this->future.share();}
  };
  /// A convenient Client::SharedFuture and request id pair.
  /**
   * Public members:
   * - future: a std::shared_future<SharedResponse>.
   * - request_id: the request id associated with the future.
   *
   * All the other methods are equivalent to the ones std::shared_future provides.
   */
  struct SharedFutureAndRequestId
    : detail::FutureAndRequestId<std::shared_future<SharedResponse>>
  {
    using detail::FutureAndRequestId<std::shared_future<SharedResponse>>::FutureAndRequestId;
  };
  /// A convenient Client::SharedFutureWithRequest and request id pair.
  /**
   * Public members:
   * - future: a std::shared_future<SharedResponse>.
   * - request_id: the request id associated with the future.
   *
   * All the other methods are equivalent to the ones std::shared_future provides.
   */
  struct SharedFutureWithRequestAndRequestId
    : detail::FutureAndRequestId<std::shared_future<std::pair<SharedRequest, SharedResponse>>>
  {
    using detail::FutureAndRequestId<


Like set_parameter, if any of the parameters to be set have not first been
declared, and undeclared parameters are not allowed (the default), then this
method will throw [ rclcpp::exceptions::ParameterNotDeclaredException
](classrclcpp_1_1exceptions_1_1ParameterNotDeclaredException.html "Thrown if
parameter is not declared, e.g. either set or get was called without first
declaring.") .


Returns


](namespacerclcpp__action.html#a67daf44a45003173e42ccc612fcb052b) |  [
get_goal_id_from_result_request
](classrclcpp__action_1_1ServerBase.html#ac4074115e5b5967f509c20a0b09b2647)
(void *message)=0
virtual [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) [
std::shared_ptr ](http://en.cppreference.com/w/cpp/memory/shared_ptr.html) <
void > |  [ create_result_request
](classrclcpp__action_1_1ServerBase.html#ad4fdf05782782e3ea01e8aafd6b9eccd)
()=0
virtual [ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) [
std::shared_ptr ](http://en.cppreference.com/w/cpp/memory/shared_ptr.html) <
void > |  [ create_result_response
](classrclcpp__action_1_1ServerBase.html#a89f2f956eb78af2bfeb695da330f888b)
(decltype(action_msgs::msg::GoalStatus::status) status)=0
[ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) void  |  [
publish_status
](classrclcpp__action_1_1ServerBase.html#af9042363e4f33c4625ded77338156051) ()
[ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) void  |  [
notify_goal_terminal_state
](classrclcpp__action_1_1ServerBase.html#a7cd4e92510a60af5a52f01012e293045) ()
[ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) void  |  [
publish_result
](classrclcpp__action_1_1ServerBase.html#a9fa920a4b8383bb48bd0ba2995609813)
(const [ GoalUUID
](namespacerclcpp__action.html#a67daf44a45003173e42ccc612fcb052b) &uuid, [
std::shared_ptr ](http://en.cppreference.com/w/cpp/memory/shared_ptr.html) <
void > result_msg)
[ RCLCPP_ACTION_PUBLIC
](visibility__control_8hpp.html#a736fe60d4de4417a213ed34ba1926048) void  |  [
publish_feedback
](classrclcpp__action_1_1ServerBase.html#ae29a00ddaf7e45fdf8ca1585b71b7a66) (
[ std::shared_ptr ](http://en.cppreference.com/w/cpp/memory/shared_ptr.html) <
void > feedback_msg)

##  Detailed Description


[ std::vector ](http://en.cppreference.com/w/cpp/container/vector.html) <
ParameterT > rclcpp::Node::declare_parameters  |  (  |  const [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) & |  _namespace__
,
---|---|---|---
|  |  const [ std::map ](http://en.cppreference.com/w/cpp/container/map.html)
< [ std::string ](http://en.cppreference.com/w/cpp/string/basic_string.html) ,
ParameterT > & |  _parameters_ ,
|  |  bool  |  _ignore_overrides_ = ` false `
|  )  |  |

Declare and initialize several parameters with the same namespace and type.


    int main(int argc, char **argv) {
      // Initiate the rclcpp library
      rclcpp::init(argc, argv);

      // Create a shared pointer to node and name it "diagnostics_node"
      std::shared_ptr<rclcpp::Node> node=rclcpp::Node::make_shared("diagnostics_node");

      // Create client inside the node to call our "checks" server node
      rclcpp::Client<std_srvs::srv::Trigger>::SharedPtr client =
        node->create_client<std_srvs::srv::Trigger>("checks");


[ Node ](classrclcpp_1_1Node.html "Node is the single point of entry for
creating publishers and subscribers.") is the single point of entry for
creating publishers and subscribers. [ More...
](classrclcpp_1_1Node.html#details)


To define a service, you must create a ` .srv ` file in your ROS 2 package’s `
srv ` directory that contains both those components:


![Inheritance graph](classrclcpp_1_1Node__inherit__graph.png)


[ rclcpp::Service ](classrclcpp_1_1Service.html) < ServiceT >::SharedPtr
rclcpp::Node::create_service  |  (  |  const [ std::string
](http://en.cppreference.com/w/cpp/string/basic_string.html) & |
_service_name_ ,
---|---|---|---
|  |  CallbackT && |  _callback_ ,
|  |  const [ rmw_qos_profile_t
](http://docs.ros2.org/foxy/api/rmw/structrmw__qos__profile__t.html) & |
_qos_profile_ = ` rmw_qos_profile_services_default ` ,
|  |  rclcpp::CallbackGroup::SharedPtr  |  _group_ = ` nullptr `
|  )  |  |

Create and return a [ Service ](classrclcpp_1_1Service.html) .


Finally, we create a ` main ` function as our entrypoint:


For each key in the map, a parameter with a name of "namespace.key" will be
set to the value in the map. The resulting value for each declared parameter
will be returned.


Parameters


` scoped_callback.reset() `


###  Read more:


  * [ About ](/about)
  * [ Blog ](/blog)
  * [ Careers ](/careers)
  * [ Customers ](/customers)
  * [ Media ](/media)


     [in]  |  service_name  |  The topic to service on.
---|---|---
[in]  |  callback  |  User-defined callback function.
[in]  |  qos_profile  |  [ rmw_qos_profile_t
](http://docs.ros2.org/foxy/api/rmw/structrmw__qos__profile__t.html) Quality
of service profile for client.
[in]  |  group  |  Callback group to call the service.

Returns


      auto result = client->async_send_request(request);
      // Wait for the result.
      if (rclcpp::spin_until_future_complete(node, result) ==
        rclcpp::FutureReturnCode::SUCCESS)
      {
        RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "Sum: %ld", result.get()->sum);
      } else {
        RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Failed to call service add_two_ints");
      }

      rclcpp::shutdown();
      return 0;
    }