1use 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
33pub const DISCOVERY_INFO_TOPIC: &str = "ros_discovery_info";
35pub 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 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 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#[derive(Clone, Debug)]
117pub struct RosParticipant {
118 ctx: Arc<Context>,
119}
120
121impl RosParticipant {
122 pub fn new(domain_id: u32) -> Result<RosParticipant> {
124 RosParticipant::with_config(ParticipantConfig::new(domain_id))
125 }
126
127 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 pub fn participant(&self) -> &DomainParticipant {
165 &self.ctx.participant
166 }
167
168 pub fn gid(&self) -> [u8; 16] {
170 self.ctx.participant.guid().to_bytes()
171 }
172
173 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 pub fn writer_of(&self, info: &SampleInfo) -> Option<DiscoveredEndpoint> {
202 self.ctx.participant.discovered_endpoint(&info.writer)
203 }
204}
205
206#[derive(Debug)]
208pub struct Node {
209 ctx: Arc<Context>,
210 id: u64,
211 namespace: String,
212 name: String,
213}
214
215impl Node {
216 pub fn namespace(&self) -> &str {
218 &self.namespace
219 }
220
221 pub fn name(&self) -> &str {
223 &self.name
224 }
225
226 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 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 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 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 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 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#[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#[derive(Debug)]
376pub struct NodeWriter {
377 writer: DataWriter<DynamicData>,
378 entry: EndpointEntry,
379}
380
381impl NodeWriter {
382 pub fn writer(&self) -> &DataWriter<DynamicData> {
384 &self.writer
385 }
386
387 pub fn gid(&self) -> [u8; 16] {
389 self.entry.guid.to_bytes()
390 }
391}
392
393#[derive(Debug)]
395pub struct NodeReader {
396 reader: DataReader<DynamicData>,
397 entry: EndpointEntry,
398}
399
400impl NodeReader {
401 pub fn reader(&self) -> &DataReader<DynamicData> {
403 &self.reader
404 }
405
406 pub fn gid(&self) -> [u8; 16] {
408 self.entry.guid.to_bytes()
409 }
410}
411
412#[derive(Debug)]
414pub struct RosPublisher {
415 ty: MessageType,
416 topic: String,
417 writer: NodeWriter,
418}
419
420impl RosPublisher {
421 pub fn topic(&self) -> &str {
423 &self.topic
424 }
425
426 pub fn message_type(&self) -> &MessageType {
428 &self.ty
429 }
430
431 pub fn writer(&self) -> &DataWriter<DynamicData> {
433 self.writer.writer()
434 }
435
436 pub fn gid(&self) -> [u8; 16] {
438 self.writer.gid()
439 }
440
441 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#[derive(Debug)]
451pub struct RosSubscription {
452 ty: MessageType,
453 topic: String,
454 reader: NodeReader,
455}
456
457impl RosSubscription {
458 pub fn topic(&self) -> &str {
460 &self.topic
461 }
462
463 pub fn message_type(&self) -> &MessageType {
465 &self.ty
466 }
467
468 pub fn reader(&self) -> &DataReader<DynamicData> {
470 self.reader.reader()
471 }
472
473 pub fn gid(&self) -> [u8; 16] {
475 self.reader.gid()
476 }
477
478 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}