-
Notifications
You must be signed in to change notification settings - Fork 152
/
Copy pathnode.rs
484 lines (450 loc) · 17.1 KB
/
node.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
mod builder;
mod graph;
use std::cmp::PartialEq;
use std::ffi::CStr;
use std::fmt;
use std::os::raw::c_char;
use std::sync::{Arc, Mutex, Weak};
use std::vec::Vec;
use rosidl_runtime_rs::Message;
pub use self::builder::*;
pub use self::graph::*;
use crate::rcl_bindings::*;
use crate::{
Client, ClientBase, Clock, Context, GuardCondition, ParameterBuilder, ParameterInterface,
ParameterVariant, Parameters, Publisher, QoSProfile, RclrsError, Service, ServiceBase,
Subscription, SubscriptionBase, SubscriptionCallback, TimeSource, ToResult,
};
impl Drop for rcl_node_t {
fn drop(&mut self) {
// SAFETY: No preconditions for this function
unsafe { rcl_node_fini(self).ok().unwrap() };
}
}
// SAFETY: The functions accessing this type, including drop(), shouldn't care about the thread
// they are running in. Therefore, this type can be safely sent to another thread.
unsafe impl Send for rcl_node_t {}
/// A processing unit that can communicate with other nodes.
///
/// Nodes are a core concept in ROS 2. Refer to the official ["Understanding ROS 2 nodes"][1]
/// tutorial for an introduction.
///
/// Ownership of the node is shared with all [`Publisher`]s and [`Subscription`]s created from it.
/// That means that even after the node itself is dropped, it will continue to exist and be
/// displayed by e.g. `ros2 topic` as long as its publishers and subscriptions are not dropped.
///
/// # Naming
/// A node has a *name* and a *namespace*.
/// The node namespace will be prefixed to the node name to form the *fully qualified
/// node name*. This is the name that is shown e.g. in `ros2 node list`.
/// Similarly, the node namespace will be prefixed to all names of topics and services
/// created from this node.
///
/// By convention, a node name with a leading underscore marks the node as hidden.
///
/// It's a good idea for node names in the same executable to be unique.
///
/// ## Remapping
/// The namespace and name given when creating the node can be overriden through the command line.
/// In that sense, the parameters to the node creation functions are only the _default_ namespace and
/// name.
/// See also the [official tutorial][1] on the command line arguments for ROS nodes, and the
/// [`Node::namespace()`] and [`Node::name()`] functions for examples.
///
/// ## Rules for valid names
/// The rules for valid node names and node namespaces are explained in
/// [`NodeBuilder::new()`][3] and [`NodeBuilder::namespace()`][4].
///
/// [1]: https://docs.ros.org/en/rolling/Tutorials/Understanding-ROS2-Nodes.html
/// [2]: https://docs.ros.org/en/rolling/How-To-Guides/Node-arguments.html
/// [3]: crate::NodeBuilder::new
/// [4]: crate::NodeBuilder::namespace
pub struct Node {
pub(crate) clients_mtx: Mutex<Vec<Weak<dyn ClientBase>>>,
pub(crate) guard_conditions_mtx: Mutex<Vec<Weak<GuardCondition>>>,
pub(crate) services_mtx: Mutex<Vec<Weak<dyn ServiceBase>>>,
pub(crate) subscriptions_mtx: Mutex<Vec<Weak<dyn SubscriptionBase>>>,
time_source: TimeSource,
parameter: ParameterInterface,
// Note: it's important to have those last since `drop` will be called in order of declaration
// in the struct and both `TimeSource` and `ParameterInterface` contain subscriptions /
// services that will fail to be dropped if the context or node is destroyed first.
pub(crate) rcl_node_mtx: Arc<Mutex<rcl_node_t>>,
pub(crate) rcl_context_mtx: Arc<Mutex<rcl_context_t>>,
}
impl Eq for Node {}
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.rcl_node_mtx, &other.rcl_node_mtx)
}
}
impl fmt::Debug for Node {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.debug_struct("Node")
.field("fully_qualified_name", &self.fully_qualified_name())
.finish()
}
}
impl Node {
/// Creates a new node in the empty namespace.
///
/// See [`NodeBuilder::new()`] for documentation.
#[allow(clippy::new_ret_no_self)]
pub fn new(context: &Context, node_name: &str) -> Result<Arc<Node>, RclrsError> {
Self::builder(context, node_name).build()
}
/// Returns the clock associated with this node.
pub fn get_clock(&self) -> Clock {
self.time_source.get_clock()
}
/// Returns the name of the node.
///
/// This returns the name after remapping, so it is not necessarily the same as the name that
/// was used when creating the node.
///
/// # Example
/// ```
/// # use rclrs::{Context, RclrsError};
/// // Without remapping
/// let context = Context::new([])?;
/// let node = rclrs::create_node(&context, "my_node")?;
/// assert_eq!(node.name(), "my_node");
/// // With remapping
/// let remapping = ["--ros-args", "-r", "__node:=your_node"].map(String::from);
/// let context_r = Context::new(remapping)?;
/// let node_r = rclrs::create_node(&context_r, "my_node")?;
/// assert_eq!(node_r.name(), "your_node");
/// # Ok::<(), RclrsError>(())
/// ```
pub fn name(&self) -> String {
self.call_string_getter(rcl_node_get_name)
}
/// Returns the namespace of the node.
///
/// This returns the namespace after remapping, so it is not necessarily the same as the
/// namespace that was used when creating the node.
///
/// # Example
/// ```
/// # use rclrs::{Context, RclrsError};
/// // Without remapping
/// let context = Context::new([])?;
/// let node =
/// rclrs::create_node_builder(&context, "my_node")
/// .namespace("/my/namespace")
/// .build()?;
/// assert_eq!(node.namespace(), "/my/namespace");
/// // With remapping
/// let remapping = ["--ros-args", "-r", "__ns:=/your_namespace"].map(String::from);
/// let context_r = Context::new(remapping)?;
/// let node_r = rclrs::create_node(&context_r, "my_node")?;
/// assert_eq!(node_r.namespace(), "/your_namespace");
/// # Ok::<(), RclrsError>(())
/// ```
pub fn namespace(&self) -> String {
self.call_string_getter(rcl_node_get_namespace)
}
/// Returns the fully qualified name of the node.
///
/// The fully qualified name of the node is the node namespace combined with the node name.
/// It is subject to the remappings shown in [`Node::name()`] and [`Node::namespace()`].
///
/// # Example
/// ```
/// # use rclrs::{Context, RclrsError};
/// let context = Context::new([])?;
/// let node =
/// rclrs::create_node_builder(&context, "my_node")
/// .namespace("/my/namespace")
/// .build()?;
/// assert_eq!(node.fully_qualified_name(), "/my/namespace/my_node");
/// # Ok::<(), RclrsError>(())
/// ```
pub fn fully_qualified_name(&self) -> String {
self.call_string_getter(rcl_node_get_fully_qualified_name)
}
// Helper for name(), namespace(), fully_qualified_name()
fn call_string_getter(
&self,
getter: unsafe extern "C" fn(*const rcl_node_t) -> *const c_char,
) -> String {
unsafe { call_string_getter_with_handle(&self.rcl_node_mtx.lock().unwrap(), getter) }
}
/// Creates a [`Client`][1].
///
/// [1]: crate::Client
// TODO: make client's lifetime depend on node's lifetime
pub fn create_client<T>(&self, topic: &str) -> Result<Arc<Client<T>>, RclrsError>
where
T: rosidl_runtime_rs::Service,
{
let client = Arc::new(Client::<T>::new(Arc::clone(&self.rcl_node_mtx), topic)?);
{ self.clients_mtx.lock().unwrap() }.push(Arc::downgrade(&client) as Weak<dyn ClientBase>);
Ok(client)
}
/// Creates a [`GuardCondition`][1] with no callback.
///
/// A weak pointer to the `GuardCondition` is stored within this node.
/// When this node is added to a wait set (e.g. when calling `spin_once`[2]
/// with this node as an argument), the guard condition can be used to
/// interrupt the wait.
///
/// [1]: crate::GuardCondition
/// [2]: crate::spin_once
pub fn create_guard_condition(&self) -> Arc<GuardCondition> {
let guard_condition = Arc::new(GuardCondition::new_with_rcl_context(
&mut self.rcl_context_mtx.lock().unwrap(),
None,
));
{ self.guard_conditions_mtx.lock().unwrap() }
.push(Arc::downgrade(&guard_condition) as Weak<GuardCondition>);
guard_condition
}
/// Creates a [`GuardCondition`][1] with a callback.
///
/// A weak pointer to the `GuardCondition` is stored within this node.
/// When this node is added to a wait set (e.g. when calling `spin_once`[2]
/// with this node as an argument), the guard condition can be used to
/// interrupt the wait.
///
/// [1]: crate::GuardCondition
/// [2]: crate::spin_once
pub fn create_guard_condition_with_callback<F>(&mut self, callback: F) -> Arc<GuardCondition>
where
F: Fn() + Send + Sync + 'static,
{
let guard_condition = Arc::new(GuardCondition::new_with_rcl_context(
&mut self.rcl_context_mtx.lock().unwrap(),
Some(Box::new(callback) as Box<dyn Fn() + Send + Sync>),
));
{ self.guard_conditions_mtx.lock().unwrap() }
.push(Arc::downgrade(&guard_condition) as Weak<GuardCondition>);
guard_condition
}
/// Creates a [`Publisher`][1].
///
/// [1]: crate::Publisher
// TODO: make publisher's lifetime depend on node's lifetime
pub fn create_publisher<T>(
&self,
topic: &str,
qos: QoSProfile,
) -> Result<Arc<Publisher<T>>, RclrsError>
where
T: Message,
{
let publisher = Arc::new(Publisher::<T>::new(
Arc::clone(&self.rcl_node_mtx),
topic,
qos,
)?);
Ok(publisher)
}
/// Creates a [`Service`][1].
///
/// [1]: crate::Service
// TODO: make service's lifetime depend on node's lifetime
pub fn create_service<T>(
&self,
topic: &str,
mut callback: impl FnMut(T::Request) -> T::Response + 'static + Send,
) -> Result<Arc<Service<T>>, RclrsError>
where
T: rosidl_runtime_rs::Service,
{
let callback =
move |_request_header: &rmw_request_id_t, request: T::Request| callback(request);
self.create_service_with_header(topic, callback)
}
/// Creates a [`Service`][1]. Same as [`create_service`][2] but the callback
/// also has access to the ID of the service request.
///
/// [1]: crate::Service
/// [2]: Self::create_service
// TODO: make service's lifetime depend on node's lifetime
pub fn create_service_with_header<T>(
&self,
topic: &str,
callback: impl FnMut(&rmw_request_id_t, T::Request) -> T::Response + 'static + Send,
) -> Result<Arc<Service<T>>, RclrsError>
where
T: rosidl_runtime_rs::Service,
{
let service = Arc::new(Service::<T>::new(
Arc::clone(&self.rcl_node_mtx),
topic,
callback,
)?);
{ self.services_mtx.lock().unwrap() }
.push(Arc::downgrade(&service) as Weak<dyn ServiceBase>);
Ok(service)
}
/// Creates a [`Subscription`][1].
///
/// [1]: crate::Subscription
// TODO: make subscription's lifetime depend on node's lifetime
pub fn create_subscription<T, Args>(
&self,
topic: &str,
qos: QoSProfile,
callback: impl SubscriptionCallback<T, Args>,
) -> Result<Arc<Subscription<T>>, RclrsError>
where
T: Message,
{
let subscription = Arc::new(Subscription::<T>::new(
Arc::clone(&self.rcl_node_mtx),
topic,
qos,
callback,
)?);
{ self.subscriptions_mtx.lock() }
.unwrap()
.push(Arc::downgrade(&subscription) as Weak<dyn SubscriptionBase>);
Ok(subscription)
}
/// Returns the subscriptions that have not been dropped yet.
pub(crate) fn live_subscriptions(&self) -> Vec<Arc<dyn SubscriptionBase>> {
{ self.subscriptions_mtx.lock().unwrap() }
.iter()
.filter_map(Weak::upgrade)
.collect()
}
pub(crate) fn live_clients(&self) -> Vec<Arc<dyn ClientBase>> {
{ self.clients_mtx.lock().unwrap() }
.iter()
.filter_map(Weak::upgrade)
.collect()
}
pub(crate) fn live_guard_conditions(&self) -> Vec<Arc<GuardCondition>> {
{ self.guard_conditions_mtx.lock().unwrap() }
.iter()
.filter_map(Weak::upgrade)
.collect()
}
pub(crate) fn live_services(&self) -> Vec<Arc<dyn ServiceBase>> {
{ self.services_mtx.lock().unwrap() }
.iter()
.filter_map(Weak::upgrade)
.collect()
}
/// Returns the ROS domain ID that the node is using.
///
/// The domain ID controls which nodes can send messages to each other, see the [ROS 2 concept article][1].
/// It can be set through the `ROS_DOMAIN_ID` environment variable.
///
/// [1]: https://docs.ros.org/en/rolling/Concepts/About-Domain-ID.html
///
/// # Example
/// ```
/// # use rclrs::{Context, RclrsError};
/// // Set default ROS domain ID to 10 here
/// std::env::set_var("ROS_DOMAIN_ID", "10");
/// let context = Context::new([])?;
/// let node = rclrs::create_node(&context, "domain_id_node")?;
/// let domain_id = node.domain_id();
/// assert_eq!(domain_id, 10);
/// # Ok::<(), RclrsError>(())
/// ```
// TODO: If node option is supported,
// add description about this function is for getting actual domain_id
// and about override of domain_id via node option
pub fn domain_id(&self) -> usize {
let rcl_node = &*self.rcl_node_mtx.lock().unwrap();
let mut domain_id: usize = 0;
let ret = unsafe {
// SAFETY: No preconditions for this function.
rcl_node_get_domain_id(rcl_node, &mut domain_id)
};
debug_assert_eq!(ret, 0);
domain_id
}
/// Creates a [`ParameterBuilder`] that can be used to set parameter declaration options and
/// declare a parameter as [`OptionalParameter`](crate::parameter::OptionalParameter),
/// [`MandatoryParameter`](crate::parameter::MandatoryParameter), or
/// [`ReadOnly`](crate::parameter::ReadOnlyParameter).
///
/// # Example
/// ```
/// # use rclrs::{Context, ParameterRange, RclrsError};
/// let context = Context::new([])?;
/// let node = rclrs::create_node(&context, "domain_id_node")?;
/// // Set it to a range of 0-100, with a step of 2
/// let range = ParameterRange {
/// lower: Some(0),
/// upper: Some(100),
/// step: Some(2),
/// };
/// let param = node.declare_parameter("int_param")
/// .default(10)
/// .range(range)
/// .mandatory()
/// .unwrap();
/// assert_eq!(param.get(), 10);
/// param.set(50).unwrap();
/// assert_eq!(param.get(), 50);
/// // Out of range, will return an error
/// assert!(param.set(200).is_err());
/// # Ok::<(), RclrsError>(())
/// ```
pub fn declare_parameter<'a, T: ParameterVariant + 'a>(
&'a self,
name: impl Into<Arc<str>>,
) -> ParameterBuilder<'a, T> {
self.parameter.declare(name.into())
}
/// Enables usage of undeclared parameters for this node.
///
/// Returns a [`Parameters`] struct that can be used to get and set all parameters.
pub fn use_undeclared_parameters(&self) -> Parameters {
self.parameter.allow_undeclared();
Parameters {
interface: &self.parameter,
}
}
/// Creates a [`NodeBuilder`][1] with the given name.
///
/// Convenience function equivalent to [`NodeBuilder::new()`][2].
///
/// [1]: crate::NodeBuilder
/// [2]: crate::NodeBuilder::new
///
/// # Example
/// ```
/// # use rclrs::{Context, Node, RclrsError};
/// let context = Context::new([])?;
/// let node = Node::builder(&context, "my_node").build()?;
/// assert_eq!(node.name(), "my_node");
/// # Ok::<(), RclrsError>(())
/// ```
pub fn builder(context: &Context, node_name: &str) -> NodeBuilder {
NodeBuilder::new(context, node_name)
}
}
// Helper used to implement call_string_getter(), but also used to get the FQN in the Node::new()
// function, which is why it's not merged into Node::call_string_getter().
// This function is unsafe since it's possible to pass in an rcl_node_t with dangling
// pointers etc.
pub(crate) unsafe fn call_string_getter_with_handle(
rcl_node: &rcl_node_t,
getter: unsafe extern "C" fn(*const rcl_node_t) -> *const c_char,
) -> String {
let char_ptr = getter(rcl_node);
debug_assert!(!char_ptr.is_null());
// SAFETY: The returned CStr is immediately converted to an owned string,
// so the lifetime is no issue. The ptr is valid as per the documentation
// of rcl_node_get_name.
let cstr = CStr::from_ptr(char_ptr);
cstr.to_string_lossy().into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
#[test]
fn node_is_send_and_sync() {
assert_send::<Node>();
assert_sync::<Node>();
}
}