Skip to main content

rustorb_dds_ros2/
node.rs

1//! ROS 2 nodes on a DDS participant, announced on `ros_discovery_info`.
2//!
3//! A ROS 2 node is not a DDS entity. ROS 2 (since Foxy) tells which
4//! writers and readers belong to which node on the DDS topic
5//! `ros_discovery_info`, of type `rmw_dds_common/msg/ParticipantEntitiesInfo`:
6//! each participant writes, every time its nodes or their endpoints
7//! change, the GID of the participant and, for each of its nodes, the
8//! namespace, the name and the GIDs of the node's readers and writers. A
9//! GID is the 16 octets of a DDS GUID. The writer is RELIABLE,
10//! TRANSIENT_LOCAL, KEEP_LAST(1), so that late joiners get the last one.
11//! Without it, `ros2 node list` does not show the nodes, and `ros2 topic
12//! info -v` shows the endpoints under `_NODE_NAME_UNKNOWN_`; the data
13//! goes through anyway.
14
15use std::collections::BTreeMap;
16use std::sync::atomic::{AtomicU64, Ordering};
17use std::sync::{Arc, Mutex};
18
19use rustorb_dds::{
20    DataReader, DataWriter, DiscoveredEndpoint, DomainParticipant, DynamicData, Guid,
21    ParticipantConfig, SampleInfo,
22};
23
24use crate::library::{MessageType, TypeLibrary};
25use crate::names::{
26    expand_topic_name, service_to_dds, topic_to_dds, validate_namespace, validate_node_name,
27};
28use crate::qos::QosProfile;
29use crate::user_data::{ENCLAVE_KEY, UserData};
30use crate::value::Value;
31use crate::{Error, Result};
32
33/// The DDS topic of the graph of ROS 2 nodes.
34pub const DISCOVERY_INFO_TOPIC: &str = "ros_discovery_info";
35/// The type of [`DISCOVERY_INFO_TOPIC`].
36pub const DISCOVERY_INFO_TYPE: &str = "rmw_dds_common/msg/ParticipantEntitiesInfo";
37
38#[derive(Debug)]
39struct NodeEntry {
40    namespace: String,
41    name: String,
42    readers: Vec<Guid>,
43    writers: Vec<Guid>,
44}
45
46struct Context {
47    info_type: MessageType,
48    info_writer: DataWriter<DynamicData>,
49    nodes: Mutex<BTreeMap<u64, NodeEntry>>,
50    next_node: AtomicU64,
51    publisher: rustorb_dds::Publisher,
52    subscriber: rustorb_dds::Subscriber,
53    participant: DomainParticipant,
54}
55
56impl std::fmt::Debug for Context {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("Context")
59            .field("participant", &self.participant.guid())
60            .field("nodes", &self.nodes)
61            .finish_non_exhaustive()
62    }
63}
64
65fn gid(g: Guid) -> Value {
66    Value::Struct(vec![("data".into(), Value::Bytes(g.to_bytes().to_vec()))])
67}
68
69impl Context {
70    /// Writes the nodes and their endpoints on `ros_discovery_info`.
71    fn announce(&self) -> Result<()> {
72        let nodes = self.nodes.lock().expect("not poisoned");
73        let gids = |v: &[Guid]| Value::List(v.iter().copied().map(gid).collect());
74        let info = Value::Struct(vec![
75            ("gid".into(), gid(self.participant.guid())),
76            (
77                "node_entities_info_seq".into(),
78                Value::List(
79                    nodes
80                        .values()
81                        .map(|n| {
82                            Value::Struct(vec![
83                                ("node_namespace".into(), Value::String(n.namespace.clone())),
84                                ("node_name".into(), Value::String(n.name.clone())),
85                                ("reader_gid_seq".into(), gids(&n.readers)),
86                                ("writer_gid_seq".into(), gids(&n.writers)),
87                            ])
88                        })
89                        .collect(),
90                ),
91            ),
92        ]);
93        let data = self.info_type.to_data(&info)?;
94        // Under the lock, so that the last one written is the latest.
95        self.info_writer.write(&data)?;
96        drop(nodes);
97        Ok(())
98    }
99
100    fn change(&self, node: u64, f: impl FnOnce(&mut NodeEntry)) -> Result<()> {
101        {
102            let mut nodes = self.nodes.lock().expect("not poisoned");
103            match nodes.get_mut(&node) {
104                Some(n) => f(n),
105                None => return Ok(()),
106            }
107        }
108        self.announce()
109    }
110}
111
112/// A DDS participant that ROS 2 sees as the participant of ROS 2 nodes.
113///
114/// It announces `enclave=/;` in its USER_DATA, as ROS 2 participants do,
115/// and its nodes on `ros_discovery_info`. Clones share the participant.
116#[derive(Clone, Debug)]
117pub struct RosParticipant {
118    ctx: Arc<Context>,
119}
120
121impl RosParticipant {
122    /// A participant in DDS domain `domain_id` (the `ROS_DOMAIN_ID`).
123    pub fn new(domain_id: u32) -> Result<RosParticipant> {
124        RosParticipant::with_config(ParticipantConfig::new(domain_id))
125    }
126
127    /// A participant of `config`. Its USER_DATA gets `enclave=/;` unless
128    /// it already has an enclave.
129    pub fn with_config(mut config: ParticipantConfig) -> Result<RosParticipant> {
130        let mut user_data = UserData::parse(&config.user_data);
131        if user_data.get(ENCLAVE_KEY).is_none() {
132            let mut u = UserData::new();
133            u.set(ENCLAVE_KEY, "/");
134            u.merge(&user_data);
135            user_data = u;
136            config.user_data = user_data.to_bytes();
137        }
138        let participant = DomainParticipant::with_config(config)?;
139        let info_type = TypeLibrary::new().message(DISCOVERY_INFO_TYPE)?;
140        let topic =
141            participant.create_dynamic_topic(DISCOVERY_INFO_TOPIC, info_type.dynamic_type())?;
142        let publisher = participant.create_publisher()?;
143        let subscriber = participant.create_subscriber()?;
144        let mut ud = UserData::new();
145        ud.set_type_hash(&info_type.type_hash());
146        let info_writer = publisher.create_datawriter_with_qos(
147            &topic,
148            QosProfile::TRANSIENT_LOCAL.writer_qos(ud.to_bytes()),
149        )?;
150        let ctx = Arc::new(Context {
151            info_type,
152            info_writer,
153            nodes: Mutex::new(BTreeMap::new()),
154            next_node: AtomicU64::new(1),
155            publisher,
156            subscriber,
157            participant,
158        });
159        ctx.announce()?;
160        Ok(RosParticipant { ctx })
161    }
162
163    /// The DDS participant.
164    pub fn participant(&self) -> &DomainParticipant {
165        &self.ctx.participant
166    }
167
168    /// The GID of the participant: the 16 octets of its GUID.
169    pub fn gid(&self) -> [u8; 16] {
170        self.ctx.participant.guid().to_bytes()
171    }
172
173    /// A node `name` in `namespace` (`/` or `/a/b`), announced at once.
174    /// The node is gone when the [`Node`] is dropped.
175    pub fn create_node(&self, namespace: &str, name: &str) -> Result<Node> {
176        validate_namespace(namespace)?;
177        validate_node_name(name)?;
178        let id = self.ctx.next_node.fetch_add(1, Ordering::Relaxed);
179        self.ctx.nodes.lock().expect("not poisoned").insert(
180            id,
181            NodeEntry {
182                namespace: namespace.to_string(),
183                name: name.to_string(),
184                readers: Vec::new(),
185                writers: Vec::new(),
186            },
187        );
188        self.ctx.announce()?;
189        Ok(Node {
190            ctx: self.ctx.clone(),
191            id,
192            namespace: namespace.to_string(),
193            name: name.to_string(),
194        })
195    }
196
197    /// The writer of a sample, as discovered: its participant and its
198    /// USER_DATA (with [`UserData::parse`]), for instance to know that it
199    /// is not a ROS 2 program but another bridge. `None` when it is not
200    /// (or no longer) known, and for the writers of this participant.
201    pub fn writer_of(&self, info: &SampleInfo) -> Option<DiscoveredEndpoint> {
202        self.ctx.participant.discovered_endpoint(&info.writer)
203    }
204}
205
206/// A ROS 2 node.
207#[derive(Debug)]
208pub struct Node {
209    ctx: Arc<Context>,
210    id: u64,
211    namespace: String,
212    name: String,
213}
214
215impl Node {
216    /// Its namespace.
217    pub fn namespace(&self) -> &str {
218        &self.namespace
219    }
220
221    /// Its name.
222    pub fn name(&self) -> &str {
223        &self.name
224    }
225
226    /// The fully qualified name of a topic or service of this node
227    /// ([`expand_topic_name`]).
228    pub fn expand(&self, topic: &str) -> Result<String> {
229        expand_topic_name(topic, &self.name, &self.namespace)
230    }
231
232    fn user_data(ty: &MessageType, extra: &UserData) -> Vec<u8> {
233        let mut u = UserData::new();
234        u.set_type_hash(&ty.type_hash());
235        u.merge(extra);
236        u.to_bytes()
237    }
238
239    /// A writer of the ROS 2 topic `topic` (expanded for this node) of
240    /// message type `ty`, with the QoS of `qos`. Its USER_DATA is
241    /// `typehash=...;` and the entries of `extra`.
242    pub fn create_publisher(
243        &self,
244        topic: &str,
245        ty: &MessageType,
246        qos: &QosProfile,
247        extra: &UserData,
248    ) -> Result<RosPublisher> {
249        let full = self.expand(topic)?;
250        let writer = self.create_writer(&topic_to_dds(&full)?, ty, qos, extra)?;
251        Ok(RosPublisher {
252            ty: ty.clone(),
253            topic: full,
254            writer,
255        })
256    }
257
258    /// A reader of the ROS 2 topic `topic` (expanded for this node) of
259    /// message type `ty`, as [`Self::create_publisher`] a writer.
260    pub fn create_subscription(
261        &self,
262        topic: &str,
263        ty: &MessageType,
264        qos: &QosProfile,
265        extra: &UserData,
266    ) -> Result<RosSubscription> {
267        let full = self.expand(topic)?;
268        let reader = self.create_reader(&topic_to_dds(&full)?, ty, qos, extra)?;
269        Ok(RosSubscription {
270            ty: ty.clone(),
271            topic: full,
272            reader,
273        })
274    }
275
276    /// A writer of DDS topic `dds_topic` of `ty`, counted as this node's:
277    /// for the topics of services (`rq/`, `rr/`, [`service_to_dds`]) and
278    /// others the helpers do not make.
279    pub fn create_writer(
280        &self,
281        dds_topic: &str,
282        ty: &MessageType,
283        qos: &QosProfile,
284        extra: &UserData,
285    ) -> Result<NodeWriter> {
286        let topic = self
287            .ctx
288            .participant
289            .create_dynamic_topic(dds_topic, ty.dynamic_type())?;
290        let writer = self
291            .ctx
292            .publisher
293            .create_datawriter_with_qos(&topic, qos.writer_qos(Node::user_data(ty, extra)))?;
294        let guid = writer.guid();
295        self.ctx.change(self.id, |n| n.writers.push(guid))?;
296        Ok(NodeWriter {
297            writer,
298            entry: EndpointEntry {
299                ctx: self.ctx.clone(),
300                node: self.id,
301                guid,
302            },
303        })
304    }
305
306    /// A reader of DDS topic `dds_topic` of `ty`, counted as this node's.
307    pub fn create_reader(
308        &self,
309        dds_topic: &str,
310        ty: &MessageType,
311        qos: &QosProfile,
312        extra: &UserData,
313    ) -> Result<NodeReader> {
314        let topic = self
315            .ctx
316            .participant
317            .create_dynamic_topic(dds_topic, ty.dynamic_type())?;
318        let reader = self
319            .ctx
320            .subscriber
321            .create_datareader_with_qos(&topic, qos.reader_qos(Node::user_data(ty, extra)))?;
322        let guid = reader.guid();
323        self.ctx.change(self.id, |n| n.readers.push(guid))?;
324        Ok(NodeReader {
325            reader,
326            entry: EndpointEntry {
327                ctx: self.ctx.clone(),
328                node: self.id,
329                guid,
330            },
331        })
332    }
333
334    /// The DDS topics of the requests and replies of service `service`
335    /// (expanded for this node).
336    pub fn service_topics(&self, service: &str) -> Result<(String, String)> {
337        service_to_dds(&self.expand(service)?)
338    }
339}
340
341impl Drop for Node {
342    fn drop(&mut self) {
343        let removed = self
344            .ctx
345            .nodes
346            .lock()
347            .expect("not poisoned")
348            .remove(&self.id)
349            .is_some();
350        if removed {
351            let _ = self.ctx.announce();
352        }
353    }
354}
355
356/// Takes an endpoint out of its node's entry when dropped.
357#[derive(Debug)]
358struct EndpointEntry {
359    ctx: Arc<Context>,
360    node: u64,
361    guid: Guid,
362}
363
364impl Drop for EndpointEntry {
365    fn drop(&mut self) {
366        let guid = self.guid;
367        let _ = self.ctx.change(self.node, |n| {
368            n.readers.retain(|g| *g != guid);
369            n.writers.retain(|g| *g != guid);
370        });
371    }
372}
373
374/// A DDS writer of a node: taken out of the node's endpoints when dropped.
375#[derive(Debug)]
376pub struct NodeWriter {
377    writer: DataWriter<DynamicData>,
378    entry: EndpointEntry,
379}
380
381impl NodeWriter {
382    /// The DDS writer.
383    pub fn writer(&self) -> &DataWriter<DynamicData> {
384        &self.writer
385    }
386
387    /// Its GID.
388    pub fn gid(&self) -> [u8; 16] {
389        self.entry.guid.to_bytes()
390    }
391}
392
393/// A DDS reader of a node: taken out of the node's endpoints when dropped.
394#[derive(Debug)]
395pub struct NodeReader {
396    reader: DataReader<DynamicData>,
397    entry: EndpointEntry,
398}
399
400impl NodeReader {
401    /// The DDS reader.
402    pub fn reader(&self) -> &DataReader<DynamicData> {
403        &self.reader
404    }
405
406    /// Its GID.
407    pub fn gid(&self) -> [u8; 16] {
408        self.entry.guid.to_bytes()
409    }
410}
411
412/// A publisher of a ROS 2 topic.
413#[derive(Debug)]
414pub struct RosPublisher {
415    ty: MessageType,
416    topic: String,
417    writer: NodeWriter,
418}
419
420impl RosPublisher {
421    /// The fully qualified topic name.
422    pub fn topic(&self) -> &str {
423        &self.topic
424    }
425
426    /// The message type.
427    pub fn message_type(&self) -> &MessageType {
428        &self.ty
429    }
430
431    /// The DDS writer.
432    pub fn writer(&self) -> &DataWriter<DynamicData> {
433        self.writer.writer()
434    }
435
436    /// Its GID.
437    pub fn gid(&self) -> [u8; 16] {
438        self.writer.gid()
439    }
440
441    /// Publishes `value`, checked against the message type
442    /// ([`MessageType::to_data`]).
443    pub fn publish(&self, value: &Value) -> Result<()> {
444        let data = self.ty.to_data(value)?;
445        self.writer().write(&data).map_err(Error::from)
446    }
447}
448
449/// A subscription to a ROS 2 topic.
450#[derive(Debug)]
451pub struct RosSubscription {
452    ty: MessageType,
453    topic: String,
454    reader: NodeReader,
455}
456
457impl RosSubscription {
458    /// The fully qualified topic name.
459    pub fn topic(&self) -> &str {
460        &self.topic
461    }
462
463    /// The message type.
464    pub fn message_type(&self) -> &MessageType {
465        &self.ty
466    }
467
468    /// The DDS reader.
469    pub fn reader(&self) -> &DataReader<DynamicData> {
470        self.reader.reader()
471    }
472
473    /// Its GID.
474    pub fn gid(&self) -> [u8; 16] {
475        self.reader.gid()
476    }
477
478    /// Takes the messages received, as values, with their information.
479    pub fn take(&self) -> Result<Vec<(Value, SampleInfo)>> {
480        self.reader()
481            .take()
482            .into_iter()
483            .filter_map(|s| Some((s.data?, s.info)))
484            .map(|(d, info)| Ok((self.ty.from_data(&d)?, info)))
485            .collect()
486    }
487}