use std::time::{Duration, Instant};
use rustorb_dds::{DataReader, DynamicData, ParticipantConfig};
use rustorb_dds_ros2::node::{DISCOVERY_INFO_TOPIC, DISCOVERY_INFO_TYPE};
use rustorb_dds_ros2::{QosProfile, RosParticipant, TypeLibrary, UserData, Value};
fn wait_for<T>(timeout: Duration, mut f: impl FnMut() -> Option<T>) -> T {
let deadline = Instant::now() + timeout;
loop {
if let Some(v) = f() {
return v;
}
assert!(Instant::now() < deadline, "timed out");
std::thread::sleep(Duration::from_millis(20));
}
}
fn ros_participant(domain: u32) -> RosParticipant {
RosParticipant::with_config(ParticipantConfig::localhost(domain)).unwrap()
}
fn string_type() -> rustorb_dds_ros2::MessageType {
let mut l = TypeLibrary::new();
l.add_text("std_msgs/msg/String", "string data\n").unwrap();
l.message("std_msgs/msg/String").unwrap()
}
#[test]
fn talk_and_listen() {
let ty = string_type();
let talker = ros_participant(71);
let listener = ros_participant(71);
let tn = talker.create_node("/demo", "talker").unwrap();
let ln = listener.create_node("/demo", "listener").unwrap();
let mut extra = UserData::new();
extra.set("juiz", "1234");
let publisher = tn
.create_publisher("chatter", &ty, &QosProfile::DEFAULT, &extra)
.unwrap();
assert_eq!(publisher.topic(), "/demo/chatter");
let subscription = ln
.create_subscription("/demo/chatter", &ty, &QosProfile::DEFAULT, &UserData::new())
.unwrap();
assert!(
subscription
.reader()
.wait_for_publications(1, Duration::from_secs(10))
);
assert!(
publisher
.writer()
.wait_for_subscriptions(1, Duration::from_secs(10))
);
let hello = Value::Struct(vec![(
"data".into(),
Value::String("Hello World: 1".into()),
)]);
publisher.publish(&hello).unwrap();
let (got, info) = wait_for(Duration::from_secs(10), || {
subscription.take().unwrap().pop()
});
assert_eq!(got, hello);
let writer = listener.writer_of(&info).expect("the writer is known");
assert_eq!(writer.topic_name, "rt/demo/chatter");
assert_eq!(writer.type_name, "std_msgs::msg::dds_::String_");
assert_eq!(writer.guid.to_bytes(), publisher.gid());
assert_eq!(writer.participant_guid.to_bytes(), talker.gid());
let ud = UserData::parse(&writer.user_data);
assert_eq!(
ud.type_hash().unwrap().to_string(),
"RIHS01_df668c740482bbd48fb39d76a70dfd4bd59db1288021743503259e948f6b1a18"
);
assert_eq!(ud.get("juiz"), Some("1234"));
let readers = talker
.participant()
.discovered_subscriptions(Some("rt/demo/chatter"));
assert_eq!(readers.len(), 1);
assert_eq!(readers[0].guid.to_bytes(), subscription.gid());
assert!(
publisher
.publish(&Value::Struct(vec![("data".into(), Value::Int(1))]))
.is_err()
);
}
type Announced = (String, String, Vec<Vec<u8>>, Vec<Vec<u8>>);
fn nodes(info: &Value) -> Vec<Announced> {
let gids = |v: &Value| match v {
Value::List(l) => l
.iter()
.map(|g| match g.get("data") {
Some(Value::Bytes(b)) => b.clone(),
other => panic!("a gid: {other:?}"),
})
.collect(),
other => panic!("gids: {other:?}"),
};
let text = |v: Option<&Value>| match v {
Some(Value::String(s)) => s.clone(),
other => panic!("a string: {other:?}"),
};
match info.get("node_entities_info_seq") {
Some(Value::List(l)) => l
.iter()
.map(|n| {
(
text(n.get("node_namespace")),
text(n.get("node_name")),
gids(n.get("reader_gid_seq").unwrap()),
gids(n.get("writer_gid_seq").unwrap()),
)
})
.collect(),
other => panic!("nodes: {other:?}"),
}
}
#[test]
fn discovery_info() {
let ty = string_type();
let info_type = TypeLibrary::new().message(DISCOVERY_INFO_TYPE).unwrap();
let ros =
rustorb_dds::DomainParticipant::with_config(ParticipantConfig::localhost(72)).unwrap();
let topic = ros
.create_dynamic_topic(DISCOVERY_INFO_TOPIC, info_type.dynamic_type())
.unwrap();
let reader: DataReader<DynamicData> = ros
.create_subscriber()
.unwrap()
.create_datareader_with_qos(&topic, QosProfile::TRANSIENT_LOCAL.reader_qos(Vec::new()))
.unwrap();
let participant = ros_participant(72);
let mut last: Option<Value> = None;
let mut latest = |want: &dyn Fn(&Value) -> bool| -> Value {
wait_for(Duration::from_secs(10), || {
for s in reader.take() {
if let Some(d) = s.data {
last = Some(info_type.from_data(&d).unwrap());
}
}
last.clone().filter(|v| want(v))
})
};
let node = participant.create_node("/", "talker").unwrap();
let publisher = node
.create_publisher("chatter", &ty, &QosProfile::DEFAULT, &UserData::new())
.unwrap();
let pub_gid = publisher.gid().to_vec();
let v = latest(&|v| nodes(v).iter().any(|n| n.3.len() == 1));
assert_eq!(
v.get("gid").unwrap().get("data"),
Some(&Value::Bytes(participant.gid().to_vec()))
);
let n = nodes(&v);
assert_eq!(n.len(), 1);
assert_eq!((n[0].0.as_str(), n[0].1.as_str()), ("/", "talker"));
assert_eq!(n[0].3, vec![pub_gid]);
assert!(n[0].2.is_empty());
let other = participant.create_node("/robot", "listener").unwrap();
let sub = other
.create_subscription("chatter", &ty, &QosProfile::SENSOR_DATA, &UserData::new())
.unwrap();
assert_eq!(sub.topic(), "/robot/chatter");
let v = latest(&|v| nodes(v).len() == 2 && nodes(v)[1].2.len() == 1);
assert_eq!(nodes(&v)[1].2, vec![sub.gid().to_vec()]);
drop(publisher);
latest(&|v| nodes(v)[0].3.is_empty());
drop(sub);
drop(other);
let v = latest(&|v| nodes(v).len() == 1);
assert_eq!(nodes(&v)[0].1, "talker");
}