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};
pub const DISCOVERY_INFO_TOPIC: &str = "ros_discovery_info";
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 {
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)?;
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()
}
}
#[derive(Clone, Debug)]
pub struct RosParticipant {
ctx: Arc<Context>,
}
impl RosParticipant {
pub fn new(domain_id: u32) -> Result<RosParticipant> {
RosParticipant::with_config(ParticipantConfig::new(domain_id))
}
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 })
}
pub fn participant(&self) -> &DomainParticipant {
&self.ctx.participant
}
pub fn gid(&self) -> [u8; 16] {
self.ctx.participant.guid().to_bytes()
}
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(),
})
}
pub fn writer_of(&self, info: &SampleInfo) -> Option<DiscoveredEndpoint> {
self.ctx.participant.discovered_endpoint(&info.writer)
}
}
#[derive(Debug)]
pub struct Node {
ctx: Arc<Context>,
id: u64,
namespace: String,
name: String,
}
impl Node {
pub fn namespace(&self) -> &str {
&self.namespace
}
pub fn name(&self) -> &str {
&self.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()
}
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,
})
}
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,
})
}
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,
},
})
}
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,
},
})
}
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();
}
}
}
#[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);
});
}
}
#[derive(Debug)]
pub struct NodeWriter {
writer: DataWriter<DynamicData>,
entry: EndpointEntry,
}
impl NodeWriter {
pub fn writer(&self) -> &DataWriter<DynamicData> {
&self.writer
}
pub fn gid(&self) -> [u8; 16] {
self.entry.guid.to_bytes()
}
}
#[derive(Debug)]
pub struct NodeReader {
reader: DataReader<DynamicData>,
entry: EndpointEntry,
}
impl NodeReader {
pub fn reader(&self) -> &DataReader<DynamicData> {
&self.reader
}
pub fn gid(&self) -> [u8; 16] {
self.entry.guid.to_bytes()
}
}
#[derive(Debug)]
pub struct RosPublisher {
ty: MessageType,
topic: String,
writer: NodeWriter,
}
impl RosPublisher {
pub fn topic(&self) -> &str {
&self.topic
}
pub fn message_type(&self) -> &MessageType {
&self.ty
}
pub fn writer(&self) -> &DataWriter<DynamicData> {
self.writer.writer()
}
pub fn gid(&self) -> [u8; 16] {
self.writer.gid()
}
pub fn publish(&self, value: &Value) -> Result<()> {
let data = self.ty.to_data(value)?;
self.writer().write(&data).map_err(Error::from)
}
}
#[derive(Debug)]
pub struct RosSubscription {
ty: MessageType,
topic: String,
reader: NodeReader,
}
impl RosSubscription {
pub fn topic(&self) -> &str {
&self.topic
}
pub fn message_type(&self) -> &MessageType {
&self.ty
}
pub fn reader(&self) -> &DataReader<DynamicData> {
self.reader.reader()
}
pub fn gid(&self) -> [u8; 16] {
self.reader.gid()
}
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()
}
}