use std::time::{Duration, Instant};
use rustorb_dds::{Error as DdsError, StatusMask, WaitSet};
use rustorb_dds_ros2::{QosProfile, RosParticipant, TypeLibrary, UserData, Value};
const FALLBACK: &[(&str, &str)] = &[
("std_msgs/msg/String", "string data\n"),
(
"geometry_msgs/msg/Vector3",
"float64 x\nfloat64 y\nfloat64 z\n",
),
(
"geometry_msgs/msg/Twist",
"Vector3 linear\nVector3 angular\n",
),
];
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
let role = args.get(1).map(String::as_str).unwrap_or("listener");
let arg = |i: usize| -> Result<Option<u64>, Box<dyn std::error::Error>> {
Ok(match args.get(i) {
Some(v) => Some(v.parse()?),
None => None,
})
};
let domain = arg(2)?.unwrap_or(0) as u32;
let count = arg(3)?;
let mut types = TypeLibrary::with_dirs::<&str>([]);
for (name, text) in FALLBACK {
types.add_text(name, text)?;
}
let string = types.message("std_msgs/msg/String")?;
let twist = types.message("geometry_msgs/msg/Twist")?;
let ros = RosParticipant::new(domain)?;
let none = UserData::new();
match role {
"talker" => {
let interval = Duration::from_millis(arg(4)?.unwrap_or(500));
let node = ros.create_node("/", "rustorb_talker")?;
let chatter = node.create_publisher("chatter", &string, &QosProfile::DEFAULT, &none)?;
let cmd_vel = node.create_publisher("cmd_vel", &twist, &QosProfile::DEFAULT, &none)?;
println!(
"rustorb-dds: /chatter {} {}",
string.name(),
string.type_hash()
);
println!(
"rustorb-dds: /cmd_vel {} {}",
twist.name(),
twist.type_hash()
);
while !chatter
.writer()
.wait_for_subscriptions(1, Duration::from_secs(1))
&& !cmd_vel
.writer()
.wait_for_subscriptions(1, Duration::from_millis(1))
{}
std::thread::sleep(Duration::from_millis(500));
let mut i = 0u64;
while count.is_none_or(|c| i < c) {
i += 1;
let text = format!("Hello World: {i}");
println!("rustorb-dds: Publishing: '{text}'");
chatter.publish(&Value::Struct(vec![("data".into(), Value::String(text))]))?;
cmd_vel.publish(&Value::Struct(vec![(
"linear".into(),
Value::Struct(vec![("x".into(), Value::Float(i as f64 * 0.5))]),
)]))?;
std::thread::sleep(interval);
}
chatter
.writer()
.wait_for_acknowledgments(Duration::from_secs(10))?;
}
"listener" | "twist_listener" => {
let deadline = Instant::now() + Duration::from_secs(arg(4)?.unwrap_or(60));
let (node_name, topic, ty) = if role == "listener" {
("rustorb_listener", "chatter", &string)
} else {
("rustorb_twist_listener", "cmd_vel", &twist)
};
let node = ros.create_node("/", node_name)?;
let sub = node.create_subscription(topic, ty, &QosProfile::DEFAULT, &none)?;
let status = sub.reader().status_condition();
status.set_enabled_statuses(StatusMask::DATA_AVAILABLE);
let waitset = WaitSet::new();
waitset.attach_condition(&status)?;
let mut got = 0u64;
while count.is_none_or(|c| got < c) {
let left = deadline.saturating_duration_since(Instant::now());
match waitset.wait(left) {
Err(DdsError::Timeout) => {
return Err(format!("rustorb-dds: heard {got} messages").into());
}
r => r?,
};
for (v, info) in sub.take()? {
let from = ros
.writer_of(&info)
.and_then(|w| UserData::parse(&w.user_data).type_hash())
.map(|h| h.to_string())
.unwrap_or_else(|| "no type hash".into());
match (v.get("data"), v.get("linear").and_then(|l| l.get("x"))) {
(Some(Value::String(s)), _) => {
println!("rustorb-dds: I heard: [{s}] ({from})")
}
(_, Some(Value::Float(x))) => {
println!("rustorb-dds: I heard: linear.x {x} ({from})")
}
_ => println!("rustorb-dds: I heard: {v:?}"),
}
got += 1;
}
}
}
_ => {
return Err(
format!("unknown role {role:?}: use talker, listener or twist_listener").into(),
);
}
}
Ok(())
}