PX4 ROS 2 Interface Library
Library to interface with PX4 from a companion computer using ROS 2
Loading...
Searching...
No Matches
subscription.hpp
1/****************************************************************************
2 * Copyright (c) 2023 PX4 Development Team.
3 * SPDX-License-Identifier: BSD-3-Clause
4 ****************************************************************************/
5
6#pragma once
7
8#include <px4_ros2/common/context.hpp>
9#include <px4_ros2/common/exception.hpp>
10#include <px4_ros2/components/shared_subscription.hpp>
11
12using namespace std::chrono_literals; // NOLINT
13
14namespace px4_ros2 {
26template <typename RosMessageType>
28 using UpdateCallback = std::function<void(const RosMessageType&)>;
29
30 public:
31 Subscription(Context& context, const std::string& topic) : _node(context.node())
32 {
33 const std::string namespaced_topic = context.topicNamespacePrefix() + topic;
35 _node, namespaced_topic, [this](const typename RosMessageType::UniquePtr& msg) {
36 _last = *msg;
37 _last_message_time = _node.get_clock()->now();
38 for (const auto& callback : _callbacks) {
39 callback(_last);
40 }
41 });
42 }
43
49 void onUpdate(const UpdateCallback& callback) { _callbacks.push_back(callback); }
50
57 const RosMessageType& last() const
58 {
59 if (!hasReceivedMessages()) {
60 throw Exception("No messages received.");
61 }
62 return _last;
63 }
64
70 const rclcpp::Time& lastTime() const { return _last_message_time; }
71
79 template <typename DurationT = std::milli>
80 bool lastValid(const std::chrono::duration<int64_t, DurationT> max_delay = 500ms) const
81 {
82 return hasReceivedMessages() && _node.get_clock()->now() - _last_message_time < max_delay;
83 }
84
85 protected:
86 rclcpp::Node& _node;
87
88 private:
89 SharedSubscriptionCallbackInstance _callback_instance;
90
91 RosMessageType _last;
92 rclcpp::Time _last_message_time;
93
94 std::vector<std::function<void(const RosMessageType&)>> _callbacks{};
95
96 bool hasReceivedMessages() const { return _last_message_time.seconds() != 0; }
97};
98
100} // namespace px4_ros2
Shared class for a ROS subscription.
Definition shared_subscription.hpp:39
Definition context.hpp:18
Definition exception.hpp:14
Provides a subscription to arbitrary ROS topics.
Definition subscription.hpp:27
const rclcpp::Time & lastTime() const
Get the receive-time of the last message.
Definition subscription.hpp:70
bool lastValid(const std::chrono::duration< int64_t, DurationT > max_delay=500ms) const
Check whether the last message is still valid. To be valid, the message must have been received withi...
Definition subscription.hpp:80
void onUpdate(const UpdateCallback &callback)
Add a callback to execute when receiving a new message.
Definition subscription.hpp:49
const RosMessageType & last() const
Get the last-received message.
Definition subscription.hpp:57