rustorb-dds-ros2 0.4.0

The ROS 2 conventions on DDS for rustorb-dds: names, interface types from .msg/.srv, RIHS01 type hashes, node discovery
Documentation
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
485
486
487
//! ROS 2 nodes on a DDS participant, announced on `ros_discovery_info`.
//!
//! A ROS 2 node is not a DDS entity. ROS 2 (since Foxy) tells which
//! writers and readers belong to which node on the DDS topic
//! `ros_discovery_info`, of type `rmw_dds_common/msg/ParticipantEntitiesInfo`:
//! each participant writes, every time its nodes or their endpoints
//! change, the GID of the participant and, for each of its nodes, the
//! namespace, the name and the GIDs of the node's readers and writers. A
//! GID is the 16 octets of a DDS GUID. The writer is RELIABLE,
//! TRANSIENT_LOCAL, KEEP_LAST(1), so that late joiners get the last one.
//! Without it, `ros2 node list` does not show the nodes, and `ros2 topic
//! info -v` shows the endpoints under `_NODE_NAME_UNKNOWN_`; the data
//! goes through anyway.

use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use rustorb_dds::{
    DataReader, DataWriter, DiscoveredEndpoint, DomainParticipant, DynamicData, Guid,
    ParticipantConfig, SampleInfo,
};

use crate::library::{MessageType, TypeLibrary};
use crate::names::{
    expand_topic_name, service_to_dds, topic_to_dds, validate_namespace, validate_node_name,
};
use crate::qos::QosProfile;
use crate::user_data::{ENCLAVE_KEY, UserData};
use crate::value::Value;
use crate::{Error, Result};

/// The DDS topic of the graph of ROS 2 nodes.
pub const DISCOVERY_INFO_TOPIC: &str = "ros_discovery_info";
/// The type of [`DISCOVERY_INFO_TOPIC`].
pub const DISCOVERY_INFO_TYPE: &str = "rmw_dds_common/msg/ParticipantEntitiesInfo";

#[derive(Debug)]
struct NodeEntry {
    namespace: String,
    name: String,
    readers: Vec<Guid>,
    writers: Vec<Guid>,
}

struct Context {
    info_type: MessageType,
    info_writer: DataWriter<DynamicData>,
    nodes: Mutex<BTreeMap<u64, NodeEntry>>,
    next_node: AtomicU64,
    publisher: rustorb_dds::Publisher,
    subscriber: rustorb_dds::Subscriber,
    participant: DomainParticipant,
}

impl std::fmt::Debug for Context {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Context")
            .field("participant", &self.participant.guid())
            .field("nodes", &self.nodes)
            .finish_non_exhaustive()
    }
}

fn gid(g: Guid) -> Value {
    Value::Struct(vec![("data".into(), Value::Bytes(g.to_bytes().to_vec()))])
}

impl Context {
    /// Writes the nodes and their endpoints on `ros_discovery_info`.
    fn announce(&self) -> Result<()> {
        let nodes = self.nodes.lock().expect("not poisoned");
        let gids = |v: &[Guid]| Value::List(v.iter().copied().map(gid).collect());
        let info = Value::Struct(vec![
            ("gid".into(), gid(self.participant.guid())),
            (
                "node_entities_info_seq".into(),
                Value::List(
                    nodes
                        .values()
                        .map(|n| {
                            Value::Struct(vec![
                                ("node_namespace".into(), Value::String(n.namespace.clone())),
                                ("node_name".into(), Value::String(n.name.clone())),
                                ("reader_gid_seq".into(), gids(&n.readers)),
                                ("writer_gid_seq".into(), gids(&n.writers)),
                            ])
                        })
                        .collect(),
                ),
            ),
        ]);
        let data = self.info_type.to_data(&info)?;
        // Under the lock, so that the last one written is the latest.
        self.info_writer.write(&data)?;
        drop(nodes);
        Ok(())
    }

    fn change(&self, node: u64, f: impl FnOnce(&mut NodeEntry)) -> Result<()> {
        {
            let mut nodes = self.nodes.lock().expect("not poisoned");
            match nodes.get_mut(&node) {
                Some(n) => f(n),
                None => return Ok(()),
            }
        }
        self.announce()
    }
}

/// A DDS participant that ROS 2 sees as the participant of ROS 2 nodes.
///
/// It announces `enclave=/;` in its USER_DATA, as ROS 2 participants do,
/// and its nodes on `ros_discovery_info`. Clones share the participant.
#[derive(Clone, Debug)]
pub struct RosParticipant {
    ctx: Arc<Context>,
}

impl RosParticipant {
    /// A participant in DDS domain `domain_id` (the `ROS_DOMAIN_ID`).
    pub fn new(domain_id: u32) -> Result<RosParticipant> {
        RosParticipant::with_config(ParticipantConfig::new(domain_id))
    }

    /// A participant of `config`. Its USER_DATA gets `enclave=/;` unless
    /// it already has an enclave.
    pub fn with_config(mut config: ParticipantConfig) -> Result<RosParticipant> {
        let mut user_data = UserData::parse(&config.user_data);
        if user_data.get(ENCLAVE_KEY).is_none() {
            let mut u = UserData::new();
            u.set(ENCLAVE_KEY, "/");
            u.merge(&user_data);
            user_data = u;
            config.user_data = user_data.to_bytes();
        }
        let participant = DomainParticipant::with_config(config)?;
        let info_type = TypeLibrary::new().message(DISCOVERY_INFO_TYPE)?;
        let topic =
            participant.create_dynamic_topic(DISCOVERY_INFO_TOPIC, info_type.dynamic_type())?;
        let publisher = participant.create_publisher()?;
        let subscriber = participant.create_subscriber()?;
        let mut ud = UserData::new();
        ud.set_type_hash(&info_type.type_hash());
        let info_writer = publisher.create_datawriter_with_qos(
            &topic,
            QosProfile::TRANSIENT_LOCAL.writer_qos(ud.to_bytes()),
        )?;
        let ctx = Arc::new(Context {
            info_type,
            info_writer,
            nodes: Mutex::new(BTreeMap::new()),
            next_node: AtomicU64::new(1),
            publisher,
            subscriber,
            participant,
        });
        ctx.announce()?;
        Ok(RosParticipant { ctx })
    }

    /// The DDS participant.
    pub fn participant(&self) -> &DomainParticipant {
        &self.ctx.participant
    }

    /// The GID of the participant: the 16 octets of its GUID.
    pub fn gid(&self) -> [u8; 16] {
        self.ctx.participant.guid().to_bytes()
    }

    /// A node `name` in `namespace` (`/` or `/a/b`), announced at once.
    /// The node is gone when the [`Node`] is dropped.
    pub fn create_node(&self, namespace: &str, name: &str) -> Result<Node> {
        validate_namespace(namespace)?;
        validate_node_name(name)?;
        let id = self.ctx.next_node.fetch_add(1, Ordering::Relaxed);
        self.ctx.nodes.lock().expect("not poisoned").insert(
            id,
            NodeEntry {
                namespace: namespace.to_string(),
                name: name.to_string(),
                readers: Vec::new(),
                writers: Vec::new(),
            },
        );
        self.ctx.announce()?;
        Ok(Node {
            ctx: self.ctx.clone(),
            id,
            namespace: namespace.to_string(),
            name: name.to_string(),
        })
    }

    /// The writer of a sample, as discovered: its participant and its
    /// USER_DATA (with [`UserData::parse`]), for instance to know that it
    /// is not a ROS 2 program but another bridge. `None` when it is not
    /// (or no longer) known, and for the writers of this participant.
    pub fn writer_of(&self, info: &SampleInfo) -> Option<DiscoveredEndpoint> {
        self.ctx.participant.discovered_endpoint(&info.writer)
    }
}

/// A ROS 2 node.
#[derive(Debug)]
pub struct Node {
    ctx: Arc<Context>,
    id: u64,
    namespace: String,
    name: String,
}

impl Node {
    /// Its namespace.
    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// Its name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The fully qualified name of a topic or service of this node
    /// ([`expand_topic_name`]).
    pub fn expand(&self, topic: &str) -> Result<String> {
        expand_topic_name(topic, &self.name, &self.namespace)
    }

    fn user_data(ty: &MessageType, extra: &UserData) -> Vec<u8> {
        let mut u = UserData::new();
        u.set_type_hash(&ty.type_hash());
        u.merge(extra);
        u.to_bytes()
    }

    /// A writer of the ROS 2 topic `topic` (expanded for this node) of
    /// message type `ty`, with the QoS of `qos`. Its USER_DATA is
    /// `typehash=...;` and the entries of `extra`.
    pub fn create_publisher(
        &self,
        topic: &str,
        ty: &MessageType,
        qos: &QosProfile,
        extra: &UserData,
    ) -> Result<RosPublisher> {
        let full = self.expand(topic)?;
        let writer = self.create_writer(&topic_to_dds(&full)?, ty, qos, extra)?;
        Ok(RosPublisher {
            ty: ty.clone(),
            topic: full,
            writer,
        })
    }

    /// A reader of the ROS 2 topic `topic` (expanded for this node) of
    /// message type `ty`, as [`Self::create_publisher`] a writer.
    pub fn create_subscription(
        &self,
        topic: &str,
        ty: &MessageType,
        qos: &QosProfile,
        extra: &UserData,
    ) -> Result<RosSubscription> {
        let full = self.expand(topic)?;
        let reader = self.create_reader(&topic_to_dds(&full)?, ty, qos, extra)?;
        Ok(RosSubscription {
            ty: ty.clone(),
            topic: full,
            reader,
        })
    }

    /// A writer of DDS topic `dds_topic` of `ty`, counted as this node's:
    /// for the topics of services (`rq/`, `rr/`, [`service_to_dds`]) and
    /// others the helpers do not make.
    pub fn create_writer(
        &self,
        dds_topic: &str,
        ty: &MessageType,
        qos: &QosProfile,
        extra: &UserData,
    ) -> Result<NodeWriter> {
        let topic = self
            .ctx
            .participant
            .create_dynamic_topic(dds_topic, ty.dynamic_type())?;
        let writer = self
            .ctx
            .publisher
            .create_datawriter_with_qos(&topic, qos.writer_qos(Node::user_data(ty, extra)))?;
        let guid = writer.guid();
        self.ctx.change(self.id, |n| n.writers.push(guid))?;
        Ok(NodeWriter {
            writer,
            entry: EndpointEntry {
                ctx: self.ctx.clone(),
                node: self.id,
                guid,
            },
        })
    }

    /// A reader of DDS topic `dds_topic` of `ty`, counted as this node's.
    pub fn create_reader(
        &self,
        dds_topic: &str,
        ty: &MessageType,
        qos: &QosProfile,
        extra: &UserData,
    ) -> Result<NodeReader> {
        let topic = self
            .ctx
            .participant
            .create_dynamic_topic(dds_topic, ty.dynamic_type())?;
        let reader = self
            .ctx
            .subscriber
            .create_datareader_with_qos(&topic, qos.reader_qos(Node::user_data(ty, extra)))?;
        let guid = reader.guid();
        self.ctx.change(self.id, |n| n.readers.push(guid))?;
        Ok(NodeReader {
            reader,
            entry: EndpointEntry {
                ctx: self.ctx.clone(),
                node: self.id,
                guid,
            },
        })
    }

    /// The DDS topics of the requests and replies of service `service`
    /// (expanded for this node).
    pub fn service_topics(&self, service: &str) -> Result<(String, String)> {
        service_to_dds(&self.expand(service)?)
    }
}

impl Drop for Node {
    fn drop(&mut self) {
        let removed = self
            .ctx
            .nodes
            .lock()
            .expect("not poisoned")
            .remove(&self.id)
            .is_some();
        if removed {
            let _ = self.ctx.announce();
        }
    }
}

/// Takes an endpoint out of its node's entry when dropped.
#[derive(Debug)]
struct EndpointEntry {
    ctx: Arc<Context>,
    node: u64,
    guid: Guid,
}

impl Drop for EndpointEntry {
    fn drop(&mut self) {
        let guid = self.guid;
        let _ = self.ctx.change(self.node, |n| {
            n.readers.retain(|g| *g != guid);
            n.writers.retain(|g| *g != guid);
        });
    }
}

/// A DDS writer of a node: taken out of the node's endpoints when dropped.
#[derive(Debug)]
pub struct NodeWriter {
    writer: DataWriter<DynamicData>,
    entry: EndpointEntry,
}

impl NodeWriter {
    /// The DDS writer.
    pub fn writer(&self) -> &DataWriter<DynamicData> {
        &self.writer
    }

    /// Its GID.
    pub fn gid(&self) -> [u8; 16] {
        self.entry.guid.to_bytes()
    }
}

/// A DDS reader of a node: taken out of the node's endpoints when dropped.
#[derive(Debug)]
pub struct NodeReader {
    reader: DataReader<DynamicData>,
    entry: EndpointEntry,
}

impl NodeReader {
    /// The DDS reader.
    pub fn reader(&self) -> &DataReader<DynamicData> {
        &self.reader
    }

    /// Its GID.
    pub fn gid(&self) -> [u8; 16] {
        self.entry.guid.to_bytes()
    }
}

/// A publisher of a ROS 2 topic.
#[derive(Debug)]
pub struct RosPublisher {
    ty: MessageType,
    topic: String,
    writer: NodeWriter,
}

impl RosPublisher {
    /// The fully qualified topic name.
    pub fn topic(&self) -> &str {
        &self.topic
    }

    /// The message type.
    pub fn message_type(&self) -> &MessageType {
        &self.ty
    }

    /// The DDS writer.
    pub fn writer(&self) -> &DataWriter<DynamicData> {
        self.writer.writer()
    }

    /// Its GID.
    pub fn gid(&self) -> [u8; 16] {
        self.writer.gid()
    }

    /// Publishes `value`, checked against the message type
    /// ([`MessageType::to_data`]).
    pub fn publish(&self, value: &Value) -> Result<()> {
        let data = self.ty.to_data(value)?;
        self.writer().write(&data).map_err(Error::from)
    }
}

/// A subscription to a ROS 2 topic.
#[derive(Debug)]
pub struct RosSubscription {
    ty: MessageType,
    topic: String,
    reader: NodeReader,
}

impl RosSubscription {
    /// The fully qualified topic name.
    pub fn topic(&self) -> &str {
        &self.topic
    }

    /// The message type.
    pub fn message_type(&self) -> &MessageType {
        &self.ty
    }

    /// The DDS reader.
    pub fn reader(&self) -> &DataReader<DynamicData> {
        self.reader.reader()
    }

    /// Its GID.
    pub fn gid(&self) -> [u8; 16] {
        self.reader.gid()
    }

    /// Takes the messages received, as values, with their information.
    pub fn take(&self) -> Result<Vec<(Value, SampleInfo)>> {
        self.reader()
            .take()
            .into_iter()
            .filter_map(|s| Some((s.data?, s.info)))
            .map(|(d, info)| Ok((self.ty.from_data(&d)?, info)))
            .collect()
    }
}