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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! ROS 2 interface types found in `.msg` and `.srv` files, with their
//! DDS types (DynamicType), descriptions and RIHS01 hashes.

use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use rustorb_xtypes::dynamic::DynamicType;
use rustorb_xtypes::types::{
    ArrayType, Element, Extensibility, Primitive as XPrimitive, SequenceType, StructMember,
    StructType, Type,
};

use crate::msg::{
    ArraySpec, BaseSpec, MessageSpec, Primitive, TypeSpec, parse_message, parse_service,
};
use crate::names::{InterfaceKind, TypeName};
use crate::type_description::{
    Field as DescField, FieldType as DescFieldType, IndividualTypeDescription, TypeDescription,
    TypeHash, field_type,
};
use crate::value::{Value, check_length, parse_literal};
use crate::{Error, Result};

/// The member ROS 2 gives a message without fields, since a DDS struct
/// has at least one.
pub const EMPTY_MESSAGE_MEMBER: &str = "structure_needs_at_least_one_member";

/// The element type of a field, its messages found.
#[derive(Clone, Debug)]
pub enum BaseType {
    /// A primitive.
    Primitive(Primitive),
    /// `string` or `wstring`.
    String {
        /// `wstring`.
        wide: bool,
        /// The bound, in characters; `None` for none.
        bound: Option<u32>,
    },
    /// A message.
    Message(MessageType),
}

impl BaseType {
    pub(crate) fn describe(&self) -> String {
        match self {
            BaseType::Primitive(p) => p.name().to_string(),
            BaseType::String { wide, bound } => format!(
                "{}{}",
                if *wide { "wstring" } else { "string" },
                bound.map(|b| format!("<={b}")).unwrap_or_default()
            ),
            BaseType::Message(m) => m.name().to_string(),
        }
    }
}

/// The type of a field.
#[derive(Clone, Debug)]
pub struct FieldType {
    /// The element type.
    pub base: BaseType,
    /// One value, an array or a sequence.
    pub array: ArraySpec,
}

/// A field of a message.
#[derive(Clone, Debug)]
pub struct Field {
    /// The name.
    pub name: String,
    /// The type.
    pub ty: FieldType,
    /// The default value of the `.msg` file.
    pub default: Option<Value>,
}

/// A constant of a message.
#[derive(Clone, Debug)]
pub struct Constant {
    /// The name.
    pub name: String,
    /// The type.
    pub ty: TypeSpec,
    /// The value.
    pub value: Value,
}

#[derive(Debug)]
struct MessageInner {
    name: TypeName,
    fields: Vec<Field>,
    constants: Vec<Constant>,
    dynamic: DynamicType,
    individual: IndividualTypeDescription,
    /// The descriptions of the types it uses, by name.
    referenced: BTreeMap<String, IndividualTypeDescription>,
    hash: TypeHash,
}

/// A ROS 2 message type: `pkg/msg/Name`, or the request, response or
/// event of a service.
///
/// A message without fields has the one field
/// [`EMPTY_MESSAGE_MEMBER`] of type `uint8`, in its DDS type and in its
/// description, as ROS 2 gives it.
#[derive(Clone, Debug)]
pub struct MessageType(Arc<MessageInner>);

impl MessageType {
    /// Its name.
    pub fn name(&self) -> &TypeName {
        &self.0.name
    }

    /// Its fields, in order.
    pub fn fields(&self) -> &[Field] {
        &self.0.fields
    }

    /// Its constants.
    pub fn constants(&self) -> &[Constant] {
        &self.0.constants
    }

    /// Its DDS type, `pkg::msg::dds_::Name_`, for
    /// [`DomainParticipant::create_dynamic_topic`](rustorb_dds::DomainParticipant::create_dynamic_topic).
    pub fn dynamic_type(&self) -> &DynamicType {
        &self.0.dynamic
    }

    /// Its description (REP-2011).
    pub fn type_description(&self) -> TypeDescription {
        TypeDescription {
            type_description: self.0.individual.clone(),
            referenced_type_descriptions: self.0.referenced.values().cloned().collect(),
        }
    }

    /// Its RIHS01 hash.
    pub fn type_hash(&self) -> TypeHash {
        self.0.hash
    }
}

impl PartialEq for MessageType {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0) || self.0.name == other.0.name && self.0.hash == other.0.hash
    }
}

/// A ROS 2 service type `pkg/srv/Name`.
#[derive(Clone, Debug)]
pub struct ServiceType {
    name: TypeName,
    request: MessageType,
    response: MessageType,
    event: MessageType,
    description: TypeDescription,
}

impl ServiceType {
    /// Its name.
    pub fn name(&self) -> &TypeName {
        &self.name
    }

    /// The request, `pkg/srv/Name_Request`: the type of the topic `rq/`.
    pub fn request(&self) -> &MessageType {
        &self.request
    }

    /// The response, `pkg/srv/Name_Response`: the type of the topic `rr/`.
    pub fn response(&self) -> &MessageType {
        &self.response
    }

    /// The event of service introspection, `pkg/srv/Name_Event`.
    pub fn event(&self) -> &MessageType {
        &self.event
    }

    /// The description of the service: `pkg/srv/Name`, whose fields are
    /// its request, response and event.
    pub fn type_description(&self) -> &TypeDescription {
        &self.description
    }

    /// The RIHS01 hash of the service.
    pub fn type_hash(&self) -> TypeHash {
        self.description.hash()
    }
}

/// Definitions this crate needs even when no `.msg` file is found: those
/// of service events and of `ros_discovery_info`. Written from their
/// documented fields; files found on the search path come first.
const BUILTIN: &[(&str, &str)] = &[
    ("builtin_interfaces/msg/Time", "int32 sec\nuint32 nanosec\n"),
    (
        "service_msgs/msg/ServiceEventInfo",
        "uint8 REQUEST_SENT = 0\nuint8 REQUEST_RECEIVED = 1\nuint8 RESPONSE_SENT = 2\n\
         uint8 RESPONSE_RECEIVED = 3\nuint8 event_type\nbuiltin_interfaces/Time stamp\n\
         char[16] client_gid\nint64 sequence_number\n",
    ),
    ("rmw_dds_common/msg/Gid", "char[16] data\n"),
    (
        "rmw_dds_common/msg/NodeEntitiesInfo",
        "string<=256 node_namespace\nstring<=256 node_name\nGid[] reader_gid_seq\n\
         Gid[] writer_gid_seq\n",
    ),
    (
        "rmw_dds_common/msg/ParticipantEntitiesInfo",
        "Gid gid\nNodeEntitiesInfo[] node_entities_info_seq\n",
    ),
];

/// Where the definitions of interface types are found, and the types
/// made from them.
///
/// A type `pkg/msg/Name` is the file `<dir>/<pkg>/msg/Name.msg` (or
/// `<dir>/share/<pkg>/msg/Name.msg`) of the first directory that has
/// it, else a text given with [`Self::add_text`], else one of the few
/// built in. [`Self::add_ament_prefix_path`] adds the `share` directories
/// of the ROS 2 installations of `AMENT_PREFIX_PATH`.
///
/// The types are made once and kept.
#[derive(Debug, Default)]
pub struct TypeLibrary {
    dirs: Vec<PathBuf>,
    texts: HashMap<TypeName, String>,
    messages: Mutex<HashMap<TypeName, MessageType>>,
}

impl TypeLibrary {
    /// A library with no directories: the built-in definitions only.
    pub fn new() -> TypeLibrary {
        TypeLibrary::default()
    }

    /// A library of the directories `dirs`, then those of
    /// `AMENT_PREFIX_PATH`.
    pub fn with_dirs<P: AsRef<Path>>(dirs: impl IntoIterator<Item = P>) -> TypeLibrary {
        let mut l = TypeLibrary::new();
        for d in dirs {
            l.add_dir(d);
        }
        l.add_ament_prefix_path();
        l
    }

    /// Adds a directory to look in, after those added before.
    pub fn add_dir(&mut self, dir: impl AsRef<Path>) {
        self.dirs.push(dir.as_ref().to_path_buf());
    }

    /// Adds `<prefix>/share` for each prefix of `AMENT_PREFIX_PATH`.
    pub fn add_ament_prefix_path(&mut self) {
        if let Some(path) = std::env::var_os("AMENT_PREFIX_PATH") {
            for p in std::env::split_paths(&path) {
                if !p.as_os_str().is_empty() {
                    self.add_dir(p.join("share"));
                }
            }
        }
    }

    /// The directories looked in, in order.
    pub fn dirs(&self) -> &[PathBuf] {
        &self.dirs
    }

    /// Gives the text of the `.msg` or `.srv` file of `name`
    /// (`pkg/msg/Name` or `pkg/srv/Name`), for when there is no file; a
    /// file found in the directories comes first.
    pub fn add_text(&mut self, name: &str, text: &str) -> Result<()> {
        let name = TypeName::parse(name)?;
        self.texts.insert(name, text.to_string());
        Ok(())
    }

    /// The file of `name` in the directories, if one has it.
    pub fn find_file(&self, name: &TypeName) -> Option<PathBuf> {
        let file = format!("{}.{}", name.name, name.kind.as_str());
        self.dirs.iter().find_map(|d| {
            [
                d.join(&name.package).join(name.kind.as_str()).join(&file),
                d.join("share")
                    .join(&name.package)
                    .join(name.kind.as_str())
                    .join(&file),
            ]
            .into_iter()
            .find(|p| p.is_file())
        })
    }

    fn text(&self, name: &TypeName) -> Result<String> {
        if let Some(p) = self.find_file(name) {
            return std::fs::read_to_string(&p)
                .map_err(|e| Error::Io(format!("{}: {e}", p.display())));
        }
        if let Some(t) = self.texts.get(name) {
            return Ok(t.clone());
        }
        let full = name.to_string();
        if let Some((_, t)) = BUILTIN.iter().find(|(n, _)| *n == full) {
            return Ok(t.to_string());
        }
        Err(Error::NotFound(format!(
            "{name}: no {}/{}/{}.{} in {:?}",
            name.package,
            name.kind.as_str(),
            name.name,
            name.kind.as_str(),
            self.dirs
        )))
    }

    /// The message type `name` (`pkg/msg/Name` or `pkg/Name`), and the
    /// types it uses.
    pub fn message(&self, name: &str) -> Result<MessageType> {
        let name = TypeName::parse(name)?;
        if name.kind != InterfaceKind::Message {
            return Err(Error::Name(format!(
                "{name} is not a message (pkg/msg/Name)"
            )));
        }
        self.resolve(&name, &mut Vec::new())
    }

    /// The service type `name` (`pkg/srv/Name`).
    pub fn service(&self, name: &str) -> Result<ServiceType> {
        let name = TypeName::parse(name)?;
        if name.kind != InterfaceKind::Service {
            return Err(Error::Name(format!(
                "{name} is not a service (pkg/srv/Name)"
            )));
        }
        let spec = parse_service(&name, &self.text(&name)?)?;
        let mut stack = Vec::new();
        let request = self.build(&spec.request, &mut stack)?;
        let response = self.build(&spec.response, &mut stack)?;
        // The event of service introspection (REP-2012): what ROS 2
        // hashes the service with.
        let info = self.resolve(
            &TypeName::message("service_msgs", "ServiceEventInfo")?,
            &mut stack,
        )?;
        let nested = |m: &MessageType, array: ArraySpec| FieldType {
            base: BaseType::Message(m.clone()),
            array,
        };
        let event = self.assemble(
            name.with_suffix("_Event"),
            vec![
                ("info", nested(&info, ArraySpec::None)),
                ("request", nested(&request, ArraySpec::Bounded(1))),
                ("response", nested(&response, ArraySpec::Bounded(1))),
            ],
        )?;
        let service = self.assemble(
            name.clone(),
            vec![
                ("request_message", nested(&request, ArraySpec::None)),
                ("response_message", nested(&response, ArraySpec::None)),
                ("event_message", nested(&event, ArraySpec::None)),
            ],
        )?;
        Ok(ServiceType {
            name,
            request,
            response,
            event,
            description: service.type_description(),
        })
    }

    fn resolve(&self, name: &TypeName, stack: &mut Vec<TypeName>) -> Result<MessageType> {
        if let Some(m) = self.messages.lock().expect("not poisoned").get(name) {
            return Ok(m.clone());
        }
        if stack.contains(name) {
            return Err(Error::Parse(format!(
                "{name} uses itself: {}",
                stack
                    .iter()
                    .map(|n| n.to_string())
                    .collect::<Vec<_>>()
                    .join(" -> ")
            )));
        }
        let spec = parse_message(name, &self.text(name)?)?;
        stack.push(name.clone());
        let m = self.build(&spec, stack);
        stack.pop();
        let m = m?;
        self.messages
            .lock()
            .expect("not poisoned")
            .insert(name.clone(), m.clone());
        Ok(m)
    }

    /// The message of `spec`, the messages it names found.
    fn build(&self, spec: &MessageSpec, stack: &mut Vec<TypeName>) -> Result<MessageType> {
        let at = |e: Error| Error::Parse(format!("{}: {e}", spec.name));
        let mut fields = Vec::new();
        for f in &spec.fields {
            let base = match &f.ty.base {
                BaseSpec::Primitive(p) => BaseType::Primitive(*p),
                BaseSpec::String { wide, bound } => BaseType::String {
                    wide: *wide,
                    bound: *bound,
                },
                BaseSpec::Message(n) => BaseType::Message(self.resolve(n, stack)?),
            };
            let ty = FieldType {
                base,
                array: f.ty.array,
            };
            let default = match &f.default {
                Some(d) => {
                    let v = parse_literal(&ty, d)
                        .map_err(|e| at(Error::Parse(format!("field {}: {e}", f.name))))?;
                    check_length(&ty, &v)
                        .map_err(|e| at(Error::Parse(format!("field {}: {e}", f.name))))?;
                    Some(v)
                }
                None => None,
            };
            fields.push(Field {
                name: f.name.clone(),
                ty,
                default,
            });
        }
        let mut constants = Vec::new();
        for c in &spec.constants {
            let ty = FieldType {
                base: match &c.ty.base {
                    BaseSpec::Primitive(p) => BaseType::Primitive(*p),
                    BaseSpec::String { wide, bound } => BaseType::String {
                        wide: *wide,
                        bound: *bound,
                    },
                    BaseSpec::Message(_) => unreachable!("checked by the parser"),
                },
                array: ArraySpec::None,
            };
            let value = parse_literal(&ty, &c.value)
                .map_err(|e| at(Error::Parse(format!("constant {}: {e}", c.name))))?;
            constants.push(Constant {
                name: c.name.clone(),
                ty: c.ty.clone(),
                value,
            });
        }
        let mut m = self.assemble_fields(spec.name.clone(), fields)?;
        Arc::get_mut(&mut m.0).expect("not shared yet").constants = constants;
        Ok(m)
    }

    fn assemble(&self, name: TypeName, fields: Vec<(&str, FieldType)>) -> Result<MessageType> {
        self.assemble_fields(
            name,
            fields
                .into_iter()
                .map(|(n, ty)| Field {
                    name: n.to_string(),
                    ty,
                    default: None,
                })
                .collect(),
        )
    }

    fn assemble_fields(&self, name: TypeName, mut fields: Vec<Field>) -> Result<MessageType> {
        if fields.is_empty() {
            fields.push(Field {
                name: EMPTY_MESSAGE_MEMBER.to_string(),
                ty: FieldType {
                    base: BaseType::Primitive(Primitive::Uint8),
                    array: ArraySpec::None,
                },
                default: None,
            });
        }
        let mut referenced = BTreeMap::new();
        for f in &fields {
            if let BaseType::Message(m) = &f.ty.base {
                referenced.insert(m.0.name.to_string(), m.0.individual.clone());
                for (k, v) in &m.0.referenced {
                    referenced.insert(k.clone(), v.clone());
                }
            }
        }
        let individual = IndividualTypeDescription {
            type_name: name.to_string(),
            fields: fields
                .iter()
                .map(|f| DescField {
                    name: f.name.clone(),
                    field_type: describe(&f.ty),
                    default_value: String::new(),
                })
                .collect(),
        };
        let description = TypeDescription {
            type_description: individual.clone(),
            referenced_type_descriptions: referenced.values().cloned().collect(),
        };
        let dynamic = DynamicType::new(Type::Struct(Arc::new(StructType {
            name: name.dds_name(),
            // ROS 2's types are appendable in its IDL; with XCDR1, which
            // ROS 2 uses, appendable and final serialize the same.
            extensibility: Extensibility::Appendable,
            members: fields
                .iter()
                .enumerate()
                .map(|(i, f)| StructMember::new(f.name.clone(), i as u32, dds_type(&f.ty)))
                .collect(),
            ..StructType::default()
        })));
        let hash = description.hash();
        Ok(MessageType(Arc::new(MessageInner {
            name,
            fields,
            constants: Vec::new(),
            dynamic,
            individual,
            referenced,
            hash,
        })))
    }
}

fn describe(ty: &FieldType) -> DescFieldType {
    let (mut id, string_capacity, nested) = match &ty.base {
        BaseType::Primitive(p) => (
            match p {
                Primitive::Bool => field_type::BOOLEAN,
                Primitive::Byte => field_type::BYTE,
                // `char` is `uint8` in ROS 2 (its .msg to .idl mapping).
                Primitive::Char | Primitive::Uint8 => field_type::UINT8,
                Primitive::Float32 => field_type::FLOAT,
                Primitive::Float64 => field_type::DOUBLE,
                Primitive::Int8 => field_type::INT8,
                Primitive::Int16 => field_type::INT16,
                Primitive::Uint16 => field_type::UINT16,
                Primitive::Int32 => field_type::INT32,
                Primitive::Uint32 => field_type::UINT32,
                Primitive::Int64 => field_type::INT64,
                Primitive::Uint64 => field_type::UINT64,
            },
            0,
            String::new(),
        ),
        BaseType::String { wide, bound: None } => (
            if *wide {
                field_type::WSTRING
            } else {
                field_type::STRING
            },
            0,
            String::new(),
        ),
        BaseType::String {
            wide,
            bound: Some(b),
        } => (
            if *wide {
                field_type::BOUNDED_WSTRING
            } else {
                field_type::BOUNDED_STRING
            },
            *b as u64,
            String::new(),
        ),
        BaseType::Message(m) => (field_type::NESTED_TYPE, 0, m.name().to_string()),
    };
    let capacity = match ty.array {
        ArraySpec::None => 0,
        ArraySpec::Fixed(n) => {
            id += field_type::ARRAY_OFFSET;
            n as u64
        }
        ArraySpec::Bounded(n) => {
            id += field_type::BOUNDED_SEQUENCE_OFFSET;
            n as u64
        }
        ArraySpec::Unbounded => {
            id += field_type::UNBOUNDED_SEQUENCE_OFFSET;
            0
        }
    };
    DescFieldType {
        type_id: id,
        capacity,
        string_capacity,
        nested_type_name: nested,
    }
}

fn dds_type(ty: &FieldType) -> Type {
    let element = match &ty.base {
        BaseType::Primitive(p) => Type::Primitive(match p {
            Primitive::Bool => XPrimitive::Boolean,
            Primitive::Byte => XPrimitive::Byte,
            Primitive::Char | Primitive::Uint8 => XPrimitive::Uint8,
            Primitive::Float32 => XPrimitive::Float32,
            Primitive::Float64 => XPrimitive::Float64,
            Primitive::Int8 => XPrimitive::Int8,
            Primitive::Int16 => XPrimitive::Int16,
            Primitive::Uint16 => XPrimitive::Uint16,
            Primitive::Int32 => XPrimitive::Int32,
            Primitive::Uint32 => XPrimitive::Uint32,
            Primitive::Int64 => XPrimitive::Int64,
            Primitive::Uint64 => XPrimitive::Uint64,
        }),
        BaseType::String { wide, bound } => Type::String {
            wide: *wide,
            bound: bound.unwrap_or(0),
        },
        BaseType::Message(m) => m.dynamic_type().as_type().clone(),
    };
    match ty.array {
        ArraySpec::None => element,
        ArraySpec::Fixed(n) => Type::Array(Arc::new(ArrayType {
            element: Element::new(element),
            dimensions: vec![n],
        })),
        ArraySpec::Bounded(n) => Type::Sequence(Arc::new(SequenceType {
            element: Element::new(element),
            bound: n,
        })),
        ArraySpec::Unbounded => Type::Sequence(Arc::new(SequenceType {
            element: Element::new(element),
            bound: 0,
        })),
    }
}