Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding two_ints_server example #317

Open
wants to merge 2 commits into
base: examples
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion examples/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ name = "rust_examples"
version = "0.1.0"
edition = "2021"

[features]
unstable = ["zenoh/unstable"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[workspace]
[dependencies]
async-std = { version = "1.12.0" }
futures = { version = "0.3.28" }
zenoh = { version = "0.10.1-rc" }
zenoh = { version = "1.0.0" }
clap = { version = "4.4.11", features = ["derive"] }
env_logger = { version = "0.10.0" }
serde = {version = "1" }
Expand Down
34 changes: 4 additions & 30 deletions examples/rust/src/bin/add_two_ints_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@
// ZettaScale Zenoh Team, <[email protected]>
//
use cdr::{CdrLe, Infinite};
use clap::{App, Arg};
use serde::{Deserialize, Serialize};
use zenoh::config::Config;
use zenoh::prelude::r#async::*;

#[derive(Serialize, PartialEq, Debug)]
struct AddTwoIntsRequest {
Expand All @@ -28,26 +25,19 @@ struct AddTwoIntsResponse {
sum: i64,
}

#[async_std::main]
#[tokio::main]
async fn main() {
env_logger::init();

let config = parse_args();

let session = zenoh::open(config).res().await.unwrap();
let session = zenoh::open(zenoh::Config::default()).await.unwrap();

let req = AddTwoIntsRequest { a: 2, b: 3 };
let buf = cdr::serialize::<_, _, CdrLe>(&req, Infinite).unwrap();
let replies = session
.get("add_two_ints")
.with_value(buf)
.res()
.await
.unwrap();
let replies = session.get("add_two_ints").payload(buf).await.unwrap();

while let Ok(reply) = replies.recv_async().await {
match cdr::deserialize_from::<_, AddTwoIntsResponse, _>(
reply.sample.unwrap().payload.reader(),
reply.result().unwrap().payload().reader(),
cdr::size::Infinite,
) {
Ok(res) => {
Expand All @@ -57,19 +47,3 @@ async fn main() {
}
}
}

fn parse_args() -> Config {
let args = App::new("zenoh sub example")
.arg(Arg::from_usage(
"-c, --config=[FILE] 'A configuration file.'",
))
.get_matches();

let config = if let Some(conf_file) = args.value_of("config") {
Config::from_file(conf_file).unwrap()
} else {
Config::default()
};

config
}
57 changes: 57 additions & 0 deletions examples/rust/src/bin/add_two_ints_server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
// ZettaScale Zenoh Team, <[email protected]>
//
use cdr::{CdrLe, Infinite};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, PartialEq, Debug)]
struct AddTwoIntsRequest {
a: i64,
b: i64,
}

#[derive(Serialize, PartialEq, Debug)]
struct AddTwoIntsResponse {
sum: i64,
}

#[tokio::main]
async fn main() {
env_logger::init();

let session = zenoh::open(zenoh::Config::default()).await.unwrap();

let liveliness = session.liveliness().declare_token("@/f2f0382de97ce1ddc0e6738833feb2b9/@ros2_lv/SS/add_two_ints/example_interfaces§srv§AddTwoInts").await.unwrap();

let queryable = session
.declare_queryable("add_two_ints")
.complete(true)
.await
.unwrap();

while let Ok(query) = queryable.recv_async().await {
match cdr::deserialize_from::<_, AddTwoIntsRequest, _>(
query.payload().unwrap().reader(),
cdr::size::Infinite,
) {
Ok(res) => {
let reply = AddTwoIntsResponse { sum: res.a + res.b };
println!("Result of add_two_ints: {}", reply.sum);
let payload = cdr::serialize::<_, _, CdrLe>(&reply, Infinite).unwrap();
let key_expr = "add_two_ints";
query.reply(key_expr, payload).await.unwrap();
}
Err(e) => log::warn!("Error decoding message: {}", e),
}
}
}
38 changes: 7 additions & 31 deletions examples/rust/src/bin/fibonnacci_action_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@
// ZettaScale Zenoh Team, <[email protected]>
//
use cdr::{CdrLe, Infinite};
use clap::{App, Arg};
use serde::{Deserialize, Serialize};
use zenoh::config::Config;
use zenoh::prelude::r#async::*;

#[derive(Deserialize, PartialEq, Debug)]
struct Time {
Expand Down Expand Up @@ -52,19 +49,17 @@ struct FibonacciFeedback {
partial_sequence: Vec<i32>,
}

#[async_std::main]
#[tokio::main]
async fn main() {
env_logger::init();

let config = parse_args();

let session = zenoh::open(config).res().await.unwrap();
let session = zenoh::open(zenoh::Config::default()).await.unwrap();

let _subscriber = session
.declare_subscriber("fibonacci/_action/feedback")
.callback(|sample| {
match cdr::deserialize_from::<_, FibonacciFeedback, _>(
sample.value.payload.reader(),
sample.payload().reader(),
cdr::size::Infinite,
) {
Ok(msg) => {
Expand All @@ -76,7 +71,6 @@ async fn main() {
Err(e) => log::warn!("Error decoding message: {}", e),
};
})
.res()
.await
.unwrap();

Expand All @@ -90,14 +84,13 @@ async fn main() {
println!("Sending goal");
let replies = session
.get("fibonacci/_action/send_goal")
.with_value(buf)
.res()
.payload(buf)
.await
.unwrap();

while let Ok(reply) = replies.recv_async().await {
match cdr::deserialize_from::<_, FibonacciSendGoalResponse, _>(
reply.sample.unwrap().payload.reader(),
reply.result().unwrap().payload().reader(),
cdr::size::Infinite,
) {
Ok(res) => {
Expand All @@ -116,13 +109,12 @@ async fn main() {
let buf = cdr::serialize::<_, _, CdrLe>(&req, Infinite).unwrap();
let replies = session
.get("fibonacci/_action/get_result")
.with_value(buf)
.res()
.payload(buf)
.await
.unwrap();
while let Ok(reply) = replies.recv_async().await {
match cdr::deserialize_from::<_, FibonacciGetResultResponse, _>(
reply.sample.unwrap().payload.reader(),
reply.result().unwrap().payload().reader(),
cdr::size::Infinite,
) {
Ok(res) => {
Expand All @@ -132,19 +124,3 @@ async fn main() {
}
}
}

fn parse_args() -> Config {
let args = App::new("zenoh sub example")
.arg(Arg::from_usage(
"-c, --config=[FILE] 'A configuration file.'",
))
.get_matches();

let config = if let Some(conf_file) = args.value_of("config") {
Config::from_file(conf_file).unwrap()
} else {
Config::default()
};

config
}
33 changes: 5 additions & 28 deletions examples/rust/src/bin/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,52 +11,29 @@
// Contributors:
// ZettaScale Zenoh Team, <[email protected]>
//
use clap::{App, Arg};
use serde::Deserialize;
use zenoh::config::Config;
use zenoh::prelude::r#async::*;

#[derive(Deserialize, PartialEq, Debug)]
struct Message {
data: String,
}
#[async_std::main]
#[tokio::main]
async fn main() {
// Initiate logging
env_logger::init();

let config = parse_args();

println!("Opening session...");
let session = zenoh::open(config).res().await.unwrap();
let session = zenoh::open(zenoh::Config::default()).await.unwrap();

let subscriber = session.declare_subscriber("chatter").res().await.unwrap();
let subscriber = session.declare_subscriber("chatter").await.unwrap();

while let Ok(sample) = subscriber.recv_async().await {
match cdr::deserialize_from::<_, Message, _>(
sample.value.payload.reader(),
cdr::size::Infinite,
) {
match cdr::deserialize_from::<_, Message, _>(sample.payload().reader(), cdr::size::Infinite)
{
Ok(msg) => {
println!("I heard: [{}]", msg.data);
}
Err(e) => log::warn!("Error decoding message: {}", e),
}
}
}

fn parse_args() -> Config {
let args = App::new("zenoh sub example")
.arg(Arg::from_usage(
"-c, --config=[FILE] 'A configuration file.'",
))
.get_matches();

let config = if let Some(conf_file) = args.value_of("config") {
Config::from_file(conf_file).unwrap()
} else {
Config::default()
};

config
}
33 changes: 6 additions & 27 deletions examples/rust/src/bin/talker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,54 +11,33 @@
// Contributors:
// ZettaScale Zenoh Team, <[email protected]>
//
use async_std::task::sleep;
use cdr::{CdrLe, Infinite};
use clap::{App, Arg};
use serde::Serialize;
use std::time::Duration;
use zenoh::config::Config;
use zenoh::prelude::r#async::*;
use tokio::time::sleep;

#[derive(Serialize, PartialEq, Debug)]
struct Message {
data: String,
}

#[async_std::main]
#[tokio::main]
async fn main() {
// Initiate logging
env_logger::init();

let config = parse_args();

println!("Opening session...");
let session = zenoh::open(config).res().await.unwrap();
let session = zenoh::open(zenoh::Config::default()).await.unwrap();

let publisher = session.declare_publisher("chatter").res().await.unwrap();
let publisher = session.declare_publisher("chatter").await.unwrap();

for idx in 0..u32::MAX {
for idx in 1..u32::MAX {
sleep(Duration::from_secs(1)).await;
let message = Message {
data: format!("Hello World:{idx:4}"),
};
let buf = cdr::serialize::<_, _, CdrLe>(&message, Infinite).unwrap();
println!("Publishing: '{}')...", message.data);
publisher.put(buf).res().await.unwrap();
publisher.put(buf).await.unwrap();
}
}

fn parse_args() -> Config {
let args = App::new("zenoh talker example")
.arg(Arg::from_usage(
"-c, --config=[FILE] 'A configuration file.'",
))
.get_matches();

let config = if let Some(conf_file) = args.value_of("config") {
Config::from_file(conf_file).unwrap()
} else {
Config::default()
};

config
}